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.

280012 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. MemoryOutputStream mo;
  1859. OutputStream* o = &mo;
  1860. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  1861. o = dynamic_cast <MemoryOutputStream*> (o);
  1862. jassert (o != 0);
  1863. }
  1864. catch (...)
  1865. {
  1866. // Ended up here? If so, TURN ON RTTI in your compiler settings!!
  1867. jassertfalse;
  1868. }
  1869. #endif
  1870. }
  1871. }
  1872. JUCE_API void JUCE_CALLTYPE shutdownJuce_GUI()
  1873. {
  1874. if (juceInitialisedGUI)
  1875. {
  1876. juceInitialisedGUI = false;
  1877. JUCE_AUTORELEASEPOOL
  1878. DeletedAtShutdown::deleteAll();
  1879. LookAndFeel::clearDefaultLookAndFeel();
  1880. delete MessageManager::getInstance();
  1881. shutdownJuce_NonGUI();
  1882. }
  1883. }
  1884. #endif
  1885. #if JUCE_UNIT_TESTS
  1886. class AtomicTests : public UnitTest
  1887. {
  1888. public:
  1889. AtomicTests() : UnitTest ("Atomics") {}
  1890. void runTest()
  1891. {
  1892. beginTest ("Misc");
  1893. char a1[7];
  1894. expect (numElementsInArray(a1) == 7);
  1895. int a2[3];
  1896. expect (numElementsInArray(a2) == 3);
  1897. expect (ByteOrder::swap ((uint16) 0x1122) == 0x2211);
  1898. expect (ByteOrder::swap ((uint32) 0x11223344) == 0x44332211);
  1899. expect (ByteOrder::swap ((uint64) literal64bit (0x1122334455667788)) == literal64bit (0x8877665544332211));
  1900. beginTest ("Atomic types");
  1901. AtomicTester <int>::testInteger (*this);
  1902. AtomicTester <unsigned int>::testInteger (*this);
  1903. AtomicTester <int32>::testInteger (*this);
  1904. AtomicTester <uint32>::testInteger (*this);
  1905. AtomicTester <long>::testInteger (*this);
  1906. AtomicTester <void*>::testInteger (*this);
  1907. AtomicTester <int*>::testInteger (*this);
  1908. AtomicTester <float>::testFloat (*this);
  1909. #if ! JUCE_64BIT_ATOMICS_UNAVAILABLE // 64-bit intrinsics aren't available on some old platforms
  1910. AtomicTester <int64>::testInteger (*this);
  1911. AtomicTester <uint64>::testInteger (*this);
  1912. AtomicTester <double>::testFloat (*this);
  1913. #endif
  1914. }
  1915. template <typename Type>
  1916. class AtomicTester
  1917. {
  1918. public:
  1919. AtomicTester() {}
  1920. static void testInteger (UnitTest& test)
  1921. {
  1922. Atomic<Type> a, b;
  1923. a.set ((Type) 10);
  1924. a += (Type) 15;
  1925. a.memoryBarrier();
  1926. a -= (Type) 5;
  1927. ++a; ++a; --a;
  1928. a.memoryBarrier();
  1929. testFloat (test);
  1930. }
  1931. static void testFloat (UnitTest& test)
  1932. {
  1933. Atomic<Type> a, b;
  1934. a = (Type) 21;
  1935. a.memoryBarrier();
  1936. /* These are some simple test cases to check the atomics - let me know
  1937. if any of these assertions fail on your system!
  1938. */
  1939. test.expect (a.get() == (Type) 21);
  1940. test.expect (a.compareAndSetValue ((Type) 100, (Type) 50) == (Type) 21);
  1941. test.expect (a.get() == (Type) 21);
  1942. test.expect (a.compareAndSetValue ((Type) 101, a.get()) == (Type) 21);
  1943. test.expect (a.get() == (Type) 101);
  1944. test.expect (! a.compareAndSetBool ((Type) 300, (Type) 200));
  1945. test.expect (a.get() == (Type) 101);
  1946. test.expect (a.compareAndSetBool ((Type) 200, a.get()));
  1947. test.expect (a.get() == (Type) 200);
  1948. test.expect (a.exchange ((Type) 300) == (Type) 200);
  1949. test.expect (a.get() == (Type) 300);
  1950. b = a;
  1951. test.expect (b.get() == a.get());
  1952. }
  1953. };
  1954. };
  1955. static AtomicTests atomicUnitTests;
  1956. #endif
  1957. END_JUCE_NAMESPACE
  1958. /*** End of inlined file: juce_Initialisation.cpp ***/
  1959. /*** Start of inlined file: juce_AbstractFifo.cpp ***/
  1960. BEGIN_JUCE_NAMESPACE
  1961. AbstractFifo::AbstractFifo (const int capacity) throw()
  1962. : bufferSize (capacity)
  1963. {
  1964. jassert (bufferSize > 0);
  1965. }
  1966. AbstractFifo::~AbstractFifo() {}
  1967. int AbstractFifo::getTotalSize() const throw() { return bufferSize; }
  1968. int AbstractFifo::getFreeSpace() const throw() { return bufferSize - getNumReady(); }
  1969. int AbstractFifo::getNumReady() const throw() { return validEnd.get() - validStart.get(); }
  1970. void AbstractFifo::reset() throw()
  1971. {
  1972. validEnd = 0;
  1973. validStart = 0;
  1974. }
  1975. void AbstractFifo::setTotalSize (int newSize) throw()
  1976. {
  1977. jassert (newSize > 0);
  1978. reset();
  1979. bufferSize = newSize;
  1980. }
  1981. void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  1982. {
  1983. const int vs = validStart.get();
  1984. const int ve = validEnd.get();
  1985. const int freeSpace = bufferSize - (ve - vs);
  1986. numToWrite = jmin (numToWrite, freeSpace);
  1987. if (numToWrite <= 0)
  1988. {
  1989. startIndex1 = 0;
  1990. startIndex2 = 0;
  1991. blockSize1 = 0;
  1992. blockSize2 = 0;
  1993. }
  1994. else
  1995. {
  1996. startIndex1 = (int) (ve % bufferSize);
  1997. startIndex2 = 0;
  1998. blockSize1 = jmin (bufferSize - startIndex1, numToWrite);
  1999. numToWrite -= blockSize1;
  2000. blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, (int) (vs % bufferSize));
  2001. }
  2002. }
  2003. void AbstractFifo::finishedWrite (int numWritten) throw()
  2004. {
  2005. jassert (numWritten >= 0 && numWritten < bufferSize);
  2006. validEnd += numWritten;
  2007. }
  2008. void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const throw()
  2009. {
  2010. const int vs = validStart.get();
  2011. const int ve = validEnd.get();
  2012. const int numReady = ve - vs;
  2013. numWanted = jmin (numWanted, numReady);
  2014. if (numWanted <= 0)
  2015. {
  2016. startIndex1 = 0;
  2017. startIndex2 = 0;
  2018. blockSize1 = 0;
  2019. blockSize2 = 0;
  2020. }
  2021. else
  2022. {
  2023. startIndex1 = (int) (vs % bufferSize);
  2024. startIndex2 = 0;
  2025. blockSize1 = jmin (bufferSize - startIndex1, numWanted);
  2026. numWanted -= blockSize1;
  2027. blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, (int) (ve % bufferSize));
  2028. }
  2029. }
  2030. void AbstractFifo::finishedRead (int numRead) throw()
  2031. {
  2032. jassert (numRead >= 0 && numRead < bufferSize);
  2033. validStart += numRead;
  2034. }
  2035. END_JUCE_NAMESPACE
  2036. /*** End of inlined file: juce_AbstractFifo.cpp ***/
  2037. /*** Start of inlined file: juce_BigInteger.cpp ***/
  2038. BEGIN_JUCE_NAMESPACE
  2039. BigInteger::BigInteger()
  2040. : numValues (4),
  2041. highestBit (-1),
  2042. negative (false)
  2043. {
  2044. values.calloc (numValues + 1);
  2045. }
  2046. BigInteger::BigInteger (const int32 value)
  2047. : numValues (4),
  2048. highestBit (31),
  2049. negative (value < 0)
  2050. {
  2051. values.calloc (numValues + 1);
  2052. values[0] = abs (value);
  2053. highestBit = getHighestBit();
  2054. }
  2055. BigInteger::BigInteger (const uint32 value)
  2056. : numValues (4),
  2057. highestBit (31),
  2058. negative (false)
  2059. {
  2060. values.calloc (numValues + 1);
  2061. values[0] = value;
  2062. highestBit = getHighestBit();
  2063. }
  2064. BigInteger::BigInteger (int64 value)
  2065. : numValues (4),
  2066. highestBit (63),
  2067. negative (value < 0)
  2068. {
  2069. values.calloc (numValues + 1);
  2070. if (value < 0)
  2071. value = -value;
  2072. values[0] = (uint32) value;
  2073. values[1] = (uint32) (value >> 32);
  2074. highestBit = getHighestBit();
  2075. }
  2076. BigInteger::BigInteger (const BigInteger& other)
  2077. : numValues (jmax (4, bitToIndex (other.highestBit) + 1)),
  2078. highestBit (other.getHighestBit()),
  2079. negative (other.negative)
  2080. {
  2081. values.malloc (numValues + 1);
  2082. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2083. }
  2084. BigInteger::~BigInteger()
  2085. {
  2086. }
  2087. void BigInteger::swapWith (BigInteger& other) throw()
  2088. {
  2089. values.swapWith (other.values);
  2090. swapVariables (numValues, other.numValues);
  2091. swapVariables (highestBit, other.highestBit);
  2092. swapVariables (negative, other.negative);
  2093. }
  2094. BigInteger& BigInteger::operator= (const BigInteger& other)
  2095. {
  2096. if (this != &other)
  2097. {
  2098. highestBit = other.getHighestBit();
  2099. numValues = jmax (4, bitToIndex (highestBit) + 1);
  2100. negative = other.negative;
  2101. values.malloc (numValues + 1);
  2102. memcpy (values, other.values, sizeof (uint32) * (numValues + 1));
  2103. }
  2104. return *this;
  2105. }
  2106. void BigInteger::ensureSize (const int numVals)
  2107. {
  2108. if (numVals + 2 >= numValues)
  2109. {
  2110. int oldSize = numValues;
  2111. numValues = ((numVals + 2) * 3) / 2;
  2112. values.realloc (numValues + 1);
  2113. while (oldSize < numValues)
  2114. values [oldSize++] = 0;
  2115. }
  2116. }
  2117. bool BigInteger::operator[] (const int bit) const throw()
  2118. {
  2119. return bit <= highestBit && bit >= 0
  2120. && ((values [bitToIndex (bit)] & bitToMask (bit)) != 0);
  2121. }
  2122. int BigInteger::toInteger() const throw()
  2123. {
  2124. const int n = (int) (values[0] & 0x7fffffff);
  2125. return negative ? -n : n;
  2126. }
  2127. const BigInteger BigInteger::getBitRange (int startBit, int numBits) const
  2128. {
  2129. BigInteger r;
  2130. numBits = jmin (numBits, getHighestBit() + 1 - startBit);
  2131. r.ensureSize (bitToIndex (numBits));
  2132. r.highestBit = numBits;
  2133. int i = 0;
  2134. while (numBits > 0)
  2135. {
  2136. r.values[i++] = getBitRangeAsInt (startBit, jmin (32, numBits));
  2137. numBits -= 32;
  2138. startBit += 32;
  2139. }
  2140. r.highestBit = r.getHighestBit();
  2141. return r;
  2142. }
  2143. int BigInteger::getBitRangeAsInt (const int startBit, int numBits) const throw()
  2144. {
  2145. if (numBits > 32)
  2146. {
  2147. jassertfalse; // use getBitRange() if you need more than 32 bits..
  2148. numBits = 32;
  2149. }
  2150. numBits = jmin (numBits, highestBit + 1 - startBit);
  2151. if (numBits <= 0)
  2152. return 0;
  2153. const int pos = bitToIndex (startBit);
  2154. const int offset = startBit & 31;
  2155. const int endSpace = 32 - numBits;
  2156. uint32 n = ((uint32) values [pos]) >> offset;
  2157. if (offset > endSpace)
  2158. n |= ((uint32) values [pos + 1]) << (32 - offset);
  2159. return (int) (n & (((uint32) 0xffffffff) >> endSpace));
  2160. }
  2161. void BigInteger::setBitRangeAsInt (const int startBit, int numBits, uint32 valueToSet)
  2162. {
  2163. if (numBits > 32)
  2164. {
  2165. jassertfalse;
  2166. numBits = 32;
  2167. }
  2168. for (int i = 0; i < numBits; ++i)
  2169. {
  2170. setBit (startBit + i, (valueToSet & 1) != 0);
  2171. valueToSet >>= 1;
  2172. }
  2173. }
  2174. void BigInteger::clear()
  2175. {
  2176. if (numValues > 16)
  2177. {
  2178. numValues = 4;
  2179. values.calloc (numValues + 1);
  2180. }
  2181. else
  2182. {
  2183. zeromem (values, sizeof (uint32) * (numValues + 1));
  2184. }
  2185. highestBit = -1;
  2186. negative = false;
  2187. }
  2188. void BigInteger::setBit (const int bit)
  2189. {
  2190. if (bit >= 0)
  2191. {
  2192. if (bit > highestBit)
  2193. {
  2194. ensureSize (bitToIndex (bit));
  2195. highestBit = bit;
  2196. }
  2197. values [bitToIndex (bit)] |= bitToMask (bit);
  2198. }
  2199. }
  2200. void BigInteger::setBit (const int bit, const bool shouldBeSet)
  2201. {
  2202. if (shouldBeSet)
  2203. setBit (bit);
  2204. else
  2205. clearBit (bit);
  2206. }
  2207. void BigInteger::clearBit (const int bit) throw()
  2208. {
  2209. if (bit >= 0 && bit <= highestBit)
  2210. values [bitToIndex (bit)] &= ~bitToMask (bit);
  2211. }
  2212. void BigInteger::setRange (int startBit, int numBits, const bool shouldBeSet)
  2213. {
  2214. while (--numBits >= 0)
  2215. setBit (startBit++, shouldBeSet);
  2216. }
  2217. void BigInteger::insertBit (const int bit, const bool shouldBeSet)
  2218. {
  2219. if (bit >= 0)
  2220. shiftBits (1, bit);
  2221. setBit (bit, shouldBeSet);
  2222. }
  2223. bool BigInteger::isZero() const throw()
  2224. {
  2225. return getHighestBit() < 0;
  2226. }
  2227. bool BigInteger::isOne() const throw()
  2228. {
  2229. return getHighestBit() == 0 && ! negative;
  2230. }
  2231. bool BigInteger::isNegative() const throw()
  2232. {
  2233. return negative && ! isZero();
  2234. }
  2235. void BigInteger::setNegative (const bool neg) throw()
  2236. {
  2237. negative = neg;
  2238. }
  2239. void BigInteger::negate() throw()
  2240. {
  2241. negative = (! negative) && ! isZero();
  2242. }
  2243. int BigInteger::countNumberOfSetBits() const throw()
  2244. {
  2245. int total = 0;
  2246. for (int i = bitToIndex (highestBit) + 1; --i >= 0;)
  2247. {
  2248. uint32 n = values[i];
  2249. if (n == 0xffffffff)
  2250. {
  2251. total += 32;
  2252. }
  2253. else
  2254. {
  2255. while (n != 0)
  2256. {
  2257. total += (n & 1);
  2258. n >>= 1;
  2259. }
  2260. }
  2261. }
  2262. return total;
  2263. }
  2264. int BigInteger::getHighestBit() const throw()
  2265. {
  2266. for (int i = highestBit + 1; --i >= 0;)
  2267. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2268. return i;
  2269. return -1;
  2270. }
  2271. int BigInteger::findNextSetBit (int i) const throw()
  2272. {
  2273. for (; i <= highestBit; ++i)
  2274. if ((values [bitToIndex (i)] & bitToMask (i)) != 0)
  2275. return i;
  2276. return -1;
  2277. }
  2278. int BigInteger::findNextClearBit (int i) const throw()
  2279. {
  2280. for (; i <= highestBit; ++i)
  2281. if ((values [bitToIndex (i)] & bitToMask (i)) == 0)
  2282. break;
  2283. return i;
  2284. }
  2285. BigInteger& BigInteger::operator+= (const BigInteger& other)
  2286. {
  2287. if (other.isNegative())
  2288. return operator-= (-other);
  2289. if (isNegative())
  2290. {
  2291. if (compareAbsolute (other) < 0)
  2292. {
  2293. BigInteger temp (*this);
  2294. temp.negate();
  2295. *this = other;
  2296. operator-= (temp);
  2297. }
  2298. else
  2299. {
  2300. negate();
  2301. operator-= (other);
  2302. negate();
  2303. }
  2304. }
  2305. else
  2306. {
  2307. if (other.highestBit > highestBit)
  2308. highestBit = other.highestBit;
  2309. ++highestBit;
  2310. const int numInts = bitToIndex (highestBit) + 1;
  2311. ensureSize (numInts);
  2312. int64 remainder = 0;
  2313. for (int i = 0; i <= numInts; ++i)
  2314. {
  2315. if (i < numValues)
  2316. remainder += values[i];
  2317. if (i < other.numValues)
  2318. remainder += other.values[i];
  2319. values[i] = (uint32) remainder;
  2320. remainder >>= 32;
  2321. }
  2322. jassert (remainder == 0);
  2323. highestBit = getHighestBit();
  2324. }
  2325. return *this;
  2326. }
  2327. BigInteger& BigInteger::operator-= (const BigInteger& other)
  2328. {
  2329. if (other.isNegative())
  2330. return operator+= (-other);
  2331. if (! isNegative())
  2332. {
  2333. if (compareAbsolute (other) < 0)
  2334. {
  2335. BigInteger temp (other);
  2336. swapWith (temp);
  2337. operator-= (temp);
  2338. negate();
  2339. return *this;
  2340. }
  2341. }
  2342. else
  2343. {
  2344. negate();
  2345. operator+= (other);
  2346. negate();
  2347. return *this;
  2348. }
  2349. const int numInts = bitToIndex (highestBit) + 1;
  2350. const int maxOtherInts = bitToIndex (other.highestBit) + 1;
  2351. int64 amountToSubtract = 0;
  2352. for (int i = 0; i <= numInts; ++i)
  2353. {
  2354. if (i <= maxOtherInts)
  2355. amountToSubtract += (int64) other.values[i];
  2356. if (values[i] >= amountToSubtract)
  2357. {
  2358. values[i] = (uint32) (values[i] - amountToSubtract);
  2359. amountToSubtract = 0;
  2360. }
  2361. else
  2362. {
  2363. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  2364. values[i] = (uint32) n;
  2365. amountToSubtract = 1;
  2366. }
  2367. }
  2368. return *this;
  2369. }
  2370. BigInteger& BigInteger::operator*= (const BigInteger& other)
  2371. {
  2372. BigInteger total;
  2373. highestBit = getHighestBit();
  2374. const bool wasNegative = isNegative();
  2375. setNegative (false);
  2376. for (int i = 0; i <= highestBit; ++i)
  2377. {
  2378. if (operator[](i))
  2379. {
  2380. BigInteger n (other);
  2381. n.setNegative (false);
  2382. n <<= i;
  2383. total += n;
  2384. }
  2385. }
  2386. total.setNegative (wasNegative ^ other.isNegative());
  2387. swapWith (total);
  2388. return *this;
  2389. }
  2390. void BigInteger::divideBy (const BigInteger& divisor, BigInteger& remainder)
  2391. {
  2392. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  2393. const int divHB = divisor.getHighestBit();
  2394. const int ourHB = getHighestBit();
  2395. if (divHB < 0 || ourHB < 0)
  2396. {
  2397. // division by zero
  2398. remainder.clear();
  2399. clear();
  2400. }
  2401. else
  2402. {
  2403. const bool wasNegative = isNegative();
  2404. swapWith (remainder);
  2405. remainder.setNegative (false);
  2406. clear();
  2407. BigInteger temp (divisor);
  2408. temp.setNegative (false);
  2409. int leftShift = ourHB - divHB;
  2410. temp <<= leftShift;
  2411. while (leftShift >= 0)
  2412. {
  2413. if (remainder.compareAbsolute (temp) >= 0)
  2414. {
  2415. remainder -= temp;
  2416. setBit (leftShift);
  2417. }
  2418. if (--leftShift >= 0)
  2419. temp >>= 1;
  2420. }
  2421. negative = wasNegative ^ divisor.isNegative();
  2422. remainder.setNegative (wasNegative);
  2423. }
  2424. }
  2425. BigInteger& BigInteger::operator/= (const BigInteger& other)
  2426. {
  2427. BigInteger remainder;
  2428. divideBy (other, remainder);
  2429. return *this;
  2430. }
  2431. BigInteger& BigInteger::operator|= (const BigInteger& other)
  2432. {
  2433. // this operation doesn't take into account negative values..
  2434. jassert (isNegative() == other.isNegative());
  2435. if (other.highestBit >= 0)
  2436. {
  2437. ensureSize (bitToIndex (other.highestBit));
  2438. int n = bitToIndex (other.highestBit) + 1;
  2439. while (--n >= 0)
  2440. values[n] |= other.values[n];
  2441. if (other.highestBit > highestBit)
  2442. highestBit = other.highestBit;
  2443. highestBit = getHighestBit();
  2444. }
  2445. return *this;
  2446. }
  2447. BigInteger& BigInteger::operator&= (const BigInteger& other)
  2448. {
  2449. // this operation doesn't take into account negative values..
  2450. jassert (isNegative() == other.isNegative());
  2451. int n = numValues;
  2452. while (n > other.numValues)
  2453. values[--n] = 0;
  2454. while (--n >= 0)
  2455. values[n] &= other.values[n];
  2456. if (other.highestBit < highestBit)
  2457. highestBit = other.highestBit;
  2458. highestBit = getHighestBit();
  2459. return *this;
  2460. }
  2461. BigInteger& BigInteger::operator^= (const BigInteger& other)
  2462. {
  2463. // this operation will only work with the absolute values
  2464. jassert (isNegative() == other.isNegative());
  2465. if (other.highestBit >= 0)
  2466. {
  2467. ensureSize (bitToIndex (other.highestBit));
  2468. int n = bitToIndex (other.highestBit) + 1;
  2469. while (--n >= 0)
  2470. values[n] ^= other.values[n];
  2471. if (other.highestBit > highestBit)
  2472. highestBit = other.highestBit;
  2473. highestBit = getHighestBit();
  2474. }
  2475. return *this;
  2476. }
  2477. BigInteger& BigInteger::operator%= (const BigInteger& divisor)
  2478. {
  2479. BigInteger remainder;
  2480. divideBy (divisor, remainder);
  2481. swapWith (remainder);
  2482. return *this;
  2483. }
  2484. BigInteger& BigInteger::operator<<= (int numBitsToShift)
  2485. {
  2486. shiftBits (numBitsToShift, 0);
  2487. return *this;
  2488. }
  2489. BigInteger& BigInteger::operator>>= (int numBitsToShift)
  2490. {
  2491. return operator<<= (-numBitsToShift);
  2492. }
  2493. BigInteger& BigInteger::operator++() { return operator+= (1); }
  2494. BigInteger& BigInteger::operator--() { return operator-= (1); }
  2495. const BigInteger BigInteger::operator++ (int) { const BigInteger old (*this); operator+= (1); return old; }
  2496. const BigInteger BigInteger::operator-- (int) { const BigInteger old (*this); operator-= (1); return old; }
  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 BigInteger& other) const { BigInteger b (*this); return b %= other; }
  2505. const BigInteger BigInteger::operator<< (const int numBits) const { BigInteger b (*this); return b <<= numBits; }
  2506. const BigInteger BigInteger::operator>> (const int numBits) const { BigInteger b (*this); return b >>= numBits; }
  2507. const BigInteger BigInteger::operator-() const { BigInteger b (*this); b.negate(); return b; }
  2508. int BigInteger::compare (const BigInteger& other) const throw()
  2509. {
  2510. if (isNegative() == other.isNegative())
  2511. {
  2512. const int absComp = compareAbsolute (other);
  2513. return isNegative() ? -absComp : absComp;
  2514. }
  2515. else
  2516. {
  2517. return isNegative() ? -1 : 1;
  2518. }
  2519. }
  2520. int BigInteger::compareAbsolute (const BigInteger& other) const throw()
  2521. {
  2522. const int h1 = getHighestBit();
  2523. const int h2 = other.getHighestBit();
  2524. if (h1 > h2)
  2525. return 1;
  2526. else if (h1 < h2)
  2527. return -1;
  2528. for (int i = bitToIndex (h1) + 1; --i >= 0;)
  2529. if (values[i] != other.values[i])
  2530. return (values[i] > other.values[i]) ? 1 : -1;
  2531. return 0;
  2532. }
  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. bool BigInteger::operator>= (const BigInteger& other) const throw() { return compare (other) >= 0; }
  2539. void BigInteger::shiftBits (int bits, const int startBit)
  2540. {
  2541. if (highestBit < 0)
  2542. return;
  2543. if (startBit > 0)
  2544. {
  2545. if (bits < 0)
  2546. {
  2547. // right shift
  2548. for (int i = startBit; i <= highestBit; ++i)
  2549. setBit (i, operator[] (i - bits));
  2550. highestBit = getHighestBit();
  2551. }
  2552. else if (bits > 0)
  2553. {
  2554. // left shift
  2555. for (int i = highestBit + 1; --i >= startBit;)
  2556. setBit (i + bits, operator[] (i));
  2557. while (--bits >= 0)
  2558. clearBit (bits + startBit);
  2559. }
  2560. }
  2561. else
  2562. {
  2563. if (bits < 0)
  2564. {
  2565. // right shift
  2566. bits = -bits;
  2567. if (bits > highestBit)
  2568. {
  2569. clear();
  2570. }
  2571. else
  2572. {
  2573. const int wordsToMove = bitToIndex (bits);
  2574. int top = 1 + bitToIndex (highestBit) - wordsToMove;
  2575. highestBit -= bits;
  2576. if (wordsToMove > 0)
  2577. {
  2578. int i;
  2579. for (i = 0; i < top; ++i)
  2580. values [i] = values [i + wordsToMove];
  2581. for (i = 0; i < wordsToMove; ++i)
  2582. values [top + i] = 0;
  2583. bits &= 31;
  2584. }
  2585. if (bits != 0)
  2586. {
  2587. const int invBits = 32 - bits;
  2588. --top;
  2589. for (int i = 0; i < top; ++i)
  2590. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  2591. values[top] = (values[top] >> bits);
  2592. }
  2593. highestBit = getHighestBit();
  2594. }
  2595. }
  2596. else if (bits > 0)
  2597. {
  2598. // left shift
  2599. ensureSize (bitToIndex (highestBit + bits) + 1);
  2600. const int wordsToMove = bitToIndex (bits);
  2601. int top = 1 + bitToIndex (highestBit);
  2602. highestBit += bits;
  2603. if (wordsToMove > 0)
  2604. {
  2605. int i;
  2606. for (i = top; --i >= 0;)
  2607. values [i + wordsToMove] = values [i];
  2608. for (i = 0; i < wordsToMove; ++i)
  2609. values [i] = 0;
  2610. bits &= 31;
  2611. }
  2612. if (bits != 0)
  2613. {
  2614. const int invBits = 32 - bits;
  2615. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  2616. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  2617. values [wordsToMove] = values [wordsToMove] << bits;
  2618. }
  2619. highestBit = getHighestBit();
  2620. }
  2621. }
  2622. }
  2623. const BigInteger BigInteger::simpleGCD (BigInteger* m, BigInteger* n)
  2624. {
  2625. while (! m->isZero())
  2626. {
  2627. if (n->compareAbsolute (*m) > 0)
  2628. swapVariables (m, n);
  2629. *m -= *n;
  2630. }
  2631. return *n;
  2632. }
  2633. const BigInteger BigInteger::findGreatestCommonDivisor (BigInteger n) const
  2634. {
  2635. BigInteger m (*this);
  2636. while (! n.isZero())
  2637. {
  2638. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  2639. return simpleGCD (&m, &n);
  2640. BigInteger temp1 (m), temp2;
  2641. temp1.divideBy (n, temp2);
  2642. m = n;
  2643. n = temp2;
  2644. }
  2645. return m;
  2646. }
  2647. void BigInteger::exponentModulo (const BigInteger& exponent, const BigInteger& modulus)
  2648. {
  2649. BigInteger exp (exponent);
  2650. exp %= modulus;
  2651. BigInteger value (1);
  2652. swapWith (value);
  2653. value %= modulus;
  2654. while (! exp.isZero())
  2655. {
  2656. if (exp [0])
  2657. {
  2658. operator*= (value);
  2659. operator%= (modulus);
  2660. }
  2661. value *= value;
  2662. value %= modulus;
  2663. exp >>= 1;
  2664. }
  2665. }
  2666. void BigInteger::inverseModulo (const BigInteger& modulus)
  2667. {
  2668. if (modulus.isOne() || modulus.isNegative())
  2669. {
  2670. clear();
  2671. return;
  2672. }
  2673. if (isNegative() || compareAbsolute (modulus) >= 0)
  2674. operator%= (modulus);
  2675. if (isOne())
  2676. return;
  2677. if (! (*this)[0])
  2678. {
  2679. // not invertible
  2680. clear();
  2681. return;
  2682. }
  2683. BigInteger a1 (modulus);
  2684. BigInteger a2 (*this);
  2685. BigInteger b1 (modulus);
  2686. BigInteger b2 (1);
  2687. while (! a2.isOne())
  2688. {
  2689. BigInteger temp1, temp2, multiplier (a1);
  2690. multiplier.divideBy (a2, temp1);
  2691. temp1 = a2;
  2692. temp1 *= multiplier;
  2693. temp2 = a1;
  2694. temp2 -= temp1;
  2695. a1 = a2;
  2696. a2 = temp2;
  2697. temp1 = b2;
  2698. temp1 *= multiplier;
  2699. temp2 = b1;
  2700. temp2 -= temp1;
  2701. b1 = b2;
  2702. b2 = temp2;
  2703. }
  2704. while (b2.isNegative())
  2705. b2 += modulus;
  2706. b2 %= modulus;
  2707. swapWith (b2);
  2708. }
  2709. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const BigInteger& value)
  2710. {
  2711. return stream << value.toString (10);
  2712. }
  2713. const String BigInteger::toString (const int base, const int minimumNumCharacters) const
  2714. {
  2715. String s;
  2716. BigInteger v (*this);
  2717. if (base == 2 || base == 8 || base == 16)
  2718. {
  2719. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2720. static const char* const hexDigits = "0123456789abcdef";
  2721. for (;;)
  2722. {
  2723. const int remainder = v.getBitRangeAsInt (0, bits);
  2724. v >>= bits;
  2725. if (remainder == 0 && v.isZero())
  2726. break;
  2727. s = String::charToString (hexDigits [remainder]) + s;
  2728. }
  2729. }
  2730. else if (base == 10)
  2731. {
  2732. const BigInteger ten (10);
  2733. BigInteger remainder;
  2734. for (;;)
  2735. {
  2736. v.divideBy (ten, remainder);
  2737. if (remainder.isZero() && v.isZero())
  2738. break;
  2739. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2740. }
  2741. }
  2742. else
  2743. {
  2744. jassertfalse; // can't do the specified base!
  2745. return String::empty;
  2746. }
  2747. s = s.paddedLeft ('0', minimumNumCharacters);
  2748. return isNegative() ? "-" + s : s;
  2749. }
  2750. void BigInteger::parseString (const String& text, const int base)
  2751. {
  2752. clear();
  2753. const juce_wchar* t = text;
  2754. if (base == 2 || base == 8 || base == 16)
  2755. {
  2756. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2757. for (;;)
  2758. {
  2759. const juce_wchar c = *t++;
  2760. const int digit = CharacterFunctions::getHexDigitValue (c);
  2761. if (((uint32) digit) < (uint32) base)
  2762. {
  2763. operator<<= (bits);
  2764. operator+= (digit);
  2765. }
  2766. else if (c == 0)
  2767. {
  2768. break;
  2769. }
  2770. }
  2771. }
  2772. else if (base == 10)
  2773. {
  2774. const BigInteger ten ((uint32) 10);
  2775. for (;;)
  2776. {
  2777. const juce_wchar c = *t++;
  2778. if (c >= '0' && c <= '9')
  2779. {
  2780. operator*= (ten);
  2781. operator+= ((int) (c - '0'));
  2782. }
  2783. else if (c == 0)
  2784. {
  2785. break;
  2786. }
  2787. }
  2788. }
  2789. setNegative (text.trimStart().startsWithChar ('-'));
  2790. }
  2791. const MemoryBlock BigInteger::toMemoryBlock() const
  2792. {
  2793. const int numBytes = (getHighestBit() + 8) >> 3;
  2794. MemoryBlock mb ((size_t) numBytes);
  2795. for (int i = 0; i < numBytes; ++i)
  2796. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2797. return mb;
  2798. }
  2799. void BigInteger::loadFromMemoryBlock (const MemoryBlock& data)
  2800. {
  2801. clear();
  2802. for (int i = (int) data.getSize(); --i >= 0;)
  2803. this->setBitRangeAsInt ((int) (i << 3), 8, data [i]);
  2804. }
  2805. END_JUCE_NAMESPACE
  2806. /*** End of inlined file: juce_BigInteger.cpp ***/
  2807. /*** Start of inlined file: juce_MemoryBlock.cpp ***/
  2808. BEGIN_JUCE_NAMESPACE
  2809. MemoryBlock::MemoryBlock() throw()
  2810. : size (0)
  2811. {
  2812. }
  2813. MemoryBlock::MemoryBlock (const size_t initialSize, const bool initialiseToZero)
  2814. {
  2815. if (initialSize > 0)
  2816. {
  2817. size = initialSize;
  2818. data.allocate (initialSize, initialiseToZero);
  2819. }
  2820. else
  2821. {
  2822. size = 0;
  2823. }
  2824. }
  2825. MemoryBlock::MemoryBlock (const MemoryBlock& other)
  2826. : size (other.size)
  2827. {
  2828. if (size > 0)
  2829. {
  2830. jassert (other.data != 0);
  2831. data.malloc (size);
  2832. memcpy (data, other.data, size);
  2833. }
  2834. }
  2835. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
  2836. : size (jmax ((size_t) 0, sizeInBytes))
  2837. {
  2838. jassert (sizeInBytes >= 0);
  2839. if (size > 0)
  2840. {
  2841. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2842. data.malloc (size);
  2843. if (dataToInitialiseFrom != 0)
  2844. memcpy (data, dataToInitialiseFrom, size);
  2845. }
  2846. }
  2847. MemoryBlock::~MemoryBlock() throw()
  2848. {
  2849. jassert (size >= 0); // should never happen
  2850. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2851. }
  2852. MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other)
  2853. {
  2854. if (this != &other)
  2855. {
  2856. setSize (other.size, false);
  2857. memcpy (data, other.data, size);
  2858. }
  2859. return *this;
  2860. }
  2861. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2862. {
  2863. return matches (other.data, other.size);
  2864. }
  2865. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2866. {
  2867. return ! operator== (other);
  2868. }
  2869. bool MemoryBlock::matches (const void* dataToCompare, size_t dataSize) const throw()
  2870. {
  2871. return size == dataSize
  2872. && memcmp (data, dataToCompare, size) == 0;
  2873. }
  2874. // this will resize the block to this size
  2875. void MemoryBlock::setSize (const size_t newSize, const bool initialiseToZero)
  2876. {
  2877. if (size != newSize)
  2878. {
  2879. if (newSize <= 0)
  2880. {
  2881. data.free();
  2882. size = 0;
  2883. }
  2884. else
  2885. {
  2886. if (data != 0)
  2887. {
  2888. data.realloc (newSize);
  2889. if (initialiseToZero && (newSize > size))
  2890. zeromem (data + size, newSize - size);
  2891. }
  2892. else
  2893. {
  2894. data.allocate (newSize, initialiseToZero);
  2895. }
  2896. size = newSize;
  2897. }
  2898. }
  2899. }
  2900. void MemoryBlock::ensureSize (const size_t minimumSize, const bool initialiseToZero)
  2901. {
  2902. if (size < minimumSize)
  2903. setSize (minimumSize, initialiseToZero);
  2904. }
  2905. void MemoryBlock::swapWith (MemoryBlock& other) throw()
  2906. {
  2907. swapVariables (size, other.size);
  2908. data.swapWith (other.data);
  2909. }
  2910. void MemoryBlock::fillWith (const uint8 value) throw()
  2911. {
  2912. memset (data, (int) value, size);
  2913. }
  2914. void MemoryBlock::append (const void* const srcData, const size_t numBytes)
  2915. {
  2916. if (numBytes > 0)
  2917. {
  2918. const size_t oldSize = size;
  2919. setSize (size + numBytes);
  2920. memcpy (data + oldSize, srcData, numBytes);
  2921. }
  2922. }
  2923. void MemoryBlock::copyFrom (const void* const src, int offset, size_t num) throw()
  2924. {
  2925. const char* d = static_cast<const char*> (src);
  2926. if (offset < 0)
  2927. {
  2928. d -= offset;
  2929. num -= offset;
  2930. offset = 0;
  2931. }
  2932. if (offset + num > size)
  2933. num = size - offset;
  2934. if (num > 0)
  2935. memcpy (data + offset, d, num);
  2936. }
  2937. void MemoryBlock::copyTo (void* const dst, int offset, size_t num) const throw()
  2938. {
  2939. char* d = static_cast<char*> (dst);
  2940. if (offset < 0)
  2941. {
  2942. zeromem (d, -offset);
  2943. d -= offset;
  2944. num += offset;
  2945. offset = 0;
  2946. }
  2947. if (offset + num > size)
  2948. {
  2949. const size_t newNum = size - offset;
  2950. zeromem (d + newNum, num - newNum);
  2951. num = newNum;
  2952. }
  2953. if (num > 0)
  2954. memcpy (d, data + offset, num);
  2955. }
  2956. void MemoryBlock::removeSection (size_t startByte, size_t numBytesToRemove)
  2957. {
  2958. if (startByte < 0)
  2959. {
  2960. numBytesToRemove += startByte;
  2961. startByte = 0;
  2962. }
  2963. if (startByte + numBytesToRemove >= size)
  2964. {
  2965. setSize (startByte);
  2966. }
  2967. else if (numBytesToRemove > 0)
  2968. {
  2969. memmove (data + startByte,
  2970. data + startByte + numBytesToRemove,
  2971. size - (startByte + numBytesToRemove));
  2972. setSize (size - numBytesToRemove);
  2973. }
  2974. }
  2975. const String MemoryBlock::toString() const
  2976. {
  2977. return String (static_cast <const char*> (getData()), size);
  2978. }
  2979. int MemoryBlock::getBitRange (const size_t bitRangeStart, size_t numBits) const throw()
  2980. {
  2981. int res = 0;
  2982. size_t byte = bitRangeStart >> 3;
  2983. int offsetInByte = (int) bitRangeStart & 7;
  2984. size_t bitsSoFar = 0;
  2985. while (numBits > 0 && (size_t) byte < size)
  2986. {
  2987. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  2988. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2989. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2990. bitsSoFar += bitsThisTime;
  2991. numBits -= bitsThisTime;
  2992. ++byte;
  2993. offsetInByte = 0;
  2994. }
  2995. return res;
  2996. }
  2997. void MemoryBlock::setBitRange (const size_t bitRangeStart, size_t numBits, int bitsToSet) throw()
  2998. {
  2999. size_t byte = bitRangeStart >> 3;
  3000. int offsetInByte = (int) bitRangeStart & 7;
  3001. unsigned int mask = ~((((unsigned int) 0xffffffff) << (32 - numBits)) >> (32 - numBits));
  3002. while (numBits > 0 && (size_t) byte < size)
  3003. {
  3004. const int bitsThisTime = jmin ((int) numBits, 8 - offsetInByte);
  3005. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int) 0xffffffff) >> offsetInByte) << offsetInByte);
  3006. const unsigned int tempBits = bitsToSet << offsetInByte;
  3007. data[byte] = (char) ((data[byte] & tempMask) | tempBits);
  3008. ++byte;
  3009. numBits -= bitsThisTime;
  3010. bitsToSet >>= bitsThisTime;
  3011. mask >>= bitsThisTime;
  3012. offsetInByte = 0;
  3013. }
  3014. }
  3015. void MemoryBlock::loadFromHexString (const String& hex)
  3016. {
  3017. ensureSize (hex.length() >> 1);
  3018. char* dest = data;
  3019. int i = 0;
  3020. for (;;)
  3021. {
  3022. int byte = 0;
  3023. for (int loop = 2; --loop >= 0;)
  3024. {
  3025. byte <<= 4;
  3026. for (;;)
  3027. {
  3028. const juce_wchar c = hex [i++];
  3029. if (c >= '0' && c <= '9')
  3030. {
  3031. byte |= c - '0';
  3032. break;
  3033. }
  3034. else if (c >= 'a' && c <= 'z')
  3035. {
  3036. byte |= c - ('a' - 10);
  3037. break;
  3038. }
  3039. else if (c >= 'A' && c <= 'Z')
  3040. {
  3041. byte |= c - ('A' - 10);
  3042. break;
  3043. }
  3044. else if (c == 0)
  3045. {
  3046. setSize (static_cast <size_t> (dest - data));
  3047. return;
  3048. }
  3049. }
  3050. }
  3051. *dest++ = (char) byte;
  3052. }
  3053. }
  3054. const char* const MemoryBlock::encodingTable = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  3055. const String MemoryBlock::toBase64Encoding() const
  3056. {
  3057. const size_t numChars = ((size << 3) + 5) / 6;
  3058. String destString ((unsigned int) size); // store the length, followed by a '.', and then the data.
  3059. const int initialLen = destString.length();
  3060. destString.preallocateStorage (initialLen + 2 + numChars);
  3061. juce_wchar* d = destString;
  3062. d += initialLen;
  3063. *d++ = '.';
  3064. for (size_t i = 0; i < numChars; ++i)
  3065. *d++ = encodingTable [getBitRange (i * 6, 6)];
  3066. *d++ = 0;
  3067. return destString;
  3068. }
  3069. bool MemoryBlock::fromBase64Encoding (const String& s)
  3070. {
  3071. const int startPos = s.indexOfChar ('.') + 1;
  3072. if (startPos <= 0)
  3073. return false;
  3074. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  3075. setSize (numBytesNeeded, true);
  3076. const int numChars = s.length() - startPos;
  3077. const juce_wchar* srcChars = s;
  3078. srcChars += startPos;
  3079. int pos = 0;
  3080. for (int i = 0; i < numChars; ++i)
  3081. {
  3082. const char c = (char) srcChars[i];
  3083. for (int j = 0; j < 64; ++j)
  3084. {
  3085. if (encodingTable[j] == c)
  3086. {
  3087. setBitRange (pos, 6, j);
  3088. pos += 6;
  3089. break;
  3090. }
  3091. }
  3092. }
  3093. return true;
  3094. }
  3095. END_JUCE_NAMESPACE
  3096. /*** End of inlined file: juce_MemoryBlock.cpp ***/
  3097. /*** Start of inlined file: juce_PropertySet.cpp ***/
  3098. BEGIN_JUCE_NAMESPACE
  3099. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames)
  3100. : properties (ignoreCaseOfKeyNames),
  3101. fallbackProperties (0),
  3102. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  3103. {
  3104. }
  3105. PropertySet::PropertySet (const PropertySet& other)
  3106. : properties (other.properties),
  3107. fallbackProperties (other.fallbackProperties),
  3108. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  3109. {
  3110. }
  3111. PropertySet& PropertySet::operator= (const PropertySet& other)
  3112. {
  3113. properties = other.properties;
  3114. fallbackProperties = other.fallbackProperties;
  3115. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  3116. propertyChanged();
  3117. return *this;
  3118. }
  3119. PropertySet::~PropertySet()
  3120. {
  3121. }
  3122. void PropertySet::clear()
  3123. {
  3124. const ScopedLock sl (lock);
  3125. if (properties.size() > 0)
  3126. {
  3127. properties.clear();
  3128. propertyChanged();
  3129. }
  3130. }
  3131. const String PropertySet::getValue (const String& keyName,
  3132. const String& defaultValue) const throw()
  3133. {
  3134. const ScopedLock sl (lock);
  3135. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3136. if (index >= 0)
  3137. return properties.getAllValues() [index];
  3138. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  3139. : defaultValue;
  3140. }
  3141. int PropertySet::getIntValue (const String& keyName,
  3142. const int defaultValue) const throw()
  3143. {
  3144. const ScopedLock sl (lock);
  3145. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3146. if (index >= 0)
  3147. return properties.getAllValues() [index].getIntValue();
  3148. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  3149. : defaultValue;
  3150. }
  3151. double PropertySet::getDoubleValue (const String& keyName,
  3152. const double defaultValue) const throw()
  3153. {
  3154. const ScopedLock sl (lock);
  3155. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3156. if (index >= 0)
  3157. return properties.getAllValues()[index].getDoubleValue();
  3158. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  3159. : defaultValue;
  3160. }
  3161. bool PropertySet::getBoolValue (const String& keyName,
  3162. const bool defaultValue) const throw()
  3163. {
  3164. const ScopedLock sl (lock);
  3165. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3166. if (index >= 0)
  3167. return properties.getAllValues() [index].getIntValue() != 0;
  3168. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  3169. : defaultValue;
  3170. }
  3171. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  3172. {
  3173. XmlDocument doc (getValue (keyName));
  3174. return doc.getDocumentElement();
  3175. }
  3176. void PropertySet::setValue (const String& keyName, const var& v)
  3177. {
  3178. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  3179. if (keyName.isNotEmpty())
  3180. {
  3181. const String value (v.toString());
  3182. const ScopedLock sl (lock);
  3183. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3184. if (index < 0 || properties.getAllValues() [index] != value)
  3185. {
  3186. properties.set (keyName, value);
  3187. propertyChanged();
  3188. }
  3189. }
  3190. }
  3191. void PropertySet::removeValue (const String& keyName)
  3192. {
  3193. if (keyName.isNotEmpty())
  3194. {
  3195. const ScopedLock sl (lock);
  3196. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  3197. if (index >= 0)
  3198. {
  3199. properties.remove (keyName);
  3200. propertyChanged();
  3201. }
  3202. }
  3203. }
  3204. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  3205. {
  3206. setValue (keyName, xml == 0 ? var::null
  3207. : var (xml->createDocument (String::empty, true)));
  3208. }
  3209. bool PropertySet::containsKey (const String& keyName) const throw()
  3210. {
  3211. const ScopedLock sl (lock);
  3212. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  3213. }
  3214. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  3215. {
  3216. const ScopedLock sl (lock);
  3217. fallbackProperties = fallbackProperties_;
  3218. }
  3219. XmlElement* PropertySet::createXml (const String& nodeName) const
  3220. {
  3221. const ScopedLock sl (lock);
  3222. XmlElement* const xml = new XmlElement (nodeName);
  3223. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  3224. {
  3225. XmlElement* const e = xml->createNewChildElement ("VALUE");
  3226. e->setAttribute ("name", properties.getAllKeys()[i]);
  3227. e->setAttribute ("val", properties.getAllValues()[i]);
  3228. }
  3229. return xml;
  3230. }
  3231. void PropertySet::restoreFromXml (const XmlElement& xml)
  3232. {
  3233. const ScopedLock sl (lock);
  3234. clear();
  3235. forEachXmlChildElementWithTagName (xml, e, "VALUE")
  3236. {
  3237. if (e->hasAttribute ("name")
  3238. && e->hasAttribute ("val"))
  3239. {
  3240. properties.set (e->getStringAttribute ("name"),
  3241. e->getStringAttribute ("val"));
  3242. }
  3243. }
  3244. if (properties.size() > 0)
  3245. propertyChanged();
  3246. }
  3247. void PropertySet::propertyChanged()
  3248. {
  3249. }
  3250. END_JUCE_NAMESPACE
  3251. /*** End of inlined file: juce_PropertySet.cpp ***/
  3252. /*** Start of inlined file: juce_Identifier.cpp ***/
  3253. BEGIN_JUCE_NAMESPACE
  3254. StringPool& Identifier::getPool()
  3255. {
  3256. static StringPool pool;
  3257. return pool;
  3258. }
  3259. Identifier::Identifier() throw()
  3260. : name (0)
  3261. {
  3262. }
  3263. Identifier::Identifier (const Identifier& other) throw()
  3264. : name (other.name)
  3265. {
  3266. }
  3267. Identifier& Identifier::operator= (const Identifier& other) throw()
  3268. {
  3269. name = other.name;
  3270. return *this;
  3271. }
  3272. Identifier::Identifier (const String& name_)
  3273. : name (Identifier::getPool().getPooledString (name_))
  3274. {
  3275. /* An Identifier string must be suitable for use as a script variable or XML
  3276. attribute, so it can only contain this limited set of characters.. */
  3277. jassert (name_.containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && name_.isNotEmpty());
  3278. }
  3279. Identifier::Identifier (const char* const name_)
  3280. : name (Identifier::getPool().getPooledString (name_))
  3281. {
  3282. /* An Identifier string must be suitable for use as a script variable or XML
  3283. attribute, so it can only contain this limited set of characters.. */
  3284. jassert (toString().containsOnly ("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_") && toString().isNotEmpty());
  3285. }
  3286. Identifier::~Identifier()
  3287. {
  3288. }
  3289. END_JUCE_NAMESPACE
  3290. /*** End of inlined file: juce_Identifier.cpp ***/
  3291. /*** Start of inlined file: juce_Variant.cpp ***/
  3292. BEGIN_JUCE_NAMESPACE
  3293. class var::VariantType
  3294. {
  3295. public:
  3296. VariantType() {}
  3297. virtual ~VariantType() {}
  3298. virtual int toInt (const ValueUnion&) const { return 0; }
  3299. virtual double toDouble (const ValueUnion&) const { return 0; }
  3300. virtual const String toString (const ValueUnion&) const { return String::empty; }
  3301. virtual bool toBool (const ValueUnion&) const { return false; }
  3302. virtual DynamicObject* toObject (const ValueUnion&) const { return 0; }
  3303. virtual bool isVoid() const throw() { return false; }
  3304. virtual bool isInt() const throw() { return false; }
  3305. virtual bool isBool() const throw() { return false; }
  3306. virtual bool isDouble() const throw() { return false; }
  3307. virtual bool isString() const throw() { return false; }
  3308. virtual bool isObject() const throw() { return false; }
  3309. virtual bool isMethod() const throw() { return false; }
  3310. virtual void cleanUp (ValueUnion&) const throw() {}
  3311. virtual void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest = source; }
  3312. virtual bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw() = 0;
  3313. virtual void writeToStream (const ValueUnion& data, OutputStream& output) const = 0;
  3314. };
  3315. class var::VariantType_Void : public var::VariantType
  3316. {
  3317. public:
  3318. VariantType_Void() {}
  3319. static const VariantType_Void* getInstance() { static const VariantType_Void i; return &i; }
  3320. bool isVoid() const throw() { return true; }
  3321. bool equals (const ValueUnion&, const ValueUnion&, const VariantType& otherType) const throw() { return otherType.isVoid(); }
  3322. void writeToStream (const ValueUnion&, OutputStream& output) const { output.writeCompressedInt (0); }
  3323. };
  3324. class var::VariantType_Int : public var::VariantType
  3325. {
  3326. public:
  3327. VariantType_Int() {}
  3328. static const VariantType_Int* getInstance() { static const VariantType_Int i; return &i; }
  3329. int toInt (const ValueUnion& data) const { return data.intValue; };
  3330. double toDouble (const ValueUnion& data) const { return (double) data.intValue; }
  3331. const String toString (const ValueUnion& data) const { return String (data.intValue); }
  3332. bool toBool (const ValueUnion& data) const { return data.intValue != 0; }
  3333. bool isInt() const throw() { return true; }
  3334. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3335. {
  3336. return otherType.toInt (otherData) == data.intValue;
  3337. }
  3338. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3339. {
  3340. output.writeCompressedInt (5);
  3341. output.writeByte (1);
  3342. output.writeInt (data.intValue);
  3343. }
  3344. };
  3345. class var::VariantType_Double : public var::VariantType
  3346. {
  3347. public:
  3348. VariantType_Double() {}
  3349. static const VariantType_Double* getInstance() { static const VariantType_Double i; return &i; }
  3350. int toInt (const ValueUnion& data) const { return (int) data.doubleValue; };
  3351. double toDouble (const ValueUnion& data) const { return data.doubleValue; }
  3352. const String toString (const ValueUnion& data) const { return String (data.doubleValue); }
  3353. bool toBool (const ValueUnion& data) const { return data.doubleValue != 0; }
  3354. bool isDouble() const throw() { return true; }
  3355. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3356. {
  3357. return otherType.toDouble (otherData) == data.doubleValue;
  3358. }
  3359. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3360. {
  3361. output.writeCompressedInt (9);
  3362. output.writeByte (4);
  3363. output.writeDouble (data.doubleValue);
  3364. }
  3365. };
  3366. class var::VariantType_Bool : public var::VariantType
  3367. {
  3368. public:
  3369. VariantType_Bool() {}
  3370. static const VariantType_Bool* getInstance() { static const VariantType_Bool i; return &i; }
  3371. int toInt (const ValueUnion& data) const { return data.boolValue ? 1 : 0; };
  3372. double toDouble (const ValueUnion& data) const { return data.boolValue ? 1.0 : 0.0; }
  3373. const String toString (const ValueUnion& data) const { return String::charToString (data.boolValue ? '1' : '0'); }
  3374. bool toBool (const ValueUnion& data) const { return data.boolValue; }
  3375. bool isBool() const throw() { return true; }
  3376. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3377. {
  3378. return otherType.toBool (otherData) == data.boolValue;
  3379. }
  3380. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3381. {
  3382. output.writeCompressedInt (1);
  3383. output.writeByte (data.boolValue ? 2 : 3);
  3384. }
  3385. };
  3386. class var::VariantType_String : public var::VariantType
  3387. {
  3388. public:
  3389. VariantType_String() {}
  3390. static const VariantType_String* getInstance() { static const VariantType_String i; return &i; }
  3391. void cleanUp (ValueUnion& data) const throw() { delete data.stringValue; }
  3392. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.stringValue = new String (*source.stringValue); }
  3393. int toInt (const ValueUnion& data) const { return data.stringValue->getIntValue(); };
  3394. double toDouble (const ValueUnion& data) const { return data.stringValue->getDoubleValue(); }
  3395. const String toString (const ValueUnion& data) const { return *data.stringValue; }
  3396. bool toBool (const ValueUnion& data) const { return data.stringValue->getIntValue() != 0
  3397. || data.stringValue->trim().equalsIgnoreCase ("true")
  3398. || data.stringValue->trim().equalsIgnoreCase ("yes"); }
  3399. bool isString() const throw() { return true; }
  3400. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3401. {
  3402. return otherType.toString (otherData) == *data.stringValue;
  3403. }
  3404. void writeToStream (const ValueUnion& data, OutputStream& output) const
  3405. {
  3406. const int len = data.stringValue->getNumBytesAsUTF8() + 1;
  3407. output.writeCompressedInt (len + 1);
  3408. output.writeByte (5);
  3409. HeapBlock<char> temp (len);
  3410. data.stringValue->copyToUTF8 (temp, len);
  3411. output.write (temp, len);
  3412. }
  3413. };
  3414. class var::VariantType_Object : public var::VariantType
  3415. {
  3416. public:
  3417. VariantType_Object() {}
  3418. static const VariantType_Object* getInstance() { static const VariantType_Object i; return &i; }
  3419. void cleanUp (ValueUnion& data) const throw() { if (data.objectValue != 0) data.objectValue->decReferenceCount(); }
  3420. void createCopy (ValueUnion& dest, const ValueUnion& source) const { dest.objectValue = source.objectValue; if (dest.objectValue != 0) dest.objectValue->incReferenceCount(); }
  3421. const String toString (const ValueUnion& data) const { return "Object 0x" + String::toHexString ((int) (pointer_sized_int) data.objectValue); }
  3422. bool toBool (const ValueUnion& data) const { return data.objectValue != 0; }
  3423. DynamicObject* toObject (const ValueUnion& data) const { return data.objectValue; }
  3424. bool isObject() const throw() { return true; }
  3425. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3426. {
  3427. return otherType.toObject (otherData) == data.objectValue;
  3428. }
  3429. void writeToStream (const ValueUnion&, OutputStream& output) const
  3430. {
  3431. jassertfalse; // Can't write an object to a stream!
  3432. output.writeCompressedInt (0);
  3433. }
  3434. };
  3435. class var::VariantType_Method : public var::VariantType
  3436. {
  3437. public:
  3438. VariantType_Method() {}
  3439. static const VariantType_Method* getInstance() { static const VariantType_Method i; return &i; }
  3440. const String toString (const ValueUnion&) const { return "Method"; }
  3441. bool toBool (const ValueUnion& data) const { return data.methodValue != 0; }
  3442. bool isMethod() const throw() { return true; }
  3443. bool equals (const ValueUnion& data, const ValueUnion& otherData, const VariantType& otherType) const throw()
  3444. {
  3445. return otherType.isMethod() && otherData.methodValue == data.methodValue;
  3446. }
  3447. void writeToStream (const ValueUnion&, OutputStream& output) const
  3448. {
  3449. jassertfalse; // Can't write a method to a stream!
  3450. output.writeCompressedInt (0);
  3451. }
  3452. };
  3453. var::var() throw()
  3454. : type (VariantType_Void::getInstance())
  3455. {
  3456. }
  3457. var::~var() throw()
  3458. {
  3459. type->cleanUp (value);
  3460. }
  3461. const var var::null;
  3462. var::var (const var& valueToCopy) : type (valueToCopy.type)
  3463. {
  3464. type->createCopy (value, valueToCopy.value);
  3465. }
  3466. var::var (const int value_) throw() : type (VariantType_Int::getInstance())
  3467. {
  3468. value.intValue = value_;
  3469. }
  3470. var::var (const bool value_) throw() : type (VariantType_Bool::getInstance())
  3471. {
  3472. value.boolValue = value_;
  3473. }
  3474. var::var (const double value_) throw() : type (VariantType_Double::getInstance())
  3475. {
  3476. value.doubleValue = value_;
  3477. }
  3478. var::var (const String& value_) : type (VariantType_String::getInstance())
  3479. {
  3480. value.stringValue = new String (value_);
  3481. }
  3482. var::var (const char* const value_) : type (VariantType_String::getInstance())
  3483. {
  3484. value.stringValue = new String (value_);
  3485. }
  3486. var::var (const juce_wchar* const value_) : type (VariantType_String::getInstance())
  3487. {
  3488. value.stringValue = new String (value_);
  3489. }
  3490. var::var (DynamicObject* const object) : type (VariantType_Object::getInstance())
  3491. {
  3492. value.objectValue = object;
  3493. if (object != 0)
  3494. object->incReferenceCount();
  3495. }
  3496. var::var (MethodFunction method_) throw() : type (VariantType_Method::getInstance())
  3497. {
  3498. value.methodValue = method_;
  3499. }
  3500. bool var::isVoid() const throw() { return type->isVoid(); }
  3501. bool var::isInt() const throw() { return type->isInt(); }
  3502. bool var::isBool() const throw() { return type->isBool(); }
  3503. bool var::isDouble() const throw() { return type->isDouble(); }
  3504. bool var::isString() const throw() { return type->isString(); }
  3505. bool var::isObject() const throw() { return type->isObject(); }
  3506. bool var::isMethod() const throw() { return type->isMethod(); }
  3507. var::operator int() const { return type->toInt (value); }
  3508. var::operator bool() const { return type->toBool (value); }
  3509. var::operator float() const { return (float) type->toDouble (value); }
  3510. var::operator double() const { return type->toDouble (value); }
  3511. const String var::toString() const { return type->toString (value); }
  3512. var::operator const String() const { return type->toString (value); }
  3513. DynamicObject* var::getObject() const { return type->toObject (value); }
  3514. void var::swapWith (var& other) throw()
  3515. {
  3516. swapVariables (type, other.type);
  3517. swapVariables (value, other.value);
  3518. }
  3519. var& var::operator= (const var& newValue) { type->cleanUp (value); type = newValue.type; type->createCopy (value, newValue.value); return *this; }
  3520. var& var::operator= (int newValue) { var v (newValue); swapWith (v); return *this; }
  3521. var& var::operator= (bool newValue) { var v (newValue); swapWith (v); return *this; }
  3522. var& var::operator= (double newValue) { var v (newValue); swapWith (v); return *this; }
  3523. var& var::operator= (const char* newValue) { var v (newValue); swapWith (v); return *this; }
  3524. var& var::operator= (const juce_wchar* newValue) { var v (newValue); swapWith (v); return *this; }
  3525. var& var::operator= (const String& newValue) { var v (newValue); swapWith (v); return *this; }
  3526. var& var::operator= (DynamicObject* newValue) { var v (newValue); swapWith (v); return *this; }
  3527. var& var::operator= (MethodFunction newValue) { var v (newValue); swapWith (v); return *this; }
  3528. bool var::equals (const var& other) const throw()
  3529. {
  3530. return type->equals (value, other.value, *other.type);
  3531. }
  3532. bool operator== (const var& v1, const var& v2) throw() { return v1.equals (v2); }
  3533. bool operator!= (const var& v1, const var& v2) throw() { return ! v1.equals (v2); }
  3534. bool operator== (const var& v1, const String& v2) throw() { return v1.toString() == v2; }
  3535. bool operator!= (const var& v1, const String& v2) throw() { return v1.toString() != v2; }
  3536. void var::writeToStream (OutputStream& output) const
  3537. {
  3538. type->writeToStream (value, output);
  3539. }
  3540. const var var::readFromStream (InputStream& input)
  3541. {
  3542. const int numBytes = input.readCompressedInt();
  3543. if (numBytes > 0)
  3544. {
  3545. switch (input.readByte())
  3546. {
  3547. case 1: return var (input.readInt());
  3548. case 2: return var (true);
  3549. case 3: return var (false);
  3550. case 4: return var (input.readDouble());
  3551. case 5:
  3552. {
  3553. MemoryOutputStream mo;
  3554. mo.writeFromInputStream (input, numBytes - 1);
  3555. return var (mo.toUTF8());
  3556. }
  3557. default: input.skipNextBytes (numBytes - 1); break;
  3558. }
  3559. }
  3560. return var::null;
  3561. }
  3562. const var var::operator[] (const Identifier& propertyName) const
  3563. {
  3564. DynamicObject* const o = getObject();
  3565. return o != 0 ? o->getProperty (propertyName) : var::null;
  3566. }
  3567. const var var::invoke (const Identifier& method, const var* arguments, int numArguments) const
  3568. {
  3569. DynamicObject* const o = getObject();
  3570. return o != 0 ? o->invokeMethod (method, arguments, numArguments) : var::null;
  3571. }
  3572. const var var::invoke (const var& targetObject, const var* arguments, int numArguments) const
  3573. {
  3574. if (isMethod())
  3575. {
  3576. DynamicObject* const target = targetObject.getObject();
  3577. if (target != 0)
  3578. return (target->*(value.methodValue)) (arguments, numArguments);
  3579. }
  3580. return var::null;
  3581. }
  3582. const var var::call (const Identifier& method) const
  3583. {
  3584. return invoke (method, 0, 0);
  3585. }
  3586. const var var::call (const Identifier& method, const var& arg1) const
  3587. {
  3588. return invoke (method, &arg1, 1);
  3589. }
  3590. const var var::call (const Identifier& method, const var& arg1, const var& arg2) const
  3591. {
  3592. var args[] = { arg1, arg2 };
  3593. return invoke (method, args, 2);
  3594. }
  3595. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3)
  3596. {
  3597. var args[] = { arg1, arg2, arg3 };
  3598. return invoke (method, args, 3);
  3599. }
  3600. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const
  3601. {
  3602. var args[] = { arg1, arg2, arg3, arg4 };
  3603. return invoke (method, args, 4);
  3604. }
  3605. const var var::call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const
  3606. {
  3607. var args[] = { arg1, arg2, arg3, arg4, arg5 };
  3608. return invoke (method, args, 5);
  3609. }
  3610. END_JUCE_NAMESPACE
  3611. /*** End of inlined file: juce_Variant.cpp ***/
  3612. /*** Start of inlined file: juce_NamedValueSet.cpp ***/
  3613. BEGIN_JUCE_NAMESPACE
  3614. NamedValueSet::NamedValue::NamedValue() throw()
  3615. {
  3616. }
  3617. inline NamedValueSet::NamedValue::NamedValue (const Identifier& name_, const var& value_)
  3618. : name (name_), value (value_)
  3619. {
  3620. }
  3621. bool NamedValueSet::NamedValue::operator== (const NamedValueSet::NamedValue& other) const throw()
  3622. {
  3623. return name == other.name && value == other.value;
  3624. }
  3625. NamedValueSet::NamedValueSet() throw()
  3626. {
  3627. }
  3628. NamedValueSet::NamedValueSet (const NamedValueSet& other)
  3629. : values (other.values)
  3630. {
  3631. }
  3632. NamedValueSet& NamedValueSet::operator= (const NamedValueSet& other)
  3633. {
  3634. values = other.values;
  3635. return *this;
  3636. }
  3637. NamedValueSet::~NamedValueSet()
  3638. {
  3639. }
  3640. bool NamedValueSet::operator== (const NamedValueSet& other) const
  3641. {
  3642. return values == other.values;
  3643. }
  3644. bool NamedValueSet::operator!= (const NamedValueSet& other) const
  3645. {
  3646. return ! operator== (other);
  3647. }
  3648. int NamedValueSet::size() const throw()
  3649. {
  3650. return values.size();
  3651. }
  3652. const var& NamedValueSet::operator[] (const Identifier& name) const
  3653. {
  3654. for (int i = values.size(); --i >= 0;)
  3655. {
  3656. const NamedValue& v = values.getReference(i);
  3657. if (v.name == name)
  3658. return v.value;
  3659. }
  3660. return var::null;
  3661. }
  3662. const var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
  3663. {
  3664. const var* v = getVarPointer (name);
  3665. return v != 0 ? *v : defaultReturnValue;
  3666. }
  3667. var* NamedValueSet::getVarPointer (const Identifier& name) const
  3668. {
  3669. for (int i = values.size(); --i >= 0;)
  3670. {
  3671. NamedValue& v = values.getReference(i);
  3672. if (v.name == name)
  3673. return &(v.value);
  3674. }
  3675. return 0;
  3676. }
  3677. bool NamedValueSet::set (const Identifier& name, const var& newValue)
  3678. {
  3679. for (int i = values.size(); --i >= 0;)
  3680. {
  3681. NamedValue& v = values.getReference(i);
  3682. if (v.name == name)
  3683. {
  3684. if (v.value == newValue)
  3685. return false;
  3686. v.value = newValue;
  3687. return true;
  3688. }
  3689. }
  3690. values.add (NamedValue (name, newValue));
  3691. return true;
  3692. }
  3693. bool NamedValueSet::contains (const Identifier& name) const
  3694. {
  3695. return getVarPointer (name) != 0;
  3696. }
  3697. bool NamedValueSet::remove (const Identifier& name)
  3698. {
  3699. for (int i = values.size(); --i >= 0;)
  3700. {
  3701. if (values.getReference(i).name == name)
  3702. {
  3703. values.remove (i);
  3704. return true;
  3705. }
  3706. }
  3707. return false;
  3708. }
  3709. const Identifier NamedValueSet::getName (const int index) const
  3710. {
  3711. jassert (((unsigned int) index) < (unsigned int) values.size());
  3712. return values [index].name;
  3713. }
  3714. const var NamedValueSet::getValueAt (const int index) const
  3715. {
  3716. jassert (((unsigned int) index) < (unsigned int) values.size());
  3717. return values [index].value;
  3718. }
  3719. void NamedValueSet::clear()
  3720. {
  3721. values.clear();
  3722. }
  3723. END_JUCE_NAMESPACE
  3724. /*** End of inlined file: juce_NamedValueSet.cpp ***/
  3725. /*** Start of inlined file: juce_DynamicObject.cpp ***/
  3726. BEGIN_JUCE_NAMESPACE
  3727. DynamicObject::DynamicObject()
  3728. {
  3729. }
  3730. DynamicObject::~DynamicObject()
  3731. {
  3732. }
  3733. bool DynamicObject::hasProperty (const Identifier& propertyName) const
  3734. {
  3735. var* const v = properties.getVarPointer (propertyName);
  3736. return v != 0 && ! v->isMethod();
  3737. }
  3738. const var DynamicObject::getProperty (const Identifier& propertyName) const
  3739. {
  3740. return properties [propertyName];
  3741. }
  3742. void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
  3743. {
  3744. properties.set (propertyName, newValue);
  3745. }
  3746. void DynamicObject::removeProperty (const Identifier& propertyName)
  3747. {
  3748. properties.remove (propertyName);
  3749. }
  3750. bool DynamicObject::hasMethod (const Identifier& methodName) const
  3751. {
  3752. return getProperty (methodName).isMethod();
  3753. }
  3754. const var DynamicObject::invokeMethod (const Identifier& methodName,
  3755. const var* parameters,
  3756. int numParameters)
  3757. {
  3758. return properties [methodName].invoke (var (this), parameters, numParameters);
  3759. }
  3760. void DynamicObject::setMethod (const Identifier& name,
  3761. var::MethodFunction methodFunction)
  3762. {
  3763. properties.set (name, var (methodFunction));
  3764. }
  3765. void DynamicObject::clear()
  3766. {
  3767. properties.clear();
  3768. }
  3769. END_JUCE_NAMESPACE
  3770. /*** End of inlined file: juce_DynamicObject.cpp ***/
  3771. /*** Start of inlined file: juce_Expression.cpp ***/
  3772. BEGIN_JUCE_NAMESPACE
  3773. class Expression::Helpers
  3774. {
  3775. public:
  3776. typedef ReferenceCountedObjectPtr<Term> TermPtr;
  3777. class Constant : public Term
  3778. {
  3779. public:
  3780. Constant (const double value_, bool isResolutionTarget_)
  3781. : value (value_), isResolutionTarget (isResolutionTarget_) {}
  3782. Type getType() const throw() { return constantType; }
  3783. Term* clone() const { return new Constant (value, isResolutionTarget); }
  3784. double evaluate (const EvaluationContext&, int) const { return value; }
  3785. int getNumInputs() const { return 0; }
  3786. Term* getInput (int) const { return 0; }
  3787. const TermPtr negated()
  3788. {
  3789. return new Constant (-value, isResolutionTarget);
  3790. }
  3791. const String toString() const
  3792. {
  3793. if (isResolutionTarget)
  3794. return "@" + String (value);
  3795. return String (value);
  3796. }
  3797. double value;
  3798. bool isResolutionTarget;
  3799. };
  3800. class Symbol : public Term
  3801. {
  3802. public:
  3803. explicit Symbol (const String& symbol_)
  3804. : mainSymbol (symbol_.upToFirstOccurrenceOf (".", false, false).trim()),
  3805. member (symbol_.fromFirstOccurrenceOf (".", false, false).trim())
  3806. {}
  3807. Symbol (const String& symbol_, const String& member_)
  3808. : mainSymbol (symbol_),
  3809. member (member_)
  3810. {}
  3811. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3812. {
  3813. if (++recursionDepth > 256)
  3814. throw EvaluationError ("Recursive symbol references");
  3815. try
  3816. {
  3817. return c.getSymbolValue (mainSymbol, member).term->evaluate (c, recursionDepth);
  3818. }
  3819. catch (...)
  3820. {}
  3821. return 0;
  3822. }
  3823. Type getType() const throw() { return symbolType; }
  3824. Term* clone() const { return new Symbol (mainSymbol, member); }
  3825. int getNumInputs() const { return 0; }
  3826. Term* getInput (int) const { return 0; }
  3827. const String getSymbolName() const { return toString(); }
  3828. const String toString() const
  3829. {
  3830. return member.isEmpty() ? mainSymbol
  3831. : mainSymbol + "." + member;
  3832. }
  3833. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3834. {
  3835. if (s == mainSymbol)
  3836. return true;
  3837. if (++recursionDepth > 256)
  3838. throw EvaluationError ("Recursive symbol references");
  3839. try
  3840. {
  3841. return c != 0 && c->getSymbolValue (mainSymbol, member).term->referencesSymbol (s, c, recursionDepth);
  3842. }
  3843. catch (EvaluationError&)
  3844. {
  3845. return false;
  3846. }
  3847. }
  3848. String mainSymbol, member;
  3849. };
  3850. class Function : public Term
  3851. {
  3852. public:
  3853. Function (const String& functionName_, const ReferenceCountedArray<Term>& parameters_)
  3854. : functionName (functionName_), parameters (parameters_)
  3855. {}
  3856. Term* clone() const { return new Function (functionName, parameters); }
  3857. double evaluate (const EvaluationContext& c, int recursionDepth) const
  3858. {
  3859. HeapBlock <double> params (parameters.size());
  3860. for (int i = 0; i < parameters.size(); ++i)
  3861. params[i] = parameters.getUnchecked(i)->evaluate (c, recursionDepth);
  3862. return c.evaluateFunction (functionName, params, parameters.size());
  3863. }
  3864. Type getType() const throw() { return functionType; }
  3865. int getInputIndexFor (const Term* possibleInput) const { return parameters.indexOf (possibleInput); }
  3866. int getNumInputs() const { return parameters.size(); }
  3867. Term* getInput (int i) const { return parameters [i]; }
  3868. const String getFunctionName() const { return functionName; }
  3869. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3870. {
  3871. for (int i = 0; i < parameters.size(); ++i)
  3872. if (parameters.getUnchecked(i)->referencesSymbol (s, c, recursionDepth))
  3873. return true;
  3874. return false;
  3875. }
  3876. const String toString() const
  3877. {
  3878. if (parameters.size() == 0)
  3879. return functionName + "()";
  3880. String s (functionName + " (");
  3881. for (int i = 0; i < parameters.size(); ++i)
  3882. {
  3883. s << parameters.getUnchecked(i)->toString();
  3884. if (i < parameters.size() - 1)
  3885. s << ", ";
  3886. }
  3887. s << ')';
  3888. return s;
  3889. }
  3890. const String functionName;
  3891. ReferenceCountedArray<Term> parameters;
  3892. };
  3893. class Negate : public Term
  3894. {
  3895. public:
  3896. Negate (const TermPtr& input_) : input (input_)
  3897. {
  3898. jassert (input_ != 0);
  3899. }
  3900. Type getType() const throw() { return operatorType; }
  3901. int getInputIndexFor (const Term* possibleInput) const { return possibleInput == input ? 0 : -1; }
  3902. int getNumInputs() const { return 1; }
  3903. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (input) : 0; }
  3904. Term* clone() const { return new Negate (input->clone()); }
  3905. double evaluate (const EvaluationContext& c, int recursionDepth) const { return -input->evaluate (c, recursionDepth); }
  3906. const String getFunctionName() const { return "-"; }
  3907. const TermPtr negated()
  3908. {
  3909. return input;
  3910. }
  3911. const TermPtr createTermToEvaluateInput (const EvaluationContext& context, const Term* input_, double overallTarget, Term* topLevelTerm) const
  3912. {
  3913. (void) input_;
  3914. jassert (input_ == input);
  3915. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3916. return new Negate (dest == 0 ? new Constant (overallTarget, false)
  3917. : dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm));
  3918. }
  3919. const String toString() const
  3920. {
  3921. if (input->getOperatorPrecedence() > 0)
  3922. return "-(" + input->toString() + ")";
  3923. else
  3924. return "-" + input->toString();
  3925. }
  3926. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3927. {
  3928. return input->referencesSymbol (s, c, recursionDepth);
  3929. }
  3930. private:
  3931. const TermPtr input;
  3932. };
  3933. class BinaryTerm : public Term
  3934. {
  3935. public:
  3936. BinaryTerm (Term* const left_, Term* const right_) : left (left_), right (right_)
  3937. {
  3938. jassert (left_ != 0 && right_ != 0);
  3939. }
  3940. int getInputIndexFor (const Term* possibleInput) const
  3941. {
  3942. return possibleInput == left ? 0 : (possibleInput == right ? 1 : -1);
  3943. }
  3944. Type getType() const throw() { return operatorType; }
  3945. int getNumInputs() const { return 2; }
  3946. Term* getInput (int index) const { return index == 0 ? static_cast<Term*> (left) : (index == 1 ? static_cast<Term*> (right) : 0); }
  3947. bool referencesSymbol (const String& s, const EvaluationContext* c, int recursionDepth) const
  3948. {
  3949. return left->referencesSymbol (s, c, recursionDepth)
  3950. || right->referencesSymbol (s, c, recursionDepth);
  3951. }
  3952. const String toString() const
  3953. {
  3954. String s;
  3955. const int ourPrecendence = getOperatorPrecedence();
  3956. if (left->getOperatorPrecedence() > ourPrecendence)
  3957. s << '(' << left->toString() << ')';
  3958. else
  3959. s = left->toString();
  3960. s << ' ' << getFunctionName() << ' ';
  3961. if (right->getOperatorPrecedence() >= ourPrecendence)
  3962. s << '(' << right->toString() << ')';
  3963. else
  3964. s << right->toString();
  3965. return s;
  3966. }
  3967. protected:
  3968. const TermPtr left, right;
  3969. const TermPtr createDestinationTerm (const EvaluationContext& context, const Term* input, double overallTarget, Term* topLevelTerm) const
  3970. {
  3971. jassert (input == left || input == right);
  3972. if (input != left && input != right)
  3973. return 0;
  3974. const Term* const dest = findDestinationFor (topLevelTerm, this);
  3975. if (dest == 0)
  3976. return new Constant (overallTarget, false);
  3977. return dest->createTermToEvaluateInput (context, this, overallTarget, topLevelTerm);
  3978. }
  3979. };
  3980. class Add : public BinaryTerm
  3981. {
  3982. public:
  3983. Add (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  3984. Term* clone() const { return new Add (left->clone(), right->clone()); }
  3985. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) + right->evaluate (c, recursionDepth); }
  3986. int getOperatorPrecedence() const { return 2; }
  3987. const String getFunctionName() const { return "+"; }
  3988. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  3989. {
  3990. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  3991. if (newDest == 0)
  3992. return 0;
  3993. return new Subtract (newDest, (input == left ? right : left)->clone());
  3994. }
  3995. private:
  3996. Add (const Add&);
  3997. Add& operator= (const Add&);
  3998. };
  3999. class Subtract : public BinaryTerm
  4000. {
  4001. public:
  4002. Subtract (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4003. Term* clone() const { return new Subtract (left->clone(), right->clone()); }
  4004. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) - right->evaluate (c, recursionDepth); }
  4005. int getOperatorPrecedence() const { return 2; }
  4006. const String getFunctionName() const { return "-"; }
  4007. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4008. {
  4009. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4010. if (newDest == 0)
  4011. return 0;
  4012. if (input == left)
  4013. return new Add (newDest, right->clone());
  4014. else
  4015. return new Subtract (left->clone(), newDest);
  4016. }
  4017. private:
  4018. Subtract (const Subtract&);
  4019. Subtract& operator= (const Subtract&);
  4020. };
  4021. class Multiply : public BinaryTerm
  4022. {
  4023. public:
  4024. Multiply (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4025. Term* clone() const { return new Multiply (left->clone(), right->clone()); }
  4026. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) * right->evaluate (c, recursionDepth); }
  4027. const String getFunctionName() const { return "*"; }
  4028. int getOperatorPrecedence() const { return 1; }
  4029. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4030. {
  4031. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4032. if (newDest == 0)
  4033. return 0;
  4034. return new Divide (newDest, (input == left ? right : left)->clone());
  4035. }
  4036. private:
  4037. Multiply (const Multiply&);
  4038. Multiply& operator= (const Multiply&);
  4039. };
  4040. class Divide : public BinaryTerm
  4041. {
  4042. public:
  4043. Divide (Term* const left_, Term* const right_) : BinaryTerm (left_, right_) {}
  4044. Term* clone() const { return new Divide (left->clone(), right->clone()); }
  4045. double evaluate (const EvaluationContext& c, int recursionDepth) const { return left->evaluate (c, recursionDepth) / right->evaluate (c, recursionDepth); }
  4046. const String getFunctionName() const { return "/"; }
  4047. int getOperatorPrecedence() const { return 1; }
  4048. const TermPtr createTermToEvaluateInput (const EvaluationContext& c, const Term* input, double overallTarget, Term* topLevelTerm) const
  4049. {
  4050. const TermPtr newDest (createDestinationTerm (c, input, overallTarget, topLevelTerm));
  4051. if (newDest == 0)
  4052. return 0;
  4053. if (input == left)
  4054. return new Multiply (newDest, right->clone());
  4055. else
  4056. return new Divide (left->clone(), newDest);
  4057. }
  4058. private:
  4059. Divide (const Divide&);
  4060. Divide& operator= (const Divide&);
  4061. };
  4062. static Term* findDestinationFor (Term* const topLevel, const Term* const inputTerm)
  4063. {
  4064. const int inputIndex = topLevel->getInputIndexFor (inputTerm);
  4065. if (inputIndex >= 0)
  4066. return topLevel;
  4067. for (int i = topLevel->getNumInputs(); --i >= 0;)
  4068. {
  4069. Term* t = findDestinationFor (topLevel->getInput (i), inputTerm);
  4070. if (t != 0)
  4071. return t;
  4072. }
  4073. return 0;
  4074. }
  4075. static Constant* findTermToAdjust (Term* const term, const bool mustBeFlagged)
  4076. {
  4077. Constant* c = dynamic_cast<Constant*> (term);
  4078. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4079. return c;
  4080. if (dynamic_cast<Function*> (term) != 0)
  4081. return 0;
  4082. int i;
  4083. const int numIns = term->getNumInputs();
  4084. for (i = 0; i < numIns; ++i)
  4085. {
  4086. Constant* c = dynamic_cast<Constant*> (term->getInput (i));
  4087. if (c != 0 && (c->isResolutionTarget || ! mustBeFlagged))
  4088. return c;
  4089. }
  4090. for (i = 0; i < numIns; ++i)
  4091. {
  4092. Constant* c = findTermToAdjust (term->getInput (i), mustBeFlagged);
  4093. if (c != 0)
  4094. return c;
  4095. }
  4096. return 0;
  4097. }
  4098. static bool containsAnySymbols (const Term* const t)
  4099. {
  4100. if (dynamic_cast <const Symbol*> (t) != 0)
  4101. return true;
  4102. for (int i = t->getNumInputs(); --i >= 0;)
  4103. if (containsAnySymbols (t->getInput (i)))
  4104. return true;
  4105. return false;
  4106. }
  4107. static bool renameSymbol (Term* const t, const String& oldName, const String& newName)
  4108. {
  4109. Symbol* const sym = dynamic_cast <Symbol*> (t);
  4110. if (sym != 0 && sym->mainSymbol == oldName)
  4111. {
  4112. sym->mainSymbol = newName;
  4113. return true;
  4114. }
  4115. bool anyChanged = false;
  4116. for (int i = t->getNumInputs(); --i >= 0;)
  4117. if (renameSymbol (t->getInput (i), oldName, newName))
  4118. anyChanged = true;
  4119. return anyChanged;
  4120. }
  4121. class Parser
  4122. {
  4123. public:
  4124. Parser (const String& stringToParse, int& textIndex_)
  4125. : textString (stringToParse), textIndex (textIndex_)
  4126. {
  4127. text = textString;
  4128. }
  4129. const TermPtr readExpression()
  4130. {
  4131. TermPtr lhs (readMultiplyOrDivideExpression());
  4132. char opType;
  4133. while (lhs != 0 && readOperator ("+-", &opType))
  4134. {
  4135. TermPtr rhs (readMultiplyOrDivideExpression());
  4136. if (rhs == 0)
  4137. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4138. if (opType == '+')
  4139. lhs = new Add (lhs, rhs);
  4140. else
  4141. lhs = new Subtract (lhs, rhs);
  4142. }
  4143. return lhs;
  4144. }
  4145. private:
  4146. const String textString;
  4147. const juce_wchar* text;
  4148. int& textIndex;
  4149. static inline bool isDecimalDigit (const juce_wchar c) throw()
  4150. {
  4151. return c >= '0' && c <= '9';
  4152. }
  4153. void skipWhitespace (int& i)
  4154. {
  4155. while (CharacterFunctions::isWhitespace (text [i]))
  4156. ++i;
  4157. }
  4158. bool readChar (const juce_wchar required)
  4159. {
  4160. if (text[textIndex] == required)
  4161. {
  4162. ++textIndex;
  4163. return true;
  4164. }
  4165. return false;
  4166. }
  4167. bool readOperator (const char* ops, char* const opType = 0)
  4168. {
  4169. skipWhitespace (textIndex);
  4170. while (*ops != 0)
  4171. {
  4172. if (readChar (*ops))
  4173. {
  4174. if (opType != 0)
  4175. *opType = *ops;
  4176. return true;
  4177. }
  4178. ++ops;
  4179. }
  4180. return false;
  4181. }
  4182. bool readIdentifier (String& identifier)
  4183. {
  4184. skipWhitespace (textIndex);
  4185. int i = textIndex;
  4186. if (CharacterFunctions::isLetter (text[i]) || text[i] == '_')
  4187. {
  4188. ++i;
  4189. while (CharacterFunctions::isLetterOrDigit (text[i]) || text[i] == '_' || text[i] == '.')
  4190. ++i;
  4191. }
  4192. if (i > textIndex)
  4193. {
  4194. identifier = String (text + textIndex, i - textIndex);
  4195. textIndex = i;
  4196. return true;
  4197. }
  4198. return false;
  4199. }
  4200. Term* readNumber()
  4201. {
  4202. skipWhitespace (textIndex);
  4203. int i = textIndex;
  4204. const bool isResolutionTarget = (text[i] == '@');
  4205. if (isResolutionTarget)
  4206. {
  4207. ++i;
  4208. skipWhitespace (i);
  4209. textIndex = i;
  4210. }
  4211. if (text[i] == '-')
  4212. {
  4213. ++i;
  4214. skipWhitespace (i);
  4215. }
  4216. int numDigits = 0;
  4217. while (isDecimalDigit (text[i]))
  4218. {
  4219. ++i;
  4220. ++numDigits;
  4221. }
  4222. const bool hasPoint = (text[i] == '.');
  4223. if (hasPoint)
  4224. {
  4225. ++i;
  4226. while (isDecimalDigit (text[i]))
  4227. {
  4228. ++i;
  4229. ++numDigits;
  4230. }
  4231. }
  4232. if (numDigits == 0)
  4233. return 0;
  4234. juce_wchar c = text[i];
  4235. const bool hasExponent = (c == 'e' || c == 'E');
  4236. if (hasExponent)
  4237. {
  4238. ++i;
  4239. c = text[i];
  4240. if (c == '+' || c == '-')
  4241. ++i;
  4242. int numExpDigits = 0;
  4243. while (isDecimalDigit (text[i]))
  4244. {
  4245. ++i;
  4246. ++numExpDigits;
  4247. }
  4248. if (numExpDigits == 0)
  4249. return 0;
  4250. }
  4251. const int start = textIndex;
  4252. textIndex = i;
  4253. return new Constant (String (text + start, i - start).getDoubleValue(), isResolutionTarget);
  4254. }
  4255. const TermPtr readMultiplyOrDivideExpression()
  4256. {
  4257. TermPtr lhs (readUnaryExpression());
  4258. char opType;
  4259. while (lhs != 0 && readOperator ("*/", &opType))
  4260. {
  4261. TermPtr rhs (readUnaryExpression());
  4262. if (rhs == 0)
  4263. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4264. if (opType == '*')
  4265. lhs = new Multiply (lhs, rhs);
  4266. else
  4267. lhs = new Divide (lhs, rhs);
  4268. }
  4269. return lhs;
  4270. }
  4271. const TermPtr readUnaryExpression()
  4272. {
  4273. char opType;
  4274. if (readOperator ("+-", &opType))
  4275. {
  4276. TermPtr term (readUnaryExpression());
  4277. if (term == 0)
  4278. throw ParseError ("Expected expression after \"" + String::charToString (opType) + "\"");
  4279. if (opType == '-')
  4280. term = term->negated();
  4281. return term;
  4282. }
  4283. return readPrimaryExpression();
  4284. }
  4285. const TermPtr readPrimaryExpression()
  4286. {
  4287. TermPtr e (readParenthesisedExpression());
  4288. if (e != 0)
  4289. return e;
  4290. e = readNumber();
  4291. if (e != 0)
  4292. return e;
  4293. String identifier;
  4294. if (readIdentifier (identifier))
  4295. {
  4296. if (readOperator ("(")) // method call...
  4297. {
  4298. Function* f = new Function (identifier, ReferenceCountedArray<Term>());
  4299. ScopedPointer<Term> func (f); // (can't use ScopedPointer<Function> in MSVC)
  4300. TermPtr param (readExpression());
  4301. if (param == 0)
  4302. {
  4303. if (readOperator (")"))
  4304. return func.release();
  4305. throw ParseError ("Expected parameters after \"" + identifier + " (\"");
  4306. }
  4307. f->parameters.add (param);
  4308. while (readOperator (","))
  4309. {
  4310. param = readExpression();
  4311. if (param == 0)
  4312. throw ParseError ("Expected expression after \",\"");
  4313. f->parameters.add (param);
  4314. }
  4315. if (readOperator (")"))
  4316. return func.release();
  4317. throw ParseError ("Expected \")\"");
  4318. }
  4319. else // just a symbol..
  4320. {
  4321. return new Symbol (identifier);
  4322. }
  4323. }
  4324. return 0;
  4325. }
  4326. const TermPtr readParenthesisedExpression()
  4327. {
  4328. if (! readOperator ("("))
  4329. return 0;
  4330. const TermPtr e (readExpression());
  4331. if (e == 0 || ! readOperator (")"))
  4332. return 0;
  4333. return e;
  4334. }
  4335. Parser (const Parser&);
  4336. Parser& operator= (const Parser&);
  4337. };
  4338. };
  4339. Expression::Expression()
  4340. : term (new Expression::Helpers::Constant (0, false))
  4341. {
  4342. }
  4343. Expression::~Expression()
  4344. {
  4345. }
  4346. Expression::Expression (Term* const term_)
  4347. : term (term_)
  4348. {
  4349. jassert (term != 0);
  4350. }
  4351. Expression::Expression (const double constant)
  4352. : term (new Expression::Helpers::Constant (constant, false))
  4353. {
  4354. }
  4355. Expression::Expression (const Expression& other)
  4356. : term (other.term)
  4357. {
  4358. }
  4359. Expression& Expression::operator= (const Expression& other)
  4360. {
  4361. term = other.term;
  4362. return *this;
  4363. }
  4364. Expression::Expression (const String& stringToParse)
  4365. {
  4366. int i = 0;
  4367. Helpers::Parser parser (stringToParse, i);
  4368. term = parser.readExpression();
  4369. if (term == 0)
  4370. term = new Helpers::Constant (0, false);
  4371. }
  4372. const Expression Expression::parse (const String& stringToParse, int& textIndexToStartFrom)
  4373. {
  4374. Helpers::Parser parser (stringToParse, textIndexToStartFrom);
  4375. const Helpers::TermPtr term (parser.readExpression());
  4376. if (term != 0)
  4377. return Expression (term);
  4378. return Expression();
  4379. }
  4380. double Expression::evaluate() const
  4381. {
  4382. return evaluate (Expression::EvaluationContext());
  4383. }
  4384. double Expression::evaluate (const Expression::EvaluationContext& context) const
  4385. {
  4386. return term->evaluate (context, 0);
  4387. }
  4388. const Expression Expression::operator+ (const Expression& other) const { return Expression (new Helpers::Add (term, other.term)); }
  4389. const Expression Expression::operator- (const Expression& other) const { return Expression (new Helpers::Subtract (term, other.term)); }
  4390. const Expression Expression::operator* (const Expression& other) const { return Expression (new Helpers::Multiply (term, other.term)); }
  4391. const Expression Expression::operator/ (const Expression& other) const { return Expression (new Helpers::Divide (term, other.term)); }
  4392. const Expression Expression::operator-() const { return Expression (term->negated()); }
  4393. const String Expression::toString() const
  4394. {
  4395. return term->toString();
  4396. }
  4397. const Expression Expression::symbol (const String& symbol)
  4398. {
  4399. return Expression (new Helpers::Symbol (symbol));
  4400. }
  4401. const Expression Expression::function (const String& functionName, const Array<Expression>& parameters)
  4402. {
  4403. ReferenceCountedArray<Term> params;
  4404. for (int i = 0; i < parameters.size(); ++i)
  4405. params.add (parameters.getReference(i).term);
  4406. return Expression (new Helpers::Function (functionName, params));
  4407. }
  4408. const Expression Expression::adjustedToGiveNewResult (const double targetValue,
  4409. const Expression::EvaluationContext& context) const
  4410. {
  4411. ScopedPointer<Term> newTerm (term->clone());
  4412. Helpers::Constant* termToAdjust = Helpers::findTermToAdjust (newTerm, true);
  4413. if (termToAdjust == 0)
  4414. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4415. if (termToAdjust == 0)
  4416. {
  4417. newTerm = new Helpers::Add (newTerm.release(), new Helpers::Constant (0, false));
  4418. termToAdjust = Helpers::findTermToAdjust (newTerm, false);
  4419. }
  4420. jassert (termToAdjust != 0);
  4421. const Term* parent = Helpers::findDestinationFor (newTerm, termToAdjust);
  4422. if (parent == 0)
  4423. {
  4424. termToAdjust->value = targetValue;
  4425. }
  4426. else
  4427. {
  4428. const Helpers::TermPtr reverseTerm (parent->createTermToEvaluateInput (context, termToAdjust, targetValue, newTerm));
  4429. if (reverseTerm == 0)
  4430. return Expression (targetValue);
  4431. termToAdjust->value = reverseTerm->evaluate (context, 0);
  4432. }
  4433. return Expression (newTerm.release());
  4434. }
  4435. const Expression Expression::withRenamedSymbol (const String& oldSymbol, const String& newSymbol) const
  4436. {
  4437. jassert (newSymbol.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  4438. Expression newExpression (term->clone());
  4439. Helpers::renameSymbol (newExpression.term, oldSymbol, newSymbol);
  4440. return newExpression;
  4441. }
  4442. bool Expression::referencesSymbol (const String& symbol, const EvaluationContext* context) const
  4443. {
  4444. return term->referencesSymbol (symbol, context, 0);
  4445. }
  4446. bool Expression::usesAnySymbols() const
  4447. {
  4448. return Helpers::containsAnySymbols (term);
  4449. }
  4450. Expression::Type Expression::getType() const throw()
  4451. {
  4452. return term->getType();
  4453. }
  4454. const String Expression::getSymbol() const
  4455. {
  4456. return term->getSymbolName();
  4457. }
  4458. const String Expression::getFunction() const
  4459. {
  4460. return term->getFunctionName();
  4461. }
  4462. const String Expression::getOperator() const
  4463. {
  4464. return term->getFunctionName();
  4465. }
  4466. int Expression::getNumInputs() const
  4467. {
  4468. return term->getNumInputs();
  4469. }
  4470. const Expression Expression::getInput (int index) const
  4471. {
  4472. return Expression (term->getInput (index));
  4473. }
  4474. int Expression::Term::getOperatorPrecedence() const
  4475. {
  4476. return 0;
  4477. }
  4478. bool Expression::Term::referencesSymbol (const String&, const EvaluationContext*, int) const
  4479. {
  4480. return false;
  4481. }
  4482. int Expression::Term::getInputIndexFor (const Term*) const
  4483. {
  4484. return -1;
  4485. }
  4486. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::createTermToEvaluateInput (const EvaluationContext&, const Term*, double, Term*) const
  4487. {
  4488. jassertfalse;
  4489. return 0;
  4490. }
  4491. const ReferenceCountedObjectPtr<Expression::Term> Expression::Term::negated()
  4492. {
  4493. return new Helpers::Negate (this);
  4494. }
  4495. const String Expression::Term::getSymbolName() const
  4496. {
  4497. jassertfalse; // You should only call getSymbol() on an expression that's actually a symbol!
  4498. return String::empty;
  4499. }
  4500. const String Expression::Term::getFunctionName() const
  4501. {
  4502. jassertfalse; // You shouldn't call this for an expression that's not actually a function!
  4503. return String::empty;
  4504. }
  4505. Expression::ParseError::ParseError (const String& message)
  4506. : description (message)
  4507. {
  4508. DBG ("Expression::ParseError: " + message);
  4509. }
  4510. Expression::EvaluationError::EvaluationError (const String& message)
  4511. : description (message)
  4512. {
  4513. DBG ("Expression::EvaluationError: " + description);
  4514. }
  4515. Expression::EvaluationError::EvaluationError (const String& symbol, const String& member)
  4516. : description ("Unknown symbol: \"" + symbol + (member.isEmpty() ? "\"" : ("." + member + "\"")))
  4517. {
  4518. DBG ("Expression::EvaluationError: " + description);
  4519. }
  4520. Expression::EvaluationContext::EvaluationContext() {}
  4521. Expression::EvaluationContext::~EvaluationContext() {}
  4522. const Expression Expression::EvaluationContext::getSymbolValue (const String& symbol, const String& member) const
  4523. {
  4524. throw EvaluationError (symbol, member);
  4525. }
  4526. double Expression::EvaluationContext::evaluateFunction (const String& functionName, const double* parameters, int numParams) const
  4527. {
  4528. if (numParams > 0)
  4529. {
  4530. if (functionName == "min")
  4531. {
  4532. double v = parameters[0];
  4533. for (int i = 1; i < numParams; ++i)
  4534. v = jmin (v, parameters[i]);
  4535. return v;
  4536. }
  4537. else if (functionName == "max")
  4538. {
  4539. double v = parameters[0];
  4540. for (int i = 1; i < numParams; ++i)
  4541. v = jmax (v, parameters[i]);
  4542. return v;
  4543. }
  4544. else if (numParams == 1)
  4545. {
  4546. if (functionName == "sin") return sin (parameters[0]);
  4547. else if (functionName == "cos") return cos (parameters[0]);
  4548. else if (functionName == "tan") return tan (parameters[0]);
  4549. else if (functionName == "abs") return std::abs (parameters[0]);
  4550. }
  4551. }
  4552. throw EvaluationError ("Unknown function: \"" + functionName + "\"");
  4553. }
  4554. END_JUCE_NAMESPACE
  4555. /*** End of inlined file: juce_Expression.cpp ***/
  4556. /*** Start of inlined file: juce_BlowFish.cpp ***/
  4557. BEGIN_JUCE_NAMESPACE
  4558. BlowFish::BlowFish (const void* const keyData, const int keyBytes)
  4559. {
  4560. jassert (keyData != 0);
  4561. jassert (keyBytes > 0);
  4562. static const uint32 initialPValues [18] =
  4563. {
  4564. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344, 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  4565. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c, 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  4566. 0x9216d5d9, 0x8979fb1b
  4567. };
  4568. static const uint32 initialSValues [4 * 256] =
  4569. {
  4570. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  4571. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  4572. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  4573. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef, 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  4574. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60, 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  4575. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce, 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  4576. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e, 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  4577. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193, 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  4578. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88, 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  4579. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e, 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  4580. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3, 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  4581. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88, 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  4582. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6, 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  4583. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b, 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  4584. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba, 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  4585. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f, 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  4586. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3, 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  4587. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279, 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  4588. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab, 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  4589. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db, 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  4590. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0, 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  4591. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790, 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  4592. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4, 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  4593. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7, 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  4594. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad, 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  4595. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299, 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  4596. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477, 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  4597. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49, 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  4598. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa, 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  4599. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41, 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  4600. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400, 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  4601. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664, 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  4602. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623, 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  4603. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1, 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  4604. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6, 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  4605. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e, 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  4606. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737, 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  4607. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff, 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  4608. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701, 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  4609. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41, 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  4610. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf, 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  4611. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e, 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  4612. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c, 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  4613. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16, 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  4614. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b, 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  4615. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e, 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  4616. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f, 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  4617. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4, 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  4618. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66, 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  4619. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802, 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  4620. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510, 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  4621. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14, 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  4622. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50, 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  4623. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8, 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  4624. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99, 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  4625. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128, 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  4626. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0, 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  4627. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105, 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  4628. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3, 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  4629. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00, 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  4630. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb, 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  4631. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735, 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  4632. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9, 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  4633. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20, 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  4634. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934, 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  4635. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af, 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  4636. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45, 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  4637. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a, 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  4638. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee, 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  4639. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42, 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  4640. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2, 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  4641. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527, 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  4642. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33, 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  4643. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3, 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  4644. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17, 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  4645. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b, 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  4646. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922, 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  4647. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0, 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  4648. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37, 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  4649. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804, 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  4650. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3, 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  4651. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d, 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  4652. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350, 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  4653. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a, 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  4654. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d, 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  4655. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f, 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  4656. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2, 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  4657. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2, 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  4658. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e, 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  4659. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10, 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  4660. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52, 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  4661. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5, 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  4662. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634, 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  4663. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24, 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  4664. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4, 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  4665. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837, 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  4666. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b, 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  4667. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b, 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  4668. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8, 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  4669. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304, 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  4670. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4, 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  4671. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9, 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  4672. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593, 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  4673. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28, 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  4674. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b, 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  4675. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c, 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  4676. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a, 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  4677. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb, 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  4678. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991, 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  4679. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680, 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  4680. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae, 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  4681. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5, 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  4682. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370, 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  4683. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84, 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  4684. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8, 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  4685. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9, 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  4686. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38, 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  4687. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c, 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  4688. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1, 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  4689. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964, 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  4690. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8, 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  4691. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f, 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  4692. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02, 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  4693. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614, 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  4694. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6, 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  4695. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0, 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  4696. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e, 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  4697. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f, 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  4698. };
  4699. memcpy (p, initialPValues, sizeof (p));
  4700. int i, j = 0;
  4701. for (i = 4; --i >= 0;)
  4702. {
  4703. s[i].malloc (256);
  4704. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  4705. }
  4706. for (i = 0; i < 18; ++i)
  4707. {
  4708. uint32 d = 0;
  4709. for (int k = 0; k < 4; ++k)
  4710. {
  4711. d = (d << 8) | static_cast <const uint8*> (keyData)[j];
  4712. if (++j >= keyBytes)
  4713. j = 0;
  4714. }
  4715. p[i] = initialPValues[i] ^ d;
  4716. }
  4717. uint32 l = 0, r = 0;
  4718. for (i = 0; i < 18; i += 2)
  4719. {
  4720. encrypt (l, r);
  4721. p[i] = l;
  4722. p[i + 1] = r;
  4723. }
  4724. for (i = 0; i < 4; ++i)
  4725. {
  4726. for (j = 0; j < 256; j += 2)
  4727. {
  4728. encrypt (l, r);
  4729. s[i][j] = l;
  4730. s[i][j + 1] = r;
  4731. }
  4732. }
  4733. }
  4734. BlowFish::BlowFish (const BlowFish& other)
  4735. {
  4736. for (int i = 4; --i >= 0;)
  4737. s[i].malloc (256);
  4738. operator= (other);
  4739. }
  4740. BlowFish& BlowFish::operator= (const BlowFish& other)
  4741. {
  4742. memcpy (p, other.p, sizeof (p));
  4743. for (int i = 4; --i >= 0;)
  4744. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  4745. return *this;
  4746. }
  4747. BlowFish::~BlowFish()
  4748. {
  4749. }
  4750. uint32 BlowFish::F (const uint32 x) const throw()
  4751. {
  4752. return ((s[0][(x >> 24) & 0xff] + s[1][(x >> 16) & 0xff])
  4753. ^ s[2][(x >> 8) & 0xff]) + s[3][x & 0xff];
  4754. }
  4755. void BlowFish::encrypt (uint32& data1, uint32& data2) const throw()
  4756. {
  4757. uint32 l = data1;
  4758. uint32 r = data2;
  4759. for (int i = 0; i < 16; ++i)
  4760. {
  4761. l ^= p[i];
  4762. r ^= F(l);
  4763. swapVariables (l, r);
  4764. }
  4765. data1 = r ^ p[17];
  4766. data2 = l ^ p[16];
  4767. }
  4768. void BlowFish::decrypt (uint32& data1, uint32& data2) const throw()
  4769. {
  4770. uint32 l = data1;
  4771. uint32 r = data2;
  4772. for (int i = 17; i > 1; --i)
  4773. {
  4774. l ^= p[i];
  4775. r ^= F(l);
  4776. swapVariables (l, r);
  4777. }
  4778. data1 = r ^ p[0];
  4779. data2 = l ^ p[1];
  4780. }
  4781. END_JUCE_NAMESPACE
  4782. /*** End of inlined file: juce_BlowFish.cpp ***/
  4783. /*** Start of inlined file: juce_MD5.cpp ***/
  4784. BEGIN_JUCE_NAMESPACE
  4785. MD5::MD5()
  4786. {
  4787. zerostruct (result);
  4788. }
  4789. MD5::MD5 (const MD5& other)
  4790. {
  4791. memcpy (result, other.result, sizeof (result));
  4792. }
  4793. MD5& MD5::operator= (const MD5& other)
  4794. {
  4795. memcpy (result, other.result, sizeof (result));
  4796. return *this;
  4797. }
  4798. MD5::MD5 (const MemoryBlock& data)
  4799. {
  4800. ProcessContext context;
  4801. context.processBlock (data.getData(), data.getSize());
  4802. context.finish (result);
  4803. }
  4804. MD5::MD5 (const void* data, const size_t numBytes)
  4805. {
  4806. ProcessContext context;
  4807. context.processBlock (data, numBytes);
  4808. context.finish (result);
  4809. }
  4810. MD5::MD5 (const String& text)
  4811. {
  4812. ProcessContext context;
  4813. const int len = text.length();
  4814. const juce_wchar* const t = text;
  4815. for (int i = 0; i < len; ++i)
  4816. {
  4817. // force the string into integer-sized unicode characters, to try to make it
  4818. // get the same results on all platforms + compilers.
  4819. uint32 unicodeChar = ByteOrder::swapIfBigEndian ((uint32) t[i]);
  4820. context.processBlock (&unicodeChar, sizeof (unicodeChar));
  4821. }
  4822. context.finish (result);
  4823. }
  4824. void MD5::processStream (InputStream& input, int64 numBytesToRead)
  4825. {
  4826. ProcessContext context;
  4827. if (numBytesToRead < 0)
  4828. numBytesToRead = std::numeric_limits<int64>::max();
  4829. while (numBytesToRead > 0)
  4830. {
  4831. uint8 tempBuffer [512];
  4832. const int bytesRead = input.read (tempBuffer, (int) jmin (numBytesToRead, (int64) sizeof (tempBuffer)));
  4833. if (bytesRead <= 0)
  4834. break;
  4835. numBytesToRead -= bytesRead;
  4836. context.processBlock (tempBuffer, bytesRead);
  4837. }
  4838. context.finish (result);
  4839. }
  4840. MD5::MD5 (InputStream& input, int64 numBytesToRead)
  4841. {
  4842. processStream (input, numBytesToRead);
  4843. }
  4844. MD5::MD5 (const File& file)
  4845. {
  4846. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  4847. if (fin != 0)
  4848. processStream (*fin, -1);
  4849. else
  4850. zerostruct (result);
  4851. }
  4852. MD5::~MD5()
  4853. {
  4854. }
  4855. namespace MD5Functions
  4856. {
  4857. static void encode (void* const output, const void* const input, const int numBytes) throw()
  4858. {
  4859. for (int i = 0; i < (numBytes >> 2); ++i)
  4860. static_cast<uint32*> (output)[i] = ByteOrder::swapIfBigEndian (static_cast<const uint32*> (input) [i]);
  4861. }
  4862. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & y) | (~x & z); }
  4863. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) throw() { return (x & z) | (y & ~z); }
  4864. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) throw() { return x ^ y ^ z; }
  4865. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) throw() { return y ^ (x | ~z); }
  4866. static inline uint32 rotateLeft (const uint32 x, const uint32 n) throw() { return (x << n) | (x >> (32 - n)); }
  4867. static void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4868. {
  4869. a += F (b, c, d) + x + ac;
  4870. a = rotateLeft (a, s) + b;
  4871. }
  4872. static void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4873. {
  4874. a += G (b, c, d) + x + ac;
  4875. a = rotateLeft (a, s) + b;
  4876. }
  4877. static void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4878. {
  4879. a += H (b, c, d) + x + ac;
  4880. a = rotateLeft (a, s) + b;
  4881. }
  4882. static void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac) throw()
  4883. {
  4884. a += I (b, c, d) + x + ac;
  4885. a = rotateLeft (a, s) + b;
  4886. }
  4887. }
  4888. MD5::ProcessContext::ProcessContext()
  4889. {
  4890. state[0] = 0x67452301;
  4891. state[1] = 0xefcdab89;
  4892. state[2] = 0x98badcfe;
  4893. state[3] = 0x10325476;
  4894. count[0] = 0;
  4895. count[1] = 0;
  4896. }
  4897. void MD5::ProcessContext::processBlock (const void* const data, const size_t dataSize)
  4898. {
  4899. int bufferPos = ((count[0] >> 3) & 0x3F);
  4900. count[0] += (uint32) (dataSize << 3);
  4901. if (count[0] < ((uint32) dataSize << 3))
  4902. count[1]++;
  4903. count[1] += (uint32) (dataSize >> 29);
  4904. const size_t spaceLeft = 64 - bufferPos;
  4905. size_t i = 0;
  4906. if (dataSize >= spaceLeft)
  4907. {
  4908. memcpy (buffer + bufferPos, data, spaceLeft);
  4909. transform (buffer);
  4910. for (i = spaceLeft; i + 64 <= dataSize; i += 64)
  4911. transform (static_cast <const char*> (data) + i);
  4912. bufferPos = 0;
  4913. }
  4914. memcpy (buffer + bufferPos, static_cast <const char*> (data) + i, dataSize - i);
  4915. }
  4916. void MD5::ProcessContext::finish (void* const result)
  4917. {
  4918. unsigned char encodedLength[8];
  4919. MD5Functions::encode (encodedLength, count, 8);
  4920. // Pad out to 56 mod 64.
  4921. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  4922. const int paddingLength = (index < 56) ? (56 - index)
  4923. : (120 - index);
  4924. uint8 paddingBuffer [64];
  4925. zeromem (paddingBuffer, paddingLength);
  4926. paddingBuffer [0] = 0x80;
  4927. processBlock (paddingBuffer, paddingLength);
  4928. processBlock (encodedLength, 8);
  4929. MD5Functions::encode (result, state, 16);
  4930. zerostruct (buffer);
  4931. }
  4932. void MD5::ProcessContext::transform (const void* const bufferToTransform)
  4933. {
  4934. using namespace MD5Functions;
  4935. uint32 a = state[0];
  4936. uint32 b = state[1];
  4937. uint32 c = state[2];
  4938. uint32 d = state[3];
  4939. uint32 x[16];
  4940. encode (x, bufferToTransform, 64);
  4941. enum Constants
  4942. {
  4943. S11 = 7, S12 = 12, S13 = 17, S14 = 22, S21 = 5, S22 = 9, S23 = 14, S24 = 20,
  4944. S31 = 4, S32 = 11, S33 = 16, S34 = 23, S41 = 6, S42 = 10, S43 = 15, S44 = 21
  4945. };
  4946. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); FF (d, a, b, c, x[ 1], S12, 0xe8c7b756);
  4947. FF (c, d, a, b, x[ 2], S13, 0x242070db); FF (b, c, d, a, x[ 3], S14, 0xc1bdceee);
  4948. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); FF (d, a, b, c, x[ 5], S12, 0x4787c62a);
  4949. FF (c, d, a, b, x[ 6], S13, 0xa8304613); FF (b, c, d, a, x[ 7], S14, 0xfd469501);
  4950. FF (a, b, c, d, x[ 8], S11, 0x698098d8); FF (d, a, b, c, x[ 9], S12, 0x8b44f7af);
  4951. FF (c, d, a, b, x[10], S13, 0xffff5bb1); FF (b, c, d, a, x[11], S14, 0x895cd7be);
  4952. FF (a, b, c, d, x[12], S11, 0x6b901122); FF (d, a, b, c, x[13], S12, 0xfd987193);
  4953. FF (c, d, a, b, x[14], S13, 0xa679438e); FF (b, c, d, a, x[15], S14, 0x49b40821);
  4954. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); GG (d, a, b, c, x[ 6], S22, 0xc040b340);
  4955. GG (c, d, a, b, x[11], S23, 0x265e5a51); GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa);
  4956. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); GG (d, a, b, c, x[10], S22, 0x02441453);
  4957. GG (c, d, a, b, x[15], S23, 0xd8a1e681); GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8);
  4958. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); GG (d, a, b, c, x[14], S22, 0xc33707d6);
  4959. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); GG (b, c, d, a, x[ 8], S24, 0x455a14ed);
  4960. GG (a, b, c, d, x[13], S21, 0xa9e3e905); GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8);
  4961. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); GG (b, c, d, a, x[12], S24, 0x8d2a4c8a);
  4962. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); HH (d, a, b, c, x[ 8], S32, 0x8771f681);
  4963. HH (c, d, a, b, x[11], S33, 0x6d9d6122); HH (b, c, d, a, x[14], S34, 0xfde5380c);
  4964. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9);
  4965. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); HH (b, c, d, a, x[10], S34, 0xbebfbc70);
  4966. HH (a, b, c, d, x[13], S31, 0x289b7ec6); HH (d, a, b, c, x[ 0], S32, 0xeaa127fa);
  4967. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); HH (b, c, d, a, x[ 6], S34, 0x04881d05);
  4968. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); HH (d, a, b, c, x[12], S32, 0xe6db99e5);
  4969. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); HH (b, c, d, a, x[ 2], S34, 0xc4ac5665);
  4970. II (a, b, c, d, x[ 0], S41, 0xf4292244); II (d, a, b, c, x[ 7], S42, 0x432aff97);
  4971. II (c, d, a, b, x[14], S43, 0xab9423a7); II (b, c, d, a, x[ 5], S44, 0xfc93a039);
  4972. II (a, b, c, d, x[12], S41, 0x655b59c3); II (d, a, b, c, x[ 3], S42, 0x8f0ccc92);
  4973. II (c, d, a, b, x[10], S43, 0xffeff47d); II (b, c, d, a, x[ 1], S44, 0x85845dd1);
  4974. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); II (d, a, b, c, x[15], S42, 0xfe2ce6e0);
  4975. II (c, d, a, b, x[ 6], S43, 0xa3014314); II (b, c, d, a, x[13], S44, 0x4e0811a1);
  4976. II (a, b, c, d, x[ 4], S41, 0xf7537e82); II (d, a, b, c, x[11], S42, 0xbd3af235);
  4977. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); II (b, c, d, a, x[ 9], S44, 0xeb86d391);
  4978. state[0] += a;
  4979. state[1] += b;
  4980. state[2] += c;
  4981. state[3] += d;
  4982. zerostruct (x);
  4983. }
  4984. const MemoryBlock MD5::getRawChecksumData() const
  4985. {
  4986. return MemoryBlock (result, sizeof (result));
  4987. }
  4988. const String MD5::toHexString() const
  4989. {
  4990. return String::toHexString (result, sizeof (result), 0);
  4991. }
  4992. bool MD5::operator== (const MD5& other) const
  4993. {
  4994. return memcmp (result, other.result, sizeof (result)) == 0;
  4995. }
  4996. bool MD5::operator!= (const MD5& other) const
  4997. {
  4998. return ! operator== (other);
  4999. }
  5000. END_JUCE_NAMESPACE
  5001. /*** End of inlined file: juce_MD5.cpp ***/
  5002. /*** Start of inlined file: juce_Primes.cpp ***/
  5003. BEGIN_JUCE_NAMESPACE
  5004. namespace PrimesHelpers
  5005. {
  5006. static void createSmallSieve (const int numBits, BigInteger& result)
  5007. {
  5008. result.setBit (numBits);
  5009. result.clearBit (numBits); // to enlarge the array
  5010. result.setBit (0);
  5011. int n = 2;
  5012. do
  5013. {
  5014. for (int i = n + n; i < numBits; i += n)
  5015. result.setBit (i);
  5016. n = result.findNextClearBit (n + 1);
  5017. }
  5018. while (n <= (numBits >> 1));
  5019. }
  5020. static void bigSieve (const BigInteger& base, const int numBits, BigInteger& result,
  5021. const BigInteger& smallSieve, const int smallSieveSize)
  5022. {
  5023. jassert (! base[0]); // must be even!
  5024. result.setBit (numBits);
  5025. result.clearBit (numBits); // to enlarge the array
  5026. int index = smallSieve.findNextClearBit (0);
  5027. do
  5028. {
  5029. const int prime = (index << 1) + 1;
  5030. BigInteger r (base), remainder;
  5031. r.divideBy (prime, remainder);
  5032. int i = prime - remainder.getBitRangeAsInt (0, 32);
  5033. if (r.isZero())
  5034. i += prime;
  5035. if ((i & 1) == 0)
  5036. i += prime;
  5037. i = (i - 1) >> 1;
  5038. while (i < numBits)
  5039. {
  5040. result.setBit (i);
  5041. i += prime;
  5042. }
  5043. index = smallSieve.findNextClearBit (index + 1);
  5044. }
  5045. while (index < smallSieveSize);
  5046. }
  5047. static bool findCandidate (const BigInteger& base, const BigInteger& sieve,
  5048. const int numBits, BigInteger& result, const int certainty)
  5049. {
  5050. for (int i = 0; i < numBits; ++i)
  5051. {
  5052. if (! sieve[i])
  5053. {
  5054. result = base + (unsigned int) ((i << 1) + 1);
  5055. if (Primes::isProbablyPrime (result, certainty))
  5056. return true;
  5057. }
  5058. }
  5059. return false;
  5060. }
  5061. static bool passesMillerRabin (const BigInteger& n, int iterations)
  5062. {
  5063. const BigInteger one (1), two (2);
  5064. const BigInteger nMinusOne (n - one);
  5065. BigInteger d (nMinusOne);
  5066. const int s = d.findNextSetBit (0);
  5067. d >>= s;
  5068. BigInteger smallPrimes;
  5069. int numBitsInSmallPrimes = 0;
  5070. for (;;)
  5071. {
  5072. numBitsInSmallPrimes += 256;
  5073. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  5074. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  5075. if (numPrimesFound > iterations + 1)
  5076. break;
  5077. }
  5078. int smallPrime = 2;
  5079. while (--iterations >= 0)
  5080. {
  5081. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  5082. BigInteger r (smallPrime);
  5083. r.exponentModulo (d, n);
  5084. if (r != one && r != nMinusOne)
  5085. {
  5086. for (int j = 0; j < s; ++j)
  5087. {
  5088. r.exponentModulo (two, n);
  5089. if (r == nMinusOne)
  5090. break;
  5091. }
  5092. if (r != nMinusOne)
  5093. return false;
  5094. }
  5095. }
  5096. return true;
  5097. }
  5098. }
  5099. const BigInteger Primes::createProbablePrime (const int bitLength,
  5100. const int certainty,
  5101. const int* randomSeeds,
  5102. int numRandomSeeds)
  5103. {
  5104. using namespace PrimesHelpers;
  5105. int defaultSeeds [16];
  5106. if (numRandomSeeds <= 0)
  5107. {
  5108. randomSeeds = defaultSeeds;
  5109. numRandomSeeds = numElementsInArray (defaultSeeds);
  5110. Random r (0);
  5111. for (int j = 10; --j >= 0;)
  5112. {
  5113. r.setSeedRandomly();
  5114. for (int i = numRandomSeeds; --i >= 0;)
  5115. defaultSeeds[i] ^= r.nextInt() ^ Random::getSystemRandom().nextInt();
  5116. }
  5117. }
  5118. BigInteger smallSieve;
  5119. const int smallSieveSize = 15000;
  5120. createSmallSieve (smallSieveSize, smallSieve);
  5121. BigInteger p;
  5122. for (int i = numRandomSeeds; --i >= 0;)
  5123. {
  5124. BigInteger p2;
  5125. Random r (randomSeeds[i]);
  5126. r.fillBitsRandomly (p2, 0, bitLength);
  5127. p ^= p2;
  5128. }
  5129. p.setBit (bitLength - 1);
  5130. p.clearBit (0);
  5131. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  5132. while (p.getHighestBit() < bitLength)
  5133. {
  5134. p += 2 * searchLen;
  5135. BigInteger sieve;
  5136. bigSieve (p, searchLen, sieve,
  5137. smallSieve, smallSieveSize);
  5138. BigInteger candidate;
  5139. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  5140. return candidate;
  5141. }
  5142. jassertfalse;
  5143. return BigInteger();
  5144. }
  5145. bool Primes::isProbablyPrime (const BigInteger& number, const int certainty)
  5146. {
  5147. using namespace PrimesHelpers;
  5148. if (! number[0])
  5149. return false;
  5150. if (number.getHighestBit() <= 10)
  5151. {
  5152. const int num = number.getBitRangeAsInt (0, 10);
  5153. for (int i = num / 2; --i > 1;)
  5154. if (num % i == 0)
  5155. return false;
  5156. return true;
  5157. }
  5158. else
  5159. {
  5160. if (number.findGreatestCommonDivisor (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23) != 1)
  5161. return false;
  5162. return passesMillerRabin (number, certainty);
  5163. }
  5164. }
  5165. END_JUCE_NAMESPACE
  5166. /*** End of inlined file: juce_Primes.cpp ***/
  5167. /*** Start of inlined file: juce_RSAKey.cpp ***/
  5168. BEGIN_JUCE_NAMESPACE
  5169. RSAKey::RSAKey()
  5170. {
  5171. }
  5172. RSAKey::RSAKey (const String& s)
  5173. {
  5174. if (s.containsChar (','))
  5175. {
  5176. part1.parseString (s.upToFirstOccurrenceOf (",", false, false), 16);
  5177. part2.parseString (s.fromFirstOccurrenceOf (",", false, false), 16);
  5178. }
  5179. else
  5180. {
  5181. // the string needs to be two hex numbers, comma-separated..
  5182. jassertfalse;
  5183. }
  5184. }
  5185. RSAKey::~RSAKey()
  5186. {
  5187. }
  5188. bool RSAKey::operator== (const RSAKey& other) const throw()
  5189. {
  5190. return part1 == other.part1 && part2 == other.part2;
  5191. }
  5192. bool RSAKey::operator!= (const RSAKey& other) const throw()
  5193. {
  5194. return ! operator== (other);
  5195. }
  5196. const String RSAKey::toString() const
  5197. {
  5198. return part1.toString (16) + "," + part2.toString (16);
  5199. }
  5200. bool RSAKey::applyToValue (BigInteger& value) const
  5201. {
  5202. if (part1.isZero() || part2.isZero() || value <= 0)
  5203. {
  5204. jassertfalse; // using an uninitialised key
  5205. value.clear();
  5206. return false;
  5207. }
  5208. BigInteger result;
  5209. while (! value.isZero())
  5210. {
  5211. result *= part2;
  5212. BigInteger remainder;
  5213. value.divideBy (part2, remainder);
  5214. remainder.exponentModulo (part1, part2);
  5215. result += remainder;
  5216. }
  5217. value.swapWith (result);
  5218. return true;
  5219. }
  5220. const BigInteger RSAKey::findBestCommonDivisor (const BigInteger& p, const BigInteger& q)
  5221. {
  5222. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  5223. // are fast to divide + multiply
  5224. for (int i = 2; i <= 65536; i *= 2)
  5225. {
  5226. const BigInteger e (1 + i);
  5227. if (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne())
  5228. return e;
  5229. }
  5230. BigInteger e (4);
  5231. while (! (e.findGreatestCommonDivisor (p).isOne() && e.findGreatestCommonDivisor (q).isOne()))
  5232. ++e;
  5233. return e;
  5234. }
  5235. void RSAKey::createKeyPair (RSAKey& publicKey, RSAKey& privateKey,
  5236. const int numBits, const int* randomSeeds, const int numRandomSeeds)
  5237. {
  5238. jassert (numBits > 16); // not much point using less than this..
  5239. jassert (numRandomSeeds == 0 || numRandomSeeds >= 2); // you need to provide plenty of seeds here!
  5240. BigInteger p (Primes::createProbablePrime (numBits / 2, 30, randomSeeds, numRandomSeeds / 2));
  5241. BigInteger q (Primes::createProbablePrime (numBits - numBits / 2, 30, randomSeeds == 0 ? 0 : (randomSeeds + numRandomSeeds / 2), numRandomSeeds - numRandomSeeds / 2));
  5242. const BigInteger n (p * q);
  5243. const BigInteger m (--p * --q);
  5244. const BigInteger e (findBestCommonDivisor (p, q));
  5245. BigInteger d (e);
  5246. d.inverseModulo (m);
  5247. publicKey.part1 = e;
  5248. publicKey.part2 = n;
  5249. privateKey.part1 = d;
  5250. privateKey.part2 = n;
  5251. }
  5252. END_JUCE_NAMESPACE
  5253. /*** End of inlined file: juce_RSAKey.cpp ***/
  5254. /*** Start of inlined file: juce_InputStream.cpp ***/
  5255. BEGIN_JUCE_NAMESPACE
  5256. char InputStream::readByte()
  5257. {
  5258. char temp = 0;
  5259. read (&temp, 1);
  5260. return temp;
  5261. }
  5262. bool InputStream::readBool()
  5263. {
  5264. return readByte() != 0;
  5265. }
  5266. short InputStream::readShort()
  5267. {
  5268. char temp[2];
  5269. if (read (temp, 2) == 2)
  5270. return (short) ByteOrder::littleEndianShort (temp);
  5271. return 0;
  5272. }
  5273. short InputStream::readShortBigEndian()
  5274. {
  5275. char temp[2];
  5276. if (read (temp, 2) == 2)
  5277. return (short) ByteOrder::bigEndianShort (temp);
  5278. return 0;
  5279. }
  5280. int InputStream::readInt()
  5281. {
  5282. char temp[4];
  5283. if (read (temp, 4) == 4)
  5284. return (int) ByteOrder::littleEndianInt (temp);
  5285. return 0;
  5286. }
  5287. int InputStream::readIntBigEndian()
  5288. {
  5289. char temp[4];
  5290. if (read (temp, 4) == 4)
  5291. return (int) ByteOrder::bigEndianInt (temp);
  5292. return 0;
  5293. }
  5294. int InputStream::readCompressedInt()
  5295. {
  5296. const unsigned char sizeByte = readByte();
  5297. if (sizeByte == 0)
  5298. return 0;
  5299. const int numBytes = (sizeByte & 0x7f);
  5300. if (numBytes > 4)
  5301. {
  5302. jassertfalse; // trying to read corrupt data - this method must only be used
  5303. // to read data that was written by OutputStream::writeCompressedInt()
  5304. return 0;
  5305. }
  5306. char bytes[4] = { 0, 0, 0, 0 };
  5307. if (read (bytes, numBytes) != numBytes)
  5308. return 0;
  5309. const int num = (int) ByteOrder::littleEndianInt (bytes);
  5310. return (sizeByte >> 7) ? -num : num;
  5311. }
  5312. int64 InputStream::readInt64()
  5313. {
  5314. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5315. if (read (n.asBytes, 8) == 8)
  5316. return (int64) ByteOrder::swapIfBigEndian (n.asInt64);
  5317. return 0;
  5318. }
  5319. int64 InputStream::readInt64BigEndian()
  5320. {
  5321. union { uint8 asBytes[8]; uint64 asInt64; } n;
  5322. if (read (n.asBytes, 8) == 8)
  5323. return (int64) ByteOrder::swapIfLittleEndian (n.asInt64);
  5324. return 0;
  5325. }
  5326. float InputStream::readFloat()
  5327. {
  5328. // the union below relies on these types being the same size...
  5329. static_jassert (sizeof (int32) == sizeof (float));
  5330. union { int32 asInt; float asFloat; } n;
  5331. n.asInt = (int32) readInt();
  5332. return n.asFloat;
  5333. }
  5334. float InputStream::readFloatBigEndian()
  5335. {
  5336. union { int32 asInt; float asFloat; } n;
  5337. n.asInt = (int32) readIntBigEndian();
  5338. return n.asFloat;
  5339. }
  5340. double InputStream::readDouble()
  5341. {
  5342. union { int64 asInt; double asDouble; } n;
  5343. n.asInt = readInt64();
  5344. return n.asDouble;
  5345. }
  5346. double InputStream::readDoubleBigEndian()
  5347. {
  5348. union { int64 asInt; double asDouble; } n;
  5349. n.asInt = readInt64BigEndian();
  5350. return n.asDouble;
  5351. }
  5352. const String InputStream::readString()
  5353. {
  5354. MemoryBlock buffer (256);
  5355. char* data = static_cast<char*> (buffer.getData());
  5356. size_t i = 0;
  5357. while ((data[i] = readByte()) != 0)
  5358. {
  5359. if (++i >= buffer.getSize())
  5360. {
  5361. buffer.setSize (buffer.getSize() + 512);
  5362. data = static_cast<char*> (buffer.getData());
  5363. }
  5364. }
  5365. return String::fromUTF8 (data, (int) i);
  5366. }
  5367. const String InputStream::readNextLine()
  5368. {
  5369. MemoryBlock buffer (256);
  5370. char* data = static_cast<char*> (buffer.getData());
  5371. size_t i = 0;
  5372. while ((data[i] = readByte()) != 0)
  5373. {
  5374. if (data[i] == '\n')
  5375. break;
  5376. if (data[i] == '\r')
  5377. {
  5378. const int64 lastPos = getPosition();
  5379. if (readByte() != '\n')
  5380. setPosition (lastPos);
  5381. break;
  5382. }
  5383. if (++i >= buffer.getSize())
  5384. {
  5385. buffer.setSize (buffer.getSize() + 512);
  5386. data = static_cast<char*> (buffer.getData());
  5387. }
  5388. }
  5389. return String::fromUTF8 (data, (int) i);
  5390. }
  5391. int InputStream::readIntoMemoryBlock (MemoryBlock& block, int numBytes)
  5392. {
  5393. MemoryOutputStream mo (block, true);
  5394. return mo.writeFromInputStream (*this, numBytes);
  5395. }
  5396. const String InputStream::readEntireStreamAsString()
  5397. {
  5398. MemoryOutputStream mo;
  5399. mo.writeFromInputStream (*this, -1);
  5400. return mo.toString();
  5401. }
  5402. void InputStream::skipNextBytes (int64 numBytesToSkip)
  5403. {
  5404. if (numBytesToSkip > 0)
  5405. {
  5406. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  5407. HeapBlock<char> temp (skipBufferSize);
  5408. while (numBytesToSkip > 0 && ! isExhausted())
  5409. numBytesToSkip -= read (temp, (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  5410. }
  5411. }
  5412. END_JUCE_NAMESPACE
  5413. /*** End of inlined file: juce_InputStream.cpp ***/
  5414. /*** Start of inlined file: juce_OutputStream.cpp ***/
  5415. BEGIN_JUCE_NAMESPACE
  5416. #if JUCE_DEBUG
  5417. static Array<void*, CriticalSection> activeStreams;
  5418. void juce_CheckForDanglingStreams()
  5419. {
  5420. /*
  5421. It's always a bad idea to leak any object, but if you're leaking output
  5422. streams, then there's a good chance that you're failing to flush a file
  5423. to disk properly, which could result in corrupted data and other similar
  5424. nastiness..
  5425. */
  5426. jassert (activeStreams.size() == 0);
  5427. };
  5428. #endif
  5429. OutputStream::OutputStream()
  5430. {
  5431. #if JUCE_DEBUG
  5432. activeStreams.add (this);
  5433. #endif
  5434. }
  5435. OutputStream::~OutputStream()
  5436. {
  5437. #if JUCE_DEBUG
  5438. activeStreams.removeValue (this);
  5439. #endif
  5440. }
  5441. void OutputStream::writeBool (const bool b)
  5442. {
  5443. writeByte (b ? (char) 1
  5444. : (char) 0);
  5445. }
  5446. void OutputStream::writeByte (char byte)
  5447. {
  5448. write (&byte, 1);
  5449. }
  5450. void OutputStream::writeShort (short value)
  5451. {
  5452. const unsigned short v = ByteOrder::swapIfBigEndian ((unsigned short) value);
  5453. write (&v, 2);
  5454. }
  5455. void OutputStream::writeShortBigEndian (short value)
  5456. {
  5457. const unsigned short v = ByteOrder::swapIfLittleEndian ((unsigned short) value);
  5458. write (&v, 2);
  5459. }
  5460. void OutputStream::writeInt (int value)
  5461. {
  5462. const unsigned int v = ByteOrder::swapIfBigEndian ((unsigned int) value);
  5463. write (&v, 4);
  5464. }
  5465. void OutputStream::writeIntBigEndian (int value)
  5466. {
  5467. const unsigned int v = ByteOrder::swapIfLittleEndian ((unsigned int) value);
  5468. write (&v, 4);
  5469. }
  5470. void OutputStream::writeCompressedInt (int value)
  5471. {
  5472. unsigned int un = (value < 0) ? (unsigned int) -value
  5473. : (unsigned int) value;
  5474. uint8 data[5];
  5475. int num = 0;
  5476. while (un > 0)
  5477. {
  5478. data[++num] = (uint8) un;
  5479. un >>= 8;
  5480. }
  5481. data[0] = (uint8) num;
  5482. if (value < 0)
  5483. data[0] |= 0x80;
  5484. write (data, num + 1);
  5485. }
  5486. void OutputStream::writeInt64 (int64 value)
  5487. {
  5488. const uint64 v = ByteOrder::swapIfBigEndian ((uint64) value);
  5489. write (&v, 8);
  5490. }
  5491. void OutputStream::writeInt64BigEndian (int64 value)
  5492. {
  5493. const uint64 v = ByteOrder::swapIfLittleEndian ((uint64) value);
  5494. write (&v, 8);
  5495. }
  5496. void OutputStream::writeFloat (float value)
  5497. {
  5498. union { int asInt; float asFloat; } n;
  5499. n.asFloat = value;
  5500. writeInt (n.asInt);
  5501. }
  5502. void OutputStream::writeFloatBigEndian (float value)
  5503. {
  5504. union { int asInt; float asFloat; } n;
  5505. n.asFloat = value;
  5506. writeIntBigEndian (n.asInt);
  5507. }
  5508. void OutputStream::writeDouble (double value)
  5509. {
  5510. union { int64 asInt; double asDouble; } n;
  5511. n.asDouble = value;
  5512. writeInt64 (n.asInt);
  5513. }
  5514. void OutputStream::writeDoubleBigEndian (double value)
  5515. {
  5516. union { int64 asInt; double asDouble; } n;
  5517. n.asDouble = value;
  5518. writeInt64BigEndian (n.asInt);
  5519. }
  5520. void OutputStream::writeString (const String& text)
  5521. {
  5522. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  5523. // if lots of large, persistent strings were to be written to streams).
  5524. const int numBytes = text.getNumBytesAsUTF8() + 1;
  5525. HeapBlock<char> temp (numBytes);
  5526. text.copyToUTF8 (temp, numBytes);
  5527. write (temp, numBytes);
  5528. }
  5529. void OutputStream::writeText (const String& text, const bool asUnicode,
  5530. const bool writeUnicodeHeaderBytes)
  5531. {
  5532. if (asUnicode)
  5533. {
  5534. if (writeUnicodeHeaderBytes)
  5535. write ("\x0ff\x0fe", 2);
  5536. const juce_wchar* src = text;
  5537. bool lastCharWasReturn = false;
  5538. while (*src != 0)
  5539. {
  5540. if (*src == L'\n' && ! lastCharWasReturn)
  5541. writeShort ((short) L'\r');
  5542. lastCharWasReturn = (*src == L'\r');
  5543. writeShort ((short) *src++);
  5544. }
  5545. }
  5546. else
  5547. {
  5548. const char* src = text.toUTF8();
  5549. const char* t = src;
  5550. for (;;)
  5551. {
  5552. if (*t == '\n')
  5553. {
  5554. if (t > src)
  5555. write (src, (int) (t - src));
  5556. write ("\r\n", 2);
  5557. src = t + 1;
  5558. }
  5559. else if (*t == '\r')
  5560. {
  5561. if (t[1] == '\n')
  5562. ++t;
  5563. }
  5564. else if (*t == 0)
  5565. {
  5566. if (t > src)
  5567. write (src, (int) (t - src));
  5568. break;
  5569. }
  5570. ++t;
  5571. }
  5572. }
  5573. }
  5574. int OutputStream::writeFromInputStream (InputStream& source, int64 numBytesToWrite)
  5575. {
  5576. if (numBytesToWrite < 0)
  5577. numBytesToWrite = std::numeric_limits<int64>::max();
  5578. int numWritten = 0;
  5579. while (numBytesToWrite > 0 && ! source.isExhausted())
  5580. {
  5581. char buffer [8192];
  5582. const int num = source.read (buffer, (int) jmin (numBytesToWrite, (int64) sizeof (buffer)));
  5583. if (num <= 0)
  5584. break;
  5585. write (buffer, num);
  5586. numBytesToWrite -= num;
  5587. numWritten += num;
  5588. }
  5589. return numWritten;
  5590. }
  5591. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const int number)
  5592. {
  5593. return stream << String (number);
  5594. }
  5595. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const double number)
  5596. {
  5597. return stream << String (number);
  5598. }
  5599. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char character)
  5600. {
  5601. stream.writeByte (character);
  5602. return stream;
  5603. }
  5604. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const char* const text)
  5605. {
  5606. stream.write (text, (int) strlen (text));
  5607. return stream;
  5608. }
  5609. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryBlock& data)
  5610. {
  5611. stream.write (data.getData(), (int) data.getSize());
  5612. return stream;
  5613. }
  5614. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const File& fileToRead)
  5615. {
  5616. const ScopedPointer<FileInputStream> in (fileToRead.createInputStream());
  5617. if (in != 0)
  5618. stream.writeFromInputStream (*in, -1);
  5619. return stream;
  5620. }
  5621. END_JUCE_NAMESPACE
  5622. /*** End of inlined file: juce_OutputStream.cpp ***/
  5623. /*** Start of inlined file: juce_DirectoryIterator.cpp ***/
  5624. BEGIN_JUCE_NAMESPACE
  5625. DirectoryIterator::DirectoryIterator (const File& directory,
  5626. bool isRecursive_,
  5627. const String& wildCard_,
  5628. const int whatToLookFor_)
  5629. : fileFinder (directory, isRecursive_ ? "*" : wildCard_),
  5630. wildCard (wildCard_),
  5631. path (File::addTrailingSeparator (directory.getFullPathName())),
  5632. index (-1),
  5633. totalNumFiles (-1),
  5634. whatToLookFor (whatToLookFor_),
  5635. isRecursive (isRecursive_),
  5636. hasBeenAdvanced (false)
  5637. {
  5638. // you have to specify the type of files you're looking for!
  5639. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  5640. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  5641. }
  5642. DirectoryIterator::~DirectoryIterator()
  5643. {
  5644. }
  5645. bool DirectoryIterator::next()
  5646. {
  5647. return next (0, 0, 0, 0, 0, 0);
  5648. }
  5649. bool DirectoryIterator::next (bool* const isDirResult, bool* const isHiddenResult, int64* const fileSize,
  5650. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  5651. {
  5652. hasBeenAdvanced = true;
  5653. if (subIterator != 0)
  5654. {
  5655. if (subIterator->next (isDirResult, isHiddenResult, fileSize, modTime, creationTime, isReadOnly))
  5656. return true;
  5657. subIterator = 0;
  5658. }
  5659. String filename;
  5660. bool isDirectory, isHidden;
  5661. while (fileFinder.next (filename, &isDirectory, &isHidden, fileSize, modTime, creationTime, isReadOnly))
  5662. {
  5663. ++index;
  5664. if (! filename.containsOnly ("."))
  5665. {
  5666. const File fileFound (path + filename, 0);
  5667. bool matches = false;
  5668. if (isDirectory)
  5669. {
  5670. if (isRecursive && ((whatToLookFor & File::ignoreHiddenFiles) == 0 || ! isHidden))
  5671. subIterator = new DirectoryIterator (fileFound, true, wildCard, whatToLookFor);
  5672. matches = (whatToLookFor & File::findDirectories) != 0;
  5673. }
  5674. else
  5675. {
  5676. matches = (whatToLookFor & File::findFiles) != 0;
  5677. }
  5678. // if recursive, we're not relying on the OS iterator to do the wildcard match, so do it now..
  5679. if (matches && isRecursive)
  5680. matches = filename.matchesWildcard (wildCard, ! File::areFileNamesCaseSensitive());
  5681. if (matches && (whatToLookFor & File::ignoreHiddenFiles) != 0)
  5682. matches = ! isHidden;
  5683. if (matches)
  5684. {
  5685. currentFile = fileFound;
  5686. if (isHiddenResult != 0) *isHiddenResult = isHidden;
  5687. if (isDirResult != 0) *isDirResult = isDirectory;
  5688. return true;
  5689. }
  5690. else if (subIterator != 0)
  5691. {
  5692. return next();
  5693. }
  5694. }
  5695. }
  5696. return false;
  5697. }
  5698. const File DirectoryIterator::getFile() const
  5699. {
  5700. if (subIterator != 0 && subIterator->hasBeenAdvanced)
  5701. return subIterator->getFile();
  5702. // You need to call DirectoryIterator::next() before asking it for the file that it found!
  5703. jassert (hasBeenAdvanced);
  5704. return currentFile;
  5705. }
  5706. float DirectoryIterator::getEstimatedProgress() const
  5707. {
  5708. if (totalNumFiles < 0)
  5709. totalNumFiles = File (path).getNumberOfChildFiles (File::findFilesAndDirectories);
  5710. if (totalNumFiles <= 0)
  5711. return 0.0f;
  5712. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  5713. : (float) index;
  5714. return detailedIndex / totalNumFiles;
  5715. }
  5716. END_JUCE_NAMESPACE
  5717. /*** End of inlined file: juce_DirectoryIterator.cpp ***/
  5718. /*** Start of inlined file: juce_File.cpp ***/
  5719. #if ! JUCE_WINDOWS
  5720. #include <pwd.h>
  5721. #endif
  5722. BEGIN_JUCE_NAMESPACE
  5723. File::File (const String& fullPathName)
  5724. : fullPath (parseAbsolutePath (fullPathName))
  5725. {
  5726. }
  5727. File::File (const String& path, int)
  5728. : fullPath (path)
  5729. {
  5730. }
  5731. const File File::createFileWithoutCheckingPath (const String& path)
  5732. {
  5733. return File (path, 0);
  5734. }
  5735. File::File (const File& other)
  5736. : fullPath (other.fullPath)
  5737. {
  5738. }
  5739. File& File::operator= (const String& newPath)
  5740. {
  5741. fullPath = parseAbsolutePath (newPath);
  5742. return *this;
  5743. }
  5744. File& File::operator= (const File& other)
  5745. {
  5746. fullPath = other.fullPath;
  5747. return *this;
  5748. }
  5749. const File File::nonexistent;
  5750. const String File::parseAbsolutePath (const String& p)
  5751. {
  5752. if (p.isEmpty())
  5753. return String::empty;
  5754. #if JUCE_WINDOWS
  5755. // Windows..
  5756. String path (p.replaceCharacter ('/', '\\'));
  5757. if (path.startsWithChar (File::separator))
  5758. {
  5759. if (path[1] != File::separator)
  5760. {
  5761. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5762. If you're trying to parse a string that may be either a relative path or an absolute path,
  5763. you MUST provide a context against which the partial path can be evaluated - you can do
  5764. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5765. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5766. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5767. */
  5768. jassertfalse;
  5769. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  5770. }
  5771. }
  5772. else if (! path.containsChar (':'))
  5773. {
  5774. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5775. If you're trying to parse a string that may be either a relative path or an absolute path,
  5776. you MUST provide a context against which the partial path can be evaluated - you can do
  5777. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5778. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5779. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5780. */
  5781. jassertfalse;
  5782. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5783. }
  5784. #else
  5785. // Mac or Linux..
  5786. String path (p.replaceCharacter ('\\', '/'));
  5787. if (path.startsWithChar ('~'))
  5788. {
  5789. if (path[1] == File::separator || path[1] == 0)
  5790. {
  5791. // expand a name of the form "~/abc"
  5792. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  5793. + path.substring (1);
  5794. }
  5795. else
  5796. {
  5797. // expand a name of type "~dave/abc"
  5798. const String userName (path.substring (1).upToFirstOccurrenceOf ("/", false, false));
  5799. struct passwd* const pw = getpwnam (userName.toUTF8());
  5800. if (pw != 0)
  5801. path = addTrailingSeparator (pw->pw_dir) + path.fromFirstOccurrenceOf ("/", false, false);
  5802. }
  5803. }
  5804. else if (! path.startsWithChar (File::separator))
  5805. {
  5806. /* When you supply a raw string to the File object constructor, it must be an absolute path.
  5807. If you're trying to parse a string that may be either a relative path or an absolute path,
  5808. you MUST provide a context against which the partial path can be evaluated - you can do
  5809. this by simply using File::getChildFile() instead of the File constructor. E.g. saying
  5810. "File::getCurrentWorkingDirectory().getChildFile (myUnknownPath)" would return an absolute
  5811. path if that's what was supplied, or would evaluate a partial path relative to the CWD.
  5812. */
  5813. jassert (path.startsWith ("./") || path.startsWith ("../")); // (assume that a path "./xyz" is deliberately intended to be relative to the CWD)
  5814. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  5815. }
  5816. #endif
  5817. while (path.endsWithChar (separator) && path != separatorString) // careful not to turn a single "/" into an empty string.
  5818. path = path.dropLastCharacters (1);
  5819. return path;
  5820. }
  5821. const String File::addTrailingSeparator (const String& path)
  5822. {
  5823. return path.endsWithChar (File::separator) ? path
  5824. : path + File::separator;
  5825. }
  5826. #if JUCE_LINUX
  5827. #define NAMES_ARE_CASE_SENSITIVE 1
  5828. #endif
  5829. bool File::areFileNamesCaseSensitive()
  5830. {
  5831. #if NAMES_ARE_CASE_SENSITIVE
  5832. return true;
  5833. #else
  5834. return false;
  5835. #endif
  5836. }
  5837. bool File::operator== (const File& other) const
  5838. {
  5839. #if NAMES_ARE_CASE_SENSITIVE
  5840. return fullPath == other.fullPath;
  5841. #else
  5842. return fullPath.equalsIgnoreCase (other.fullPath);
  5843. #endif
  5844. }
  5845. bool File::operator!= (const File& other) const
  5846. {
  5847. return ! operator== (other);
  5848. }
  5849. bool File::operator< (const File& other) const
  5850. {
  5851. #if NAMES_ARE_CASE_SENSITIVE
  5852. return fullPath < other.fullPath;
  5853. #else
  5854. return fullPath.compareIgnoreCase (other.fullPath) < 0;
  5855. #endif
  5856. }
  5857. bool File::operator> (const File& other) const
  5858. {
  5859. #if NAMES_ARE_CASE_SENSITIVE
  5860. return fullPath > other.fullPath;
  5861. #else
  5862. return fullPath.compareIgnoreCase (other.fullPath) > 0;
  5863. #endif
  5864. }
  5865. bool File::setReadOnly (const bool shouldBeReadOnly,
  5866. const bool applyRecursively) const
  5867. {
  5868. bool worked = true;
  5869. if (applyRecursively && isDirectory())
  5870. {
  5871. Array <File> subFiles;
  5872. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5873. for (int i = subFiles.size(); --i >= 0;)
  5874. worked = subFiles.getReference(i).setReadOnly (shouldBeReadOnly, true) && worked;
  5875. }
  5876. return setFileReadOnlyInternal (shouldBeReadOnly) && worked;
  5877. }
  5878. bool File::deleteRecursively() const
  5879. {
  5880. bool worked = true;
  5881. if (isDirectory())
  5882. {
  5883. Array<File> subFiles;
  5884. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  5885. for (int i = subFiles.size(); --i >= 0;)
  5886. worked = subFiles.getReference(i).deleteRecursively() && worked;
  5887. }
  5888. return deleteFile() && worked;
  5889. }
  5890. bool File::moveFileTo (const File& newFile) const
  5891. {
  5892. if (newFile.fullPath == fullPath)
  5893. return true;
  5894. #if ! NAMES_ARE_CASE_SENSITIVE
  5895. if (*this != newFile)
  5896. #endif
  5897. if (! newFile.deleteFile())
  5898. return false;
  5899. return moveInternal (newFile);
  5900. }
  5901. bool File::copyFileTo (const File& newFile) const
  5902. {
  5903. return (*this == newFile)
  5904. || (exists() && newFile.deleteFile() && copyInternal (newFile));
  5905. }
  5906. bool File::copyDirectoryTo (const File& newDirectory) const
  5907. {
  5908. if (isDirectory() && newDirectory.createDirectory())
  5909. {
  5910. Array<File> subFiles;
  5911. findChildFiles (subFiles, File::findFiles, false);
  5912. int i;
  5913. for (i = 0; i < subFiles.size(); ++i)
  5914. if (! subFiles.getReference(i).copyFileTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5915. return false;
  5916. subFiles.clear();
  5917. findChildFiles (subFiles, File::findDirectories, false);
  5918. for (i = 0; i < subFiles.size(); ++i)
  5919. if (! subFiles.getReference(i).copyDirectoryTo (newDirectory.getChildFile (subFiles.getReference(i).getFileName())))
  5920. return false;
  5921. return true;
  5922. }
  5923. return false;
  5924. }
  5925. const String File::getPathUpToLastSlash() const
  5926. {
  5927. const int lastSlash = fullPath.lastIndexOfChar (separator);
  5928. if (lastSlash > 0)
  5929. return fullPath.substring (0, lastSlash);
  5930. else if (lastSlash == 0)
  5931. return separatorString;
  5932. else
  5933. return fullPath;
  5934. }
  5935. const File File::getParentDirectory() const
  5936. {
  5937. return File (getPathUpToLastSlash(), (int) 0);
  5938. }
  5939. const String File::getFileName() const
  5940. {
  5941. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  5942. }
  5943. int File::hashCode() const
  5944. {
  5945. return fullPath.hashCode();
  5946. }
  5947. int64 File::hashCode64() const
  5948. {
  5949. return fullPath.hashCode64();
  5950. }
  5951. const String File::getFileNameWithoutExtension() const
  5952. {
  5953. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  5954. const int lastDot = fullPath.lastIndexOfChar ('.');
  5955. if (lastDot > lastSlash)
  5956. return fullPath.substring (lastSlash, lastDot);
  5957. else
  5958. return fullPath.substring (lastSlash);
  5959. }
  5960. bool File::isAChildOf (const File& potentialParent) const
  5961. {
  5962. if (potentialParent == File::nonexistent)
  5963. return false;
  5964. const String ourPath (getPathUpToLastSlash());
  5965. #if NAMES_ARE_CASE_SENSITIVE
  5966. if (potentialParent.fullPath == ourPath)
  5967. #else
  5968. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  5969. #endif
  5970. {
  5971. return true;
  5972. }
  5973. else if (potentialParent.fullPath.length() >= ourPath.length())
  5974. {
  5975. return false;
  5976. }
  5977. else
  5978. {
  5979. return getParentDirectory().isAChildOf (potentialParent);
  5980. }
  5981. }
  5982. bool File::isAbsolutePath (const String& path)
  5983. {
  5984. return path.startsWithChar ('/') || path.startsWithChar ('\\')
  5985. #if JUCE_WINDOWS
  5986. || (path.isNotEmpty() && path[1] == ':');
  5987. #else
  5988. || path.startsWithChar ('~');
  5989. #endif
  5990. }
  5991. const File File::getChildFile (String relativePath) const
  5992. {
  5993. if (isAbsolutePath (relativePath))
  5994. {
  5995. // the path is really absolute..
  5996. return File (relativePath);
  5997. }
  5998. else
  5999. {
  6000. // it's relative, so remove any ../ or ./ bits at the start.
  6001. String path (fullPath);
  6002. if (relativePath[0] == '.')
  6003. {
  6004. #if JUCE_WINDOWS
  6005. relativePath = relativePath.replaceCharacter ('/', '\\').trimStart();
  6006. #else
  6007. relativePath = relativePath.replaceCharacter ('\\', '/').trimStart();
  6008. #endif
  6009. while (relativePath[0] == '.')
  6010. {
  6011. if (relativePath[1] == '.')
  6012. {
  6013. if (relativePath [2] == 0 || relativePath[2] == separator)
  6014. {
  6015. const int lastSlash = path.lastIndexOfChar (separator);
  6016. if (lastSlash >= 0)
  6017. path = path.substring (0, lastSlash);
  6018. relativePath = relativePath.substring (3);
  6019. }
  6020. else
  6021. {
  6022. break;
  6023. }
  6024. }
  6025. else if (relativePath[1] == separator)
  6026. {
  6027. relativePath = relativePath.substring (2);
  6028. }
  6029. else
  6030. {
  6031. break;
  6032. }
  6033. }
  6034. }
  6035. return File (addTrailingSeparator (path) + relativePath);
  6036. }
  6037. }
  6038. const File File::getSiblingFile (const String& fileName) const
  6039. {
  6040. return getParentDirectory().getChildFile (fileName);
  6041. }
  6042. const String File::descriptionOfSizeInBytes (const int64 bytes)
  6043. {
  6044. if (bytes == 1)
  6045. {
  6046. return "1 byte";
  6047. }
  6048. else if (bytes < 1024)
  6049. {
  6050. return String ((int) bytes) + " bytes";
  6051. }
  6052. else if (bytes < 1024 * 1024)
  6053. {
  6054. return String (bytes / 1024.0, 1) + " KB";
  6055. }
  6056. else if (bytes < 1024 * 1024 * 1024)
  6057. {
  6058. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  6059. }
  6060. else
  6061. {
  6062. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  6063. }
  6064. }
  6065. bool File::create() const
  6066. {
  6067. if (exists())
  6068. return true;
  6069. {
  6070. const File parentDir (getParentDirectory());
  6071. if (parentDir == *this || ! parentDir.createDirectory())
  6072. return false;
  6073. FileOutputStream fo (*this, 8);
  6074. }
  6075. return exists();
  6076. }
  6077. bool File::createDirectory() const
  6078. {
  6079. if (! isDirectory())
  6080. {
  6081. const File parentDir (getParentDirectory());
  6082. if (parentDir == *this || ! parentDir.createDirectory())
  6083. return false;
  6084. createDirectoryInternal (fullPath.trimCharactersAtEnd (separatorString));
  6085. return isDirectory();
  6086. }
  6087. return true;
  6088. }
  6089. const Time File::getCreationTime() const
  6090. {
  6091. int64 m, a, c;
  6092. getFileTimesInternal (m, a, c);
  6093. return Time (c);
  6094. }
  6095. const Time File::getLastModificationTime() const
  6096. {
  6097. int64 m, a, c;
  6098. getFileTimesInternal (m, a, c);
  6099. return Time (m);
  6100. }
  6101. const Time File::getLastAccessTime() const
  6102. {
  6103. int64 m, a, c;
  6104. getFileTimesInternal (m, a, c);
  6105. return Time (a);
  6106. }
  6107. bool File::setLastModificationTime (const Time& t) const { return setFileTimesInternal (t.toMilliseconds(), 0, 0); }
  6108. bool File::setLastAccessTime (const Time& t) const { return setFileTimesInternal (0, t.toMilliseconds(), 0); }
  6109. bool File::setCreationTime (const Time& t) const { return setFileTimesInternal (0, 0, t.toMilliseconds()); }
  6110. bool File::loadFileAsData (MemoryBlock& destBlock) const
  6111. {
  6112. if (! existsAsFile())
  6113. return false;
  6114. FileInputStream in (*this);
  6115. return getSize() == in.readIntoMemoryBlock (destBlock);
  6116. }
  6117. const String File::loadFileAsString() const
  6118. {
  6119. if (! existsAsFile())
  6120. return String::empty;
  6121. FileInputStream in (*this);
  6122. return in.readEntireStreamAsString();
  6123. }
  6124. int File::findChildFiles (Array<File>& results,
  6125. const int whatToLookFor,
  6126. const bool searchRecursively,
  6127. const String& wildCardPattern) const
  6128. {
  6129. DirectoryIterator di (*this, searchRecursively, wildCardPattern, whatToLookFor);
  6130. int total = 0;
  6131. while (di.next())
  6132. {
  6133. results.add (di.getFile());
  6134. ++total;
  6135. }
  6136. return total;
  6137. }
  6138. int File::getNumberOfChildFiles (const int whatToLookFor, const String& wildCardPattern) const
  6139. {
  6140. DirectoryIterator di (*this, false, wildCardPattern, whatToLookFor);
  6141. int total = 0;
  6142. while (di.next())
  6143. ++total;
  6144. return total;
  6145. }
  6146. bool File::containsSubDirectories() const
  6147. {
  6148. if (isDirectory())
  6149. {
  6150. DirectoryIterator di (*this, false, "*", findDirectories);
  6151. return di.next();
  6152. }
  6153. return false;
  6154. }
  6155. const File File::getNonexistentChildFile (const String& prefix_,
  6156. const String& suffix,
  6157. bool putNumbersInBrackets) const
  6158. {
  6159. File f (getChildFile (prefix_ + suffix));
  6160. if (f.exists())
  6161. {
  6162. int num = 2;
  6163. String prefix (prefix_);
  6164. // remove any bracketed numbers that may already be on the end..
  6165. if (prefix.trim().endsWithChar (')'))
  6166. {
  6167. putNumbersInBrackets = true;
  6168. const int openBracks = prefix.lastIndexOfChar ('(');
  6169. const int closeBracks = prefix.lastIndexOfChar (')');
  6170. if (openBracks > 0
  6171. && closeBracks > openBracks
  6172. && prefix.substring (openBracks + 1, closeBracks).containsOnly ("0123456789"))
  6173. {
  6174. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  6175. prefix = prefix.substring (0, openBracks);
  6176. }
  6177. }
  6178. // also use brackets if it ends in a digit.
  6179. putNumbersInBrackets = putNumbersInBrackets
  6180. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  6181. do
  6182. {
  6183. if (putNumbersInBrackets)
  6184. f = getChildFile (prefix + '(' + String (num++) + ')' + suffix);
  6185. else
  6186. f = getChildFile (prefix + String (num++) + suffix);
  6187. } while (f.exists());
  6188. }
  6189. return f;
  6190. }
  6191. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const
  6192. {
  6193. if (exists())
  6194. {
  6195. return getParentDirectory()
  6196. .getNonexistentChildFile (getFileNameWithoutExtension(),
  6197. getFileExtension(),
  6198. putNumbersInBrackets);
  6199. }
  6200. else
  6201. {
  6202. return *this;
  6203. }
  6204. }
  6205. const String File::getFileExtension() const
  6206. {
  6207. String ext;
  6208. if (! isDirectory())
  6209. {
  6210. const int indexOfDot = fullPath.lastIndexOfChar ('.');
  6211. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  6212. ext = fullPath.substring (indexOfDot);
  6213. }
  6214. return ext;
  6215. }
  6216. bool File::hasFileExtension (const String& possibleSuffix) const
  6217. {
  6218. if (possibleSuffix.isEmpty())
  6219. return fullPath.lastIndexOfChar ('.') <= fullPath.lastIndexOfChar (separator);
  6220. const int semicolon = possibleSuffix.indexOfChar (0, ';');
  6221. if (semicolon >= 0)
  6222. {
  6223. return hasFileExtension (possibleSuffix.substring (0, semicolon).trimEnd())
  6224. || hasFileExtension (possibleSuffix.substring (semicolon + 1).trimStart());
  6225. }
  6226. else
  6227. {
  6228. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  6229. {
  6230. if (possibleSuffix.startsWithChar ('.'))
  6231. return true;
  6232. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  6233. if (dotPos >= 0)
  6234. return fullPath [dotPos] == '.';
  6235. }
  6236. }
  6237. return false;
  6238. }
  6239. const File File::withFileExtension (const String& newExtension) const
  6240. {
  6241. if (fullPath.isEmpty())
  6242. return File::nonexistent;
  6243. String filePart (getFileName());
  6244. int i = filePart.lastIndexOfChar ('.');
  6245. if (i >= 0)
  6246. filePart = filePart.substring (0, i);
  6247. if (newExtension.isNotEmpty() && ! newExtension.startsWithChar ('.'))
  6248. filePart << '.';
  6249. return getSiblingFile (filePart + newExtension);
  6250. }
  6251. bool File::startAsProcess (const String& parameters) const
  6252. {
  6253. return exists() && PlatformUtilities::openDocument (fullPath, parameters);
  6254. }
  6255. FileInputStream* File::createInputStream() const
  6256. {
  6257. if (existsAsFile())
  6258. return new FileInputStream (*this);
  6259. return 0;
  6260. }
  6261. FileOutputStream* File::createOutputStream (const int bufferSize) const
  6262. {
  6263. ScopedPointer <FileOutputStream> out (new FileOutputStream (*this, bufferSize));
  6264. if (out->failedToOpen())
  6265. return 0;
  6266. return out.release();
  6267. }
  6268. bool File::appendData (const void* const dataToAppend,
  6269. const int numberOfBytes) const
  6270. {
  6271. if (numberOfBytes > 0)
  6272. {
  6273. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6274. if (out == 0)
  6275. return false;
  6276. out->write (dataToAppend, numberOfBytes);
  6277. }
  6278. return true;
  6279. }
  6280. bool File::replaceWithData (const void* const dataToWrite,
  6281. const int numberOfBytes) const
  6282. {
  6283. jassert (numberOfBytes >= 0); // a negative number of bytes??
  6284. if (numberOfBytes <= 0)
  6285. return deleteFile();
  6286. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6287. tempFile.getFile().appendData (dataToWrite, numberOfBytes);
  6288. return tempFile.overwriteTargetFileWithTemporary();
  6289. }
  6290. bool File::appendText (const String& text,
  6291. const bool asUnicode,
  6292. const bool writeUnicodeHeaderBytes) const
  6293. {
  6294. const ScopedPointer <FileOutputStream> out (createOutputStream());
  6295. if (out != 0)
  6296. {
  6297. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  6298. return true;
  6299. }
  6300. return false;
  6301. }
  6302. bool File::replaceWithText (const String& textToWrite,
  6303. const bool asUnicode,
  6304. const bool writeUnicodeHeaderBytes) const
  6305. {
  6306. TemporaryFile tempFile (*this, TemporaryFile::useHiddenFile);
  6307. tempFile.getFile().appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes);
  6308. return tempFile.overwriteTargetFileWithTemporary();
  6309. }
  6310. bool File::hasIdenticalContentTo (const File& other) const
  6311. {
  6312. if (other == *this)
  6313. return true;
  6314. if (getSize() == other.getSize() && existsAsFile() && other.existsAsFile())
  6315. {
  6316. FileInputStream in1 (*this), in2 (other);
  6317. const int bufferSize = 4096;
  6318. HeapBlock <char> buffer1, buffer2;
  6319. buffer1.malloc (bufferSize);
  6320. buffer2.malloc (bufferSize);
  6321. for (;;)
  6322. {
  6323. const int num1 = in1.read (buffer1, bufferSize);
  6324. const int num2 = in2.read (buffer2, bufferSize);
  6325. if (num1 != num2)
  6326. break;
  6327. if (num1 <= 0)
  6328. return true;
  6329. if (memcmp (buffer1, buffer2, num1) != 0)
  6330. break;
  6331. }
  6332. }
  6333. return false;
  6334. }
  6335. const String File::createLegalPathName (const String& original)
  6336. {
  6337. String s (original);
  6338. String start;
  6339. if (s[1] == ':')
  6340. {
  6341. start = s.substring (0, 2);
  6342. s = s.substring (2);
  6343. }
  6344. return start + s.removeCharacters ("\"#@,;:<>*^|?")
  6345. .substring (0, 1024);
  6346. }
  6347. const String File::createLegalFileName (const String& original)
  6348. {
  6349. String s (original.removeCharacters ("\"#@,;:<>*^|?\\/"));
  6350. const int maxLength = 128; // only the length of the filename, not the whole path
  6351. const int len = s.length();
  6352. if (len > maxLength)
  6353. {
  6354. const int lastDot = s.lastIndexOfChar ('.');
  6355. if (lastDot > jmax (0, len - 12))
  6356. {
  6357. s = s.substring (0, maxLength - (len - lastDot))
  6358. + s.substring (lastDot);
  6359. }
  6360. else
  6361. {
  6362. s = s.substring (0, maxLength);
  6363. }
  6364. }
  6365. return s;
  6366. }
  6367. const String File::getRelativePathFrom (const File& dir) const
  6368. {
  6369. String thisPath (fullPath);
  6370. {
  6371. int len = thisPath.length();
  6372. while (--len >= 0 && thisPath [len] == File::separator)
  6373. thisPath [len] = 0;
  6374. }
  6375. String dirPath (addTrailingSeparator (dir.existsAsFile() ? dir.getParentDirectory().getFullPathName()
  6376. : dir.fullPath));
  6377. const int len = jmin (thisPath.length(), dirPath.length());
  6378. int commonBitLength = 0;
  6379. for (int i = 0; i < len; ++i)
  6380. {
  6381. #if NAMES_ARE_CASE_SENSITIVE
  6382. if (thisPath[i] != dirPath[i])
  6383. #else
  6384. if (CharacterFunctions::toLowerCase (thisPath[i])
  6385. != CharacterFunctions::toLowerCase (dirPath[i]))
  6386. #endif
  6387. {
  6388. break;
  6389. }
  6390. ++commonBitLength;
  6391. }
  6392. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  6393. --commonBitLength;
  6394. // if the only common bit is the root, then just return the full path..
  6395. if (commonBitLength <= 0
  6396. || (commonBitLength == 1 && thisPath [1] == File::separator))
  6397. return fullPath;
  6398. thisPath = thisPath.substring (commonBitLength);
  6399. dirPath = dirPath.substring (commonBitLength);
  6400. while (dirPath.isNotEmpty())
  6401. {
  6402. #if JUCE_WINDOWS
  6403. thisPath = "..\\" + thisPath;
  6404. #else
  6405. thisPath = "../" + thisPath;
  6406. #endif
  6407. const int sep = dirPath.indexOfChar (separator);
  6408. if (sep >= 0)
  6409. dirPath = dirPath.substring (sep + 1);
  6410. else
  6411. dirPath = String::empty;
  6412. }
  6413. return thisPath;
  6414. }
  6415. const File File::createTempFile (const String& fileNameEnding)
  6416. {
  6417. const File tempFile (getSpecialLocation (tempDirectory)
  6418. .getChildFile ("temp_" + String (Random::getSystemRandom().nextInt()))
  6419. .withFileExtension (fileNameEnding));
  6420. if (tempFile.exists())
  6421. return createTempFile (fileNameEnding);
  6422. else
  6423. return tempFile;
  6424. }
  6425. #if JUCE_UNIT_TESTS
  6426. class FileTests : public UnitTest
  6427. {
  6428. public:
  6429. FileTests() : UnitTest ("Files") {}
  6430. void runTest()
  6431. {
  6432. beginTest ("Reading");
  6433. const File home (File::getSpecialLocation (File::userHomeDirectory));
  6434. const File temp (File::getSpecialLocation (File::tempDirectory));
  6435. expect (! File::nonexistent.exists());
  6436. expect (home.isDirectory());
  6437. expect (home.exists());
  6438. expect (! home.existsAsFile());
  6439. expect (File::getSpecialLocation (File::userDocumentsDirectory).isDirectory());
  6440. expect (File::getSpecialLocation (File::userApplicationDataDirectory).isDirectory());
  6441. expect (File::getSpecialLocation (File::currentExecutableFile).exists());
  6442. expect (File::getSpecialLocation (File::currentApplicationFile).exists());
  6443. expect (File::getSpecialLocation (File::invokedExecutableFile).exists());
  6444. expect (home.getVolumeTotalSize() > 1024 * 1024);
  6445. expect (home.getBytesFreeOnVolume() > 0);
  6446. expect (! home.isHidden());
  6447. expect (home.isOnHardDisk());
  6448. expect (! home.isOnCDRomDrive());
  6449. expect (File::getCurrentWorkingDirectory().exists());
  6450. expect (home.setAsCurrentWorkingDirectory());
  6451. expect (File::getCurrentWorkingDirectory() == home);
  6452. {
  6453. Array<File> roots;
  6454. File::findFileSystemRoots (roots);
  6455. expect (roots.size() > 0);
  6456. int numRootsExisting = 0;
  6457. for (int i = 0; i < roots.size(); ++i)
  6458. if (roots[i].exists())
  6459. ++numRootsExisting;
  6460. // (on windows, some of the drives may not contain media, so as long as at least one is ok..)
  6461. expect (numRootsExisting > 0);
  6462. }
  6463. beginTest ("Writing");
  6464. File demoFolder (temp.getChildFile ("Juce UnitTests Temp Folder.folder"));
  6465. expect (demoFolder.deleteRecursively());
  6466. expect (demoFolder.createDirectory());
  6467. expect (demoFolder.isDirectory());
  6468. expect (demoFolder.getParentDirectory() == temp);
  6469. expect (temp.isDirectory());
  6470. {
  6471. Array<File> files;
  6472. temp.findChildFiles (files, File::findFilesAndDirectories, false, "*");
  6473. expect (files.contains (demoFolder));
  6474. }
  6475. {
  6476. Array<File> files;
  6477. temp.findChildFiles (files, File::findDirectories, true, "*.folder");
  6478. expect (files.contains (demoFolder));
  6479. }
  6480. File tempFile (demoFolder.getNonexistentChildFile ("test", ".txt", false));
  6481. expect (tempFile.getFileExtension() == ".txt");
  6482. expect (tempFile.hasFileExtension (".txt"));
  6483. expect (tempFile.hasFileExtension ("txt"));
  6484. expect (tempFile.withFileExtension ("xyz").hasFileExtension (".xyz"));
  6485. expect (tempFile.getSiblingFile ("foo").isAChildOf (temp));
  6486. expect (tempFile.hasWriteAccess());
  6487. {
  6488. FileOutputStream fo (tempFile);
  6489. fo.write ("0123456789", 10);
  6490. }
  6491. expect (tempFile.exists());
  6492. expect (tempFile.getSize() == 10);
  6493. expect (std::abs ((int) (tempFile.getLastModificationTime().toMilliseconds() - Time::getCurrentTime().toMilliseconds())) < 3000);
  6494. expect (tempFile.loadFileAsString() == "0123456789");
  6495. expect (! demoFolder.containsSubDirectories());
  6496. expect (demoFolder.getNumberOfChildFiles (File::findFiles) == 1);
  6497. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 1);
  6498. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 0);
  6499. demoFolder.getNonexistentChildFile ("tempFolder", "", false).createDirectory();
  6500. expect (demoFolder.getNumberOfChildFiles (File::findDirectories) == 1);
  6501. expect (demoFolder.getNumberOfChildFiles (File::findFilesAndDirectories) == 2);
  6502. expect (demoFolder.containsSubDirectories());
  6503. expect (tempFile.hasWriteAccess());
  6504. tempFile.setReadOnly (true);
  6505. expect (! tempFile.hasWriteAccess());
  6506. tempFile.setReadOnly (false);
  6507. expect (tempFile.hasWriteAccess());
  6508. Time t (Time::getCurrentTime());
  6509. tempFile.setLastModificationTime (t);
  6510. Time t2 = tempFile.getLastModificationTime();
  6511. expect (std::abs ((int) (t2.toMilliseconds() - t.toMilliseconds())) <= 1000);
  6512. {
  6513. MemoryBlock mb;
  6514. tempFile.loadFileAsData (mb);
  6515. expect (mb.getSize() == 10);
  6516. expect (mb[0] == '0');
  6517. }
  6518. expect (tempFile.appendData ("abcdefghij", 10));
  6519. expect (tempFile.getSize() == 20);
  6520. expect (tempFile.replaceWithData ("abcdefghij", 10));
  6521. expect (tempFile.getSize() == 10);
  6522. File tempFile2 (tempFile.getNonexistentSibling (false));
  6523. expect (tempFile.copyFileTo (tempFile2));
  6524. expect (tempFile2.exists());
  6525. expect (tempFile2.hasIdenticalContentTo (tempFile));
  6526. expect (tempFile.deleteFile());
  6527. expect (! tempFile.exists());
  6528. expect (tempFile2.moveFileTo (tempFile));
  6529. expect (tempFile.exists());
  6530. expect (! tempFile2.exists());
  6531. expect (demoFolder.deleteRecursively());
  6532. expect (! demoFolder.exists());
  6533. }
  6534. };
  6535. static FileTests fileUnitTests;
  6536. #endif
  6537. END_JUCE_NAMESPACE
  6538. /*** End of inlined file: juce_File.cpp ***/
  6539. /*** Start of inlined file: juce_FileInputStream.cpp ***/
  6540. BEGIN_JUCE_NAMESPACE
  6541. int64 juce_fileSetPosition (void* handle, int64 pos);
  6542. FileInputStream::FileInputStream (const File& f)
  6543. : file (f),
  6544. fileHandle (0),
  6545. currentPosition (0),
  6546. totalSize (0),
  6547. needToSeek (true)
  6548. {
  6549. openHandle();
  6550. }
  6551. FileInputStream::~FileInputStream()
  6552. {
  6553. closeHandle();
  6554. }
  6555. int64 FileInputStream::getTotalLength()
  6556. {
  6557. return totalSize;
  6558. }
  6559. int FileInputStream::read (void* buffer, int bytesToRead)
  6560. {
  6561. int num = 0;
  6562. if (needToSeek)
  6563. {
  6564. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  6565. return 0;
  6566. needToSeek = false;
  6567. }
  6568. num = readInternal (buffer, bytesToRead);
  6569. currentPosition += num;
  6570. return num;
  6571. }
  6572. bool FileInputStream::isExhausted()
  6573. {
  6574. return currentPosition >= totalSize;
  6575. }
  6576. int64 FileInputStream::getPosition()
  6577. {
  6578. return currentPosition;
  6579. }
  6580. bool FileInputStream::setPosition (int64 pos)
  6581. {
  6582. pos = jlimit ((int64) 0, totalSize, pos);
  6583. needToSeek |= (currentPosition != pos);
  6584. currentPosition = pos;
  6585. return true;
  6586. }
  6587. END_JUCE_NAMESPACE
  6588. /*** End of inlined file: juce_FileInputStream.cpp ***/
  6589. /*** Start of inlined file: juce_FileOutputStream.cpp ***/
  6590. BEGIN_JUCE_NAMESPACE
  6591. int64 juce_fileSetPosition (void* handle, int64 pos);
  6592. FileOutputStream::FileOutputStream (const File& f, const int bufferSize_)
  6593. : file (f),
  6594. fileHandle (0),
  6595. currentPosition (0),
  6596. bufferSize (bufferSize_),
  6597. bytesInBuffer (0),
  6598. buffer (jmax (bufferSize_, 16))
  6599. {
  6600. openHandle();
  6601. }
  6602. FileOutputStream::~FileOutputStream()
  6603. {
  6604. flush();
  6605. closeHandle();
  6606. }
  6607. int64 FileOutputStream::getPosition()
  6608. {
  6609. return currentPosition;
  6610. }
  6611. bool FileOutputStream::setPosition (int64 newPosition)
  6612. {
  6613. if (newPosition != currentPosition)
  6614. {
  6615. flush();
  6616. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  6617. }
  6618. return newPosition == currentPosition;
  6619. }
  6620. void FileOutputStream::flush()
  6621. {
  6622. if (bytesInBuffer > 0)
  6623. {
  6624. writeInternal (buffer, bytesInBuffer);
  6625. bytesInBuffer = 0;
  6626. }
  6627. flushInternal();
  6628. }
  6629. bool FileOutputStream::write (const void* const src, const int numBytes)
  6630. {
  6631. if (bytesInBuffer + numBytes < bufferSize)
  6632. {
  6633. memcpy (buffer + bytesInBuffer, src, numBytes);
  6634. bytesInBuffer += numBytes;
  6635. currentPosition += numBytes;
  6636. }
  6637. else
  6638. {
  6639. if (bytesInBuffer > 0)
  6640. {
  6641. // flush the reservoir
  6642. const bool wroteOk = (writeInternal (buffer, bytesInBuffer) == bytesInBuffer);
  6643. bytesInBuffer = 0;
  6644. if (! wroteOk)
  6645. return false;
  6646. }
  6647. if (numBytes < bufferSize)
  6648. {
  6649. memcpy (buffer + bytesInBuffer, src, numBytes);
  6650. bytesInBuffer += numBytes;
  6651. currentPosition += numBytes;
  6652. }
  6653. else
  6654. {
  6655. const int bytesWritten = writeInternal (src, numBytes);
  6656. if (bytesWritten < 0)
  6657. return false;
  6658. currentPosition += bytesWritten;
  6659. return bytesWritten == numBytes;
  6660. }
  6661. }
  6662. return true;
  6663. }
  6664. END_JUCE_NAMESPACE
  6665. /*** End of inlined file: juce_FileOutputStream.cpp ***/
  6666. /*** Start of inlined file: juce_FileSearchPath.cpp ***/
  6667. BEGIN_JUCE_NAMESPACE
  6668. FileSearchPath::FileSearchPath()
  6669. {
  6670. }
  6671. FileSearchPath::FileSearchPath (const String& path)
  6672. {
  6673. init (path);
  6674. }
  6675. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  6676. : directories (other.directories)
  6677. {
  6678. }
  6679. FileSearchPath::~FileSearchPath()
  6680. {
  6681. }
  6682. FileSearchPath& FileSearchPath::operator= (const String& path)
  6683. {
  6684. init (path);
  6685. return *this;
  6686. }
  6687. void FileSearchPath::init (const String& path)
  6688. {
  6689. directories.clear();
  6690. directories.addTokens (path, ";", "\"");
  6691. directories.trim();
  6692. directories.removeEmptyStrings();
  6693. for (int i = directories.size(); --i >= 0;)
  6694. directories.set (i, directories[i].unquoted());
  6695. }
  6696. int FileSearchPath::getNumPaths() const
  6697. {
  6698. return directories.size();
  6699. }
  6700. const File FileSearchPath::operator[] (const int index) const
  6701. {
  6702. return File (directories [index]);
  6703. }
  6704. const String FileSearchPath::toString() const
  6705. {
  6706. StringArray directories2 (directories);
  6707. for (int i = directories2.size(); --i >= 0;)
  6708. if (directories2[i].containsChar (';'))
  6709. directories2.set (i, directories2[i].quoted());
  6710. return directories2.joinIntoString (";");
  6711. }
  6712. void FileSearchPath::add (const File& dir, const int insertIndex)
  6713. {
  6714. directories.insert (insertIndex, dir.getFullPathName());
  6715. }
  6716. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  6717. {
  6718. for (int i = 0; i < directories.size(); ++i)
  6719. if (File (directories[i]) == dir)
  6720. return;
  6721. add (dir);
  6722. }
  6723. void FileSearchPath::remove (const int index)
  6724. {
  6725. directories.remove (index);
  6726. }
  6727. void FileSearchPath::addPath (const FileSearchPath& other)
  6728. {
  6729. for (int i = 0; i < other.getNumPaths(); ++i)
  6730. addIfNotAlreadyThere (other[i]);
  6731. }
  6732. void FileSearchPath::removeRedundantPaths()
  6733. {
  6734. for (int i = directories.size(); --i >= 0;)
  6735. {
  6736. const File d1 (directories[i]);
  6737. for (int j = directories.size(); --j >= 0;)
  6738. {
  6739. const File d2 (directories[j]);
  6740. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  6741. {
  6742. directories.remove (i);
  6743. break;
  6744. }
  6745. }
  6746. }
  6747. }
  6748. void FileSearchPath::removeNonExistentPaths()
  6749. {
  6750. for (int i = directories.size(); --i >= 0;)
  6751. if (! File (directories[i]).isDirectory())
  6752. directories.remove (i);
  6753. }
  6754. int FileSearchPath::findChildFiles (Array<File>& results,
  6755. const int whatToLookFor,
  6756. const bool searchRecursively,
  6757. const String& wildCardPattern) const
  6758. {
  6759. int total = 0;
  6760. for (int i = 0; i < directories.size(); ++i)
  6761. total += operator[] (i).findChildFiles (results,
  6762. whatToLookFor,
  6763. searchRecursively,
  6764. wildCardPattern);
  6765. return total;
  6766. }
  6767. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  6768. const bool checkRecursively) const
  6769. {
  6770. for (int i = directories.size(); --i >= 0;)
  6771. {
  6772. const File d (directories[i]);
  6773. if (checkRecursively)
  6774. {
  6775. if (fileToCheck.isAChildOf (d))
  6776. return true;
  6777. }
  6778. else
  6779. {
  6780. if (fileToCheck.getParentDirectory() == d)
  6781. return true;
  6782. }
  6783. }
  6784. return false;
  6785. }
  6786. END_JUCE_NAMESPACE
  6787. /*** End of inlined file: juce_FileSearchPath.cpp ***/
  6788. /*** Start of inlined file: juce_NamedPipe.cpp ***/
  6789. BEGIN_JUCE_NAMESPACE
  6790. NamedPipe::NamedPipe()
  6791. : internal (0)
  6792. {
  6793. }
  6794. NamedPipe::~NamedPipe()
  6795. {
  6796. close();
  6797. }
  6798. bool NamedPipe::openExisting (const String& pipeName)
  6799. {
  6800. currentPipeName = pipeName;
  6801. return openInternal (pipeName, false);
  6802. }
  6803. bool NamedPipe::createNewPipe (const String& pipeName)
  6804. {
  6805. currentPipeName = pipeName;
  6806. return openInternal (pipeName, true);
  6807. }
  6808. bool NamedPipe::isOpen() const
  6809. {
  6810. return internal != 0;
  6811. }
  6812. const String NamedPipe::getName() const
  6813. {
  6814. return currentPipeName;
  6815. }
  6816. // other methods for this class are implemented in the platform-specific files
  6817. END_JUCE_NAMESPACE
  6818. /*** End of inlined file: juce_NamedPipe.cpp ***/
  6819. /*** Start of inlined file: juce_TemporaryFile.cpp ***/
  6820. BEGIN_JUCE_NAMESPACE
  6821. TemporaryFile::TemporaryFile (const String& suffix, const int optionFlags)
  6822. {
  6823. createTempFile (File::getSpecialLocation (File::tempDirectory),
  6824. "temp_" + String (Random::getSystemRandom().nextInt()),
  6825. suffix,
  6826. optionFlags);
  6827. }
  6828. TemporaryFile::TemporaryFile (const File& targetFile_, const int optionFlags)
  6829. : targetFile (targetFile_)
  6830. {
  6831. // If you use this constructor, you need to give it a valid target file!
  6832. jassert (targetFile != File::nonexistent);
  6833. createTempFile (targetFile.getParentDirectory(),
  6834. targetFile.getFileNameWithoutExtension() + "_temp" + String (Random::getSystemRandom().nextInt()),
  6835. targetFile.getFileExtension(),
  6836. optionFlags);
  6837. }
  6838. void TemporaryFile::createTempFile (const File& parentDirectory, String name,
  6839. const String& suffix, const int optionFlags)
  6840. {
  6841. if ((optionFlags & useHiddenFile) != 0)
  6842. name = "." + name;
  6843. temporaryFile = parentDirectory.getNonexistentChildFile (name, suffix, (optionFlags & putNumbersInBrackets) != 0);
  6844. }
  6845. TemporaryFile::~TemporaryFile()
  6846. {
  6847. if (! deleteTemporaryFile())
  6848. {
  6849. /* Failed to delete our temporary file! The most likely reason for this would be
  6850. that you've not closed an output stream that was being used to write to file.
  6851. If you find that something beyond your control is changing permissions on
  6852. your temporary files and preventing them from being deleted, you may want to
  6853. call TemporaryFile::deleteTemporaryFile() to detect those error cases and
  6854. handle them appropriately.
  6855. */
  6856. jassertfalse;
  6857. }
  6858. }
  6859. bool TemporaryFile::overwriteTargetFileWithTemporary() const
  6860. {
  6861. // This method only works if you created this object with the constructor
  6862. // that takes a target file!
  6863. jassert (targetFile != File::nonexistent);
  6864. if (temporaryFile.exists())
  6865. {
  6866. // Have a few attempts at overwriting the file before giving up..
  6867. for (int i = 5; --i >= 0;)
  6868. {
  6869. if (temporaryFile.moveFileTo (targetFile))
  6870. return true;
  6871. Thread::sleep (100);
  6872. }
  6873. }
  6874. else
  6875. {
  6876. // There's no temporary file to use. If your write failed, you should
  6877. // probably check, and not bother calling this method.
  6878. jassertfalse;
  6879. }
  6880. return false;
  6881. }
  6882. bool TemporaryFile::deleteTemporaryFile() const
  6883. {
  6884. // Have a few attempts at deleting the file before giving up..
  6885. for (int i = 5; --i >= 0;)
  6886. {
  6887. if (temporaryFile.deleteFile())
  6888. return true;
  6889. Thread::sleep (50);
  6890. }
  6891. return false;
  6892. }
  6893. END_JUCE_NAMESPACE
  6894. /*** End of inlined file: juce_TemporaryFile.cpp ***/
  6895. /*** Start of inlined file: juce_Socket.cpp ***/
  6896. #if JUCE_WINDOWS
  6897. #include <winsock2.h>
  6898. #if JUCE_MSVC
  6899. #pragma warning (push)
  6900. #pragma warning (disable : 4127 4389 4018)
  6901. #endif
  6902. #else
  6903. #if JUCE_LINUX
  6904. #include <sys/types.h>
  6905. #include <sys/socket.h>
  6906. #include <sys/errno.h>
  6907. #include <unistd.h>
  6908. #include <netinet/in.h>
  6909. #elif (MACOSX_DEPLOYMENT_TARGET <= MAC_OS_X_VERSION_10_4) && ! JUCE_IOS
  6910. #include <CoreServices/CoreServices.h>
  6911. #endif
  6912. #include <fcntl.h>
  6913. #include <netdb.h>
  6914. #include <arpa/inet.h>
  6915. #include <netinet/tcp.h>
  6916. #endif
  6917. BEGIN_JUCE_NAMESPACE
  6918. #if defined (JUCE_LINUX) || defined (JUCE_MAC) || defined (JUCE_IOS)
  6919. typedef socklen_t juce_socklen_t;
  6920. #else
  6921. typedef int juce_socklen_t;
  6922. #endif
  6923. #if JUCE_WINDOWS
  6924. namespace SocketHelpers
  6925. {
  6926. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  6927. static juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  6928. 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. }
  6941. void juce_shutdownWin32Sockets()
  6942. {
  6943. if (SocketHelpers::juce_CloseWin32SocketLib != 0)
  6944. (*SocketHelpers::juce_CloseWin32SocketLib)();
  6945. }
  6946. #endif
  6947. namespace SocketHelpers
  6948. {
  6949. static bool resetSocketOptions (const int handle, const bool isDatagram, const bool allowBroadcast) throw()
  6950. {
  6951. const int sndBufSize = 65536;
  6952. const int rcvBufSize = 65536;
  6953. const int one = 1;
  6954. return handle > 0
  6955. && setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (rcvBufSize)) == 0
  6956. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (sndBufSize)) == 0
  6957. && (isDatagram ? ((! allowBroadcast) || setsockopt (handle, SOL_SOCKET, SO_BROADCAST, (const char*) &one, sizeof (one)) == 0)
  6958. : (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (one)) == 0));
  6959. }
  6960. static bool bindSocketToPort (const int handle, const int port) throw()
  6961. {
  6962. if (handle <= 0 || port <= 0)
  6963. return false;
  6964. struct sockaddr_in servTmpAddr;
  6965. zerostruct (servTmpAddr);
  6966. servTmpAddr.sin_family = PF_INET;
  6967. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  6968. servTmpAddr.sin_port = htons ((uint16) port);
  6969. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  6970. }
  6971. static int readSocket (const int handle,
  6972. void* const destBuffer, const int maxBytesToRead,
  6973. bool volatile& connected,
  6974. const bool blockUntilSpecifiedAmountHasArrived) throw()
  6975. {
  6976. int bytesRead = 0;
  6977. while (bytesRead < maxBytesToRead)
  6978. {
  6979. int bytesThisTime;
  6980. #if JUCE_WINDOWS
  6981. bytesThisTime = recv (handle, static_cast<char*> (destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  6982. #else
  6983. while ((bytesThisTime = (int) ::read (handle, addBytesToPointer (destBuffer, bytesRead), maxBytesToRead - bytesRead)) < 0
  6984. && errno == EINTR
  6985. && connected)
  6986. {
  6987. }
  6988. #endif
  6989. if (bytesThisTime <= 0 || ! connected)
  6990. {
  6991. if (bytesRead == 0)
  6992. bytesRead = -1;
  6993. break;
  6994. }
  6995. bytesRead += bytesThisTime;
  6996. if (! blockUntilSpecifiedAmountHasArrived)
  6997. break;
  6998. }
  6999. return bytesRead;
  7000. }
  7001. static int waitForReadiness (const int handle, const bool forReading,
  7002. const int timeoutMsecs) throw()
  7003. {
  7004. struct timeval timeout;
  7005. struct timeval* timeoutp;
  7006. if (timeoutMsecs >= 0)
  7007. {
  7008. timeout.tv_sec = timeoutMsecs / 1000;
  7009. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  7010. timeoutp = &timeout;
  7011. }
  7012. else
  7013. {
  7014. timeoutp = 0;
  7015. }
  7016. fd_set rset, wset;
  7017. FD_ZERO (&rset);
  7018. FD_SET (handle, &rset);
  7019. FD_ZERO (&wset);
  7020. FD_SET (handle, &wset);
  7021. fd_set* const prset = forReading ? &rset : 0;
  7022. fd_set* const pwset = forReading ? 0 : &wset;
  7023. #if JUCE_WINDOWS
  7024. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  7025. return -1;
  7026. #else
  7027. {
  7028. int result;
  7029. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  7030. && errno == EINTR)
  7031. {
  7032. }
  7033. if (result < 0)
  7034. return -1;
  7035. }
  7036. #endif
  7037. {
  7038. int opt;
  7039. juce_socklen_t len = sizeof (opt);
  7040. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  7041. || opt != 0)
  7042. return -1;
  7043. }
  7044. if ((forReading && FD_ISSET (handle, &rset))
  7045. || ((! forReading) && FD_ISSET (handle, &wset)))
  7046. return 1;
  7047. return 0;
  7048. }
  7049. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  7050. {
  7051. #if JUCE_WINDOWS
  7052. u_long nonBlocking = shouldBlock ? 0 : 1;
  7053. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  7054. return false;
  7055. #else
  7056. int socketFlags = fcntl (handle, F_GETFL, 0);
  7057. if (socketFlags == -1)
  7058. return false;
  7059. if (shouldBlock)
  7060. socketFlags &= ~O_NONBLOCK;
  7061. else
  7062. socketFlags |= O_NONBLOCK;
  7063. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  7064. return false;
  7065. #endif
  7066. return true;
  7067. }
  7068. static bool connectSocket (int volatile& handle,
  7069. const bool isDatagram,
  7070. void** serverAddress,
  7071. const String& hostName,
  7072. const int portNumber,
  7073. const int timeOutMillisecs) throw()
  7074. {
  7075. struct hostent* const hostEnt = gethostbyname (hostName.toUTF8());
  7076. if (hostEnt == 0)
  7077. return false;
  7078. struct in_addr targetAddress;
  7079. memcpy (&targetAddress.s_addr,
  7080. *(hostEnt->h_addr_list),
  7081. sizeof (targetAddress.s_addr));
  7082. struct sockaddr_in servTmpAddr;
  7083. zerostruct (servTmpAddr);
  7084. servTmpAddr.sin_family = PF_INET;
  7085. servTmpAddr.sin_addr = targetAddress;
  7086. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7087. if (handle < 0)
  7088. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  7089. if (handle < 0)
  7090. return false;
  7091. if (isDatagram)
  7092. {
  7093. *serverAddress = new struct sockaddr_in();
  7094. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  7095. return true;
  7096. }
  7097. setSocketBlockingState (handle, false);
  7098. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  7099. if (result < 0)
  7100. {
  7101. #if JUCE_WINDOWS
  7102. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  7103. #else
  7104. if (errno == EINPROGRESS)
  7105. #endif
  7106. {
  7107. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  7108. {
  7109. setSocketBlockingState (handle, true);
  7110. return false;
  7111. }
  7112. }
  7113. }
  7114. setSocketBlockingState (handle, true);
  7115. resetSocketOptions (handle, false, false);
  7116. return true;
  7117. }
  7118. }
  7119. StreamingSocket::StreamingSocket()
  7120. : portNumber (0),
  7121. handle (-1),
  7122. connected (false),
  7123. isListener (false)
  7124. {
  7125. #if JUCE_WINDOWS
  7126. SocketHelpers::initWin32Sockets();
  7127. #endif
  7128. }
  7129. StreamingSocket::StreamingSocket (const String& hostName_,
  7130. const int portNumber_,
  7131. const int handle_)
  7132. : hostName (hostName_),
  7133. portNumber (portNumber_),
  7134. handle (handle_),
  7135. connected (true),
  7136. isListener (false)
  7137. {
  7138. #if JUCE_WINDOWS
  7139. SocketHelpers::initWin32Sockets();
  7140. #endif
  7141. SocketHelpers::resetSocketOptions (handle_, false, false);
  7142. }
  7143. StreamingSocket::~StreamingSocket()
  7144. {
  7145. close();
  7146. }
  7147. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7148. {
  7149. return (connected && ! isListener) ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7150. : -1;
  7151. }
  7152. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7153. {
  7154. if (isListener || ! connected)
  7155. return -1;
  7156. #if JUCE_WINDOWS
  7157. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  7158. #else
  7159. int result;
  7160. while ((result = (int) ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  7161. && errno == EINTR)
  7162. {
  7163. }
  7164. return result;
  7165. #endif
  7166. }
  7167. int StreamingSocket::waitUntilReady (const bool readyForReading,
  7168. const int timeoutMsecs) const
  7169. {
  7170. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7171. : -1;
  7172. }
  7173. bool StreamingSocket::bindToPort (const int port)
  7174. {
  7175. return SocketHelpers::bindSocketToPort (handle, port);
  7176. }
  7177. bool StreamingSocket::connect (const String& remoteHostName,
  7178. const int remotePortNumber,
  7179. const int timeOutMillisecs)
  7180. {
  7181. if (isListener)
  7182. {
  7183. jassertfalse; // a listener socket can't connect to another one!
  7184. return false;
  7185. }
  7186. if (connected)
  7187. close();
  7188. hostName = remoteHostName;
  7189. portNumber = remotePortNumber;
  7190. isListener = false;
  7191. connected = SocketHelpers::connectSocket (handle, false, 0, remoteHostName,
  7192. remotePortNumber, timeOutMillisecs);
  7193. if (! (connected && SocketHelpers::resetSocketOptions (handle, false, false)))
  7194. {
  7195. close();
  7196. return false;
  7197. }
  7198. return true;
  7199. }
  7200. void StreamingSocket::close()
  7201. {
  7202. #if JUCE_WINDOWS
  7203. if (handle != SOCKET_ERROR || connected)
  7204. closesocket (handle);
  7205. connected = false;
  7206. #else
  7207. if (connected)
  7208. {
  7209. connected = false;
  7210. if (isListener)
  7211. {
  7212. // need to do this to interrupt the accept() function..
  7213. StreamingSocket temp;
  7214. temp.connect ("localhost", portNumber, 1000);
  7215. }
  7216. }
  7217. if (handle != -1)
  7218. ::close (handle);
  7219. #endif
  7220. hostName = String::empty;
  7221. portNumber = 0;
  7222. handle = -1;
  7223. isListener = false;
  7224. }
  7225. bool StreamingSocket::createListener (const int newPortNumber, const String& localHostName)
  7226. {
  7227. if (connected)
  7228. close();
  7229. hostName = "listener";
  7230. portNumber = newPortNumber;
  7231. isListener = true;
  7232. struct sockaddr_in servTmpAddr;
  7233. zerostruct (servTmpAddr);
  7234. servTmpAddr.sin_family = PF_INET;
  7235. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  7236. if (localHostName.isNotEmpty())
  7237. servTmpAddr.sin_addr.s_addr = ::inet_addr (localHostName.toUTF8());
  7238. servTmpAddr.sin_port = htons ((uint16) portNumber);
  7239. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  7240. if (handle < 0)
  7241. return false;
  7242. const int reuse = 1;
  7243. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  7244. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  7245. || listen (handle, SOMAXCONN) < 0)
  7246. {
  7247. close();
  7248. return false;
  7249. }
  7250. connected = true;
  7251. return true;
  7252. }
  7253. StreamingSocket* StreamingSocket::waitForNextConnection() const
  7254. {
  7255. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  7256. // prepare this socket as a listener.
  7257. if (connected && isListener)
  7258. {
  7259. struct sockaddr address;
  7260. juce_socklen_t len = sizeof (sockaddr);
  7261. const int newSocket = (int) accept (handle, &address, &len);
  7262. if (newSocket >= 0 && connected)
  7263. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7264. portNumber, newSocket);
  7265. }
  7266. return 0;
  7267. }
  7268. bool StreamingSocket::isLocal() const throw()
  7269. {
  7270. return hostName == "127.0.0.1";
  7271. }
  7272. DatagramSocket::DatagramSocket (const int localPortNumber, const bool allowBroadcast_)
  7273. : portNumber (0),
  7274. handle (-1),
  7275. connected (true),
  7276. allowBroadcast (allowBroadcast_),
  7277. serverAddress (0)
  7278. {
  7279. #if JUCE_WINDOWS
  7280. SocketHelpers::initWin32Sockets();
  7281. #endif
  7282. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  7283. bindToPort (localPortNumber);
  7284. }
  7285. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  7286. const int handle_, const int localPortNumber)
  7287. : hostName (hostName_),
  7288. portNumber (portNumber_),
  7289. handle (handle_),
  7290. connected (true),
  7291. allowBroadcast (false),
  7292. serverAddress (0)
  7293. {
  7294. #if JUCE_WINDOWS
  7295. SocketHelpers::initWin32Sockets();
  7296. #endif
  7297. SocketHelpers::resetSocketOptions (handle_, true, allowBroadcast);
  7298. bindToPort (localPortNumber);
  7299. }
  7300. DatagramSocket::~DatagramSocket()
  7301. {
  7302. close();
  7303. delete static_cast <struct sockaddr_in*> (serverAddress);
  7304. serverAddress = 0;
  7305. }
  7306. void DatagramSocket::close()
  7307. {
  7308. #if JUCE_WINDOWS
  7309. closesocket (handle);
  7310. connected = false;
  7311. #else
  7312. connected = false;
  7313. ::close (handle);
  7314. #endif
  7315. hostName = String::empty;
  7316. portNumber = 0;
  7317. handle = -1;
  7318. }
  7319. bool DatagramSocket::bindToPort (const int port)
  7320. {
  7321. return SocketHelpers::bindSocketToPort (handle, port);
  7322. }
  7323. bool DatagramSocket::connect (const String& remoteHostName,
  7324. const int remotePortNumber,
  7325. const int timeOutMillisecs)
  7326. {
  7327. if (connected)
  7328. close();
  7329. hostName = remoteHostName;
  7330. portNumber = remotePortNumber;
  7331. connected = SocketHelpers::connectSocket (handle, true, &serverAddress,
  7332. remoteHostName, remotePortNumber,
  7333. timeOutMillisecs);
  7334. if (! (connected && SocketHelpers::resetSocketOptions (handle, true, allowBroadcast)))
  7335. {
  7336. close();
  7337. return false;
  7338. }
  7339. return true;
  7340. }
  7341. DatagramSocket* DatagramSocket::waitForNextConnection() const
  7342. {
  7343. struct sockaddr address;
  7344. juce_socklen_t len = sizeof (sockaddr);
  7345. while (waitUntilReady (true, -1) == 1)
  7346. {
  7347. char buf[1];
  7348. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  7349. {
  7350. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  7351. ntohs (((struct sockaddr_in*) &address)->sin_port),
  7352. -1, -1);
  7353. }
  7354. }
  7355. return 0;
  7356. }
  7357. int DatagramSocket::waitUntilReady (const bool readyForReading,
  7358. const int timeoutMsecs) const
  7359. {
  7360. return connected ? SocketHelpers::waitForReadiness (handle, readyForReading, timeoutMsecs)
  7361. : -1;
  7362. }
  7363. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead, const bool blockUntilSpecifiedAmountHasArrived)
  7364. {
  7365. return connected ? SocketHelpers::readSocket (handle, destBuffer, maxBytesToRead, connected, blockUntilSpecifiedAmountHasArrived)
  7366. : -1;
  7367. }
  7368. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  7369. {
  7370. // You need to call connect() first to set the server address..
  7371. jassert (serverAddress != 0 && connected);
  7372. return connected ? (int) sendto (handle, (const char*) sourceBuffer,
  7373. numBytesToWrite, 0,
  7374. (const struct sockaddr*) serverAddress,
  7375. sizeof (struct sockaddr_in))
  7376. : -1;
  7377. }
  7378. bool DatagramSocket::isLocal() const throw()
  7379. {
  7380. return hostName == "127.0.0.1";
  7381. }
  7382. #if JUCE_MSVC
  7383. #pragma warning (pop)
  7384. #endif
  7385. END_JUCE_NAMESPACE
  7386. /*** End of inlined file: juce_Socket.cpp ***/
  7387. /*** Start of inlined file: juce_URL.cpp ***/
  7388. BEGIN_JUCE_NAMESPACE
  7389. URL::URL()
  7390. {
  7391. }
  7392. URL::URL (const String& url_)
  7393. : url (url_)
  7394. {
  7395. int i = url.indexOfChar ('?');
  7396. if (i >= 0)
  7397. {
  7398. do
  7399. {
  7400. const int nextAmp = url.indexOfChar (i + 1, '&');
  7401. const int equalsPos = url.indexOfChar (i + 1, '=');
  7402. if (equalsPos > i + 1)
  7403. {
  7404. if (nextAmp < 0)
  7405. {
  7406. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7407. removeEscapeChars (url.substring (equalsPos + 1)));
  7408. }
  7409. else if (nextAmp > 0 && equalsPos < nextAmp)
  7410. {
  7411. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  7412. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  7413. }
  7414. }
  7415. i = nextAmp;
  7416. }
  7417. while (i >= 0);
  7418. url = url.upToFirstOccurrenceOf ("?", false, false);
  7419. }
  7420. }
  7421. URL::URL (const URL& other)
  7422. : url (other.url),
  7423. postData (other.postData),
  7424. parameters (other.parameters),
  7425. filesToUpload (other.filesToUpload),
  7426. mimeTypes (other.mimeTypes)
  7427. {
  7428. }
  7429. URL& URL::operator= (const URL& other)
  7430. {
  7431. url = other.url;
  7432. postData = other.postData;
  7433. parameters = other.parameters;
  7434. filesToUpload = other.filesToUpload;
  7435. mimeTypes = other.mimeTypes;
  7436. return *this;
  7437. }
  7438. URL::~URL()
  7439. {
  7440. }
  7441. namespace URLHelpers
  7442. {
  7443. const String getMangledParameters (const StringPairArray& parameters)
  7444. {
  7445. String p;
  7446. for (int i = 0; i < parameters.size(); ++i)
  7447. {
  7448. if (i > 0)
  7449. p << '&';
  7450. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  7451. << '='
  7452. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  7453. }
  7454. return p;
  7455. }
  7456. int findStartOfDomain (const String& url)
  7457. {
  7458. int i = 0;
  7459. while (CharacterFunctions::isLetterOrDigit (url[i])
  7460. || CharacterFunctions::indexOfChar (L"+-.", url[i], false) >= 0)
  7461. ++i;
  7462. return url[i] == ':' ? i + 1 : 0;
  7463. }
  7464. }
  7465. const String URL::toString (const bool includeGetParameters) const
  7466. {
  7467. if (includeGetParameters && parameters.size() > 0)
  7468. return url + "?" + URLHelpers::getMangledParameters (parameters);
  7469. else
  7470. return url;
  7471. }
  7472. bool URL::isWellFormed() const
  7473. {
  7474. //xxx TODO
  7475. return url.isNotEmpty();
  7476. }
  7477. const String URL::getDomain() const
  7478. {
  7479. int start = URLHelpers::findStartOfDomain (url);
  7480. while (url[start] == '/')
  7481. ++start;
  7482. const int end1 = url.indexOfChar (start, '/');
  7483. const int end2 = url.indexOfChar (start, ':');
  7484. const int end = (end1 < 0 || end2 < 0) ? jmax (end1, end2)
  7485. : jmin (end1, end2);
  7486. return url.substring (start, end);
  7487. }
  7488. const String URL::getSubPath() const
  7489. {
  7490. int start = URLHelpers::findStartOfDomain (url);
  7491. while (url[start] == '/')
  7492. ++start;
  7493. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7494. return startOfPath <= 0 ? String::empty
  7495. : url.substring (startOfPath);
  7496. }
  7497. const String URL::getScheme() const
  7498. {
  7499. return url.substring (0, URLHelpers::findStartOfDomain (url) - 1);
  7500. }
  7501. const URL URL::withNewSubPath (const String& newPath) const
  7502. {
  7503. int start = URLHelpers::findStartOfDomain (url);
  7504. while (url[start] == '/')
  7505. ++start;
  7506. const int startOfPath = url.indexOfChar (start, '/') + 1;
  7507. URL u (*this);
  7508. if (startOfPath > 0)
  7509. u.url = url.substring (0, startOfPath);
  7510. if (! u.url.endsWithChar ('/'))
  7511. u.url << '/';
  7512. if (newPath.startsWithChar ('/'))
  7513. u.url << newPath.substring (1);
  7514. else
  7515. u.url << newPath;
  7516. return u;
  7517. }
  7518. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  7519. {
  7520. if (possibleURL.startsWithIgnoreCase ("http:")
  7521. || possibleURL.startsWithIgnoreCase ("ftp:"))
  7522. return true;
  7523. if (possibleURL.startsWithIgnoreCase ("file:")
  7524. || possibleURL.containsChar ('@')
  7525. || possibleURL.endsWithChar ('.')
  7526. || (! possibleURL.containsChar ('.')))
  7527. return false;
  7528. if (possibleURL.startsWithIgnoreCase ("www.")
  7529. && possibleURL.substring (5).containsChar ('.'))
  7530. return true;
  7531. const char* commonTLDs[] = { "com", "net", "org", "uk", "de", "fr", "jp" };
  7532. for (int i = 0; i < numElementsInArray (commonTLDs); ++i)
  7533. if ((possibleURL + "/").containsIgnoreCase ("." + String (commonTLDs[i]) + "/"))
  7534. return true;
  7535. return false;
  7536. }
  7537. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  7538. {
  7539. const int atSign = possibleEmailAddress.indexOfChar ('@');
  7540. return atSign > 0
  7541. && possibleEmailAddress.lastIndexOfChar ('.') > (atSign + 1)
  7542. && (! possibleEmailAddress.endsWithChar ('.'));
  7543. }
  7544. void* juce_openInternetFile (const String& url,
  7545. const String& headers,
  7546. const MemoryBlock& optionalPostData,
  7547. const bool isPost,
  7548. URL::OpenStreamProgressCallback* callback,
  7549. void* callbackContext,
  7550. int timeOutMs);
  7551. void juce_closeInternetFile (void* handle);
  7552. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  7553. int juce_seekInInternetFile (void* handle, int newPosition);
  7554. int64 juce_getInternetFileContentLength (void* handle);
  7555. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers);
  7556. class WebInputStream : public InputStream
  7557. {
  7558. public:
  7559. WebInputStream (const URL& url,
  7560. const bool isPost_,
  7561. URL::OpenStreamProgressCallback* const progressCallback_,
  7562. void* const progressCallbackContext_,
  7563. const String& extraHeaders,
  7564. const int timeOutMs_,
  7565. StringPairArray* const responseHeaders)
  7566. : position (0),
  7567. finished (false),
  7568. isPost (isPost_),
  7569. progressCallback (progressCallback_),
  7570. progressCallbackContext (progressCallbackContext_),
  7571. timeOutMs (timeOutMs_)
  7572. {
  7573. server = url.toString (! isPost);
  7574. if (isPost_)
  7575. createHeadersAndPostData (url);
  7576. headers += extraHeaders;
  7577. if (! headers.endsWithChar ('\n'))
  7578. headers << "\r\n";
  7579. handle = juce_openInternetFile (server, headers, postData, isPost,
  7580. progressCallback_, progressCallbackContext_,
  7581. timeOutMs);
  7582. if (responseHeaders != 0)
  7583. juce_getInternetFileHeaders (handle, *responseHeaders);
  7584. }
  7585. ~WebInputStream()
  7586. {
  7587. juce_closeInternetFile (handle);
  7588. }
  7589. bool isError() const { return handle == 0; }
  7590. int64 getTotalLength() { return juce_getInternetFileContentLength (handle); }
  7591. bool isExhausted() { return finished; }
  7592. int64 getPosition() { return position; }
  7593. int read (void* dest, int bytes)
  7594. {
  7595. if (finished || isError())
  7596. {
  7597. return 0;
  7598. }
  7599. else
  7600. {
  7601. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  7602. position += bytesRead;
  7603. if (bytesRead == 0)
  7604. finished = true;
  7605. return bytesRead;
  7606. }
  7607. }
  7608. bool setPosition (int64 wantedPos)
  7609. {
  7610. if (wantedPos != position)
  7611. {
  7612. finished = false;
  7613. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  7614. if (actualPos == wantedPos)
  7615. {
  7616. position = wantedPos;
  7617. }
  7618. else
  7619. {
  7620. if (wantedPos < position)
  7621. {
  7622. juce_closeInternetFile (handle);
  7623. position = 0;
  7624. finished = false;
  7625. handle = juce_openInternetFile (server, headers, postData, isPost,
  7626. progressCallback, progressCallbackContext,
  7627. timeOutMs);
  7628. }
  7629. skipNextBytes (wantedPos - position);
  7630. }
  7631. }
  7632. return true;
  7633. }
  7634. juce_UseDebuggingNewOperator
  7635. private:
  7636. String server, headers;
  7637. MemoryBlock postData;
  7638. int64 position;
  7639. bool finished;
  7640. const bool isPost;
  7641. void* handle;
  7642. URL::OpenStreamProgressCallback* const progressCallback;
  7643. void* const progressCallbackContext;
  7644. const int timeOutMs;
  7645. void createHeadersAndPostData (const URL& url)
  7646. {
  7647. MemoryOutputStream data (postData, false);
  7648. if (url.getFilesToUpload().size() > 0)
  7649. {
  7650. // need to upload some files, so do it as multi-part...
  7651. const String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  7652. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  7653. data << "--" << boundary;
  7654. int i;
  7655. for (i = 0; i < url.getParameters().size(); ++i)
  7656. {
  7657. data << "\r\nContent-Disposition: form-data; name=\""
  7658. << url.getParameters().getAllKeys() [i]
  7659. << "\"\r\n\r\n"
  7660. << url.getParameters().getAllValues() [i]
  7661. << "\r\n--"
  7662. << boundary;
  7663. }
  7664. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  7665. {
  7666. const File file (url.getFilesToUpload().getAllValues() [i]);
  7667. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  7668. data << "\r\nContent-Disposition: form-data; name=\"" << paramName
  7669. << "\"; filename=\"" << file.getFileName() << "\"\r\n";
  7670. const String mimeType (url.getMimeTypesOfUploadFiles()
  7671. .getValue (paramName, String::empty));
  7672. if (mimeType.isNotEmpty())
  7673. data << "Content-Type: " << mimeType << "\r\n";
  7674. data << "Content-Transfer-Encoding: binary\r\n\r\n"
  7675. << file << "\r\n--" << boundary;
  7676. }
  7677. data << "--\r\n";
  7678. data.flush();
  7679. }
  7680. else
  7681. {
  7682. data << URLHelpers::getMangledParameters (url.getParameters())
  7683. << url.getPostData();
  7684. data.flush();
  7685. // just a short text attachment, so use simple url encoding..
  7686. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  7687. + String ((unsigned int) postData.getSize())
  7688. + "\r\n";
  7689. }
  7690. }
  7691. WebInputStream (const WebInputStream&);
  7692. WebInputStream& operator= (const WebInputStream&);
  7693. };
  7694. InputStream* URL::createInputStream (const bool usePostCommand,
  7695. OpenStreamProgressCallback* const progressCallback,
  7696. void* const progressCallbackContext,
  7697. const String& extraHeaders,
  7698. const int timeOutMs,
  7699. StringPairArray* const responseHeaders) const
  7700. {
  7701. ScopedPointer <WebInputStream> wi (new WebInputStream (*this, usePostCommand,
  7702. progressCallback, progressCallbackContext,
  7703. extraHeaders, timeOutMs, responseHeaders));
  7704. return wi->isError() ? 0 : wi.release();
  7705. }
  7706. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  7707. const bool usePostCommand) const
  7708. {
  7709. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7710. if (in != 0)
  7711. {
  7712. in->readIntoMemoryBlock (destData);
  7713. return true;
  7714. }
  7715. return false;
  7716. }
  7717. const String URL::readEntireTextStream (const bool usePostCommand) const
  7718. {
  7719. const ScopedPointer <InputStream> in (createInputStream (usePostCommand));
  7720. if (in != 0)
  7721. return in->readEntireStreamAsString();
  7722. return String::empty;
  7723. }
  7724. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  7725. {
  7726. XmlDocument doc (readEntireTextStream (usePostCommand));
  7727. return doc.getDocumentElement();
  7728. }
  7729. const URL URL::withParameter (const String& parameterName,
  7730. const String& parameterValue) const
  7731. {
  7732. URL u (*this);
  7733. u.parameters.set (parameterName, parameterValue);
  7734. return u;
  7735. }
  7736. const URL URL::withFileToUpload (const String& parameterName,
  7737. const File& fileToUpload,
  7738. const String& mimeType) const
  7739. {
  7740. jassert (mimeType.isNotEmpty()); // You need to supply a mime type!
  7741. URL u (*this);
  7742. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  7743. u.mimeTypes.set (parameterName, mimeType);
  7744. return u;
  7745. }
  7746. const URL URL::withPOSTData (const String& postData_) const
  7747. {
  7748. URL u (*this);
  7749. u.postData = postData_;
  7750. return u;
  7751. }
  7752. const StringPairArray& URL::getParameters() const
  7753. {
  7754. return parameters;
  7755. }
  7756. const StringPairArray& URL::getFilesToUpload() const
  7757. {
  7758. return filesToUpload;
  7759. }
  7760. const StringPairArray& URL::getMimeTypesOfUploadFiles() const
  7761. {
  7762. return mimeTypes;
  7763. }
  7764. const String URL::removeEscapeChars (const String& s)
  7765. {
  7766. String result (s.replaceCharacter ('+', ' '));
  7767. if (! result.containsChar ('%'))
  7768. return result;
  7769. // We need to operate on the string as raw UTF8 chars, and then recombine them into unicode
  7770. // after all the replacements have been made, so that multi-byte chars are handled.
  7771. Array<char> utf8 (result.toUTF8(), result.getNumBytesAsUTF8());
  7772. for (int i = 0; i < utf8.size(); ++i)
  7773. {
  7774. if (utf8.getUnchecked(i) == '%')
  7775. {
  7776. const int hexDigit1 = CharacterFunctions::getHexDigitValue (utf8 [i + 1]);
  7777. const int hexDigit2 = CharacterFunctions::getHexDigitValue (utf8 [i + 2]);
  7778. if (hexDigit1 >= 0 && hexDigit2 >= 0)
  7779. {
  7780. utf8.set (i, (char) ((hexDigit1 << 4) + hexDigit2));
  7781. utf8.removeRange (i + 1, 2);
  7782. }
  7783. }
  7784. }
  7785. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7786. }
  7787. const String URL::addEscapeChars (const String& s, const bool isParameter)
  7788. {
  7789. const char* const legalChars = isParameter ? "_-.*!'()"
  7790. : ",$_-.*!'()";
  7791. Array<char> utf8 (s.toUTF8(), s.getNumBytesAsUTF8());
  7792. for (int i = 0; i < utf8.size(); ++i)
  7793. {
  7794. const char c = utf8.getUnchecked(i);
  7795. if (! (CharacterFunctions::isLetterOrDigit (c)
  7796. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0))
  7797. {
  7798. if (c == ' ')
  7799. {
  7800. utf8.set (i, '+');
  7801. }
  7802. else
  7803. {
  7804. static const char* const hexDigits = "0123456789abcdef";
  7805. utf8.set (i, '%');
  7806. utf8.insert (++i, hexDigits [((uint8) c) >> 4]);
  7807. utf8.insert (++i, hexDigits [c & 15]);
  7808. }
  7809. }
  7810. }
  7811. return String::fromUTF8 (utf8.getRawDataPointer(), utf8.size());
  7812. }
  7813. bool URL::launchInDefaultBrowser() const
  7814. {
  7815. String u (toString (true));
  7816. if (u.containsChar ('@') && ! u.containsChar (':'))
  7817. u = "mailto:" + u;
  7818. return PlatformUtilities::openDocument (u, String::empty);
  7819. }
  7820. END_JUCE_NAMESPACE
  7821. /*** End of inlined file: juce_URL.cpp ***/
  7822. /*** Start of inlined file: juce_BufferedInputStream.cpp ***/
  7823. BEGIN_JUCE_NAMESPACE
  7824. namespace
  7825. {
  7826. int calcBufferStreamBufferSize (int requestedSize, InputStream* const source) throw()
  7827. {
  7828. // You need to supply a real stream when creating a BufferedInputStream
  7829. jassert (source != 0);
  7830. requestedSize = jmax (256, requestedSize);
  7831. const int64 sourceSize = source->getTotalLength();
  7832. if (sourceSize >= 0 && sourceSize < requestedSize)
  7833. requestedSize = jmax (32, (int) sourceSize);
  7834. return requestedSize;
  7835. }
  7836. }
  7837. BufferedInputStream::BufferedInputStream (InputStream* const sourceStream, const int bufferSize_,
  7838. const bool deleteSourceWhenDestroyed)
  7839. : source (sourceStream),
  7840. sourceToDelete (deleteSourceWhenDestroyed ? sourceStream : 0),
  7841. bufferSize (calcBufferStreamBufferSize (bufferSize_, sourceStream)),
  7842. position (sourceStream->getPosition()),
  7843. lastReadPos (0),
  7844. bufferStart (position),
  7845. bufferOverlap (128)
  7846. {
  7847. buffer.malloc (bufferSize);
  7848. }
  7849. BufferedInputStream::BufferedInputStream (InputStream& sourceStream, const int bufferSize_)
  7850. : source (&sourceStream),
  7851. bufferSize (calcBufferStreamBufferSize (bufferSize_, &sourceStream)),
  7852. position (sourceStream.getPosition()),
  7853. lastReadPos (0),
  7854. bufferStart (position),
  7855. bufferOverlap (128)
  7856. {
  7857. buffer.malloc (bufferSize);
  7858. }
  7859. BufferedInputStream::~BufferedInputStream()
  7860. {
  7861. }
  7862. int64 BufferedInputStream::getTotalLength()
  7863. {
  7864. return source->getTotalLength();
  7865. }
  7866. int64 BufferedInputStream::getPosition()
  7867. {
  7868. return position;
  7869. }
  7870. bool BufferedInputStream::setPosition (int64 newPosition)
  7871. {
  7872. position = jmax ((int64) 0, newPosition);
  7873. return true;
  7874. }
  7875. bool BufferedInputStream::isExhausted()
  7876. {
  7877. return (position >= lastReadPos)
  7878. && source->isExhausted();
  7879. }
  7880. void BufferedInputStream::ensureBuffered()
  7881. {
  7882. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  7883. if (position < bufferStart || position >= bufferEndOverlap)
  7884. {
  7885. int bytesRead;
  7886. if (position < lastReadPos
  7887. && position >= bufferEndOverlap
  7888. && position >= bufferStart)
  7889. {
  7890. const int bytesToKeep = (int) (lastReadPos - position);
  7891. memmove (buffer, buffer + (int) (position - bufferStart), bytesToKeep);
  7892. bufferStart = position;
  7893. bytesRead = source->read (buffer + bytesToKeep,
  7894. bufferSize - bytesToKeep);
  7895. lastReadPos += bytesRead;
  7896. bytesRead += bytesToKeep;
  7897. }
  7898. else
  7899. {
  7900. bufferStart = position;
  7901. source->setPosition (bufferStart);
  7902. bytesRead = source->read (buffer, bufferSize);
  7903. lastReadPos = bufferStart + bytesRead;
  7904. }
  7905. while (bytesRead < bufferSize)
  7906. buffer [bytesRead++] = 0;
  7907. }
  7908. }
  7909. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  7910. {
  7911. if (position >= bufferStart
  7912. && position + maxBytesToRead <= lastReadPos)
  7913. {
  7914. memcpy (destBuffer, buffer + (int) (position - bufferStart), maxBytesToRead);
  7915. position += maxBytesToRead;
  7916. return maxBytesToRead;
  7917. }
  7918. else
  7919. {
  7920. if (position < bufferStart || position >= lastReadPos)
  7921. ensureBuffered();
  7922. int bytesRead = 0;
  7923. while (maxBytesToRead > 0)
  7924. {
  7925. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  7926. if (bytesAvailable > 0)
  7927. {
  7928. memcpy (destBuffer, buffer + (int) (position - bufferStart), bytesAvailable);
  7929. maxBytesToRead -= bytesAvailable;
  7930. bytesRead += bytesAvailable;
  7931. position += bytesAvailable;
  7932. destBuffer = static_cast <char*> (destBuffer) + bytesAvailable;
  7933. }
  7934. const int64 oldLastReadPos = lastReadPos;
  7935. ensureBuffered();
  7936. if (oldLastReadPos == lastReadPos)
  7937. break; // if ensureBuffered() failed to read any more data, bail out
  7938. if (isExhausted())
  7939. break;
  7940. }
  7941. return bytesRead;
  7942. }
  7943. }
  7944. const String BufferedInputStream::readString()
  7945. {
  7946. if (position >= bufferStart
  7947. && position < lastReadPos)
  7948. {
  7949. const int maxChars = (int) (lastReadPos - position);
  7950. const char* const src = buffer + (int) (position - bufferStart);
  7951. for (int i = 0; i < maxChars; ++i)
  7952. {
  7953. if (src[i] == 0)
  7954. {
  7955. position += i + 1;
  7956. return String::fromUTF8 (src, i);
  7957. }
  7958. }
  7959. }
  7960. return InputStream::readString();
  7961. }
  7962. END_JUCE_NAMESPACE
  7963. /*** End of inlined file: juce_BufferedInputStream.cpp ***/
  7964. /*** Start of inlined file: juce_FileInputSource.cpp ***/
  7965. BEGIN_JUCE_NAMESPACE
  7966. FileInputSource::FileInputSource (const File& file_)
  7967. : file (file_)
  7968. {
  7969. }
  7970. FileInputSource::~FileInputSource()
  7971. {
  7972. }
  7973. InputStream* FileInputSource::createInputStream()
  7974. {
  7975. return file.createInputStream();
  7976. }
  7977. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  7978. {
  7979. return file.getSiblingFile (relatedItemPath).createInputStream();
  7980. }
  7981. int64 FileInputSource::hashCode() const
  7982. {
  7983. return file.hashCode();
  7984. }
  7985. END_JUCE_NAMESPACE
  7986. /*** End of inlined file: juce_FileInputSource.cpp ***/
  7987. /*** Start of inlined file: juce_MemoryInputStream.cpp ***/
  7988. BEGIN_JUCE_NAMESPACE
  7989. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  7990. const size_t sourceDataSize,
  7991. const bool keepInternalCopy)
  7992. : data (static_cast <const char*> (sourceData)),
  7993. dataSize (sourceDataSize),
  7994. position (0)
  7995. {
  7996. if (keepInternalCopy)
  7997. {
  7998. internalCopy.append (data, sourceDataSize);
  7999. data = static_cast <const char*> (internalCopy.getData());
  8000. }
  8001. }
  8002. MemoryInputStream::MemoryInputStream (const MemoryBlock& sourceData,
  8003. const bool keepInternalCopy)
  8004. : data (static_cast <const char*> (sourceData.getData())),
  8005. dataSize (sourceData.getSize()),
  8006. position (0)
  8007. {
  8008. if (keepInternalCopy)
  8009. {
  8010. internalCopy = sourceData;
  8011. data = static_cast <const char*> (internalCopy.getData());
  8012. }
  8013. }
  8014. MemoryInputStream::~MemoryInputStream()
  8015. {
  8016. }
  8017. int64 MemoryInputStream::getTotalLength()
  8018. {
  8019. return dataSize;
  8020. }
  8021. int MemoryInputStream::read (void* const buffer, const int howMany)
  8022. {
  8023. jassert (howMany >= 0);
  8024. const int num = jmin (howMany, (int) (dataSize - position));
  8025. memcpy (buffer, data + position, num);
  8026. position += num;
  8027. return (int) num;
  8028. }
  8029. bool MemoryInputStream::isExhausted()
  8030. {
  8031. return (position >= dataSize);
  8032. }
  8033. bool MemoryInputStream::setPosition (const int64 pos)
  8034. {
  8035. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  8036. return true;
  8037. }
  8038. int64 MemoryInputStream::getPosition()
  8039. {
  8040. return position;
  8041. }
  8042. #if JUCE_UNIT_TESTS
  8043. class MemoryStreamTests : public UnitTest
  8044. {
  8045. public:
  8046. MemoryStreamTests() : UnitTest ("MemoryInputStream & MemoryOutputStream") {}
  8047. void runTest()
  8048. {
  8049. beginTest ("Basics");
  8050. int randomInt = Random::getSystemRandom().nextInt();
  8051. int64 randomInt64 = Random::getSystemRandom().nextInt64();
  8052. double randomDouble = Random::getSystemRandom().nextDouble();
  8053. String randomString;
  8054. for (int i = 50; --i >= 0;)
  8055. randomString << (juce_wchar) (Random::getSystemRandom().nextInt() & 0xffff);
  8056. MemoryOutputStream mo;
  8057. mo.writeInt (randomInt);
  8058. mo.writeIntBigEndian (randomInt);
  8059. mo.writeCompressedInt (randomInt);
  8060. mo.writeString (randomString);
  8061. mo.writeInt64 (randomInt64);
  8062. mo.writeInt64BigEndian (randomInt64);
  8063. mo.writeDouble (randomDouble);
  8064. mo.writeDoubleBigEndian (randomDouble);
  8065. MemoryInputStream mi (mo.getData(), mo.getDataSize(), false);
  8066. expect (mi.readInt() == randomInt);
  8067. expect (mi.readIntBigEndian() == randomInt);
  8068. expect (mi.readCompressedInt() == randomInt);
  8069. expect (mi.readString() == randomString);
  8070. expect (mi.readInt64() == randomInt64);
  8071. expect (mi.readInt64BigEndian() == randomInt64);
  8072. expect (mi.readDouble() == randomDouble);
  8073. expect (mi.readDoubleBigEndian() == randomDouble);
  8074. }
  8075. };
  8076. static MemoryStreamTests memoryInputStreamUnitTests;
  8077. #endif
  8078. END_JUCE_NAMESPACE
  8079. /*** End of inlined file: juce_MemoryInputStream.cpp ***/
  8080. /*** Start of inlined file: juce_MemoryOutputStream.cpp ***/
  8081. BEGIN_JUCE_NAMESPACE
  8082. MemoryOutputStream::MemoryOutputStream (const size_t initialSize)
  8083. : data (internalBlock),
  8084. position (0),
  8085. size (0)
  8086. {
  8087. internalBlock.setSize (initialSize, false);
  8088. }
  8089. MemoryOutputStream::MemoryOutputStream (MemoryBlock& memoryBlockToWriteTo,
  8090. const bool appendToExistingBlockContent)
  8091. : data (memoryBlockToWriteTo),
  8092. position (0),
  8093. size (0)
  8094. {
  8095. if (appendToExistingBlockContent)
  8096. position = size = memoryBlockToWriteTo.getSize();
  8097. }
  8098. MemoryOutputStream::~MemoryOutputStream()
  8099. {
  8100. flush();
  8101. }
  8102. void MemoryOutputStream::flush()
  8103. {
  8104. if (&data != &internalBlock)
  8105. data.setSize (size, false);
  8106. }
  8107. void MemoryOutputStream::preallocate (const size_t bytesToPreallocate)
  8108. {
  8109. data.ensureSize (bytesToPreallocate + 1);
  8110. }
  8111. void MemoryOutputStream::reset() throw()
  8112. {
  8113. position = 0;
  8114. size = 0;
  8115. }
  8116. bool MemoryOutputStream::write (const void* const buffer, int howMany)
  8117. {
  8118. if (howMany > 0)
  8119. {
  8120. const size_t storageNeeded = position + howMany;
  8121. if (storageNeeded >= data.getSize())
  8122. data.ensureSize ((storageNeeded + jmin (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31);
  8123. memcpy (static_cast<char*> (data.getData()) + position, buffer, howMany);
  8124. position += howMany;
  8125. size = jmax (size, position);
  8126. }
  8127. return true;
  8128. }
  8129. const void* MemoryOutputStream::getData() const throw()
  8130. {
  8131. void* const d = data.getData();
  8132. if (data.getSize() > size)
  8133. static_cast <char*> (d) [size] = 0;
  8134. return d;
  8135. }
  8136. bool MemoryOutputStream::setPosition (int64 newPosition)
  8137. {
  8138. if (newPosition <= (int64) size)
  8139. {
  8140. // ok to seek backwards
  8141. position = jlimit ((size_t) 0, size, (size_t) newPosition);
  8142. return true;
  8143. }
  8144. else
  8145. {
  8146. // trying to make it bigger isn't a good thing to do..
  8147. return false;
  8148. }
  8149. }
  8150. int MemoryOutputStream::writeFromInputStream (InputStream& source, int64 maxNumBytesToWrite)
  8151. {
  8152. // before writing from an input, see if we can preallocate to make it more efficient..
  8153. int64 availableData = source.getTotalLength() - source.getPosition();
  8154. if (availableData > 0)
  8155. {
  8156. if (maxNumBytesToWrite > 0 && maxNumBytesToWrite < availableData)
  8157. availableData = maxNumBytesToWrite;
  8158. preallocate (data.getSize() + (size_t) maxNumBytesToWrite);
  8159. }
  8160. return OutputStream::writeFromInputStream (source, maxNumBytesToWrite);
  8161. }
  8162. const String MemoryOutputStream::toUTF8() const
  8163. {
  8164. return String (static_cast <const char*> (getData()), getDataSize());
  8165. }
  8166. const String MemoryOutputStream::toString() const
  8167. {
  8168. return String::createStringFromData (getData(), getDataSize());
  8169. }
  8170. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const MemoryOutputStream& streamToRead)
  8171. {
  8172. stream.write (streamToRead.getData(), streamToRead.getDataSize());
  8173. return stream;
  8174. }
  8175. END_JUCE_NAMESPACE
  8176. /*** End of inlined file: juce_MemoryOutputStream.cpp ***/
  8177. /*** Start of inlined file: juce_SubregionStream.cpp ***/
  8178. BEGIN_JUCE_NAMESPACE
  8179. SubregionStream::SubregionStream (InputStream* const sourceStream,
  8180. const int64 startPositionInSourceStream_,
  8181. const int64 lengthOfSourceStream_,
  8182. const bool deleteSourceWhenDestroyed)
  8183. : source (sourceStream),
  8184. startPositionInSourceStream (startPositionInSourceStream_),
  8185. lengthOfSourceStream (lengthOfSourceStream_)
  8186. {
  8187. if (deleteSourceWhenDestroyed)
  8188. sourceToDelete = source;
  8189. setPosition (0);
  8190. }
  8191. SubregionStream::~SubregionStream()
  8192. {
  8193. }
  8194. int64 SubregionStream::getTotalLength()
  8195. {
  8196. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  8197. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  8198. : srcLen;
  8199. }
  8200. int64 SubregionStream::getPosition()
  8201. {
  8202. return source->getPosition() - startPositionInSourceStream;
  8203. }
  8204. bool SubregionStream::setPosition (int64 newPosition)
  8205. {
  8206. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  8207. }
  8208. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  8209. {
  8210. if (lengthOfSourceStream < 0)
  8211. {
  8212. return source->read (destBuffer, maxBytesToRead);
  8213. }
  8214. else
  8215. {
  8216. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  8217. if (maxBytesToRead <= 0)
  8218. return 0;
  8219. return source->read (destBuffer, maxBytesToRead);
  8220. }
  8221. }
  8222. bool SubregionStream::isExhausted()
  8223. {
  8224. if (lengthOfSourceStream >= 0)
  8225. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  8226. else
  8227. return source->isExhausted();
  8228. }
  8229. END_JUCE_NAMESPACE
  8230. /*** End of inlined file: juce_SubregionStream.cpp ***/
  8231. /*** Start of inlined file: juce_PerformanceCounter.cpp ***/
  8232. BEGIN_JUCE_NAMESPACE
  8233. PerformanceCounter::PerformanceCounter (const String& name_,
  8234. int runsPerPrintout,
  8235. const File& loggingFile)
  8236. : name (name_),
  8237. numRuns (0),
  8238. runsPerPrint (runsPerPrintout),
  8239. totalTime (0),
  8240. outputFile (loggingFile)
  8241. {
  8242. if (outputFile != File::nonexistent)
  8243. {
  8244. String s ("**** Counter for \"");
  8245. s << name_ << "\" started at: "
  8246. << Time::getCurrentTime().toString (true, true)
  8247. << "\r\n";
  8248. outputFile.appendText (s, false, false);
  8249. }
  8250. }
  8251. PerformanceCounter::~PerformanceCounter()
  8252. {
  8253. printStatistics();
  8254. }
  8255. void PerformanceCounter::start()
  8256. {
  8257. started = Time::getHighResolutionTicks();
  8258. }
  8259. void PerformanceCounter::stop()
  8260. {
  8261. const int64 now = Time::getHighResolutionTicks();
  8262. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  8263. if (++numRuns == runsPerPrint)
  8264. printStatistics();
  8265. }
  8266. void PerformanceCounter::printStatistics()
  8267. {
  8268. if (numRuns > 0)
  8269. {
  8270. String s ("Performance count for \"");
  8271. s << name << "\" - average over " << numRuns << " run(s) = ";
  8272. const int micros = (int) (totalTime * (1000.0 / numRuns));
  8273. if (micros > 10000)
  8274. s << (micros/1000) << " millisecs";
  8275. else
  8276. s << micros << " microsecs";
  8277. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  8278. Logger::outputDebugString (s);
  8279. s << "\r\n";
  8280. if (outputFile != File::nonexistent)
  8281. outputFile.appendText (s, false, false);
  8282. numRuns = 0;
  8283. totalTime = 0;
  8284. }
  8285. }
  8286. END_JUCE_NAMESPACE
  8287. /*** End of inlined file: juce_PerformanceCounter.cpp ***/
  8288. /*** Start of inlined file: juce_Uuid.cpp ***/
  8289. BEGIN_JUCE_NAMESPACE
  8290. Uuid::Uuid()
  8291. {
  8292. // Mix up any available MAC addresses with some time-based pseudo-random numbers
  8293. // to make it very very unlikely that two UUIDs will ever be the same..
  8294. static int64 macAddresses[2];
  8295. static bool hasCheckedMacAddresses = false;
  8296. if (! hasCheckedMacAddresses)
  8297. {
  8298. hasCheckedMacAddresses = true;
  8299. SystemStats::getMACAddresses (macAddresses, 2);
  8300. }
  8301. value.asInt64[0] = macAddresses[0];
  8302. value.asInt64[1] = macAddresses[1];
  8303. // We'll use both a local RNG that is re-seeded, plus the shared RNG,
  8304. // whose seed will carry over between calls to this method.
  8305. Random r (macAddresses[0] ^ macAddresses[1]
  8306. ^ Random::getSystemRandom().nextInt64());
  8307. for (int i = 4; --i >= 0;)
  8308. {
  8309. r.setSeedRandomly(); // calling this repeatedly improves randomness
  8310. value.asInt[i] ^= r.nextInt();
  8311. value.asInt[i] ^= Random::getSystemRandom().nextInt();
  8312. }
  8313. }
  8314. Uuid::~Uuid() throw()
  8315. {
  8316. }
  8317. Uuid::Uuid (const Uuid& other)
  8318. : value (other.value)
  8319. {
  8320. }
  8321. Uuid& Uuid::operator= (const Uuid& other)
  8322. {
  8323. value = other.value;
  8324. return *this;
  8325. }
  8326. bool Uuid::operator== (const Uuid& other) const
  8327. {
  8328. return value.asInt64[0] == other.value.asInt64[0]
  8329. && value.asInt64[1] == other.value.asInt64[1];
  8330. }
  8331. bool Uuid::operator!= (const Uuid& other) const
  8332. {
  8333. return ! operator== (other);
  8334. }
  8335. bool Uuid::isNull() const throw()
  8336. {
  8337. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  8338. }
  8339. const String Uuid::toString() const
  8340. {
  8341. return String::toHexString (value.asBytes, sizeof (value.asBytes), 0);
  8342. }
  8343. Uuid::Uuid (const String& uuidString)
  8344. {
  8345. operator= (uuidString);
  8346. }
  8347. Uuid& Uuid::operator= (const String& uuidString)
  8348. {
  8349. MemoryBlock mb;
  8350. mb.loadFromHexString (uuidString);
  8351. mb.ensureSize (sizeof (value.asBytes), true);
  8352. mb.copyTo (value.asBytes, 0, sizeof (value.asBytes));
  8353. return *this;
  8354. }
  8355. Uuid::Uuid (const uint8* const rawData)
  8356. {
  8357. operator= (rawData);
  8358. }
  8359. Uuid& Uuid::operator= (const uint8* const rawData)
  8360. {
  8361. if (rawData != 0)
  8362. memcpy (value.asBytes, rawData, sizeof (value.asBytes));
  8363. else
  8364. zeromem (value.asBytes, sizeof (value.asBytes));
  8365. return *this;
  8366. }
  8367. END_JUCE_NAMESPACE
  8368. /*** End of inlined file: juce_Uuid.cpp ***/
  8369. /*** Start of inlined file: juce_ZipFile.cpp ***/
  8370. BEGIN_JUCE_NAMESPACE
  8371. class ZipFile::ZipEntryInfo
  8372. {
  8373. public:
  8374. ZipFile::ZipEntry entry;
  8375. int streamOffset;
  8376. int compressedSize;
  8377. bool compressed;
  8378. };
  8379. class ZipFile::ZipInputStream : public InputStream
  8380. {
  8381. public:
  8382. ZipInputStream (ZipFile& file_, ZipFile::ZipEntryInfo& zei)
  8383. : file (file_),
  8384. zipEntryInfo (zei),
  8385. pos (0),
  8386. headerSize (0),
  8387. inputStream (0)
  8388. {
  8389. inputStream = file_.inputStream;
  8390. if (file_.inputSource != 0)
  8391. {
  8392. inputStream = streamToDelete = file.inputSource->createInputStream();
  8393. }
  8394. else
  8395. {
  8396. #if JUCE_DEBUG
  8397. file_.numOpenStreams++;
  8398. #endif
  8399. }
  8400. char buffer [30];
  8401. if (inputStream != 0
  8402. && inputStream->setPosition (zei.streamOffset)
  8403. && inputStream->read (buffer, 30) == 30
  8404. && ByteOrder::littleEndianInt (buffer) == 0x04034b50)
  8405. {
  8406. headerSize = 30 + ByteOrder::littleEndianShort (buffer + 26)
  8407. + ByteOrder::littleEndianShort (buffer + 28);
  8408. }
  8409. }
  8410. ~ZipInputStream()
  8411. {
  8412. #if JUCE_DEBUG
  8413. if (inputStream != 0 && inputStream == file.inputStream)
  8414. file.numOpenStreams--;
  8415. #endif
  8416. }
  8417. int64 getTotalLength()
  8418. {
  8419. return zipEntryInfo.compressedSize;
  8420. }
  8421. int read (void* buffer, int howMany)
  8422. {
  8423. if (headerSize <= 0)
  8424. return 0;
  8425. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  8426. if (inputStream == 0)
  8427. return 0;
  8428. int num;
  8429. if (inputStream == file.inputStream)
  8430. {
  8431. const ScopedLock sl (file.lock);
  8432. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8433. num = inputStream->read (buffer, howMany);
  8434. }
  8435. else
  8436. {
  8437. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  8438. num = inputStream->read (buffer, howMany);
  8439. }
  8440. pos += num;
  8441. return num;
  8442. }
  8443. bool isExhausted()
  8444. {
  8445. return headerSize <= 0 || pos >= zipEntryInfo.compressedSize;
  8446. }
  8447. int64 getPosition()
  8448. {
  8449. return pos;
  8450. }
  8451. bool setPosition (int64 newPos)
  8452. {
  8453. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  8454. return true;
  8455. }
  8456. private:
  8457. ZipFile& file;
  8458. ZipEntryInfo zipEntryInfo;
  8459. int64 pos;
  8460. int headerSize;
  8461. InputStream* inputStream;
  8462. ScopedPointer<InputStream> streamToDelete;
  8463. ZipInputStream (const ZipInputStream&);
  8464. ZipInputStream& operator= (const ZipInputStream&);
  8465. };
  8466. ZipFile::ZipFile (InputStream* const source_, const bool deleteStreamWhenDestroyed)
  8467. : inputStream (source_)
  8468. #if JUCE_DEBUG
  8469. , numOpenStreams (0)
  8470. #endif
  8471. {
  8472. if (deleteStreamWhenDestroyed)
  8473. streamToDelete = inputStream;
  8474. init();
  8475. }
  8476. ZipFile::ZipFile (const File& file)
  8477. : inputStream (0)
  8478. #if JUCE_DEBUG
  8479. , numOpenStreams (0)
  8480. #endif
  8481. {
  8482. inputSource = new FileInputSource (file);
  8483. init();
  8484. }
  8485. ZipFile::ZipFile (InputSource* const inputSource_)
  8486. : inputStream (0),
  8487. inputSource (inputSource_)
  8488. #if JUCE_DEBUG
  8489. , numOpenStreams (0)
  8490. #endif
  8491. {
  8492. init();
  8493. }
  8494. ZipFile::~ZipFile()
  8495. {
  8496. #if JUCE_DEBUG
  8497. entries.clear();
  8498. /* If you hit this assertion, it means you've created a stream to read one of the items in the
  8499. zipfile, but you've forgotten to delete that stream object before deleting the file..
  8500. Streams can't be kept open after the file is deleted because they need to share the input
  8501. stream that the file uses to read itself.
  8502. */
  8503. jassert (numOpenStreams == 0);
  8504. #endif
  8505. }
  8506. int ZipFile::getNumEntries() const throw()
  8507. {
  8508. return entries.size();
  8509. }
  8510. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  8511. {
  8512. ZipEntryInfo* const zei = entries [index];
  8513. return zei != 0 ? &(zei->entry) : 0;
  8514. }
  8515. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  8516. {
  8517. for (int i = 0; i < entries.size(); ++i)
  8518. if (entries.getUnchecked (i)->entry.filename == fileName)
  8519. return i;
  8520. return -1;
  8521. }
  8522. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  8523. {
  8524. return getEntry (getIndexOfFileName (fileName));
  8525. }
  8526. InputStream* ZipFile::createStreamForEntry (const int index)
  8527. {
  8528. ZipEntryInfo* const zei = entries[index];
  8529. InputStream* stream = 0;
  8530. if (zei != 0)
  8531. {
  8532. stream = new ZipInputStream (*this, *zei);
  8533. if (zei->compressed)
  8534. {
  8535. stream = new GZIPDecompressorInputStream (stream, true, true,
  8536. zei->entry.uncompressedSize);
  8537. // (much faster to unzip in big blocks using a buffer..)
  8538. stream = new BufferedInputStream (stream, 32768, true);
  8539. }
  8540. }
  8541. return stream;
  8542. }
  8543. class ZipFile::ZipFilenameComparator
  8544. {
  8545. public:
  8546. int compareElements (const ZipFile::ZipEntryInfo* first, const ZipFile::ZipEntryInfo* second)
  8547. {
  8548. return first->entry.filename.compare (second->entry.filename);
  8549. }
  8550. };
  8551. void ZipFile::sortEntriesByFilename()
  8552. {
  8553. ZipFilenameComparator sorter;
  8554. entries.sort (sorter);
  8555. }
  8556. void ZipFile::init()
  8557. {
  8558. ScopedPointer <InputStream> toDelete;
  8559. InputStream* in = inputStream;
  8560. if (inputSource != 0)
  8561. {
  8562. in = inputSource->createInputStream();
  8563. toDelete = in;
  8564. }
  8565. if (in != 0)
  8566. {
  8567. int numEntries = 0;
  8568. int pos = findEndOfZipEntryTable (*in, numEntries);
  8569. if (pos >= 0 && pos < in->getTotalLength())
  8570. {
  8571. const int size = (int) (in->getTotalLength() - pos);
  8572. in->setPosition (pos);
  8573. MemoryBlock headerData;
  8574. if (in->readIntoMemoryBlock (headerData, size) == size)
  8575. {
  8576. pos = 0;
  8577. for (int i = 0; i < numEntries; ++i)
  8578. {
  8579. if (pos + 46 > size)
  8580. break;
  8581. const char* const buffer = static_cast <const char*> (headerData.getData()) + pos;
  8582. const int fileNameLen = ByteOrder::littleEndianShort (buffer + 28);
  8583. if (pos + 46 + fileNameLen > size)
  8584. break;
  8585. ZipEntryInfo* const zei = new ZipEntryInfo();
  8586. zei->entry.filename = String::fromUTF8 (buffer + 46, fileNameLen);
  8587. const int time = ByteOrder::littleEndianShort (buffer + 12);
  8588. const int date = ByteOrder::littleEndianShort (buffer + 14);
  8589. const int year = 1980 + (date >> 9);
  8590. const int month = ((date >> 5) & 15) - 1;
  8591. const int day = date & 31;
  8592. const int hours = time >> 11;
  8593. const int minutes = (time >> 5) & 63;
  8594. const int seconds = (time & 31) << 1;
  8595. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  8596. zei->compressed = ByteOrder::littleEndianShort (buffer + 10) != 0;
  8597. zei->compressedSize = ByteOrder::littleEndianInt (buffer + 20);
  8598. zei->entry.uncompressedSize = ByteOrder::littleEndianInt (buffer + 24);
  8599. zei->streamOffset = ByteOrder::littleEndianInt (buffer + 42);
  8600. entries.add (zei);
  8601. pos += 46 + fileNameLen
  8602. + ByteOrder::littleEndianShort (buffer + 30)
  8603. + ByteOrder::littleEndianShort (buffer + 32);
  8604. }
  8605. }
  8606. }
  8607. }
  8608. }
  8609. int ZipFile::findEndOfZipEntryTable (InputStream& input, int& numEntries)
  8610. {
  8611. BufferedInputStream in (input, 8192);
  8612. in.setPosition (in.getTotalLength());
  8613. int64 pos = in.getPosition();
  8614. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  8615. char buffer [32];
  8616. zeromem (buffer, sizeof (buffer));
  8617. while (pos > lowestPos)
  8618. {
  8619. in.setPosition (pos - 22);
  8620. pos = in.getPosition();
  8621. memcpy (buffer + 22, buffer, 4);
  8622. if (in.read (buffer, 22) != 22)
  8623. return 0;
  8624. for (int i = 0; i < 22; ++i)
  8625. {
  8626. if (ByteOrder::littleEndianInt (buffer + i) == 0x06054b50)
  8627. {
  8628. in.setPosition (pos + i);
  8629. in.read (buffer, 22);
  8630. numEntries = ByteOrder::littleEndianShort (buffer + 10);
  8631. return ByteOrder::littleEndianInt (buffer + 16);
  8632. }
  8633. }
  8634. }
  8635. return 0;
  8636. }
  8637. bool ZipFile::uncompressTo (const File& targetDirectory,
  8638. const bool shouldOverwriteFiles)
  8639. {
  8640. for (int i = 0; i < entries.size(); ++i)
  8641. if (! uncompressEntry (i, targetDirectory, shouldOverwriteFiles))
  8642. return false;
  8643. return true;
  8644. }
  8645. bool ZipFile::uncompressEntry (const int index,
  8646. const File& targetDirectory,
  8647. bool shouldOverwriteFiles)
  8648. {
  8649. const ZipEntryInfo* zei = entries [index];
  8650. if (zei != 0)
  8651. {
  8652. const File targetFile (targetDirectory.getChildFile (zei->entry.filename));
  8653. if (zei->entry.filename.endsWithChar ('/'))
  8654. {
  8655. return targetFile.createDirectory(); // (entry is a directory, not a file)
  8656. }
  8657. else
  8658. {
  8659. ScopedPointer<InputStream> in (createStreamForEntry (index));
  8660. if (in != 0)
  8661. {
  8662. if (shouldOverwriteFiles && ! targetFile.deleteFile())
  8663. return false;
  8664. if ((! targetFile.exists()) && targetFile.getParentDirectory().createDirectory())
  8665. {
  8666. ScopedPointer<FileOutputStream> out (targetFile.createOutputStream());
  8667. if (out != 0)
  8668. {
  8669. out->writeFromInputStream (*in, -1);
  8670. out = 0;
  8671. targetFile.setCreationTime (zei->entry.fileTime);
  8672. targetFile.setLastModificationTime (zei->entry.fileTime);
  8673. targetFile.setLastAccessTime (zei->entry.fileTime);
  8674. return true;
  8675. }
  8676. }
  8677. }
  8678. }
  8679. }
  8680. return false;
  8681. }
  8682. END_JUCE_NAMESPACE
  8683. /*** End of inlined file: juce_ZipFile.cpp ***/
  8684. /*** Start of inlined file: juce_CharacterFunctions.cpp ***/
  8685. #if JUCE_MSVC
  8686. #pragma warning (push)
  8687. #pragma warning (disable: 4514 4996)
  8688. #endif
  8689. #include <cwctype>
  8690. #include <cctype>
  8691. #include <ctime>
  8692. BEGIN_JUCE_NAMESPACE
  8693. int CharacterFunctions::length (const char* const s) throw()
  8694. {
  8695. return (int) strlen (s);
  8696. }
  8697. int CharacterFunctions::length (const juce_wchar* const s) throw()
  8698. {
  8699. return (int) wcslen (s);
  8700. }
  8701. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  8702. {
  8703. strncpy (dest, src, maxChars);
  8704. }
  8705. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  8706. {
  8707. wcsncpy (dest, src, maxChars);
  8708. }
  8709. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  8710. {
  8711. mbstowcs (dest, src, maxChars);
  8712. }
  8713. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  8714. {
  8715. wcstombs (dest, src, maxChars);
  8716. }
  8717. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  8718. {
  8719. return (int) wcstombs (0, src, 0);
  8720. }
  8721. void CharacterFunctions::append (char* dest, const char* src) throw()
  8722. {
  8723. strcat (dest, src);
  8724. }
  8725. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  8726. {
  8727. wcscat (dest, src);
  8728. }
  8729. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  8730. {
  8731. return strcmp (s1, s2);
  8732. }
  8733. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  8734. {
  8735. jassert (s1 != 0 && s2 != 0);
  8736. return wcscmp (s1, s2);
  8737. }
  8738. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  8739. {
  8740. jassert (s1 != 0 && s2 != 0);
  8741. return strncmp (s1, s2, maxChars);
  8742. }
  8743. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8744. {
  8745. jassert (s1 != 0 && s2 != 0);
  8746. return wcsncmp (s1, s2, maxChars);
  8747. }
  8748. int CharacterFunctions::compare (const juce_wchar* s1, const char* s2) throw()
  8749. {
  8750. jassert (s1 != 0 && s2 != 0);
  8751. for (;;)
  8752. {
  8753. const int diff = (int) (*s1 - (juce_wchar) (unsigned char) *s2);
  8754. if (diff != 0)
  8755. return diff;
  8756. else if (*s1 == 0)
  8757. break;
  8758. ++s1;
  8759. ++s2;
  8760. }
  8761. return 0;
  8762. }
  8763. int CharacterFunctions::compare (const char* s1, const juce_wchar* s2) throw()
  8764. {
  8765. return -compare (s2, s1);
  8766. }
  8767. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  8768. {
  8769. jassert (s1 != 0 && s2 != 0);
  8770. #if JUCE_WINDOWS
  8771. return stricmp (s1, s2);
  8772. #else
  8773. return strcasecmp (s1, s2);
  8774. #endif
  8775. }
  8776. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  8777. {
  8778. jassert (s1 != 0 && s2 != 0);
  8779. #if JUCE_WINDOWS
  8780. return _wcsicmp (s1, s2);
  8781. #else
  8782. for (;;)
  8783. {
  8784. if (*s1 != *s2)
  8785. {
  8786. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8787. if (diff != 0)
  8788. return diff < 0 ? -1 : 1;
  8789. }
  8790. else if (*s1 == 0)
  8791. break;
  8792. ++s1;
  8793. ++s2;
  8794. }
  8795. return 0;
  8796. #endif
  8797. }
  8798. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const char* s2) throw()
  8799. {
  8800. jassert (s1 != 0 && s2 != 0);
  8801. for (;;)
  8802. {
  8803. if (*s1 != *s2)
  8804. {
  8805. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8806. if (diff != 0)
  8807. return diff < 0 ? -1 : 1;
  8808. }
  8809. else if (*s1 == 0)
  8810. break;
  8811. ++s1;
  8812. ++s2;
  8813. }
  8814. return 0;
  8815. }
  8816. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  8817. {
  8818. jassert (s1 != 0 && s2 != 0);
  8819. #if JUCE_WINDOWS
  8820. return strnicmp (s1, s2, maxChars);
  8821. #else
  8822. return strncasecmp (s1, s2, maxChars);
  8823. #endif
  8824. }
  8825. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  8826. {
  8827. jassert (s1 != 0 && s2 != 0);
  8828. #if JUCE_WINDOWS
  8829. return _wcsnicmp (s1, s2, maxChars);
  8830. #else
  8831. while (--maxChars >= 0)
  8832. {
  8833. if (*s1 != *s2)
  8834. {
  8835. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  8836. if (diff != 0)
  8837. return diff < 0 ? -1 : 1;
  8838. }
  8839. else if (*s1 == 0)
  8840. break;
  8841. ++s1;
  8842. ++s2;
  8843. }
  8844. return 0;
  8845. #endif
  8846. }
  8847. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  8848. {
  8849. return strstr (haystack, needle);
  8850. }
  8851. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  8852. {
  8853. return wcsstr (haystack, needle);
  8854. }
  8855. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  8856. {
  8857. if (haystack != 0)
  8858. {
  8859. int i = 0;
  8860. if (ignoreCase)
  8861. {
  8862. const char n1 = toLowerCase (needle);
  8863. const char n2 = toUpperCase (needle);
  8864. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8865. {
  8866. while (haystack[i] != 0)
  8867. {
  8868. if (haystack[i] == n1 || haystack[i] == n2)
  8869. return i;
  8870. ++i;
  8871. }
  8872. return -1;
  8873. }
  8874. jassert (n1 == needle);
  8875. }
  8876. while (haystack[i] != 0)
  8877. {
  8878. if (haystack[i] == needle)
  8879. return i;
  8880. ++i;
  8881. }
  8882. }
  8883. return -1;
  8884. }
  8885. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  8886. {
  8887. if (haystack != 0)
  8888. {
  8889. int i = 0;
  8890. if (ignoreCase)
  8891. {
  8892. const juce_wchar n1 = toLowerCase (needle);
  8893. const juce_wchar n2 = toUpperCase (needle);
  8894. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  8895. {
  8896. while (haystack[i] != 0)
  8897. {
  8898. if (haystack[i] == n1 || haystack[i] == n2)
  8899. return i;
  8900. ++i;
  8901. }
  8902. return -1;
  8903. }
  8904. jassert (n1 == needle);
  8905. }
  8906. while (haystack[i] != 0)
  8907. {
  8908. if (haystack[i] == needle)
  8909. return i;
  8910. ++i;
  8911. }
  8912. }
  8913. return -1;
  8914. }
  8915. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  8916. {
  8917. jassert (haystack != 0);
  8918. int i = 0;
  8919. while (haystack[i] != 0)
  8920. {
  8921. if (haystack[i] == needle)
  8922. return i;
  8923. ++i;
  8924. }
  8925. return -1;
  8926. }
  8927. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  8928. {
  8929. jassert (haystack != 0);
  8930. int i = 0;
  8931. while (haystack[i] != 0)
  8932. {
  8933. if (haystack[i] == needle)
  8934. return i;
  8935. ++i;
  8936. }
  8937. return -1;
  8938. }
  8939. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  8940. {
  8941. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  8942. }
  8943. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  8944. {
  8945. if (allowedChars == 0)
  8946. return 0;
  8947. int i = 0;
  8948. for (;;)
  8949. {
  8950. if (indexOfCharFast (allowedChars, text[i]) < 0)
  8951. break;
  8952. ++i;
  8953. }
  8954. return i;
  8955. }
  8956. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  8957. {
  8958. return (int) strftime (dest, maxChars, format, tm);
  8959. }
  8960. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  8961. {
  8962. return (int) wcsftime (dest, maxChars, format, tm);
  8963. }
  8964. int CharacterFunctions::getIntValue (const char* const s) throw()
  8965. {
  8966. return atoi (s);
  8967. }
  8968. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  8969. {
  8970. #if JUCE_WINDOWS
  8971. return _wtoi (s);
  8972. #else
  8973. int v = 0;
  8974. while (isWhitespace (*s))
  8975. ++s;
  8976. const bool isNeg = *s == '-';
  8977. if (isNeg)
  8978. ++s;
  8979. for (;;)
  8980. {
  8981. const wchar_t c = *s++;
  8982. if (c >= '0' && c <= '9')
  8983. v = v * 10 + (int) (c - '0');
  8984. else
  8985. break;
  8986. }
  8987. return isNeg ? -v : v;
  8988. #endif
  8989. }
  8990. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  8991. {
  8992. #if JUCE_LINUX
  8993. return atoll (s);
  8994. #elif JUCE_WINDOWS
  8995. return _atoi64 (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 char 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. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  9015. {
  9016. #if JUCE_WINDOWS
  9017. return _wtoi64 (s);
  9018. #else
  9019. int64 v = 0;
  9020. while (isWhitespace (*s))
  9021. ++s;
  9022. const bool isNeg = *s == '-';
  9023. if (isNeg)
  9024. ++s;
  9025. for (;;)
  9026. {
  9027. const juce_wchar c = *s++;
  9028. if (c >= '0' && c <= '9')
  9029. v = v * 10 + (int64) (c - '0');
  9030. else
  9031. break;
  9032. }
  9033. return isNeg ? -v : v;
  9034. #endif
  9035. }
  9036. namespace
  9037. {
  9038. double juce_mulexp10 (const double value, int exponent) throw()
  9039. {
  9040. if (exponent == 0)
  9041. return value;
  9042. if (value == 0)
  9043. return 0;
  9044. const bool negative = (exponent < 0);
  9045. if (negative)
  9046. exponent = -exponent;
  9047. double result = 1.0, power = 10.0;
  9048. for (int bit = 1; exponent != 0; bit <<= 1)
  9049. {
  9050. if ((exponent & bit) != 0)
  9051. {
  9052. exponent ^= bit;
  9053. result *= power;
  9054. if (exponent == 0)
  9055. break;
  9056. }
  9057. power *= power;
  9058. }
  9059. return negative ? (value / result) : (value * result);
  9060. }
  9061. template <class CharType>
  9062. double juce_atof (const CharType* const original) throw()
  9063. {
  9064. double result[3] = { 0, 0, 0 }, accumulator[2] = { 0, 0 };
  9065. int exponentAdjustment[2] = { 0, 0 }, exponentAccumulator[2] = { -1, -1 };
  9066. int exponent = 0, decPointIndex = 0, digit = 0;
  9067. int lastDigit = 0, numSignificantDigits = 0;
  9068. bool isNegative = false, digitsFound = false;
  9069. const int maxSignificantDigits = 15 + 2;
  9070. const CharType* s = original;
  9071. while (CharacterFunctions::isWhitespace (*s))
  9072. ++s;
  9073. switch (*s)
  9074. {
  9075. case '-': isNegative = true; // fall-through..
  9076. case '+': ++s;
  9077. }
  9078. if (*s == 'n' || *s == 'N' || *s == 'i' || *s == 'I')
  9079. return atof (String (original).toUTF8()); // Let the c library deal with NAN and INF
  9080. for (;;)
  9081. {
  9082. if (CharacterFunctions::isDigit (*s))
  9083. {
  9084. lastDigit = digit;
  9085. digit = *s++ - '0';
  9086. digitsFound = true;
  9087. if (decPointIndex != 0)
  9088. exponentAdjustment[1]++;
  9089. if (numSignificantDigits == 0 && digit == 0)
  9090. continue;
  9091. if (++numSignificantDigits > maxSignificantDigits)
  9092. {
  9093. if (digit > 5)
  9094. ++accumulator [decPointIndex];
  9095. else if (digit == 5 && (lastDigit & 1) != 0)
  9096. ++accumulator [decPointIndex];
  9097. if (decPointIndex > 0)
  9098. exponentAdjustment[1]--;
  9099. else
  9100. exponentAdjustment[0]++;
  9101. while (CharacterFunctions::isDigit (*s))
  9102. {
  9103. ++s;
  9104. if (decPointIndex == 0)
  9105. exponentAdjustment[0]++;
  9106. }
  9107. }
  9108. else
  9109. {
  9110. const double maxAccumulatorValue = (double) ((std::numeric_limits<unsigned int>::max() - 9) / 10);
  9111. if (accumulator [decPointIndex] > maxAccumulatorValue)
  9112. {
  9113. result [decPointIndex] = juce_mulexp10 (result [decPointIndex], exponentAccumulator [decPointIndex])
  9114. + accumulator [decPointIndex];
  9115. accumulator [decPointIndex] = 0;
  9116. exponentAccumulator [decPointIndex] = 0;
  9117. }
  9118. accumulator [decPointIndex] = accumulator[decPointIndex] * 10 + digit;
  9119. exponentAccumulator [decPointIndex]++;
  9120. }
  9121. }
  9122. else if (decPointIndex == 0 && *s == '.')
  9123. {
  9124. ++s;
  9125. decPointIndex = 1;
  9126. if (numSignificantDigits > maxSignificantDigits)
  9127. {
  9128. while (CharacterFunctions::isDigit (*s))
  9129. ++s;
  9130. break;
  9131. }
  9132. }
  9133. else
  9134. {
  9135. break;
  9136. }
  9137. }
  9138. result[0] = juce_mulexp10 (result[0], exponentAccumulator[0]) + accumulator[0];
  9139. if (decPointIndex != 0)
  9140. result[1] = juce_mulexp10 (result[1], exponentAccumulator[1]) + accumulator[1];
  9141. if ((*s == 'e' || *s == 'E') && digitsFound)
  9142. {
  9143. bool negativeExponent = false;
  9144. switch (*++s)
  9145. {
  9146. case '-': negativeExponent = true; // fall-through..
  9147. case '+': ++s;
  9148. }
  9149. while (CharacterFunctions::isDigit (*s))
  9150. exponent = (exponent * 10) + (*s++ - '0');
  9151. if (negativeExponent)
  9152. exponent = -exponent;
  9153. }
  9154. double r = juce_mulexp10 (result[0], exponent + exponentAdjustment[0]);
  9155. if (decPointIndex != 0)
  9156. r += juce_mulexp10 (result[1], exponent - exponentAdjustment[1]);
  9157. return isNegative ? -r : r;
  9158. }
  9159. }
  9160. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  9161. {
  9162. return juce_atof <char> (s);
  9163. }
  9164. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  9165. {
  9166. return juce_atof <juce_wchar> (s);
  9167. }
  9168. char CharacterFunctions::toUpperCase (const char character) throw()
  9169. {
  9170. return (char) toupper (character);
  9171. }
  9172. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  9173. {
  9174. return towupper (character);
  9175. }
  9176. void CharacterFunctions::toUpperCase (char* s) throw()
  9177. {
  9178. #if JUCE_WINDOWS
  9179. strupr (s);
  9180. #else
  9181. while (*s != 0)
  9182. {
  9183. *s = toUpperCase (*s);
  9184. ++s;
  9185. }
  9186. #endif
  9187. }
  9188. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  9189. {
  9190. #if JUCE_WINDOWS
  9191. _wcsupr (s);
  9192. #else
  9193. while (*s != 0)
  9194. {
  9195. *s = toUpperCase (*s);
  9196. ++s;
  9197. }
  9198. #endif
  9199. }
  9200. bool CharacterFunctions::isUpperCase (const char character) throw()
  9201. {
  9202. return isupper (character) != 0;
  9203. }
  9204. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  9205. {
  9206. #if JUCE_WINDOWS
  9207. return iswupper (character) != 0;
  9208. #else
  9209. return toLowerCase (character) != character;
  9210. #endif
  9211. }
  9212. char CharacterFunctions::toLowerCase (const char character) throw()
  9213. {
  9214. return (char) tolower (character);
  9215. }
  9216. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  9217. {
  9218. return towlower (character);
  9219. }
  9220. void CharacterFunctions::toLowerCase (char* s) throw()
  9221. {
  9222. #if JUCE_WINDOWS
  9223. strlwr (s);
  9224. #else
  9225. while (*s != 0)
  9226. {
  9227. *s = toLowerCase (*s);
  9228. ++s;
  9229. }
  9230. #endif
  9231. }
  9232. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  9233. {
  9234. #if JUCE_WINDOWS
  9235. _wcslwr (s);
  9236. #else
  9237. while (*s != 0)
  9238. {
  9239. *s = toLowerCase (*s);
  9240. ++s;
  9241. }
  9242. #endif
  9243. }
  9244. bool CharacterFunctions::isLowerCase (const char character) throw()
  9245. {
  9246. return islower (character) != 0;
  9247. }
  9248. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  9249. {
  9250. #if JUCE_WINDOWS
  9251. return iswlower (character) != 0;
  9252. #else
  9253. return toUpperCase (character) != character;
  9254. #endif
  9255. }
  9256. bool CharacterFunctions::isWhitespace (const char character) throw()
  9257. {
  9258. return character == ' ' || (character <= 13 && character >= 9);
  9259. }
  9260. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  9261. {
  9262. return iswspace (character) != 0;
  9263. }
  9264. bool CharacterFunctions::isDigit (const char character) throw()
  9265. {
  9266. return (character >= '0' && character <= '9');
  9267. }
  9268. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  9269. {
  9270. return iswdigit (character) != 0;
  9271. }
  9272. bool CharacterFunctions::isLetter (const char character) throw()
  9273. {
  9274. return (character >= 'a' && character <= 'z')
  9275. || (character >= 'A' && character <= 'Z');
  9276. }
  9277. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  9278. {
  9279. return iswalpha (character) != 0;
  9280. }
  9281. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  9282. {
  9283. return (character >= 'a' && character <= 'z')
  9284. || (character >= 'A' && character <= 'Z')
  9285. || (character >= '0' && character <= '9');
  9286. }
  9287. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  9288. {
  9289. return iswalnum (character) != 0;
  9290. }
  9291. int CharacterFunctions::getHexDigitValue (const juce_wchar digit) throw()
  9292. {
  9293. unsigned int d = digit - '0';
  9294. if (d < (unsigned int) 10)
  9295. return (int) d;
  9296. d += (unsigned int) ('0' - 'a');
  9297. if (d < (unsigned int) 6)
  9298. return (int) d + 10;
  9299. d += (unsigned int) ('a' - 'A');
  9300. if (d < (unsigned int) 6)
  9301. return (int) d + 10;
  9302. return -1;
  9303. }
  9304. #if JUCE_MSVC
  9305. #pragma warning (pop)
  9306. #endif
  9307. END_JUCE_NAMESPACE
  9308. /*** End of inlined file: juce_CharacterFunctions.cpp ***/
  9309. /*** Start of inlined file: juce_LocalisedStrings.cpp ***/
  9310. BEGIN_JUCE_NAMESPACE
  9311. LocalisedStrings::LocalisedStrings (const String& fileContents)
  9312. {
  9313. loadFromText (fileContents);
  9314. }
  9315. LocalisedStrings::LocalisedStrings (const File& fileToLoad)
  9316. {
  9317. loadFromText (fileToLoad.loadFileAsString());
  9318. }
  9319. LocalisedStrings::~LocalisedStrings()
  9320. {
  9321. }
  9322. const String LocalisedStrings::translate (const String& text) const
  9323. {
  9324. return translations.getValue (text, text);
  9325. }
  9326. namespace
  9327. {
  9328. CriticalSection currentMappingsLock;
  9329. LocalisedStrings* currentMappings = 0;
  9330. int findCloseQuote (const String& text, int startPos)
  9331. {
  9332. juce_wchar lastChar = 0;
  9333. for (;;)
  9334. {
  9335. const juce_wchar c = text [startPos];
  9336. if (c == 0 || (c == '"' && lastChar != '\\'))
  9337. break;
  9338. lastChar = c;
  9339. ++startPos;
  9340. }
  9341. return startPos;
  9342. }
  9343. const String unescapeString (const String& s)
  9344. {
  9345. return s.replace ("\\\"", "\"")
  9346. .replace ("\\\'", "\'")
  9347. .replace ("\\t", "\t")
  9348. .replace ("\\r", "\r")
  9349. .replace ("\\n", "\n");
  9350. }
  9351. }
  9352. void LocalisedStrings::loadFromText (const String& fileContents)
  9353. {
  9354. StringArray lines;
  9355. lines.addLines (fileContents);
  9356. for (int i = 0; i < lines.size(); ++i)
  9357. {
  9358. String line (lines[i].trim());
  9359. if (line.startsWithChar ('"'))
  9360. {
  9361. int closeQuote = findCloseQuote (line, 1);
  9362. const String originalText (unescapeString (line.substring (1, closeQuote)));
  9363. if (originalText.isNotEmpty())
  9364. {
  9365. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  9366. closeQuote = findCloseQuote (line, openingQuote + 1);
  9367. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  9368. if (newText.isNotEmpty())
  9369. translations.set (originalText, newText);
  9370. }
  9371. }
  9372. else if (line.startsWithIgnoreCase ("language:"))
  9373. {
  9374. languageName = line.substring (9).trim();
  9375. }
  9376. else if (line.startsWithIgnoreCase ("countries:"))
  9377. {
  9378. countryCodes.addTokens (line.substring (10).trim(), true);
  9379. countryCodes.trim();
  9380. countryCodes.removeEmptyStrings();
  9381. }
  9382. }
  9383. }
  9384. void LocalisedStrings::setIgnoresCase (const bool shouldIgnoreCase)
  9385. {
  9386. translations.setIgnoresCase (shouldIgnoreCase);
  9387. }
  9388. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations)
  9389. {
  9390. const ScopedLock sl (currentMappingsLock);
  9391. delete currentMappings;
  9392. currentMappings = newTranslations;
  9393. }
  9394. LocalisedStrings* LocalisedStrings::getCurrentMappings()
  9395. {
  9396. return currentMappings;
  9397. }
  9398. const String LocalisedStrings::translateWithCurrentMappings (const String& text)
  9399. {
  9400. const ScopedLock sl (currentMappingsLock);
  9401. if (currentMappings != 0)
  9402. return currentMappings->translate (text);
  9403. return text;
  9404. }
  9405. const String LocalisedStrings::translateWithCurrentMappings (const char* text)
  9406. {
  9407. return translateWithCurrentMappings (String (text));
  9408. }
  9409. END_JUCE_NAMESPACE
  9410. /*** End of inlined file: juce_LocalisedStrings.cpp ***/
  9411. /*** Start of inlined file: juce_String.cpp ***/
  9412. #if JUCE_MSVC
  9413. #pragma warning (push)
  9414. #pragma warning (disable: 4514)
  9415. #endif
  9416. #include <locale>
  9417. BEGIN_JUCE_NAMESPACE
  9418. #if JUCE_MSVC
  9419. #pragma warning (pop)
  9420. #endif
  9421. #if defined (JUCE_STRINGS_ARE_UNICODE) && ! JUCE_STRINGS_ARE_UNICODE
  9422. #error "JUCE_STRINGS_ARE_UNICODE is deprecated! All strings are now unicode by default."
  9423. #endif
  9424. class StringHolder
  9425. {
  9426. public:
  9427. StringHolder()
  9428. : refCount (0x3fffffff), allocatedNumChars (0)
  9429. {
  9430. text[0] = 0;
  9431. }
  9432. static juce_wchar* createUninitialised (const size_t numChars)
  9433. {
  9434. StringHolder* const s = reinterpret_cast <StringHolder*> (new char [sizeof (StringHolder) + numChars * sizeof (juce_wchar)]);
  9435. s->refCount.value = 0;
  9436. s->allocatedNumChars = numChars;
  9437. return &(s->text[0]);
  9438. }
  9439. static juce_wchar* createCopy (const juce_wchar* const src, const size_t numChars)
  9440. {
  9441. juce_wchar* const dest = createUninitialised (numChars);
  9442. copyChars (dest, src, numChars);
  9443. return dest;
  9444. }
  9445. static juce_wchar* createCopy (const char* const src, const size_t numChars)
  9446. {
  9447. juce_wchar* const dest = createUninitialised (numChars);
  9448. CharacterFunctions::copy (dest, src, (int) numChars);
  9449. dest [numChars] = 0;
  9450. return dest;
  9451. }
  9452. static inline juce_wchar* getEmpty() throw()
  9453. {
  9454. return &(empty.text[0]);
  9455. }
  9456. static void retain (juce_wchar* const text) throw()
  9457. {
  9458. ++(bufferFromText (text)->refCount);
  9459. }
  9460. static inline void release (StringHolder* const b) throw()
  9461. {
  9462. if (--(b->refCount) == -1 && b != &empty)
  9463. delete[] reinterpret_cast <char*> (b);
  9464. }
  9465. static void release (juce_wchar* const text) throw()
  9466. {
  9467. release (bufferFromText (text));
  9468. }
  9469. static juce_wchar* makeUnique (juce_wchar* const text)
  9470. {
  9471. StringHolder* const b = bufferFromText (text);
  9472. if (b->refCount.get() <= 0)
  9473. return text;
  9474. juce_wchar* const newText = createCopy (text, b->allocatedNumChars);
  9475. release (b);
  9476. return newText;
  9477. }
  9478. static juce_wchar* makeUniqueWithSize (juce_wchar* const text, size_t numChars)
  9479. {
  9480. StringHolder* const b = bufferFromText (text);
  9481. if (b->refCount.get() <= 0 && b->allocatedNumChars >= numChars)
  9482. return text;
  9483. juce_wchar* const newText = createUninitialised (jmax (b->allocatedNumChars, numChars));
  9484. copyChars (newText, text, b->allocatedNumChars);
  9485. release (b);
  9486. return newText;
  9487. }
  9488. static size_t getAllocatedNumChars (juce_wchar* const text) throw()
  9489. {
  9490. return bufferFromText (text)->allocatedNumChars;
  9491. }
  9492. static void copyChars (juce_wchar* const dest, const juce_wchar* const src, const size_t numChars) throw()
  9493. {
  9494. jassert (src != 0 && dest != 0);
  9495. memcpy (dest, src, numChars * sizeof (juce_wchar));
  9496. dest [numChars] = 0;
  9497. }
  9498. Atomic<int> refCount;
  9499. size_t allocatedNumChars;
  9500. juce_wchar text[1];
  9501. static StringHolder empty;
  9502. private:
  9503. static inline StringHolder* bufferFromText (void* const text) throw()
  9504. {
  9505. // (Can't use offsetof() here because of warnings about this not being a POD)
  9506. return reinterpret_cast <StringHolder*> (static_cast <char*> (text)
  9507. - (reinterpret_cast <size_t> (reinterpret_cast <StringHolder*> (1)->text) - 1));
  9508. }
  9509. };
  9510. StringHolder StringHolder::empty;
  9511. const String String::empty;
  9512. void String::createInternal (const juce_wchar* const t, const size_t numChars)
  9513. {
  9514. jassert (t[numChars] == 0); // must have a null terminator
  9515. text = StringHolder::createCopy (t, numChars);
  9516. }
  9517. void String::appendInternal (const juce_wchar* const newText, const int numExtraChars)
  9518. {
  9519. if (numExtraChars > 0)
  9520. {
  9521. const int oldLen = length();
  9522. const int newTotalLen = oldLen + numExtraChars;
  9523. text = StringHolder::makeUniqueWithSize (text, newTotalLen);
  9524. StringHolder::copyChars (text + oldLen, newText, numExtraChars);
  9525. }
  9526. }
  9527. void String::preallocateStorage (const size_t numChars)
  9528. {
  9529. text = StringHolder::makeUniqueWithSize (text, numChars);
  9530. }
  9531. String::String() throw()
  9532. : text (StringHolder::getEmpty())
  9533. {
  9534. }
  9535. String::~String() throw()
  9536. {
  9537. StringHolder::release (text);
  9538. }
  9539. String::String (const String& other) throw()
  9540. : text (other.text)
  9541. {
  9542. StringHolder::retain (text);
  9543. }
  9544. void String::swapWith (String& other) throw()
  9545. {
  9546. swapVariables (text, other.text);
  9547. }
  9548. String& String::operator= (const String& other) throw()
  9549. {
  9550. juce_wchar* const newText = other.text;
  9551. StringHolder::retain (newText);
  9552. StringHolder::release (reinterpret_cast <Atomic<juce_wchar*>*> (&text)->exchange (newText));
  9553. return *this;
  9554. }
  9555. String::String (const size_t numChars, const int /*dummyVariable*/)
  9556. : text (StringHolder::createUninitialised (numChars))
  9557. {
  9558. }
  9559. String::String (const String& stringToCopy, const size_t charsToAllocate)
  9560. {
  9561. const size_t otherSize = StringHolder::getAllocatedNumChars (stringToCopy.text);
  9562. text = StringHolder::createUninitialised (jmax (charsToAllocate, otherSize));
  9563. StringHolder::copyChars (text, stringToCopy.text, otherSize);
  9564. }
  9565. String::String (const char* const t)
  9566. {
  9567. if (t != 0 && *t != 0)
  9568. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9569. else
  9570. text = StringHolder::getEmpty();
  9571. }
  9572. String::String (const juce_wchar* const t)
  9573. {
  9574. if (t != 0 && *t != 0)
  9575. text = StringHolder::createCopy (t, CharacterFunctions::length (t));
  9576. else
  9577. text = StringHolder::getEmpty();
  9578. }
  9579. String::String (const char* const t, const size_t maxChars)
  9580. {
  9581. int i;
  9582. for (i = 0; (size_t) i < maxChars; ++i)
  9583. if (t[i] == 0)
  9584. break;
  9585. if (i > 0)
  9586. text = StringHolder::createCopy (t, i);
  9587. else
  9588. text = StringHolder::getEmpty();
  9589. }
  9590. String::String (const juce_wchar* const t, const size_t maxChars)
  9591. {
  9592. int i;
  9593. for (i = 0; (size_t) i < maxChars; ++i)
  9594. if (t[i] == 0)
  9595. break;
  9596. if (i > 0)
  9597. text = StringHolder::createCopy (t, i);
  9598. else
  9599. text = StringHolder::getEmpty();
  9600. }
  9601. const String String::charToString (const juce_wchar character)
  9602. {
  9603. String result ((size_t) 1, (int) 0);
  9604. result.text[0] = character;
  9605. result.text[1] = 0;
  9606. return result;
  9607. }
  9608. namespace NumberToStringConverters
  9609. {
  9610. // pass in a pointer to the END of a buffer..
  9611. static juce_wchar* int64ToString (juce_wchar* t, const int64 n) throw()
  9612. {
  9613. *--t = 0;
  9614. int64 v = (n >= 0) ? n : -n;
  9615. do
  9616. {
  9617. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9618. v /= 10;
  9619. } while (v > 0);
  9620. if (n < 0)
  9621. *--t = '-';
  9622. return t;
  9623. }
  9624. static juce_wchar* uint64ToString (juce_wchar* t, int64 v) throw()
  9625. {
  9626. *--t = 0;
  9627. do
  9628. {
  9629. *--t = (juce_wchar) ('0' + (int) (v % 10));
  9630. v /= 10;
  9631. } while (v > 0);
  9632. return t;
  9633. }
  9634. static juce_wchar* intToString (juce_wchar* t, const int n) throw()
  9635. {
  9636. if (n == (int) 0x80000000) // (would cause an overflow)
  9637. return int64ToString (t, n);
  9638. *--t = 0;
  9639. int v = abs (n);
  9640. do
  9641. {
  9642. *--t = (juce_wchar) ('0' + (v % 10));
  9643. v /= 10;
  9644. } while (v > 0);
  9645. if (n < 0)
  9646. *--t = '-';
  9647. return t;
  9648. }
  9649. static juce_wchar* uintToString (juce_wchar* t, unsigned int v) throw()
  9650. {
  9651. *--t = 0;
  9652. do
  9653. {
  9654. *--t = (juce_wchar) ('0' + (v % 10));
  9655. v /= 10;
  9656. } while (v > 0);
  9657. return t;
  9658. }
  9659. static juce_wchar getDecimalPoint()
  9660. {
  9661. #if JUCE_MSVC && _MSC_VER < 1400
  9662. static juce_wchar dp = std::_USE (std::locale(), std::numpunct <wchar_t>).decimal_point();
  9663. #else
  9664. static juce_wchar dp = std::use_facet <std::numpunct <wchar_t> > (std::locale()).decimal_point();
  9665. #endif
  9666. return dp;
  9667. }
  9668. static juce_wchar* doubleToString (juce_wchar* buffer, int numChars, double n, int numDecPlaces, size_t& len) throw()
  9669. {
  9670. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  9671. {
  9672. juce_wchar* const end = buffer + numChars;
  9673. juce_wchar* t = end;
  9674. int64 v = (int64) (pow (10.0, numDecPlaces) * std::abs (n) + 0.5);
  9675. *--t = (juce_wchar) 0;
  9676. while (numDecPlaces >= 0 || v > 0)
  9677. {
  9678. if (numDecPlaces == 0)
  9679. *--t = getDecimalPoint();
  9680. *--t = (juce_wchar) ('0' + (v % 10));
  9681. v /= 10;
  9682. --numDecPlaces;
  9683. }
  9684. if (n < 0)
  9685. *--t = '-';
  9686. len = end - t - 1;
  9687. return t;
  9688. }
  9689. else
  9690. {
  9691. #if JUCE_WINDOWS
  9692. #if JUCE_MSVC && _MSC_VER <= 1400
  9693. len = _snwprintf (buffer, numChars, L"%.9g", n);
  9694. #else
  9695. len = _snwprintf_s (buffer, numChars, _TRUNCATE, L"%.9g", n);
  9696. #endif
  9697. #else
  9698. len = swprintf (buffer, numChars, L"%.9g", n);
  9699. #endif
  9700. return buffer;
  9701. }
  9702. }
  9703. }
  9704. String::String (const int number)
  9705. {
  9706. juce_wchar buffer [16];
  9707. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9708. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9709. createInternal (start, end - start - 1);
  9710. }
  9711. String::String (const unsigned int number)
  9712. {
  9713. juce_wchar buffer [16];
  9714. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9715. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9716. createInternal (start, end - start - 1);
  9717. }
  9718. String::String (const short number)
  9719. {
  9720. juce_wchar buffer [16];
  9721. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9722. juce_wchar* const start = NumberToStringConverters::intToString (end, (int) number);
  9723. createInternal (start, end - start - 1);
  9724. }
  9725. String::String (const unsigned short number)
  9726. {
  9727. juce_wchar buffer [16];
  9728. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9729. juce_wchar* const start = NumberToStringConverters::uintToString (end, (unsigned int) number);
  9730. createInternal (start, end - start - 1);
  9731. }
  9732. String::String (const int64 number)
  9733. {
  9734. juce_wchar buffer [32];
  9735. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9736. juce_wchar* const start = NumberToStringConverters::int64ToString (end, number);
  9737. createInternal (start, end - start - 1);
  9738. }
  9739. String::String (const uint64 number)
  9740. {
  9741. juce_wchar buffer [32];
  9742. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9743. juce_wchar* const start = NumberToStringConverters::uint64ToString (end, number);
  9744. createInternal (start, end - start - 1);
  9745. }
  9746. String::String (const float number, const int numberOfDecimalPlaces)
  9747. {
  9748. juce_wchar buffer [48];
  9749. size_t len;
  9750. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), (double) number, numberOfDecimalPlaces, len);
  9751. createInternal (start, len);
  9752. }
  9753. String::String (const double number, const int numberOfDecimalPlaces)
  9754. {
  9755. juce_wchar buffer [48];
  9756. size_t len;
  9757. juce_wchar* start = NumberToStringConverters::doubleToString (buffer, numElementsInArray (buffer), number, numberOfDecimalPlaces, len);
  9758. createInternal (start, len);
  9759. }
  9760. int String::length() const throw()
  9761. {
  9762. return CharacterFunctions::length (text);
  9763. }
  9764. int String::hashCode() const throw()
  9765. {
  9766. const juce_wchar* t = text;
  9767. int result = 0;
  9768. while (*t != (juce_wchar) 0)
  9769. result = 31 * result + *t++;
  9770. return result;
  9771. }
  9772. int64 String::hashCode64() const throw()
  9773. {
  9774. const juce_wchar* t = text;
  9775. int64 result = 0;
  9776. while (*t != (juce_wchar) 0)
  9777. result = 101 * result + *t++;
  9778. return result;
  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 char* string2) throw()
  9785. {
  9786. return string1.compare (string2) == 0;
  9787. }
  9788. JUCE_API bool JUCE_CALLTYPE operator== (const String& string1, const juce_wchar* string2) throw()
  9789. {
  9790. return string1.compare (string2) == 0;
  9791. }
  9792. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const String& string2) throw()
  9793. {
  9794. return string1.compare (string2) != 0;
  9795. }
  9796. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const char* string2) throw()
  9797. {
  9798. return string1.compare (string2) != 0;
  9799. }
  9800. JUCE_API bool JUCE_CALLTYPE operator!= (const String& string1, const juce_wchar* string2) throw()
  9801. {
  9802. return string1.compare (string2) != 0;
  9803. }
  9804. JUCE_API bool JUCE_CALLTYPE operator> (const String& string1, const String& string2) throw()
  9805. {
  9806. return string1.compare (string2) > 0;
  9807. }
  9808. JUCE_API bool JUCE_CALLTYPE operator< (const String& string1, const String& string2) throw()
  9809. {
  9810. return string1.compare (string2) < 0;
  9811. }
  9812. JUCE_API bool JUCE_CALLTYPE operator>= (const String& string1, const String& string2) throw()
  9813. {
  9814. return string1.compare (string2) >= 0;
  9815. }
  9816. JUCE_API bool JUCE_CALLTYPE operator<= (const String& string1, const String& string2) throw()
  9817. {
  9818. return string1.compare (string2) <= 0;
  9819. }
  9820. bool String::equalsIgnoreCase (const juce_wchar* t) const throw()
  9821. {
  9822. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9823. : isEmpty();
  9824. }
  9825. bool String::equalsIgnoreCase (const char* t) const throw()
  9826. {
  9827. return t != 0 ? CharacterFunctions::compareIgnoreCase (text, t) == 0
  9828. : isEmpty();
  9829. }
  9830. bool String::equalsIgnoreCase (const String& other) const throw()
  9831. {
  9832. return text == other.text
  9833. || CharacterFunctions::compareIgnoreCase (text, other.text) == 0;
  9834. }
  9835. int String::compare (const String& other) const throw()
  9836. {
  9837. return (text == other.text) ? 0 : CharacterFunctions::compare (text, other.text);
  9838. }
  9839. int String::compare (const char* other) const throw()
  9840. {
  9841. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9842. }
  9843. int String::compare (const juce_wchar* other) const throw()
  9844. {
  9845. return other == 0 ? isEmpty() : CharacterFunctions::compare (text, other);
  9846. }
  9847. int String::compareIgnoreCase (const String& other) const throw()
  9848. {
  9849. return (text == other.text) ? 0 : CharacterFunctions::compareIgnoreCase (text, other.text);
  9850. }
  9851. int String::compareLexicographically (const String& other) const throw()
  9852. {
  9853. const juce_wchar* s1 = text;
  9854. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  9855. ++s1;
  9856. const juce_wchar* s2 = other.text;
  9857. while (*s2 != 0 && ! CharacterFunctions::isLetterOrDigit (*s2))
  9858. ++s2;
  9859. return CharacterFunctions::compareIgnoreCase (s1, s2);
  9860. }
  9861. String& String::operator+= (const juce_wchar* const t)
  9862. {
  9863. if (t != 0)
  9864. appendInternal (t, CharacterFunctions::length (t));
  9865. return *this;
  9866. }
  9867. String& String::operator+= (const String& other)
  9868. {
  9869. if (isEmpty())
  9870. operator= (other);
  9871. else
  9872. appendInternal (other.text, other.length());
  9873. return *this;
  9874. }
  9875. String& String::operator+= (const char ch)
  9876. {
  9877. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9878. return operator+= (static_cast <const juce_wchar*> (asString));
  9879. }
  9880. String& String::operator+= (const juce_wchar ch)
  9881. {
  9882. const juce_wchar asString[] = { (juce_wchar) ch, 0 };
  9883. return operator+= (static_cast <const juce_wchar*> (asString));
  9884. }
  9885. String& String::operator+= (const int number)
  9886. {
  9887. juce_wchar buffer [16];
  9888. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9889. juce_wchar* const start = NumberToStringConverters::intToString (end, number);
  9890. appendInternal (start, (int) (end - start));
  9891. return *this;
  9892. }
  9893. String& String::operator+= (const unsigned int number)
  9894. {
  9895. juce_wchar buffer [16];
  9896. juce_wchar* const end = buffer + numElementsInArray (buffer);
  9897. juce_wchar* const start = NumberToStringConverters::uintToString (end, number);
  9898. appendInternal (start, (int) (end - start));
  9899. return *this;
  9900. }
  9901. void String::append (const juce_wchar* const other, const int howMany)
  9902. {
  9903. if (howMany > 0)
  9904. {
  9905. int i;
  9906. for (i = 0; i < howMany; ++i)
  9907. if (other[i] == 0)
  9908. break;
  9909. appendInternal (other, i);
  9910. }
  9911. }
  9912. JUCE_API const String JUCE_CALLTYPE operator+ (const char* const string1, const String& string2)
  9913. {
  9914. String s (string1);
  9915. return s += string2;
  9916. }
  9917. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar* const string1, const String& string2)
  9918. {
  9919. String s (string1);
  9920. return s += string2;
  9921. }
  9922. JUCE_API const String JUCE_CALLTYPE operator+ (const char string1, const String& string2)
  9923. {
  9924. return String::charToString (string1) + string2;
  9925. }
  9926. JUCE_API const String JUCE_CALLTYPE operator+ (const juce_wchar string1, const String& string2)
  9927. {
  9928. return String::charToString (string1) + string2;
  9929. }
  9930. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const String& string2)
  9931. {
  9932. return string1 += string2;
  9933. }
  9934. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char* const string2)
  9935. {
  9936. return string1 += string2;
  9937. }
  9938. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar* const string2)
  9939. {
  9940. return string1 += string2;
  9941. }
  9942. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const char string2)
  9943. {
  9944. return string1 += string2;
  9945. }
  9946. JUCE_API const String JUCE_CALLTYPE operator+ (String string1, const juce_wchar string2)
  9947. {
  9948. return string1 += string2;
  9949. }
  9950. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char characterToAppend)
  9951. {
  9952. return string1 += characterToAppend;
  9953. }
  9954. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar characterToAppend)
  9955. {
  9956. return string1 += characterToAppend;
  9957. }
  9958. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const char* const string2)
  9959. {
  9960. return string1 += string2;
  9961. }
  9962. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const juce_wchar* const string2)
  9963. {
  9964. return string1 += string2;
  9965. }
  9966. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const String& string2)
  9967. {
  9968. return string1 += string2;
  9969. }
  9970. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const short number)
  9971. {
  9972. return string1 += (int) number;
  9973. }
  9974. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const int number)
  9975. {
  9976. return string1 += number;
  9977. }
  9978. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned int number)
  9979. {
  9980. return string1 += number;
  9981. }
  9982. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const long number)
  9983. {
  9984. return string1 += (int) number;
  9985. }
  9986. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const unsigned long number)
  9987. {
  9988. return string1 += (unsigned int) number;
  9989. }
  9990. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const float number)
  9991. {
  9992. return string1 += String (number);
  9993. }
  9994. JUCE_API String& JUCE_CALLTYPE operator<< (String& string1, const double number)
  9995. {
  9996. return string1 += String (number);
  9997. }
  9998. JUCE_API OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const String& text)
  9999. {
  10000. // (This avoids using toUTF8() to prevent the memory bloat that it would leave behind
  10001. // if lots of large, persistent strings were to be written to streams).
  10002. const int numBytes = text.getNumBytesAsUTF8();
  10003. HeapBlock<char> temp (numBytes + 1);
  10004. text.copyToUTF8 (temp, numBytes + 1);
  10005. stream.write (temp, numBytes);
  10006. return stream;
  10007. }
  10008. int String::indexOfChar (const juce_wchar character) const throw()
  10009. {
  10010. const juce_wchar* t = text;
  10011. for (;;)
  10012. {
  10013. if (*t == character)
  10014. return (int) (t - text);
  10015. if (*t++ == 0)
  10016. return -1;
  10017. }
  10018. }
  10019. int String::lastIndexOfChar (const juce_wchar character) const throw()
  10020. {
  10021. for (int i = length(); --i >= 0;)
  10022. if (text[i] == character)
  10023. return i;
  10024. return -1;
  10025. }
  10026. int String::indexOf (const String& t) const throw()
  10027. {
  10028. const juce_wchar* const r = CharacterFunctions::find (text, t.text);
  10029. return r == 0 ? -1 : (int) (r - text);
  10030. }
  10031. int String::indexOfChar (const int startIndex,
  10032. const juce_wchar character) const throw()
  10033. {
  10034. if (startIndex > 0 && startIndex >= length())
  10035. return -1;
  10036. const juce_wchar* t = text + jmax (0, startIndex);
  10037. for (;;)
  10038. {
  10039. if (*t == character)
  10040. return (int) (t - text);
  10041. if (*t == 0)
  10042. return -1;
  10043. ++t;
  10044. }
  10045. }
  10046. int String::indexOfAnyOf (const String& charactersToLookFor,
  10047. const int startIndex,
  10048. const bool ignoreCase) const throw()
  10049. {
  10050. if (startIndex > 0 && startIndex >= length())
  10051. return -1;
  10052. const juce_wchar* t = text + jmax (0, startIndex);
  10053. while (*t != 0)
  10054. {
  10055. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, *t, ignoreCase) >= 0)
  10056. return (int) (t - text);
  10057. ++t;
  10058. }
  10059. return -1;
  10060. }
  10061. int String::indexOf (const int startIndex, const String& other) const throw()
  10062. {
  10063. if (startIndex > 0 && startIndex >= length())
  10064. return -1;
  10065. const juce_wchar* const found = CharacterFunctions::find (text + jmax (0, startIndex), other.text);
  10066. return found == 0 ? -1 : (int) (found - text);
  10067. }
  10068. int String::indexOfIgnoreCase (const String& other) const throw()
  10069. {
  10070. if (other.isNotEmpty())
  10071. {
  10072. const int len = other.length();
  10073. const int end = length() - len;
  10074. for (int i = 0; i <= end; ++i)
  10075. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10076. return i;
  10077. }
  10078. return -1;
  10079. }
  10080. int String::indexOfIgnoreCase (const int startIndex, const String& other) const throw()
  10081. {
  10082. if (other.isNotEmpty())
  10083. {
  10084. const int len = other.length();
  10085. const int end = length() - len;
  10086. for (int i = jmax (0, startIndex); i <= end; ++i)
  10087. if (CharacterFunctions::compareIgnoreCase (text + i, other.text, len) == 0)
  10088. return i;
  10089. }
  10090. return -1;
  10091. }
  10092. int String::lastIndexOf (const String& other) const throw()
  10093. {
  10094. if (other.isNotEmpty())
  10095. {
  10096. const int len = other.length();
  10097. int i = length() - len;
  10098. if (i >= 0)
  10099. {
  10100. const juce_wchar* n = text + i;
  10101. while (i >= 0)
  10102. {
  10103. if (CharacterFunctions::compare (n--, other.text, len) == 0)
  10104. return i;
  10105. --i;
  10106. }
  10107. }
  10108. }
  10109. return -1;
  10110. }
  10111. int String::lastIndexOfIgnoreCase (const String& other) const throw()
  10112. {
  10113. if (other.isNotEmpty())
  10114. {
  10115. const int len = other.length();
  10116. int i = length() - len;
  10117. if (i >= 0)
  10118. {
  10119. const juce_wchar* n = text + i;
  10120. while (i >= 0)
  10121. {
  10122. if (CharacterFunctions::compareIgnoreCase (n--, other.text, len) == 0)
  10123. return i;
  10124. --i;
  10125. }
  10126. }
  10127. }
  10128. return -1;
  10129. }
  10130. int String::lastIndexOfAnyOf (const String& charactersToLookFor, const bool ignoreCase) const throw()
  10131. {
  10132. for (int i = length(); --i >= 0;)
  10133. if (CharacterFunctions::indexOfChar (charactersToLookFor.text, text[i], ignoreCase) >= 0)
  10134. return i;
  10135. return -1;
  10136. }
  10137. bool String::contains (const String& other) const throw()
  10138. {
  10139. return indexOf (other) >= 0;
  10140. }
  10141. bool String::containsChar (const juce_wchar character) const throw()
  10142. {
  10143. const juce_wchar* t = text;
  10144. for (;;)
  10145. {
  10146. if (*t == 0)
  10147. return false;
  10148. if (*t == character)
  10149. return true;
  10150. ++t;
  10151. }
  10152. }
  10153. bool String::containsIgnoreCase (const String& t) const throw()
  10154. {
  10155. return indexOfIgnoreCase (t) >= 0;
  10156. }
  10157. int String::indexOfWholeWord (const String& word) const throw()
  10158. {
  10159. if (word.isNotEmpty())
  10160. {
  10161. const int wordLen = word.length();
  10162. const int end = length() - wordLen;
  10163. const juce_wchar* t = text;
  10164. for (int i = 0; i <= end; ++i)
  10165. {
  10166. if (CharacterFunctions::compare (t, word.text, wordLen) == 0
  10167. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10168. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10169. {
  10170. return i;
  10171. }
  10172. ++t;
  10173. }
  10174. }
  10175. return -1;
  10176. }
  10177. int String::indexOfWholeWordIgnoreCase (const String& word) const throw()
  10178. {
  10179. if (word.isNotEmpty())
  10180. {
  10181. const int wordLen = word.length();
  10182. const int end = length() - wordLen;
  10183. const juce_wchar* t = text;
  10184. for (int i = 0; i <= end; ++i)
  10185. {
  10186. if (CharacterFunctions::compareIgnoreCase (t, word.text, wordLen) == 0
  10187. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  10188. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  10189. {
  10190. return i;
  10191. }
  10192. ++t;
  10193. }
  10194. }
  10195. return -1;
  10196. }
  10197. bool String::containsWholeWord (const String& wordToLookFor) const throw()
  10198. {
  10199. return indexOfWholeWord (wordToLookFor) >= 0;
  10200. }
  10201. bool String::containsWholeWordIgnoreCase (const String& wordToLookFor) const throw()
  10202. {
  10203. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  10204. }
  10205. namespace WildCardHelpers
  10206. {
  10207. int indexOfMatch (const juce_wchar* const wildcard,
  10208. const juce_wchar* const test,
  10209. const bool ignoreCase) throw()
  10210. {
  10211. int start = 0;
  10212. while (test [start] != 0)
  10213. {
  10214. int i = 0;
  10215. for (;;)
  10216. {
  10217. const juce_wchar wc = wildcard [i];
  10218. const juce_wchar c = test [i + start];
  10219. if (wc == c
  10220. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10221. || (wc == '?' && c != 0))
  10222. {
  10223. if (wc == 0)
  10224. return start;
  10225. ++i;
  10226. }
  10227. else
  10228. {
  10229. if (wc == '*' && (wildcard [i + 1] == 0
  10230. || indexOfMatch (wildcard + i + 1, test + start + i, ignoreCase) >= 0))
  10231. {
  10232. return start;
  10233. }
  10234. break;
  10235. }
  10236. }
  10237. ++start;
  10238. }
  10239. return -1;
  10240. }
  10241. }
  10242. bool String::matchesWildcard (const String& wildcard, const bool ignoreCase) const throw()
  10243. {
  10244. int i = 0;
  10245. for (;;)
  10246. {
  10247. const juce_wchar wc = wildcard.text [i];
  10248. const juce_wchar c = text [i];
  10249. if (wc == c
  10250. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  10251. || (wc == '?' && c != 0))
  10252. {
  10253. if (wc == 0)
  10254. return true;
  10255. ++i;
  10256. }
  10257. else
  10258. {
  10259. return wc == '*' && (wildcard [i + 1] == 0
  10260. || WildCardHelpers::indexOfMatch (wildcard.text + i + 1, text + i, ignoreCase) >= 0);
  10261. }
  10262. }
  10263. }
  10264. const String String::repeatedString (const String& stringToRepeat, int numberOfTimesToRepeat)
  10265. {
  10266. const int len = stringToRepeat.length();
  10267. String result ((size_t) (len * numberOfTimesToRepeat + 1), (int) 0);
  10268. juce_wchar* n = result.text;
  10269. *n = 0;
  10270. while (--numberOfTimesToRepeat >= 0)
  10271. {
  10272. StringHolder::copyChars (n, stringToRepeat.text, len);
  10273. n += len;
  10274. }
  10275. return result;
  10276. }
  10277. const String String::paddedLeft (const juce_wchar padCharacter, int minimumLength) const
  10278. {
  10279. jassert (padCharacter != 0);
  10280. const int len = length();
  10281. if (len >= minimumLength || padCharacter == 0)
  10282. return *this;
  10283. String result ((size_t) minimumLength + 1, (int) 0);
  10284. juce_wchar* n = result.text;
  10285. minimumLength -= len;
  10286. while (--minimumLength >= 0)
  10287. *n++ = padCharacter;
  10288. StringHolder::copyChars (n, text, len);
  10289. return result;
  10290. }
  10291. const String String::paddedRight (const juce_wchar padCharacter, int minimumLength) const
  10292. {
  10293. jassert (padCharacter != 0);
  10294. const int len = length();
  10295. if (len >= minimumLength || padCharacter == 0)
  10296. return *this;
  10297. String result (*this, (size_t) minimumLength);
  10298. juce_wchar* n = result.text + len;
  10299. minimumLength -= len;
  10300. while (--minimumLength >= 0)
  10301. *n++ = padCharacter;
  10302. *n = 0;
  10303. return result;
  10304. }
  10305. const String String::replaceSection (int index, int numCharsToReplace, const String& stringToInsert) const
  10306. {
  10307. if (index < 0)
  10308. {
  10309. // a negative index to replace from?
  10310. jassertfalse;
  10311. index = 0;
  10312. }
  10313. if (numCharsToReplace < 0)
  10314. {
  10315. // replacing a negative number of characters?
  10316. numCharsToReplace = 0;
  10317. jassertfalse;
  10318. }
  10319. const int len = length();
  10320. if (index + numCharsToReplace > len)
  10321. {
  10322. if (index > len)
  10323. {
  10324. // replacing beyond the end of the string?
  10325. index = len;
  10326. jassertfalse;
  10327. }
  10328. numCharsToReplace = len - index;
  10329. }
  10330. const int newStringLen = stringToInsert.length();
  10331. const int newTotalLen = len + newStringLen - numCharsToReplace;
  10332. if (newTotalLen <= 0)
  10333. return String::empty;
  10334. String result ((size_t) newTotalLen, (int) 0);
  10335. StringHolder::copyChars (result.text, text, index);
  10336. if (newStringLen > 0)
  10337. StringHolder::copyChars (result.text + index, stringToInsert.text, newStringLen);
  10338. const int endStringLen = newTotalLen - (index + newStringLen);
  10339. if (endStringLen > 0)
  10340. StringHolder::copyChars (result.text + (index + newStringLen),
  10341. text + (index + numCharsToReplace),
  10342. endStringLen);
  10343. return result;
  10344. }
  10345. const String String::replace (const String& stringToReplace, const String& stringToInsert, const bool ignoreCase) const
  10346. {
  10347. const int stringToReplaceLen = stringToReplace.length();
  10348. const int stringToInsertLen = stringToInsert.length();
  10349. int i = 0;
  10350. String result (*this);
  10351. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  10352. : result.indexOf (i, stringToReplace))) >= 0)
  10353. {
  10354. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  10355. i += stringToInsertLen;
  10356. }
  10357. return result;
  10358. }
  10359. const String String::replaceCharacter (const juce_wchar charToReplace, const juce_wchar charToInsert) const
  10360. {
  10361. const int index = indexOfChar (charToReplace);
  10362. if (index < 0)
  10363. return *this;
  10364. String result (*this, size_t());
  10365. juce_wchar* t = result.text + index;
  10366. while (*t != 0)
  10367. {
  10368. if (*t == charToReplace)
  10369. *t = charToInsert;
  10370. ++t;
  10371. }
  10372. return result;
  10373. }
  10374. const String String::replaceCharacters (const String& charactersToReplace,
  10375. const String& charactersToInsertInstead) const
  10376. {
  10377. String result (*this, size_t());
  10378. juce_wchar* t = result.text;
  10379. const int len2 = charactersToInsertInstead.length();
  10380. // the two strings passed in are supposed to be the same length!
  10381. jassert (len2 == charactersToReplace.length());
  10382. while (*t != 0)
  10383. {
  10384. const int index = charactersToReplace.indexOfChar (*t);
  10385. if (((unsigned int) index) < (unsigned int) len2)
  10386. *t = charactersToInsertInstead [index];
  10387. ++t;
  10388. }
  10389. return result;
  10390. }
  10391. bool String::startsWith (const String& other) const throw()
  10392. {
  10393. return CharacterFunctions::compare (text, other.text, other.length()) == 0;
  10394. }
  10395. bool String::startsWithIgnoreCase (const String& other) const throw()
  10396. {
  10397. return CharacterFunctions::compareIgnoreCase (text, other.text, other.length()) == 0;
  10398. }
  10399. bool String::startsWithChar (const juce_wchar character) const throw()
  10400. {
  10401. jassert (character != 0); // strings can't contain a null character!
  10402. return text[0] == character;
  10403. }
  10404. bool String::endsWithChar (const juce_wchar character) const throw()
  10405. {
  10406. jassert (character != 0); // strings can't contain a null character!
  10407. return text[0] != 0
  10408. && text [length() - 1] == character;
  10409. }
  10410. bool String::endsWith (const String& other) const throw()
  10411. {
  10412. const int thisLen = length();
  10413. const int otherLen = other.length();
  10414. return thisLen >= otherLen
  10415. && CharacterFunctions::compare (text + thisLen - otherLen, other.text) == 0;
  10416. }
  10417. bool String::endsWithIgnoreCase (const String& other) const throw()
  10418. {
  10419. const int thisLen = length();
  10420. const int otherLen = other.length();
  10421. return thisLen >= otherLen
  10422. && CharacterFunctions::compareIgnoreCase (text + thisLen - otherLen, other.text) == 0;
  10423. }
  10424. const String String::toUpperCase() const
  10425. {
  10426. String result (*this, size_t());
  10427. CharacterFunctions::toUpperCase (result.text);
  10428. return result;
  10429. }
  10430. const String String::toLowerCase() const
  10431. {
  10432. String result (*this, size_t());
  10433. CharacterFunctions::toLowerCase (result.text);
  10434. return result;
  10435. }
  10436. juce_wchar& String::operator[] (const int index)
  10437. {
  10438. jassert (((unsigned int) index) <= (unsigned int) length());
  10439. text = StringHolder::makeUnique (text);
  10440. return text [index];
  10441. }
  10442. juce_wchar String::getLastCharacter() const throw()
  10443. {
  10444. return isEmpty() ? juce_wchar() : text [length() - 1];
  10445. }
  10446. const String String::substring (int start, int end) const
  10447. {
  10448. if (start < 0)
  10449. start = 0;
  10450. else if (end <= start)
  10451. return empty;
  10452. int len = 0;
  10453. while (len <= end && text [len] != 0)
  10454. ++len;
  10455. if (end >= len)
  10456. {
  10457. if (start == 0)
  10458. return *this;
  10459. end = len;
  10460. }
  10461. return String (text + start, end - start);
  10462. }
  10463. const String String::substring (const int start) const
  10464. {
  10465. if (start <= 0)
  10466. return *this;
  10467. const int len = length();
  10468. if (start >= len)
  10469. return empty;
  10470. return String (text + start, len - start);
  10471. }
  10472. const String String::dropLastCharacters (const int numberToDrop) const
  10473. {
  10474. return String (text, jmax (0, length() - numberToDrop));
  10475. }
  10476. const String String::getLastCharacters (const int numCharacters) const
  10477. {
  10478. return String (text + jmax (0, length() - jmax (0, numCharacters)));
  10479. }
  10480. const String String::fromFirstOccurrenceOf (const String& sub,
  10481. const bool includeSubString,
  10482. const bool ignoreCase) const
  10483. {
  10484. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10485. : indexOf (sub);
  10486. if (i < 0)
  10487. return empty;
  10488. return substring (includeSubString ? i : i + sub.length());
  10489. }
  10490. const String String::fromLastOccurrenceOf (const String& sub,
  10491. const bool includeSubString,
  10492. const bool ignoreCase) const
  10493. {
  10494. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10495. : lastIndexOf (sub);
  10496. if (i < 0)
  10497. return *this;
  10498. return substring (includeSubString ? i : i + sub.length());
  10499. }
  10500. const String String::upToFirstOccurrenceOf (const String& sub,
  10501. const bool includeSubString,
  10502. const bool ignoreCase) const
  10503. {
  10504. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  10505. : indexOf (sub);
  10506. if (i < 0)
  10507. return *this;
  10508. return substring (0, includeSubString ? i + sub.length() : i);
  10509. }
  10510. const String String::upToLastOccurrenceOf (const String& sub,
  10511. const bool includeSubString,
  10512. const bool ignoreCase) const
  10513. {
  10514. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  10515. : lastIndexOf (sub);
  10516. if (i < 0)
  10517. return *this;
  10518. return substring (0, includeSubString ? i + sub.length() : i);
  10519. }
  10520. bool String::isQuotedString() const
  10521. {
  10522. const String trimmed (trimStart());
  10523. return trimmed[0] == '"'
  10524. || trimmed[0] == '\'';
  10525. }
  10526. const String String::unquoted() const
  10527. {
  10528. String s (*this);
  10529. if (s.text[0] == '"' || s.text[0] == '\'')
  10530. s = s.substring (1);
  10531. const int lastCharIndex = s.length() - 1;
  10532. if (lastCharIndex >= 0
  10533. && (s [lastCharIndex] == '"' || s[lastCharIndex] == '\''))
  10534. s [lastCharIndex] = 0;
  10535. return s;
  10536. }
  10537. const String String::quoted (const juce_wchar quoteCharacter) const
  10538. {
  10539. if (isEmpty())
  10540. return charToString (quoteCharacter) + quoteCharacter;
  10541. String t (*this);
  10542. if (! t.startsWithChar (quoteCharacter))
  10543. t = charToString (quoteCharacter) + t;
  10544. if (! t.endsWithChar (quoteCharacter))
  10545. t += quoteCharacter;
  10546. return t;
  10547. }
  10548. const String String::trim() const
  10549. {
  10550. if (isEmpty())
  10551. return empty;
  10552. int start = 0;
  10553. while (CharacterFunctions::isWhitespace (text [start]))
  10554. ++start;
  10555. const int len = length();
  10556. int end = len - 1;
  10557. while ((end >= start) && CharacterFunctions::isWhitespace (text [end]))
  10558. --end;
  10559. ++end;
  10560. if (end <= start)
  10561. return empty;
  10562. else if (start > 0 || end < len)
  10563. return String (text + start, end - start);
  10564. return *this;
  10565. }
  10566. const String String::trimStart() const
  10567. {
  10568. if (isEmpty())
  10569. return empty;
  10570. const juce_wchar* t = text;
  10571. while (CharacterFunctions::isWhitespace (*t))
  10572. ++t;
  10573. if (t == text)
  10574. return *this;
  10575. return String (t);
  10576. }
  10577. const String String::trimEnd() const
  10578. {
  10579. if (isEmpty())
  10580. return empty;
  10581. const juce_wchar* endT = text + (length() - 1);
  10582. while ((endT >= text) && CharacterFunctions::isWhitespace (*endT))
  10583. --endT;
  10584. return String (text, (int) (++endT - text));
  10585. }
  10586. const String String::trimCharactersAtStart (const String& charactersToTrim) const
  10587. {
  10588. const juce_wchar* t = text;
  10589. while (charactersToTrim.containsChar (*t))
  10590. ++t;
  10591. return t == text ? *this : String (t);
  10592. }
  10593. const String String::trimCharactersAtEnd (const String& charactersToTrim) const
  10594. {
  10595. if (isEmpty())
  10596. return empty;
  10597. const int len = length();
  10598. const juce_wchar* endT = text + (len - 1);
  10599. int numToRemove = 0;
  10600. while (numToRemove < len && charactersToTrim.containsChar (*endT))
  10601. {
  10602. ++numToRemove;
  10603. --endT;
  10604. }
  10605. return numToRemove > 0 ? String (text, len - numToRemove) : *this;
  10606. }
  10607. const String String::retainCharacters (const String& charactersToRetain) const
  10608. {
  10609. if (isEmpty())
  10610. return empty;
  10611. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10612. juce_wchar* dst = result.text;
  10613. const juce_wchar* src = text;
  10614. while (*src != 0)
  10615. {
  10616. if (charactersToRetain.containsChar (*src))
  10617. *dst++ = *src;
  10618. ++src;
  10619. }
  10620. *dst = 0;
  10621. return result;
  10622. }
  10623. const String String::removeCharacters (const String& charactersToRemove) const
  10624. {
  10625. if (isEmpty())
  10626. return empty;
  10627. String result (StringHolder::getAllocatedNumChars (text), (int) 0);
  10628. juce_wchar* dst = result.text;
  10629. const juce_wchar* src = text;
  10630. while (*src != 0)
  10631. {
  10632. if (! charactersToRemove.containsChar (*src))
  10633. *dst++ = *src;
  10634. ++src;
  10635. }
  10636. *dst = 0;
  10637. return result;
  10638. }
  10639. const String String::initialSectionContainingOnly (const String& permittedCharacters) const
  10640. {
  10641. int i = 0;
  10642. for (;;)
  10643. {
  10644. if (! permittedCharacters.containsChar (text[i]))
  10645. break;
  10646. ++i;
  10647. }
  10648. return substring (0, i);
  10649. }
  10650. const String String::initialSectionNotContaining (const String& charactersToStopAt) const
  10651. {
  10652. const juce_wchar* const t = text;
  10653. int i = 0;
  10654. while (t[i] != 0)
  10655. {
  10656. if (charactersToStopAt.containsChar (t[i]))
  10657. return String (text, i);
  10658. ++i;
  10659. }
  10660. return empty;
  10661. }
  10662. bool String::containsOnly (const String& chars) const throw()
  10663. {
  10664. const juce_wchar* t = text;
  10665. while (*t != 0)
  10666. if (! chars.containsChar (*t++))
  10667. return false;
  10668. return true;
  10669. }
  10670. bool String::containsAnyOf (const String& chars) const throw()
  10671. {
  10672. const juce_wchar* t = text;
  10673. while (*t != 0)
  10674. if (chars.containsChar (*t++))
  10675. return true;
  10676. return false;
  10677. }
  10678. bool String::containsNonWhitespaceChars() const throw()
  10679. {
  10680. const juce_wchar* t = text;
  10681. while (*t != 0)
  10682. if (! CharacterFunctions::isWhitespace (*t++))
  10683. return true;
  10684. return false;
  10685. }
  10686. const String String::formatted (const juce_wchar* const pf, ... )
  10687. {
  10688. jassert (pf != 0);
  10689. va_list args;
  10690. va_start (args, pf);
  10691. size_t bufferSize = 256;
  10692. String result (bufferSize, (int) 0);
  10693. result.text[0] = 0;
  10694. for (;;)
  10695. {
  10696. #if JUCE_LINUX && JUCE_64BIT
  10697. va_list tempArgs;
  10698. va_copy (tempArgs, args);
  10699. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, tempArgs);
  10700. va_end (tempArgs);
  10701. #elif JUCE_WINDOWS
  10702. #if JUCE_MSVC
  10703. #pragma warning (push)
  10704. #pragma warning (disable: 4996)
  10705. #endif
  10706. const int num = (int) _vsnwprintf (result.text, bufferSize - 1, pf, args);
  10707. #if JUCE_MSVC
  10708. #pragma warning (pop)
  10709. #endif
  10710. #else
  10711. const int num = (int) vswprintf (result.text, bufferSize - 1, pf, args);
  10712. #endif
  10713. if (num > 0)
  10714. return result;
  10715. bufferSize += 256;
  10716. if (num == 0 || bufferSize > 65536) // the upper limit is a sanity check to avoid situations where vprintf repeatedly
  10717. break; // returns -1 because of an error rather than because it needs more space.
  10718. result.preallocateStorage (bufferSize);
  10719. }
  10720. return empty;
  10721. }
  10722. int String::getIntValue() const throw()
  10723. {
  10724. return CharacterFunctions::getIntValue (text);
  10725. }
  10726. int String::getTrailingIntValue() const throw()
  10727. {
  10728. int n = 0;
  10729. int mult = 1;
  10730. const juce_wchar* t = text + length();
  10731. while (--t >= text)
  10732. {
  10733. const juce_wchar c = *t;
  10734. if (! CharacterFunctions::isDigit (c))
  10735. {
  10736. if (c == '-')
  10737. n = -n;
  10738. break;
  10739. }
  10740. n += mult * (c - '0');
  10741. mult *= 10;
  10742. }
  10743. return n;
  10744. }
  10745. int64 String::getLargeIntValue() const throw()
  10746. {
  10747. return CharacterFunctions::getInt64Value (text);
  10748. }
  10749. float String::getFloatValue() const throw()
  10750. {
  10751. return (float) CharacterFunctions::getDoubleValue (text);
  10752. }
  10753. double String::getDoubleValue() const throw()
  10754. {
  10755. return CharacterFunctions::getDoubleValue (text);
  10756. }
  10757. static const juce_wchar* const hexDigits = JUCE_T("0123456789abcdef");
  10758. const String String::toHexString (const int number)
  10759. {
  10760. juce_wchar buffer[32];
  10761. juce_wchar* const end = buffer + 32;
  10762. juce_wchar* t = end;
  10763. *--t = 0;
  10764. unsigned int v = (unsigned int) number;
  10765. do
  10766. {
  10767. *--t = hexDigits [v & 15];
  10768. v >>= 4;
  10769. } while (v != 0);
  10770. return String (t, (int) (((char*) end) - (char*) t) - 1);
  10771. }
  10772. const String String::toHexString (const int64 number)
  10773. {
  10774. juce_wchar buffer[32];
  10775. juce_wchar* const end = buffer + 32;
  10776. juce_wchar* t = end;
  10777. *--t = 0;
  10778. uint64 v = (uint64) number;
  10779. do
  10780. {
  10781. *--t = hexDigits [(int) (v & 15)];
  10782. v >>= 4;
  10783. } while (v != 0);
  10784. return String (t, (int) (((char*) end) - (char*) t));
  10785. }
  10786. const String String::toHexString (const short number)
  10787. {
  10788. return toHexString ((int) (unsigned short) number);
  10789. }
  10790. const String String::toHexString (const unsigned char* data,
  10791. const int size,
  10792. const int groupSize)
  10793. {
  10794. if (size <= 0)
  10795. return empty;
  10796. int numChars = (size * 2) + 2;
  10797. if (groupSize > 0)
  10798. numChars += size / groupSize;
  10799. String s ((size_t) numChars, (int) 0);
  10800. juce_wchar* d = s.text;
  10801. for (int i = 0; i < size; ++i)
  10802. {
  10803. *d++ = hexDigits [(*data) >> 4];
  10804. *d++ = hexDigits [(*data) & 0xf];
  10805. ++data;
  10806. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  10807. *d++ = ' ';
  10808. }
  10809. *d = 0;
  10810. return s;
  10811. }
  10812. int String::getHexValue32() const throw()
  10813. {
  10814. int result = 0;
  10815. const juce_wchar* c = text;
  10816. for (;;)
  10817. {
  10818. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10819. if (hexValue >= 0)
  10820. result = (result << 4) | hexValue;
  10821. else if (*c == 0)
  10822. break;
  10823. ++c;
  10824. }
  10825. return result;
  10826. }
  10827. int64 String::getHexValue64() const throw()
  10828. {
  10829. int64 result = 0;
  10830. const juce_wchar* c = text;
  10831. for (;;)
  10832. {
  10833. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  10834. if (hexValue >= 0)
  10835. result = (result << 4) | hexValue;
  10836. else if (*c == 0)
  10837. break;
  10838. ++c;
  10839. }
  10840. return result;
  10841. }
  10842. const String String::createStringFromData (const void* const data_, const int size)
  10843. {
  10844. const char* const data = static_cast <const char*> (data_);
  10845. if (size <= 0 || data == 0)
  10846. {
  10847. return empty;
  10848. }
  10849. else if (size < 2)
  10850. {
  10851. return charToString (data[0]);
  10852. }
  10853. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  10854. || (data[0] == (char)-1 && data[1] == (char)-2))
  10855. {
  10856. // assume it's 16-bit unicode
  10857. const bool bigEndian = (data[0] == (char)-2);
  10858. const int numChars = size / 2 - 1;
  10859. String result;
  10860. result.preallocateStorage (numChars + 2);
  10861. const uint16* const src = (const uint16*) (data + 2);
  10862. juce_wchar* const dst = const_cast <juce_wchar*> (static_cast <const juce_wchar*> (result));
  10863. if (bigEndian)
  10864. {
  10865. for (int i = 0; i < numChars; ++i)
  10866. dst[i] = (juce_wchar) ByteOrder::swapIfLittleEndian (src[i]);
  10867. }
  10868. else
  10869. {
  10870. for (int i = 0; i < numChars; ++i)
  10871. dst[i] = (juce_wchar) ByteOrder::swapIfBigEndian (src[i]);
  10872. }
  10873. dst [numChars] = 0;
  10874. return result;
  10875. }
  10876. else
  10877. {
  10878. return String::fromUTF8 (data, size);
  10879. }
  10880. }
  10881. const char* String::toUTF8() const
  10882. {
  10883. if (isEmpty())
  10884. {
  10885. return reinterpret_cast <const char*> (text);
  10886. }
  10887. else
  10888. {
  10889. const int currentLen = length() + 1;
  10890. const int utf8BytesNeeded = getNumBytesAsUTF8();
  10891. String* const mutableThis = const_cast <String*> (this);
  10892. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, currentLen + 1 + utf8BytesNeeded / sizeof (juce_wchar));
  10893. char* const otherCopy = reinterpret_cast <char*> (mutableThis->text + currentLen);
  10894. #if JUCE_DEBUG // (This just avoids spurious warnings from valgrind about the uninitialised bytes at the end of the buffer..)
  10895. *(juce_wchar*) (otherCopy + (utf8BytesNeeded & ~(sizeof (juce_wchar) - 1))) = 0;
  10896. #endif
  10897. copyToUTF8 (otherCopy, std::numeric_limits<int>::max());
  10898. return otherCopy;
  10899. }
  10900. }
  10901. int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
  10902. {
  10903. jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
  10904. int num = 0, index = 0;
  10905. for (;;)
  10906. {
  10907. const uint32 c = (uint32) text [index++];
  10908. if (c >= 0x80)
  10909. {
  10910. int numExtraBytes = 1;
  10911. if (c >= 0x800)
  10912. {
  10913. ++numExtraBytes;
  10914. if (c >= 0x10000)
  10915. {
  10916. ++numExtraBytes;
  10917. if (c >= 0x200000)
  10918. {
  10919. ++numExtraBytes;
  10920. if (c >= 0x4000000)
  10921. ++numExtraBytes;
  10922. }
  10923. }
  10924. }
  10925. if (buffer != 0)
  10926. {
  10927. if (num + numExtraBytes >= maxBufferSizeBytes)
  10928. {
  10929. buffer [num++] = 0;
  10930. break;
  10931. }
  10932. else
  10933. {
  10934. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  10935. while (--numExtraBytes >= 0)
  10936. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  10937. }
  10938. }
  10939. else
  10940. {
  10941. num += numExtraBytes + 1;
  10942. }
  10943. }
  10944. else
  10945. {
  10946. if (buffer != 0)
  10947. {
  10948. if (num + 1 >= maxBufferSizeBytes)
  10949. {
  10950. buffer [num++] = 0;
  10951. break;
  10952. }
  10953. buffer [num] = (uint8) c;
  10954. }
  10955. ++num;
  10956. }
  10957. if (c == 0)
  10958. break;
  10959. }
  10960. return num;
  10961. }
  10962. int String::getNumBytesAsUTF8() const throw()
  10963. {
  10964. int num = 0;
  10965. const juce_wchar* t = text;
  10966. for (;;)
  10967. {
  10968. const uint32 c = (uint32) *t;
  10969. if (c >= 0x80)
  10970. {
  10971. ++num;
  10972. if (c >= 0x800)
  10973. {
  10974. ++num;
  10975. if (c >= 0x10000)
  10976. {
  10977. ++num;
  10978. if (c >= 0x200000)
  10979. {
  10980. ++num;
  10981. if (c >= 0x4000000)
  10982. ++num;
  10983. }
  10984. }
  10985. }
  10986. }
  10987. else if (c == 0)
  10988. break;
  10989. ++num;
  10990. ++t;
  10991. }
  10992. return num;
  10993. }
  10994. const String String::fromUTF8 (const char* const buffer, int bufferSizeBytes)
  10995. {
  10996. if (buffer == 0)
  10997. return empty;
  10998. if (bufferSizeBytes < 0)
  10999. bufferSizeBytes = std::numeric_limits<int>::max();
  11000. size_t numBytes;
  11001. for (numBytes = 0; numBytes < (size_t) bufferSizeBytes; ++numBytes)
  11002. if (buffer [numBytes] == 0)
  11003. break;
  11004. String result ((size_t) numBytes + 1, (int) 0);
  11005. juce_wchar* dest = result.text;
  11006. size_t i = 0;
  11007. while (i < numBytes)
  11008. {
  11009. const char c = buffer [i++];
  11010. if (c < 0)
  11011. {
  11012. unsigned int mask = 0x7f;
  11013. int bit = 0x40;
  11014. int numExtraValues = 0;
  11015. while (bit != 0 && (c & bit) != 0)
  11016. {
  11017. bit >>= 1;
  11018. mask >>= 1;
  11019. ++numExtraValues;
  11020. }
  11021. int n = (mask & (unsigned char) c);
  11022. while (--numExtraValues >= 0 && i < (size_t) bufferSizeBytes)
  11023. {
  11024. const char nextByte = buffer[i];
  11025. if ((nextByte & 0xc0) != 0x80)
  11026. break;
  11027. n <<= 6;
  11028. n |= (nextByte & 0x3f);
  11029. ++i;
  11030. }
  11031. *dest++ = (juce_wchar) n;
  11032. }
  11033. else
  11034. {
  11035. *dest++ = (juce_wchar) c;
  11036. }
  11037. }
  11038. *dest = 0;
  11039. return result;
  11040. }
  11041. const char* String::toCString() const
  11042. {
  11043. if (isEmpty())
  11044. {
  11045. return reinterpret_cast <const char*> (text);
  11046. }
  11047. else
  11048. {
  11049. const int len = length();
  11050. String* const mutableThis = const_cast <String*> (this);
  11051. mutableThis->text = StringHolder::makeUniqueWithSize (mutableThis->text, (len + 1) * 2);
  11052. char* otherCopy = reinterpret_cast <char*> (mutableThis->text + len + 1);
  11053. CharacterFunctions::copy (otherCopy, text, len);
  11054. otherCopy [len] = 0;
  11055. return otherCopy;
  11056. }
  11057. }
  11058. #if JUCE_MSVC
  11059. #pragma warning (push)
  11060. #pragma warning (disable: 4514 4996)
  11061. #endif
  11062. int String::getNumBytesAsCString() const throw()
  11063. {
  11064. return (int) wcstombs (0, text, 0);
  11065. }
  11066. int String::copyToCString (char* destBuffer, const int maxBufferSizeBytes) const throw()
  11067. {
  11068. const int numBytes = (int) wcstombs (destBuffer, text, maxBufferSizeBytes);
  11069. if (destBuffer != 0 && numBytes >= 0)
  11070. destBuffer [numBytes] = 0;
  11071. return numBytes;
  11072. }
  11073. #if JUCE_MSVC
  11074. #pragma warning (pop)
  11075. #endif
  11076. void String::copyToUnicode (juce_wchar* const destBuffer, const int maxCharsToCopy) const throw()
  11077. {
  11078. jassert (destBuffer != 0 && maxCharsToCopy >= 0);
  11079. if (destBuffer != 0 && maxCharsToCopy >= 0)
  11080. StringHolder::copyChars (destBuffer, text, jmin (maxCharsToCopy, length()));
  11081. }
  11082. String::Concatenator::Concatenator (String& stringToAppendTo)
  11083. : result (stringToAppendTo),
  11084. nextIndex (stringToAppendTo.length())
  11085. {
  11086. }
  11087. String::Concatenator::~Concatenator()
  11088. {
  11089. }
  11090. void String::Concatenator::append (const String& s)
  11091. {
  11092. const int len = s.length();
  11093. if (len > 0)
  11094. {
  11095. result.preallocateStorage (nextIndex + len);
  11096. s.copyToUnicode (static_cast <juce_wchar*> (result) + nextIndex, len);
  11097. nextIndex += len;
  11098. }
  11099. }
  11100. #if JUCE_UNIT_TESTS
  11101. class StringTests : public UnitTest
  11102. {
  11103. public:
  11104. StringTests() : UnitTest ("String class") {}
  11105. void runTest()
  11106. {
  11107. {
  11108. beginTest ("Basics");
  11109. expect (String().length() == 0);
  11110. expect (String() == String::empty);
  11111. String s1, s2 ("abcd");
  11112. expect (s1.isEmpty() && ! s1.isNotEmpty());
  11113. expect (s2.isNotEmpty() && ! s2.isEmpty());
  11114. expect (s2.length() == 4);
  11115. s1 = "abcd";
  11116. expect (s2 == s1 && s1 == s2);
  11117. expect (s1 == "abcd" && s1 == L"abcd");
  11118. expect (String ("abcd") == String (L"abcd"));
  11119. expect (String ("abcdefg", 4) == L"abcd");
  11120. expect (String ("abcdefg", 4) == String (L"abcdefg", 4));
  11121. expect (String::charToString ('x') == "x");
  11122. expect (String::charToString (0) == String::empty);
  11123. expect (s2 + "e" == "abcde" && s2 + 'e' == "abcde");
  11124. expect (s2 + L'e' == "abcde" && s2 + L"e" == "abcde");
  11125. expect (s1.equalsIgnoreCase ("abcD") && s1 < "abce" && s1 > "abbb");
  11126. expect (s1.startsWith ("ab") && s1.startsWith ("abcd") && ! s1.startsWith ("abcde"));
  11127. expect (s1.startsWithIgnoreCase ("aB") && s1.endsWithIgnoreCase ("CD"));
  11128. expect (s1.endsWith ("bcd") && ! s1.endsWith ("aabcd"));
  11129. expect (s1.indexOf (String::empty) == 0);
  11130. expect (s1.startsWith (String::empty) && s1.endsWith (String::empty) && s1.contains (String::empty));
  11131. expect (s1.contains ("cd") && s1.contains ("ab") && s1.contains ("abcd"));
  11132. expect (s1.containsChar ('a') && ! s1.containsChar (0));
  11133. expect (String ("abc foo bar").containsWholeWord ("abc") && String ("abc foo bar").containsWholeWord ("abc"));
  11134. }
  11135. {
  11136. beginTest ("Operations");
  11137. String s ("012345678");
  11138. expect (s.hashCode() != 0);
  11139. expect (s.hashCode64() != 0);
  11140. expect (s.hashCode() != (s + s).hashCode());
  11141. expect (s.hashCode64() != (s + s).hashCode64());
  11142. expect (s.compare (String ("012345678")) == 0);
  11143. expect (s.compare (String ("012345679")) < 0);
  11144. expect (s.compare (String ("012345676")) > 0);
  11145. expect (s.substring (2, 3) == String::charToString (s[2]));
  11146. expect (s.substring (0, 1) == String::charToString (s[0]));
  11147. expect (s.getLastCharacter() == s [s.length() - 1]);
  11148. expect (String::charToString (s.getLastCharacter()) == s.getLastCharacters (1));
  11149. expect (s.substring (0, 3) == L"012");
  11150. expect (s.substring (0, 100) == s);
  11151. expect (s.substring (-1, 100) == s);
  11152. expect (s.substring (3) == "345678");
  11153. expect (s.indexOf (L"45") == 4);
  11154. expect (String ("444445").indexOf ("45") == 4);
  11155. expect (String ("444445").lastIndexOfChar ('4') == 4);
  11156. expect (String ("45454545x").lastIndexOf (L"45") == 6);
  11157. expect (String ("45454545x").lastIndexOfAnyOf ("456") == 7);
  11158. expect (String ("45454545x").lastIndexOfAnyOf (L"456x") == 8);
  11159. expect (String ("abABaBaBa").lastIndexOfIgnoreCase ("Ab") == 6);
  11160. expect (s.indexOfChar (L'4') == 4);
  11161. expect (s + s == "012345678012345678");
  11162. expect (s.startsWith (s));
  11163. expect (s.startsWith (s.substring (0, 4)));
  11164. expect (s.startsWith (s.dropLastCharacters (4)));
  11165. expect (s.endsWith (s.substring (5)));
  11166. expect (s.endsWith (s));
  11167. expect (s.contains (s.substring (3, 6)));
  11168. expect (s.contains (s.substring (3)));
  11169. expect (s.startsWithChar (s[0]));
  11170. expect (s.endsWithChar (s.getLastCharacter()));
  11171. expect (s [s.length()] == 0);
  11172. expect (String ("abcdEFGH").toLowerCase() == String ("abcdefgh"));
  11173. expect (String ("abcdEFGH").toUpperCase() == String ("ABCDEFGH"));
  11174. String s2 ("123");
  11175. s2 << ((int) 4) << ((short) 5) << "678" << L"9" << '0';
  11176. s2 += "xyz";
  11177. expect (s2 == "1234567890xyz");
  11178. beginTest ("Numeric conversions");
  11179. expect (String::empty.getIntValue() == 0);
  11180. expect (String::empty.getDoubleValue() == 0.0);
  11181. expect (String::empty.getFloatValue() == 0.0f);
  11182. expect (s.getIntValue() == 12345678);
  11183. expect (s.getLargeIntValue() == (int64) 12345678);
  11184. expect (s.getDoubleValue() == 12345678.0);
  11185. expect (s.getFloatValue() == 12345678.0f);
  11186. expect (String (-1234).getIntValue() == -1234);
  11187. expect (String ((int64) -1234).getLargeIntValue() == -1234);
  11188. expect (String (-1234.56).getDoubleValue() == -1234.56);
  11189. expect (String (-1234.56f).getFloatValue() == -1234.56f);
  11190. expect (("xyz" + s).getTrailingIntValue() == s.getIntValue());
  11191. expect (s.getHexValue32() == 0x12345678);
  11192. expect (s.getHexValue64() == (int64) 0x12345678);
  11193. expect (String::toHexString (0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11194. expect (String::toHexString ((int64) 0x1234abcd).equalsIgnoreCase ("1234abcd"));
  11195. expect (String::toHexString ((short) 0x12ab).equalsIgnoreCase ("12ab"));
  11196. unsigned char data[] = { 1, 2, 3, 4, 0xa, 0xb, 0xc, 0xd };
  11197. expect (String::toHexString (data, 8, 0).equalsIgnoreCase ("010203040a0b0c0d"));
  11198. expect (String::toHexString (data, 8, 1).equalsIgnoreCase ("01 02 03 04 0a 0b 0c 0d"));
  11199. expect (String::toHexString (data, 8, 2).equalsIgnoreCase ("0102 0304 0a0b 0c0d"));
  11200. beginTest ("Subsections");
  11201. String s3;
  11202. s3 = "abcdeFGHIJ";
  11203. expect (s3.equalsIgnoreCase ("ABCdeFGhiJ"));
  11204. expect (s3.compareIgnoreCase (L"ABCdeFGhiJ") == 0);
  11205. expect (s3.containsIgnoreCase (s3.substring (3)));
  11206. expect (s3.indexOfAnyOf ("xyzf", 2, true) == 5);
  11207. expect (s3.indexOfAnyOf (L"xyzf", 2, false) == -1);
  11208. expect (s3.indexOfAnyOf ("xyzF", 2, false) == 5);
  11209. expect (s3.containsAnyOf (L"zzzFs"));
  11210. expect (s3.startsWith ("abcd"));
  11211. expect (s3.startsWithIgnoreCase (L"abCD"));
  11212. expect (s3.startsWith (String::empty));
  11213. expect (s3.startsWithChar ('a'));
  11214. expect (s3.endsWith (String ("HIJ")));
  11215. expect (s3.endsWithIgnoreCase (L"Hij"));
  11216. expect (s3.endsWith (String::empty));
  11217. expect (s3.endsWithChar (L'J'));
  11218. expect (s3.indexOf ("HIJ") == 7);
  11219. expect (s3.indexOf (L"HIJK") == -1);
  11220. expect (s3.indexOfIgnoreCase ("hij") == 7);
  11221. expect (s3.indexOfIgnoreCase (L"hijk") == -1);
  11222. String s4 (s3);
  11223. s4.append (String ("xyz123"), 3);
  11224. expect (s4 == s3 + "xyz");
  11225. expect (String (1234) < String (1235));
  11226. expect (String (1235) > String (1234));
  11227. expect (String (1234) >= String (1234));
  11228. expect (String (1234) <= String (1234));
  11229. expect (String (1235) >= String (1234));
  11230. expect (String (1234) <= String (1235));
  11231. String s5 ("word word2 word3");
  11232. expect (s5.containsWholeWord (String ("word2")));
  11233. expect (s5.indexOfWholeWord ("word2") == 5);
  11234. expect (s5.containsWholeWord (L"word"));
  11235. expect (s5.containsWholeWord ("word3"));
  11236. expect (s5.containsWholeWord (s5));
  11237. expect (s5.containsWholeWordIgnoreCase (L"Word2"));
  11238. expect (s5.indexOfWholeWordIgnoreCase ("Word2") == 5);
  11239. expect (s5.containsWholeWordIgnoreCase (L"Word"));
  11240. expect (s5.containsWholeWordIgnoreCase ("Word3"));
  11241. expect (! s5.containsWholeWordIgnoreCase (L"Wordx"));
  11242. expect (!s5.containsWholeWordIgnoreCase ("xWord2"));
  11243. expect (s5.containsNonWhitespaceChars());
  11244. expect (! String (" \n\r\t").containsNonWhitespaceChars());
  11245. expect (s5.matchesWildcard (L"wor*", false));
  11246. expect (s5.matchesWildcard ("wOr*", true));
  11247. expect (s5.matchesWildcard (L"*word3", true));
  11248. expect (s5.matchesWildcard ("*word?", true));
  11249. expect (s5.matchesWildcard (L"Word*3", true));
  11250. expect (s5.fromFirstOccurrenceOf (String::empty, true, false) == s5);
  11251. expect (s5.fromFirstOccurrenceOf ("xword2", true, false) == s5.substring (100));
  11252. expect (s5.fromFirstOccurrenceOf (L"word2", true, false) == s5.substring (5));
  11253. expect (s5.fromFirstOccurrenceOf ("Word2", true, true) == s5.substring (5));
  11254. expect (s5.fromFirstOccurrenceOf ("word2", false, false) == s5.getLastCharacters (6));
  11255. expect (s5.fromFirstOccurrenceOf (L"Word2", false, true) == s5.getLastCharacters (6));
  11256. expect (s5.fromLastOccurrenceOf (String::empty, true, false) == s5);
  11257. expect (s5.fromLastOccurrenceOf (L"wordx", true, false) == s5);
  11258. expect (s5.fromLastOccurrenceOf ("word", true, false) == s5.getLastCharacters (5));
  11259. expect (s5.fromLastOccurrenceOf (L"worD", true, true) == s5.getLastCharacters (5));
  11260. expect (s5.fromLastOccurrenceOf ("word", false, false) == s5.getLastCharacters (1));
  11261. expect (s5.fromLastOccurrenceOf (L"worD", false, true) == s5.getLastCharacters (1));
  11262. expect (s5.upToFirstOccurrenceOf (String::empty, true, false).isEmpty());
  11263. expect (s5.upToFirstOccurrenceOf ("word4", true, false) == s5);
  11264. expect (s5.upToFirstOccurrenceOf (L"word2", true, false) == s5.substring (0, 10));
  11265. expect (s5.upToFirstOccurrenceOf ("Word2", true, true) == s5.substring (0, 10));
  11266. expect (s5.upToFirstOccurrenceOf (L"word2", false, false) == s5.substring (0, 5));
  11267. expect (s5.upToFirstOccurrenceOf ("Word2", false, true) == s5.substring (0, 5));
  11268. expect (s5.upToLastOccurrenceOf (String::empty, true, false) == s5);
  11269. expect (s5.upToLastOccurrenceOf ("zword", true, false) == s5);
  11270. expect (s5.upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11271. expect (s5.dropLastCharacters(1).upToLastOccurrenceOf ("word", true, false) == s5.dropLastCharacters (1));
  11272. expect (s5.upToLastOccurrenceOf ("Word", true, true) == s5.dropLastCharacters (1));
  11273. expect (s5.upToLastOccurrenceOf ("word", false, false) == s5.dropLastCharacters (5));
  11274. expect (s5.upToLastOccurrenceOf ("Word", false, true) == s5.dropLastCharacters (5));
  11275. expect (s5.replace ("word", L"xyz", false) == String ("xyz xyz2 xyz3"));
  11276. expect (s5.replace (L"Word", "xyz", true) == "xyz xyz2 xyz3");
  11277. expect (s5.dropLastCharacters (1).replace ("Word", String ("xyz"), true) == L"xyz xyz2 xyz");
  11278. expect (s5.replace ("Word", "", true) == " 2 3");
  11279. expect (s5.replace ("Word2", L"xyz", true) == String ("word xyz word3"));
  11280. expect (s5.replaceCharacter (L'w', 'x') != s5);
  11281. expect (s5.replaceCharacter ('w', L'x').replaceCharacter ('x', 'w') == s5);
  11282. expect (s5.replaceCharacters ("wo", "xy") != s5);
  11283. expect (s5.replaceCharacters ("wo", "xy").replaceCharacters ("xy", L"wo") == s5);
  11284. expect (s5.retainCharacters ("1wordxya") == String ("wordwordword"));
  11285. expect (s5.retainCharacters (String::empty).isEmpty());
  11286. expect (s5.removeCharacters ("1wordxya") == " 2 3");
  11287. expect (s5.removeCharacters (String::empty) == s5);
  11288. expect (s5.initialSectionContainingOnly ("word") == L"word");
  11289. expect (s5.initialSectionNotContaining (String ("xyz ")) == String ("word"));
  11290. expect (! s5.isQuotedString());
  11291. expect (s5.quoted().isQuotedString());
  11292. expect (! s5.quoted().unquoted().isQuotedString());
  11293. expect (! String ("x'").isQuotedString());
  11294. expect (String ("'x").isQuotedString());
  11295. String s6 (" \t xyz \t\r\n");
  11296. expect (s6.trim() == String ("xyz"));
  11297. expect (s6.trim().trim() == "xyz");
  11298. expect (s5.trim() == s5);
  11299. expect (s6.trimStart().trimEnd() == s6.trim());
  11300. expect (s6.trimStart().trimEnd() == s6.trimEnd().trimStart());
  11301. expect (s6.trimStart().trimStart().trimEnd().trimEnd() == s6.trimEnd().trimStart());
  11302. expect (s6.trimStart() != s6.trimEnd());
  11303. expect (("\t\r\n " + s6 + "\t\n \r").trim() == s6.trim());
  11304. expect (String::repeatedString ("xyz", 3) == L"xyzxyzxyz");
  11305. }
  11306. {
  11307. beginTest ("UTF8");
  11308. String s ("word word2 word3");
  11309. {
  11310. char buffer [100];
  11311. memset (buffer, 0xff, sizeof (buffer));
  11312. s.copyToUTF8 (buffer, 100);
  11313. expect (String::fromUTF8 (buffer, 100) == s);
  11314. juce_wchar bufferUnicode [100];
  11315. memset (bufferUnicode, 0xff, sizeof (bufferUnicode));
  11316. s.copyToUnicode (bufferUnicode, 100);
  11317. expect (String (bufferUnicode, 100) == s);
  11318. }
  11319. {
  11320. juce_wchar wideBuffer [50];
  11321. zerostruct (wideBuffer);
  11322. for (int i = 0; i < numElementsInArray (wideBuffer) - 1; ++i)
  11323. wideBuffer[i] = (juce_wchar) (1 + Random::getSystemRandom().nextInt (std::numeric_limits<juce_wchar>::max() - 1));
  11324. String wide (wideBuffer);
  11325. expect (wide == (const juce_wchar*) wideBuffer);
  11326. expect (wide.length() == numElementsInArray (wideBuffer) - 1);
  11327. expect (String::fromUTF8 (wide.toUTF8()) == wide);
  11328. expect (String::fromUTF8 (wide.toUTF8()) == wideBuffer);
  11329. }
  11330. }
  11331. }
  11332. };
  11333. static StringTests stringUnitTests;
  11334. #endif
  11335. END_JUCE_NAMESPACE
  11336. /*** End of inlined file: juce_String.cpp ***/
  11337. /*** Start of inlined file: juce_StringArray.cpp ***/
  11338. BEGIN_JUCE_NAMESPACE
  11339. StringArray::StringArray() throw()
  11340. {
  11341. }
  11342. StringArray::StringArray (const StringArray& other)
  11343. : strings (other.strings)
  11344. {
  11345. }
  11346. StringArray::StringArray (const String& firstValue)
  11347. {
  11348. strings.add (firstValue);
  11349. }
  11350. StringArray::StringArray (const juce_wchar* const* const initialStrings,
  11351. const int numberOfStrings)
  11352. {
  11353. for (int i = 0; i < numberOfStrings; ++i)
  11354. strings.add (initialStrings [i]);
  11355. }
  11356. StringArray::StringArray (const char* const* const initialStrings,
  11357. const int numberOfStrings)
  11358. {
  11359. for (int i = 0; i < numberOfStrings; ++i)
  11360. strings.add (initialStrings [i]);
  11361. }
  11362. StringArray::StringArray (const juce_wchar* const* const initialStrings)
  11363. {
  11364. int i = 0;
  11365. while (initialStrings[i] != 0)
  11366. strings.add (initialStrings [i++]);
  11367. }
  11368. StringArray::StringArray (const char* const* const initialStrings)
  11369. {
  11370. int i = 0;
  11371. while (initialStrings[i] != 0)
  11372. strings.add (initialStrings [i++]);
  11373. }
  11374. StringArray& StringArray::operator= (const StringArray& other)
  11375. {
  11376. strings = other.strings;
  11377. return *this;
  11378. }
  11379. StringArray::~StringArray()
  11380. {
  11381. }
  11382. bool StringArray::operator== (const StringArray& other) const throw()
  11383. {
  11384. if (other.size() != size())
  11385. return false;
  11386. for (int i = size(); --i >= 0;)
  11387. if (other.strings.getReference(i) != strings.getReference(i))
  11388. return false;
  11389. return true;
  11390. }
  11391. bool StringArray::operator!= (const StringArray& other) const throw()
  11392. {
  11393. return ! operator== (other);
  11394. }
  11395. void StringArray::clear()
  11396. {
  11397. strings.clear();
  11398. }
  11399. const String& StringArray::operator[] (const int index) const throw()
  11400. {
  11401. if (((unsigned int) index) < (unsigned int) strings.size())
  11402. return strings.getReference (index);
  11403. return String::empty;
  11404. }
  11405. String& StringArray::getReference (const int index) throw()
  11406. {
  11407. jassert (((unsigned int) index) < (unsigned int) strings.size());
  11408. return strings.getReference (index);
  11409. }
  11410. void StringArray::add (const String& newString)
  11411. {
  11412. strings.add (newString);
  11413. }
  11414. void StringArray::insert (const int index, const String& newString)
  11415. {
  11416. strings.insert (index, newString);
  11417. }
  11418. void StringArray::addIfNotAlreadyThere (const String& newString, const bool ignoreCase)
  11419. {
  11420. if (! contains (newString, ignoreCase))
  11421. add (newString);
  11422. }
  11423. void StringArray::addArray (const StringArray& otherArray, int startIndex, int numElementsToAdd)
  11424. {
  11425. if (startIndex < 0)
  11426. {
  11427. jassertfalse;
  11428. startIndex = 0;
  11429. }
  11430. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  11431. numElementsToAdd = otherArray.size() - startIndex;
  11432. while (--numElementsToAdd >= 0)
  11433. strings.add (otherArray.strings.getReference (startIndex++));
  11434. }
  11435. void StringArray::set (const int index, const String& newString)
  11436. {
  11437. strings.set (index, newString);
  11438. }
  11439. bool StringArray::contains (const String& stringToLookFor, const bool ignoreCase) const
  11440. {
  11441. if (ignoreCase)
  11442. {
  11443. for (int i = size(); --i >= 0;)
  11444. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11445. return true;
  11446. }
  11447. else
  11448. {
  11449. for (int i = size(); --i >= 0;)
  11450. if (stringToLookFor == strings.getReference(i))
  11451. return true;
  11452. }
  11453. return false;
  11454. }
  11455. int StringArray::indexOf (const String& stringToLookFor, const bool ignoreCase, int i) const
  11456. {
  11457. if (i < 0)
  11458. i = 0;
  11459. const int numElements = size();
  11460. if (ignoreCase)
  11461. {
  11462. while (i < numElements)
  11463. {
  11464. if (strings.getReference(i).equalsIgnoreCase (stringToLookFor))
  11465. return i;
  11466. ++i;
  11467. }
  11468. }
  11469. else
  11470. {
  11471. while (i < numElements)
  11472. {
  11473. if (stringToLookFor == strings.getReference (i))
  11474. return i;
  11475. ++i;
  11476. }
  11477. }
  11478. return -1;
  11479. }
  11480. void StringArray::remove (const int index)
  11481. {
  11482. strings.remove (index);
  11483. }
  11484. void StringArray::removeString (const String& stringToRemove,
  11485. const bool ignoreCase)
  11486. {
  11487. if (ignoreCase)
  11488. {
  11489. for (int i = size(); --i >= 0;)
  11490. if (strings.getReference(i).equalsIgnoreCase (stringToRemove))
  11491. strings.remove (i);
  11492. }
  11493. else
  11494. {
  11495. for (int i = size(); --i >= 0;)
  11496. if (stringToRemove == strings.getReference (i))
  11497. strings.remove (i);
  11498. }
  11499. }
  11500. void StringArray::removeRange (int startIndex, int numberToRemove)
  11501. {
  11502. strings.removeRange (startIndex, numberToRemove);
  11503. }
  11504. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings)
  11505. {
  11506. if (removeWhitespaceStrings)
  11507. {
  11508. for (int i = size(); --i >= 0;)
  11509. if (! strings.getReference(i).containsNonWhitespaceChars())
  11510. strings.remove (i);
  11511. }
  11512. else
  11513. {
  11514. for (int i = size(); --i >= 0;)
  11515. if (strings.getReference(i).isEmpty())
  11516. strings.remove (i);
  11517. }
  11518. }
  11519. void StringArray::trim()
  11520. {
  11521. for (int i = size(); --i >= 0;)
  11522. {
  11523. String& s = strings.getReference(i);
  11524. s = s.trim();
  11525. }
  11526. }
  11527. class InternalStringArrayComparator_CaseSensitive
  11528. {
  11529. public:
  11530. static int compareElements (String& first, String& second) { return first.compare (second); }
  11531. };
  11532. class InternalStringArrayComparator_CaseInsensitive
  11533. {
  11534. public:
  11535. static int compareElements (String& first, String& second) { return first.compareIgnoreCase (second); }
  11536. };
  11537. void StringArray::sort (const bool ignoreCase)
  11538. {
  11539. if (ignoreCase)
  11540. {
  11541. InternalStringArrayComparator_CaseInsensitive comp;
  11542. strings.sort (comp);
  11543. }
  11544. else
  11545. {
  11546. InternalStringArrayComparator_CaseSensitive comp;
  11547. strings.sort (comp);
  11548. }
  11549. }
  11550. void StringArray::move (const int currentIndex, int newIndex) throw()
  11551. {
  11552. strings.move (currentIndex, newIndex);
  11553. }
  11554. const String StringArray::joinIntoString (const String& separator, int start, int numberToJoin) const
  11555. {
  11556. const int last = (numberToJoin < 0) ? size()
  11557. : jmin (size(), start + numberToJoin);
  11558. if (start < 0)
  11559. start = 0;
  11560. if (start >= last)
  11561. return String::empty;
  11562. if (start == last - 1)
  11563. return strings.getReference (start);
  11564. const int separatorLen = separator.length();
  11565. int charsNeeded = separatorLen * (last - start - 1);
  11566. for (int i = start; i < last; ++i)
  11567. charsNeeded += strings.getReference(i).length();
  11568. String result;
  11569. result.preallocateStorage (charsNeeded);
  11570. juce_wchar* dest = result;
  11571. while (start < last)
  11572. {
  11573. const String& s = strings.getReference (start);
  11574. const int len = s.length();
  11575. if (len > 0)
  11576. {
  11577. s.copyToUnicode (dest, len);
  11578. dest += len;
  11579. }
  11580. if (++start < last && separatorLen > 0)
  11581. {
  11582. separator.copyToUnicode (dest, separatorLen);
  11583. dest += separatorLen;
  11584. }
  11585. }
  11586. *dest = 0;
  11587. return result;
  11588. }
  11589. int StringArray::addTokens (const String& text, const bool preserveQuotedStrings)
  11590. {
  11591. return addTokens (text, " \n\r\t", preserveQuotedStrings ? "\"" : "");
  11592. }
  11593. int StringArray::addTokens (const String& text, const String& breakCharacters, const String& quoteCharacters)
  11594. {
  11595. int num = 0;
  11596. if (text.isNotEmpty())
  11597. {
  11598. bool insideQuotes = false;
  11599. juce_wchar currentQuoteChar = 0;
  11600. int i = 0;
  11601. int tokenStart = 0;
  11602. for (;;)
  11603. {
  11604. const juce_wchar c = text[i];
  11605. const bool isBreak = (c == 0) || ((! insideQuotes) && breakCharacters.containsChar (c));
  11606. if (! isBreak)
  11607. {
  11608. if (quoteCharacters.containsChar (c))
  11609. {
  11610. if (insideQuotes)
  11611. {
  11612. // only break out of quotes-mode if we find a matching quote to the
  11613. // one that we opened with..
  11614. if (currentQuoteChar == c)
  11615. insideQuotes = false;
  11616. }
  11617. else
  11618. {
  11619. insideQuotes = true;
  11620. currentQuoteChar = c;
  11621. }
  11622. }
  11623. }
  11624. else
  11625. {
  11626. add (String (static_cast <const juce_wchar*> (text) + tokenStart, i - tokenStart));
  11627. ++num;
  11628. tokenStart = i + 1;
  11629. }
  11630. if (c == 0)
  11631. break;
  11632. ++i;
  11633. }
  11634. }
  11635. return num;
  11636. }
  11637. int StringArray::addLines (const String& sourceText)
  11638. {
  11639. int numLines = 0;
  11640. const juce_wchar* text = sourceText;
  11641. while (*text != 0)
  11642. {
  11643. const juce_wchar* const startOfLine = text;
  11644. while (*text != 0)
  11645. {
  11646. if (*text == '\r')
  11647. {
  11648. ++text;
  11649. if (*text == '\n')
  11650. ++text;
  11651. break;
  11652. }
  11653. if (*text == '\n')
  11654. {
  11655. ++text;
  11656. break;
  11657. }
  11658. ++text;
  11659. }
  11660. const juce_wchar* endOfLine = text;
  11661. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11662. --endOfLine;
  11663. if (endOfLine > startOfLine && (*(endOfLine - 1) == '\r' || *(endOfLine - 1) == '\n'))
  11664. --endOfLine;
  11665. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  11666. ++numLines;
  11667. }
  11668. return numLines;
  11669. }
  11670. void StringArray::removeDuplicates (const bool ignoreCase)
  11671. {
  11672. for (int i = 0; i < size() - 1; ++i)
  11673. {
  11674. const String s (strings.getReference(i));
  11675. int nextIndex = i + 1;
  11676. for (;;)
  11677. {
  11678. nextIndex = indexOf (s, ignoreCase, nextIndex);
  11679. if (nextIndex < 0)
  11680. break;
  11681. strings.remove (nextIndex);
  11682. }
  11683. }
  11684. }
  11685. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  11686. const bool appendNumberToFirstInstance,
  11687. const juce_wchar* preNumberString,
  11688. const juce_wchar* postNumberString)
  11689. {
  11690. if (preNumberString == 0)
  11691. preNumberString = L" (";
  11692. if (postNumberString == 0)
  11693. postNumberString = L")";
  11694. for (int i = 0; i < size() - 1; ++i)
  11695. {
  11696. String& s = strings.getReference(i);
  11697. int nextIndex = indexOf (s, ignoreCase, i + 1);
  11698. if (nextIndex >= 0)
  11699. {
  11700. const String original (s);
  11701. int number = 0;
  11702. if (appendNumberToFirstInstance)
  11703. s = original + preNumberString + String (++number) + postNumberString;
  11704. else
  11705. ++number;
  11706. while (nextIndex >= 0)
  11707. {
  11708. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  11709. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  11710. }
  11711. }
  11712. }
  11713. }
  11714. void StringArray::minimiseStorageOverheads()
  11715. {
  11716. strings.minimiseStorageOverheads();
  11717. }
  11718. END_JUCE_NAMESPACE
  11719. /*** End of inlined file: juce_StringArray.cpp ***/
  11720. /*** Start of inlined file: juce_StringPairArray.cpp ***/
  11721. BEGIN_JUCE_NAMESPACE
  11722. StringPairArray::StringPairArray (const bool ignoreCase_)
  11723. : ignoreCase (ignoreCase_)
  11724. {
  11725. }
  11726. StringPairArray::StringPairArray (const StringPairArray& other)
  11727. : keys (other.keys),
  11728. values (other.values),
  11729. ignoreCase (other.ignoreCase)
  11730. {
  11731. }
  11732. StringPairArray::~StringPairArray()
  11733. {
  11734. }
  11735. StringPairArray& StringPairArray::operator= (const StringPairArray& other)
  11736. {
  11737. keys = other.keys;
  11738. values = other.values;
  11739. return *this;
  11740. }
  11741. bool StringPairArray::operator== (const StringPairArray& other) const
  11742. {
  11743. for (int i = keys.size(); --i >= 0;)
  11744. if (other [keys[i]] != values[i])
  11745. return false;
  11746. return true;
  11747. }
  11748. bool StringPairArray::operator!= (const StringPairArray& other) const
  11749. {
  11750. return ! operator== (other);
  11751. }
  11752. const String& StringPairArray::operator[] (const String& key) const
  11753. {
  11754. return values [keys.indexOf (key, ignoreCase)];
  11755. }
  11756. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  11757. {
  11758. const int i = keys.indexOf (key, ignoreCase);
  11759. if (i >= 0)
  11760. return values[i];
  11761. return defaultReturnValue;
  11762. }
  11763. void StringPairArray::set (const String& key, const String& value)
  11764. {
  11765. const int i = keys.indexOf (key, ignoreCase);
  11766. if (i >= 0)
  11767. {
  11768. values.set (i, value);
  11769. }
  11770. else
  11771. {
  11772. keys.add (key);
  11773. values.add (value);
  11774. }
  11775. }
  11776. void StringPairArray::addArray (const StringPairArray& other)
  11777. {
  11778. for (int i = 0; i < other.size(); ++i)
  11779. set (other.keys[i], other.values[i]);
  11780. }
  11781. void StringPairArray::clear()
  11782. {
  11783. keys.clear();
  11784. values.clear();
  11785. }
  11786. void StringPairArray::remove (const String& key)
  11787. {
  11788. remove (keys.indexOf (key, ignoreCase));
  11789. }
  11790. void StringPairArray::remove (const int index)
  11791. {
  11792. keys.remove (index);
  11793. values.remove (index);
  11794. }
  11795. void StringPairArray::setIgnoresCase (const bool shouldIgnoreCase)
  11796. {
  11797. ignoreCase = shouldIgnoreCase;
  11798. }
  11799. const String StringPairArray::getDescription() const
  11800. {
  11801. String s;
  11802. for (int i = 0; i < keys.size(); ++i)
  11803. {
  11804. s << keys[i] << " = " << values[i];
  11805. if (i < keys.size())
  11806. s << ", ";
  11807. }
  11808. return s;
  11809. }
  11810. void StringPairArray::minimiseStorageOverheads()
  11811. {
  11812. keys.minimiseStorageOverheads();
  11813. values.minimiseStorageOverheads();
  11814. }
  11815. END_JUCE_NAMESPACE
  11816. /*** End of inlined file: juce_StringPairArray.cpp ***/
  11817. /*** Start of inlined file: juce_StringPool.cpp ***/
  11818. BEGIN_JUCE_NAMESPACE
  11819. StringPool::StringPool() throw() {}
  11820. StringPool::~StringPool() {}
  11821. namespace StringPoolHelpers
  11822. {
  11823. template <class StringType>
  11824. const juce_wchar* getPooledStringFromArray (Array<String>& strings, StringType newString)
  11825. {
  11826. int start = 0;
  11827. int end = strings.size();
  11828. for (;;)
  11829. {
  11830. if (start >= end)
  11831. {
  11832. jassert (start <= end);
  11833. strings.insert (start, newString);
  11834. return strings.getReference (start);
  11835. }
  11836. else
  11837. {
  11838. const String& startString = strings.getReference (start);
  11839. if (startString == newString)
  11840. return startString;
  11841. const int halfway = (start + end) >> 1;
  11842. if (halfway == start)
  11843. {
  11844. if (startString.compare (newString) < 0)
  11845. ++start;
  11846. strings.insert (start, newString);
  11847. return strings.getReference (start);
  11848. }
  11849. const int comp = strings.getReference (halfway).compare (newString);
  11850. if (comp == 0)
  11851. return strings.getReference (halfway);
  11852. else if (comp < 0)
  11853. start = halfway;
  11854. else
  11855. end = halfway;
  11856. }
  11857. }
  11858. }
  11859. }
  11860. const juce_wchar* StringPool::getPooledString (const String& s)
  11861. {
  11862. if (s.isEmpty())
  11863. return String::empty;
  11864. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11865. }
  11866. const juce_wchar* StringPool::getPooledString (const char* const s)
  11867. {
  11868. if (s == 0 || *s == 0)
  11869. return String::empty;
  11870. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11871. }
  11872. const juce_wchar* StringPool::getPooledString (const juce_wchar* const s)
  11873. {
  11874. if (s == 0 || *s == 0)
  11875. return String::empty;
  11876. return StringPoolHelpers::getPooledStringFromArray (strings, s);
  11877. }
  11878. int StringPool::size() const throw()
  11879. {
  11880. return strings.size();
  11881. }
  11882. const juce_wchar* StringPool::operator[] (const int index) const throw()
  11883. {
  11884. return strings [index];
  11885. }
  11886. END_JUCE_NAMESPACE
  11887. /*** End of inlined file: juce_StringPool.cpp ***/
  11888. /*** Start of inlined file: juce_XmlDocument.cpp ***/
  11889. BEGIN_JUCE_NAMESPACE
  11890. XmlDocument::XmlDocument (const String& documentText)
  11891. : originalText (documentText),
  11892. ignoreEmptyTextElements (true)
  11893. {
  11894. }
  11895. XmlDocument::XmlDocument (const File& file)
  11896. : ignoreEmptyTextElements (true)
  11897. {
  11898. inputSource = new FileInputSource (file);
  11899. }
  11900. XmlDocument::~XmlDocument()
  11901. {
  11902. }
  11903. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  11904. {
  11905. inputSource = newSource;
  11906. }
  11907. void XmlDocument::setEmptyTextElementsIgnored (const bool shouldBeIgnored) throw()
  11908. {
  11909. ignoreEmptyTextElements = shouldBeIgnored;
  11910. }
  11911. bool XmlDocument::isXmlIdentifierCharSlow (const juce_wchar c) throw()
  11912. {
  11913. return CharacterFunctions::isLetterOrDigit (c)
  11914. || c == '_' || c == '-' || c == ':' || c == '.';
  11915. }
  11916. inline bool XmlDocument::isXmlIdentifierChar (const juce_wchar c) const throw()
  11917. {
  11918. return (c > 0 && c <= 127) ? identifierLookupTable [(int) c]
  11919. : isXmlIdentifierCharSlow (c);
  11920. }
  11921. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  11922. {
  11923. String textToParse (originalText);
  11924. if (textToParse.isEmpty() && inputSource != 0)
  11925. {
  11926. ScopedPointer <InputStream> in (inputSource->createInputStream());
  11927. if (in != 0)
  11928. {
  11929. MemoryOutputStream data;
  11930. data.writeFromInputStream (*in, onlyReadOuterDocumentElement ? 8192 : -1);
  11931. textToParse = data.toString();
  11932. if (! onlyReadOuterDocumentElement)
  11933. originalText = textToParse;
  11934. }
  11935. }
  11936. input = textToParse;
  11937. lastError = String::empty;
  11938. errorOccurred = false;
  11939. outOfData = false;
  11940. needToLoadDTD = true;
  11941. for (int i = 0; i < 128; ++i)
  11942. identifierLookupTable[i] = isXmlIdentifierCharSlow ((juce_wchar) i);
  11943. if (textToParse.isEmpty())
  11944. {
  11945. lastError = "not enough input";
  11946. }
  11947. else
  11948. {
  11949. skipHeader();
  11950. if (input != 0)
  11951. {
  11952. ScopedPointer <XmlElement> result (readNextElement (! onlyReadOuterDocumentElement));
  11953. if (! errorOccurred)
  11954. return result.release();
  11955. }
  11956. else
  11957. {
  11958. lastError = "incorrect xml header";
  11959. }
  11960. }
  11961. return 0;
  11962. }
  11963. const String& XmlDocument::getLastParseError() const throw()
  11964. {
  11965. return lastError;
  11966. }
  11967. void XmlDocument::setLastError (const String& desc, const bool carryOn)
  11968. {
  11969. lastError = desc;
  11970. errorOccurred = ! carryOn;
  11971. }
  11972. const String XmlDocument::getFileContents (const String& filename) const
  11973. {
  11974. if (inputSource != 0)
  11975. {
  11976. const ScopedPointer <InputStream> in (inputSource->createInputStreamFor (filename.trim().unquoted()));
  11977. if (in != 0)
  11978. return in->readEntireStreamAsString();
  11979. }
  11980. return String::empty;
  11981. }
  11982. juce_wchar XmlDocument::readNextChar() throw()
  11983. {
  11984. if (*input != 0)
  11985. {
  11986. return *input++;
  11987. }
  11988. else
  11989. {
  11990. outOfData = true;
  11991. return 0;
  11992. }
  11993. }
  11994. int XmlDocument::findNextTokenLength() throw()
  11995. {
  11996. int len = 0;
  11997. juce_wchar c = *input;
  11998. while (isXmlIdentifierChar (c))
  11999. c = input [++len];
  12000. return len;
  12001. }
  12002. void XmlDocument::skipHeader()
  12003. {
  12004. const juce_wchar* const found = CharacterFunctions::find (input, JUCE_T("<?xml"));
  12005. if (found != 0)
  12006. {
  12007. input = found;
  12008. input = CharacterFunctions::find (input, JUCE_T("?>"));
  12009. if (input == 0)
  12010. return;
  12011. input += 2;
  12012. }
  12013. skipNextWhiteSpace();
  12014. const juce_wchar* docType = CharacterFunctions::find (input, JUCE_T("<!DOCTYPE"));
  12015. if (docType == 0)
  12016. return;
  12017. input = docType + 9;
  12018. int n = 1;
  12019. while (n > 0)
  12020. {
  12021. const juce_wchar c = readNextChar();
  12022. if (outOfData)
  12023. return;
  12024. if (c == '<')
  12025. ++n;
  12026. else if (c == '>')
  12027. --n;
  12028. }
  12029. docType += 9;
  12030. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  12031. }
  12032. void XmlDocument::skipNextWhiteSpace()
  12033. {
  12034. for (;;)
  12035. {
  12036. juce_wchar c = *input;
  12037. while (CharacterFunctions::isWhitespace (c))
  12038. c = *++input;
  12039. if (c == 0)
  12040. {
  12041. outOfData = true;
  12042. break;
  12043. }
  12044. else if (c == '<')
  12045. {
  12046. if (input[1] == '!'
  12047. && input[2] == '-'
  12048. && input[3] == '-')
  12049. {
  12050. const juce_wchar* const closeComment = CharacterFunctions::find (input, JUCE_T("-->"));
  12051. if (closeComment == 0)
  12052. {
  12053. outOfData = true;
  12054. break;
  12055. }
  12056. input = closeComment + 3;
  12057. continue;
  12058. }
  12059. else if (input[1] == '?')
  12060. {
  12061. const juce_wchar* const closeBracket = CharacterFunctions::find (input, JUCE_T("?>"));
  12062. if (closeBracket == 0)
  12063. {
  12064. outOfData = true;
  12065. break;
  12066. }
  12067. input = closeBracket + 2;
  12068. continue;
  12069. }
  12070. }
  12071. break;
  12072. }
  12073. }
  12074. void XmlDocument::readQuotedString (String& result)
  12075. {
  12076. const juce_wchar quote = readNextChar();
  12077. while (! outOfData)
  12078. {
  12079. const juce_wchar c = readNextChar();
  12080. if (c == quote)
  12081. break;
  12082. if (c == '&')
  12083. {
  12084. --input;
  12085. readEntity (result);
  12086. }
  12087. else
  12088. {
  12089. --input;
  12090. const juce_wchar* const start = input;
  12091. for (;;)
  12092. {
  12093. const juce_wchar character = *input;
  12094. if (character == quote)
  12095. {
  12096. result.append (start, (int) (input - start));
  12097. ++input;
  12098. return;
  12099. }
  12100. else if (character == '&')
  12101. {
  12102. result.append (start, (int) (input - start));
  12103. break;
  12104. }
  12105. else if (character == 0)
  12106. {
  12107. outOfData = true;
  12108. setLastError ("unmatched quotes", false);
  12109. break;
  12110. }
  12111. ++input;
  12112. }
  12113. }
  12114. }
  12115. }
  12116. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements)
  12117. {
  12118. XmlElement* node = 0;
  12119. skipNextWhiteSpace();
  12120. if (outOfData)
  12121. return 0;
  12122. input = CharacterFunctions::find (input, JUCE_T("<"));
  12123. if (input != 0)
  12124. {
  12125. ++input;
  12126. int tagLen = findNextTokenLength();
  12127. if (tagLen == 0)
  12128. {
  12129. // no tag name - but allow for a gap after the '<' before giving an error
  12130. skipNextWhiteSpace();
  12131. tagLen = findNextTokenLength();
  12132. if (tagLen == 0)
  12133. {
  12134. setLastError ("tag name missing", false);
  12135. return node;
  12136. }
  12137. }
  12138. node = new XmlElement (String (input, tagLen));
  12139. input += tagLen;
  12140. XmlElement::XmlAttributeNode* lastAttribute = 0;
  12141. // look for attributes
  12142. for (;;)
  12143. {
  12144. skipNextWhiteSpace();
  12145. const juce_wchar c = *input;
  12146. // empty tag..
  12147. if (c == '/' && input[1] == '>')
  12148. {
  12149. input += 2;
  12150. break;
  12151. }
  12152. // parse the guts of the element..
  12153. if (c == '>')
  12154. {
  12155. ++input;
  12156. if (alsoParseSubElements)
  12157. readChildElements (node);
  12158. break;
  12159. }
  12160. // get an attribute..
  12161. if (isXmlIdentifierChar (c))
  12162. {
  12163. const int attNameLen = findNextTokenLength();
  12164. if (attNameLen > 0)
  12165. {
  12166. const juce_wchar* attNameStart = input;
  12167. input += attNameLen;
  12168. skipNextWhiteSpace();
  12169. if (readNextChar() == '=')
  12170. {
  12171. skipNextWhiteSpace();
  12172. const juce_wchar nextChar = *input;
  12173. if (nextChar == '"' || nextChar == '\'')
  12174. {
  12175. XmlElement::XmlAttributeNode* const newAtt
  12176. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  12177. String::empty);
  12178. readQuotedString (newAtt->value);
  12179. if (lastAttribute == 0)
  12180. node->attributes = newAtt;
  12181. else
  12182. lastAttribute->next = newAtt;
  12183. lastAttribute = newAtt;
  12184. continue;
  12185. }
  12186. }
  12187. }
  12188. }
  12189. else
  12190. {
  12191. if (! outOfData)
  12192. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  12193. }
  12194. break;
  12195. }
  12196. }
  12197. return node;
  12198. }
  12199. void XmlDocument::readChildElements (XmlElement* parent)
  12200. {
  12201. XmlElement* lastChildNode = 0;
  12202. for (;;)
  12203. {
  12204. const juce_wchar* const preWhitespaceInput = input;
  12205. skipNextWhiteSpace();
  12206. if (outOfData)
  12207. {
  12208. setLastError ("unmatched tags", false);
  12209. break;
  12210. }
  12211. if (*input == '<')
  12212. {
  12213. if (input[1] == '/')
  12214. {
  12215. // our close tag..
  12216. input = CharacterFunctions::find (input, JUCE_T(">"));
  12217. ++input;
  12218. break;
  12219. }
  12220. else if (input[1] == '!'
  12221. && input[2] == '['
  12222. && input[3] == 'C'
  12223. && input[4] == 'D'
  12224. && input[5] == 'A'
  12225. && input[6] == 'T'
  12226. && input[7] == 'A'
  12227. && input[8] == '[')
  12228. {
  12229. input += 9;
  12230. const juce_wchar* const inputStart = input;
  12231. int len = 0;
  12232. for (;;)
  12233. {
  12234. if (*input == 0)
  12235. {
  12236. setLastError ("unterminated CDATA section", false);
  12237. outOfData = true;
  12238. break;
  12239. }
  12240. else if (input[0] == ']'
  12241. && input[1] == ']'
  12242. && input[2] == '>')
  12243. {
  12244. input += 3;
  12245. break;
  12246. }
  12247. ++input;
  12248. ++len;
  12249. }
  12250. XmlElement* const e = XmlElement::createTextElement (String (inputStart, len));
  12251. if (lastChildNode != 0)
  12252. lastChildNode->nextElement = e;
  12253. else
  12254. parent->addChildElement (e);
  12255. lastChildNode = e;
  12256. }
  12257. else
  12258. {
  12259. // this is some other element, so parse and add it..
  12260. XmlElement* const n = readNextElement (true);
  12261. if (n != 0)
  12262. {
  12263. if (lastChildNode == 0)
  12264. parent->addChildElement (n);
  12265. else
  12266. lastChildNode->nextElement = n;
  12267. lastChildNode = n;
  12268. }
  12269. else
  12270. {
  12271. return;
  12272. }
  12273. }
  12274. }
  12275. else // must be a character block
  12276. {
  12277. input = preWhitespaceInput; // roll back to include the leading whitespace
  12278. String textElementContent;
  12279. for (;;)
  12280. {
  12281. const juce_wchar c = *input;
  12282. if (c == '<')
  12283. break;
  12284. if (c == 0)
  12285. {
  12286. setLastError ("unmatched tags", false);
  12287. outOfData = true;
  12288. return;
  12289. }
  12290. if (c == '&')
  12291. {
  12292. String entity;
  12293. readEntity (entity);
  12294. if (entity.startsWithChar ('<') && entity [1] != 0)
  12295. {
  12296. const juce_wchar* const oldInput = input;
  12297. const bool oldOutOfData = outOfData;
  12298. input = entity;
  12299. outOfData = false;
  12300. for (;;)
  12301. {
  12302. XmlElement* const n = readNextElement (true);
  12303. if (n == 0)
  12304. break;
  12305. if (lastChildNode == 0)
  12306. parent->addChildElement (n);
  12307. else
  12308. lastChildNode->nextElement = n;
  12309. lastChildNode = n;
  12310. }
  12311. input = oldInput;
  12312. outOfData = oldOutOfData;
  12313. }
  12314. else
  12315. {
  12316. textElementContent += entity;
  12317. }
  12318. }
  12319. else
  12320. {
  12321. const juce_wchar* start = input;
  12322. int len = 0;
  12323. for (;;)
  12324. {
  12325. const juce_wchar nextChar = *input;
  12326. if (nextChar == '<' || nextChar == '&')
  12327. {
  12328. break;
  12329. }
  12330. else if (nextChar == 0)
  12331. {
  12332. setLastError ("unmatched tags", false);
  12333. outOfData = true;
  12334. return;
  12335. }
  12336. ++input;
  12337. ++len;
  12338. }
  12339. textElementContent.append (start, len);
  12340. }
  12341. }
  12342. if ((! ignoreEmptyTextElements) || textElementContent.containsNonWhitespaceChars())
  12343. {
  12344. XmlElement* const textElement = XmlElement::createTextElement (textElementContent);
  12345. if (lastChildNode != 0)
  12346. lastChildNode->nextElement = textElement;
  12347. else
  12348. parent->addChildElement (textElement);
  12349. lastChildNode = textElement;
  12350. }
  12351. }
  12352. }
  12353. }
  12354. void XmlDocument::readEntity (String& result)
  12355. {
  12356. // skip over the ampersand
  12357. ++input;
  12358. if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("amp;"), 4) == 0)
  12359. {
  12360. input += 4;
  12361. result += '&';
  12362. }
  12363. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("quot;"), 5) == 0)
  12364. {
  12365. input += 5;
  12366. result += '"';
  12367. }
  12368. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("apos;"), 5) == 0)
  12369. {
  12370. input += 5;
  12371. result += '\'';
  12372. }
  12373. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("lt;"), 3) == 0)
  12374. {
  12375. input += 3;
  12376. result += '<';
  12377. }
  12378. else if (CharacterFunctions::compareIgnoreCase (input, JUCE_T("gt;"), 3) == 0)
  12379. {
  12380. input += 3;
  12381. result += '>';
  12382. }
  12383. else if (*input == '#')
  12384. {
  12385. int charCode = 0;
  12386. ++input;
  12387. if (*input == 'x' || *input == 'X')
  12388. {
  12389. ++input;
  12390. int numChars = 0;
  12391. while (input[0] != ';')
  12392. {
  12393. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  12394. if (hexValue < 0 || ++numChars > 8)
  12395. {
  12396. setLastError ("illegal escape sequence", true);
  12397. break;
  12398. }
  12399. charCode = (charCode << 4) | hexValue;
  12400. ++input;
  12401. }
  12402. ++input;
  12403. }
  12404. else if (input[0] >= '0' && input[0] <= '9')
  12405. {
  12406. int numChars = 0;
  12407. while (input[0] != ';')
  12408. {
  12409. if (++numChars > 12)
  12410. {
  12411. setLastError ("illegal escape sequence", true);
  12412. break;
  12413. }
  12414. charCode = charCode * 10 + (input[0] - '0');
  12415. ++input;
  12416. }
  12417. ++input;
  12418. }
  12419. else
  12420. {
  12421. setLastError ("illegal escape sequence", true);
  12422. result += '&';
  12423. return;
  12424. }
  12425. result << (juce_wchar) charCode;
  12426. }
  12427. else
  12428. {
  12429. const juce_wchar* const entityNameStart = input;
  12430. const juce_wchar* const closingSemiColon = CharacterFunctions::find (input, JUCE_T(";"));
  12431. if (closingSemiColon == 0)
  12432. {
  12433. outOfData = true;
  12434. result += '&';
  12435. }
  12436. else
  12437. {
  12438. input = closingSemiColon + 1;
  12439. result += expandExternalEntity (String (entityNameStart,
  12440. (int) (closingSemiColon - entityNameStart)));
  12441. }
  12442. }
  12443. }
  12444. const String XmlDocument::expandEntity (const String& ent)
  12445. {
  12446. if (ent.equalsIgnoreCase ("amp"))
  12447. return String::charToString ('&');
  12448. if (ent.equalsIgnoreCase ("quot"))
  12449. return String::charToString ('"');
  12450. if (ent.equalsIgnoreCase ("apos"))
  12451. return String::charToString ('\'');
  12452. if (ent.equalsIgnoreCase ("lt"))
  12453. return String::charToString ('<');
  12454. if (ent.equalsIgnoreCase ("gt"))
  12455. return String::charToString ('>');
  12456. if (ent[0] == '#')
  12457. {
  12458. if (ent[1] == 'x' || ent[1] == 'X')
  12459. return String::charToString (static_cast <juce_wchar> (ent.substring (2).getHexValue32()));
  12460. if (ent[1] >= '0' && ent[1] <= '9')
  12461. return String::charToString (static_cast <juce_wchar> (ent.substring (1).getIntValue()));
  12462. setLastError ("illegal escape sequence", false);
  12463. return String::charToString ('&');
  12464. }
  12465. return expandExternalEntity (ent);
  12466. }
  12467. const String XmlDocument::expandExternalEntity (const String& entity)
  12468. {
  12469. if (needToLoadDTD)
  12470. {
  12471. if (dtdText.isNotEmpty())
  12472. {
  12473. dtdText = dtdText.trimCharactersAtEnd (">");
  12474. tokenisedDTD.addTokens (dtdText, true);
  12475. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase ("system")
  12476. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  12477. {
  12478. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  12479. tokenisedDTD.clear();
  12480. tokenisedDTD.addTokens (getFileContents (fn), true);
  12481. }
  12482. else
  12483. {
  12484. tokenisedDTD.clear();
  12485. const int openBracket = dtdText.indexOfChar ('[');
  12486. if (openBracket > 0)
  12487. {
  12488. const int closeBracket = dtdText.lastIndexOfChar (']');
  12489. if (closeBracket > openBracket)
  12490. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  12491. closeBracket), true);
  12492. }
  12493. }
  12494. for (int i = tokenisedDTD.size(); --i >= 0;)
  12495. {
  12496. if (tokenisedDTD[i].startsWithChar ('%')
  12497. && tokenisedDTD[i].endsWithChar (';'))
  12498. {
  12499. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  12500. StringArray newToks;
  12501. newToks.addTokens (parsed, true);
  12502. tokenisedDTD.remove (i);
  12503. for (int j = newToks.size(); --j >= 0;)
  12504. tokenisedDTD.insert (i, newToks[j]);
  12505. }
  12506. }
  12507. }
  12508. needToLoadDTD = false;
  12509. }
  12510. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12511. {
  12512. if (tokenisedDTD[i] == entity)
  12513. {
  12514. if (tokenisedDTD[i - 1].equalsIgnoreCase ("<!entity"))
  12515. {
  12516. String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">").trim().unquoted());
  12517. // check for sub-entities..
  12518. int ampersand = ent.indexOfChar ('&');
  12519. while (ampersand >= 0)
  12520. {
  12521. const int semiColon = ent.indexOf (i + 1, ";");
  12522. if (semiColon < 0)
  12523. {
  12524. setLastError ("entity without terminating semi-colon", false);
  12525. break;
  12526. }
  12527. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  12528. ent = ent.substring (0, ampersand)
  12529. + resolved
  12530. + ent.substring (semiColon + 1);
  12531. ampersand = ent.indexOfChar (semiColon + 1, '&');
  12532. }
  12533. return ent;
  12534. }
  12535. }
  12536. }
  12537. setLastError ("unknown entity", true);
  12538. return entity;
  12539. }
  12540. const String XmlDocument::getParameterEntity (const String& entity)
  12541. {
  12542. for (int i = 0; i < tokenisedDTD.size(); ++i)
  12543. {
  12544. if (tokenisedDTD[i] == entity)
  12545. {
  12546. if (tokenisedDTD [i - 1] == "%"
  12547. && tokenisedDTD [i - 2].equalsIgnoreCase ("<!entity"))
  12548. {
  12549. const String ent (tokenisedDTD [i + 1].trimCharactersAtEnd (">"));
  12550. if (ent.equalsIgnoreCase ("system"))
  12551. return getFileContents (tokenisedDTD [i + 2].trimCharactersAtEnd (">"));
  12552. else
  12553. return ent.trim().unquoted();
  12554. }
  12555. }
  12556. }
  12557. return entity;
  12558. }
  12559. END_JUCE_NAMESPACE
  12560. /*** End of inlined file: juce_XmlDocument.cpp ***/
  12561. /*** Start of inlined file: juce_XmlElement.cpp ***/
  12562. BEGIN_JUCE_NAMESPACE
  12563. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  12564. : name (other.name),
  12565. value (other.value),
  12566. next (0)
  12567. {
  12568. }
  12569. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_, const String& value_) throw()
  12570. : name (name_),
  12571. value (value_),
  12572. next (0)
  12573. {
  12574. }
  12575. XmlElement::XmlElement (const String& tagName_) throw()
  12576. : tagName (tagName_),
  12577. firstChildElement (0),
  12578. nextElement (0),
  12579. attributes (0)
  12580. {
  12581. // the tag name mustn't be empty, or it'll look like a text element!
  12582. jassert (tagName_.containsNonWhitespaceChars())
  12583. // The tag can't contain spaces or other characters that would create invalid XML!
  12584. jassert (! tagName_.containsAnyOf (" <>/&"));
  12585. }
  12586. XmlElement::XmlElement (int /*dummy*/) throw()
  12587. : firstChildElement (0),
  12588. nextElement (0),
  12589. attributes (0)
  12590. {
  12591. }
  12592. XmlElement::XmlElement (const XmlElement& other)
  12593. : tagName (other.tagName),
  12594. firstChildElement (0),
  12595. nextElement (0),
  12596. attributes (0)
  12597. {
  12598. copyChildrenAndAttributesFrom (other);
  12599. }
  12600. XmlElement& XmlElement::operator= (const XmlElement& other)
  12601. {
  12602. if (this != &other)
  12603. {
  12604. removeAllAttributes();
  12605. deleteAllChildElements();
  12606. tagName = other.tagName;
  12607. copyChildrenAndAttributesFrom (other);
  12608. }
  12609. return *this;
  12610. }
  12611. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other)
  12612. {
  12613. XmlElement* child = other.firstChildElement;
  12614. XmlElement* lastChild = 0;
  12615. while (child != 0)
  12616. {
  12617. XmlElement* const copiedChild = new XmlElement (*child);
  12618. if (lastChild != 0)
  12619. lastChild->nextElement = copiedChild;
  12620. else
  12621. firstChildElement = copiedChild;
  12622. lastChild = copiedChild;
  12623. child = child->nextElement;
  12624. }
  12625. const XmlAttributeNode* att = other.attributes;
  12626. XmlAttributeNode* lastAtt = 0;
  12627. while (att != 0)
  12628. {
  12629. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  12630. if (lastAtt != 0)
  12631. lastAtt->next = newAtt;
  12632. else
  12633. attributes = newAtt;
  12634. lastAtt = newAtt;
  12635. att = att->next;
  12636. }
  12637. }
  12638. XmlElement::~XmlElement() throw()
  12639. {
  12640. XmlElement* child = firstChildElement;
  12641. while (child != 0)
  12642. {
  12643. XmlElement* const nextChild = child->nextElement;
  12644. delete child;
  12645. child = nextChild;
  12646. }
  12647. XmlAttributeNode* att = attributes;
  12648. while (att != 0)
  12649. {
  12650. XmlAttributeNode* const nextAtt = att->next;
  12651. delete att;
  12652. att = nextAtt;
  12653. }
  12654. }
  12655. namespace XmlOutputFunctions
  12656. {
  12657. /*static bool isLegalXmlCharSlow (const juce_wchar character) throw()
  12658. {
  12659. if ((character >= 'a' && character <= 'z')
  12660. || (character >= 'A' && character <= 'Z')
  12661. || (character >= '0' && character <= '9'))
  12662. return true;
  12663. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}$|";
  12664. do
  12665. {
  12666. if (((juce_wchar) (uint8) *t) == character)
  12667. return true;
  12668. }
  12669. while (*++t != 0);
  12670. return false;
  12671. }
  12672. static void generateLegalCharConstants()
  12673. {
  12674. uint8 n[32];
  12675. zerostruct (n);
  12676. for (int i = 0; i < 256; ++i)
  12677. if (isLegalXmlCharSlow (i))
  12678. n[i >> 3] |= (1 << (i & 7));
  12679. String s;
  12680. for (int i = 0; i < 32; ++i)
  12681. s << (int) n[i] << ", ";
  12682. DBG (s);
  12683. }*/
  12684. static bool isLegalXmlChar (const uint32 c) throw()
  12685. {
  12686. static const unsigned char legalChars[] = { 0, 0, 0, 0, 187, 255, 255, 175, 255, 255, 255, 191, 254, 255, 255, 127 };
  12687. return c < sizeof (legalChars) * 8
  12688. && (legalChars [c >> 3] & (1 << (c & 7))) != 0;
  12689. }
  12690. static void escapeIllegalXmlChars (OutputStream& outputStream, const String& text, const bool changeNewLines)
  12691. {
  12692. const juce_wchar* t = text;
  12693. for (;;)
  12694. {
  12695. const juce_wchar character = *t++;
  12696. if (character == 0)
  12697. break;
  12698. if (isLegalXmlChar ((uint32) character))
  12699. {
  12700. outputStream << (char) character;
  12701. }
  12702. else
  12703. {
  12704. switch (character)
  12705. {
  12706. case '&': outputStream << "&amp;"; break;
  12707. case '"': outputStream << "&quot;"; break;
  12708. case '>': outputStream << "&gt;"; break;
  12709. case '<': outputStream << "&lt;"; break;
  12710. case '\n':
  12711. if (changeNewLines)
  12712. outputStream << "&#10;";
  12713. else
  12714. outputStream << (char) character;
  12715. break;
  12716. case '\r':
  12717. if (changeNewLines)
  12718. outputStream << "&#13;";
  12719. else
  12720. outputStream << (char) character;
  12721. break;
  12722. default:
  12723. outputStream << "&#" << ((int) (unsigned int) character) << ';';
  12724. break;
  12725. }
  12726. }
  12727. }
  12728. }
  12729. static void writeSpaces (OutputStream& out, int numSpaces)
  12730. {
  12731. if (numSpaces > 0)
  12732. {
  12733. const char blanks[] = " ";
  12734. const int blankSize = (int) numElementsInArray (blanks) - 1;
  12735. while (numSpaces > blankSize)
  12736. {
  12737. out.write (blanks, blankSize);
  12738. numSpaces -= blankSize;
  12739. }
  12740. out.write (blanks, numSpaces);
  12741. }
  12742. }
  12743. static void writeNewLine (OutputStream& out)
  12744. {
  12745. out.write ("\r\n", 2);
  12746. }
  12747. }
  12748. void XmlElement::writeElementAsText (OutputStream& outputStream,
  12749. const int indentationLevel,
  12750. const int lineWrapLength) const
  12751. {
  12752. using namespace XmlOutputFunctions;
  12753. writeSpaces (outputStream, indentationLevel);
  12754. if (! isTextElement())
  12755. {
  12756. outputStream.writeByte ('<');
  12757. outputStream << tagName;
  12758. {
  12759. const int attIndent = indentationLevel + tagName.length() + 1;
  12760. int lineLen = 0;
  12761. const XmlAttributeNode* att = attributes;
  12762. while (att != 0)
  12763. {
  12764. if (lineLen > lineWrapLength && indentationLevel >= 0)
  12765. {
  12766. writeNewLine (outputStream);
  12767. writeSpaces (outputStream, attIndent);
  12768. lineLen = 0;
  12769. }
  12770. const int64 startPos = outputStream.getPosition();
  12771. outputStream.writeByte (' ');
  12772. outputStream << att->name;
  12773. outputStream.write ("=\"", 2);
  12774. escapeIllegalXmlChars (outputStream, att->value, true);
  12775. outputStream.writeByte ('"');
  12776. lineLen += (int) (outputStream.getPosition() - startPos);
  12777. att = att->next;
  12778. }
  12779. }
  12780. if (firstChildElement != 0)
  12781. {
  12782. outputStream.writeByte ('>');
  12783. XmlElement* child = firstChildElement;
  12784. bool lastWasTextNode = false;
  12785. while (child != 0)
  12786. {
  12787. if (child->isTextElement())
  12788. {
  12789. escapeIllegalXmlChars (outputStream, child->getText(), false);
  12790. lastWasTextNode = true;
  12791. }
  12792. else
  12793. {
  12794. if (indentationLevel >= 0 && ! lastWasTextNode)
  12795. writeNewLine (outputStream);
  12796. child->writeElementAsText (outputStream,
  12797. lastWasTextNode ? 0 : (indentationLevel + (indentationLevel >= 0 ? 2 : 0)), lineWrapLength);
  12798. lastWasTextNode = false;
  12799. }
  12800. child = child->nextElement;
  12801. }
  12802. if (indentationLevel >= 0 && ! lastWasTextNode)
  12803. {
  12804. writeNewLine (outputStream);
  12805. writeSpaces (outputStream, indentationLevel);
  12806. }
  12807. outputStream.write ("</", 2);
  12808. outputStream << tagName;
  12809. outputStream.writeByte ('>');
  12810. }
  12811. else
  12812. {
  12813. outputStream.write ("/>", 2);
  12814. }
  12815. }
  12816. else
  12817. {
  12818. escapeIllegalXmlChars (outputStream, getText(), false);
  12819. }
  12820. }
  12821. const String XmlElement::createDocument (const String& dtdToUse,
  12822. const bool allOnOneLine,
  12823. const bool includeXmlHeader,
  12824. const String& encodingType,
  12825. const int lineWrapLength) const
  12826. {
  12827. MemoryOutputStream mem (2048);
  12828. writeToStream (mem, dtdToUse, allOnOneLine, includeXmlHeader, encodingType, lineWrapLength);
  12829. return mem.toUTF8();
  12830. }
  12831. void XmlElement::writeToStream (OutputStream& output,
  12832. const String& dtdToUse,
  12833. const bool allOnOneLine,
  12834. const bool includeXmlHeader,
  12835. const String& encodingType,
  12836. const int lineWrapLength) const
  12837. {
  12838. using namespace XmlOutputFunctions;
  12839. if (includeXmlHeader)
  12840. {
  12841. output << "<?xml version=\"1.0\" encoding=\"" << encodingType << "\"?>";
  12842. if (allOnOneLine)
  12843. {
  12844. output.writeByte (' ');
  12845. }
  12846. else
  12847. {
  12848. writeNewLine (output);
  12849. writeNewLine (output);
  12850. }
  12851. }
  12852. if (dtdToUse.isNotEmpty())
  12853. {
  12854. output << dtdToUse;
  12855. if (allOnOneLine)
  12856. output.writeByte (' ');
  12857. else
  12858. writeNewLine (output);
  12859. }
  12860. writeElementAsText (output, allOnOneLine ? -1 : 0, lineWrapLength);
  12861. if (! allOnOneLine)
  12862. writeNewLine (output);
  12863. }
  12864. bool XmlElement::writeToFile (const File& file,
  12865. const String& dtdToUse,
  12866. const String& encodingType,
  12867. const int lineWrapLength) const
  12868. {
  12869. if (file.hasWriteAccess())
  12870. {
  12871. TemporaryFile tempFile (file);
  12872. ScopedPointer <FileOutputStream> out (tempFile.getFile().createOutputStream());
  12873. if (out != 0)
  12874. {
  12875. writeToStream (*out, dtdToUse, false, true, encodingType, lineWrapLength);
  12876. out = 0;
  12877. return tempFile.overwriteTargetFileWithTemporary();
  12878. }
  12879. }
  12880. return false;
  12881. }
  12882. bool XmlElement::hasTagName (const String& tagNameWanted) const throw()
  12883. {
  12884. #if JUCE_DEBUG
  12885. // if debugging, check that the case is actually the same, because
  12886. // valid xml is case-sensitive, and although this lets it pass, it's
  12887. // better not to..
  12888. if (tagName.equalsIgnoreCase (tagNameWanted))
  12889. {
  12890. jassert (tagName == tagNameWanted);
  12891. return true;
  12892. }
  12893. else
  12894. {
  12895. return false;
  12896. }
  12897. #else
  12898. return tagName.equalsIgnoreCase (tagNameWanted);
  12899. #endif
  12900. }
  12901. XmlElement* XmlElement::getNextElementWithTagName (const String& requiredTagName) const
  12902. {
  12903. XmlElement* e = nextElement;
  12904. while (e != 0 && ! e->hasTagName (requiredTagName))
  12905. e = e->nextElement;
  12906. return e;
  12907. }
  12908. int XmlElement::getNumAttributes() const throw()
  12909. {
  12910. const XmlAttributeNode* att = attributes;
  12911. int count = 0;
  12912. while (att != 0)
  12913. {
  12914. att = att->next;
  12915. ++count;
  12916. }
  12917. return count;
  12918. }
  12919. const String& XmlElement::getAttributeName (const int index) const throw()
  12920. {
  12921. const XmlAttributeNode* att = attributes;
  12922. int count = 0;
  12923. while (att != 0)
  12924. {
  12925. if (count == index)
  12926. return att->name;
  12927. att = att->next;
  12928. ++count;
  12929. }
  12930. return String::empty;
  12931. }
  12932. const String& XmlElement::getAttributeValue (const int index) const throw()
  12933. {
  12934. const XmlAttributeNode* att = attributes;
  12935. int count = 0;
  12936. while (att != 0)
  12937. {
  12938. if (count == index)
  12939. return att->value;
  12940. att = att->next;
  12941. ++count;
  12942. }
  12943. return String::empty;
  12944. }
  12945. bool XmlElement::hasAttribute (const String& attributeName) const throw()
  12946. {
  12947. const XmlAttributeNode* att = attributes;
  12948. while (att != 0)
  12949. {
  12950. if (att->name.equalsIgnoreCase (attributeName))
  12951. return true;
  12952. att = att->next;
  12953. }
  12954. return false;
  12955. }
  12956. const String& XmlElement::getStringAttribute (const String& attributeName) const throw()
  12957. {
  12958. const XmlAttributeNode* att = attributes;
  12959. while (att != 0)
  12960. {
  12961. if (att->name.equalsIgnoreCase (attributeName))
  12962. return att->value;
  12963. att = att->next;
  12964. }
  12965. return String::empty;
  12966. }
  12967. const String XmlElement::getStringAttribute (const String& attributeName, const String& defaultReturnValue) const
  12968. {
  12969. const XmlAttributeNode* att = attributes;
  12970. while (att != 0)
  12971. {
  12972. if (att->name.equalsIgnoreCase (attributeName))
  12973. return att->value;
  12974. att = att->next;
  12975. }
  12976. return defaultReturnValue;
  12977. }
  12978. int XmlElement::getIntAttribute (const String& attributeName, const int defaultReturnValue) const
  12979. {
  12980. const XmlAttributeNode* att = attributes;
  12981. while (att != 0)
  12982. {
  12983. if (att->name.equalsIgnoreCase (attributeName))
  12984. return att->value.getIntValue();
  12985. att = att->next;
  12986. }
  12987. return defaultReturnValue;
  12988. }
  12989. double XmlElement::getDoubleAttribute (const String& attributeName, const double defaultReturnValue) const
  12990. {
  12991. const XmlAttributeNode* att = attributes;
  12992. while (att != 0)
  12993. {
  12994. if (att->name.equalsIgnoreCase (attributeName))
  12995. return att->value.getDoubleValue();
  12996. att = att->next;
  12997. }
  12998. return defaultReturnValue;
  12999. }
  13000. bool XmlElement::getBoolAttribute (const String& attributeName, const bool defaultReturnValue) const
  13001. {
  13002. const XmlAttributeNode* att = attributes;
  13003. while (att != 0)
  13004. {
  13005. if (att->name.equalsIgnoreCase (attributeName))
  13006. {
  13007. juce_wchar firstChar = att->value[0];
  13008. if (CharacterFunctions::isWhitespace (firstChar))
  13009. firstChar = att->value.trimStart() [0];
  13010. return firstChar == '1'
  13011. || firstChar == 't'
  13012. || firstChar == 'y'
  13013. || firstChar == 'T'
  13014. || firstChar == 'Y';
  13015. }
  13016. att = att->next;
  13017. }
  13018. return defaultReturnValue;
  13019. }
  13020. bool XmlElement::compareAttribute (const String& attributeName,
  13021. const String& stringToCompareAgainst,
  13022. const bool ignoreCase) const throw()
  13023. {
  13024. const XmlAttributeNode* att = attributes;
  13025. while (att != 0)
  13026. {
  13027. if (att->name.equalsIgnoreCase (attributeName))
  13028. {
  13029. if (ignoreCase)
  13030. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  13031. else
  13032. return att->value == stringToCompareAgainst;
  13033. }
  13034. att = att->next;
  13035. }
  13036. return false;
  13037. }
  13038. void XmlElement::setAttribute (const String& attributeName, const String& value)
  13039. {
  13040. #if JUCE_DEBUG
  13041. // check the identifier being passed in is legal..
  13042. const juce_wchar* t = attributeName;
  13043. while (*t != 0)
  13044. {
  13045. jassert (CharacterFunctions::isLetterOrDigit (*t)
  13046. || *t == '_'
  13047. || *t == '-'
  13048. || *t == ':');
  13049. ++t;
  13050. }
  13051. #endif
  13052. if (attributes == 0)
  13053. {
  13054. attributes = new XmlAttributeNode (attributeName, value);
  13055. }
  13056. else
  13057. {
  13058. XmlAttributeNode* att = attributes;
  13059. for (;;)
  13060. {
  13061. if (att->name.equalsIgnoreCase (attributeName))
  13062. {
  13063. att->value = value;
  13064. break;
  13065. }
  13066. else if (att->next == 0)
  13067. {
  13068. att->next = new XmlAttributeNode (attributeName, value);
  13069. break;
  13070. }
  13071. att = att->next;
  13072. }
  13073. }
  13074. }
  13075. void XmlElement::setAttribute (const String& attributeName, const int number)
  13076. {
  13077. setAttribute (attributeName, String (number));
  13078. }
  13079. void XmlElement::setAttribute (const String& attributeName, const double number)
  13080. {
  13081. setAttribute (attributeName, String (number));
  13082. }
  13083. void XmlElement::removeAttribute (const String& attributeName) throw()
  13084. {
  13085. XmlAttributeNode* att = attributes;
  13086. XmlAttributeNode* lastAtt = 0;
  13087. while (att != 0)
  13088. {
  13089. if (att->name.equalsIgnoreCase (attributeName))
  13090. {
  13091. if (lastAtt == 0)
  13092. attributes = att->next;
  13093. else
  13094. lastAtt->next = att->next;
  13095. delete att;
  13096. break;
  13097. }
  13098. lastAtt = att;
  13099. att = att->next;
  13100. }
  13101. }
  13102. void XmlElement::removeAllAttributes() throw()
  13103. {
  13104. while (attributes != 0)
  13105. {
  13106. XmlAttributeNode* const nextAtt = attributes->next;
  13107. delete attributes;
  13108. attributes = nextAtt;
  13109. }
  13110. }
  13111. int XmlElement::getNumChildElements() const throw()
  13112. {
  13113. int count = 0;
  13114. const XmlElement* child = firstChildElement;
  13115. while (child != 0)
  13116. {
  13117. ++count;
  13118. child = child->nextElement;
  13119. }
  13120. return count;
  13121. }
  13122. XmlElement* XmlElement::getChildElement (const int index) const throw()
  13123. {
  13124. int count = 0;
  13125. XmlElement* child = firstChildElement;
  13126. while (child != 0 && count < index)
  13127. {
  13128. child = child->nextElement;
  13129. ++count;
  13130. }
  13131. return child;
  13132. }
  13133. XmlElement* XmlElement::getChildByName (const String& childName) const throw()
  13134. {
  13135. XmlElement* child = firstChildElement;
  13136. while (child != 0)
  13137. {
  13138. if (child->hasTagName (childName))
  13139. break;
  13140. child = child->nextElement;
  13141. }
  13142. return child;
  13143. }
  13144. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  13145. {
  13146. if (newNode != 0)
  13147. {
  13148. if (firstChildElement == 0)
  13149. {
  13150. firstChildElement = newNode;
  13151. }
  13152. else
  13153. {
  13154. XmlElement* child = firstChildElement;
  13155. while (child->nextElement != 0)
  13156. child = child->nextElement;
  13157. child->nextElement = newNode;
  13158. // if this is non-zero, then something's probably
  13159. // gone wrong..
  13160. jassert (newNode->nextElement == 0);
  13161. }
  13162. }
  13163. }
  13164. void XmlElement::insertChildElement (XmlElement* const newNode,
  13165. int indexToInsertAt) throw()
  13166. {
  13167. if (newNode != 0)
  13168. {
  13169. removeChildElement (newNode, false);
  13170. if (indexToInsertAt == 0)
  13171. {
  13172. newNode->nextElement = firstChildElement;
  13173. firstChildElement = newNode;
  13174. }
  13175. else
  13176. {
  13177. if (firstChildElement == 0)
  13178. {
  13179. firstChildElement = newNode;
  13180. }
  13181. else
  13182. {
  13183. if (indexToInsertAt < 0)
  13184. indexToInsertAt = std::numeric_limits<int>::max();
  13185. XmlElement* child = firstChildElement;
  13186. while (child->nextElement != 0 && --indexToInsertAt > 0)
  13187. child = child->nextElement;
  13188. newNode->nextElement = child->nextElement;
  13189. child->nextElement = newNode;
  13190. }
  13191. }
  13192. }
  13193. }
  13194. XmlElement* XmlElement::createNewChildElement (const String& childTagName)
  13195. {
  13196. XmlElement* const newElement = new XmlElement (childTagName);
  13197. addChildElement (newElement);
  13198. return newElement;
  13199. }
  13200. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  13201. XmlElement* const newNode) throw()
  13202. {
  13203. if (newNode != 0)
  13204. {
  13205. XmlElement* child = firstChildElement;
  13206. XmlElement* previousNode = 0;
  13207. while (child != 0)
  13208. {
  13209. if (child == currentChildElement)
  13210. {
  13211. if (child != newNode)
  13212. {
  13213. if (previousNode == 0)
  13214. firstChildElement = newNode;
  13215. else
  13216. previousNode->nextElement = newNode;
  13217. newNode->nextElement = child->nextElement;
  13218. delete child;
  13219. }
  13220. return true;
  13221. }
  13222. previousNode = child;
  13223. child = child->nextElement;
  13224. }
  13225. }
  13226. return false;
  13227. }
  13228. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  13229. const bool shouldDeleteTheChild) throw()
  13230. {
  13231. if (childToRemove != 0)
  13232. {
  13233. if (firstChildElement == childToRemove)
  13234. {
  13235. firstChildElement = childToRemove->nextElement;
  13236. childToRemove->nextElement = 0;
  13237. }
  13238. else
  13239. {
  13240. XmlElement* child = firstChildElement;
  13241. XmlElement* last = 0;
  13242. while (child != 0)
  13243. {
  13244. if (child == childToRemove)
  13245. {
  13246. if (last == 0)
  13247. firstChildElement = child->nextElement;
  13248. else
  13249. last->nextElement = child->nextElement;
  13250. childToRemove->nextElement = 0;
  13251. break;
  13252. }
  13253. last = child;
  13254. child = child->nextElement;
  13255. }
  13256. }
  13257. if (shouldDeleteTheChild)
  13258. delete childToRemove;
  13259. }
  13260. }
  13261. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  13262. const bool ignoreOrderOfAttributes) const throw()
  13263. {
  13264. if (this != other)
  13265. {
  13266. if (other == 0 || tagName != other->tagName)
  13267. return false;
  13268. if (ignoreOrderOfAttributes)
  13269. {
  13270. int totalAtts = 0;
  13271. const XmlAttributeNode* att = attributes;
  13272. while (att != 0)
  13273. {
  13274. if (! other->compareAttribute (att->name, att->value))
  13275. return false;
  13276. att = att->next;
  13277. ++totalAtts;
  13278. }
  13279. if (totalAtts != other->getNumAttributes())
  13280. return false;
  13281. }
  13282. else
  13283. {
  13284. const XmlAttributeNode* thisAtt = attributes;
  13285. const XmlAttributeNode* otherAtt = other->attributes;
  13286. for (;;)
  13287. {
  13288. if (thisAtt == 0 || otherAtt == 0)
  13289. {
  13290. if (thisAtt == otherAtt) // both 0, so it's a match
  13291. break;
  13292. return false;
  13293. }
  13294. if (thisAtt->name != otherAtt->name
  13295. || thisAtt->value != otherAtt->value)
  13296. {
  13297. return false;
  13298. }
  13299. thisAtt = thisAtt->next;
  13300. otherAtt = otherAtt->next;
  13301. }
  13302. }
  13303. const XmlElement* thisChild = firstChildElement;
  13304. const XmlElement* otherChild = other->firstChildElement;
  13305. for (;;)
  13306. {
  13307. if (thisChild == 0 || otherChild == 0)
  13308. {
  13309. if (thisChild == otherChild) // both 0, so it's a match
  13310. break;
  13311. return false;
  13312. }
  13313. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  13314. return false;
  13315. thisChild = thisChild->nextElement;
  13316. otherChild = otherChild->nextElement;
  13317. }
  13318. }
  13319. return true;
  13320. }
  13321. void XmlElement::deleteAllChildElements() throw()
  13322. {
  13323. while (firstChildElement != 0)
  13324. {
  13325. XmlElement* const nextChild = firstChildElement->nextElement;
  13326. delete firstChildElement;
  13327. firstChildElement = nextChild;
  13328. }
  13329. }
  13330. void XmlElement::deleteAllChildElementsWithTagName (const String& name) throw()
  13331. {
  13332. XmlElement* child = firstChildElement;
  13333. while (child != 0)
  13334. {
  13335. if (child->hasTagName (name))
  13336. {
  13337. XmlElement* const nextChild = child->nextElement;
  13338. removeChildElement (child, true);
  13339. child = nextChild;
  13340. }
  13341. else
  13342. {
  13343. child = child->nextElement;
  13344. }
  13345. }
  13346. }
  13347. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  13348. {
  13349. const XmlElement* child = firstChildElement;
  13350. while (child != 0)
  13351. {
  13352. if (child == possibleChild)
  13353. return true;
  13354. child = child->nextElement;
  13355. }
  13356. return false;
  13357. }
  13358. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  13359. {
  13360. if (this == elementToLookFor || elementToLookFor == 0)
  13361. return 0;
  13362. XmlElement* child = firstChildElement;
  13363. while (child != 0)
  13364. {
  13365. if (elementToLookFor == child)
  13366. return this;
  13367. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  13368. if (found != 0)
  13369. return found;
  13370. child = child->nextElement;
  13371. }
  13372. return 0;
  13373. }
  13374. void XmlElement::getChildElementsAsArray (XmlElement** elems) const throw()
  13375. {
  13376. XmlElement* e = firstChildElement;
  13377. while (e != 0)
  13378. {
  13379. *elems++ = e;
  13380. e = e->nextElement;
  13381. }
  13382. }
  13383. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  13384. {
  13385. XmlElement* e = firstChildElement = elems[0];
  13386. for (int i = 1; i < num; ++i)
  13387. {
  13388. e->nextElement = elems[i];
  13389. e = e->nextElement;
  13390. }
  13391. e->nextElement = 0;
  13392. }
  13393. bool XmlElement::isTextElement() const throw()
  13394. {
  13395. return tagName.isEmpty();
  13396. }
  13397. static const juce_wchar* const juce_xmltextContentAttributeName = L"text";
  13398. const String& XmlElement::getText() const throw()
  13399. {
  13400. jassert (isTextElement()); // you're trying to get the text from an element that
  13401. // isn't actually a text element.. If this contains text sub-nodes, you
  13402. // probably want to use getAllSubText instead.
  13403. return getStringAttribute (juce_xmltextContentAttributeName);
  13404. }
  13405. void XmlElement::setText (const String& newText)
  13406. {
  13407. if (isTextElement())
  13408. setAttribute (juce_xmltextContentAttributeName, newText);
  13409. else
  13410. jassertfalse; // you can only change the text in a text element, not a normal one.
  13411. }
  13412. const String XmlElement::getAllSubText() const
  13413. {
  13414. if (isTextElement())
  13415. return getText();
  13416. String result;
  13417. String::Concatenator concatenator (result);
  13418. const XmlElement* child = firstChildElement;
  13419. while (child != 0)
  13420. {
  13421. concatenator.append (child->getAllSubText());
  13422. child = child->nextElement;
  13423. }
  13424. return result;
  13425. }
  13426. const String XmlElement::getChildElementAllSubText (const String& childTagName,
  13427. const String& defaultReturnValue) const
  13428. {
  13429. const XmlElement* const child = getChildByName (childTagName);
  13430. if (child != 0)
  13431. return child->getAllSubText();
  13432. return defaultReturnValue;
  13433. }
  13434. XmlElement* XmlElement::createTextElement (const String& text)
  13435. {
  13436. XmlElement* const e = new XmlElement ((int) 0);
  13437. e->setAttribute (juce_xmltextContentAttributeName, text);
  13438. return e;
  13439. }
  13440. void XmlElement::addTextElement (const String& text)
  13441. {
  13442. addChildElement (createTextElement (text));
  13443. }
  13444. void XmlElement::deleteAllTextElements() throw()
  13445. {
  13446. XmlElement* child = firstChildElement;
  13447. while (child != 0)
  13448. {
  13449. XmlElement* const next = child->nextElement;
  13450. if (child->isTextElement())
  13451. removeChildElement (child, true);
  13452. child = next;
  13453. }
  13454. }
  13455. END_JUCE_NAMESPACE
  13456. /*** End of inlined file: juce_XmlElement.cpp ***/
  13457. /*** Start of inlined file: juce_ReadWriteLock.cpp ***/
  13458. BEGIN_JUCE_NAMESPACE
  13459. ReadWriteLock::ReadWriteLock() throw()
  13460. : numWaitingWriters (0),
  13461. numWriters (0),
  13462. writerThreadId (0)
  13463. {
  13464. }
  13465. ReadWriteLock::~ReadWriteLock() throw()
  13466. {
  13467. jassert (readerThreads.size() == 0);
  13468. jassert (numWriters == 0);
  13469. }
  13470. void ReadWriteLock::enterRead() const throw()
  13471. {
  13472. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13473. const ScopedLock sl (accessLock);
  13474. for (;;)
  13475. {
  13476. jassert (readerThreads.size() % 2 == 0);
  13477. int i;
  13478. for (i = 0; i < readerThreads.size(); i += 2)
  13479. if (readerThreads.getUnchecked(i) == threadId)
  13480. break;
  13481. if (i < readerThreads.size()
  13482. || numWriters + numWaitingWriters == 0
  13483. || (threadId == writerThreadId && numWriters > 0))
  13484. {
  13485. if (i < readerThreads.size())
  13486. {
  13487. readerThreads.set (i + 1, (Thread::ThreadID) (1 + (pointer_sized_int) readerThreads.getUnchecked (i + 1)));
  13488. }
  13489. else
  13490. {
  13491. readerThreads.add (threadId);
  13492. readerThreads.add ((Thread::ThreadID) 1);
  13493. }
  13494. return;
  13495. }
  13496. const ScopedUnlock ul (accessLock);
  13497. waitEvent.wait (100);
  13498. }
  13499. }
  13500. void ReadWriteLock::exitRead() const throw()
  13501. {
  13502. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13503. const ScopedLock sl (accessLock);
  13504. for (int i = 0; i < readerThreads.size(); i += 2)
  13505. {
  13506. if (readerThreads.getUnchecked(i) == threadId)
  13507. {
  13508. const pointer_sized_int newCount = ((pointer_sized_int) readerThreads.getUnchecked (i + 1)) - 1;
  13509. if (newCount == 0)
  13510. {
  13511. readerThreads.removeRange (i, 2);
  13512. waitEvent.signal();
  13513. }
  13514. else
  13515. {
  13516. readerThreads.set (i + 1, (Thread::ThreadID) newCount);
  13517. }
  13518. return;
  13519. }
  13520. }
  13521. jassertfalse; // unlocking a lock that wasn't locked..
  13522. }
  13523. void ReadWriteLock::enterWrite() const throw()
  13524. {
  13525. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13526. const ScopedLock sl (accessLock);
  13527. for (;;)
  13528. {
  13529. if (readerThreads.size() + numWriters == 0
  13530. || threadId == writerThreadId
  13531. || (readerThreads.size() == 2
  13532. && readerThreads.getUnchecked(0) == threadId))
  13533. {
  13534. writerThreadId = threadId;
  13535. ++numWriters;
  13536. break;
  13537. }
  13538. ++numWaitingWriters;
  13539. accessLock.exit();
  13540. waitEvent.wait (100);
  13541. accessLock.enter();
  13542. --numWaitingWriters;
  13543. }
  13544. }
  13545. bool ReadWriteLock::tryEnterWrite() const throw()
  13546. {
  13547. const Thread::ThreadID threadId = Thread::getCurrentThreadId();
  13548. const ScopedLock sl (accessLock);
  13549. if (readerThreads.size() + numWriters == 0
  13550. || threadId == writerThreadId
  13551. || (readerThreads.size() == 2
  13552. && readerThreads.getUnchecked(0) == threadId))
  13553. {
  13554. writerThreadId = threadId;
  13555. ++numWriters;
  13556. return true;
  13557. }
  13558. return false;
  13559. }
  13560. void ReadWriteLock::exitWrite() const throw()
  13561. {
  13562. const ScopedLock sl (accessLock);
  13563. // check this thread actually had the lock..
  13564. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  13565. if (--numWriters == 0)
  13566. {
  13567. writerThreadId = 0;
  13568. waitEvent.signal();
  13569. }
  13570. }
  13571. END_JUCE_NAMESPACE
  13572. /*** End of inlined file: juce_ReadWriteLock.cpp ***/
  13573. /*** Start of inlined file: juce_Thread.cpp ***/
  13574. BEGIN_JUCE_NAMESPACE
  13575. // these functions are implemented in the platform-specific code.
  13576. void* juce_createThread (void* userData);
  13577. void juce_killThread (void* handle);
  13578. bool juce_setThreadPriority (void* handle, int priority);
  13579. void juce_setCurrentThreadName (const String& name);
  13580. #if JUCE_WINDOWS
  13581. void juce_CloseThreadHandle (void* handle);
  13582. #endif
  13583. void Thread::threadEntryPoint (Thread* const thread)
  13584. {
  13585. {
  13586. const ScopedLock sl (runningThreadsLock);
  13587. runningThreads.add (thread);
  13588. }
  13589. JUCE_TRY
  13590. {
  13591. thread->threadId_ = Thread::getCurrentThreadId();
  13592. if (thread->threadName_.isNotEmpty())
  13593. juce_setCurrentThreadName (thread->threadName_);
  13594. if (thread->startSuspensionEvent_.wait (10000))
  13595. {
  13596. if (thread->affinityMask_ != 0)
  13597. setCurrentThreadAffinityMask (thread->affinityMask_);
  13598. thread->run();
  13599. }
  13600. }
  13601. JUCE_CATCH_ALL_ASSERT
  13602. {
  13603. const ScopedLock sl (runningThreadsLock);
  13604. jassert (runningThreads.contains (thread));
  13605. runningThreads.removeValue (thread);
  13606. }
  13607. #if JUCE_WINDOWS
  13608. juce_CloseThreadHandle (thread->threadHandle_);
  13609. #endif
  13610. thread->threadHandle_ = 0;
  13611. thread->threadId_ = 0;
  13612. }
  13613. // used to wrap the incoming call from the platform-specific code
  13614. void JUCE_API juce_threadEntryPoint (void* userData)
  13615. {
  13616. Thread::threadEntryPoint (static_cast <Thread*> (userData));
  13617. }
  13618. Thread::Thread (const String& threadName)
  13619. : threadName_ (threadName),
  13620. threadHandle_ (0),
  13621. threadPriority_ (5),
  13622. threadId_ (0),
  13623. affinityMask_ (0),
  13624. threadShouldExit_ (false)
  13625. {
  13626. }
  13627. Thread::~Thread()
  13628. {
  13629. stopThread (100);
  13630. }
  13631. void Thread::startThread()
  13632. {
  13633. const ScopedLock sl (startStopLock);
  13634. threadShouldExit_ = false;
  13635. if (threadHandle_ == 0)
  13636. {
  13637. threadHandle_ = juce_createThread (this);
  13638. juce_setThreadPriority (threadHandle_, threadPriority_);
  13639. startSuspensionEvent_.signal();
  13640. }
  13641. }
  13642. void Thread::startThread (const int priority)
  13643. {
  13644. const ScopedLock sl (startStopLock);
  13645. if (threadHandle_ == 0)
  13646. {
  13647. threadPriority_ = priority;
  13648. startThread();
  13649. }
  13650. else
  13651. {
  13652. setPriority (priority);
  13653. }
  13654. }
  13655. bool Thread::isThreadRunning() const
  13656. {
  13657. return threadHandle_ != 0;
  13658. }
  13659. void Thread::signalThreadShouldExit()
  13660. {
  13661. threadShouldExit_ = true;
  13662. }
  13663. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const
  13664. {
  13665. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  13666. jassert (getThreadId() != getCurrentThreadId());
  13667. const int sleepMsPerIteration = 5;
  13668. int count = timeOutMilliseconds / sleepMsPerIteration;
  13669. while (isThreadRunning())
  13670. {
  13671. if (timeOutMilliseconds > 0 && --count < 0)
  13672. return false;
  13673. sleep (sleepMsPerIteration);
  13674. }
  13675. return true;
  13676. }
  13677. void Thread::stopThread (const int timeOutMilliseconds)
  13678. {
  13679. // agh! You can't stop the thread that's calling this method! How on earth
  13680. // would that work??
  13681. jassert (getCurrentThreadId() != getThreadId());
  13682. const ScopedLock sl (startStopLock);
  13683. if (isThreadRunning())
  13684. {
  13685. signalThreadShouldExit();
  13686. notify();
  13687. if (timeOutMilliseconds != 0)
  13688. waitForThreadToExit (timeOutMilliseconds);
  13689. if (isThreadRunning())
  13690. {
  13691. // very bad karma if this point is reached, as
  13692. // there are bound to be locks and events left in
  13693. // silly states when a thread is killed by force..
  13694. jassertfalse;
  13695. Logger::writeToLog ("!! killing thread by force !!");
  13696. juce_killThread (threadHandle_);
  13697. threadHandle_ = 0;
  13698. threadId_ = 0;
  13699. const ScopedLock sl2 (runningThreadsLock);
  13700. runningThreads.removeValue (this);
  13701. }
  13702. }
  13703. }
  13704. bool Thread::setPriority (const int priority)
  13705. {
  13706. const ScopedLock sl (startStopLock);
  13707. const bool worked = juce_setThreadPriority (threadHandle_, priority);
  13708. if (worked)
  13709. threadPriority_ = priority;
  13710. return worked;
  13711. }
  13712. bool Thread::setCurrentThreadPriority (const int priority)
  13713. {
  13714. return juce_setThreadPriority (0, priority);
  13715. }
  13716. void Thread::setAffinityMask (const uint32 affinityMask)
  13717. {
  13718. affinityMask_ = affinityMask;
  13719. }
  13720. bool Thread::wait (const int timeOutMilliseconds) const
  13721. {
  13722. return defaultEvent_.wait (timeOutMilliseconds);
  13723. }
  13724. void Thread::notify() const
  13725. {
  13726. defaultEvent_.signal();
  13727. }
  13728. int Thread::getNumRunningThreads()
  13729. {
  13730. return runningThreads.size();
  13731. }
  13732. Thread* Thread::getCurrentThread()
  13733. {
  13734. const ThreadID thisId = getCurrentThreadId();
  13735. const ScopedLock sl (runningThreadsLock);
  13736. for (int i = runningThreads.size(); --i >= 0;)
  13737. {
  13738. Thread* const t = runningThreads.getUnchecked(i);
  13739. if (t->threadId_ == thisId)
  13740. return t;
  13741. }
  13742. return 0;
  13743. }
  13744. void Thread::stopAllThreads (const int timeOutMilliseconds)
  13745. {
  13746. {
  13747. const ScopedLock sl (runningThreadsLock);
  13748. for (int i = runningThreads.size(); --i >= 0;)
  13749. runningThreads.getUnchecked(i)->signalThreadShouldExit();
  13750. }
  13751. for (;;)
  13752. {
  13753. Thread* firstThread;
  13754. {
  13755. const ScopedLock sl (runningThreadsLock);
  13756. firstThread = runningThreads.getFirst();
  13757. }
  13758. if (firstThread == 0)
  13759. break;
  13760. firstThread->stopThread (timeOutMilliseconds);
  13761. }
  13762. }
  13763. Array<Thread*> Thread::runningThreads;
  13764. CriticalSection Thread::runningThreadsLock;
  13765. END_JUCE_NAMESPACE
  13766. /*** End of inlined file: juce_Thread.cpp ***/
  13767. /*** Start of inlined file: juce_ThreadPool.cpp ***/
  13768. BEGIN_JUCE_NAMESPACE
  13769. ThreadPoolJob::ThreadPoolJob (const String& name)
  13770. : jobName (name),
  13771. pool (0),
  13772. shouldStop (false),
  13773. isActive (false),
  13774. shouldBeDeleted (false)
  13775. {
  13776. }
  13777. ThreadPoolJob::~ThreadPoolJob()
  13778. {
  13779. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  13780. // to remove it first!
  13781. jassert (pool == 0 || ! pool->contains (this));
  13782. }
  13783. const String ThreadPoolJob::getJobName() const
  13784. {
  13785. return jobName;
  13786. }
  13787. void ThreadPoolJob::setJobName (const String& newName)
  13788. {
  13789. jobName = newName;
  13790. }
  13791. void ThreadPoolJob::signalJobShouldExit()
  13792. {
  13793. shouldStop = true;
  13794. }
  13795. class ThreadPool::ThreadPoolThread : public Thread
  13796. {
  13797. public:
  13798. ThreadPoolThread (ThreadPool& pool_)
  13799. : Thread ("Pool"),
  13800. pool (pool_),
  13801. busy (false)
  13802. {
  13803. }
  13804. ~ThreadPoolThread()
  13805. {
  13806. }
  13807. void run()
  13808. {
  13809. while (! threadShouldExit())
  13810. {
  13811. if (! pool.runNextJob())
  13812. wait (500);
  13813. }
  13814. }
  13815. private:
  13816. ThreadPool& pool;
  13817. bool volatile busy;
  13818. ThreadPoolThread (const ThreadPoolThread&);
  13819. ThreadPoolThread& operator= (const ThreadPoolThread&);
  13820. };
  13821. ThreadPool::ThreadPool (const int numThreads,
  13822. const bool startThreadsOnlyWhenNeeded,
  13823. const int stopThreadsWhenNotUsedTimeoutMs)
  13824. : threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  13825. priority (5)
  13826. {
  13827. jassert (numThreads > 0); // not much point having one of these with no threads in it.
  13828. for (int i = jmax (1, numThreads); --i >= 0;)
  13829. threads.add (new ThreadPoolThread (*this));
  13830. if (! startThreadsOnlyWhenNeeded)
  13831. for (int i = threads.size(); --i >= 0;)
  13832. threads.getUnchecked(i)->startThread (priority);
  13833. }
  13834. ThreadPool::~ThreadPool()
  13835. {
  13836. removeAllJobs (true, 4000);
  13837. int i;
  13838. for (i = threads.size(); --i >= 0;)
  13839. threads.getUnchecked(i)->signalThreadShouldExit();
  13840. for (i = threads.size(); --i >= 0;)
  13841. threads.getUnchecked(i)->stopThread (500);
  13842. }
  13843. void ThreadPool::addJob (ThreadPoolJob* const job)
  13844. {
  13845. jassert (job != 0);
  13846. jassert (job->pool == 0);
  13847. if (job->pool == 0)
  13848. {
  13849. job->pool = this;
  13850. job->shouldStop = false;
  13851. job->isActive = false;
  13852. {
  13853. const ScopedLock sl (lock);
  13854. jobs.add (job);
  13855. int numRunning = 0;
  13856. for (int i = threads.size(); --i >= 0;)
  13857. if (threads.getUnchecked(i)->isThreadRunning() && ! threads.getUnchecked(i)->threadShouldExit())
  13858. ++numRunning;
  13859. if (numRunning < threads.size())
  13860. {
  13861. bool startedOne = false;
  13862. int n = 1000;
  13863. while (--n >= 0 && ! startedOne)
  13864. {
  13865. for (int i = threads.size(); --i >= 0;)
  13866. {
  13867. if (! threads.getUnchecked(i)->isThreadRunning())
  13868. {
  13869. threads.getUnchecked(i)->startThread (priority);
  13870. startedOne = true;
  13871. break;
  13872. }
  13873. }
  13874. if (! startedOne)
  13875. Thread::sleep (2);
  13876. }
  13877. }
  13878. }
  13879. for (int i = threads.size(); --i >= 0;)
  13880. threads.getUnchecked(i)->notify();
  13881. }
  13882. }
  13883. int ThreadPool::getNumJobs() const
  13884. {
  13885. return jobs.size();
  13886. }
  13887. ThreadPoolJob* ThreadPool::getJob (const int index) const
  13888. {
  13889. const ScopedLock sl (lock);
  13890. return jobs [index];
  13891. }
  13892. bool ThreadPool::contains (const ThreadPoolJob* const job) const
  13893. {
  13894. const ScopedLock sl (lock);
  13895. return jobs.contains (const_cast <ThreadPoolJob*> (job));
  13896. }
  13897. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  13898. {
  13899. const ScopedLock sl (lock);
  13900. return jobs.contains (const_cast <ThreadPoolJob*> (job)) && job->isActive;
  13901. }
  13902. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  13903. const int timeOutMs) const
  13904. {
  13905. if (job != 0)
  13906. {
  13907. const uint32 start = Time::getMillisecondCounter();
  13908. while (contains (job))
  13909. {
  13910. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13911. return false;
  13912. jobFinishedSignal.wait (2);
  13913. }
  13914. }
  13915. return true;
  13916. }
  13917. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  13918. const bool interruptIfRunning,
  13919. const int timeOutMs)
  13920. {
  13921. bool dontWait = true;
  13922. if (job != 0)
  13923. {
  13924. const ScopedLock sl (lock);
  13925. if (jobs.contains (job))
  13926. {
  13927. if (job->isActive)
  13928. {
  13929. if (interruptIfRunning)
  13930. job->signalJobShouldExit();
  13931. dontWait = false;
  13932. }
  13933. else
  13934. {
  13935. jobs.removeValue (job);
  13936. job->pool = 0;
  13937. }
  13938. }
  13939. }
  13940. return dontWait || waitForJobToFinish (job, timeOutMs);
  13941. }
  13942. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  13943. const int timeOutMs,
  13944. const bool deleteInactiveJobs,
  13945. ThreadPool::JobSelector* selectedJobsToRemove)
  13946. {
  13947. Array <ThreadPoolJob*> jobsToWaitFor;
  13948. {
  13949. const ScopedLock sl (lock);
  13950. for (int i = jobs.size(); --i >= 0;)
  13951. {
  13952. ThreadPoolJob* const job = jobs.getUnchecked(i);
  13953. if (selectedJobsToRemove == 0 || selectedJobsToRemove->isJobSuitable (job))
  13954. {
  13955. if (job->isActive)
  13956. {
  13957. jobsToWaitFor.add (job);
  13958. if (interruptRunningJobs)
  13959. job->signalJobShouldExit();
  13960. }
  13961. else
  13962. {
  13963. jobs.remove (i);
  13964. if (deleteInactiveJobs)
  13965. delete job;
  13966. else
  13967. job->pool = 0;
  13968. }
  13969. }
  13970. }
  13971. }
  13972. const uint32 start = Time::getMillisecondCounter();
  13973. for (;;)
  13974. {
  13975. for (int i = jobsToWaitFor.size(); --i >= 0;)
  13976. if (! isJobRunning (jobsToWaitFor.getUnchecked (i)))
  13977. jobsToWaitFor.remove (i);
  13978. if (jobsToWaitFor.size() == 0)
  13979. break;
  13980. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  13981. return false;
  13982. jobFinishedSignal.wait (20);
  13983. }
  13984. return true;
  13985. }
  13986. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  13987. {
  13988. StringArray s;
  13989. const ScopedLock sl (lock);
  13990. for (int i = 0; i < jobs.size(); ++i)
  13991. {
  13992. const ThreadPoolJob* const job = jobs.getUnchecked(i);
  13993. if (job->isActive || ! onlyReturnActiveJobs)
  13994. s.add (job->getJobName());
  13995. }
  13996. return s;
  13997. }
  13998. bool ThreadPool::setThreadPriorities (const int newPriority)
  13999. {
  14000. bool ok = true;
  14001. if (priority != newPriority)
  14002. {
  14003. priority = newPriority;
  14004. for (int i = threads.size(); --i >= 0;)
  14005. if (! threads.getUnchecked(i)->setPriority (newPriority))
  14006. ok = false;
  14007. }
  14008. return ok;
  14009. }
  14010. bool ThreadPool::runNextJob()
  14011. {
  14012. ThreadPoolJob* job = 0;
  14013. {
  14014. const ScopedLock sl (lock);
  14015. for (int i = 0; i < jobs.size(); ++i)
  14016. {
  14017. job = jobs[i];
  14018. if (job != 0 && ! (job->isActive || job->shouldStop))
  14019. break;
  14020. job = 0;
  14021. }
  14022. if (job != 0)
  14023. job->isActive = true;
  14024. }
  14025. if (job != 0)
  14026. {
  14027. JUCE_TRY
  14028. {
  14029. ThreadPoolJob::JobStatus result = job->runJob();
  14030. lastJobEndTime = Time::getApproximateMillisecondCounter();
  14031. const ScopedLock sl (lock);
  14032. if (jobs.contains (job))
  14033. {
  14034. job->isActive = false;
  14035. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  14036. {
  14037. job->pool = 0;
  14038. job->shouldStop = true;
  14039. jobs.removeValue (job);
  14040. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  14041. delete job;
  14042. jobFinishedSignal.signal();
  14043. }
  14044. else
  14045. {
  14046. // move the job to the end of the queue if it wants another go
  14047. jobs.move (jobs.indexOf (job), -1);
  14048. }
  14049. }
  14050. }
  14051. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  14052. catch (...)
  14053. {
  14054. const ScopedLock sl (lock);
  14055. jobs.removeValue (job);
  14056. }
  14057. #endif
  14058. }
  14059. else
  14060. {
  14061. if (threadStopTimeout > 0
  14062. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  14063. {
  14064. const ScopedLock sl (lock);
  14065. if (jobs.size() == 0)
  14066. for (int i = threads.size(); --i >= 0;)
  14067. threads.getUnchecked(i)->signalThreadShouldExit();
  14068. }
  14069. else
  14070. {
  14071. return false;
  14072. }
  14073. }
  14074. return true;
  14075. }
  14076. END_JUCE_NAMESPACE
  14077. /*** End of inlined file: juce_ThreadPool.cpp ***/
  14078. /*** Start of inlined file: juce_TimeSliceThread.cpp ***/
  14079. BEGIN_JUCE_NAMESPACE
  14080. TimeSliceThread::TimeSliceThread (const String& threadName)
  14081. : Thread (threadName),
  14082. index (0),
  14083. clientBeingCalled (0),
  14084. clientsChanged (false)
  14085. {
  14086. }
  14087. TimeSliceThread::~TimeSliceThread()
  14088. {
  14089. stopThread (2000);
  14090. }
  14091. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  14092. {
  14093. const ScopedLock sl (listLock);
  14094. clients.addIfNotAlreadyThere (client);
  14095. clientsChanged = true;
  14096. notify();
  14097. }
  14098. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  14099. {
  14100. const ScopedLock sl1 (listLock);
  14101. clientsChanged = true;
  14102. // if there's a chance we're in the middle of calling this client, we need to
  14103. // also lock the outer lock..
  14104. if (clientBeingCalled == client)
  14105. {
  14106. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  14107. const ScopedLock sl2 (callbackLock);
  14108. const ScopedLock sl3 (listLock);
  14109. clients.removeValue (client);
  14110. }
  14111. else
  14112. {
  14113. clients.removeValue (client);
  14114. }
  14115. }
  14116. int TimeSliceThread::getNumClients() const
  14117. {
  14118. return clients.size();
  14119. }
  14120. TimeSliceClient* TimeSliceThread::getClient (const int i) const
  14121. {
  14122. const ScopedLock sl (listLock);
  14123. return clients [i];
  14124. }
  14125. void TimeSliceThread::run()
  14126. {
  14127. int numCallsSinceBusy = 0;
  14128. while (! threadShouldExit())
  14129. {
  14130. int timeToWait = 500;
  14131. {
  14132. const ScopedLock sl (callbackLock);
  14133. {
  14134. const ScopedLock sl2 (listLock);
  14135. if (clients.size() > 0)
  14136. {
  14137. index = (index + 1) % clients.size();
  14138. clientBeingCalled = clients [index];
  14139. }
  14140. else
  14141. {
  14142. index = 0;
  14143. clientBeingCalled = 0;
  14144. }
  14145. if (clientsChanged)
  14146. {
  14147. clientsChanged = false;
  14148. numCallsSinceBusy = 0;
  14149. }
  14150. }
  14151. if (clientBeingCalled != 0)
  14152. {
  14153. if (clientBeingCalled->useTimeSlice())
  14154. numCallsSinceBusy = 0;
  14155. else
  14156. ++numCallsSinceBusy;
  14157. if (numCallsSinceBusy >= clients.size())
  14158. timeToWait = 500;
  14159. else if (index == 0)
  14160. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  14161. else
  14162. timeToWait = 0;
  14163. }
  14164. }
  14165. if (timeToWait > 0)
  14166. wait (timeToWait);
  14167. }
  14168. }
  14169. END_JUCE_NAMESPACE
  14170. /*** End of inlined file: juce_TimeSliceThread.cpp ***/
  14171. /*** Start of inlined file: juce_DeletedAtShutdown.cpp ***/
  14172. BEGIN_JUCE_NAMESPACE
  14173. DeletedAtShutdown::DeletedAtShutdown()
  14174. {
  14175. const ScopedLock sl (getLock());
  14176. getObjects().add (this);
  14177. }
  14178. DeletedAtShutdown::~DeletedAtShutdown()
  14179. {
  14180. const ScopedLock sl (getLock());
  14181. getObjects().removeValue (this);
  14182. }
  14183. void DeletedAtShutdown::deleteAll()
  14184. {
  14185. // make a local copy of the array, so it can't get into a loop if something
  14186. // creates another DeletedAtShutdown object during its destructor.
  14187. Array <DeletedAtShutdown*> localCopy;
  14188. {
  14189. const ScopedLock sl (getLock());
  14190. localCopy = getObjects();
  14191. }
  14192. for (int i = localCopy.size(); --i >= 0;)
  14193. {
  14194. JUCE_TRY
  14195. {
  14196. DeletedAtShutdown* deletee = localCopy.getUnchecked(i);
  14197. // double-check that it's not already been deleted during another object's destructor.
  14198. {
  14199. const ScopedLock sl (getLock());
  14200. if (! getObjects().contains (deletee))
  14201. deletee = 0;
  14202. }
  14203. delete deletee;
  14204. }
  14205. JUCE_CATCH_EXCEPTION
  14206. }
  14207. // if no objects got re-created during shutdown, this should have been emptied by their
  14208. // destructors
  14209. jassert (getObjects().size() == 0);
  14210. getObjects().clear(); // just to make sure the array doesn't have any memory still allocated
  14211. }
  14212. CriticalSection& DeletedAtShutdown::getLock()
  14213. {
  14214. static CriticalSection lock;
  14215. return lock;
  14216. }
  14217. Array <DeletedAtShutdown*>& DeletedAtShutdown::getObjects()
  14218. {
  14219. static Array <DeletedAtShutdown*> objects;
  14220. return objects;
  14221. }
  14222. END_JUCE_NAMESPACE
  14223. /*** End of inlined file: juce_DeletedAtShutdown.cpp ***/
  14224. /*** Start of inlined file: juce_UnitTest.cpp ***/
  14225. BEGIN_JUCE_NAMESPACE
  14226. UnitTest::UnitTest (const String& name_)
  14227. : name (name_), runner (0)
  14228. {
  14229. getAllTests().add (this);
  14230. }
  14231. UnitTest::~UnitTest()
  14232. {
  14233. getAllTests().removeValue (this);
  14234. }
  14235. Array<UnitTest*>& UnitTest::getAllTests()
  14236. {
  14237. static Array<UnitTest*> tests;
  14238. return tests;
  14239. }
  14240. void UnitTest::initialise() {}
  14241. void UnitTest::shutdown() {}
  14242. void UnitTest::performTest (UnitTestRunner* const runner_)
  14243. {
  14244. jassert (runner_ != 0);
  14245. runner = runner_;
  14246. initialise();
  14247. runTest();
  14248. shutdown();
  14249. }
  14250. void UnitTest::logMessage (const String& message)
  14251. {
  14252. runner->logMessage (message);
  14253. }
  14254. void UnitTest::beginTest (const String& testName)
  14255. {
  14256. runner->beginNewTest (this, testName);
  14257. }
  14258. void UnitTest::expect (const bool result, const String& failureMessage)
  14259. {
  14260. if (result)
  14261. runner->addPass();
  14262. else
  14263. runner->addFail (failureMessage);
  14264. }
  14265. UnitTestRunner::UnitTestRunner()
  14266. : currentTest (0), assertOnFailure (false)
  14267. {
  14268. }
  14269. UnitTestRunner::~UnitTestRunner()
  14270. {
  14271. }
  14272. int UnitTestRunner::getNumResults() const throw()
  14273. {
  14274. return results.size();
  14275. }
  14276. const UnitTestRunner::TestResult* UnitTestRunner::getResult (int index) const throw()
  14277. {
  14278. return results [index];
  14279. }
  14280. void UnitTestRunner::resultsUpdated()
  14281. {
  14282. }
  14283. void UnitTestRunner::runTests (const Array<UnitTest*>& tests, const bool assertOnFailure_)
  14284. {
  14285. results.clear();
  14286. assertOnFailure = assertOnFailure_;
  14287. resultsUpdated();
  14288. for (int i = 0; i < tests.size(); ++i)
  14289. {
  14290. try
  14291. {
  14292. tests.getUnchecked(i)->performTest (this);
  14293. }
  14294. catch (...)
  14295. {
  14296. addFail ("An unhandled exception was thrown!");
  14297. }
  14298. }
  14299. endTest();
  14300. }
  14301. void UnitTestRunner::runAllTests (const bool assertOnFailure_)
  14302. {
  14303. runTests (UnitTest::getAllTests(), assertOnFailure_);
  14304. }
  14305. void UnitTestRunner::logMessage (const String& message)
  14306. {
  14307. Logger::writeToLog (message);
  14308. }
  14309. void UnitTestRunner::beginNewTest (UnitTest* const test, const String& subCategory)
  14310. {
  14311. endTest();
  14312. currentTest = test;
  14313. TestResult* const r = new TestResult();
  14314. r->unitTestName = test->getName();
  14315. r->subcategoryName = subCategory;
  14316. r->passes = 0;
  14317. r->failures = 0;
  14318. results.add (r);
  14319. logMessage ("-----------------------------------------------------------------");
  14320. logMessage ("Starting test: " + r->unitTestName + " / " + subCategory + "...");
  14321. resultsUpdated();
  14322. }
  14323. void UnitTestRunner::endTest()
  14324. {
  14325. if (results.size() > 0)
  14326. {
  14327. TestResult* const r = results.getLast();
  14328. if (r->failures > 0)
  14329. {
  14330. String m ("FAILED!!");
  14331. m << r->failures << (r->failures == 1 ? "test" : "tests")
  14332. << " failed, out of a total of " << (r->passes + r->failures);
  14333. logMessage (String::empty);
  14334. logMessage (m);
  14335. logMessage (String::empty);
  14336. }
  14337. else
  14338. {
  14339. logMessage ("All tests completed successfully");
  14340. }
  14341. }
  14342. }
  14343. void UnitTestRunner::addPass()
  14344. {
  14345. {
  14346. const ScopedLock sl (results.getLock());
  14347. TestResult* const r = results.getLast();
  14348. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14349. r->passes++;
  14350. String message ("Test ");
  14351. message << (r->failures + r->passes) << " passed";
  14352. logMessage (message);
  14353. }
  14354. resultsUpdated();
  14355. }
  14356. void UnitTestRunner::addFail (const String& failureMessage)
  14357. {
  14358. {
  14359. const ScopedLock sl (results.getLock());
  14360. TestResult* const r = results.getLast();
  14361. jassert (r != 0); // You need to call UnitTest::beginTest() before performing any tests!
  14362. r->failures++;
  14363. String message ("!!! Test ");
  14364. message << (r->failures + r->passes) << " failed";
  14365. if (failureMessage.isNotEmpty())
  14366. message << ": " << failureMessage;
  14367. r->messages.add (message);
  14368. logMessage (message);
  14369. }
  14370. resultsUpdated();
  14371. if (assertOnFailure) { jassertfalse }
  14372. }
  14373. END_JUCE_NAMESPACE
  14374. /*** End of inlined file: juce_UnitTest.cpp ***/
  14375. #endif
  14376. #if JUCE_BUILD_MISC
  14377. /*** Start of inlined file: juce_ValueTree.cpp ***/
  14378. BEGIN_JUCE_NAMESPACE
  14379. class ValueTree::SetPropertyAction : public UndoableAction
  14380. {
  14381. public:
  14382. SetPropertyAction (const SharedObjectPtr& target_, const Identifier& name_,
  14383. const var& newValue_, const var& oldValue_,
  14384. const bool isAddingNewProperty_, const bool isDeletingProperty_)
  14385. : target (target_), name (name_), newValue (newValue_), oldValue (oldValue_),
  14386. isAddingNewProperty (isAddingNewProperty_), isDeletingProperty (isDeletingProperty_)
  14387. {
  14388. }
  14389. ~SetPropertyAction() {}
  14390. bool perform()
  14391. {
  14392. jassert (! (isAddingNewProperty && target->hasProperty (name)));
  14393. if (isDeletingProperty)
  14394. target->removeProperty (name, 0);
  14395. else
  14396. target->setProperty (name, newValue, 0);
  14397. return true;
  14398. }
  14399. bool undo()
  14400. {
  14401. if (isAddingNewProperty)
  14402. target->removeProperty (name, 0);
  14403. else
  14404. target->setProperty (name, oldValue, 0);
  14405. return true;
  14406. }
  14407. int getSizeInUnits()
  14408. {
  14409. return (int) sizeof (*this); //xxx should be more accurate
  14410. }
  14411. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14412. {
  14413. if (! (isAddingNewProperty || isDeletingProperty))
  14414. {
  14415. SetPropertyAction* next = dynamic_cast <SetPropertyAction*> (nextAction);
  14416. if (next != 0 && next->target == target && next->name == name
  14417. && ! (next->isAddingNewProperty || next->isDeletingProperty))
  14418. {
  14419. return new SetPropertyAction (target, name, next->newValue, oldValue, false, false);
  14420. }
  14421. }
  14422. return 0;
  14423. }
  14424. private:
  14425. const SharedObjectPtr target;
  14426. const Identifier name;
  14427. const var newValue;
  14428. var oldValue;
  14429. const bool isAddingNewProperty : 1, isDeletingProperty : 1;
  14430. SetPropertyAction (const SetPropertyAction&);
  14431. SetPropertyAction& operator= (const SetPropertyAction&);
  14432. };
  14433. class ValueTree::AddOrRemoveChildAction : public UndoableAction
  14434. {
  14435. public:
  14436. AddOrRemoveChildAction (const SharedObjectPtr& target_, const int childIndex_,
  14437. const SharedObjectPtr& newChild_)
  14438. : target (target_),
  14439. child (newChild_ != 0 ? newChild_ : target_->children [childIndex_]),
  14440. childIndex (childIndex_),
  14441. isDeleting (newChild_ == 0)
  14442. {
  14443. jassert (child != 0);
  14444. }
  14445. ~AddOrRemoveChildAction() {}
  14446. bool perform()
  14447. {
  14448. if (isDeleting)
  14449. target->removeChild (childIndex, 0);
  14450. else
  14451. target->addChild (child, childIndex, 0);
  14452. return true;
  14453. }
  14454. bool undo()
  14455. {
  14456. if (isDeleting)
  14457. {
  14458. target->addChild (child, childIndex, 0);
  14459. }
  14460. else
  14461. {
  14462. // If you hit this, it seems that your object's state is getting confused - probably
  14463. // because you've interleaved some undoable and non-undoable operations?
  14464. jassert (childIndex < target->children.size());
  14465. target->removeChild (childIndex, 0);
  14466. }
  14467. return true;
  14468. }
  14469. int getSizeInUnits()
  14470. {
  14471. return (int) sizeof (*this); //xxx should be more accurate
  14472. }
  14473. private:
  14474. const SharedObjectPtr target, child;
  14475. const int childIndex;
  14476. const bool isDeleting;
  14477. AddOrRemoveChildAction (const AddOrRemoveChildAction&);
  14478. AddOrRemoveChildAction& operator= (const AddOrRemoveChildAction&);
  14479. };
  14480. class ValueTree::MoveChildAction : public UndoableAction
  14481. {
  14482. public:
  14483. MoveChildAction (const SharedObjectPtr& parent_,
  14484. const int startIndex_, const int endIndex_)
  14485. : parent (parent_),
  14486. startIndex (startIndex_),
  14487. endIndex (endIndex_)
  14488. {
  14489. }
  14490. ~MoveChildAction() {}
  14491. bool perform()
  14492. {
  14493. parent->moveChild (startIndex, endIndex, 0);
  14494. return true;
  14495. }
  14496. bool undo()
  14497. {
  14498. parent->moveChild (endIndex, startIndex, 0);
  14499. return true;
  14500. }
  14501. int getSizeInUnits()
  14502. {
  14503. return (int) sizeof (*this); //xxx should be more accurate
  14504. }
  14505. UndoableAction* createCoalescedAction (UndoableAction* nextAction)
  14506. {
  14507. MoveChildAction* next = dynamic_cast <MoveChildAction*> (nextAction);
  14508. if (next != 0 && next->parent == parent && next->startIndex == endIndex)
  14509. return new MoveChildAction (parent, startIndex, next->endIndex);
  14510. return 0;
  14511. }
  14512. private:
  14513. const SharedObjectPtr parent;
  14514. const int startIndex, endIndex;
  14515. MoveChildAction (const MoveChildAction&);
  14516. MoveChildAction& operator= (const MoveChildAction&);
  14517. };
  14518. ValueTree::SharedObject::SharedObject (const Identifier& type_)
  14519. : type (type_), parent (0)
  14520. {
  14521. }
  14522. ValueTree::SharedObject::SharedObject (const SharedObject& other)
  14523. : type (other.type), properties (other.properties), parent (0)
  14524. {
  14525. for (int i = 0; i < other.children.size(); ++i)
  14526. {
  14527. SharedObject* const child = new SharedObject (*other.children.getUnchecked(i));
  14528. child->parent = this;
  14529. children.add (child);
  14530. }
  14531. }
  14532. ValueTree::SharedObject::~SharedObject()
  14533. {
  14534. jassert (parent == 0); // this should never happen unless something isn't obeying the ref-counting!
  14535. for (int i = children.size(); --i >= 0;)
  14536. {
  14537. const SharedObjectPtr c (children.getUnchecked(i));
  14538. c->parent = 0;
  14539. children.remove (i);
  14540. c->sendParentChangeMessage();
  14541. }
  14542. }
  14543. void ValueTree::SharedObject::sendPropertyChangeMessage (ValueTree& tree, const Identifier& property)
  14544. {
  14545. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14546. {
  14547. ValueTree* const v = valueTreesWithListeners[i];
  14548. if (v != 0)
  14549. v->listeners.call (&ValueTree::Listener::valueTreePropertyChanged, tree, property);
  14550. }
  14551. }
  14552. void ValueTree::SharedObject::sendPropertyChangeMessage (const Identifier& property)
  14553. {
  14554. ValueTree tree (this);
  14555. ValueTree::SharedObject* t = this;
  14556. while (t != 0)
  14557. {
  14558. t->sendPropertyChangeMessage (tree, property);
  14559. t = t->parent;
  14560. }
  14561. }
  14562. void ValueTree::SharedObject::sendChildChangeMessage (ValueTree& tree)
  14563. {
  14564. for (int i = valueTreesWithListeners.size(); --i >= 0;)
  14565. {
  14566. ValueTree* const v = valueTreesWithListeners[i];
  14567. if (v != 0)
  14568. v->listeners.call (&ValueTree::Listener::valueTreeChildrenChanged, tree);
  14569. }
  14570. }
  14571. void ValueTree::SharedObject::sendChildChangeMessage()
  14572. {
  14573. ValueTree tree (this);
  14574. ValueTree::SharedObject* t = this;
  14575. while (t != 0)
  14576. {
  14577. t->sendChildChangeMessage (tree);
  14578. t = t->parent;
  14579. }
  14580. }
  14581. void ValueTree::SharedObject::sendParentChangeMessage()
  14582. {
  14583. ValueTree tree (this);
  14584. int i;
  14585. for (i = children.size(); --i >= 0;)
  14586. {
  14587. SharedObject* const t = children[i];
  14588. if (t != 0)
  14589. t->sendParentChangeMessage();
  14590. }
  14591. for (i = valueTreesWithListeners.size(); --i >= 0;)
  14592. {
  14593. ValueTree* const v = valueTreesWithListeners[i];
  14594. if (v != 0)
  14595. v->listeners.call (&ValueTree::Listener::valueTreeParentChanged, tree);
  14596. }
  14597. }
  14598. const var& ValueTree::SharedObject::getProperty (const Identifier& name) const
  14599. {
  14600. return properties [name];
  14601. }
  14602. const var ValueTree::SharedObject::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14603. {
  14604. return properties.getWithDefault (name, defaultReturnValue);
  14605. }
  14606. void ValueTree::SharedObject::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14607. {
  14608. if (undoManager == 0)
  14609. {
  14610. if (properties.set (name, newValue))
  14611. sendPropertyChangeMessage (name);
  14612. }
  14613. else
  14614. {
  14615. var* const existingValue = properties.getVarPointer (name);
  14616. if (existingValue != 0)
  14617. {
  14618. if (*existingValue != newValue)
  14619. undoManager->perform (new SetPropertyAction (this, name, newValue, properties [name], false, false));
  14620. }
  14621. else
  14622. {
  14623. undoManager->perform (new SetPropertyAction (this, name, newValue, var::null, true, false));
  14624. }
  14625. }
  14626. }
  14627. bool ValueTree::SharedObject::hasProperty (const Identifier& name) const
  14628. {
  14629. return properties.contains (name);
  14630. }
  14631. void ValueTree::SharedObject::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14632. {
  14633. if (undoManager == 0)
  14634. {
  14635. if (properties.remove (name))
  14636. sendPropertyChangeMessage (name);
  14637. }
  14638. else
  14639. {
  14640. if (properties.contains (name))
  14641. undoManager->perform (new SetPropertyAction (this, name, var::null, properties [name], false, true));
  14642. }
  14643. }
  14644. void ValueTree::SharedObject::removeAllProperties (UndoManager* const undoManager)
  14645. {
  14646. if (undoManager == 0)
  14647. {
  14648. while (properties.size() > 0)
  14649. {
  14650. const Identifier name (properties.getName (properties.size() - 1));
  14651. properties.remove (name);
  14652. sendPropertyChangeMessage (name);
  14653. }
  14654. }
  14655. else
  14656. {
  14657. for (int i = properties.size(); --i >= 0;)
  14658. undoManager->perform (new SetPropertyAction (this, properties.getName(i), var::null, properties.getValueAt(i), false, true));
  14659. }
  14660. }
  14661. ValueTree ValueTree::SharedObject::getChildWithName (const Identifier& typeToMatch) const
  14662. {
  14663. for (int i = 0; i < children.size(); ++i)
  14664. if (children.getUnchecked(i)->type == typeToMatch)
  14665. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14666. return ValueTree::invalid;
  14667. }
  14668. ValueTree ValueTree::SharedObject::getOrCreateChildWithName (const Identifier& typeToMatch, UndoManager* undoManager)
  14669. {
  14670. for (int i = 0; i < children.size(); ++i)
  14671. if (children.getUnchecked(i)->type == typeToMatch)
  14672. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14673. SharedObject* const newObject = new SharedObject (typeToMatch);
  14674. addChild (newObject, -1, undoManager);
  14675. return ValueTree (newObject);
  14676. }
  14677. ValueTree ValueTree::SharedObject::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14678. {
  14679. for (int i = 0; i < children.size(); ++i)
  14680. if (children.getUnchecked(i)->getProperty (propertyName) == propertyValue)
  14681. return ValueTree (static_cast <SharedObject*> (children.getUnchecked(i)));
  14682. return ValueTree::invalid;
  14683. }
  14684. bool ValueTree::SharedObject::isAChildOf (const SharedObject* const possibleParent) const
  14685. {
  14686. const SharedObject* p = parent;
  14687. while (p != 0)
  14688. {
  14689. if (p == possibleParent)
  14690. return true;
  14691. p = p->parent;
  14692. }
  14693. return false;
  14694. }
  14695. int ValueTree::SharedObject::indexOf (const ValueTree& child) const
  14696. {
  14697. return children.indexOf (child.object);
  14698. }
  14699. void ValueTree::SharedObject::addChild (SharedObject* child, int index, UndoManager* const undoManager)
  14700. {
  14701. if (child != 0 && child->parent != this)
  14702. {
  14703. if (child != this && ! isAChildOf (child))
  14704. {
  14705. // You should always make sure that a child is removed from its previous parent before
  14706. // adding it somewhere else - otherwise, it's ambiguous as to whether a different
  14707. // undomanager should be used when removing it from its current parent..
  14708. jassert (child->parent == 0);
  14709. if (child->parent != 0)
  14710. {
  14711. jassert (child->parent->children.indexOf (child) >= 0);
  14712. child->parent->removeChild (child->parent->children.indexOf (child), undoManager);
  14713. }
  14714. if (undoManager == 0)
  14715. {
  14716. children.insert (index, child);
  14717. child->parent = this;
  14718. sendChildChangeMessage();
  14719. child->sendParentChangeMessage();
  14720. }
  14721. else
  14722. {
  14723. if (index < 0)
  14724. index = children.size();
  14725. undoManager->perform (new AddOrRemoveChildAction (this, index, child));
  14726. }
  14727. }
  14728. else
  14729. {
  14730. // You're attempting to create a recursive loop! A node
  14731. // can't be a child of one of its own children!
  14732. jassertfalse;
  14733. }
  14734. }
  14735. }
  14736. void ValueTree::SharedObject::removeChild (const int childIndex, UndoManager* const undoManager)
  14737. {
  14738. const SharedObjectPtr child (children [childIndex]);
  14739. if (child != 0)
  14740. {
  14741. if (undoManager == 0)
  14742. {
  14743. children.remove (childIndex);
  14744. child->parent = 0;
  14745. sendChildChangeMessage();
  14746. child->sendParentChangeMessage();
  14747. }
  14748. else
  14749. {
  14750. undoManager->perform (new AddOrRemoveChildAction (this, childIndex, 0));
  14751. }
  14752. }
  14753. }
  14754. void ValueTree::SharedObject::removeAllChildren (UndoManager* const undoManager)
  14755. {
  14756. while (children.size() > 0)
  14757. removeChild (children.size() - 1, undoManager);
  14758. }
  14759. void ValueTree::SharedObject::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  14760. {
  14761. // The source index must be a valid index!
  14762. jassert (((unsigned int) currentIndex) < (unsigned int) children.size());
  14763. if (currentIndex != newIndex
  14764. && ((unsigned int) currentIndex) < (unsigned int) children.size())
  14765. {
  14766. if (undoManager == 0)
  14767. {
  14768. children.move (currentIndex, newIndex);
  14769. sendChildChangeMessage();
  14770. }
  14771. else
  14772. {
  14773. if (((unsigned int) newIndex) >= (unsigned int) children.size())
  14774. newIndex = children.size() - 1;
  14775. undoManager->perform (new MoveChildAction (this, currentIndex, newIndex));
  14776. }
  14777. }
  14778. }
  14779. void ValueTree::SharedObject::reorderChildren (const ReferenceCountedArray <SharedObject>& newOrder, UndoManager* undoManager)
  14780. {
  14781. jassert (newOrder.size() == children.size());
  14782. if (undoManager == 0)
  14783. {
  14784. children = newOrder;
  14785. sendChildChangeMessage();
  14786. }
  14787. else
  14788. {
  14789. for (int i = 0; i < children.size(); ++i)
  14790. {
  14791. if (children.getUnchecked(i) != newOrder.getUnchecked(i))
  14792. {
  14793. jassert (children.contains (newOrder.getUnchecked(i)));
  14794. moveChild (children.indexOf (newOrder.getUnchecked(i)), i, undoManager);
  14795. }
  14796. }
  14797. }
  14798. }
  14799. bool ValueTree::SharedObject::isEquivalentTo (const SharedObject& other) const
  14800. {
  14801. if (type != other.type
  14802. || properties.size() != other.properties.size()
  14803. || children.size() != other.children.size()
  14804. || properties != other.properties)
  14805. return false;
  14806. for (int i = 0; i < children.size(); ++i)
  14807. if (! children.getUnchecked(i)->isEquivalentTo (*other.children.getUnchecked(i)))
  14808. return false;
  14809. return true;
  14810. }
  14811. ValueTree::ValueTree() throw()
  14812. : object (0)
  14813. {
  14814. }
  14815. const ValueTree ValueTree::invalid;
  14816. ValueTree::ValueTree (const Identifier& type_)
  14817. : object (new ValueTree::SharedObject (type_))
  14818. {
  14819. jassert (type_.toString().isNotEmpty()); // All objects should be given a sensible type name!
  14820. }
  14821. ValueTree::ValueTree (SharedObject* const object_)
  14822. : object (object_)
  14823. {
  14824. }
  14825. ValueTree::ValueTree (const ValueTree& other)
  14826. : object (other.object)
  14827. {
  14828. }
  14829. ValueTree& ValueTree::operator= (const ValueTree& other)
  14830. {
  14831. if (listeners.size() > 0)
  14832. {
  14833. if (object != 0)
  14834. object->valueTreesWithListeners.removeValue (this);
  14835. if (other.object != 0)
  14836. other.object->valueTreesWithListeners.add (this);
  14837. }
  14838. object = other.object;
  14839. return *this;
  14840. }
  14841. ValueTree::~ValueTree()
  14842. {
  14843. if (listeners.size() > 0 && object != 0)
  14844. object->valueTreesWithListeners.removeValue (this);
  14845. }
  14846. bool ValueTree::operator== (const ValueTree& other) const throw()
  14847. {
  14848. return object == other.object;
  14849. }
  14850. bool ValueTree::operator!= (const ValueTree& other) const throw()
  14851. {
  14852. return object != other.object;
  14853. }
  14854. bool ValueTree::isEquivalentTo (const ValueTree& other) const
  14855. {
  14856. return object == other.object
  14857. || (object != 0 && other.object != 0 && object->isEquivalentTo (*other.object));
  14858. }
  14859. ValueTree ValueTree::createCopy() const
  14860. {
  14861. return ValueTree (object != 0 ? new SharedObject (*object) : 0);
  14862. }
  14863. bool ValueTree::hasType (const Identifier& typeName) const
  14864. {
  14865. return object != 0 && object->type == typeName;
  14866. }
  14867. const Identifier ValueTree::getType() const
  14868. {
  14869. return object != 0 ? object->type : Identifier();
  14870. }
  14871. ValueTree ValueTree::getParent() const
  14872. {
  14873. return ValueTree (object != 0 ? object->parent : (SharedObject*) 0);
  14874. }
  14875. ValueTree ValueTree::getSibling (const int delta) const
  14876. {
  14877. if (object == 0 || object->parent == 0)
  14878. return invalid;
  14879. const int index = object->parent->indexOf (*this) + delta;
  14880. return ValueTree (static_cast <SharedObject*> (object->parent->children [index]));
  14881. }
  14882. const var& ValueTree::operator[] (const Identifier& name) const
  14883. {
  14884. return object == 0 ? var::null : object->getProperty (name);
  14885. }
  14886. const var& ValueTree::getProperty (const Identifier& name) const
  14887. {
  14888. return object == 0 ? var::null : object->getProperty (name);
  14889. }
  14890. const var ValueTree::getProperty (const Identifier& name, const var& defaultReturnValue) const
  14891. {
  14892. return object == 0 ? defaultReturnValue : object->getProperty (name, defaultReturnValue);
  14893. }
  14894. void ValueTree::setProperty (const Identifier& name, const var& newValue, UndoManager* const undoManager)
  14895. {
  14896. jassert (name.toString().isNotEmpty());
  14897. if (object != 0 && name.toString().isNotEmpty())
  14898. object->setProperty (name, newValue, undoManager);
  14899. }
  14900. bool ValueTree::hasProperty (const Identifier& name) const
  14901. {
  14902. return object != 0 && object->hasProperty (name);
  14903. }
  14904. void ValueTree::removeProperty (const Identifier& name, UndoManager* const undoManager)
  14905. {
  14906. if (object != 0)
  14907. object->removeProperty (name, undoManager);
  14908. }
  14909. void ValueTree::removeAllProperties (UndoManager* const undoManager)
  14910. {
  14911. if (object != 0)
  14912. object->removeAllProperties (undoManager);
  14913. }
  14914. int ValueTree::getNumProperties() const
  14915. {
  14916. return object == 0 ? 0 : object->properties.size();
  14917. }
  14918. const Identifier ValueTree::getPropertyName (const int index) const
  14919. {
  14920. return object == 0 ? Identifier()
  14921. : object->properties.getName (index);
  14922. }
  14923. class ValueTreePropertyValueSource : public Value::ValueSource,
  14924. public ValueTree::Listener
  14925. {
  14926. public:
  14927. ValueTreePropertyValueSource (const ValueTree& tree_,
  14928. const Identifier& property_,
  14929. UndoManager* const undoManager_)
  14930. : tree (tree_),
  14931. property (property_),
  14932. undoManager (undoManager_)
  14933. {
  14934. tree.addListener (this);
  14935. }
  14936. ~ValueTreePropertyValueSource()
  14937. {
  14938. tree.removeListener (this);
  14939. }
  14940. const var getValue() const
  14941. {
  14942. return tree [property];
  14943. }
  14944. void setValue (const var& newValue)
  14945. {
  14946. tree.setProperty (property, newValue, undoManager);
  14947. }
  14948. void valueTreePropertyChanged (ValueTree& treeWhosePropertyHasChanged, const Identifier& changedProperty)
  14949. {
  14950. if (tree == treeWhosePropertyHasChanged && property == changedProperty)
  14951. sendChangeMessage (false);
  14952. }
  14953. void valueTreeChildrenChanged (ValueTree&) {}
  14954. void valueTreeParentChanged (ValueTree&) {}
  14955. private:
  14956. ValueTree tree;
  14957. const Identifier property;
  14958. UndoManager* const undoManager;
  14959. ValueTreePropertyValueSource& operator= (const ValueTreePropertyValueSource&);
  14960. };
  14961. Value ValueTree::getPropertyAsValue (const Identifier& name, UndoManager* const undoManager) const
  14962. {
  14963. return Value (new ValueTreePropertyValueSource (*this, name, undoManager));
  14964. }
  14965. int ValueTree::getNumChildren() const
  14966. {
  14967. return object == 0 ? 0 : object->children.size();
  14968. }
  14969. ValueTree ValueTree::getChild (int index) const
  14970. {
  14971. return ValueTree (object != 0 ? (SharedObject*) object->children [index] : (SharedObject*) 0);
  14972. }
  14973. ValueTree ValueTree::getChildWithName (const Identifier& type) const
  14974. {
  14975. return object != 0 ? object->getChildWithName (type) : ValueTree::invalid;
  14976. }
  14977. ValueTree ValueTree::getOrCreateChildWithName (const Identifier& type, UndoManager* undoManager)
  14978. {
  14979. return object != 0 ? object->getOrCreateChildWithName (type, undoManager) : ValueTree::invalid;
  14980. }
  14981. ValueTree ValueTree::getChildWithProperty (const Identifier& propertyName, const var& propertyValue) const
  14982. {
  14983. return object != 0 ? object->getChildWithProperty (propertyName, propertyValue) : ValueTree::invalid;
  14984. }
  14985. bool ValueTree::isAChildOf (const ValueTree& possibleParent) const
  14986. {
  14987. return object != 0 && object->isAChildOf (possibleParent.object);
  14988. }
  14989. int ValueTree::indexOf (const ValueTree& child) const
  14990. {
  14991. return object != 0 ? object->indexOf (child) : -1;
  14992. }
  14993. void ValueTree::addChild (const ValueTree& child, int index, UndoManager* const undoManager)
  14994. {
  14995. if (object != 0)
  14996. object->addChild (child.object, index, undoManager);
  14997. }
  14998. void ValueTree::removeChild (const int childIndex, UndoManager* const undoManager)
  14999. {
  15000. if (object != 0)
  15001. object->removeChild (childIndex, undoManager);
  15002. }
  15003. void ValueTree::removeChild (const ValueTree& child, UndoManager* const undoManager)
  15004. {
  15005. if (object != 0)
  15006. object->removeChild (object->children.indexOf (child.object), undoManager);
  15007. }
  15008. void ValueTree::removeAllChildren (UndoManager* const undoManager)
  15009. {
  15010. if (object != 0)
  15011. object->removeAllChildren (undoManager);
  15012. }
  15013. void ValueTree::moveChild (int currentIndex, int newIndex, UndoManager* undoManager)
  15014. {
  15015. if (object != 0)
  15016. object->moveChild (currentIndex, newIndex, undoManager);
  15017. }
  15018. void ValueTree::addListener (Listener* listener)
  15019. {
  15020. if (listener != 0)
  15021. {
  15022. if (listeners.size() == 0 && object != 0)
  15023. object->valueTreesWithListeners.add (this);
  15024. listeners.add (listener);
  15025. }
  15026. }
  15027. void ValueTree::removeListener (Listener* listener)
  15028. {
  15029. listeners.remove (listener);
  15030. if (listeners.size() == 0 && object != 0)
  15031. object->valueTreesWithListeners.removeValue (this);
  15032. }
  15033. XmlElement* ValueTree::SharedObject::createXml() const
  15034. {
  15035. XmlElement* xml = new XmlElement (type.toString());
  15036. int i;
  15037. for (i = 0; i < properties.size(); ++i)
  15038. {
  15039. Identifier name (properties.getName(i));
  15040. const var& v = properties [name];
  15041. jassert (! v.isObject()); // DynamicObjects can't be stored as XML!
  15042. xml->setAttribute (name.toString(), v.toString());
  15043. }
  15044. for (i = 0; i < children.size(); ++i)
  15045. xml->addChildElement (children.getUnchecked(i)->createXml());
  15046. return xml;
  15047. }
  15048. XmlElement* ValueTree::createXml() const
  15049. {
  15050. return object != 0 ? object->createXml() : 0;
  15051. }
  15052. ValueTree ValueTree::fromXml (const XmlElement& xml)
  15053. {
  15054. ValueTree v (xml.getTagName());
  15055. const int numAtts = xml.getNumAttributes(); // xxx inefficient - should write an att iterator..
  15056. for (int i = 0; i < numAtts; ++i)
  15057. v.setProperty (xml.getAttributeName (i), var (xml.getAttributeValue (i)), 0);
  15058. forEachXmlChildElement (xml, e)
  15059. {
  15060. v.addChild (fromXml (*e), -1, 0);
  15061. }
  15062. return v;
  15063. }
  15064. void ValueTree::writeToStream (OutputStream& output)
  15065. {
  15066. output.writeString (getType().toString());
  15067. const int numProps = getNumProperties();
  15068. output.writeCompressedInt (numProps);
  15069. int i;
  15070. for (i = 0; i < numProps; ++i)
  15071. {
  15072. const Identifier name (getPropertyName(i));
  15073. output.writeString (name.toString());
  15074. getProperty(name).writeToStream (output);
  15075. }
  15076. const int numChildren = getNumChildren();
  15077. output.writeCompressedInt (numChildren);
  15078. for (i = 0; i < numChildren; ++i)
  15079. getChild (i).writeToStream (output);
  15080. }
  15081. ValueTree ValueTree::readFromStream (InputStream& input)
  15082. {
  15083. const String type (input.readString());
  15084. if (type.isEmpty())
  15085. return ValueTree::invalid;
  15086. ValueTree v (type);
  15087. const int numProps = input.readCompressedInt();
  15088. if (numProps < 0)
  15089. {
  15090. jassertfalse; // trying to read corrupted data!
  15091. return v;
  15092. }
  15093. int i;
  15094. for (i = 0; i < numProps; ++i)
  15095. {
  15096. const String name (input.readString());
  15097. jassert (name.isNotEmpty());
  15098. const var value (var::readFromStream (input));
  15099. v.setProperty (name, value, 0);
  15100. }
  15101. const int numChildren = input.readCompressedInt();
  15102. for (i = 0; i < numChildren; ++i)
  15103. v.addChild (readFromStream (input), -1, 0);
  15104. return v;
  15105. }
  15106. ValueTree ValueTree::readFromData (const void* const data, const size_t numBytes)
  15107. {
  15108. MemoryInputStream in (data, numBytes, false);
  15109. return readFromStream (in);
  15110. }
  15111. END_JUCE_NAMESPACE
  15112. /*** End of inlined file: juce_ValueTree.cpp ***/
  15113. /*** Start of inlined file: juce_Value.cpp ***/
  15114. BEGIN_JUCE_NAMESPACE
  15115. Value::ValueSource::ValueSource()
  15116. {
  15117. }
  15118. Value::ValueSource::~ValueSource()
  15119. {
  15120. }
  15121. void Value::ValueSource::sendChangeMessage (const bool synchronous)
  15122. {
  15123. if (synchronous)
  15124. {
  15125. for (int i = valuesWithListeners.size(); --i >= 0;)
  15126. {
  15127. Value* const v = valuesWithListeners[i];
  15128. if (v != 0)
  15129. v->callListeners();
  15130. }
  15131. }
  15132. else
  15133. {
  15134. triggerAsyncUpdate();
  15135. }
  15136. }
  15137. void Value::ValueSource::handleAsyncUpdate()
  15138. {
  15139. sendChangeMessage (true);
  15140. }
  15141. class SimpleValueSource : public Value::ValueSource
  15142. {
  15143. public:
  15144. SimpleValueSource()
  15145. {
  15146. }
  15147. SimpleValueSource (const var& initialValue)
  15148. : value (initialValue)
  15149. {
  15150. }
  15151. ~SimpleValueSource()
  15152. {
  15153. }
  15154. const var getValue() const
  15155. {
  15156. return value;
  15157. }
  15158. void setValue (const var& newValue)
  15159. {
  15160. if (newValue != value)
  15161. {
  15162. value = newValue;
  15163. sendChangeMessage (false);
  15164. }
  15165. }
  15166. private:
  15167. var value;
  15168. SimpleValueSource (const SimpleValueSource&);
  15169. SimpleValueSource& operator= (const SimpleValueSource&);
  15170. };
  15171. Value::Value()
  15172. : value (new SimpleValueSource())
  15173. {
  15174. }
  15175. Value::Value (ValueSource* const value_)
  15176. : value (value_)
  15177. {
  15178. jassert (value_ != 0);
  15179. }
  15180. Value::Value (const var& initialValue)
  15181. : value (new SimpleValueSource (initialValue))
  15182. {
  15183. }
  15184. Value::Value (const Value& other)
  15185. : value (other.value)
  15186. {
  15187. }
  15188. Value& Value::operator= (const Value& other)
  15189. {
  15190. value = other.value;
  15191. return *this;
  15192. }
  15193. Value::~Value()
  15194. {
  15195. if (listeners.size() > 0)
  15196. value->valuesWithListeners.removeValue (this);
  15197. }
  15198. const var Value::getValue() const
  15199. {
  15200. return value->getValue();
  15201. }
  15202. Value::operator const var() const
  15203. {
  15204. return getValue();
  15205. }
  15206. void Value::setValue (const var& newValue)
  15207. {
  15208. value->setValue (newValue);
  15209. }
  15210. const String Value::toString() const
  15211. {
  15212. return value->getValue().toString();
  15213. }
  15214. Value& Value::operator= (const var& newValue)
  15215. {
  15216. value->setValue (newValue);
  15217. return *this;
  15218. }
  15219. void Value::referTo (const Value& valueToReferTo)
  15220. {
  15221. if (valueToReferTo.value != value)
  15222. {
  15223. if (listeners.size() > 0)
  15224. {
  15225. value->valuesWithListeners.removeValue (this);
  15226. valueToReferTo.value->valuesWithListeners.add (this);
  15227. }
  15228. value = valueToReferTo.value;
  15229. callListeners();
  15230. }
  15231. }
  15232. bool Value::refersToSameSourceAs (const Value& other) const
  15233. {
  15234. return value == other.value;
  15235. }
  15236. bool Value::operator== (const Value& other) const
  15237. {
  15238. return value == other.value || value->getValue() == other.getValue();
  15239. }
  15240. bool Value::operator!= (const Value& other) const
  15241. {
  15242. return value != other.value && value->getValue() != other.getValue();
  15243. }
  15244. void Value::addListener (Listener* const listener)
  15245. {
  15246. if (listener != 0)
  15247. {
  15248. if (listeners.size() == 0)
  15249. value->valuesWithListeners.add (this);
  15250. listeners.add (listener);
  15251. }
  15252. }
  15253. void Value::removeListener (Listener* const listener)
  15254. {
  15255. listeners.remove (listener);
  15256. if (listeners.size() == 0)
  15257. value->valuesWithListeners.removeValue (this);
  15258. }
  15259. void Value::callListeners()
  15260. {
  15261. Value v (*this); // (create a copy in case this gets deleted by a callback)
  15262. listeners.call (&Value::Listener::valueChanged, v);
  15263. }
  15264. OutputStream& JUCE_CALLTYPE operator<< (OutputStream& stream, const Value& value)
  15265. {
  15266. return stream << value.toString();
  15267. }
  15268. END_JUCE_NAMESPACE
  15269. /*** End of inlined file: juce_Value.cpp ***/
  15270. /*** Start of inlined file: juce_Application.cpp ***/
  15271. BEGIN_JUCE_NAMESPACE
  15272. #if JUCE_MAC
  15273. extern void juce_initialiseMacMainMenu();
  15274. #endif
  15275. JUCEApplication::JUCEApplication()
  15276. : appReturnValue (0),
  15277. stillInitialising (true)
  15278. {
  15279. jassert (isStandaloneApp() && appInstance == 0);
  15280. appInstance = this;
  15281. }
  15282. JUCEApplication::~JUCEApplication()
  15283. {
  15284. if (appLock != 0)
  15285. {
  15286. appLock->exit();
  15287. appLock = 0;
  15288. }
  15289. jassert (appInstance == this);
  15290. appInstance = 0;
  15291. }
  15292. JUCEApplication::CreateInstanceFunction JUCEApplication::createInstance = 0;
  15293. JUCEApplication* JUCEApplication::appInstance = 0;
  15294. bool JUCEApplication::moreThanOneInstanceAllowed()
  15295. {
  15296. return true;
  15297. }
  15298. void JUCEApplication::anotherInstanceStarted (const String&)
  15299. {
  15300. }
  15301. void JUCEApplication::systemRequestedQuit()
  15302. {
  15303. quit();
  15304. }
  15305. void JUCEApplication::quit()
  15306. {
  15307. MessageManager::getInstance()->stopDispatchLoop();
  15308. }
  15309. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  15310. {
  15311. appReturnValue = newReturnValue;
  15312. }
  15313. void JUCEApplication::actionListenerCallback (const String& message)
  15314. {
  15315. if (message.startsWith (getApplicationName() + "/"))
  15316. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  15317. }
  15318. void JUCEApplication::unhandledException (const std::exception*,
  15319. const String&,
  15320. const int)
  15321. {
  15322. jassertfalse;
  15323. }
  15324. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  15325. const char* const sourceFile,
  15326. const int lineNumber)
  15327. {
  15328. if (appInstance != 0)
  15329. appInstance->unhandledException (e, sourceFile, lineNumber);
  15330. }
  15331. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  15332. {
  15333. return 0;
  15334. }
  15335. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  15336. {
  15337. commands.add (StandardApplicationCommandIDs::quit);
  15338. }
  15339. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  15340. {
  15341. if (commandID == StandardApplicationCommandIDs::quit)
  15342. {
  15343. result.setInfo (TRANS("Quit"),
  15344. TRANS("Quits the application"),
  15345. "Application",
  15346. 0);
  15347. result.defaultKeypresses.add (KeyPress ('q', ModifierKeys::commandModifier, 0));
  15348. }
  15349. }
  15350. bool JUCEApplication::perform (const InvocationInfo& info)
  15351. {
  15352. if (info.commandID == StandardApplicationCommandIDs::quit)
  15353. {
  15354. systemRequestedQuit();
  15355. return true;
  15356. }
  15357. return false;
  15358. }
  15359. bool JUCEApplication::initialiseApp (const String& commandLine)
  15360. {
  15361. commandLineParameters = commandLine.trim();
  15362. #if ! JUCE_IOS
  15363. jassert (appLock == 0); // initialiseApp must only be called once!
  15364. if (! moreThanOneInstanceAllowed())
  15365. {
  15366. appLock = new InterProcessLock ("juceAppLock_" + getApplicationName());
  15367. if (! appLock->enter(0))
  15368. {
  15369. appLock = 0;
  15370. MessageManager::broadcastMessage (getApplicationName() + "/" + commandLineParameters);
  15371. DBG ("Another instance is running - quitting...");
  15372. return false;
  15373. }
  15374. }
  15375. #endif
  15376. // let the app do its setting-up..
  15377. initialise (commandLineParameters);
  15378. #if JUCE_MAC
  15379. juce_initialiseMacMainMenu(); // needs to be called after the app object has created, to get its name
  15380. #endif
  15381. // register for broadcast new app messages
  15382. MessageManager::getInstance()->registerBroadcastListener (this);
  15383. stillInitialising = false;
  15384. return true;
  15385. }
  15386. int JUCEApplication::shutdownApp()
  15387. {
  15388. jassert (appInstance == this);
  15389. MessageManager::getInstance()->deregisterBroadcastListener (this);
  15390. JUCE_TRY
  15391. {
  15392. // give the app a chance to clean up..
  15393. shutdown();
  15394. }
  15395. JUCE_CATCH_EXCEPTION
  15396. return getApplicationReturnValue();
  15397. }
  15398. // This is called on the Mac and iOS where the OS doesn't allow the stack to unwind on shutdown..
  15399. void JUCEApplication::appWillTerminateByForce()
  15400. {
  15401. {
  15402. const ScopedPointer<JUCEApplication> app (JUCEApplication::getInstance());
  15403. if (app != 0)
  15404. app->shutdownApp();
  15405. }
  15406. shutdownJuce_GUI();
  15407. }
  15408. int JUCEApplication::main (const String& commandLine)
  15409. {
  15410. ScopedJuceInitialiser_GUI libraryInitialiser;
  15411. jassert (createInstance != 0);
  15412. int returnCode = 0;
  15413. {
  15414. const ScopedPointer<JUCEApplication> app (createInstance());
  15415. if (! app->initialiseApp (commandLine))
  15416. return 0;
  15417. JUCE_TRY
  15418. {
  15419. // loop until a quit message is received..
  15420. MessageManager::getInstance()->runDispatchLoop();
  15421. }
  15422. JUCE_CATCH_EXCEPTION
  15423. returnCode = app->shutdownApp();
  15424. }
  15425. return returnCode;
  15426. }
  15427. #if JUCE_IOS
  15428. extern int juce_iOSMain (int argc, const char* argv[]);
  15429. #endif
  15430. #if ! JUCE_WINDOWS
  15431. extern const char* juce_Argv0;
  15432. #endif
  15433. int JUCEApplication::main (int argc, const char* argv[])
  15434. {
  15435. JUCE_AUTORELEASEPOOL
  15436. #if ! JUCE_WINDOWS
  15437. jassert (createInstance != 0);
  15438. juce_Argv0 = argv[0];
  15439. #endif
  15440. #if JUCE_IOS
  15441. return juce_iOSMain (argc, argv);
  15442. #else
  15443. String cmd;
  15444. for (int i = 1; i < argc; ++i)
  15445. cmd << argv[i] << ' ';
  15446. return JUCEApplication::main (cmd);
  15447. #endif
  15448. }
  15449. END_JUCE_NAMESPACE
  15450. /*** End of inlined file: juce_Application.cpp ***/
  15451. /*** Start of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15452. BEGIN_JUCE_NAMESPACE
  15453. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  15454. : commandID (commandID_),
  15455. flags (0)
  15456. {
  15457. }
  15458. void ApplicationCommandInfo::setInfo (const String& shortName_,
  15459. const String& description_,
  15460. const String& categoryName_,
  15461. const int flags_) throw()
  15462. {
  15463. shortName = shortName_;
  15464. description = description_;
  15465. categoryName = categoryName_;
  15466. flags = flags_;
  15467. }
  15468. void ApplicationCommandInfo::setActive (const bool b) throw()
  15469. {
  15470. if (b)
  15471. flags &= ~isDisabled;
  15472. else
  15473. flags |= isDisabled;
  15474. }
  15475. void ApplicationCommandInfo::setTicked (const bool b) throw()
  15476. {
  15477. if (b)
  15478. flags |= isTicked;
  15479. else
  15480. flags &= ~isTicked;
  15481. }
  15482. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  15483. {
  15484. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  15485. }
  15486. END_JUCE_NAMESPACE
  15487. /*** End of inlined file: juce_ApplicationCommandInfo.cpp ***/
  15488. /*** Start of inlined file: juce_ApplicationCommandManager.cpp ***/
  15489. BEGIN_JUCE_NAMESPACE
  15490. ApplicationCommandManager::ApplicationCommandManager()
  15491. : firstTarget (0)
  15492. {
  15493. keyMappings = new KeyPressMappingSet (this);
  15494. Desktop::getInstance().addFocusChangeListener (this);
  15495. }
  15496. ApplicationCommandManager::~ApplicationCommandManager()
  15497. {
  15498. Desktop::getInstance().removeFocusChangeListener (this);
  15499. keyMappings = 0;
  15500. }
  15501. void ApplicationCommandManager::clearCommands()
  15502. {
  15503. commands.clear();
  15504. keyMappings->clearAllKeyPresses();
  15505. triggerAsyncUpdate();
  15506. }
  15507. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  15508. {
  15509. // zero isn't a valid command ID!
  15510. jassert (newCommand.commandID != 0);
  15511. // the name isn't optional!
  15512. jassert (newCommand.shortName.isNotEmpty());
  15513. if (getCommandForID (newCommand.commandID) == 0)
  15514. {
  15515. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  15516. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  15517. commands.add (newInfo);
  15518. keyMappings->resetToDefaultMapping (newCommand.commandID);
  15519. triggerAsyncUpdate();
  15520. }
  15521. else
  15522. {
  15523. // trying to re-register the same command with different parameters?
  15524. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  15525. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  15526. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  15527. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  15528. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  15529. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  15530. }
  15531. }
  15532. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  15533. {
  15534. if (target != 0)
  15535. {
  15536. Array <CommandID> commandIDs;
  15537. target->getAllCommands (commandIDs);
  15538. for (int i = 0; i < commandIDs.size(); ++i)
  15539. {
  15540. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  15541. target->getCommandInfo (info.commandID, info);
  15542. registerCommand (info);
  15543. }
  15544. }
  15545. }
  15546. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  15547. {
  15548. for (int i = commands.size(); --i >= 0;)
  15549. {
  15550. if (commands.getUnchecked (i)->commandID == commandID)
  15551. {
  15552. commands.remove (i);
  15553. triggerAsyncUpdate();
  15554. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  15555. for (int j = keys.size(); --j >= 0;)
  15556. keyMappings->removeKeyPress (keys.getReference (j));
  15557. }
  15558. }
  15559. }
  15560. void ApplicationCommandManager::commandStatusChanged()
  15561. {
  15562. triggerAsyncUpdate();
  15563. }
  15564. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  15565. {
  15566. for (int i = commands.size(); --i >= 0;)
  15567. if (commands.getUnchecked(i)->commandID == commandID)
  15568. return commands.getUnchecked(i);
  15569. return 0;
  15570. }
  15571. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  15572. {
  15573. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15574. return (ci != 0) ? ci->shortName : String::empty;
  15575. }
  15576. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  15577. {
  15578. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  15579. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  15580. : String::empty;
  15581. }
  15582. const StringArray ApplicationCommandManager::getCommandCategories() const
  15583. {
  15584. StringArray s;
  15585. for (int i = 0; i < commands.size(); ++i)
  15586. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  15587. return s;
  15588. }
  15589. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const
  15590. {
  15591. Array <CommandID> results;
  15592. for (int i = 0; i < commands.size(); ++i)
  15593. if (commands.getUnchecked(i)->categoryName == categoryName)
  15594. results.add (commands.getUnchecked(i)->commandID);
  15595. return results;
  15596. }
  15597. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15598. {
  15599. ApplicationCommandTarget::InvocationInfo info (commandID);
  15600. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15601. return invoke (info, asynchronously);
  15602. }
  15603. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  15604. {
  15605. // This call isn't thread-safe for use from a non-UI thread without locking the message
  15606. // manager first..
  15607. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  15608. ApplicationCommandInfo commandInfo (0);
  15609. ApplicationCommandTarget* const target = getTargetForCommand (info_.commandID, commandInfo);
  15610. if (target == 0)
  15611. return false;
  15612. ApplicationCommandTarget::InvocationInfo info (info_);
  15613. info.commandFlags = commandInfo.flags;
  15614. sendListenerInvokeCallback (info);
  15615. const bool ok = target->invoke (info, asynchronously);
  15616. commandStatusChanged();
  15617. return ok;
  15618. }
  15619. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  15620. {
  15621. return firstTarget != 0 ? firstTarget
  15622. : findDefaultComponentTarget();
  15623. }
  15624. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  15625. {
  15626. firstTarget = newTarget;
  15627. }
  15628. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  15629. ApplicationCommandInfo& upToDateInfo)
  15630. {
  15631. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  15632. if (target == 0)
  15633. target = JUCEApplication::getInstance();
  15634. if (target != 0)
  15635. target = target->getTargetForCommand (commandID);
  15636. if (target != 0)
  15637. target->getCommandInfo (commandID, upToDateInfo);
  15638. return target;
  15639. }
  15640. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  15641. {
  15642. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  15643. if (target == 0 && c != 0)
  15644. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15645. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15646. return target;
  15647. }
  15648. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  15649. {
  15650. Component* c = Component::getCurrentlyFocusedComponent();
  15651. if (c == 0)
  15652. {
  15653. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  15654. if (activeWindow != 0)
  15655. {
  15656. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  15657. if (c == 0)
  15658. c = activeWindow;
  15659. }
  15660. }
  15661. if (c == 0 && Process::isForegroundProcess())
  15662. {
  15663. // getting a bit desperate now - try all desktop comps..
  15664. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  15665. {
  15666. ApplicationCommandTarget* const target
  15667. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  15668. ->getPeer()->getLastFocusedSubcomponent());
  15669. if (target != 0)
  15670. return target;
  15671. }
  15672. }
  15673. if (c != 0)
  15674. {
  15675. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  15676. // if we're focused on a ResizableWindow, chances are that it's the content
  15677. // component that really should get the event. And if not, the event will
  15678. // still be passed up to the top level window anyway, so let's send it to the
  15679. // content comp.
  15680. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  15681. c = resizableWindow->getContentComponent();
  15682. ApplicationCommandTarget* const target = findTargetForComponent (c);
  15683. if (target != 0)
  15684. return target;
  15685. }
  15686. return JUCEApplication::getInstance();
  15687. }
  15688. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener)
  15689. {
  15690. listeners.add (listener);
  15691. }
  15692. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener)
  15693. {
  15694. listeners.remove (listener);
  15695. }
  15696. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info)
  15697. {
  15698. listeners.call (&ApplicationCommandManagerListener::applicationCommandInvoked, info);
  15699. }
  15700. void ApplicationCommandManager::handleAsyncUpdate()
  15701. {
  15702. listeners.call (&ApplicationCommandManagerListener::applicationCommandListChanged);
  15703. }
  15704. void ApplicationCommandManager::globalFocusChanged (Component*)
  15705. {
  15706. commandStatusChanged();
  15707. }
  15708. END_JUCE_NAMESPACE
  15709. /*** End of inlined file: juce_ApplicationCommandManager.cpp ***/
  15710. /*** Start of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15711. BEGIN_JUCE_NAMESPACE
  15712. ApplicationCommandTarget::ApplicationCommandTarget()
  15713. {
  15714. }
  15715. ApplicationCommandTarget::~ApplicationCommandTarget()
  15716. {
  15717. messageInvoker = 0;
  15718. }
  15719. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  15720. {
  15721. if (isCommandActive (info.commandID))
  15722. {
  15723. if (async)
  15724. {
  15725. if (messageInvoker == 0)
  15726. messageInvoker = new CommandTargetMessageInvoker (this);
  15727. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  15728. return true;
  15729. }
  15730. else
  15731. {
  15732. const bool success = perform (info);
  15733. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  15734. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  15735. // returns the command's info.
  15736. return success;
  15737. }
  15738. }
  15739. return false;
  15740. }
  15741. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  15742. {
  15743. Component* c = dynamic_cast <Component*> (this);
  15744. if (c != 0)
  15745. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  15746. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  15747. return 0;
  15748. }
  15749. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  15750. {
  15751. ApplicationCommandTarget* target = this;
  15752. int depth = 0;
  15753. while (target != 0)
  15754. {
  15755. Array <CommandID> commandIDs;
  15756. target->getAllCommands (commandIDs);
  15757. if (commandIDs.contains (commandID))
  15758. return target;
  15759. target = target->getNextCommandTarget();
  15760. ++depth;
  15761. jassert (depth < 100); // could be a recursive command chain??
  15762. jassert (target != this); // definitely a recursive command chain!
  15763. if (depth > 100 || target == this)
  15764. break;
  15765. }
  15766. if (target == 0)
  15767. {
  15768. target = JUCEApplication::getInstance();
  15769. if (target != 0)
  15770. {
  15771. Array <CommandID> commandIDs;
  15772. target->getAllCommands (commandIDs);
  15773. if (commandIDs.contains (commandID))
  15774. return target;
  15775. }
  15776. }
  15777. return 0;
  15778. }
  15779. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  15780. {
  15781. ApplicationCommandInfo info (commandID);
  15782. info.flags = ApplicationCommandInfo::isDisabled;
  15783. getCommandInfo (commandID, info);
  15784. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  15785. }
  15786. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  15787. {
  15788. ApplicationCommandTarget* target = this;
  15789. int depth = 0;
  15790. while (target != 0)
  15791. {
  15792. if (target->tryToInvoke (info, async))
  15793. return true;
  15794. target = target->getNextCommandTarget();
  15795. ++depth;
  15796. jassert (depth < 100); // could be a recursive command chain??
  15797. jassert (target != this); // definitely a recursive command chain!
  15798. if (depth > 100 || target == this)
  15799. break;
  15800. }
  15801. if (target == 0)
  15802. {
  15803. target = JUCEApplication::getInstance();
  15804. if (target != 0)
  15805. return target->tryToInvoke (info, async);
  15806. }
  15807. return false;
  15808. }
  15809. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  15810. {
  15811. ApplicationCommandTarget::InvocationInfo info (commandID);
  15812. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  15813. return invoke (info, asynchronously);
  15814. }
  15815. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_)
  15816. : commandID (commandID_),
  15817. commandFlags (0),
  15818. invocationMethod (direct),
  15819. originatingComponent (0),
  15820. isKeyDown (false),
  15821. millisecsSinceKeyPressed (0)
  15822. {
  15823. }
  15824. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  15825. : owner (owner_)
  15826. {
  15827. }
  15828. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  15829. {
  15830. }
  15831. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  15832. {
  15833. const ScopedPointer <InvocationInfo> info (static_cast <InvocationInfo*> (message.pointerParameter));
  15834. owner->tryToInvoke (*info, false);
  15835. }
  15836. END_JUCE_NAMESPACE
  15837. /*** End of inlined file: juce_ApplicationCommandTarget.cpp ***/
  15838. /*** Start of inlined file: juce_ApplicationProperties.cpp ***/
  15839. BEGIN_JUCE_NAMESPACE
  15840. juce_ImplementSingleton (ApplicationProperties)
  15841. ApplicationProperties::ApplicationProperties()
  15842. : msBeforeSaving (3000),
  15843. options (PropertiesFile::storeAsBinary),
  15844. commonSettingsAreReadOnly (0),
  15845. processLock (0)
  15846. {
  15847. }
  15848. ApplicationProperties::~ApplicationProperties()
  15849. {
  15850. closeFiles();
  15851. clearSingletonInstance();
  15852. }
  15853. void ApplicationProperties::setStorageParameters (const String& applicationName,
  15854. const String& fileNameSuffix,
  15855. const String& folderName_,
  15856. const int millisecondsBeforeSaving,
  15857. const int propertiesFileOptions,
  15858. InterProcessLock* processLock_)
  15859. {
  15860. appName = applicationName;
  15861. fileSuffix = fileNameSuffix;
  15862. folderName = folderName_;
  15863. msBeforeSaving = millisecondsBeforeSaving;
  15864. options = propertiesFileOptions;
  15865. processLock = processLock_;
  15866. }
  15867. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  15868. const bool testCommonSettings,
  15869. const bool showWarningDialogOnFailure)
  15870. {
  15871. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  15872. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  15873. if (! (userOk && commonOk))
  15874. {
  15875. if (showWarningDialogOnFailure)
  15876. {
  15877. String filenames;
  15878. if (userProps != 0 && ! userOk)
  15879. filenames << '\n' << userProps->getFile().getFullPathName();
  15880. if (commonProps != 0 && ! commonOk)
  15881. filenames << '\n' << commonProps->getFile().getFullPathName();
  15882. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  15883. appName + TRANS(" - Unable to save settings"),
  15884. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  15885. + appName + TRANS(" needs to be able to write to the following files:\n")
  15886. + filenames
  15887. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  15888. }
  15889. return false;
  15890. }
  15891. return true;
  15892. }
  15893. void ApplicationProperties::openFiles()
  15894. {
  15895. // You need to call setStorageParameters() before trying to get hold of the
  15896. // properties!
  15897. jassert (appName.isNotEmpty());
  15898. if (appName.isNotEmpty())
  15899. {
  15900. if (userProps == 0)
  15901. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15902. false, msBeforeSaving, options, processLock);
  15903. if (commonProps == 0)
  15904. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  15905. true, msBeforeSaving, options, processLock);
  15906. userProps->setFallbackPropertySet (commonProps);
  15907. }
  15908. }
  15909. PropertiesFile* ApplicationProperties::getUserSettings()
  15910. {
  15911. if (userProps == 0)
  15912. openFiles();
  15913. return userProps;
  15914. }
  15915. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly)
  15916. {
  15917. if (commonProps == 0)
  15918. openFiles();
  15919. if (returnUserPropsIfReadOnly)
  15920. {
  15921. if (commonSettingsAreReadOnly == 0)
  15922. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  15923. if (commonSettingsAreReadOnly > 0)
  15924. return userProps;
  15925. }
  15926. return commonProps;
  15927. }
  15928. bool ApplicationProperties::saveIfNeeded()
  15929. {
  15930. return (userProps == 0 || userProps->saveIfNeeded())
  15931. && (commonProps == 0 || commonProps->saveIfNeeded());
  15932. }
  15933. void ApplicationProperties::closeFiles()
  15934. {
  15935. userProps = 0;
  15936. commonProps = 0;
  15937. }
  15938. END_JUCE_NAMESPACE
  15939. /*** End of inlined file: juce_ApplicationProperties.cpp ***/
  15940. /*** Start of inlined file: juce_PropertiesFile.cpp ***/
  15941. BEGIN_JUCE_NAMESPACE
  15942. namespace PropertyFileConstants
  15943. {
  15944. static const int magicNumber = (int) ByteOrder::littleEndianInt ("PROP");
  15945. static const int magicNumberCompressed = (int) ByteOrder::littleEndianInt ("CPRP");
  15946. static const char* const fileTag = "PROPERTIES";
  15947. static const char* const valueTag = "VALUE";
  15948. static const char* const nameAttribute = "name";
  15949. static const char* const valueAttribute = "val";
  15950. }
  15951. PropertiesFile::PropertiesFile (const File& f, const int millisecondsBeforeSaving,
  15952. const int options_, InterProcessLock* const processLock_)
  15953. : PropertySet (ignoreCaseOfKeyNames),
  15954. file (f),
  15955. timerInterval (millisecondsBeforeSaving),
  15956. options (options_),
  15957. loadedOk (false),
  15958. needsWriting (false),
  15959. processLock (processLock_)
  15960. {
  15961. // You need to correctly specify just one storage format for the file
  15962. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  15963. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  15964. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  15965. ProcessScopedLock pl (createProcessLock());
  15966. if (pl != 0 && ! pl->isLocked())
  15967. return; // locking failure..
  15968. ScopedPointer<InputStream> fileStream (f.createInputStream());
  15969. if (fileStream != 0)
  15970. {
  15971. int magicNumber = fileStream->readInt();
  15972. if (magicNumber == PropertyFileConstants::magicNumberCompressed)
  15973. {
  15974. fileStream = new GZIPDecompressorInputStream (new SubregionStream (fileStream.release(), 4, -1, true), true);
  15975. magicNumber = PropertyFileConstants::magicNumber;
  15976. }
  15977. if (magicNumber == PropertyFileConstants::magicNumber)
  15978. {
  15979. loadedOk = true;
  15980. BufferedInputStream in (fileStream.release(), 2048, true);
  15981. int numValues = in.readInt();
  15982. while (--numValues >= 0 && ! in.isExhausted())
  15983. {
  15984. const String key (in.readString());
  15985. const String value (in.readString());
  15986. jassert (key.isNotEmpty());
  15987. if (key.isNotEmpty())
  15988. getAllProperties().set (key, value);
  15989. }
  15990. }
  15991. else
  15992. {
  15993. // Not a binary props file - let's see if it's XML..
  15994. fileStream = 0;
  15995. XmlDocument parser (f);
  15996. ScopedPointer<XmlElement> doc (parser.getDocumentElement (true));
  15997. if (doc != 0 && doc->hasTagName (PropertyFileConstants::fileTag))
  15998. {
  15999. doc = parser.getDocumentElement();
  16000. if (doc != 0)
  16001. {
  16002. loadedOk = true;
  16003. forEachXmlChildElementWithTagName (*doc, e, PropertyFileConstants::valueTag)
  16004. {
  16005. const String name (e->getStringAttribute (PropertyFileConstants::nameAttribute));
  16006. if (name.isNotEmpty())
  16007. {
  16008. getAllProperties().set (name,
  16009. e->getFirstChildElement() != 0
  16010. ? e->getFirstChildElement()->createDocument (String::empty, true)
  16011. : e->getStringAttribute (PropertyFileConstants::valueAttribute));
  16012. }
  16013. }
  16014. }
  16015. else
  16016. {
  16017. // must be a pretty broken XML file we're trying to parse here,
  16018. // or a sign that this object needs an InterProcessLock,
  16019. // or just a failure reading the file. This last reason is why
  16020. // we don't jassertfalse here.
  16021. }
  16022. }
  16023. }
  16024. }
  16025. else
  16026. {
  16027. loadedOk = ! f.exists();
  16028. }
  16029. }
  16030. PropertiesFile::~PropertiesFile()
  16031. {
  16032. if (! saveIfNeeded())
  16033. jassertfalse;
  16034. }
  16035. InterProcessLock::ScopedLockType* PropertiesFile::createProcessLock() const
  16036. {
  16037. return processLock != 0 ? new InterProcessLock::ScopedLockType (*processLock) : 0;
  16038. }
  16039. bool PropertiesFile::saveIfNeeded()
  16040. {
  16041. const ScopedLock sl (getLock());
  16042. return (! needsWriting) || save();
  16043. }
  16044. bool PropertiesFile::needsToBeSaved() const
  16045. {
  16046. const ScopedLock sl (getLock());
  16047. return needsWriting;
  16048. }
  16049. void PropertiesFile::setNeedsToBeSaved (const bool needsToBeSaved_)
  16050. {
  16051. const ScopedLock sl (getLock());
  16052. needsWriting = needsToBeSaved_;
  16053. }
  16054. bool PropertiesFile::save()
  16055. {
  16056. const ScopedLock sl (getLock());
  16057. stopTimer();
  16058. if (file == File::nonexistent
  16059. || file.isDirectory()
  16060. || ! file.getParentDirectory().createDirectory())
  16061. return false;
  16062. if ((options & storeAsXML) != 0)
  16063. {
  16064. XmlElement doc (PropertyFileConstants::fileTag);
  16065. for (int i = 0; i < getAllProperties().size(); ++i)
  16066. {
  16067. XmlElement* const e = doc.createNewChildElement (PropertyFileConstants::valueTag);
  16068. e->setAttribute (PropertyFileConstants::nameAttribute, getAllProperties().getAllKeys() [i]);
  16069. // if the value seems to contain xml, store it as such..
  16070. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  16071. XmlElement* const childElement = xmlContent.getDocumentElement();
  16072. if (childElement != 0)
  16073. e->addChildElement (childElement);
  16074. else
  16075. e->setAttribute (PropertyFileConstants::valueAttribute,
  16076. getAllProperties().getAllValues() [i]);
  16077. }
  16078. ProcessScopedLock pl (createProcessLock());
  16079. if (pl != 0 && ! pl->isLocked())
  16080. return false; // locking failure..
  16081. if (doc.writeToFile (file, String::empty))
  16082. {
  16083. needsWriting = false;
  16084. return true;
  16085. }
  16086. }
  16087. else
  16088. {
  16089. ProcessScopedLock pl (createProcessLock());
  16090. if (pl != 0 && ! pl->isLocked())
  16091. return false; // locking failure..
  16092. TemporaryFile tempFile (file);
  16093. ScopedPointer <OutputStream> out (tempFile.getFile().createOutputStream());
  16094. if (out != 0)
  16095. {
  16096. if ((options & storeAsCompressedBinary) != 0)
  16097. {
  16098. out->writeInt (PropertyFileConstants::magicNumberCompressed);
  16099. out->flush();
  16100. out = new GZIPCompressorOutputStream (out.release(), 9, true);
  16101. }
  16102. else
  16103. {
  16104. // have you set up the storage option flags correctly?
  16105. jassert ((options & storeAsBinary) != 0);
  16106. out->writeInt (PropertyFileConstants::magicNumber);
  16107. }
  16108. const int numProperties = getAllProperties().size();
  16109. out->writeInt (numProperties);
  16110. for (int i = 0; i < numProperties; ++i)
  16111. {
  16112. out->writeString (getAllProperties().getAllKeys() [i]);
  16113. out->writeString (getAllProperties().getAllValues() [i]);
  16114. }
  16115. out = 0;
  16116. if (tempFile.overwriteTargetFileWithTemporary())
  16117. {
  16118. needsWriting = false;
  16119. return true;
  16120. }
  16121. }
  16122. }
  16123. return false;
  16124. }
  16125. void PropertiesFile::timerCallback()
  16126. {
  16127. saveIfNeeded();
  16128. }
  16129. void PropertiesFile::propertyChanged()
  16130. {
  16131. sendChangeMessage (this);
  16132. needsWriting = true;
  16133. if (timerInterval > 0)
  16134. startTimer (timerInterval);
  16135. else if (timerInterval == 0)
  16136. saveIfNeeded();
  16137. }
  16138. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  16139. const String& fileNameSuffix,
  16140. const String& folderName,
  16141. const bool commonToAllUsers)
  16142. {
  16143. // mustn't have illegal characters in this name..
  16144. jassert (applicationName == File::createLegalFileName (applicationName));
  16145. #if JUCE_MAC || JUCE_IOS
  16146. File dir (commonToAllUsers ? "/Library/Preferences"
  16147. : "~/Library/Preferences");
  16148. if (folderName.isNotEmpty())
  16149. dir = dir.getChildFile (folderName);
  16150. #endif
  16151. #ifdef JUCE_LINUX
  16152. const File dir ((commonToAllUsers ? "/var/" : "~/")
  16153. + (folderName.isNotEmpty() ? folderName
  16154. : ("." + applicationName)));
  16155. #endif
  16156. #if JUCE_WINDOWS
  16157. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  16158. : File::userApplicationDataDirectory));
  16159. if (dir == File::nonexistent)
  16160. return File::nonexistent;
  16161. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  16162. : applicationName);
  16163. #endif
  16164. return dir.getChildFile (applicationName)
  16165. .withFileExtension (fileNameSuffix);
  16166. }
  16167. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  16168. const String& fileNameSuffix,
  16169. const String& folderName,
  16170. const bool commonToAllUsers,
  16171. const int millisecondsBeforeSaving,
  16172. const int propertiesFileOptions,
  16173. InterProcessLock* processLock_)
  16174. {
  16175. const File file (getDefaultAppSettingsFile (applicationName,
  16176. fileNameSuffix,
  16177. folderName,
  16178. commonToAllUsers));
  16179. jassert (file != File::nonexistent);
  16180. if (file == File::nonexistent)
  16181. return 0;
  16182. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions,processLock_);
  16183. }
  16184. END_JUCE_NAMESPACE
  16185. /*** End of inlined file: juce_PropertiesFile.cpp ***/
  16186. /*** Start of inlined file: juce_FileBasedDocument.cpp ***/
  16187. BEGIN_JUCE_NAMESPACE
  16188. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  16189. const String& fileWildcard_,
  16190. const String& openFileDialogTitle_,
  16191. const String& saveFileDialogTitle_)
  16192. : changedSinceSave (false),
  16193. fileExtension (fileExtension_),
  16194. fileWildcard (fileWildcard_),
  16195. openFileDialogTitle (openFileDialogTitle_),
  16196. saveFileDialogTitle (saveFileDialogTitle_)
  16197. {
  16198. }
  16199. FileBasedDocument::~FileBasedDocument()
  16200. {
  16201. }
  16202. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  16203. {
  16204. if (changedSinceSave != hasChanged)
  16205. {
  16206. changedSinceSave = hasChanged;
  16207. sendChangeMessage (this);
  16208. }
  16209. }
  16210. void FileBasedDocument::changed()
  16211. {
  16212. changedSinceSave = true;
  16213. sendChangeMessage (this);
  16214. }
  16215. void FileBasedDocument::setFile (const File& newFile)
  16216. {
  16217. if (documentFile != newFile)
  16218. {
  16219. documentFile = newFile;
  16220. changed();
  16221. }
  16222. }
  16223. bool FileBasedDocument::loadFrom (const File& newFile,
  16224. const bool showMessageOnFailure)
  16225. {
  16226. MouseCursor::showWaitCursor();
  16227. const File oldFile (documentFile);
  16228. documentFile = newFile;
  16229. String error;
  16230. if (newFile.existsAsFile())
  16231. {
  16232. error = loadDocument (newFile);
  16233. if (error.isEmpty())
  16234. {
  16235. setChangedFlag (false);
  16236. MouseCursor::hideWaitCursor();
  16237. setLastDocumentOpened (newFile);
  16238. return true;
  16239. }
  16240. }
  16241. else
  16242. {
  16243. error = "The file doesn't exist";
  16244. }
  16245. documentFile = oldFile;
  16246. MouseCursor::hideWaitCursor();
  16247. if (showMessageOnFailure)
  16248. {
  16249. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16250. TRANS("Failed to open file..."),
  16251. TRANS("There was an error while trying to load the file:\n\n")
  16252. + newFile.getFullPathName()
  16253. + "\n\n"
  16254. + error);
  16255. }
  16256. return false;
  16257. }
  16258. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  16259. {
  16260. FileChooser fc (openFileDialogTitle,
  16261. getLastDocumentOpened(),
  16262. fileWildcard);
  16263. if (fc.browseForFileToOpen())
  16264. return loadFrom (fc.getResult(), showMessageOnFailure);
  16265. return false;
  16266. }
  16267. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  16268. const bool showMessageOnFailure)
  16269. {
  16270. return saveAs (documentFile,
  16271. false,
  16272. askUserForFileIfNotSpecified,
  16273. showMessageOnFailure);
  16274. }
  16275. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  16276. const bool warnAboutOverwritingExistingFiles,
  16277. const bool askUserForFileIfNotSpecified,
  16278. const bool showMessageOnFailure)
  16279. {
  16280. if (newFile == File::nonexistent)
  16281. {
  16282. if (askUserForFileIfNotSpecified)
  16283. {
  16284. return saveAsInteractive (true);
  16285. }
  16286. else
  16287. {
  16288. // can't save to an unspecified file
  16289. jassertfalse;
  16290. return failedToWriteToFile;
  16291. }
  16292. }
  16293. if (warnAboutOverwritingExistingFiles && newFile.exists())
  16294. {
  16295. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16296. TRANS("File already exists"),
  16297. TRANS("There's already a file called:\n\n")
  16298. + newFile.getFullPathName()
  16299. + TRANS("\n\nAre you sure you want to overwrite it?"),
  16300. TRANS("overwrite"),
  16301. TRANS("cancel")))
  16302. {
  16303. return userCancelledSave;
  16304. }
  16305. }
  16306. MouseCursor::showWaitCursor();
  16307. const File oldFile (documentFile);
  16308. documentFile = newFile;
  16309. String error (saveDocument (newFile));
  16310. if (error.isEmpty())
  16311. {
  16312. setChangedFlag (false);
  16313. MouseCursor::hideWaitCursor();
  16314. return savedOk;
  16315. }
  16316. documentFile = oldFile;
  16317. MouseCursor::hideWaitCursor();
  16318. if (showMessageOnFailure)
  16319. {
  16320. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  16321. TRANS("Error writing to file..."),
  16322. TRANS("An error occurred while trying to save \"")
  16323. + getDocumentTitle()
  16324. + TRANS("\" to the file:\n\n")
  16325. + newFile.getFullPathName()
  16326. + "\n\n"
  16327. + error);
  16328. }
  16329. return failedToWriteToFile;
  16330. }
  16331. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  16332. {
  16333. if (! hasChangedSinceSaved())
  16334. return savedOk;
  16335. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  16336. TRANS("Closing document..."),
  16337. TRANS("Do you want to save the changes to \"")
  16338. + getDocumentTitle() + "\"?",
  16339. TRANS("save"),
  16340. TRANS("discard changes"),
  16341. TRANS("cancel"));
  16342. if (r == 1)
  16343. {
  16344. // save changes
  16345. return save (true, true);
  16346. }
  16347. else if (r == 2)
  16348. {
  16349. // discard changes
  16350. return savedOk;
  16351. }
  16352. return userCancelledSave;
  16353. }
  16354. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  16355. {
  16356. File f;
  16357. if (documentFile.existsAsFile())
  16358. f = documentFile;
  16359. else
  16360. f = getLastDocumentOpened();
  16361. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  16362. if (legalFilename.isEmpty())
  16363. legalFilename = "unnamed";
  16364. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  16365. f = f.getSiblingFile (legalFilename);
  16366. else
  16367. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  16368. f = f.withFileExtension (fileExtension)
  16369. .getNonexistentSibling (true);
  16370. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  16371. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  16372. {
  16373. File chosen (fc.getResult());
  16374. if (chosen.getFileExtension().isEmpty())
  16375. {
  16376. chosen = chosen.withFileExtension (fileExtension);
  16377. if (chosen.exists())
  16378. {
  16379. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  16380. TRANS("File already exists"),
  16381. TRANS("There's already a file called:")
  16382. + "\n\n" + chosen.getFullPathName()
  16383. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  16384. TRANS("overwrite"),
  16385. TRANS("cancel")))
  16386. {
  16387. return userCancelledSave;
  16388. }
  16389. }
  16390. }
  16391. setLastDocumentOpened (chosen);
  16392. return saveAs (chosen, false, false, true);
  16393. }
  16394. return userCancelledSave;
  16395. }
  16396. END_JUCE_NAMESPACE
  16397. /*** End of inlined file: juce_FileBasedDocument.cpp ***/
  16398. /*** Start of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16399. BEGIN_JUCE_NAMESPACE
  16400. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  16401. : maxNumberOfItems (10)
  16402. {
  16403. }
  16404. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  16405. {
  16406. }
  16407. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  16408. {
  16409. maxNumberOfItems = jmax (1, newMaxNumber);
  16410. while (getNumFiles() > maxNumberOfItems)
  16411. files.remove (getNumFiles() - 1);
  16412. }
  16413. int RecentlyOpenedFilesList::getNumFiles() const
  16414. {
  16415. return files.size();
  16416. }
  16417. const File RecentlyOpenedFilesList::getFile (const int index) const
  16418. {
  16419. return File (files [index]);
  16420. }
  16421. void RecentlyOpenedFilesList::clear()
  16422. {
  16423. files.clear();
  16424. }
  16425. void RecentlyOpenedFilesList::addFile (const File& file)
  16426. {
  16427. const String path (file.getFullPathName());
  16428. files.removeString (path, true);
  16429. files.insert (0, path);
  16430. setMaxNumberOfItems (maxNumberOfItems);
  16431. }
  16432. void RecentlyOpenedFilesList::removeNonExistentFiles()
  16433. {
  16434. for (int i = getNumFiles(); --i >= 0;)
  16435. if (! getFile(i).exists())
  16436. files.remove (i);
  16437. }
  16438. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  16439. const int baseItemId,
  16440. const bool showFullPaths,
  16441. const bool dontAddNonExistentFiles,
  16442. const File** filesToAvoid)
  16443. {
  16444. int num = 0;
  16445. for (int i = 0; i < getNumFiles(); ++i)
  16446. {
  16447. const File f (getFile(i));
  16448. if ((! dontAddNonExistentFiles) || f.exists())
  16449. {
  16450. bool needsAvoiding = false;
  16451. if (filesToAvoid != 0)
  16452. {
  16453. const File** avoid = filesToAvoid;
  16454. while (*avoid != 0)
  16455. {
  16456. if (f == **avoid)
  16457. {
  16458. needsAvoiding = true;
  16459. break;
  16460. }
  16461. ++avoid;
  16462. }
  16463. }
  16464. if (! needsAvoiding)
  16465. {
  16466. menuToAddTo.addItem (baseItemId + i,
  16467. showFullPaths ? f.getFullPathName()
  16468. : f.getFileName());
  16469. ++num;
  16470. }
  16471. }
  16472. }
  16473. return num;
  16474. }
  16475. const String RecentlyOpenedFilesList::toString() const
  16476. {
  16477. return files.joinIntoString ("\n");
  16478. }
  16479. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  16480. {
  16481. clear();
  16482. files.addLines (stringifiedVersion);
  16483. setMaxNumberOfItems (maxNumberOfItems);
  16484. }
  16485. END_JUCE_NAMESPACE
  16486. /*** End of inlined file: juce_RecentlyOpenedFilesList.cpp ***/
  16487. /*** Start of inlined file: juce_UndoManager.cpp ***/
  16488. BEGIN_JUCE_NAMESPACE
  16489. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  16490. const int minimumTransactions)
  16491. : totalUnitsStored (0),
  16492. nextIndex (0),
  16493. newTransaction (true),
  16494. reentrancyCheck (false)
  16495. {
  16496. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  16497. minimumTransactions);
  16498. }
  16499. UndoManager::~UndoManager()
  16500. {
  16501. clearUndoHistory();
  16502. }
  16503. void UndoManager::clearUndoHistory()
  16504. {
  16505. transactions.clear();
  16506. transactionNames.clear();
  16507. totalUnitsStored = 0;
  16508. nextIndex = 0;
  16509. sendChangeMessage (this);
  16510. }
  16511. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  16512. {
  16513. return totalUnitsStored;
  16514. }
  16515. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  16516. const int minimumTransactions)
  16517. {
  16518. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  16519. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  16520. }
  16521. bool UndoManager::perform (UndoableAction* const command_, const String& actionName)
  16522. {
  16523. if (command_ != 0)
  16524. {
  16525. ScopedPointer<UndoableAction> command (command_);
  16526. if (actionName.isNotEmpty())
  16527. currentTransactionName = actionName;
  16528. if (reentrancyCheck)
  16529. {
  16530. jassertfalse; // don't call perform() recursively from the UndoableAction::perform() or
  16531. // undo() methods, or else these actions won't actually get done.
  16532. return false;
  16533. }
  16534. else if (command->perform())
  16535. {
  16536. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  16537. if (commandSet != 0 && ! newTransaction)
  16538. {
  16539. UndoableAction* lastAction = commandSet->getLast();
  16540. if (lastAction != 0)
  16541. {
  16542. UndoableAction* coalescedAction = lastAction->createCoalescedAction (command);
  16543. if (coalescedAction != 0)
  16544. {
  16545. command = coalescedAction;
  16546. totalUnitsStored -= lastAction->getSizeInUnits();
  16547. commandSet->removeLast();
  16548. }
  16549. }
  16550. }
  16551. else
  16552. {
  16553. commandSet = new OwnedArray<UndoableAction>();
  16554. transactions.insert (nextIndex, commandSet);
  16555. transactionNames.insert (nextIndex, currentTransactionName);
  16556. ++nextIndex;
  16557. }
  16558. totalUnitsStored += command->getSizeInUnits();
  16559. commandSet->add (command.release());
  16560. newTransaction = false;
  16561. while (nextIndex < transactions.size())
  16562. {
  16563. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  16564. for (int i = lastSet->size(); --i >= 0;)
  16565. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  16566. transactions.removeLast();
  16567. transactionNames.remove (transactionNames.size() - 1);
  16568. }
  16569. while (nextIndex > 0
  16570. && totalUnitsStored > maxNumUnitsToKeep
  16571. && transactions.size() > minimumTransactionsToKeep)
  16572. {
  16573. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  16574. for (int i = firstSet->size(); --i >= 0;)
  16575. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  16576. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  16577. transactions.remove (0);
  16578. transactionNames.remove (0);
  16579. --nextIndex;
  16580. }
  16581. sendChangeMessage (this);
  16582. return true;
  16583. }
  16584. }
  16585. return false;
  16586. }
  16587. void UndoManager::beginNewTransaction (const String& actionName)
  16588. {
  16589. newTransaction = true;
  16590. currentTransactionName = actionName;
  16591. }
  16592. void UndoManager::setCurrentTransactionName (const String& newName)
  16593. {
  16594. currentTransactionName = newName;
  16595. }
  16596. bool UndoManager::canUndo() const
  16597. {
  16598. return nextIndex > 0;
  16599. }
  16600. bool UndoManager::canRedo() const
  16601. {
  16602. return nextIndex < transactions.size();
  16603. }
  16604. const String UndoManager::getUndoDescription() const
  16605. {
  16606. return transactionNames [nextIndex - 1];
  16607. }
  16608. const String UndoManager::getRedoDescription() const
  16609. {
  16610. return transactionNames [nextIndex];
  16611. }
  16612. bool UndoManager::undo()
  16613. {
  16614. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16615. if (commandSet == 0)
  16616. return false;
  16617. reentrancyCheck = true;
  16618. bool failed = false;
  16619. for (int i = commandSet->size(); --i >= 0;)
  16620. {
  16621. if (! commandSet->getUnchecked(i)->undo())
  16622. {
  16623. jassertfalse;
  16624. failed = true;
  16625. break;
  16626. }
  16627. }
  16628. reentrancyCheck = false;
  16629. if (failed)
  16630. clearUndoHistory();
  16631. else
  16632. --nextIndex;
  16633. beginNewTransaction();
  16634. sendChangeMessage (this);
  16635. return true;
  16636. }
  16637. bool UndoManager::redo()
  16638. {
  16639. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  16640. if (commandSet == 0)
  16641. return false;
  16642. reentrancyCheck = true;
  16643. bool failed = false;
  16644. for (int i = 0; i < commandSet->size(); ++i)
  16645. {
  16646. if (! commandSet->getUnchecked(i)->perform())
  16647. {
  16648. jassertfalse;
  16649. failed = true;
  16650. break;
  16651. }
  16652. }
  16653. reentrancyCheck = false;
  16654. if (failed)
  16655. clearUndoHistory();
  16656. else
  16657. ++nextIndex;
  16658. beginNewTransaction();
  16659. sendChangeMessage (this);
  16660. return true;
  16661. }
  16662. bool UndoManager::undoCurrentTransactionOnly()
  16663. {
  16664. return newTransaction ? false : undo();
  16665. }
  16666. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  16667. {
  16668. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16669. if (commandSet != 0 && ! newTransaction)
  16670. {
  16671. for (int i = 0; i < commandSet->size(); ++i)
  16672. actionsFound.add (commandSet->getUnchecked(i));
  16673. }
  16674. }
  16675. int UndoManager::getNumActionsInCurrentTransaction() const
  16676. {
  16677. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  16678. if (commandSet != 0 && ! newTransaction)
  16679. return commandSet->size();
  16680. return 0;
  16681. }
  16682. END_JUCE_NAMESPACE
  16683. /*** End of inlined file: juce_UndoManager.cpp ***/
  16684. /*** Start of inlined file: juce_AiffAudioFormat.cpp ***/
  16685. BEGIN_JUCE_NAMESPACE
  16686. static const char* const aiffFormatName = "AIFF file";
  16687. static const char* const aiffExtensions[] = { ".aiff", ".aif", 0 };
  16688. class AiffAudioFormatReader : public AudioFormatReader
  16689. {
  16690. public:
  16691. int bytesPerFrame;
  16692. int64 dataChunkStart;
  16693. bool littleEndian;
  16694. AiffAudioFormatReader (InputStream* in)
  16695. : AudioFormatReader (in, TRANS (aiffFormatName))
  16696. {
  16697. if (input->readInt() == chunkName ("FORM"))
  16698. {
  16699. const int len = input->readIntBigEndian();
  16700. const int64 end = input->getPosition() + len;
  16701. const int nextType = input->readInt();
  16702. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  16703. {
  16704. bool hasGotVer = false;
  16705. bool hasGotData = false;
  16706. bool hasGotType = false;
  16707. while (input->getPosition() < end)
  16708. {
  16709. const int type = input->readInt();
  16710. const uint32 length = (uint32) input->readIntBigEndian();
  16711. const int64 chunkEnd = input->getPosition() + length;
  16712. if (type == chunkName ("FVER"))
  16713. {
  16714. hasGotVer = true;
  16715. const int ver = input->readIntBigEndian();
  16716. if (ver != 0 && ver != (int) 0xa2805140)
  16717. break;
  16718. }
  16719. else if (type == chunkName ("COMM"))
  16720. {
  16721. hasGotType = true;
  16722. numChannels = (unsigned int) input->readShortBigEndian();
  16723. lengthInSamples = input->readIntBigEndian();
  16724. bitsPerSample = input->readShortBigEndian();
  16725. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  16726. unsigned char sampleRateBytes[10];
  16727. input->read (sampleRateBytes, 10);
  16728. const int byte0 = sampleRateBytes[0];
  16729. if ((byte0 & 0x80) != 0
  16730. || byte0 <= 0x3F || byte0 > 0x40
  16731. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  16732. break;
  16733. unsigned int sampRate = ByteOrder::bigEndianInt (sampleRateBytes + 2);
  16734. sampRate >>= (16414 - ByteOrder::bigEndianShort (sampleRateBytes));
  16735. sampleRate = (int) sampRate;
  16736. if (length <= 18)
  16737. {
  16738. // some types don't have a chunk large enough to include a compression
  16739. // type, so assume it's just big-endian pcm
  16740. littleEndian = false;
  16741. }
  16742. else
  16743. {
  16744. const int compType = input->readInt();
  16745. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  16746. {
  16747. littleEndian = false;
  16748. }
  16749. else if (compType == chunkName ("sowt"))
  16750. {
  16751. littleEndian = true;
  16752. }
  16753. else
  16754. {
  16755. sampleRate = 0;
  16756. break;
  16757. }
  16758. }
  16759. }
  16760. else if (type == chunkName ("SSND"))
  16761. {
  16762. hasGotData = true;
  16763. const int offset = input->readIntBigEndian();
  16764. dataChunkStart = input->getPosition() + 4 + offset;
  16765. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  16766. }
  16767. else if ((hasGotVer && hasGotData && hasGotType)
  16768. || chunkEnd < input->getPosition()
  16769. || input->isExhausted())
  16770. {
  16771. break;
  16772. }
  16773. input->setPosition (chunkEnd);
  16774. }
  16775. }
  16776. }
  16777. }
  16778. ~AiffAudioFormatReader()
  16779. {
  16780. }
  16781. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  16782. int64 startSampleInFile, int numSamples)
  16783. {
  16784. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  16785. if (samplesAvailable < numSamples)
  16786. {
  16787. for (int i = numDestChannels; --i >= 0;)
  16788. if (destSamples[i] != 0)
  16789. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  16790. numSamples = (int) samplesAvailable;
  16791. }
  16792. if (numSamples <= 0)
  16793. return true;
  16794. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  16795. while (numSamples > 0)
  16796. {
  16797. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  16798. char tempBuffer [tempBufSize];
  16799. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  16800. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  16801. if (bytesRead < numThisTime * bytesPerFrame)
  16802. {
  16803. jassert (bytesRead >= 0);
  16804. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  16805. }
  16806. jassert (! usesFloatingPointData); // (would need to add support for this if it's possible)
  16807. if (littleEndian)
  16808. {
  16809. switch (bitsPerSample)
  16810. {
  16811. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16812. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16813. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16814. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16815. default: jassertfalse; break;
  16816. }
  16817. }
  16818. else
  16819. {
  16820. switch (bitsPerSample)
  16821. {
  16822. case 8: ReadHelper<AudioData::Int32, AudioData::Int8, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16823. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16824. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16825. case 32: ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  16826. default: jassertfalse; break;
  16827. }
  16828. }
  16829. startOffsetInDestBuffer += numThisTime;
  16830. numSamples -= numThisTime;
  16831. }
  16832. return true;
  16833. }
  16834. juce_UseDebuggingNewOperator
  16835. private:
  16836. AiffAudioFormatReader (const AiffAudioFormatReader&);
  16837. AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  16838. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16839. };
  16840. class AiffAudioFormatWriter : public AudioFormatWriter
  16841. {
  16842. public:
  16843. AiffAudioFormatWriter (OutputStream* out, double sampleRate_, unsigned int numChans, int bits)
  16844. : AudioFormatWriter (out, TRANS (aiffFormatName), sampleRate_, numChans, bits),
  16845. lengthInSamples (0),
  16846. bytesWritten (0),
  16847. writeFailed (false)
  16848. {
  16849. headerPosition = out->getPosition();
  16850. writeHeader();
  16851. }
  16852. ~AiffAudioFormatWriter()
  16853. {
  16854. if ((bytesWritten & 1) != 0)
  16855. output->writeByte (0);
  16856. writeHeader();
  16857. }
  16858. bool write (const int** data, int numSamples)
  16859. {
  16860. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  16861. if (writeFailed)
  16862. return false;
  16863. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16864. tempBlock.ensureSize (bytes, false);
  16865. switch (bitsPerSample)
  16866. {
  16867. case 8: WriteHelper<AudioData::Int8, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16868. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16869. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16870. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::BigEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  16871. default: jassertfalse; break;
  16872. }
  16873. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16874. || ! output->write (tempBlock.getData(), bytes))
  16875. {
  16876. // failed to write to disk, so let's try writing the header.
  16877. // If it's just run out of disk space, then if it does manage
  16878. // to write the header, we'll still have a useable file..
  16879. writeHeader();
  16880. writeFailed = true;
  16881. return false;
  16882. }
  16883. else
  16884. {
  16885. bytesWritten += bytes;
  16886. lengthInSamples += numSamples;
  16887. return true;
  16888. }
  16889. }
  16890. juce_UseDebuggingNewOperator
  16891. private:
  16892. MemoryBlock tempBlock;
  16893. uint32 lengthInSamples, bytesWritten;
  16894. int64 headerPosition;
  16895. bool writeFailed;
  16896. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  16897. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  16898. AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  16899. void writeHeader()
  16900. {
  16901. const bool couldSeekOk = output->setPosition (headerPosition);
  16902. (void) couldSeekOk;
  16903. // if this fails, you've given it an output stream that can't seek! It needs
  16904. // to be able to seek back to write the header
  16905. jassert (couldSeekOk);
  16906. const int headerLen = 54;
  16907. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  16908. audioBytes += (audioBytes & 1);
  16909. output->writeInt (chunkName ("FORM"));
  16910. output->writeIntBigEndian (headerLen + audioBytes - 8);
  16911. output->writeInt (chunkName ("AIFF"));
  16912. output->writeInt (chunkName ("COMM"));
  16913. output->writeIntBigEndian (18);
  16914. output->writeShortBigEndian ((short) numChannels);
  16915. output->writeIntBigEndian (lengthInSamples);
  16916. output->writeShortBigEndian ((short) bitsPerSample);
  16917. uint8 sampleRateBytes[10];
  16918. zeromem (sampleRateBytes, 10);
  16919. if (sampleRate <= 1)
  16920. {
  16921. sampleRateBytes[0] = 0x3f;
  16922. sampleRateBytes[1] = 0xff;
  16923. sampleRateBytes[2] = 0x80;
  16924. }
  16925. else
  16926. {
  16927. int mask = 0x40000000;
  16928. sampleRateBytes[0] = 0x40;
  16929. if (sampleRate >= mask)
  16930. {
  16931. jassertfalse;
  16932. sampleRateBytes[1] = 0x1d;
  16933. }
  16934. else
  16935. {
  16936. int n = (int) sampleRate;
  16937. int i;
  16938. for (i = 0; i <= 32 ; ++i)
  16939. {
  16940. if ((n & mask) != 0)
  16941. break;
  16942. mask >>= 1;
  16943. }
  16944. n = n << (i + 1);
  16945. sampleRateBytes[1] = (uint8) (29 - i);
  16946. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  16947. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  16948. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  16949. sampleRateBytes[5] = (uint8) (n & 0xff);
  16950. }
  16951. }
  16952. output->write (sampleRateBytes, 10);
  16953. output->writeInt (chunkName ("SSND"));
  16954. output->writeIntBigEndian (audioBytes + 8);
  16955. output->writeInt (0);
  16956. output->writeInt (0);
  16957. jassert (output->getPosition() == headerLen);
  16958. }
  16959. };
  16960. AiffAudioFormat::AiffAudioFormat()
  16961. : AudioFormat (TRANS (aiffFormatName), StringArray (aiffExtensions))
  16962. {
  16963. }
  16964. AiffAudioFormat::~AiffAudioFormat()
  16965. {
  16966. }
  16967. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  16968. {
  16969. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16970. return Array <int> (rates);
  16971. }
  16972. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  16973. {
  16974. const int depths[] = { 8, 16, 24, 0 };
  16975. return Array <int> (depths);
  16976. }
  16977. bool AiffAudioFormat::canDoStereo() { return true; }
  16978. bool AiffAudioFormat::canDoMono() { return true; }
  16979. #if JUCE_MAC
  16980. bool AiffAudioFormat::canHandleFile (const File& f)
  16981. {
  16982. if (AudioFormat::canHandleFile (f))
  16983. return true;
  16984. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  16985. return type == 'AIFF' || type == 'AIFC'
  16986. || type == 'aiff' || type == 'aifc';
  16987. }
  16988. #endif
  16989. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream, const bool deleteStreamIfOpeningFails)
  16990. {
  16991. ScopedPointer <AiffAudioFormatReader> w (new AiffAudioFormatReader (sourceStream));
  16992. if (w->sampleRate != 0)
  16993. return w.release();
  16994. if (! deleteStreamIfOpeningFails)
  16995. w->input = 0;
  16996. return 0;
  16997. }
  16998. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  16999. double sampleRate,
  17000. unsigned int numberOfChannels,
  17001. int bitsPerSample,
  17002. const StringPairArray& /*metadataValues*/,
  17003. int /*qualityOptionIndex*/)
  17004. {
  17005. if (getPossibleBitDepths().contains (bitsPerSample))
  17006. return new AiffAudioFormatWriter (out, sampleRate, numberOfChannels, bitsPerSample);
  17007. return 0;
  17008. }
  17009. END_JUCE_NAMESPACE
  17010. /*** End of inlined file: juce_AiffAudioFormat.cpp ***/
  17011. /*** Start of inlined file: juce_AudioFormat.cpp ***/
  17012. BEGIN_JUCE_NAMESPACE
  17013. AudioFormat::AudioFormat (const String& name, const StringArray& extensions)
  17014. : formatName (name),
  17015. fileExtensions (extensions)
  17016. {
  17017. }
  17018. AudioFormat::~AudioFormat()
  17019. {
  17020. }
  17021. bool AudioFormat::canHandleFile (const File& f)
  17022. {
  17023. for (int i = 0; i < fileExtensions.size(); ++i)
  17024. if (f.hasFileExtension (fileExtensions[i]))
  17025. return true;
  17026. return false;
  17027. }
  17028. const String& AudioFormat::getFormatName() const { return formatName; }
  17029. const StringArray& AudioFormat::getFileExtensions() const { return fileExtensions; }
  17030. bool AudioFormat::isCompressed() { return false; }
  17031. const StringArray AudioFormat::getQualityOptions() { return StringArray(); }
  17032. END_JUCE_NAMESPACE
  17033. /*** End of inlined file: juce_AudioFormat.cpp ***/
  17034. /*** Start of inlined file: juce_AudioFormatReader.cpp ***/
  17035. BEGIN_JUCE_NAMESPACE
  17036. AudioFormatReader::AudioFormatReader (InputStream* const in,
  17037. const String& formatName_)
  17038. : sampleRate (0),
  17039. bitsPerSample (0),
  17040. lengthInSamples (0),
  17041. numChannels (0),
  17042. usesFloatingPointData (false),
  17043. input (in),
  17044. formatName (formatName_)
  17045. {
  17046. }
  17047. AudioFormatReader::~AudioFormatReader()
  17048. {
  17049. delete input;
  17050. }
  17051. bool AudioFormatReader::read (int* const* destSamples,
  17052. int numDestChannels,
  17053. int64 startSampleInSource,
  17054. int numSamplesToRead,
  17055. const bool fillLeftoverChannelsWithCopies)
  17056. {
  17057. jassert (numDestChannels > 0); // you have to actually give this some channels to work with!
  17058. int startOffsetInDestBuffer = 0;
  17059. if (startSampleInSource < 0)
  17060. {
  17061. const int silence = (int) jmin (-startSampleInSource, (int64) numSamplesToRead);
  17062. for (int i = numDestChannels; --i >= 0;)
  17063. if (destSamples[i] != 0)
  17064. zeromem (destSamples[i], sizeof (int) * silence);
  17065. startOffsetInDestBuffer += silence;
  17066. numSamplesToRead -= silence;
  17067. startSampleInSource = 0;
  17068. }
  17069. if (numSamplesToRead <= 0)
  17070. return true;
  17071. if (! readSamples (const_cast<int**> (destSamples),
  17072. jmin ((int) numChannels, numDestChannels), startOffsetInDestBuffer,
  17073. startSampleInSource, numSamplesToRead))
  17074. return false;
  17075. if (numDestChannels > (int) numChannels)
  17076. {
  17077. if (fillLeftoverChannelsWithCopies)
  17078. {
  17079. int* lastFullChannel = destSamples[0];
  17080. for (int i = (int) numChannels; --i > 0;)
  17081. {
  17082. if (destSamples[i] != 0)
  17083. {
  17084. lastFullChannel = destSamples[i];
  17085. break;
  17086. }
  17087. }
  17088. if (lastFullChannel != 0)
  17089. for (int i = numChannels; i < numDestChannels; ++i)
  17090. if (destSamples[i] != 0)
  17091. memcpy (destSamples[i], lastFullChannel, sizeof (int) * numSamplesToRead);
  17092. }
  17093. else
  17094. {
  17095. for (int i = numChannels; i < numDestChannels; ++i)
  17096. if (destSamples[i] != 0)
  17097. zeromem (destSamples[i], sizeof (int) * numSamplesToRead);
  17098. }
  17099. }
  17100. return true;
  17101. }
  17102. static void findAudioBufferMaxMin (const float* const buffer, const int num, float& maxVal, float& minVal) throw()
  17103. {
  17104. float mn = buffer[0];
  17105. float mx = mn;
  17106. for (int i = 1; i < num; ++i)
  17107. {
  17108. const float s = buffer[i];
  17109. if (s > mx) mx = s;
  17110. if (s < mn) mn = s;
  17111. }
  17112. maxVal = mx;
  17113. minVal = mn;
  17114. }
  17115. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  17116. int64 numSamples,
  17117. float& lowestLeft, float& highestLeft,
  17118. float& lowestRight, float& highestRight)
  17119. {
  17120. if (numSamples <= 0)
  17121. {
  17122. lowestLeft = 0;
  17123. lowestRight = 0;
  17124. highestLeft = 0;
  17125. highestRight = 0;
  17126. return;
  17127. }
  17128. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  17129. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17130. int* tempBuffer[3];
  17131. tempBuffer[0] = tempSpace.getData();
  17132. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17133. tempBuffer[2] = 0;
  17134. if (usesFloatingPointData)
  17135. {
  17136. float lmin = 1.0e6f;
  17137. float lmax = -lmin;
  17138. float rmin = lmin;
  17139. float rmax = lmax;
  17140. while (numSamples > 0)
  17141. {
  17142. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17143. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17144. numSamples -= numToDo;
  17145. startSampleInFile += numToDo;
  17146. float bufmin, bufmax;
  17147. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[0]), numToDo, bufmax, bufmin);
  17148. lmin = jmin (lmin, bufmin);
  17149. lmax = jmax (lmax, bufmax);
  17150. if (numChannels > 1)
  17151. {
  17152. findAudioBufferMaxMin (reinterpret_cast<float*> (tempBuffer[1]), numToDo, bufmax, bufmin);
  17153. rmin = jmin (rmin, bufmin);
  17154. rmax = jmax (rmax, bufmax);
  17155. }
  17156. }
  17157. if (numChannels <= 1)
  17158. {
  17159. rmax = lmax;
  17160. rmin = lmin;
  17161. }
  17162. lowestLeft = lmin;
  17163. highestLeft = lmax;
  17164. lowestRight = rmin;
  17165. highestRight = rmax;
  17166. }
  17167. else
  17168. {
  17169. int lmax = std::numeric_limits<int>::min();
  17170. int lmin = std::numeric_limits<int>::max();
  17171. int rmax = std::numeric_limits<int>::min();
  17172. int rmin = std::numeric_limits<int>::max();
  17173. while (numSamples > 0)
  17174. {
  17175. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  17176. read (tempBuffer, 2, startSampleInFile, numToDo, false);
  17177. numSamples -= numToDo;
  17178. startSampleInFile += numToDo;
  17179. for (int j = numChannels; --j >= 0;)
  17180. {
  17181. int bufMax = std::numeric_limits<int>::min();
  17182. int bufMin = std::numeric_limits<int>::max();
  17183. const int* const b = tempBuffer[j];
  17184. for (int i = 0; i < numToDo; ++i)
  17185. {
  17186. const int samp = b[i];
  17187. if (samp < bufMin)
  17188. bufMin = samp;
  17189. if (samp > bufMax)
  17190. bufMax = samp;
  17191. }
  17192. if (j == 0)
  17193. {
  17194. lmax = jmax (lmax, bufMax);
  17195. lmin = jmin (lmin, bufMin);
  17196. }
  17197. else
  17198. {
  17199. rmax = jmax (rmax, bufMax);
  17200. rmin = jmin (rmin, bufMin);
  17201. }
  17202. }
  17203. }
  17204. if (numChannels <= 1)
  17205. {
  17206. rmax = lmax;
  17207. rmin = lmin;
  17208. }
  17209. lowestLeft = lmin / (float) std::numeric_limits<int>::max();
  17210. highestLeft = lmax / (float) std::numeric_limits<int>::max();
  17211. lowestRight = rmin / (float) std::numeric_limits<int>::max();
  17212. highestRight = rmax / (float) std::numeric_limits<int>::max();
  17213. }
  17214. }
  17215. int64 AudioFormatReader::searchForLevel (int64 startSample,
  17216. int64 numSamplesToSearch,
  17217. const double magnitudeRangeMinimum,
  17218. const double magnitudeRangeMaximum,
  17219. const int minimumConsecutiveSamples)
  17220. {
  17221. if (numSamplesToSearch == 0)
  17222. return -1;
  17223. const int bufferSize = 4096;
  17224. HeapBlock<int> tempSpace (bufferSize * 2 + 64);
  17225. int* tempBuffer[3];
  17226. tempBuffer[0] = tempSpace.getData();
  17227. tempBuffer[1] = tempSpace.getData() + bufferSize;
  17228. tempBuffer[2] = 0;
  17229. int consecutive = 0;
  17230. int64 firstMatchPos = -1;
  17231. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  17232. const double doubleMin = jlimit (0.0, (double) std::numeric_limits<int>::max(), magnitudeRangeMinimum * std::numeric_limits<int>::max());
  17233. const double doubleMax = jlimit (doubleMin, (double) std::numeric_limits<int>::max(), magnitudeRangeMaximum * std::numeric_limits<int>::max());
  17234. const int intMagnitudeRangeMinimum = roundToInt (doubleMin);
  17235. const int intMagnitudeRangeMaximum = roundToInt (doubleMax);
  17236. while (numSamplesToSearch != 0)
  17237. {
  17238. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  17239. int64 bufferStart = startSample;
  17240. if (numSamplesToSearch < 0)
  17241. bufferStart -= numThisTime;
  17242. if (bufferStart >= (int) lengthInSamples)
  17243. break;
  17244. read (tempBuffer, 2, bufferStart, numThisTime, false);
  17245. int num = numThisTime;
  17246. while (--num >= 0)
  17247. {
  17248. if (numSamplesToSearch < 0)
  17249. --startSample;
  17250. bool matches = false;
  17251. const int index = (int) (startSample - bufferStart);
  17252. if (usesFloatingPointData)
  17253. {
  17254. const float sample1 = std::abs (((float*) tempBuffer[0]) [index]);
  17255. if (sample1 >= magnitudeRangeMinimum
  17256. && sample1 <= magnitudeRangeMaximum)
  17257. {
  17258. matches = true;
  17259. }
  17260. else if (numChannels > 1)
  17261. {
  17262. const float sample2 = std::abs (((float*) tempBuffer[1]) [index]);
  17263. matches = (sample2 >= magnitudeRangeMinimum
  17264. && sample2 <= magnitudeRangeMaximum);
  17265. }
  17266. }
  17267. else
  17268. {
  17269. const int sample1 = abs (tempBuffer[0] [index]);
  17270. if (sample1 >= intMagnitudeRangeMinimum
  17271. && sample1 <= intMagnitudeRangeMaximum)
  17272. {
  17273. matches = true;
  17274. }
  17275. else if (numChannels > 1)
  17276. {
  17277. const int sample2 = abs (tempBuffer[1][index]);
  17278. matches = (sample2 >= intMagnitudeRangeMinimum
  17279. && sample2 <= intMagnitudeRangeMaximum);
  17280. }
  17281. }
  17282. if (matches)
  17283. {
  17284. if (firstMatchPos < 0)
  17285. firstMatchPos = startSample;
  17286. if (++consecutive >= minimumConsecutiveSamples)
  17287. {
  17288. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  17289. return -1;
  17290. return firstMatchPos;
  17291. }
  17292. }
  17293. else
  17294. {
  17295. consecutive = 0;
  17296. firstMatchPos = -1;
  17297. }
  17298. if (numSamplesToSearch > 0)
  17299. ++startSample;
  17300. }
  17301. if (numSamplesToSearch > 0)
  17302. numSamplesToSearch -= numThisTime;
  17303. else
  17304. numSamplesToSearch += numThisTime;
  17305. }
  17306. return -1;
  17307. }
  17308. END_JUCE_NAMESPACE
  17309. /*** End of inlined file: juce_AudioFormatReader.cpp ***/
  17310. /*** Start of inlined file: juce_AudioFormatWriter.cpp ***/
  17311. BEGIN_JUCE_NAMESPACE
  17312. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  17313. const String& formatName_,
  17314. const double rate,
  17315. const unsigned int numChannels_,
  17316. const unsigned int bitsPerSample_)
  17317. : sampleRate (rate),
  17318. numChannels (numChannels_),
  17319. bitsPerSample (bitsPerSample_),
  17320. usesFloatingPointData (false),
  17321. output (out),
  17322. formatName (formatName_)
  17323. {
  17324. }
  17325. AudioFormatWriter::~AudioFormatWriter()
  17326. {
  17327. delete output;
  17328. }
  17329. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  17330. int64 startSample,
  17331. int64 numSamplesToRead)
  17332. {
  17333. const int bufferSize = 16384;
  17334. AudioSampleBuffer tempBuffer (numChannels, bufferSize);
  17335. int* buffers [128];
  17336. zerostruct (buffers);
  17337. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  17338. buffers[i] = reinterpret_cast<int*> (tempBuffer.getSampleData (i, 0));
  17339. if (numSamplesToRead < 0)
  17340. numSamplesToRead = reader.lengthInSamples;
  17341. while (numSamplesToRead > 0)
  17342. {
  17343. const int numToDo = (int) jmin (numSamplesToRead, (int64) bufferSize);
  17344. if (! reader.read (buffers, numChannels, startSample, numToDo, false))
  17345. return false;
  17346. if (reader.usesFloatingPointData != isFloatingPoint())
  17347. {
  17348. int** bufferChan = buffers;
  17349. while (*bufferChan != 0)
  17350. {
  17351. int* b = *bufferChan++;
  17352. if (isFloatingPoint())
  17353. {
  17354. // int -> float
  17355. const double factor = 1.0 / std::numeric_limits<int>::max();
  17356. for (int i = 0; i < numToDo; ++i)
  17357. ((float*) b)[i] = (float) (factor * b[i]);
  17358. }
  17359. else
  17360. {
  17361. // float -> int
  17362. for (int i = 0; i < numToDo; ++i)
  17363. {
  17364. const double samp = *(const float*) b;
  17365. if (samp <= -1.0)
  17366. *b++ = std::numeric_limits<int>::min();
  17367. else if (samp >= 1.0)
  17368. *b++ = std::numeric_limits<int>::max();
  17369. else
  17370. *b++ = roundToInt (std::numeric_limits<int>::max() * samp);
  17371. }
  17372. }
  17373. }
  17374. }
  17375. if (! write (const_cast<const int**> (buffers), numToDo))
  17376. return false;
  17377. numSamplesToRead -= numToDo;
  17378. startSample += numToDo;
  17379. }
  17380. return true;
  17381. }
  17382. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source, int numSamplesToRead, const int samplesPerBlock)
  17383. {
  17384. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  17385. while (numSamplesToRead > 0)
  17386. {
  17387. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  17388. AudioSourceChannelInfo info;
  17389. info.buffer = &tempBuffer;
  17390. info.startSample = 0;
  17391. info.numSamples = numToDo;
  17392. info.clearActiveBufferRegion();
  17393. source.getNextAudioBlock (info);
  17394. if (! writeFromAudioSampleBuffer (tempBuffer, 0, numToDo))
  17395. return false;
  17396. numSamplesToRead -= numToDo;
  17397. }
  17398. return true;
  17399. }
  17400. bool AudioFormatWriter::writeFromAudioSampleBuffer (const AudioSampleBuffer& source, int startSample, int numSamples)
  17401. {
  17402. jassert (startSample >= 0 && startSample + numSamples <= source.getNumSamples() && source.getNumChannels() > 0);
  17403. if (numSamples <= 0)
  17404. return true;
  17405. HeapBlock<int> tempBuffer;
  17406. HeapBlock<int*> chans (numChannels + 1);
  17407. chans [numChannels] = 0;
  17408. if (isFloatingPoint())
  17409. {
  17410. for (int i = numChannels; --i >= 0;)
  17411. chans[i] = reinterpret_cast<int*> (source.getSampleData (i, startSample));
  17412. }
  17413. else
  17414. {
  17415. tempBuffer.malloc (numSamples * numChannels);
  17416. for (unsigned int i = 0; i < numChannels; ++i)
  17417. {
  17418. typedef AudioData::Pointer <AudioData::Int32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestSampleType;
  17419. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceSampleType;
  17420. DestSampleType destData (chans[i] = tempBuffer + i * numSamples);
  17421. SourceSampleType sourceData (source.getSampleData (i, startSample));
  17422. destData.convertSamples (sourceData, numSamples);
  17423. }
  17424. }
  17425. return write ((const int**) chans.getData(), numSamples);
  17426. }
  17427. class AudioFormatWriter::ThreadedWriter::Buffer : public TimeSliceClient,
  17428. public AbstractFifo
  17429. {
  17430. public:
  17431. Buffer (TimeSliceThread& timeSliceThread_, AudioFormatWriter* writer_, int numChannels, int bufferSize)
  17432. : AbstractFifo (bufferSize),
  17433. buffer (numChannels, bufferSize),
  17434. timeSliceThread (timeSliceThread_),
  17435. writer (writer_), isRunning (true)
  17436. {
  17437. timeSliceThread.addTimeSliceClient (this);
  17438. }
  17439. ~Buffer()
  17440. {
  17441. isRunning = false;
  17442. timeSliceThread.removeTimeSliceClient (this);
  17443. while (useTimeSlice())
  17444. {}
  17445. }
  17446. bool write (const float** data, int numSamples)
  17447. {
  17448. if (numSamples <= 0 || ! isRunning)
  17449. return true;
  17450. jassert (timeSliceThread.isThreadRunning()); // you need to get your thread running before pumping data into this!
  17451. int start1, size1, start2, size2;
  17452. prepareToWrite (numSamples, start1, size1, start2, size2);
  17453. if (size1 + size2 < numSamples)
  17454. return false;
  17455. for (int i = buffer.getNumChannels(); --i >= 0;)
  17456. {
  17457. buffer.copyFrom (i, start1, data[i], size1);
  17458. buffer.copyFrom (i, start2, data[i] + size1, size2);
  17459. }
  17460. finishedWrite (size1 + size2);
  17461. timeSliceThread.notify();
  17462. return true;
  17463. }
  17464. bool useTimeSlice()
  17465. {
  17466. const int numToDo = getTotalSize() / 4;
  17467. int start1, size1, start2, size2;
  17468. prepareToRead (numToDo, start1, size1, start2, size2);
  17469. if (size1 <= 0)
  17470. return false;
  17471. writer->writeFromAudioSampleBuffer (buffer, start1, size1);
  17472. if (size2 > 0)
  17473. writer->writeFromAudioSampleBuffer (buffer, start2, size2);
  17474. finishedRead (size1 + size2);
  17475. return true;
  17476. }
  17477. private:
  17478. AudioSampleBuffer buffer;
  17479. TimeSliceThread& timeSliceThread;
  17480. ScopedPointer<AudioFormatWriter> writer;
  17481. volatile bool isRunning;
  17482. Buffer (const Buffer&);
  17483. Buffer& operator= (const Buffer&);
  17484. };
  17485. AudioFormatWriter::ThreadedWriter::ThreadedWriter (AudioFormatWriter* writer, TimeSliceThread& backgroundThread, int numSamplesToBuffer)
  17486. : buffer (new AudioFormatWriter::ThreadedWriter::Buffer (backgroundThread, writer, writer->numChannels, numSamplesToBuffer))
  17487. {
  17488. }
  17489. AudioFormatWriter::ThreadedWriter::~ThreadedWriter()
  17490. {
  17491. }
  17492. bool AudioFormatWriter::ThreadedWriter::write (const float** data, int numSamples)
  17493. {
  17494. return buffer->write (data, numSamples);
  17495. }
  17496. END_JUCE_NAMESPACE
  17497. /*** End of inlined file: juce_AudioFormatWriter.cpp ***/
  17498. /*** Start of inlined file: juce_AudioFormatManager.cpp ***/
  17499. BEGIN_JUCE_NAMESPACE
  17500. AudioFormatManager::AudioFormatManager()
  17501. : defaultFormatIndex (0)
  17502. {
  17503. }
  17504. AudioFormatManager::~AudioFormatManager()
  17505. {
  17506. clearFormats();
  17507. clearSingletonInstance();
  17508. }
  17509. juce_ImplementSingleton (AudioFormatManager);
  17510. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  17511. const bool makeThisTheDefaultFormat)
  17512. {
  17513. jassert (newFormat != 0);
  17514. if (newFormat != 0)
  17515. {
  17516. #if JUCE_DEBUG
  17517. for (int i = getNumKnownFormats(); --i >= 0;)
  17518. {
  17519. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  17520. {
  17521. jassertfalse; // trying to add the same format twice!
  17522. }
  17523. }
  17524. #endif
  17525. if (makeThisTheDefaultFormat)
  17526. defaultFormatIndex = getNumKnownFormats();
  17527. knownFormats.add (newFormat);
  17528. }
  17529. }
  17530. void AudioFormatManager::registerBasicFormats()
  17531. {
  17532. #if JUCE_MAC
  17533. registerFormat (new AiffAudioFormat(), true);
  17534. registerFormat (new WavAudioFormat(), false);
  17535. #else
  17536. registerFormat (new WavAudioFormat(), true);
  17537. registerFormat (new AiffAudioFormat(), false);
  17538. #endif
  17539. #if JUCE_USE_FLAC
  17540. registerFormat (new FlacAudioFormat(), false);
  17541. #endif
  17542. #if JUCE_USE_OGGVORBIS
  17543. registerFormat (new OggVorbisAudioFormat(), false);
  17544. #endif
  17545. }
  17546. void AudioFormatManager::clearFormats()
  17547. {
  17548. knownFormats.clear();
  17549. defaultFormatIndex = 0;
  17550. }
  17551. int AudioFormatManager::getNumKnownFormats() const
  17552. {
  17553. return knownFormats.size();
  17554. }
  17555. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  17556. {
  17557. return knownFormats [index];
  17558. }
  17559. AudioFormat* AudioFormatManager::getDefaultFormat() const
  17560. {
  17561. return getKnownFormat (defaultFormatIndex);
  17562. }
  17563. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  17564. {
  17565. String e (fileExtension);
  17566. if (! e.startsWithChar ('.'))
  17567. e = "." + e;
  17568. for (int i = 0; i < getNumKnownFormats(); ++i)
  17569. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  17570. return getKnownFormat(i);
  17571. return 0;
  17572. }
  17573. const String AudioFormatManager::getWildcardForAllFormats() const
  17574. {
  17575. StringArray allExtensions;
  17576. int i;
  17577. for (i = 0; i < getNumKnownFormats(); ++i)
  17578. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  17579. allExtensions.trim();
  17580. allExtensions.removeEmptyStrings();
  17581. String s;
  17582. for (i = 0; i < allExtensions.size(); ++i)
  17583. {
  17584. s << '*';
  17585. if (! allExtensions[i].startsWithChar ('.'))
  17586. s << '.';
  17587. s << allExtensions[i];
  17588. if (i < allExtensions.size() - 1)
  17589. s << ';';
  17590. }
  17591. return s;
  17592. }
  17593. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  17594. {
  17595. // you need to actually register some formats before the manager can
  17596. // use them to open a file!
  17597. jassert (getNumKnownFormats() > 0);
  17598. for (int i = 0; i < getNumKnownFormats(); ++i)
  17599. {
  17600. AudioFormat* const af = getKnownFormat(i);
  17601. if (af->canHandleFile (file))
  17602. {
  17603. InputStream* const in = file.createInputStream();
  17604. if (in != 0)
  17605. {
  17606. AudioFormatReader* const r = af->createReaderFor (in, true);
  17607. if (r != 0)
  17608. return r;
  17609. }
  17610. }
  17611. }
  17612. return 0;
  17613. }
  17614. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* audioFileStream)
  17615. {
  17616. // you need to actually register some formats before the manager can
  17617. // use them to open a file!
  17618. jassert (getNumKnownFormats() > 0);
  17619. ScopedPointer <InputStream> in (audioFileStream);
  17620. if (in != 0)
  17621. {
  17622. const int64 originalStreamPos = in->getPosition();
  17623. for (int i = 0; i < getNumKnownFormats(); ++i)
  17624. {
  17625. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  17626. if (r != 0)
  17627. {
  17628. in.release();
  17629. return r;
  17630. }
  17631. in->setPosition (originalStreamPos);
  17632. // the stream that is passed-in must be capable of being repositioned so
  17633. // that all the formats can have a go at opening it.
  17634. jassert (in->getPosition() == originalStreamPos);
  17635. }
  17636. }
  17637. return 0;
  17638. }
  17639. END_JUCE_NAMESPACE
  17640. /*** End of inlined file: juce_AudioFormatManager.cpp ***/
  17641. /*** Start of inlined file: juce_AudioSubsectionReader.cpp ***/
  17642. BEGIN_JUCE_NAMESPACE
  17643. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  17644. const int64 startSample_,
  17645. const int64 length_,
  17646. const bool deleteSourceWhenDeleted_)
  17647. : AudioFormatReader (0, source_->getFormatName()),
  17648. source (source_),
  17649. startSample (startSample_),
  17650. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  17651. {
  17652. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  17653. sampleRate = source->sampleRate;
  17654. bitsPerSample = source->bitsPerSample;
  17655. lengthInSamples = length;
  17656. numChannels = source->numChannels;
  17657. usesFloatingPointData = source->usesFloatingPointData;
  17658. }
  17659. AudioSubsectionReader::~AudioSubsectionReader()
  17660. {
  17661. if (deleteSourceWhenDeleted)
  17662. delete source;
  17663. }
  17664. bool AudioSubsectionReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  17665. int64 startSampleInFile, int numSamples)
  17666. {
  17667. if (startSampleInFile + numSamples > length)
  17668. {
  17669. for (int i = numDestChannels; --i >= 0;)
  17670. if (destSamples[i] != 0)
  17671. zeromem (destSamples[i], sizeof (int) * numSamples);
  17672. numSamples = jmin (numSamples, (int) (length - startSampleInFile));
  17673. if (numSamples <= 0)
  17674. return true;
  17675. }
  17676. return source->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer,
  17677. startSampleInFile + startSample, numSamples);
  17678. }
  17679. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  17680. int64 numSamples,
  17681. float& lowestLeft,
  17682. float& highestLeft,
  17683. float& lowestRight,
  17684. float& highestRight)
  17685. {
  17686. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  17687. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  17688. source->readMaxLevels (startSampleInFile + startSample,
  17689. numSamples,
  17690. lowestLeft,
  17691. highestLeft,
  17692. lowestRight,
  17693. highestRight);
  17694. }
  17695. END_JUCE_NAMESPACE
  17696. /*** End of inlined file: juce_AudioSubsectionReader.cpp ***/
  17697. /*** Start of inlined file: juce_AudioThumbnail.cpp ***/
  17698. BEGIN_JUCE_NAMESPACE
  17699. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  17700. AudioFormatManager& formatManagerToUse_,
  17701. AudioThumbnailCache& cacheToUse)
  17702. : formatManagerToUse (formatManagerToUse_),
  17703. cache (cacheToUse),
  17704. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_),
  17705. timeBeforeDeletingReader (2000)
  17706. {
  17707. clear();
  17708. }
  17709. AudioThumbnail::~AudioThumbnail()
  17710. {
  17711. cache.removeThumbnail (this);
  17712. const ScopedLock sl (readerLock);
  17713. reader = 0;
  17714. }
  17715. AudioThumbnail::DataFormat* AudioThumbnail::getData() const throw()
  17716. {
  17717. jassert (data.getData() != 0);
  17718. return static_cast <DataFormat*> (data.getData());
  17719. }
  17720. void AudioThumbnail::setSource (InputSource* const newSource)
  17721. {
  17722. cache.removeThumbnail (this);
  17723. timerCallback(); // stops the timer and deletes the reader
  17724. source = newSource;
  17725. clear();
  17726. if (newSource != 0
  17727. && ! (cache.loadThumb (*this, newSource->hashCode())
  17728. && isFullyLoaded()))
  17729. {
  17730. {
  17731. const ScopedLock sl (readerLock);
  17732. reader = createReader();
  17733. }
  17734. if (reader != 0)
  17735. {
  17736. initialiseFromAudioFile (*reader);
  17737. cache.addThumbnail (this);
  17738. }
  17739. }
  17740. sendChangeMessage (this);
  17741. }
  17742. bool AudioThumbnail::useTimeSlice()
  17743. {
  17744. const ScopedLock sl (readerLock);
  17745. if (isFullyLoaded())
  17746. {
  17747. if (reader != 0)
  17748. startTimer (timeBeforeDeletingReader);
  17749. cache.removeThumbnail (this);
  17750. return false;
  17751. }
  17752. if (reader == 0)
  17753. reader = createReader();
  17754. if (reader != 0)
  17755. {
  17756. readNextBlockFromAudioFile (*reader);
  17757. stopTimer();
  17758. sendChangeMessage (this);
  17759. const bool justFinished = isFullyLoaded();
  17760. if (justFinished)
  17761. cache.storeThumb (*this, source->hashCode());
  17762. return ! justFinished;
  17763. }
  17764. return false;
  17765. }
  17766. AudioFormatReader* AudioThumbnail::createReader() const
  17767. {
  17768. if (source != 0)
  17769. {
  17770. InputStream* const audioFileStream = source->createInputStream();
  17771. if (audioFileStream != 0)
  17772. return formatManagerToUse.createReaderFor (audioFileStream);
  17773. }
  17774. return 0;
  17775. }
  17776. void AudioThumbnail::timerCallback()
  17777. {
  17778. stopTimer();
  17779. const ScopedLock sl (readerLock);
  17780. reader = 0;
  17781. }
  17782. void AudioThumbnail::clear()
  17783. {
  17784. data.setSize (sizeof (DataFormat) + 3);
  17785. DataFormat* const d = getData();
  17786. d->thumbnailMagic[0] = 'j';
  17787. d->thumbnailMagic[1] = 'a';
  17788. d->thumbnailMagic[2] = 't';
  17789. d->thumbnailMagic[3] = 'm';
  17790. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  17791. d->totalSamples = 0;
  17792. d->numFinishedSamples = 0;
  17793. d->numThumbnailSamples = 0;
  17794. d->numChannels = 0;
  17795. d->sampleRate = 0;
  17796. numSamplesCached = 0;
  17797. cacheNeedsRefilling = true;
  17798. }
  17799. void AudioThumbnail::loadFrom (InputStream& input)
  17800. {
  17801. const ScopedLock sl (readerLock);
  17802. data.setSize (0);
  17803. input.readIntoMemoryBlock (data);
  17804. DataFormat* const d = getData();
  17805. d->flipEndiannessIfBigEndian();
  17806. if (! (d->thumbnailMagic[0] == 'j'
  17807. && d->thumbnailMagic[1] == 'a'
  17808. && d->thumbnailMagic[2] == 't'
  17809. && d->thumbnailMagic[3] == 'm'))
  17810. {
  17811. clear();
  17812. }
  17813. numSamplesCached = 0;
  17814. cacheNeedsRefilling = true;
  17815. }
  17816. void AudioThumbnail::saveTo (OutputStream& output) const
  17817. {
  17818. const ScopedLock sl (readerLock);
  17819. DataFormat* const d = getData();
  17820. d->flipEndiannessIfBigEndian();
  17821. output.write (d, (int) data.getSize());
  17822. d->flipEndiannessIfBigEndian();
  17823. }
  17824. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& fileReader)
  17825. {
  17826. DataFormat* d = getData();
  17827. d->totalSamples = fileReader.lengthInSamples;
  17828. d->numChannels = jmin ((uint32) 2, fileReader.numChannels);
  17829. d->numFinishedSamples = 0;
  17830. d->sampleRate = roundToInt (fileReader.sampleRate);
  17831. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  17832. data.setSize (sizeof (DataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  17833. d = getData();
  17834. zeromem (d->data, d->numThumbnailSamples * d->numChannels * 2);
  17835. return d->totalSamples > 0;
  17836. }
  17837. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& fileReader)
  17838. {
  17839. DataFormat* const d = getData();
  17840. if (d->numFinishedSamples < d->totalSamples)
  17841. {
  17842. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  17843. generateSection (fileReader,
  17844. d->numFinishedSamples,
  17845. numToDo);
  17846. d->numFinishedSamples += numToDo;
  17847. }
  17848. cacheNeedsRefilling = true;
  17849. return d->numFinishedSamples < d->totalSamples;
  17850. }
  17851. int AudioThumbnail::getNumChannels() const throw()
  17852. {
  17853. return getData()->numChannels;
  17854. }
  17855. double AudioThumbnail::getTotalLength() const throw()
  17856. {
  17857. const DataFormat* const d = getData();
  17858. if (d->sampleRate > 0)
  17859. return d->totalSamples / (double) d->sampleRate;
  17860. else
  17861. return 0.0;
  17862. }
  17863. void AudioThumbnail::generateSection (AudioFormatReader& fileReader,
  17864. int64 startSample,
  17865. int numSamples)
  17866. {
  17867. DataFormat* const d = getData();
  17868. const int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  17869. const int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  17870. char* const l = getChannelData (0);
  17871. char* const r = getChannelData (1);
  17872. for (int i = firstDataPos; i < lastDataPos; ++i)
  17873. {
  17874. const int sourceStart = i * d->samplesPerThumbSample;
  17875. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  17876. float lowestLeft, highestLeft, lowestRight, highestRight;
  17877. fileReader.readMaxLevels (sourceStart,
  17878. sourceEnd - sourceStart,
  17879. lowestLeft,
  17880. highestLeft,
  17881. lowestRight,
  17882. highestRight);
  17883. int n = i * 2;
  17884. if (r != 0)
  17885. {
  17886. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17887. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  17888. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17889. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  17890. }
  17891. else
  17892. {
  17893. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  17894. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  17895. }
  17896. }
  17897. }
  17898. char* AudioThumbnail::getChannelData (int channel) const
  17899. {
  17900. DataFormat* const d = getData();
  17901. if (channel >= 0 && channel < d->numChannels)
  17902. return d->data + (channel * 2 * d->numThumbnailSamples);
  17903. return 0;
  17904. }
  17905. bool AudioThumbnail::isFullyLoaded() const throw()
  17906. {
  17907. const DataFormat* const d = getData();
  17908. return d->numFinishedSamples >= d->totalSamples;
  17909. }
  17910. void AudioThumbnail::refillCache (const int numSamples,
  17911. double startTime,
  17912. const double timePerPixel)
  17913. {
  17914. const DataFormat* const d = getData();
  17915. if (numSamples <= 0
  17916. || timePerPixel <= 0.0
  17917. || d->sampleRate <= 0)
  17918. {
  17919. numSamplesCached = 0;
  17920. cacheNeedsRefilling = true;
  17921. return;
  17922. }
  17923. if (numSamples == numSamplesCached
  17924. && numChannelsCached == d->numChannels
  17925. && startTime == cachedStart
  17926. && timePerPixel == cachedTimePerPixel
  17927. && ! cacheNeedsRefilling)
  17928. {
  17929. return;
  17930. }
  17931. numSamplesCached = numSamples;
  17932. numChannelsCached = d->numChannels;
  17933. cachedStart = startTime;
  17934. cachedTimePerPixel = timePerPixel;
  17935. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  17936. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  17937. const ScopedLock sl (readerLock);
  17938. cacheNeedsRefilling = false;
  17939. if (needExtraDetail && reader == 0)
  17940. reader = createReader();
  17941. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  17942. {
  17943. startTimer (timeBeforeDeletingReader);
  17944. char* cacheData = static_cast <char*> (cachedLevels.getData());
  17945. int sample = roundToInt (startTime * d->sampleRate);
  17946. for (int i = numSamples; --i >= 0;)
  17947. {
  17948. const int nextSample = roundToInt ((startTime + timePerPixel) * d->sampleRate);
  17949. if (sample >= 0)
  17950. {
  17951. if (sample >= reader->lengthInSamples)
  17952. break;
  17953. float lmin, lmax, rmin, rmax;
  17954. reader->readMaxLevels (sample,
  17955. jmax (1, nextSample - sample),
  17956. lmin, lmax, rmin, rmax);
  17957. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  17958. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  17959. if (numChannelsCached > 1)
  17960. {
  17961. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  17962. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  17963. }
  17964. cacheData += 2 * numChannelsCached;
  17965. }
  17966. startTime += timePerPixel;
  17967. sample = nextSample;
  17968. }
  17969. }
  17970. else
  17971. {
  17972. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  17973. {
  17974. char* const channelData = getChannelData (channelNum);
  17975. char* cacheData = static_cast <char*> (cachedLevels.getData()) + channelNum * 2;
  17976. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  17977. startTime = cachedStart;
  17978. int sample = roundToInt (startTime * timeToThumbSampleFactor);
  17979. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  17980. for (int i = numSamples; --i >= 0;)
  17981. {
  17982. const int nextSample = roundToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  17983. if (sample >= 0 && channelData != 0)
  17984. {
  17985. char mx = -128;
  17986. char mn = 127;
  17987. while (sample <= nextSample)
  17988. {
  17989. if (sample >= numFinished)
  17990. break;
  17991. const int n = sample << 1;
  17992. const char sampMin = channelData [n];
  17993. const char sampMax = channelData [n + 1];
  17994. if (sampMin < mn)
  17995. mn = sampMin;
  17996. if (sampMax > mx)
  17997. mx = sampMax;
  17998. ++sample;
  17999. }
  18000. if (mn <= mx)
  18001. {
  18002. cacheData[0] = mn;
  18003. cacheData[1] = mx;
  18004. }
  18005. else
  18006. {
  18007. cacheData[0] = 1;
  18008. cacheData[1] = 0;
  18009. }
  18010. }
  18011. else
  18012. {
  18013. cacheData[0] = 1;
  18014. cacheData[1] = 0;
  18015. }
  18016. cacheData += numChannelsCached * 2;
  18017. startTime += timePerPixel;
  18018. sample = nextSample;
  18019. }
  18020. }
  18021. }
  18022. }
  18023. void AudioThumbnail::drawChannel (Graphics& g,
  18024. int x, int y, int w, int h,
  18025. double startTime,
  18026. double endTime,
  18027. int channelNum,
  18028. const float verticalZoomFactor)
  18029. {
  18030. refillCache (w, startTime, (endTime - startTime) / w);
  18031. if (numSamplesCached >= w
  18032. && channelNum >= 0
  18033. && channelNum < numChannelsCached)
  18034. {
  18035. const float topY = (float) y;
  18036. const float bottomY = topY + h;
  18037. const float midY = topY + h * 0.5f;
  18038. const float vscale = verticalZoomFactor * h / 256.0f;
  18039. const Rectangle<int> clip (g.getClipBounds());
  18040. const int skipLeft = jlimit (0, w, clip.getX() - x);
  18041. w -= skipLeft;
  18042. x += skipLeft;
  18043. const char* cacheData = static_cast <const char*> (cachedLevels.getData())
  18044. + (channelNum << 1)
  18045. + skipLeft * (numChannelsCached << 1);
  18046. while (--w >= 0)
  18047. {
  18048. const char mn = cacheData[0];
  18049. const char mx = cacheData[1];
  18050. cacheData += numChannelsCached << 1;
  18051. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  18052. g.drawVerticalLine (x, jmax (midY - mx * vscale - 0.3f, topY),
  18053. jmin (midY - mn * vscale + 0.3f, bottomY));
  18054. if (++x >= clip.getRight())
  18055. break;
  18056. }
  18057. }
  18058. }
  18059. void AudioThumbnail::DataFormat::flipEndiannessIfBigEndian() throw()
  18060. {
  18061. #if JUCE_BIG_ENDIAN
  18062. struct Flipper
  18063. {
  18064. static void flip (int32& n) { n = (int32) ByteOrder::swap ((uint32) n); }
  18065. static void flip (int64& n) { n = (int64) ByteOrder::swap ((uint64) n); }
  18066. };
  18067. Flipper::flip (samplesPerThumbSample);
  18068. Flipper::flip (totalSamples);
  18069. Flipper::flip (numFinishedSamples);
  18070. Flipper::flip (numThumbnailSamples);
  18071. Flipper::flip (numChannels);
  18072. Flipper::flip (sampleRate);
  18073. #endif
  18074. }
  18075. END_JUCE_NAMESPACE
  18076. /*** End of inlined file: juce_AudioThumbnail.cpp ***/
  18077. /*** Start of inlined file: juce_AudioThumbnailCache.cpp ***/
  18078. BEGIN_JUCE_NAMESPACE
  18079. struct ThumbnailCacheEntry
  18080. {
  18081. int64 hash;
  18082. uint32 lastUsed;
  18083. MemoryBlock data;
  18084. juce_UseDebuggingNewOperator
  18085. };
  18086. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  18087. : TimeSliceThread ("thumb cache"),
  18088. maxNumThumbsToStore (maxNumThumbsToStore_)
  18089. {
  18090. startThread (2);
  18091. }
  18092. AudioThumbnailCache::~AudioThumbnailCache()
  18093. {
  18094. }
  18095. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  18096. {
  18097. for (int i = thumbs.size(); --i >= 0;)
  18098. {
  18099. if (thumbs[i]->hash == hashCode)
  18100. {
  18101. MemoryInputStream in (thumbs[i]->data, false);
  18102. thumb.loadFrom (in);
  18103. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  18104. return true;
  18105. }
  18106. }
  18107. return false;
  18108. }
  18109. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  18110. const int64 hashCode)
  18111. {
  18112. MemoryOutputStream out;
  18113. thumb.saveTo (out);
  18114. ThumbnailCacheEntry* te = 0;
  18115. for (int i = thumbs.size(); --i >= 0;)
  18116. {
  18117. if (thumbs[i]->hash == hashCode)
  18118. {
  18119. te = thumbs[i];
  18120. break;
  18121. }
  18122. }
  18123. if (te == 0)
  18124. {
  18125. te = new ThumbnailCacheEntry();
  18126. te->hash = hashCode;
  18127. if (thumbs.size() < maxNumThumbsToStore)
  18128. {
  18129. thumbs.add (te);
  18130. }
  18131. else
  18132. {
  18133. int oldest = 0;
  18134. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  18135. int i;
  18136. for (i = thumbs.size(); --i >= 0;)
  18137. if (thumbs[i]->lastUsed < oldestTime)
  18138. oldest = i;
  18139. thumbs.set (i, te);
  18140. }
  18141. }
  18142. te->lastUsed = Time::getMillisecondCounter();
  18143. te->data.setSize (0);
  18144. te->data.append (out.getData(), out.getDataSize());
  18145. }
  18146. void AudioThumbnailCache::clear()
  18147. {
  18148. thumbs.clear();
  18149. }
  18150. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  18151. {
  18152. addTimeSliceClient (thumb);
  18153. }
  18154. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  18155. {
  18156. removeTimeSliceClient (thumb);
  18157. }
  18158. END_JUCE_NAMESPACE
  18159. /*** End of inlined file: juce_AudioThumbnailCache.cpp ***/
  18160. /*** Start of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18161. #if JUCE_QUICKTIME && ! (JUCE_64BIT || JUCE_IOS)
  18162. #if ! JUCE_WINDOWS
  18163. #include <QuickTime/Movies.h>
  18164. #include <QuickTime/QTML.h>
  18165. #include <QuickTime/QuickTimeComponents.h>
  18166. #include <QuickTime/MediaHandlers.h>
  18167. #include <QuickTime/ImageCodec.h>
  18168. #else
  18169. #if JUCE_MSVC
  18170. #pragma warning (push)
  18171. #pragma warning (disable : 4100)
  18172. #endif
  18173. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  18174. add its header directory to your include path.
  18175. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  18176. flag in juce_Config.h
  18177. */
  18178. #include <Movies.h>
  18179. #include <QTML.h>
  18180. #include <QuickTimeComponents.h>
  18181. #include <MediaHandlers.h>
  18182. #include <ImageCodec.h>
  18183. #if JUCE_MSVC
  18184. #pragma warning (pop)
  18185. #endif
  18186. #endif
  18187. BEGIN_JUCE_NAMESPACE
  18188. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  18189. static const char* const quickTimeFormatName = "QuickTime file";
  18190. static const char* const quickTimeExtensions[] = { ".mov", ".mp3", ".mp4", ".m4a", 0 };
  18191. class QTAudioReader : public AudioFormatReader
  18192. {
  18193. public:
  18194. QTAudioReader (InputStream* const input_, const int trackNum_)
  18195. : AudioFormatReader (input_, TRANS (quickTimeFormatName)),
  18196. ok (false),
  18197. movie (0),
  18198. trackNum (trackNum_),
  18199. lastSampleRead (0),
  18200. lastThreadId (0),
  18201. extractor (0),
  18202. dataHandle (0)
  18203. {
  18204. JUCE_AUTORELEASEPOOL
  18205. bufferList.calloc (256, 1);
  18206. #if JUCE_WINDOWS
  18207. if (InitializeQTML (0) != noErr)
  18208. return;
  18209. #endif
  18210. if (EnterMovies() != noErr)
  18211. return;
  18212. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  18213. if (! opened)
  18214. return;
  18215. {
  18216. const int numTracks = GetMovieTrackCount (movie);
  18217. int trackCount = 0;
  18218. for (int i = 1; i <= numTracks; ++i)
  18219. {
  18220. track = GetMovieIndTrack (movie, i);
  18221. media = GetTrackMedia (track);
  18222. OSType mediaType;
  18223. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  18224. if (mediaType == SoundMediaType
  18225. && trackCount++ == trackNum_)
  18226. {
  18227. ok = true;
  18228. break;
  18229. }
  18230. }
  18231. }
  18232. if (! ok)
  18233. return;
  18234. ok = false;
  18235. lengthInSamples = GetMediaDecodeDuration (media);
  18236. usesFloatingPointData = false;
  18237. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  18238. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  18239. / GetMediaTimeScale (media);
  18240. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  18241. unsigned long output_layout_size;
  18242. err = MovieAudioExtractionGetPropertyInfo (extractor,
  18243. kQTPropertyClass_MovieAudioExtraction_Audio,
  18244. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18245. 0, &output_layout_size, 0);
  18246. if (err != noErr)
  18247. return;
  18248. HeapBlock <AudioChannelLayout> qt_audio_channel_layout;
  18249. qt_audio_channel_layout.calloc (output_layout_size, 1);
  18250. err = MovieAudioExtractionGetProperty (extractor,
  18251. kQTPropertyClass_MovieAudioExtraction_Audio,
  18252. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18253. output_layout_size, qt_audio_channel_layout, 0);
  18254. qt_audio_channel_layout[0].mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  18255. err = MovieAudioExtractionSetProperty (extractor,
  18256. kQTPropertyClass_MovieAudioExtraction_Audio,
  18257. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  18258. output_layout_size,
  18259. qt_audio_channel_layout);
  18260. err = MovieAudioExtractionGetProperty (extractor,
  18261. kQTPropertyClass_MovieAudioExtraction_Audio,
  18262. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18263. sizeof (inputStreamDesc),
  18264. &inputStreamDesc, 0);
  18265. if (err != noErr)
  18266. return;
  18267. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  18268. | kAudioFormatFlagIsPacked
  18269. | kAudioFormatFlagsNativeEndian;
  18270. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  18271. inputStreamDesc.mChannelsPerFrame = jmin ((UInt32) 2, inputStreamDesc.mChannelsPerFrame);
  18272. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  18273. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  18274. err = MovieAudioExtractionSetProperty (extractor,
  18275. kQTPropertyClass_MovieAudioExtraction_Audio,
  18276. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  18277. sizeof (inputStreamDesc),
  18278. &inputStreamDesc);
  18279. if (err != noErr)
  18280. return;
  18281. Boolean allChannelsDiscrete = false;
  18282. err = MovieAudioExtractionSetProperty (extractor,
  18283. kQTPropertyClass_MovieAudioExtraction_Movie,
  18284. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  18285. sizeof (allChannelsDiscrete),
  18286. &allChannelsDiscrete);
  18287. if (err != noErr)
  18288. return;
  18289. bufferList->mNumberBuffers = 1;
  18290. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  18291. bufferList->mBuffers[0].mDataByteSize = jmax ((UInt32) 4096, (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16);
  18292. dataBuffer.malloc (bufferList->mBuffers[0].mDataByteSize);
  18293. bufferList->mBuffers[0].mData = dataBuffer;
  18294. sampleRate = inputStreamDesc.mSampleRate;
  18295. bitsPerSample = 16;
  18296. numChannels = inputStreamDesc.mChannelsPerFrame;
  18297. detachThread();
  18298. ok = true;
  18299. }
  18300. ~QTAudioReader()
  18301. {
  18302. JUCE_AUTORELEASEPOOL
  18303. checkThreadIsAttached();
  18304. if (dataHandle != 0)
  18305. DisposeHandle (dataHandle);
  18306. if (extractor != 0)
  18307. {
  18308. MovieAudioExtractionEnd (extractor);
  18309. extractor = 0;
  18310. }
  18311. DisposeMovie (movie);
  18312. #if JUCE_MAC
  18313. ExitMoviesOnThread ();
  18314. #endif
  18315. }
  18316. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18317. int64 startSampleInFile, int numSamples)
  18318. {
  18319. JUCE_AUTORELEASEPOOL
  18320. checkThreadIsAttached();
  18321. bool ok = true;
  18322. while (numSamples > 0)
  18323. {
  18324. if (lastSampleRead != startSampleInFile)
  18325. {
  18326. TimeRecord time;
  18327. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  18328. time.base = 0;
  18329. time.value.hi = 0;
  18330. time.value.lo = (UInt32) startSampleInFile;
  18331. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  18332. kQTPropertyClass_MovieAudioExtraction_Movie,
  18333. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  18334. sizeof (time), &time);
  18335. if (err != noErr)
  18336. {
  18337. ok = false;
  18338. break;
  18339. }
  18340. }
  18341. int framesToDo = jmin (numSamples, (int) (bufferList->mBuffers[0].mDataByteSize / inputStreamDesc.mBytesPerFrame));
  18342. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * framesToDo;
  18343. UInt32 outFlags = 0;
  18344. UInt32 actualNumFrames = framesToDo;
  18345. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumFrames, bufferList, &outFlags);
  18346. if (err != noErr)
  18347. {
  18348. ok = false;
  18349. break;
  18350. }
  18351. lastSampleRead = startSampleInFile + actualNumFrames;
  18352. const int samplesReceived = actualNumFrames;
  18353. for (int j = numDestChannels; --j >= 0;)
  18354. {
  18355. if (destSamples[j] != 0)
  18356. {
  18357. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  18358. for (int i = 0; i < samplesReceived; ++i)
  18359. destSamples[j][startOffsetInDestBuffer + i] = src [i << 1] << 16;
  18360. }
  18361. }
  18362. startOffsetInDestBuffer += samplesReceived;
  18363. startSampleInFile += samplesReceived;
  18364. numSamples -= samplesReceived;
  18365. if ((outFlags & kQTMovieAudioExtractionComplete) != 0 && numSamples > 0)
  18366. {
  18367. for (int j = numDestChannels; --j >= 0;)
  18368. if (destSamples[j] != 0)
  18369. zeromem (destSamples[j] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18370. break;
  18371. }
  18372. }
  18373. detachThread();
  18374. return ok;
  18375. }
  18376. juce_UseDebuggingNewOperator
  18377. bool ok;
  18378. private:
  18379. Movie movie;
  18380. Media media;
  18381. Track track;
  18382. const int trackNum;
  18383. double trackUnitsPerFrame;
  18384. int samplesPerFrame;
  18385. int64 lastSampleRead;
  18386. Thread::ThreadID lastThreadId;
  18387. MovieAudioExtractionRef extractor;
  18388. AudioStreamBasicDescription inputStreamDesc;
  18389. HeapBlock <AudioBufferList> bufferList;
  18390. HeapBlock <char> dataBuffer;
  18391. Handle dataHandle;
  18392. void checkThreadIsAttached()
  18393. {
  18394. #if JUCE_MAC
  18395. if (Thread::getCurrentThreadId() != lastThreadId)
  18396. EnterMoviesOnThread (0);
  18397. AttachMovieToCurrentThread (movie);
  18398. #endif
  18399. }
  18400. void detachThread()
  18401. {
  18402. #if JUCE_MAC
  18403. DetachMovieFromCurrentThread (movie);
  18404. #endif
  18405. }
  18406. QTAudioReader (const QTAudioReader&);
  18407. QTAudioReader& operator= (const QTAudioReader&);
  18408. };
  18409. QuickTimeAudioFormat::QuickTimeAudioFormat()
  18410. : AudioFormat (TRANS (quickTimeFormatName), StringArray (quickTimeExtensions))
  18411. {
  18412. }
  18413. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  18414. {
  18415. }
  18416. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates() { return Array<int>(); }
  18417. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths() { return Array<int>(); }
  18418. bool QuickTimeAudioFormat::canDoStereo() { return true; }
  18419. bool QuickTimeAudioFormat::canDoMono() { return true; }
  18420. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  18421. const bool deleteStreamIfOpeningFails)
  18422. {
  18423. ScopedPointer <QTAudioReader> r (new QTAudioReader (sourceStream, 0));
  18424. if (r->ok)
  18425. return r.release();
  18426. if (! deleteStreamIfOpeningFails)
  18427. r->input = 0;
  18428. return 0;
  18429. }
  18430. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  18431. double /*sampleRateToUse*/,
  18432. unsigned int /*numberOfChannels*/,
  18433. int /*bitsPerSample*/,
  18434. const StringPairArray& /*metadataValues*/,
  18435. int /*qualityOptionIndex*/)
  18436. {
  18437. jassertfalse; // not yet implemented!
  18438. return 0;
  18439. }
  18440. END_JUCE_NAMESPACE
  18441. #endif
  18442. /*** End of inlined file: juce_QuickTimeAudioFormat.cpp ***/
  18443. /*** Start of inlined file: juce_WavAudioFormat.cpp ***/
  18444. BEGIN_JUCE_NAMESPACE
  18445. static const char* const wavFormatName = "WAV file";
  18446. static const char* const wavExtensions[] = { ".wav", ".bwf", 0 };
  18447. const char* const WavAudioFormat::bwavDescription = "bwav description";
  18448. const char* const WavAudioFormat::bwavOriginator = "bwav originator";
  18449. const char* const WavAudioFormat::bwavOriginatorRef = "bwav originator ref";
  18450. const char* const WavAudioFormat::bwavOriginationDate = "bwav origination date";
  18451. const char* const WavAudioFormat::bwavOriginationTime = "bwav origination time";
  18452. const char* const WavAudioFormat::bwavTimeReference = "bwav time reference";
  18453. const char* const WavAudioFormat::bwavCodingHistory = "bwav coding history";
  18454. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  18455. const String& originator,
  18456. const String& originatorRef,
  18457. const Time& date,
  18458. const int64 timeReferenceSamples,
  18459. const String& codingHistory)
  18460. {
  18461. StringPairArray m;
  18462. m.set (bwavDescription, description);
  18463. m.set (bwavOriginator, originator);
  18464. m.set (bwavOriginatorRef, originatorRef);
  18465. m.set (bwavOriginationDate, date.formatted ("%Y-%m-%d"));
  18466. m.set (bwavOriginationTime, date.formatted ("%H:%M:%S"));
  18467. m.set (bwavTimeReference, String (timeReferenceSamples));
  18468. m.set (bwavCodingHistory, codingHistory);
  18469. return m;
  18470. }
  18471. #if JUCE_MSVC
  18472. #pragma pack (push, 1)
  18473. #define PACKED
  18474. #elif JUCE_GCC
  18475. #define PACKED __attribute__((packed))
  18476. #else
  18477. #define PACKED
  18478. #endif
  18479. struct BWAVChunk
  18480. {
  18481. char description [256];
  18482. char originator [32];
  18483. char originatorRef [32];
  18484. char originationDate [10];
  18485. char originationTime [8];
  18486. uint32 timeRefLow;
  18487. uint32 timeRefHigh;
  18488. uint16 version;
  18489. uint8 umid[64];
  18490. uint8 reserved[190];
  18491. char codingHistory[1];
  18492. void copyTo (StringPairArray& values) const
  18493. {
  18494. values.set (WavAudioFormat::bwavDescription, String::fromUTF8 (description, 256));
  18495. values.set (WavAudioFormat::bwavOriginator, String::fromUTF8 (originator, 32));
  18496. values.set (WavAudioFormat::bwavOriginatorRef, String::fromUTF8 (originatorRef, 32));
  18497. values.set (WavAudioFormat::bwavOriginationDate, String::fromUTF8 (originationDate, 10));
  18498. values.set (WavAudioFormat::bwavOriginationTime, String::fromUTF8 (originationTime, 8));
  18499. const uint32 timeLow = ByteOrder::swapIfBigEndian (timeRefLow);
  18500. const uint32 timeHigh = ByteOrder::swapIfBigEndian (timeRefHigh);
  18501. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  18502. values.set (WavAudioFormat::bwavTimeReference, String (time));
  18503. values.set (WavAudioFormat::bwavCodingHistory, String::fromUTF8 (codingHistory));
  18504. }
  18505. static MemoryBlock createFrom (const StringPairArray& values)
  18506. {
  18507. const size_t sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].getNumBytesAsUTF8();
  18508. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18509. data.fillWith (0);
  18510. BWAVChunk* b = (BWAVChunk*) data.getData();
  18511. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18512. // as they get called in the right order..
  18513. values [WavAudioFormat::bwavDescription].copyToUTF8 (b->description, 257);
  18514. values [WavAudioFormat::bwavOriginator].copyToUTF8 (b->originator, 33);
  18515. values [WavAudioFormat::bwavOriginatorRef].copyToUTF8 (b->originatorRef, 33);
  18516. values [WavAudioFormat::bwavOriginationDate].copyToUTF8 (b->originationDate, 11);
  18517. values [WavAudioFormat::bwavOriginationTime].copyToUTF8 (b->originationTime, 9);
  18518. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  18519. b->timeRefLow = ByteOrder::swapIfBigEndian ((uint32) (time & 0xffffffff));
  18520. b->timeRefHigh = ByteOrder::swapIfBigEndian ((uint32) (time >> 32));
  18521. values [WavAudioFormat::bwavCodingHistory].copyToUTF8 (b->codingHistory, 0x7fffffff);
  18522. if (b->description[0] != 0
  18523. || b->originator[0] != 0
  18524. || b->originationDate[0] != 0
  18525. || b->originationTime[0] != 0
  18526. || b->codingHistory[0] != 0
  18527. || time != 0)
  18528. {
  18529. return data;
  18530. }
  18531. return MemoryBlock();
  18532. }
  18533. } PACKED;
  18534. struct SMPLChunk
  18535. {
  18536. struct SampleLoop
  18537. {
  18538. uint32 identifier;
  18539. uint32 type;
  18540. uint32 start;
  18541. uint32 end;
  18542. uint32 fraction;
  18543. uint32 playCount;
  18544. } PACKED;
  18545. uint32 manufacturer;
  18546. uint32 product;
  18547. uint32 samplePeriod;
  18548. uint32 midiUnityNote;
  18549. uint32 midiPitchFraction;
  18550. uint32 smpteFormat;
  18551. uint32 smpteOffset;
  18552. uint32 numSampleLoops;
  18553. uint32 samplerData;
  18554. SampleLoop loops[1];
  18555. void copyTo (StringPairArray& values, const int totalSize) const
  18556. {
  18557. values.set ("Manufacturer", String (ByteOrder::swapIfBigEndian (manufacturer)));
  18558. values.set ("Product", String (ByteOrder::swapIfBigEndian (product)));
  18559. values.set ("SamplePeriod", String (ByteOrder::swapIfBigEndian (samplePeriod)));
  18560. values.set ("MidiUnityNote", String (ByteOrder::swapIfBigEndian (midiUnityNote)));
  18561. values.set ("MidiPitchFraction", String (ByteOrder::swapIfBigEndian (midiPitchFraction)));
  18562. values.set ("SmpteFormat", String (ByteOrder::swapIfBigEndian (smpteFormat)));
  18563. values.set ("SmpteOffset", String (ByteOrder::swapIfBigEndian (smpteOffset)));
  18564. values.set ("NumSampleLoops", String (ByteOrder::swapIfBigEndian (numSampleLoops)));
  18565. values.set ("SamplerData", String (ByteOrder::swapIfBigEndian (samplerData)));
  18566. for (uint32 i = 0; i < numSampleLoops; ++i)
  18567. {
  18568. if ((uint8*) (loops + (i + 1)) > ((uint8*) this) + totalSize)
  18569. break;
  18570. const String prefix ("Loop" + String(i));
  18571. values.set (prefix + "Identifier", String (ByteOrder::swapIfBigEndian (loops[i].identifier)));
  18572. values.set (prefix + "Type", String (ByteOrder::swapIfBigEndian (loops[i].type)));
  18573. values.set (prefix + "Start", String (ByteOrder::swapIfBigEndian (loops[i].start)));
  18574. values.set (prefix + "End", String (ByteOrder::swapIfBigEndian (loops[i].end)));
  18575. values.set (prefix + "Fraction", String (ByteOrder::swapIfBigEndian (loops[i].fraction)));
  18576. values.set (prefix + "PlayCount", String (ByteOrder::swapIfBigEndian (loops[i].playCount)));
  18577. }
  18578. }
  18579. static MemoryBlock createFrom (const StringPairArray& values)
  18580. {
  18581. const int numLoops = jmin (64, values.getValue ("NumSampleLoops", "0").getIntValue());
  18582. if (numLoops <= 0)
  18583. return MemoryBlock();
  18584. const size_t sizeNeeded = sizeof (SMPLChunk) + (numLoops - 1) * sizeof (SampleLoop);
  18585. MemoryBlock data ((sizeNeeded + 3) & ~3);
  18586. data.fillWith (0);
  18587. SMPLChunk* s = (SMPLChunk*) data.getData();
  18588. // Allow these calls to overwrite an extra byte at the end, which is fine as long
  18589. // as they get called in the right order..
  18590. s->manufacturer = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Manufacturer", "0").getIntValue());
  18591. s->product = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("Product", "0").getIntValue());
  18592. s->samplePeriod = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplePeriod", "0").getIntValue());
  18593. s->midiUnityNote = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiUnityNote", "60").getIntValue());
  18594. s->midiPitchFraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("MidiPitchFraction", "0").getIntValue());
  18595. s->smpteFormat = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteFormat", "0").getIntValue());
  18596. s->smpteOffset = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SmpteOffset", "0").getIntValue());
  18597. s->numSampleLoops = ByteOrder::swapIfBigEndian ((uint32) numLoops);
  18598. s->samplerData = ByteOrder::swapIfBigEndian ((uint32) values.getValue ("SamplerData", "0").getIntValue());
  18599. for (int i = 0; i < numLoops; ++i)
  18600. {
  18601. const String prefix ("Loop" + String(i));
  18602. s->loops[i].identifier = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Identifier", "0").getIntValue());
  18603. s->loops[i].type = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Type", "0").getIntValue());
  18604. s->loops[i].start = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Start", "0").getIntValue());
  18605. s->loops[i].end = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "End", "0").getIntValue());
  18606. s->loops[i].fraction = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "Fraction", "0").getIntValue());
  18607. s->loops[i].playCount = ByteOrder::swapIfBigEndian ((uint32) values.getValue (prefix + "PlayCount", "0").getIntValue());
  18608. }
  18609. return data;
  18610. }
  18611. } PACKED;
  18612. struct ExtensibleWavSubFormat
  18613. {
  18614. uint32 data1;
  18615. uint16 data2;
  18616. uint16 data3;
  18617. uint8 data4[8];
  18618. } PACKED;
  18619. #if JUCE_MSVC
  18620. #pragma pack (pop)
  18621. #endif
  18622. #undef PACKED
  18623. class WavAudioFormatReader : public AudioFormatReader
  18624. {
  18625. public:
  18626. WavAudioFormatReader (InputStream* const in)
  18627. : AudioFormatReader (in, TRANS (wavFormatName)),
  18628. bwavChunkStart (0),
  18629. bwavSize (0),
  18630. dataLength (0)
  18631. {
  18632. if (input->readInt() == chunkName ("RIFF"))
  18633. {
  18634. const uint32 len = (uint32) input->readInt();
  18635. const int64 end = input->getPosition() + len;
  18636. bool hasGotType = false;
  18637. bool hasGotData = false;
  18638. if (input->readInt() == chunkName ("WAVE"))
  18639. {
  18640. while (input->getPosition() < end
  18641. && ! input->isExhausted())
  18642. {
  18643. const int chunkType = input->readInt();
  18644. uint32 length = (uint32) input->readInt();
  18645. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  18646. if (chunkType == chunkName ("fmt "))
  18647. {
  18648. // read the format chunk
  18649. const unsigned short format = input->readShort();
  18650. const short numChans = input->readShort();
  18651. sampleRate = input->readInt();
  18652. const int bytesPerSec = input->readInt();
  18653. numChannels = numChans;
  18654. bytesPerFrame = bytesPerSec / (int)sampleRate;
  18655. bitsPerSample = 8 * bytesPerFrame / numChans;
  18656. if (format == 3)
  18657. {
  18658. usesFloatingPointData = true;
  18659. }
  18660. else if (format == 0xfffe /*WAVE_FORMAT_EXTENSIBLE*/)
  18661. {
  18662. if (length < 40) // too short
  18663. {
  18664. bytesPerFrame = 0;
  18665. }
  18666. else
  18667. {
  18668. input->skipNextBytes (12); // skip over blockAlign, bitsPerSample and speakerPosition mask
  18669. ExtensibleWavSubFormat subFormat;
  18670. subFormat.data1 = input->readInt();
  18671. subFormat.data2 = input->readShort();
  18672. subFormat.data3 = input->readShort();
  18673. input->read (subFormat.data4, sizeof (subFormat.data4));
  18674. const ExtensibleWavSubFormat pcmFormat
  18675. = { 0x00000001, 0x0000, 0x0010, { 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71 } };
  18676. if (memcmp (&subFormat, &pcmFormat, sizeof (subFormat)) != 0)
  18677. {
  18678. const ExtensibleWavSubFormat ambisonicFormat
  18679. = { 0x00000001, 0x0721, 0x11d3, { 0x86, 0x44, 0xC8, 0xC1, 0xCA, 0x00, 0x00, 0x00 } };
  18680. if (memcmp (&subFormat, &ambisonicFormat, sizeof (subFormat)) != 0)
  18681. bytesPerFrame = 0;
  18682. }
  18683. }
  18684. }
  18685. else if (format != 1)
  18686. {
  18687. bytesPerFrame = 0;
  18688. }
  18689. hasGotType = true;
  18690. }
  18691. else if (chunkType == chunkName ("data"))
  18692. {
  18693. // get the data chunk's position
  18694. dataLength = length;
  18695. dataChunkStart = input->getPosition();
  18696. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  18697. hasGotData = true;
  18698. }
  18699. else if (chunkType == chunkName ("bext"))
  18700. {
  18701. bwavChunkStart = input->getPosition();
  18702. bwavSize = length;
  18703. // Broadcast-wav extension chunk..
  18704. HeapBlock <BWAVChunk> bwav;
  18705. bwav.calloc (jmax ((size_t) length + 1, sizeof (BWAVChunk)), 1);
  18706. input->read (bwav, length);
  18707. bwav->copyTo (metadataValues);
  18708. }
  18709. else if (chunkType == chunkName ("smpl"))
  18710. {
  18711. HeapBlock <SMPLChunk> smpl;
  18712. smpl.calloc (jmax ((size_t) length + 1, sizeof (SMPLChunk)), 1);
  18713. input->read (smpl, length);
  18714. smpl->copyTo (metadataValues, length);
  18715. }
  18716. else if (chunkEnd <= input->getPosition())
  18717. {
  18718. break;
  18719. }
  18720. input->setPosition (chunkEnd);
  18721. }
  18722. }
  18723. }
  18724. }
  18725. ~WavAudioFormatReader()
  18726. {
  18727. }
  18728. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  18729. int64 startSampleInFile, int numSamples)
  18730. {
  18731. jassert (destSamples != 0);
  18732. const int64 samplesAvailable = lengthInSamples - startSampleInFile;
  18733. if (samplesAvailable < numSamples)
  18734. {
  18735. for (int i = numDestChannels; --i >= 0;)
  18736. if (destSamples[i] != 0)
  18737. zeromem (destSamples[i] + startOffsetInDestBuffer, sizeof (int) * numSamples);
  18738. numSamples = (int) samplesAvailable;
  18739. }
  18740. if (numSamples <= 0)
  18741. return true;
  18742. input->setPosition (dataChunkStart + startSampleInFile * bytesPerFrame);
  18743. while (numSamples > 0)
  18744. {
  18745. const int tempBufSize = 480 * 3 * 4; // (keep this a multiple of 3)
  18746. char tempBuffer [tempBufSize];
  18747. const int numThisTime = jmin (tempBufSize / bytesPerFrame, numSamples);
  18748. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  18749. if (bytesRead < numThisTime * bytesPerFrame)
  18750. {
  18751. jassert (bytesRead >= 0);
  18752. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  18753. }
  18754. switch (bitsPerSample)
  18755. {
  18756. case 8: ReadHelper<AudioData::Int32, AudioData::UInt8, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18757. case 16: ReadHelper<AudioData::Int32, AudioData::Int16, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18758. case 24: ReadHelper<AudioData::Int32, AudioData::Int24, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18759. case 32: if (usesFloatingPointData) ReadHelper<AudioData::Float32, AudioData::Float32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime);
  18760. else ReadHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::read (destSamples, startOffsetInDestBuffer, numDestChannels, tempBuffer, numChannels, numThisTime); break;
  18761. default: jassertfalse; break;
  18762. }
  18763. startOffsetInDestBuffer += numThisTime;
  18764. numSamples -= numThisTime;
  18765. }
  18766. return true;
  18767. }
  18768. int64 bwavChunkStart, bwavSize;
  18769. juce_UseDebuggingNewOperator
  18770. private:
  18771. ScopedPointer<AudioData::Converter> converter;
  18772. int bytesPerFrame;
  18773. int64 dataChunkStart, dataLength;
  18774. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18775. WavAudioFormatReader (const WavAudioFormatReader&);
  18776. WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  18777. };
  18778. class WavAudioFormatWriter : public AudioFormatWriter
  18779. {
  18780. public:
  18781. WavAudioFormatWriter (OutputStream* const out,
  18782. const double sampleRate_,
  18783. const unsigned int numChannels_,
  18784. const int bits,
  18785. const StringPairArray& metadataValues)
  18786. : AudioFormatWriter (out,
  18787. TRANS (wavFormatName),
  18788. sampleRate_,
  18789. numChannels_,
  18790. bits),
  18791. lengthInSamples (0),
  18792. bytesWritten (0),
  18793. writeFailed (false)
  18794. {
  18795. if (metadataValues.size() > 0)
  18796. {
  18797. bwavChunk = BWAVChunk::createFrom (metadataValues);
  18798. smplChunk = SMPLChunk::createFrom (metadataValues);
  18799. }
  18800. headerPosition = out->getPosition();
  18801. writeHeader();
  18802. }
  18803. ~WavAudioFormatWriter()
  18804. {
  18805. writeHeader();
  18806. }
  18807. bool write (const int** data, int numSamples)
  18808. {
  18809. jassert (data != 0 && *data != 0); // the input must contain at least one channel!
  18810. if (writeFailed)
  18811. return false;
  18812. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  18813. tempBlock.ensureSize (bytes, false);
  18814. switch (bitsPerSample)
  18815. {
  18816. case 8: WriteHelper<AudioData::UInt8, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18817. case 16: WriteHelper<AudioData::Int16, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18818. case 24: WriteHelper<AudioData::Int24, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18819. case 32: WriteHelper<AudioData::Int32, AudioData::Int32, AudioData::LittleEndian>::write (tempBlock.getData(), numChannels, data, numSamples); break;
  18820. default: jassertfalse; break;
  18821. }
  18822. if (bytesWritten + bytes >= (uint32) 0xfff00000
  18823. || ! output->write (tempBlock.getData(), bytes))
  18824. {
  18825. // failed to write to disk, so let's try writing the header.
  18826. // If it's just run out of disk space, then if it does manage
  18827. // to write the header, we'll still have a useable file..
  18828. writeHeader();
  18829. writeFailed = true;
  18830. return false;
  18831. }
  18832. else
  18833. {
  18834. bytesWritten += bytes;
  18835. lengthInSamples += numSamples;
  18836. return true;
  18837. }
  18838. }
  18839. juce_UseDebuggingNewOperator
  18840. private:
  18841. ScopedPointer<AudioData::Converter> converter;
  18842. MemoryBlock tempBlock, bwavChunk, smplChunk;
  18843. uint32 lengthInSamples, bytesWritten;
  18844. int64 headerPosition;
  18845. bool writeFailed;
  18846. static inline int chunkName (const char* const name) { return (int) ByteOrder::littleEndianInt (name); }
  18847. void writeHeader()
  18848. {
  18849. const bool seekedOk = output->setPosition (headerPosition);
  18850. (void) seekedOk;
  18851. // if this fails, you've given it an output stream that can't seek! It needs
  18852. // to be able to seek back to write the header
  18853. jassert (seekedOk);
  18854. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  18855. output->writeInt (chunkName ("RIFF"));
  18856. output->writeInt ((int) (lengthInSamples * bytesPerFrame
  18857. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36)));
  18858. output->writeInt (chunkName ("WAVE"));
  18859. output->writeInt (chunkName ("fmt "));
  18860. output->writeInt (16);
  18861. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  18862. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  18863. output->writeShort ((short) numChannels);
  18864. output->writeInt ((int) sampleRate);
  18865. output->writeInt (bytesPerFrame * (int) sampleRate);
  18866. output->writeShort ((short) bytesPerFrame);
  18867. output->writeShort ((short) bitsPerSample);
  18868. if (bwavChunk.getSize() > 0)
  18869. {
  18870. output->writeInt (chunkName ("bext"));
  18871. output->writeInt ((int) bwavChunk.getSize());
  18872. output->write (bwavChunk.getData(), (int) bwavChunk.getSize());
  18873. }
  18874. if (smplChunk.getSize() > 0)
  18875. {
  18876. output->writeInt (chunkName ("smpl"));
  18877. output->writeInt ((int) smplChunk.getSize());
  18878. output->write (smplChunk.getData(), (int) smplChunk.getSize());
  18879. }
  18880. output->writeInt (chunkName ("data"));
  18881. output->writeInt (lengthInSamples * bytesPerFrame);
  18882. usesFloatingPointData = (bitsPerSample == 32);
  18883. }
  18884. WavAudioFormatWriter (const WavAudioFormatWriter&);
  18885. WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  18886. };
  18887. WavAudioFormat::WavAudioFormat()
  18888. : AudioFormat (TRANS (wavFormatName), StringArray (wavExtensions))
  18889. {
  18890. }
  18891. WavAudioFormat::~WavAudioFormat()
  18892. {
  18893. }
  18894. const Array <int> WavAudioFormat::getPossibleSampleRates()
  18895. {
  18896. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  18897. return Array <int> (rates);
  18898. }
  18899. const Array <int> WavAudioFormat::getPossibleBitDepths()
  18900. {
  18901. const int depths[] = { 8, 16, 24, 32, 0 };
  18902. return Array <int> (depths);
  18903. }
  18904. bool WavAudioFormat::canDoStereo() { return true; }
  18905. bool WavAudioFormat::canDoMono() { return true; }
  18906. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  18907. const bool deleteStreamIfOpeningFails)
  18908. {
  18909. ScopedPointer <WavAudioFormatReader> r (new WavAudioFormatReader (sourceStream));
  18910. if (r->sampleRate != 0)
  18911. return r.release();
  18912. if (! deleteStreamIfOpeningFails)
  18913. r->input = 0;
  18914. return 0;
  18915. }
  18916. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  18917. double sampleRate,
  18918. unsigned int numChannels,
  18919. int bitsPerSample,
  18920. const StringPairArray& metadataValues,
  18921. int /*qualityOptionIndex*/)
  18922. {
  18923. if (getPossibleBitDepths().contains (bitsPerSample))
  18924. {
  18925. return new WavAudioFormatWriter (out,
  18926. sampleRate,
  18927. numChannels,
  18928. bitsPerSample,
  18929. metadataValues);
  18930. }
  18931. return 0;
  18932. }
  18933. namespace
  18934. {
  18935. bool juce_slowCopyOfWavFileWithNewMetadata (const File& file, const StringPairArray& metadata)
  18936. {
  18937. TemporaryFile tempFile (file);
  18938. WavAudioFormat wav;
  18939. ScopedPointer <AudioFormatReader> reader (wav.createReaderFor (file.createInputStream(), true));
  18940. if (reader != 0)
  18941. {
  18942. ScopedPointer <OutputStream> outStream (tempFile.getFile().createOutputStream());
  18943. if (outStream != 0)
  18944. {
  18945. ScopedPointer <AudioFormatWriter> writer (wav.createWriterFor (outStream, reader->sampleRate,
  18946. reader->numChannels, reader->bitsPerSample,
  18947. metadata, 0));
  18948. if (writer != 0)
  18949. {
  18950. outStream.release();
  18951. bool ok = writer->writeFromAudioReader (*reader, 0, -1);
  18952. writer = 0;
  18953. reader = 0;
  18954. return ok && tempFile.overwriteTargetFileWithTemporary();
  18955. }
  18956. }
  18957. }
  18958. return false;
  18959. }
  18960. }
  18961. bool WavAudioFormat::replaceMetadataInFile (const File& wavFile, const StringPairArray& newMetadata)
  18962. {
  18963. ScopedPointer <WavAudioFormatReader> reader ((WavAudioFormatReader*) createReaderFor (wavFile.createInputStream(), true));
  18964. if (reader != 0)
  18965. {
  18966. const int64 bwavPos = reader->bwavChunkStart;
  18967. const int64 bwavSize = reader->bwavSize;
  18968. reader = 0;
  18969. if (bwavSize > 0)
  18970. {
  18971. MemoryBlock chunk = BWAVChunk::createFrom (newMetadata);
  18972. if (chunk.getSize() <= (size_t) bwavSize)
  18973. {
  18974. // the new one will fit in the space available, so write it directly..
  18975. const int64 oldSize = wavFile.getSize();
  18976. {
  18977. ScopedPointer <FileOutputStream> out (wavFile.createOutputStream());
  18978. out->setPosition (bwavPos);
  18979. out->write (chunk.getData(), (int) chunk.getSize());
  18980. out->setPosition (oldSize);
  18981. }
  18982. jassert (wavFile.getSize() == oldSize);
  18983. return true;
  18984. }
  18985. }
  18986. }
  18987. return juce_slowCopyOfWavFileWithNewMetadata (wavFile, newMetadata);
  18988. }
  18989. END_JUCE_NAMESPACE
  18990. /*** End of inlined file: juce_WavAudioFormat.cpp ***/
  18991. /*** Start of inlined file: juce_AudioCDReader.cpp ***/
  18992. #if JUCE_USE_CDREADER
  18993. BEGIN_JUCE_NAMESPACE
  18994. int AudioCDReader::getNumTracks() const
  18995. {
  18996. return trackStartSamples.size() - 1;
  18997. }
  18998. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  18999. {
  19000. return trackStartSamples [trackNum];
  19001. }
  19002. const Array<int>& AudioCDReader::getTrackOffsets() const
  19003. {
  19004. return trackStartSamples;
  19005. }
  19006. int AudioCDReader::getCDDBId()
  19007. {
  19008. int checksum = 0;
  19009. const int numTracks = getNumTracks();
  19010. for (int i = 0; i < numTracks; ++i)
  19011. for (int offset = (trackStartSamples.getUnchecked(i) + 88200) / 44100; offset > 0; offset /= 10)
  19012. checksum += offset % 10;
  19013. const int length = (trackStartSamples.getLast() - trackStartSamples.getFirst()) / 44100;
  19014. // CCLLLLTT: checksum, length, tracks
  19015. return ((checksum & 0xff) << 24) | (length << 8) | numTracks;
  19016. }
  19017. END_JUCE_NAMESPACE
  19018. #endif
  19019. /*** End of inlined file: juce_AudioCDReader.cpp ***/
  19020. /*** Start of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19021. BEGIN_JUCE_NAMESPACE
  19022. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  19023. const bool deleteReaderWhenThisIsDeleted)
  19024. : reader (reader_),
  19025. deleteReader (deleteReaderWhenThisIsDeleted),
  19026. nextPlayPos (0),
  19027. looping (false)
  19028. {
  19029. jassert (reader != 0);
  19030. }
  19031. AudioFormatReaderSource::~AudioFormatReaderSource()
  19032. {
  19033. releaseResources();
  19034. if (deleteReader)
  19035. delete reader;
  19036. }
  19037. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  19038. {
  19039. nextPlayPos = newPosition;
  19040. }
  19041. void AudioFormatReaderSource::setLooping (bool shouldLoop)
  19042. {
  19043. looping = shouldLoop;
  19044. }
  19045. int AudioFormatReaderSource::getNextReadPosition() const
  19046. {
  19047. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  19048. : nextPlayPos;
  19049. }
  19050. int AudioFormatReaderSource::getTotalLength() const
  19051. {
  19052. return (int) reader->lengthInSamples;
  19053. }
  19054. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  19055. double /*sampleRate*/)
  19056. {
  19057. }
  19058. void AudioFormatReaderSource::releaseResources()
  19059. {
  19060. }
  19061. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19062. {
  19063. if (info.numSamples > 0)
  19064. {
  19065. const int start = nextPlayPos;
  19066. if (looping)
  19067. {
  19068. const int newStart = start % (int) reader->lengthInSamples;
  19069. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  19070. if (newEnd > newStart)
  19071. {
  19072. info.buffer->readFromAudioReader (reader,
  19073. info.startSample,
  19074. newEnd - newStart,
  19075. newStart,
  19076. true, true);
  19077. }
  19078. else
  19079. {
  19080. const int endSamps = (int) reader->lengthInSamples - newStart;
  19081. info.buffer->readFromAudioReader (reader,
  19082. info.startSample,
  19083. endSamps,
  19084. newStart,
  19085. true, true);
  19086. info.buffer->readFromAudioReader (reader,
  19087. info.startSample + endSamps,
  19088. newEnd,
  19089. 0,
  19090. true, true);
  19091. }
  19092. nextPlayPos = newEnd;
  19093. }
  19094. else
  19095. {
  19096. info.buffer->readFromAudioReader (reader,
  19097. info.startSample,
  19098. info.numSamples,
  19099. start,
  19100. true, true);
  19101. nextPlayPos += info.numSamples;
  19102. }
  19103. }
  19104. }
  19105. END_JUCE_NAMESPACE
  19106. /*** End of inlined file: juce_AudioFormatReaderSource.cpp ***/
  19107. /*** Start of inlined file: juce_AudioSourcePlayer.cpp ***/
  19108. BEGIN_JUCE_NAMESPACE
  19109. AudioSourcePlayer::AudioSourcePlayer()
  19110. : source (0),
  19111. sampleRate (0),
  19112. bufferSize (0),
  19113. tempBuffer (2, 8),
  19114. lastGain (1.0f),
  19115. gain (1.0f)
  19116. {
  19117. }
  19118. AudioSourcePlayer::~AudioSourcePlayer()
  19119. {
  19120. setSource (0);
  19121. }
  19122. void AudioSourcePlayer::setSource (AudioSource* newSource)
  19123. {
  19124. if (source != newSource)
  19125. {
  19126. AudioSource* const oldSource = source;
  19127. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  19128. newSource->prepareToPlay (bufferSize, sampleRate);
  19129. {
  19130. const ScopedLock sl (readLock);
  19131. source = newSource;
  19132. }
  19133. if (oldSource != 0)
  19134. oldSource->releaseResources();
  19135. }
  19136. }
  19137. void AudioSourcePlayer::setGain (const float newGain) throw()
  19138. {
  19139. gain = newGain;
  19140. }
  19141. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  19142. int totalNumInputChannels,
  19143. float** outputChannelData,
  19144. int totalNumOutputChannels,
  19145. int numSamples)
  19146. {
  19147. // these should have been prepared by audioDeviceAboutToStart()...
  19148. jassert (sampleRate > 0 && bufferSize > 0);
  19149. const ScopedLock sl (readLock);
  19150. if (source != 0)
  19151. {
  19152. AudioSourceChannelInfo info;
  19153. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  19154. // messy stuff needed to compact the channels down into an array
  19155. // of non-zero pointers..
  19156. for (i = 0; i < totalNumInputChannels; ++i)
  19157. {
  19158. if (inputChannelData[i] != 0)
  19159. {
  19160. inputChans [numInputs++] = inputChannelData[i];
  19161. if (numInputs >= numElementsInArray (inputChans))
  19162. break;
  19163. }
  19164. }
  19165. for (i = 0; i < totalNumOutputChannels; ++i)
  19166. {
  19167. if (outputChannelData[i] != 0)
  19168. {
  19169. outputChans [numOutputs++] = outputChannelData[i];
  19170. if (numOutputs >= numElementsInArray (outputChans))
  19171. break;
  19172. }
  19173. }
  19174. if (numInputs > numOutputs)
  19175. {
  19176. // if there aren't enough output channels for the number of
  19177. // inputs, we need to create some temporary extra ones (can't
  19178. // use the input data in case it gets written to)
  19179. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  19180. false, false, true);
  19181. for (i = 0; i < numOutputs; ++i)
  19182. {
  19183. channels[numActiveChans] = outputChans[i];
  19184. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19185. ++numActiveChans;
  19186. }
  19187. for (i = numOutputs; i < numInputs; ++i)
  19188. {
  19189. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  19190. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19191. ++numActiveChans;
  19192. }
  19193. }
  19194. else
  19195. {
  19196. for (i = 0; i < numInputs; ++i)
  19197. {
  19198. channels[numActiveChans] = outputChans[i];
  19199. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  19200. ++numActiveChans;
  19201. }
  19202. for (i = numInputs; i < numOutputs; ++i)
  19203. {
  19204. channels[numActiveChans] = outputChans[i];
  19205. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  19206. ++numActiveChans;
  19207. }
  19208. }
  19209. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  19210. info.buffer = &buffer;
  19211. info.startSample = 0;
  19212. info.numSamples = numSamples;
  19213. source->getNextAudioBlock (info);
  19214. for (i = info.buffer->getNumChannels(); --i >= 0;)
  19215. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  19216. lastGain = gain;
  19217. }
  19218. else
  19219. {
  19220. for (int i = 0; i < totalNumOutputChannels; ++i)
  19221. if (outputChannelData[i] != 0)
  19222. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  19223. }
  19224. }
  19225. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  19226. {
  19227. sampleRate = device->getCurrentSampleRate();
  19228. bufferSize = device->getCurrentBufferSizeSamples();
  19229. zeromem (channels, sizeof (channels));
  19230. if (source != 0)
  19231. source->prepareToPlay (bufferSize, sampleRate);
  19232. }
  19233. void AudioSourcePlayer::audioDeviceStopped()
  19234. {
  19235. if (source != 0)
  19236. source->releaseResources();
  19237. sampleRate = 0.0;
  19238. bufferSize = 0;
  19239. tempBuffer.setSize (2, 8);
  19240. }
  19241. END_JUCE_NAMESPACE
  19242. /*** End of inlined file: juce_AudioSourcePlayer.cpp ***/
  19243. /*** Start of inlined file: juce_AudioTransportSource.cpp ***/
  19244. BEGIN_JUCE_NAMESPACE
  19245. AudioTransportSource::AudioTransportSource()
  19246. : source (0),
  19247. resamplerSource (0),
  19248. bufferingSource (0),
  19249. positionableSource (0),
  19250. masterSource (0),
  19251. gain (1.0f),
  19252. lastGain (1.0f),
  19253. playing (false),
  19254. stopped (true),
  19255. sampleRate (44100.0),
  19256. sourceSampleRate (0.0),
  19257. blockSize (128),
  19258. readAheadBufferSize (0),
  19259. isPrepared (false),
  19260. inputStreamEOF (false)
  19261. {
  19262. }
  19263. AudioTransportSource::~AudioTransportSource()
  19264. {
  19265. setSource (0);
  19266. releaseResources();
  19267. }
  19268. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  19269. int readAheadBufferSize_,
  19270. double sourceSampleRateToCorrectFor)
  19271. {
  19272. if (source == newSource)
  19273. {
  19274. if (source == 0)
  19275. return;
  19276. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  19277. }
  19278. readAheadBufferSize = readAheadBufferSize_;
  19279. sourceSampleRate = sourceSampleRateToCorrectFor;
  19280. ResamplingAudioSource* newResamplerSource = 0;
  19281. BufferingAudioSource* newBufferingSource = 0;
  19282. PositionableAudioSource* newPositionableSource = 0;
  19283. AudioSource* newMasterSource = 0;
  19284. ScopedPointer <ResamplingAudioSource> oldResamplerSource (resamplerSource);
  19285. ScopedPointer <BufferingAudioSource> oldBufferingSource (bufferingSource);
  19286. AudioSource* oldMasterSource = masterSource;
  19287. if (newSource != 0)
  19288. {
  19289. newPositionableSource = newSource;
  19290. if (readAheadBufferSize_ > 0)
  19291. newPositionableSource = newBufferingSource
  19292. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  19293. newPositionableSource->setNextReadPosition (0);
  19294. if (sourceSampleRateToCorrectFor != 0)
  19295. newMasterSource = newResamplerSource
  19296. = new ResamplingAudioSource (newPositionableSource, false);
  19297. else
  19298. newMasterSource = newPositionableSource;
  19299. if (isPrepared)
  19300. {
  19301. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  19302. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19303. newMasterSource->prepareToPlay (blockSize, sampleRate);
  19304. }
  19305. }
  19306. {
  19307. const ScopedLock sl (callbackLock);
  19308. source = newSource;
  19309. resamplerSource = newResamplerSource;
  19310. bufferingSource = newBufferingSource;
  19311. masterSource = newMasterSource;
  19312. positionableSource = newPositionableSource;
  19313. playing = false;
  19314. }
  19315. if (oldMasterSource != 0)
  19316. oldMasterSource->releaseResources();
  19317. }
  19318. void AudioTransportSource::start()
  19319. {
  19320. if ((! playing) && masterSource != 0)
  19321. {
  19322. {
  19323. const ScopedLock sl (callbackLock);
  19324. playing = true;
  19325. stopped = false;
  19326. inputStreamEOF = false;
  19327. }
  19328. sendChangeMessage (this);
  19329. }
  19330. }
  19331. void AudioTransportSource::stop()
  19332. {
  19333. if (playing)
  19334. {
  19335. {
  19336. const ScopedLock sl (callbackLock);
  19337. playing = false;
  19338. }
  19339. int n = 500;
  19340. while (--n >= 0 && ! stopped)
  19341. Thread::sleep (2);
  19342. sendChangeMessage (this);
  19343. }
  19344. }
  19345. void AudioTransportSource::setPosition (double newPosition)
  19346. {
  19347. if (sampleRate > 0.0)
  19348. setNextReadPosition (roundToInt (newPosition * sampleRate));
  19349. }
  19350. double AudioTransportSource::getCurrentPosition() const
  19351. {
  19352. if (sampleRate > 0.0)
  19353. return getNextReadPosition() / sampleRate;
  19354. else
  19355. return 0.0;
  19356. }
  19357. void AudioTransportSource::setNextReadPosition (int newPosition)
  19358. {
  19359. if (positionableSource != 0)
  19360. {
  19361. if (sampleRate > 0 && sourceSampleRate > 0)
  19362. newPosition = roundToInt (newPosition * sourceSampleRate / sampleRate);
  19363. positionableSource->setNextReadPosition (newPosition);
  19364. }
  19365. }
  19366. int AudioTransportSource::getNextReadPosition() const
  19367. {
  19368. if (positionableSource != 0)
  19369. {
  19370. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19371. return roundToInt (positionableSource->getNextReadPosition() * ratio);
  19372. }
  19373. return 0;
  19374. }
  19375. int AudioTransportSource::getTotalLength() const
  19376. {
  19377. const ScopedLock sl (callbackLock);
  19378. if (positionableSource != 0)
  19379. {
  19380. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  19381. return roundToInt (positionableSource->getTotalLength() * ratio);
  19382. }
  19383. return 0;
  19384. }
  19385. bool AudioTransportSource::isLooping() const
  19386. {
  19387. const ScopedLock sl (callbackLock);
  19388. return positionableSource != 0
  19389. && positionableSource->isLooping();
  19390. }
  19391. void AudioTransportSource::setGain (const float newGain) throw()
  19392. {
  19393. gain = newGain;
  19394. }
  19395. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  19396. double sampleRate_)
  19397. {
  19398. const ScopedLock sl (callbackLock);
  19399. sampleRate = sampleRate_;
  19400. blockSize = samplesPerBlockExpected;
  19401. if (masterSource != 0)
  19402. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19403. if (resamplerSource != 0 && sourceSampleRate != 0)
  19404. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  19405. isPrepared = true;
  19406. }
  19407. void AudioTransportSource::releaseResources()
  19408. {
  19409. const ScopedLock sl (callbackLock);
  19410. if (masterSource != 0)
  19411. masterSource->releaseResources();
  19412. isPrepared = false;
  19413. }
  19414. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19415. {
  19416. const ScopedLock sl (callbackLock);
  19417. inputStreamEOF = false;
  19418. if (masterSource != 0 && ! stopped)
  19419. {
  19420. masterSource->getNextAudioBlock (info);
  19421. if (! playing)
  19422. {
  19423. // just stopped playing, so fade out the last block..
  19424. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19425. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  19426. if (info.numSamples > 256)
  19427. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  19428. }
  19429. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  19430. && ! positionableSource->isLooping())
  19431. {
  19432. playing = false;
  19433. inputStreamEOF = true;
  19434. sendChangeMessage (this);
  19435. }
  19436. stopped = ! playing;
  19437. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  19438. {
  19439. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  19440. lastGain, gain);
  19441. }
  19442. }
  19443. else
  19444. {
  19445. info.clearActiveBufferRegion();
  19446. stopped = true;
  19447. }
  19448. lastGain = gain;
  19449. }
  19450. END_JUCE_NAMESPACE
  19451. /*** End of inlined file: juce_AudioTransportSource.cpp ***/
  19452. /*** Start of inlined file: juce_BufferingAudioSource.cpp ***/
  19453. BEGIN_JUCE_NAMESPACE
  19454. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  19455. public Thread,
  19456. private Timer
  19457. {
  19458. public:
  19459. SharedBufferingAudioSourceThread()
  19460. : Thread ("Audio Buffer")
  19461. {
  19462. }
  19463. ~SharedBufferingAudioSourceThread()
  19464. {
  19465. stopThread (10000);
  19466. clearSingletonInstance();
  19467. }
  19468. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  19469. void addSource (BufferingAudioSource* source)
  19470. {
  19471. const ScopedLock sl (lock);
  19472. if (! sources.contains (source))
  19473. {
  19474. sources.add (source);
  19475. startThread();
  19476. stopTimer();
  19477. }
  19478. notify();
  19479. }
  19480. void removeSource (BufferingAudioSource* source)
  19481. {
  19482. const ScopedLock sl (lock);
  19483. sources.removeValue (source);
  19484. if (sources.size() == 0)
  19485. startTimer (5000);
  19486. }
  19487. private:
  19488. Array <BufferingAudioSource*> sources;
  19489. CriticalSection lock;
  19490. void run()
  19491. {
  19492. while (! threadShouldExit())
  19493. {
  19494. bool busy = false;
  19495. for (int i = sources.size(); --i >= 0;)
  19496. {
  19497. if (threadShouldExit())
  19498. return;
  19499. const ScopedLock sl (lock);
  19500. BufferingAudioSource* const b = sources[i];
  19501. if (b != 0 && b->readNextBufferChunk())
  19502. busy = true;
  19503. }
  19504. if (! busy)
  19505. wait (500);
  19506. }
  19507. }
  19508. void timerCallback()
  19509. {
  19510. stopTimer();
  19511. if (sources.size() == 0)
  19512. deleteInstance();
  19513. }
  19514. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  19515. SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  19516. };
  19517. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  19518. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  19519. const bool deleteSourceWhenDeleted_,
  19520. int numberOfSamplesToBuffer_)
  19521. : source (source_),
  19522. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19523. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  19524. buffer (2, 0),
  19525. bufferValidStart (0),
  19526. bufferValidEnd (0),
  19527. nextPlayPos (0),
  19528. wasSourceLooping (false)
  19529. {
  19530. jassert (source_ != 0);
  19531. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  19532. // not using a larger buffer..
  19533. }
  19534. BufferingAudioSource::~BufferingAudioSource()
  19535. {
  19536. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19537. if (thread != 0)
  19538. thread->removeSource (this);
  19539. if (deleteSourceWhenDeleted)
  19540. delete source;
  19541. }
  19542. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  19543. {
  19544. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  19545. sampleRate = sampleRate_;
  19546. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  19547. buffer.clear();
  19548. bufferValidStart = 0;
  19549. bufferValidEnd = 0;
  19550. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  19551. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  19552. buffer.getNumSamples() / 2))
  19553. {
  19554. SharedBufferingAudioSourceThread::getInstance()->notify();
  19555. Thread::sleep (5);
  19556. }
  19557. }
  19558. void BufferingAudioSource::releaseResources()
  19559. {
  19560. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19561. if (thread != 0)
  19562. thread->removeSource (this);
  19563. buffer.setSize (2, 0);
  19564. source->releaseResources();
  19565. }
  19566. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19567. {
  19568. const ScopedLock sl (bufferStartPosLock);
  19569. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  19570. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  19571. if (validStart == validEnd)
  19572. {
  19573. // total cache miss
  19574. info.clearActiveBufferRegion();
  19575. }
  19576. else
  19577. {
  19578. if (validStart > 0)
  19579. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  19580. if (validEnd < info.numSamples)
  19581. info.buffer->clear (info.startSample + validEnd,
  19582. info.numSamples - validEnd); // partial cache miss at end
  19583. if (validStart < validEnd)
  19584. {
  19585. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  19586. {
  19587. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  19588. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  19589. if (startBufferIndex < endBufferIndex)
  19590. {
  19591. info.buffer->copyFrom (chan, info.startSample + validStart,
  19592. buffer,
  19593. chan, startBufferIndex,
  19594. validEnd - validStart);
  19595. }
  19596. else
  19597. {
  19598. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  19599. info.buffer->copyFrom (chan, info.startSample + validStart,
  19600. buffer,
  19601. chan, startBufferIndex,
  19602. initialSize);
  19603. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  19604. buffer,
  19605. chan, 0,
  19606. (validEnd - validStart) - initialSize);
  19607. }
  19608. }
  19609. }
  19610. nextPlayPos += info.numSamples;
  19611. if (source->isLooping() && nextPlayPos > 0)
  19612. nextPlayPos %= source->getTotalLength();
  19613. }
  19614. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19615. if (thread != 0)
  19616. thread->notify();
  19617. }
  19618. int BufferingAudioSource::getNextReadPosition() const
  19619. {
  19620. return (source->isLooping() && nextPlayPos > 0)
  19621. ? nextPlayPos % source->getTotalLength()
  19622. : nextPlayPos;
  19623. }
  19624. void BufferingAudioSource::setNextReadPosition (int newPosition)
  19625. {
  19626. const ScopedLock sl (bufferStartPosLock);
  19627. nextPlayPos = newPosition;
  19628. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  19629. if (thread != 0)
  19630. thread->notify();
  19631. }
  19632. bool BufferingAudioSource::readNextBufferChunk()
  19633. {
  19634. int newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  19635. {
  19636. const ScopedLock sl (bufferStartPosLock);
  19637. if (wasSourceLooping != isLooping())
  19638. {
  19639. wasSourceLooping = isLooping();
  19640. bufferValidStart = 0;
  19641. bufferValidEnd = 0;
  19642. }
  19643. newBVS = jmax (0, nextPlayPos);
  19644. newBVE = newBVS + buffer.getNumSamples() - 4;
  19645. sectionToReadStart = 0;
  19646. sectionToReadEnd = 0;
  19647. const int maxChunkSize = 2048;
  19648. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  19649. {
  19650. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  19651. sectionToReadStart = newBVS;
  19652. sectionToReadEnd = newBVE;
  19653. bufferValidStart = 0;
  19654. bufferValidEnd = 0;
  19655. }
  19656. else if (abs (newBVS - bufferValidStart) > 512
  19657. || abs (newBVE - bufferValidEnd) > 512)
  19658. {
  19659. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  19660. sectionToReadStart = bufferValidEnd;
  19661. sectionToReadEnd = newBVE;
  19662. bufferValidStart = newBVS;
  19663. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  19664. }
  19665. }
  19666. if (sectionToReadStart != sectionToReadEnd)
  19667. {
  19668. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  19669. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  19670. if (bufferIndexStart < bufferIndexEnd)
  19671. {
  19672. readBufferSection (sectionToReadStart,
  19673. sectionToReadEnd - sectionToReadStart,
  19674. bufferIndexStart);
  19675. }
  19676. else
  19677. {
  19678. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  19679. readBufferSection (sectionToReadStart,
  19680. initialSize,
  19681. bufferIndexStart);
  19682. readBufferSection (sectionToReadStart + initialSize,
  19683. (sectionToReadEnd - sectionToReadStart) - initialSize,
  19684. 0);
  19685. }
  19686. const ScopedLock sl2 (bufferStartPosLock);
  19687. bufferValidStart = newBVS;
  19688. bufferValidEnd = newBVE;
  19689. return true;
  19690. }
  19691. else
  19692. {
  19693. return false;
  19694. }
  19695. }
  19696. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  19697. {
  19698. if (source->getNextReadPosition() != start)
  19699. source->setNextReadPosition (start);
  19700. AudioSourceChannelInfo info;
  19701. info.buffer = &buffer;
  19702. info.startSample = bufferOffset;
  19703. info.numSamples = length;
  19704. source->getNextAudioBlock (info);
  19705. }
  19706. END_JUCE_NAMESPACE
  19707. /*** End of inlined file: juce_BufferingAudioSource.cpp ***/
  19708. /*** Start of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19709. BEGIN_JUCE_NAMESPACE
  19710. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  19711. const bool deleteSourceWhenDeleted_)
  19712. : requiredNumberOfChannels (2),
  19713. source (source_),
  19714. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  19715. buffer (2, 16)
  19716. {
  19717. remappedInfo.buffer = &buffer;
  19718. remappedInfo.startSample = 0;
  19719. }
  19720. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  19721. {
  19722. if (deleteSourceWhenDeleted)
  19723. delete source;
  19724. }
  19725. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_)
  19726. {
  19727. const ScopedLock sl (lock);
  19728. requiredNumberOfChannels = requiredNumberOfChannels_;
  19729. }
  19730. void ChannelRemappingAudioSource::clearAllMappings()
  19731. {
  19732. const ScopedLock sl (lock);
  19733. remappedInputs.clear();
  19734. remappedOutputs.clear();
  19735. }
  19736. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex)
  19737. {
  19738. const ScopedLock sl (lock);
  19739. while (remappedInputs.size() < destIndex)
  19740. remappedInputs.add (-1);
  19741. remappedInputs.set (destIndex, sourceIndex);
  19742. }
  19743. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex)
  19744. {
  19745. const ScopedLock sl (lock);
  19746. while (remappedOutputs.size() < sourceIndex)
  19747. remappedOutputs.add (-1);
  19748. remappedOutputs.set (sourceIndex, destIndex);
  19749. }
  19750. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const
  19751. {
  19752. const ScopedLock sl (lock);
  19753. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  19754. return remappedInputs.getUnchecked (inputChannelIndex);
  19755. return -1;
  19756. }
  19757. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const
  19758. {
  19759. const ScopedLock sl (lock);
  19760. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  19761. return remappedOutputs .getUnchecked (outputChannelIndex);
  19762. return -1;
  19763. }
  19764. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19765. {
  19766. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19767. }
  19768. void ChannelRemappingAudioSource::releaseResources()
  19769. {
  19770. source->releaseResources();
  19771. }
  19772. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19773. {
  19774. const ScopedLock sl (lock);
  19775. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  19776. const int numChans = bufferToFill.buffer->getNumChannels();
  19777. int i;
  19778. for (i = 0; i < buffer.getNumChannels(); ++i)
  19779. {
  19780. const int remappedChan = getRemappedInputChannel (i);
  19781. if (remappedChan >= 0 && remappedChan < numChans)
  19782. {
  19783. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  19784. remappedChan,
  19785. bufferToFill.startSample,
  19786. bufferToFill.numSamples);
  19787. }
  19788. else
  19789. {
  19790. buffer.clear (i, 0, bufferToFill.numSamples);
  19791. }
  19792. }
  19793. remappedInfo.numSamples = bufferToFill.numSamples;
  19794. source->getNextAudioBlock (remappedInfo);
  19795. bufferToFill.clearActiveBufferRegion();
  19796. for (i = 0; i < requiredNumberOfChannels; ++i)
  19797. {
  19798. const int remappedChan = getRemappedOutputChannel (i);
  19799. if (remappedChan >= 0 && remappedChan < numChans)
  19800. {
  19801. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  19802. buffer, i, 0, bufferToFill.numSamples);
  19803. }
  19804. }
  19805. }
  19806. XmlElement* ChannelRemappingAudioSource::createXml() const
  19807. {
  19808. XmlElement* e = new XmlElement ("MAPPINGS");
  19809. String ins, outs;
  19810. int i;
  19811. const ScopedLock sl (lock);
  19812. for (i = 0; i < remappedInputs.size(); ++i)
  19813. ins << remappedInputs.getUnchecked(i) << ' ';
  19814. for (i = 0; i < remappedOutputs.size(); ++i)
  19815. outs << remappedOutputs.getUnchecked(i) << ' ';
  19816. e->setAttribute ("inputs", ins.trimEnd());
  19817. e->setAttribute ("outputs", outs.trimEnd());
  19818. return e;
  19819. }
  19820. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e)
  19821. {
  19822. if (e.hasTagName ("MAPPINGS"))
  19823. {
  19824. const ScopedLock sl (lock);
  19825. clearAllMappings();
  19826. StringArray ins, outs;
  19827. ins.addTokens (e.getStringAttribute ("inputs"), false);
  19828. outs.addTokens (e.getStringAttribute ("outputs"), false);
  19829. int i;
  19830. for (i = 0; i < ins.size(); ++i)
  19831. remappedInputs.add (ins[i].getIntValue());
  19832. for (i = 0; i < outs.size(); ++i)
  19833. remappedOutputs.add (outs[i].getIntValue());
  19834. }
  19835. }
  19836. END_JUCE_NAMESPACE
  19837. /*** End of inlined file: juce_ChannelRemappingAudioSource.cpp ***/
  19838. /*** Start of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19839. BEGIN_JUCE_NAMESPACE
  19840. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  19841. const bool deleteInputWhenDeleted_)
  19842. : input (inputSource),
  19843. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  19844. {
  19845. jassert (inputSource != 0);
  19846. for (int i = 2; --i >= 0;)
  19847. iirFilters.add (new IIRFilter());
  19848. }
  19849. IIRFilterAudioSource::~IIRFilterAudioSource()
  19850. {
  19851. if (deleteInputWhenDeleted)
  19852. delete input;
  19853. }
  19854. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  19855. {
  19856. for (int i = iirFilters.size(); --i >= 0;)
  19857. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  19858. }
  19859. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19860. {
  19861. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19862. for (int i = iirFilters.size(); --i >= 0;)
  19863. iirFilters.getUnchecked(i)->reset();
  19864. }
  19865. void IIRFilterAudioSource::releaseResources()
  19866. {
  19867. input->releaseResources();
  19868. }
  19869. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  19870. {
  19871. input->getNextAudioBlock (bufferToFill);
  19872. const int numChannels = bufferToFill.buffer->getNumChannels();
  19873. while (numChannels > iirFilters.size())
  19874. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  19875. for (int i = 0; i < numChannels; ++i)
  19876. iirFilters.getUnchecked(i)
  19877. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  19878. bufferToFill.numSamples);
  19879. }
  19880. END_JUCE_NAMESPACE
  19881. /*** End of inlined file: juce_IIRFilterAudioSource.cpp ***/
  19882. /*** Start of inlined file: juce_MixerAudioSource.cpp ***/
  19883. BEGIN_JUCE_NAMESPACE
  19884. MixerAudioSource::MixerAudioSource()
  19885. : tempBuffer (2, 0),
  19886. currentSampleRate (0.0),
  19887. bufferSizeExpected (0)
  19888. {
  19889. }
  19890. MixerAudioSource::~MixerAudioSource()
  19891. {
  19892. removeAllInputs();
  19893. }
  19894. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  19895. {
  19896. if (input != 0 && ! inputs.contains (input))
  19897. {
  19898. double localRate;
  19899. int localBufferSize;
  19900. {
  19901. const ScopedLock sl (lock);
  19902. localRate = currentSampleRate;
  19903. localBufferSize = bufferSizeExpected;
  19904. }
  19905. if (localRate != 0.0)
  19906. input->prepareToPlay (localBufferSize, localRate);
  19907. const ScopedLock sl (lock);
  19908. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  19909. inputs.add (input);
  19910. }
  19911. }
  19912. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  19913. {
  19914. if (input != 0)
  19915. {
  19916. int index;
  19917. {
  19918. const ScopedLock sl (lock);
  19919. index = inputs.indexOf (input);
  19920. if (index >= 0)
  19921. {
  19922. inputsToDelete.shiftBits (index, 1);
  19923. inputs.remove (index);
  19924. }
  19925. }
  19926. if (index >= 0)
  19927. {
  19928. input->releaseResources();
  19929. if (deleteInput)
  19930. delete input;
  19931. }
  19932. }
  19933. }
  19934. void MixerAudioSource::removeAllInputs()
  19935. {
  19936. OwnedArray<AudioSource> toDelete;
  19937. {
  19938. const ScopedLock sl (lock);
  19939. for (int i = inputs.size(); --i >= 0;)
  19940. if (inputsToDelete[i])
  19941. toDelete.add (inputs.getUnchecked(i));
  19942. }
  19943. }
  19944. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  19945. {
  19946. tempBuffer.setSize (2, samplesPerBlockExpected);
  19947. const ScopedLock sl (lock);
  19948. currentSampleRate = sampleRate;
  19949. bufferSizeExpected = samplesPerBlockExpected;
  19950. for (int i = inputs.size(); --i >= 0;)
  19951. inputs.getUnchecked(i)->prepareToPlay (samplesPerBlockExpected, sampleRate);
  19952. }
  19953. void MixerAudioSource::releaseResources()
  19954. {
  19955. const ScopedLock sl (lock);
  19956. for (int i = inputs.size(); --i >= 0;)
  19957. inputs.getUnchecked(i)->releaseResources();
  19958. tempBuffer.setSize (2, 0);
  19959. currentSampleRate = 0;
  19960. bufferSizeExpected = 0;
  19961. }
  19962. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  19963. {
  19964. const ScopedLock sl (lock);
  19965. if (inputs.size() > 0)
  19966. {
  19967. inputs.getUnchecked(0)->getNextAudioBlock (info);
  19968. if (inputs.size() > 1)
  19969. {
  19970. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  19971. info.buffer->getNumSamples());
  19972. AudioSourceChannelInfo info2;
  19973. info2.buffer = &tempBuffer;
  19974. info2.numSamples = info.numSamples;
  19975. info2.startSample = 0;
  19976. for (int i = 1; i < inputs.size(); ++i)
  19977. {
  19978. inputs.getUnchecked(i)->getNextAudioBlock (info2);
  19979. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  19980. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  19981. }
  19982. }
  19983. }
  19984. else
  19985. {
  19986. info.clearActiveBufferRegion();
  19987. }
  19988. }
  19989. END_JUCE_NAMESPACE
  19990. /*** End of inlined file: juce_MixerAudioSource.cpp ***/
  19991. /*** Start of inlined file: juce_ResamplingAudioSource.cpp ***/
  19992. BEGIN_JUCE_NAMESPACE
  19993. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  19994. const bool deleteInputWhenDeleted_,
  19995. const int numChannels_)
  19996. : input (inputSource),
  19997. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  19998. ratio (1.0),
  19999. lastRatio (1.0),
  20000. buffer (numChannels_, 0),
  20001. sampsInBuffer (0),
  20002. numChannels (numChannels_)
  20003. {
  20004. jassert (input != 0);
  20005. }
  20006. ResamplingAudioSource::~ResamplingAudioSource()
  20007. {
  20008. if (deleteInputWhenDeleted)
  20009. delete input;
  20010. }
  20011. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  20012. {
  20013. jassert (samplesInPerOutputSample > 0);
  20014. const ScopedLock sl (ratioLock);
  20015. ratio = jmax (0.0, samplesInPerOutputSample);
  20016. }
  20017. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  20018. double sampleRate)
  20019. {
  20020. const ScopedLock sl (ratioLock);
  20021. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  20022. buffer.setSize (numChannels, roundToInt (samplesPerBlockExpected * ratio) + 32);
  20023. buffer.clear();
  20024. sampsInBuffer = 0;
  20025. bufferPos = 0;
  20026. subSampleOffset = 0.0;
  20027. filterStates.calloc (numChannels);
  20028. srcBuffers.calloc (numChannels);
  20029. destBuffers.calloc (numChannels);
  20030. createLowPass (ratio);
  20031. resetFilters();
  20032. }
  20033. void ResamplingAudioSource::releaseResources()
  20034. {
  20035. input->releaseResources();
  20036. buffer.setSize (numChannels, 0);
  20037. }
  20038. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20039. {
  20040. const ScopedLock sl (ratioLock);
  20041. if (lastRatio != ratio)
  20042. {
  20043. createLowPass (ratio);
  20044. lastRatio = ratio;
  20045. }
  20046. const int sampsNeeded = roundToInt (info.numSamples * ratio) + 2;
  20047. int bufferSize = buffer.getNumSamples();
  20048. if (bufferSize < sampsNeeded + 8)
  20049. {
  20050. bufferPos %= bufferSize;
  20051. bufferSize = sampsNeeded + 32;
  20052. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  20053. }
  20054. bufferPos %= bufferSize;
  20055. int endOfBufferPos = bufferPos + sampsInBuffer;
  20056. const int channelsToProcess = jmin (numChannels, info.buffer->getNumChannels());
  20057. while (sampsNeeded > sampsInBuffer)
  20058. {
  20059. endOfBufferPos %= bufferSize;
  20060. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  20061. bufferSize - endOfBufferPos);
  20062. AudioSourceChannelInfo readInfo;
  20063. readInfo.buffer = &buffer;
  20064. readInfo.numSamples = numToDo;
  20065. readInfo.startSample = endOfBufferPos;
  20066. input->getNextAudioBlock (readInfo);
  20067. if (ratio > 1.0001)
  20068. {
  20069. // for down-sampling, pre-apply the filter..
  20070. for (int i = channelsToProcess; --i >= 0;)
  20071. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  20072. }
  20073. sampsInBuffer += numToDo;
  20074. endOfBufferPos += numToDo;
  20075. }
  20076. for (int channel = 0; channel < channelsToProcess; ++channel)
  20077. {
  20078. destBuffers[channel] = info.buffer->getSampleData (channel, info.startSample);
  20079. srcBuffers[channel] = buffer.getSampleData (channel, 0);
  20080. }
  20081. int nextPos = (bufferPos + 1) % bufferSize;
  20082. for (int m = info.numSamples; --m >= 0;)
  20083. {
  20084. const float alpha = (float) subSampleOffset;
  20085. const float invAlpha = 1.0f - alpha;
  20086. for (int channel = 0; channel < channelsToProcess; ++channel)
  20087. *destBuffers[channel]++ = srcBuffers[channel][bufferPos] * invAlpha + srcBuffers[channel][nextPos] * alpha;
  20088. subSampleOffset += ratio;
  20089. jassert (sampsInBuffer > 0);
  20090. while (subSampleOffset >= 1.0)
  20091. {
  20092. if (++bufferPos >= bufferSize)
  20093. bufferPos = 0;
  20094. --sampsInBuffer;
  20095. nextPos = (bufferPos + 1) % bufferSize;
  20096. subSampleOffset -= 1.0;
  20097. }
  20098. }
  20099. if (ratio < 0.9999)
  20100. {
  20101. // for up-sampling, apply the filter after transposing..
  20102. for (int i = channelsToProcess; --i >= 0;)
  20103. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  20104. }
  20105. else if (ratio <= 1.0001)
  20106. {
  20107. // if the filter's not currently being applied, keep it stoked with the last couple of samples to avoid discontinuities
  20108. for (int i = channelsToProcess; --i >= 0;)
  20109. {
  20110. const float* const endOfBuffer = info.buffer->getSampleData (i, info.startSample + info.numSamples - 1);
  20111. FilterState& fs = filterStates[i];
  20112. if (info.numSamples > 1)
  20113. {
  20114. fs.y2 = fs.x2 = *(endOfBuffer - 1);
  20115. }
  20116. else
  20117. {
  20118. fs.y2 = fs.y1;
  20119. fs.x2 = fs.x1;
  20120. }
  20121. fs.y1 = fs.x1 = *endOfBuffer;
  20122. }
  20123. }
  20124. jassert (sampsInBuffer >= 0);
  20125. }
  20126. void ResamplingAudioSource::createLowPass (const double frequencyRatio)
  20127. {
  20128. const double proportionalRate = (frequencyRatio > 1.0) ? 0.5 / frequencyRatio
  20129. : 0.5 * frequencyRatio;
  20130. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  20131. const double nSquared = n * n;
  20132. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  20133. setFilterCoefficients (c1,
  20134. c1 * 2.0f,
  20135. c1,
  20136. 1.0,
  20137. c1 * 2.0 * (1.0 - nSquared),
  20138. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  20139. }
  20140. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  20141. {
  20142. const double a = 1.0 / c4;
  20143. c1 *= a;
  20144. c2 *= a;
  20145. c3 *= a;
  20146. c5 *= a;
  20147. c6 *= a;
  20148. coefficients[0] = c1;
  20149. coefficients[1] = c2;
  20150. coefficients[2] = c3;
  20151. coefficients[3] = c4;
  20152. coefficients[4] = c5;
  20153. coefficients[5] = c6;
  20154. }
  20155. void ResamplingAudioSource::resetFilters()
  20156. {
  20157. zeromem (filterStates, sizeof (FilterState) * numChannels);
  20158. }
  20159. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  20160. {
  20161. while (--num >= 0)
  20162. {
  20163. const double in = *samples;
  20164. double out = coefficients[0] * in
  20165. + coefficients[1] * fs.x1
  20166. + coefficients[2] * fs.x2
  20167. - coefficients[4] * fs.y1
  20168. - coefficients[5] * fs.y2;
  20169. #if JUCE_INTEL
  20170. if (! (out < -1.0e-8 || out > 1.0e-8))
  20171. out = 0;
  20172. #endif
  20173. fs.x2 = fs.x1;
  20174. fs.x1 = in;
  20175. fs.y2 = fs.y1;
  20176. fs.y1 = out;
  20177. *samples++ = (float) out;
  20178. }
  20179. }
  20180. END_JUCE_NAMESPACE
  20181. /*** End of inlined file: juce_ResamplingAudioSource.cpp ***/
  20182. /*** Start of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20183. BEGIN_JUCE_NAMESPACE
  20184. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  20185. : frequency (1000.0),
  20186. sampleRate (44100.0),
  20187. currentPhase (0.0),
  20188. phasePerSample (0.0),
  20189. amplitude (0.5f)
  20190. {
  20191. }
  20192. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  20193. {
  20194. }
  20195. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  20196. {
  20197. amplitude = newAmplitude;
  20198. }
  20199. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  20200. {
  20201. frequency = newFrequencyHz;
  20202. phasePerSample = 0.0;
  20203. }
  20204. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  20205. double sampleRate_)
  20206. {
  20207. currentPhase = 0.0;
  20208. phasePerSample = 0.0;
  20209. sampleRate = sampleRate_;
  20210. }
  20211. void ToneGeneratorAudioSource::releaseResources()
  20212. {
  20213. }
  20214. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  20215. {
  20216. if (phasePerSample == 0.0)
  20217. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20218. for (int i = 0; i < info.numSamples; ++i)
  20219. {
  20220. const float sample = amplitude * (float) std::sin (currentPhase);
  20221. currentPhase += phasePerSample;
  20222. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  20223. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  20224. }
  20225. }
  20226. END_JUCE_NAMESPACE
  20227. /*** End of inlined file: juce_ToneGeneratorAudioSource.cpp ***/
  20228. /*** Start of inlined file: juce_AudioDeviceManager.cpp ***/
  20229. BEGIN_JUCE_NAMESPACE
  20230. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  20231. : sampleRate (0),
  20232. bufferSize (0),
  20233. useDefaultInputChannels (true),
  20234. useDefaultOutputChannels (true)
  20235. {
  20236. }
  20237. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  20238. {
  20239. return outputDeviceName == other.outputDeviceName
  20240. && inputDeviceName == other.inputDeviceName
  20241. && sampleRate == other.sampleRate
  20242. && bufferSize == other.bufferSize
  20243. && inputChannels == other.inputChannels
  20244. && useDefaultInputChannels == other.useDefaultInputChannels
  20245. && outputChannels == other.outputChannels
  20246. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  20247. }
  20248. AudioDeviceManager::AudioDeviceManager()
  20249. : currentAudioDevice (0),
  20250. numInputChansNeeded (0),
  20251. numOutputChansNeeded (2),
  20252. listNeedsScanning (true),
  20253. useInputNames (false),
  20254. inputLevelMeasurementEnabledCount (0),
  20255. inputLevel (0),
  20256. tempBuffer (2, 2),
  20257. defaultMidiOutput (0),
  20258. cpuUsageMs (0),
  20259. timeToCpuScale (0)
  20260. {
  20261. callbackHandler.owner = this;
  20262. }
  20263. AudioDeviceManager::~AudioDeviceManager()
  20264. {
  20265. currentAudioDevice = 0;
  20266. defaultMidiOutput = 0;
  20267. }
  20268. void AudioDeviceManager::createDeviceTypesIfNeeded()
  20269. {
  20270. if (availableDeviceTypes.size() == 0)
  20271. {
  20272. createAudioDeviceTypes (availableDeviceTypes);
  20273. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  20274. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  20275. if (availableDeviceTypes.size() > 0)
  20276. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  20277. }
  20278. }
  20279. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  20280. {
  20281. scanDevicesIfNeeded();
  20282. return availableDeviceTypes;
  20283. }
  20284. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio();
  20285. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio();
  20286. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI();
  20287. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound();
  20288. AudioIODeviceType* juce_createAudioIODeviceType_ASIO();
  20289. AudioIODeviceType* juce_createAudioIODeviceType_ALSA();
  20290. AudioIODeviceType* juce_createAudioIODeviceType_JACK();
  20291. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  20292. {
  20293. (void) list; // (to avoid 'unused param' warnings)
  20294. #if JUCE_WINDOWS
  20295. #if JUCE_WASAPI
  20296. if (SystemStats::getOperatingSystemType() >= SystemStats::WinVista)
  20297. list.add (juce_createAudioIODeviceType_WASAPI());
  20298. #endif
  20299. #if JUCE_DIRECTSOUND
  20300. list.add (juce_createAudioIODeviceType_DirectSound());
  20301. #endif
  20302. #if JUCE_ASIO
  20303. list.add (juce_createAudioIODeviceType_ASIO());
  20304. #endif
  20305. #endif
  20306. #if JUCE_MAC
  20307. list.add (juce_createAudioIODeviceType_CoreAudio());
  20308. #endif
  20309. #if JUCE_IOS
  20310. list.add (juce_createAudioIODeviceType_iPhoneAudio());
  20311. #endif
  20312. #if JUCE_LINUX && JUCE_ALSA
  20313. list.add (juce_createAudioIODeviceType_ALSA());
  20314. #endif
  20315. #if JUCE_LINUX && JUCE_JACK
  20316. list.add (juce_createAudioIODeviceType_JACK());
  20317. #endif
  20318. }
  20319. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  20320. const int numOutputChannelsNeeded,
  20321. const XmlElement* const e,
  20322. const bool selectDefaultDeviceOnFailure,
  20323. const String& preferredDefaultDeviceName,
  20324. const AudioDeviceSetup* preferredSetupOptions)
  20325. {
  20326. scanDevicesIfNeeded();
  20327. numInputChansNeeded = numInputChannelsNeeded;
  20328. numOutputChansNeeded = numOutputChannelsNeeded;
  20329. if (e != 0 && e->hasTagName ("DEVICESETUP"))
  20330. {
  20331. lastExplicitSettings = new XmlElement (*e);
  20332. String error;
  20333. AudioDeviceSetup setup;
  20334. if (preferredSetupOptions != 0)
  20335. setup = *preferredSetupOptions;
  20336. if (e->getStringAttribute ("audioDeviceName").isNotEmpty())
  20337. {
  20338. setup.inputDeviceName = setup.outputDeviceName
  20339. = e->getStringAttribute ("audioDeviceName");
  20340. }
  20341. else
  20342. {
  20343. setup.inputDeviceName = e->getStringAttribute ("audioInputDeviceName");
  20344. setup.outputDeviceName = e->getStringAttribute ("audioOutputDeviceName");
  20345. }
  20346. currentDeviceType = e->getStringAttribute ("deviceType");
  20347. if (currentDeviceType.isEmpty())
  20348. {
  20349. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  20350. if (type != 0)
  20351. currentDeviceType = type->getTypeName();
  20352. else if (availableDeviceTypes.size() > 0)
  20353. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  20354. }
  20355. setup.bufferSize = e->getIntAttribute ("audioDeviceBufferSize");
  20356. setup.sampleRate = e->getDoubleAttribute ("audioDeviceRate");
  20357. setup.inputChannels.parseString (e->getStringAttribute ("audioDeviceInChans", "11"), 2);
  20358. setup.outputChannels.parseString (e->getStringAttribute ("audioDeviceOutChans", "11"), 2);
  20359. setup.useDefaultInputChannels = ! e->hasAttribute ("audioDeviceInChans");
  20360. setup.useDefaultOutputChannels = ! e->hasAttribute ("audioDeviceOutChans");
  20361. error = setAudioDeviceSetup (setup, true);
  20362. midiInsFromXml.clear();
  20363. forEachXmlChildElementWithTagName (*e, c, "MIDIINPUT")
  20364. midiInsFromXml.add (c->getStringAttribute ("name"));
  20365. const StringArray allMidiIns (MidiInput::getDevices());
  20366. for (int i = allMidiIns.size(); --i >= 0;)
  20367. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  20368. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  20369. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  20370. false, preferredDefaultDeviceName);
  20371. setDefaultMidiOutput (e->getStringAttribute ("defaultMidiOutput"));
  20372. return error;
  20373. }
  20374. else
  20375. {
  20376. AudioDeviceSetup setup;
  20377. if (preferredSetupOptions != 0)
  20378. {
  20379. setup = *preferredSetupOptions;
  20380. }
  20381. else if (preferredDefaultDeviceName.isNotEmpty())
  20382. {
  20383. for (int j = availableDeviceTypes.size(); --j >= 0;)
  20384. {
  20385. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  20386. StringArray outs (type->getDeviceNames (false));
  20387. int i;
  20388. for (i = 0; i < outs.size(); ++i)
  20389. {
  20390. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  20391. {
  20392. setup.outputDeviceName = outs[i];
  20393. break;
  20394. }
  20395. }
  20396. StringArray ins (type->getDeviceNames (true));
  20397. for (i = 0; i < ins.size(); ++i)
  20398. {
  20399. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  20400. {
  20401. setup.inputDeviceName = ins[i];
  20402. break;
  20403. }
  20404. }
  20405. }
  20406. }
  20407. insertDefaultDeviceNames (setup);
  20408. return setAudioDeviceSetup (setup, false);
  20409. }
  20410. }
  20411. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  20412. {
  20413. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20414. if (type != 0)
  20415. {
  20416. if (setup.outputDeviceName.isEmpty())
  20417. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  20418. if (setup.inputDeviceName.isEmpty())
  20419. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  20420. }
  20421. }
  20422. XmlElement* AudioDeviceManager::createStateXml() const
  20423. {
  20424. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  20425. }
  20426. void AudioDeviceManager::scanDevicesIfNeeded()
  20427. {
  20428. if (listNeedsScanning)
  20429. {
  20430. listNeedsScanning = false;
  20431. createDeviceTypesIfNeeded();
  20432. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20433. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  20434. }
  20435. }
  20436. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  20437. {
  20438. scanDevicesIfNeeded();
  20439. for (int i = availableDeviceTypes.size(); --i >= 0;)
  20440. {
  20441. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  20442. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  20443. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  20444. {
  20445. return type;
  20446. }
  20447. }
  20448. return 0;
  20449. }
  20450. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  20451. {
  20452. setup = currentSetup;
  20453. }
  20454. void AudioDeviceManager::deleteCurrentDevice()
  20455. {
  20456. currentAudioDevice = 0;
  20457. currentSetup.inputDeviceName = String::empty;
  20458. currentSetup.outputDeviceName = String::empty;
  20459. }
  20460. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  20461. const bool treatAsChosenDevice)
  20462. {
  20463. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20464. {
  20465. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  20466. && currentDeviceType != type)
  20467. {
  20468. currentDeviceType = type;
  20469. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  20470. insertDefaultDeviceNames (s);
  20471. setAudioDeviceSetup (s, treatAsChosenDevice);
  20472. sendChangeMessage (this);
  20473. break;
  20474. }
  20475. }
  20476. }
  20477. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  20478. {
  20479. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20480. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  20481. return availableDeviceTypes[i];
  20482. return availableDeviceTypes[0];
  20483. }
  20484. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  20485. const bool treatAsChosenDevice)
  20486. {
  20487. jassert (&newSetup != &currentSetup); // this will have no effect
  20488. if (newSetup == currentSetup && currentAudioDevice != 0)
  20489. return String::empty;
  20490. if (! (newSetup == currentSetup))
  20491. sendChangeMessage (this);
  20492. stopDevice();
  20493. const String newInputDeviceName (numInputChansNeeded == 0 ? String::empty : newSetup.inputDeviceName);
  20494. const String newOutputDeviceName (numOutputChansNeeded == 0 ? String::empty : newSetup.outputDeviceName);
  20495. String error;
  20496. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  20497. if (type == 0 || (newInputDeviceName.isEmpty() && newOutputDeviceName.isEmpty()))
  20498. {
  20499. deleteCurrentDevice();
  20500. if (treatAsChosenDevice)
  20501. updateXml();
  20502. return String::empty;
  20503. }
  20504. if (currentSetup.inputDeviceName != newInputDeviceName
  20505. || currentSetup.outputDeviceName != newOutputDeviceName
  20506. || currentAudioDevice == 0)
  20507. {
  20508. deleteCurrentDevice();
  20509. scanDevicesIfNeeded();
  20510. if (newOutputDeviceName.isNotEmpty()
  20511. && ! type->getDeviceNames (false).contains (newOutputDeviceName))
  20512. {
  20513. return "No such device: " + newOutputDeviceName;
  20514. }
  20515. if (newInputDeviceName.isNotEmpty()
  20516. && ! type->getDeviceNames (true).contains (newInputDeviceName))
  20517. {
  20518. return "No such device: " + newInputDeviceName;
  20519. }
  20520. currentAudioDevice = type->createDevice (newOutputDeviceName, newInputDeviceName);
  20521. if (currentAudioDevice == 0)
  20522. 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!";
  20523. else
  20524. error = currentAudioDevice->getLastError();
  20525. if (error.isNotEmpty())
  20526. {
  20527. deleteCurrentDevice();
  20528. return error;
  20529. }
  20530. if (newSetup.useDefaultInputChannels)
  20531. {
  20532. inputChannels.clear();
  20533. inputChannels.setRange (0, numInputChansNeeded, true);
  20534. }
  20535. if (newSetup.useDefaultOutputChannels)
  20536. {
  20537. outputChannels.clear();
  20538. outputChannels.setRange (0, numOutputChansNeeded, true);
  20539. }
  20540. if (newInputDeviceName.isEmpty())
  20541. inputChannels.clear();
  20542. if (newOutputDeviceName.isEmpty())
  20543. outputChannels.clear();
  20544. }
  20545. if (! newSetup.useDefaultInputChannels)
  20546. inputChannels = newSetup.inputChannels;
  20547. if (! newSetup.useDefaultOutputChannels)
  20548. outputChannels = newSetup.outputChannels;
  20549. currentSetup = newSetup;
  20550. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  20551. error = currentAudioDevice->open (inputChannels,
  20552. outputChannels,
  20553. currentSetup.sampleRate,
  20554. currentSetup.bufferSize);
  20555. if (error.isEmpty())
  20556. {
  20557. currentDeviceType = currentAudioDevice->getTypeName();
  20558. currentAudioDevice->start (&callbackHandler);
  20559. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  20560. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  20561. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  20562. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  20563. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  20564. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  20565. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  20566. if (treatAsChosenDevice)
  20567. updateXml();
  20568. }
  20569. else
  20570. {
  20571. deleteCurrentDevice();
  20572. }
  20573. return error;
  20574. }
  20575. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  20576. {
  20577. jassert (currentAudioDevice != 0);
  20578. if (rate > 0)
  20579. {
  20580. bool ok = false;
  20581. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20582. {
  20583. const double sr = currentAudioDevice->getSampleRate (i);
  20584. if (sr == rate)
  20585. ok = true;
  20586. }
  20587. if (! ok)
  20588. rate = 0;
  20589. }
  20590. if (rate == 0)
  20591. {
  20592. double lowestAbove44 = 0.0;
  20593. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  20594. {
  20595. const double sr = currentAudioDevice->getSampleRate (i);
  20596. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  20597. lowestAbove44 = sr;
  20598. }
  20599. if (lowestAbove44 == 0.0)
  20600. rate = currentAudioDevice->getSampleRate (0);
  20601. else
  20602. rate = lowestAbove44;
  20603. }
  20604. return rate;
  20605. }
  20606. void AudioDeviceManager::stopDevice()
  20607. {
  20608. if (currentAudioDevice != 0)
  20609. currentAudioDevice->stop();
  20610. testSound = 0;
  20611. }
  20612. void AudioDeviceManager::closeAudioDevice()
  20613. {
  20614. stopDevice();
  20615. currentAudioDevice = 0;
  20616. }
  20617. void AudioDeviceManager::restartLastAudioDevice()
  20618. {
  20619. if (currentAudioDevice == 0)
  20620. {
  20621. if (currentSetup.inputDeviceName.isEmpty()
  20622. && currentSetup.outputDeviceName.isEmpty())
  20623. {
  20624. // This method will only reload the last device that was running
  20625. // before closeAudioDevice() was called - you need to actually open
  20626. // one first, with setAudioDevice().
  20627. jassertfalse;
  20628. return;
  20629. }
  20630. AudioDeviceSetup s (currentSetup);
  20631. setAudioDeviceSetup (s, false);
  20632. }
  20633. }
  20634. void AudioDeviceManager::updateXml()
  20635. {
  20636. lastExplicitSettings = new XmlElement ("DEVICESETUP");
  20637. lastExplicitSettings->setAttribute ("deviceType", currentDeviceType);
  20638. lastExplicitSettings->setAttribute ("audioOutputDeviceName", currentSetup.outputDeviceName);
  20639. lastExplicitSettings->setAttribute ("audioInputDeviceName", currentSetup.inputDeviceName);
  20640. if (currentAudioDevice != 0)
  20641. {
  20642. lastExplicitSettings->setAttribute ("audioDeviceRate", currentAudioDevice->getCurrentSampleRate());
  20643. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  20644. lastExplicitSettings->setAttribute ("audioDeviceBufferSize", currentAudioDevice->getCurrentBufferSizeSamples());
  20645. if (! currentSetup.useDefaultInputChannels)
  20646. lastExplicitSettings->setAttribute ("audioDeviceInChans", currentSetup.inputChannels.toString (2));
  20647. if (! currentSetup.useDefaultOutputChannels)
  20648. lastExplicitSettings->setAttribute ("audioDeviceOutChans", currentSetup.outputChannels.toString (2));
  20649. }
  20650. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  20651. {
  20652. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20653. m->setAttribute ("name", enabledMidiInputs[i]->getName());
  20654. }
  20655. if (midiInsFromXml.size() > 0)
  20656. {
  20657. // Add any midi devices that have been enabled before, but which aren't currently
  20658. // open because the device has been disconnected.
  20659. const StringArray availableMidiDevices (MidiInput::getDevices());
  20660. for (int i = 0; i < midiInsFromXml.size(); ++i)
  20661. {
  20662. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  20663. {
  20664. XmlElement* const m = lastExplicitSettings->createNewChildElement ("MIDIINPUT");
  20665. m->setAttribute ("name", midiInsFromXml[i]);
  20666. }
  20667. }
  20668. }
  20669. if (defaultMidiOutputName.isNotEmpty())
  20670. lastExplicitSettings->setAttribute ("defaultMidiOutput", defaultMidiOutputName);
  20671. }
  20672. void AudioDeviceManager::addAudioCallback (AudioIODeviceCallback* newCallback)
  20673. {
  20674. {
  20675. const ScopedLock sl (audioCallbackLock);
  20676. if (callbacks.contains (newCallback))
  20677. return;
  20678. }
  20679. if (currentAudioDevice != 0 && newCallback != 0)
  20680. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  20681. const ScopedLock sl (audioCallbackLock);
  20682. callbacks.add (newCallback);
  20683. }
  20684. void AudioDeviceManager::removeAudioCallback (AudioIODeviceCallback* callback)
  20685. {
  20686. if (callback != 0)
  20687. {
  20688. bool needsDeinitialising = currentAudioDevice != 0;
  20689. {
  20690. const ScopedLock sl (audioCallbackLock);
  20691. needsDeinitialising = needsDeinitialising && callbacks.contains (callback);
  20692. callbacks.removeValue (callback);
  20693. }
  20694. if (needsDeinitialising)
  20695. callback->audioDeviceStopped();
  20696. }
  20697. }
  20698. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  20699. int numInputChannels,
  20700. float** outputChannelData,
  20701. int numOutputChannels,
  20702. int numSamples)
  20703. {
  20704. const ScopedLock sl (audioCallbackLock);
  20705. if (inputLevelMeasurementEnabledCount > 0)
  20706. {
  20707. for (int j = 0; j < numSamples; ++j)
  20708. {
  20709. float s = 0;
  20710. for (int i = 0; i < numInputChannels; ++i)
  20711. s += std::abs (inputChannelData[i][j]);
  20712. s /= numInputChannels;
  20713. const double decayFactor = 0.99992;
  20714. if (s > inputLevel)
  20715. inputLevel = s;
  20716. else if (inputLevel > 0.001f)
  20717. inputLevel *= decayFactor;
  20718. else
  20719. inputLevel = 0;
  20720. }
  20721. }
  20722. if (callbacks.size() > 0)
  20723. {
  20724. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  20725. tempBuffer.setSize (jmax (1, numOutputChannels), jmax (1, numSamples), false, false, true);
  20726. callbacks.getUnchecked(0)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20727. outputChannelData, numOutputChannels, numSamples);
  20728. float** const tempChans = tempBuffer.getArrayOfChannels();
  20729. for (int i = callbacks.size(); --i > 0;)
  20730. {
  20731. callbacks.getUnchecked(i)->audioDeviceIOCallback (inputChannelData, numInputChannels,
  20732. tempChans, numOutputChannels, numSamples);
  20733. for (int chan = 0; chan < numOutputChannels; ++chan)
  20734. {
  20735. const float* const src = tempChans [chan];
  20736. float* const dst = outputChannelData [chan];
  20737. if (src != 0 && dst != 0)
  20738. for (int j = 0; j < numSamples; ++j)
  20739. dst[j] += src[j];
  20740. }
  20741. }
  20742. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  20743. const double filterAmount = 0.2;
  20744. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  20745. }
  20746. else
  20747. {
  20748. for (int i = 0; i < numOutputChannels; ++i)
  20749. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  20750. }
  20751. if (testSound != 0)
  20752. {
  20753. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  20754. const float* const src = testSound->getSampleData (0, testSoundPosition);
  20755. for (int i = 0; i < numOutputChannels; ++i)
  20756. for (int j = 0; j < numSamps; ++j)
  20757. outputChannelData [i][j] += src[j];
  20758. testSoundPosition += numSamps;
  20759. if (testSoundPosition >= testSound->getNumSamples())
  20760. testSound = 0;
  20761. }
  20762. }
  20763. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  20764. {
  20765. cpuUsageMs = 0;
  20766. const double sampleRate = device->getCurrentSampleRate();
  20767. const int blockSize = device->getCurrentBufferSizeSamples();
  20768. if (sampleRate > 0.0 && blockSize > 0)
  20769. {
  20770. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  20771. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  20772. }
  20773. {
  20774. const ScopedLock sl (audioCallbackLock);
  20775. for (int i = callbacks.size(); --i >= 0;)
  20776. callbacks.getUnchecked(i)->audioDeviceAboutToStart (device);
  20777. }
  20778. sendChangeMessage (this);
  20779. }
  20780. void AudioDeviceManager::audioDeviceStoppedInt()
  20781. {
  20782. cpuUsageMs = 0;
  20783. timeToCpuScale = 0;
  20784. sendChangeMessage (this);
  20785. const ScopedLock sl (audioCallbackLock);
  20786. for (int i = callbacks.size(); --i >= 0;)
  20787. callbacks.getUnchecked(i)->audioDeviceStopped();
  20788. }
  20789. double AudioDeviceManager::getCpuUsage() const
  20790. {
  20791. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  20792. }
  20793. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  20794. const bool enabled)
  20795. {
  20796. if (enabled != isMidiInputEnabled (name))
  20797. {
  20798. if (enabled)
  20799. {
  20800. const int index = MidiInput::getDevices().indexOf (name);
  20801. if (index >= 0)
  20802. {
  20803. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  20804. if (min != 0)
  20805. {
  20806. enabledMidiInputs.add (min);
  20807. min->start();
  20808. }
  20809. }
  20810. }
  20811. else
  20812. {
  20813. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20814. if (enabledMidiInputs[i]->getName() == name)
  20815. enabledMidiInputs.remove (i);
  20816. }
  20817. updateXml();
  20818. sendChangeMessage (this);
  20819. }
  20820. }
  20821. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  20822. {
  20823. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20824. if (enabledMidiInputs[i]->getName() == name)
  20825. return true;
  20826. return false;
  20827. }
  20828. void AudioDeviceManager::addMidiInputCallback (const String& name,
  20829. MidiInputCallback* callback)
  20830. {
  20831. removeMidiInputCallback (name, callback);
  20832. if (name.isEmpty())
  20833. {
  20834. midiCallbacks.add (callback);
  20835. midiCallbackDevices.add (0);
  20836. }
  20837. else
  20838. {
  20839. for (int i = enabledMidiInputs.size(); --i >= 0;)
  20840. {
  20841. if (enabledMidiInputs[i]->getName() == name)
  20842. {
  20843. const ScopedLock sl (midiCallbackLock);
  20844. midiCallbacks.add (callback);
  20845. midiCallbackDevices.add (enabledMidiInputs[i]);
  20846. break;
  20847. }
  20848. }
  20849. }
  20850. }
  20851. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  20852. MidiInputCallback* /*callback*/)
  20853. {
  20854. const ScopedLock sl (midiCallbackLock);
  20855. for (int i = midiCallbacks.size(); --i >= 0;)
  20856. {
  20857. String devName;
  20858. if (midiCallbackDevices.getUnchecked(i) != 0)
  20859. devName = midiCallbackDevices.getUnchecked(i)->getName();
  20860. if (devName == name)
  20861. {
  20862. midiCallbacks.remove (i);
  20863. midiCallbackDevices.remove (i);
  20864. }
  20865. }
  20866. }
  20867. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  20868. const MidiMessage& message)
  20869. {
  20870. if (! message.isActiveSense())
  20871. {
  20872. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  20873. const ScopedLock sl (midiCallbackLock);
  20874. for (int i = midiCallbackDevices.size(); --i >= 0;)
  20875. {
  20876. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  20877. if (md == source || (md == 0 && isDefaultSource))
  20878. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  20879. }
  20880. }
  20881. }
  20882. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  20883. {
  20884. if (defaultMidiOutputName != deviceName)
  20885. {
  20886. SortedSet <AudioIODeviceCallback*> oldCallbacks;
  20887. {
  20888. const ScopedLock sl (audioCallbackLock);
  20889. oldCallbacks = callbacks;
  20890. callbacks.clear();
  20891. }
  20892. if (currentAudioDevice != 0)
  20893. for (int i = oldCallbacks.size(); --i >= 0;)
  20894. oldCallbacks.getUnchecked(i)->audioDeviceStopped();
  20895. defaultMidiOutput = 0;
  20896. defaultMidiOutputName = deviceName;
  20897. if (deviceName.isNotEmpty())
  20898. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  20899. if (currentAudioDevice != 0)
  20900. for (int i = oldCallbacks.size(); --i >= 0;)
  20901. oldCallbacks.getUnchecked(i)->audioDeviceAboutToStart (currentAudioDevice);
  20902. {
  20903. const ScopedLock sl (audioCallbackLock);
  20904. callbacks = oldCallbacks;
  20905. }
  20906. updateXml();
  20907. sendChangeMessage (this);
  20908. }
  20909. }
  20910. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  20911. int numInputChannels,
  20912. float** outputChannelData,
  20913. int numOutputChannels,
  20914. int numSamples)
  20915. {
  20916. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  20917. }
  20918. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  20919. {
  20920. owner->audioDeviceAboutToStartInt (device);
  20921. }
  20922. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  20923. {
  20924. owner->audioDeviceStoppedInt();
  20925. }
  20926. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  20927. {
  20928. owner->handleIncomingMidiMessageInt (source, message);
  20929. }
  20930. void AudioDeviceManager::playTestSound()
  20931. {
  20932. { // cunningly nested to swap, unlock and delete in that order.
  20933. ScopedPointer <AudioSampleBuffer> oldSound;
  20934. {
  20935. const ScopedLock sl (audioCallbackLock);
  20936. oldSound = testSound;
  20937. }
  20938. }
  20939. testSoundPosition = 0;
  20940. if (currentAudioDevice != 0)
  20941. {
  20942. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  20943. const int soundLength = (int) sampleRate;
  20944. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  20945. float* samples = newSound->getSampleData (0);
  20946. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  20947. const float amplitude = 0.5f;
  20948. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  20949. for (int i = 0; i < soundLength; ++i)
  20950. samples[i] = amplitude * (float) std::sin (i * phasePerSample);
  20951. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  20952. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  20953. const ScopedLock sl (audioCallbackLock);
  20954. testSound = newSound;
  20955. }
  20956. }
  20957. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  20958. {
  20959. const ScopedLock sl (audioCallbackLock);
  20960. if (enableMeasurement)
  20961. ++inputLevelMeasurementEnabledCount;
  20962. else
  20963. --inputLevelMeasurementEnabledCount;
  20964. inputLevel = 0;
  20965. }
  20966. double AudioDeviceManager::getCurrentInputLevel() const
  20967. {
  20968. jassert (inputLevelMeasurementEnabledCount > 0); // you need to call enableInputLevelMeasurement() before using this!
  20969. return inputLevel;
  20970. }
  20971. END_JUCE_NAMESPACE
  20972. /*** End of inlined file: juce_AudioDeviceManager.cpp ***/
  20973. /*** Start of inlined file: juce_AudioIODevice.cpp ***/
  20974. BEGIN_JUCE_NAMESPACE
  20975. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  20976. : name (deviceName),
  20977. typeName (typeName_)
  20978. {
  20979. }
  20980. AudioIODevice::~AudioIODevice()
  20981. {
  20982. }
  20983. bool AudioIODevice::hasControlPanel() const
  20984. {
  20985. return false;
  20986. }
  20987. bool AudioIODevice::showControlPanel()
  20988. {
  20989. jassertfalse; // this should only be called for devices which return true from
  20990. // their hasControlPanel() method.
  20991. return false;
  20992. }
  20993. END_JUCE_NAMESPACE
  20994. /*** End of inlined file: juce_AudioIODevice.cpp ***/
  20995. /*** Start of inlined file: juce_AudioIODeviceType.cpp ***/
  20996. BEGIN_JUCE_NAMESPACE
  20997. AudioIODeviceType::AudioIODeviceType (const String& name)
  20998. : typeName (name)
  20999. {
  21000. }
  21001. AudioIODeviceType::~AudioIODeviceType()
  21002. {
  21003. }
  21004. END_JUCE_NAMESPACE
  21005. /*** End of inlined file: juce_AudioIODeviceType.cpp ***/
  21006. /*** Start of inlined file: juce_MidiOutput.cpp ***/
  21007. BEGIN_JUCE_NAMESPACE
  21008. MidiOutput::MidiOutput()
  21009. : Thread ("midi out"),
  21010. internal (0),
  21011. firstMessage (0)
  21012. {
  21013. }
  21014. MidiOutput::PendingMessage::PendingMessage (const uint8* const data, const int len,
  21015. const double sampleNumber)
  21016. : message (data, len, sampleNumber)
  21017. {
  21018. }
  21019. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  21020. const double millisecondCounterToStartAt,
  21021. double samplesPerSecondForBuffer)
  21022. {
  21023. // You've got to call startBackgroundThread() for this to actually work..
  21024. jassert (isThreadRunning());
  21025. // this needs to be a value in the future - RTFM for this method!
  21026. jassert (millisecondCounterToStartAt > 0);
  21027. const double timeScaleFactor = 1000.0 / samplesPerSecondForBuffer;
  21028. MidiBuffer::Iterator i (buffer);
  21029. const uint8* data;
  21030. int len, time;
  21031. while (i.getNextEvent (data, len, time))
  21032. {
  21033. const double eventTime = millisecondCounterToStartAt + timeScaleFactor * time;
  21034. PendingMessage* const m
  21035. = new PendingMessage (data, len, eventTime);
  21036. const ScopedLock sl (lock);
  21037. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  21038. {
  21039. m->next = firstMessage;
  21040. firstMessage = m;
  21041. }
  21042. else
  21043. {
  21044. PendingMessage* mm = firstMessage;
  21045. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  21046. mm = mm->next;
  21047. m->next = mm->next;
  21048. mm->next = m;
  21049. }
  21050. }
  21051. notify();
  21052. }
  21053. void MidiOutput::clearAllPendingMessages()
  21054. {
  21055. const ScopedLock sl (lock);
  21056. while (firstMessage != 0)
  21057. {
  21058. PendingMessage* const m = firstMessage;
  21059. firstMessage = firstMessage->next;
  21060. delete m;
  21061. }
  21062. }
  21063. void MidiOutput::startBackgroundThread()
  21064. {
  21065. startThread (9);
  21066. }
  21067. void MidiOutput::stopBackgroundThread()
  21068. {
  21069. stopThread (5000);
  21070. }
  21071. void MidiOutput::run()
  21072. {
  21073. while (! threadShouldExit())
  21074. {
  21075. uint32 now = Time::getMillisecondCounter();
  21076. uint32 eventTime = 0;
  21077. uint32 timeToWait = 500;
  21078. PendingMessage* message;
  21079. {
  21080. const ScopedLock sl (lock);
  21081. message = firstMessage;
  21082. if (message != 0)
  21083. {
  21084. eventTime = roundToInt (message->message.getTimeStamp());
  21085. if (eventTime > now + 20)
  21086. {
  21087. timeToWait = eventTime - (now + 20);
  21088. message = 0;
  21089. }
  21090. else
  21091. {
  21092. firstMessage = message->next;
  21093. }
  21094. }
  21095. }
  21096. if (message != 0)
  21097. {
  21098. if (eventTime > now)
  21099. {
  21100. Time::waitForMillisecondCounter (eventTime);
  21101. if (threadShouldExit())
  21102. break;
  21103. }
  21104. if (eventTime > now - 200)
  21105. sendMessageNow (message->message);
  21106. delete message;
  21107. }
  21108. else
  21109. {
  21110. jassert (timeToWait < 1000 * 30);
  21111. wait (timeToWait);
  21112. }
  21113. }
  21114. clearAllPendingMessages();
  21115. }
  21116. END_JUCE_NAMESPACE
  21117. /*** End of inlined file: juce_MidiOutput.cpp ***/
  21118. /*** Start of inlined file: juce_AudioDataConverters.cpp ***/
  21119. BEGIN_JUCE_NAMESPACE
  21120. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21121. {
  21122. const double maxVal = (double) 0x7fff;
  21123. char* intData = static_cast <char*> (dest);
  21124. if (dest != (void*) source || destBytesPerSample <= 4)
  21125. {
  21126. for (int i = 0; i < numSamples; ++i)
  21127. {
  21128. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21129. intData += destBytesPerSample;
  21130. }
  21131. }
  21132. else
  21133. {
  21134. intData += destBytesPerSample * numSamples;
  21135. for (int i = numSamples; --i >= 0;)
  21136. {
  21137. intData -= destBytesPerSample;
  21138. *(uint16*) intData = ByteOrder::swapIfBigEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21139. }
  21140. }
  21141. }
  21142. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21143. {
  21144. const double maxVal = (double) 0x7fff;
  21145. char* intData = static_cast <char*> (dest);
  21146. if (dest != (void*) source || destBytesPerSample <= 4)
  21147. {
  21148. for (int i = 0; i < numSamples; ++i)
  21149. {
  21150. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21151. intData += destBytesPerSample;
  21152. }
  21153. }
  21154. else
  21155. {
  21156. intData += destBytesPerSample * numSamples;
  21157. for (int i = numSamples; --i >= 0;)
  21158. {
  21159. intData -= destBytesPerSample;
  21160. *(uint16*) intData = ByteOrder::swapIfLittleEndian ((uint16) (short) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21161. }
  21162. }
  21163. }
  21164. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21165. {
  21166. const double maxVal = (double) 0x7fffff;
  21167. char* intData = static_cast <char*> (dest);
  21168. if (dest != (void*) source || destBytesPerSample <= 4)
  21169. {
  21170. for (int i = 0; i < numSamples; ++i)
  21171. {
  21172. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21173. intData += destBytesPerSample;
  21174. }
  21175. }
  21176. else
  21177. {
  21178. intData += destBytesPerSample * numSamples;
  21179. for (int i = numSamples; --i >= 0;)
  21180. {
  21181. intData -= destBytesPerSample;
  21182. ByteOrder::littleEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21183. }
  21184. }
  21185. }
  21186. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21187. {
  21188. const double maxVal = (double) 0x7fffff;
  21189. char* intData = static_cast <char*> (dest);
  21190. if (dest != (void*) source || destBytesPerSample <= 4)
  21191. {
  21192. for (int i = 0; i < numSamples; ++i)
  21193. {
  21194. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21195. intData += destBytesPerSample;
  21196. }
  21197. }
  21198. else
  21199. {
  21200. intData += destBytesPerSample * numSamples;
  21201. for (int i = numSamples; --i >= 0;)
  21202. {
  21203. intData -= destBytesPerSample;
  21204. ByteOrder::bigEndian24BitToChars ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  21205. }
  21206. }
  21207. }
  21208. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21209. {
  21210. const double maxVal = (double) 0x7fffffff;
  21211. char* intData = static_cast <char*> (dest);
  21212. if (dest != (void*) source || destBytesPerSample <= 4)
  21213. {
  21214. for (int i = 0; i < numSamples; ++i)
  21215. {
  21216. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21217. intData += destBytesPerSample;
  21218. }
  21219. }
  21220. else
  21221. {
  21222. intData += destBytesPerSample * numSamples;
  21223. for (int i = numSamples; --i >= 0;)
  21224. {
  21225. intData -= destBytesPerSample;
  21226. *(uint32*)intData = ByteOrder::swapIfBigEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21227. }
  21228. }
  21229. }
  21230. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21231. {
  21232. const double maxVal = (double) 0x7fffffff;
  21233. char* intData = static_cast <char*> (dest);
  21234. if (dest != (void*) source || destBytesPerSample <= 4)
  21235. {
  21236. for (int i = 0; i < numSamples; ++i)
  21237. {
  21238. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21239. intData += destBytesPerSample;
  21240. }
  21241. }
  21242. else
  21243. {
  21244. intData += destBytesPerSample * numSamples;
  21245. for (int i = numSamples; --i >= 0;)
  21246. {
  21247. intData -= destBytesPerSample;
  21248. *(uint32*)intData = ByteOrder::swapIfLittleEndian ((uint32) roundToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  21249. }
  21250. }
  21251. }
  21252. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21253. {
  21254. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21255. char* d = static_cast <char*> (dest);
  21256. for (int i = 0; i < numSamples; ++i)
  21257. {
  21258. *(float*) d = source[i];
  21259. #if JUCE_BIG_ENDIAN
  21260. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21261. #endif
  21262. d += destBytesPerSample;
  21263. }
  21264. }
  21265. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  21266. {
  21267. jassert (dest != (void*) source || destBytesPerSample <= 4); // This op can't be performed on in-place data!
  21268. char* d = static_cast <char*> (dest);
  21269. for (int i = 0; i < numSamples; ++i)
  21270. {
  21271. *(float*) d = source[i];
  21272. #if JUCE_LITTLE_ENDIAN
  21273. *(uint32*) d = ByteOrder::swap (*(uint32*) d);
  21274. #endif
  21275. d += destBytesPerSample;
  21276. }
  21277. }
  21278. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21279. {
  21280. const float scale = 1.0f / 0x7fff;
  21281. const char* intData = static_cast <const char*> (source);
  21282. if (source != (void*) dest || srcBytesPerSample >= 4)
  21283. {
  21284. for (int i = 0; i < numSamples; ++i)
  21285. {
  21286. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21287. intData += srcBytesPerSample;
  21288. }
  21289. }
  21290. else
  21291. {
  21292. intData += srcBytesPerSample * numSamples;
  21293. for (int i = numSamples; --i >= 0;)
  21294. {
  21295. intData -= srcBytesPerSample;
  21296. dest[i] = scale * (short) ByteOrder::swapIfBigEndian (*(uint16*)intData);
  21297. }
  21298. }
  21299. }
  21300. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21301. {
  21302. const float scale = 1.0f / 0x7fff;
  21303. const char* intData = static_cast <const char*> (source);
  21304. if (source != (void*) dest || srcBytesPerSample >= 4)
  21305. {
  21306. for (int i = 0; i < numSamples; ++i)
  21307. {
  21308. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21309. intData += srcBytesPerSample;
  21310. }
  21311. }
  21312. else
  21313. {
  21314. intData += srcBytesPerSample * numSamples;
  21315. for (int i = numSamples; --i >= 0;)
  21316. {
  21317. intData -= srcBytesPerSample;
  21318. dest[i] = scale * (short) ByteOrder::swapIfLittleEndian (*(uint16*)intData);
  21319. }
  21320. }
  21321. }
  21322. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21323. {
  21324. const float scale = 1.0f / 0x7fffff;
  21325. const char* intData = static_cast <const char*> (source);
  21326. if (source != (void*) dest || srcBytesPerSample >= 4)
  21327. {
  21328. for (int i = 0; i < numSamples; ++i)
  21329. {
  21330. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21331. intData += srcBytesPerSample;
  21332. }
  21333. }
  21334. else
  21335. {
  21336. intData += srcBytesPerSample * numSamples;
  21337. for (int i = numSamples; --i >= 0;)
  21338. {
  21339. intData -= srcBytesPerSample;
  21340. dest[i] = scale * (short) ByteOrder::littleEndian24Bit (intData);
  21341. }
  21342. }
  21343. }
  21344. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21345. {
  21346. const float scale = 1.0f / 0x7fffff;
  21347. const char* intData = static_cast <const char*> (source);
  21348. if (source != (void*) dest || srcBytesPerSample >= 4)
  21349. {
  21350. for (int i = 0; i < numSamples; ++i)
  21351. {
  21352. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21353. intData += srcBytesPerSample;
  21354. }
  21355. }
  21356. else
  21357. {
  21358. intData += srcBytesPerSample * numSamples;
  21359. for (int i = numSamples; --i >= 0;)
  21360. {
  21361. intData -= srcBytesPerSample;
  21362. dest[i] = scale * (short) ByteOrder::bigEndian24Bit (intData);
  21363. }
  21364. }
  21365. }
  21366. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21367. {
  21368. const float scale = 1.0f / 0x7fffffff;
  21369. const char* intData = static_cast <const char*> (source);
  21370. if (source != (void*) dest || srcBytesPerSample >= 4)
  21371. {
  21372. for (int i = 0; i < numSamples; ++i)
  21373. {
  21374. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21375. intData += srcBytesPerSample;
  21376. }
  21377. }
  21378. else
  21379. {
  21380. intData += srcBytesPerSample * numSamples;
  21381. for (int i = numSamples; --i >= 0;)
  21382. {
  21383. intData -= srcBytesPerSample;
  21384. dest[i] = scale * (int) ByteOrder::swapIfBigEndian (*(uint32*) intData);
  21385. }
  21386. }
  21387. }
  21388. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21389. {
  21390. const float scale = 1.0f / 0x7fffffff;
  21391. const char* intData = static_cast <const char*> (source);
  21392. if (source != (void*) dest || srcBytesPerSample >= 4)
  21393. {
  21394. for (int i = 0; i < numSamples; ++i)
  21395. {
  21396. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21397. intData += srcBytesPerSample;
  21398. }
  21399. }
  21400. else
  21401. {
  21402. intData += srcBytesPerSample * numSamples;
  21403. for (int i = numSamples; --i >= 0;)
  21404. {
  21405. intData -= srcBytesPerSample;
  21406. dest[i] = scale * (int) ByteOrder::swapIfLittleEndian (*(uint32*) intData);
  21407. }
  21408. }
  21409. }
  21410. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21411. {
  21412. const char* s = static_cast <const char*> (source);
  21413. for (int i = 0; i < numSamples; ++i)
  21414. {
  21415. dest[i] = *(float*)s;
  21416. #if JUCE_BIG_ENDIAN
  21417. uint32* const d = (uint32*) (dest + i);
  21418. *d = ByteOrder::swap (*d);
  21419. #endif
  21420. s += srcBytesPerSample;
  21421. }
  21422. }
  21423. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  21424. {
  21425. const char* s = static_cast <const char*> (source);
  21426. for (int i = 0; i < numSamples; ++i)
  21427. {
  21428. dest[i] = *(float*)s;
  21429. #if JUCE_LITTLE_ENDIAN
  21430. uint32* const d = (uint32*) (dest + i);
  21431. *d = ByteOrder::swap (*d);
  21432. #endif
  21433. s += srcBytesPerSample;
  21434. }
  21435. }
  21436. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  21437. const float* const source,
  21438. void* const dest,
  21439. const int numSamples)
  21440. {
  21441. switch (destFormat)
  21442. {
  21443. case int16LE:
  21444. convertFloatToInt16LE (source, dest, numSamples);
  21445. break;
  21446. case int16BE:
  21447. convertFloatToInt16BE (source, dest, numSamples);
  21448. break;
  21449. case int24LE:
  21450. convertFloatToInt24LE (source, dest, numSamples);
  21451. break;
  21452. case int24BE:
  21453. convertFloatToInt24BE (source, dest, numSamples);
  21454. break;
  21455. case int32LE:
  21456. convertFloatToInt32LE (source, dest, numSamples);
  21457. break;
  21458. case int32BE:
  21459. convertFloatToInt32BE (source, dest, numSamples);
  21460. break;
  21461. case float32LE:
  21462. convertFloatToFloat32LE (source, dest, numSamples);
  21463. break;
  21464. case float32BE:
  21465. convertFloatToFloat32BE (source, dest, numSamples);
  21466. break;
  21467. default:
  21468. jassertfalse;
  21469. break;
  21470. }
  21471. }
  21472. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  21473. const void* const source,
  21474. float* const dest,
  21475. const int numSamples)
  21476. {
  21477. switch (sourceFormat)
  21478. {
  21479. case int16LE:
  21480. convertInt16LEToFloat (source, dest, numSamples);
  21481. break;
  21482. case int16BE:
  21483. convertInt16BEToFloat (source, dest, numSamples);
  21484. break;
  21485. case int24LE:
  21486. convertInt24LEToFloat (source, dest, numSamples);
  21487. break;
  21488. case int24BE:
  21489. convertInt24BEToFloat (source, dest, numSamples);
  21490. break;
  21491. case int32LE:
  21492. convertInt32LEToFloat (source, dest, numSamples);
  21493. break;
  21494. case int32BE:
  21495. convertInt32BEToFloat (source, dest, numSamples);
  21496. break;
  21497. case float32LE:
  21498. convertFloat32LEToFloat (source, dest, numSamples);
  21499. break;
  21500. case float32BE:
  21501. convertFloat32BEToFloat (source, dest, numSamples);
  21502. break;
  21503. default:
  21504. jassertfalse;
  21505. break;
  21506. }
  21507. }
  21508. void AudioDataConverters::interleaveSamples (const float** const source,
  21509. float* const dest,
  21510. const int numSamples,
  21511. const int numChannels)
  21512. {
  21513. for (int chan = 0; chan < numChannels; ++chan)
  21514. {
  21515. int i = chan;
  21516. const float* src = source [chan];
  21517. for (int j = 0; j < numSamples; ++j)
  21518. {
  21519. dest [i] = src [j];
  21520. i += numChannels;
  21521. }
  21522. }
  21523. }
  21524. void AudioDataConverters::deinterleaveSamples (const float* const source,
  21525. float** const dest,
  21526. const int numSamples,
  21527. const int numChannels)
  21528. {
  21529. for (int chan = 0; chan < numChannels; ++chan)
  21530. {
  21531. int i = chan;
  21532. float* dst = dest [chan];
  21533. for (int j = 0; j < numSamples; ++j)
  21534. {
  21535. dst [j] = source [i];
  21536. i += numChannels;
  21537. }
  21538. }
  21539. }
  21540. #if JUCE_UNIT_TESTS
  21541. class AudioConversionTests : public UnitTest
  21542. {
  21543. public:
  21544. AudioConversionTests() : UnitTest ("Audio data conversion") {}
  21545. template <class F1, class E1, class F2, class E2>
  21546. struct Test5
  21547. {
  21548. static void test (UnitTest& unitTest)
  21549. {
  21550. test (unitTest, false);
  21551. test (unitTest, true);
  21552. }
  21553. static void test (UnitTest& unitTest, bool inPlace)
  21554. {
  21555. const int numSamples = 2048;
  21556. int32 original [numSamples], converted [numSamples], reversed [numSamples];
  21557. {
  21558. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> d (original);
  21559. bool clippingFailed = false;
  21560. for (int i = 0; i < numSamples / 2; ++i)
  21561. {
  21562. d.setAsFloat (Random::getSystemRandom().nextFloat() * 2.2f - 1.1f);
  21563. if (! d.isFloatingPoint())
  21564. clippingFailed = d.getAsFloat() > 1.0f || d.getAsFloat() < -1.0f || clippingFailed;
  21565. ++d;
  21566. d.setAsInt32 (Random::getSystemRandom().nextInt());
  21567. ++d;
  21568. }
  21569. unitTest.expect (! clippingFailed);
  21570. }
  21571. // convert data from the source to dest format..
  21572. ScopedPointer<AudioData::Converter> conv (new AudioData::ConverterInstance <AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>,
  21573. AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::NonConst> >());
  21574. conv->convertSamples (inPlace ? reversed : converted, original, numSamples);
  21575. // ..and back again..
  21576. conv = new AudioData::ConverterInstance <AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>,
  21577. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::NonConst> >();
  21578. if (! inPlace)
  21579. zerostruct (reversed);
  21580. conv->convertSamples (reversed, inPlace ? reversed : converted, numSamples);
  21581. {
  21582. int biggestDiff = 0;
  21583. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d1 (original);
  21584. AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const> d2 (reversed);
  21585. const int errorMargin = 2 * AudioData::Pointer<F1, E1, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution()
  21586. + AudioData::Pointer<F2, E2, AudioData::NonInterleaved, AudioData::Const>::get32BitResolution();
  21587. for (int i = 0; i < numSamples; ++i)
  21588. {
  21589. biggestDiff = jmax (biggestDiff, std::abs (d1.getAsInt32() - d2.getAsInt32()));
  21590. ++d1;
  21591. ++d2;
  21592. }
  21593. unitTest.expect (biggestDiff <= errorMargin);
  21594. }
  21595. }
  21596. };
  21597. template <class F1, class E1, class FormatType>
  21598. struct Test3
  21599. {
  21600. static void test (UnitTest& unitTest)
  21601. {
  21602. Test5 <F1, E1, FormatType, AudioData::BigEndian>::test (unitTest);
  21603. Test5 <F1, E1, FormatType, AudioData::LittleEndian>::test (unitTest);
  21604. }
  21605. };
  21606. template <class FormatType, class Endianness>
  21607. struct Test2
  21608. {
  21609. static void test (UnitTest& unitTest)
  21610. {
  21611. Test3 <FormatType, Endianness, AudioData::Int8>::test (unitTest);
  21612. Test3 <FormatType, Endianness, AudioData::UInt8>::test (unitTest);
  21613. Test3 <FormatType, Endianness, AudioData::Int16>::test (unitTest);
  21614. Test3 <FormatType, Endianness, AudioData::Int24>::test (unitTest);
  21615. Test3 <FormatType, Endianness, AudioData::Int32>::test (unitTest);
  21616. Test3 <FormatType, Endianness, AudioData::Float32>::test (unitTest);
  21617. }
  21618. };
  21619. template <class FormatType>
  21620. struct Test1
  21621. {
  21622. static void test (UnitTest& unitTest)
  21623. {
  21624. Test2 <FormatType, AudioData::BigEndian>::test (unitTest);
  21625. Test2 <FormatType, AudioData::LittleEndian>::test (unitTest);
  21626. }
  21627. };
  21628. void runTest()
  21629. {
  21630. beginTest ("Round-trip conversion");
  21631. Test1 <AudioData::Int8>::test (*this);
  21632. Test1 <AudioData::Int16>::test (*this);
  21633. Test1 <AudioData::Int24>::test (*this);
  21634. Test1 <AudioData::Int32>::test (*this);
  21635. Test1 <AudioData::Float32>::test (*this);
  21636. }
  21637. };
  21638. static AudioConversionTests audioConversionUnitTests;
  21639. #endif
  21640. END_JUCE_NAMESPACE
  21641. /*** End of inlined file: juce_AudioDataConverters.cpp ***/
  21642. /*** Start of inlined file: juce_AudioSampleBuffer.cpp ***/
  21643. BEGIN_JUCE_NAMESPACE
  21644. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  21645. const int numSamples) throw()
  21646. : numChannels (numChannels_),
  21647. size (numSamples)
  21648. {
  21649. jassert (numSamples >= 0);
  21650. jassert (numChannels_ > 0);
  21651. allocateData();
  21652. }
  21653. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  21654. : numChannels (other.numChannels),
  21655. size (other.size)
  21656. {
  21657. allocateData();
  21658. const size_t numBytes = size * sizeof (float);
  21659. for (int i = 0; i < numChannels; ++i)
  21660. memcpy (channels[i], other.channels[i], numBytes);
  21661. }
  21662. void AudioSampleBuffer::allocateData()
  21663. {
  21664. const size_t channelListSize = (numChannels + 1) * sizeof (float*);
  21665. allocatedBytes = (int) (numChannels * size * sizeof (float) + channelListSize + 32);
  21666. allocatedData.malloc (allocatedBytes);
  21667. channels = reinterpret_cast <float**> (allocatedData.getData());
  21668. float* chan = (float*) (allocatedData + channelListSize);
  21669. for (int i = 0; i < numChannels; ++i)
  21670. {
  21671. channels[i] = chan;
  21672. chan += size;
  21673. }
  21674. channels [numChannels] = 0;
  21675. }
  21676. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  21677. const int numChannels_,
  21678. const int numSamples) throw()
  21679. : numChannels (numChannels_),
  21680. size (numSamples),
  21681. allocatedBytes (0)
  21682. {
  21683. jassert (numChannels_ > 0);
  21684. allocateChannels (dataToReferTo);
  21685. }
  21686. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  21687. const int newNumChannels,
  21688. const int newNumSamples) throw()
  21689. {
  21690. jassert (newNumChannels > 0);
  21691. allocatedBytes = 0;
  21692. allocatedData.free();
  21693. numChannels = newNumChannels;
  21694. size = newNumSamples;
  21695. allocateChannels (dataToReferTo);
  21696. }
  21697. void AudioSampleBuffer::allocateChannels (float** const dataToReferTo)
  21698. {
  21699. // (try to avoid doing a malloc here, as that'll blow up things like Pro-Tools)
  21700. if (numChannels < numElementsInArray (preallocatedChannelSpace))
  21701. {
  21702. channels = static_cast <float**> (preallocatedChannelSpace);
  21703. }
  21704. else
  21705. {
  21706. allocatedData.malloc (numChannels + 1, sizeof (float*));
  21707. channels = reinterpret_cast <float**> (allocatedData.getData());
  21708. }
  21709. for (int i = 0; i < numChannels; ++i)
  21710. {
  21711. // you have to pass in the same number of valid pointers as numChannels
  21712. jassert (dataToReferTo[i] != 0);
  21713. channels[i] = dataToReferTo[i];
  21714. }
  21715. channels [numChannels] = 0;
  21716. }
  21717. AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  21718. {
  21719. if (this != &other)
  21720. {
  21721. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  21722. const size_t numBytes = size * sizeof (float);
  21723. for (int i = 0; i < numChannels; ++i)
  21724. memcpy (channels[i], other.channels[i], numBytes);
  21725. }
  21726. return *this;
  21727. }
  21728. AudioSampleBuffer::~AudioSampleBuffer() throw()
  21729. {
  21730. }
  21731. void AudioSampleBuffer::setSize (const int newNumChannels,
  21732. const int newNumSamples,
  21733. const bool keepExistingContent,
  21734. const bool clearExtraSpace,
  21735. const bool avoidReallocating) throw()
  21736. {
  21737. jassert (newNumChannels > 0);
  21738. if (newNumSamples != size || newNumChannels != numChannels)
  21739. {
  21740. const size_t channelListSize = (newNumChannels + 1) * sizeof (float*);
  21741. const size_t newTotalBytes = (newNumChannels * newNumSamples * sizeof (float)) + channelListSize + 32;
  21742. if (keepExistingContent)
  21743. {
  21744. HeapBlock <char> newData;
  21745. newData.allocate (newTotalBytes, clearExtraSpace);
  21746. const int numChansToCopy = jmin (numChannels, newNumChannels);
  21747. const size_t numBytesToCopy = sizeof (float) * jmin (newNumSamples, size);
  21748. float** const newChannels = reinterpret_cast <float**> (newData.getData());
  21749. float* newChan = reinterpret_cast <float*> (newData + channelListSize);
  21750. for (int i = 0; i < numChansToCopy; ++i)
  21751. {
  21752. memcpy (newChan, channels[i], numBytesToCopy);
  21753. newChannels[i] = newChan;
  21754. newChan += newNumSamples;
  21755. }
  21756. allocatedData.swapWith (newData);
  21757. allocatedBytes = (int) newTotalBytes;
  21758. channels = newChannels;
  21759. }
  21760. else
  21761. {
  21762. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  21763. {
  21764. if (clearExtraSpace)
  21765. zeromem (allocatedData, newTotalBytes);
  21766. }
  21767. else
  21768. {
  21769. allocatedBytes = newTotalBytes;
  21770. allocatedData.allocate (newTotalBytes, clearExtraSpace);
  21771. channels = reinterpret_cast <float**> (allocatedData.getData());
  21772. }
  21773. float* chan = reinterpret_cast <float*> (allocatedData + channelListSize);
  21774. for (int i = 0; i < newNumChannels; ++i)
  21775. {
  21776. channels[i] = chan;
  21777. chan += newNumSamples;
  21778. }
  21779. }
  21780. channels [newNumChannels] = 0;
  21781. size = newNumSamples;
  21782. numChannels = newNumChannels;
  21783. }
  21784. }
  21785. void AudioSampleBuffer::clear() throw()
  21786. {
  21787. for (int i = 0; i < numChannels; ++i)
  21788. zeromem (channels[i], size * sizeof (float));
  21789. }
  21790. void AudioSampleBuffer::clear (const int startSample,
  21791. const int numSamples) throw()
  21792. {
  21793. jassert (startSample >= 0 && startSample + numSamples <= size);
  21794. for (int i = 0; i < numChannels; ++i)
  21795. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  21796. }
  21797. void AudioSampleBuffer::clear (const int channel,
  21798. const int startSample,
  21799. const int numSamples) throw()
  21800. {
  21801. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21802. jassert (startSample >= 0 && startSample + numSamples <= size);
  21803. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  21804. }
  21805. void AudioSampleBuffer::applyGain (const int channel,
  21806. const int startSample,
  21807. int numSamples,
  21808. const float gain) throw()
  21809. {
  21810. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21811. jassert (startSample >= 0 && startSample + numSamples <= size);
  21812. if (gain != 1.0f)
  21813. {
  21814. float* d = channels [channel] + startSample;
  21815. if (gain == 0.0f)
  21816. {
  21817. zeromem (d, sizeof (float) * numSamples);
  21818. }
  21819. else
  21820. {
  21821. while (--numSamples >= 0)
  21822. *d++ *= gain;
  21823. }
  21824. }
  21825. }
  21826. void AudioSampleBuffer::applyGainRamp (const int channel,
  21827. const int startSample,
  21828. int numSamples,
  21829. float startGain,
  21830. float endGain) throw()
  21831. {
  21832. if (startGain == endGain)
  21833. {
  21834. applyGain (channel, startSample, numSamples, startGain);
  21835. }
  21836. else
  21837. {
  21838. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  21839. jassert (startSample >= 0 && startSample + numSamples <= size);
  21840. const float increment = (endGain - startGain) / numSamples;
  21841. float* d = channels [channel] + startSample;
  21842. while (--numSamples >= 0)
  21843. {
  21844. *d++ *= startGain;
  21845. startGain += increment;
  21846. }
  21847. }
  21848. }
  21849. void AudioSampleBuffer::applyGain (const int startSample,
  21850. const int numSamples,
  21851. const float gain) throw()
  21852. {
  21853. for (int i = 0; i < numChannels; ++i)
  21854. applyGain (i, startSample, numSamples, gain);
  21855. }
  21856. void AudioSampleBuffer::addFrom (const int destChannel,
  21857. const int destStartSample,
  21858. const AudioSampleBuffer& source,
  21859. const int sourceChannel,
  21860. const int sourceStartSample,
  21861. int numSamples,
  21862. const float gain) throw()
  21863. {
  21864. jassert (&source != this || sourceChannel != destChannel);
  21865. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21866. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21867. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21868. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21869. if (gain != 0.0f && numSamples > 0)
  21870. {
  21871. float* d = channels [destChannel] + destStartSample;
  21872. const float* s = source.channels [sourceChannel] + sourceStartSample;
  21873. if (gain != 1.0f)
  21874. {
  21875. while (--numSamples >= 0)
  21876. *d++ += gain * *s++;
  21877. }
  21878. else
  21879. {
  21880. while (--numSamples >= 0)
  21881. *d++ += *s++;
  21882. }
  21883. }
  21884. }
  21885. void AudioSampleBuffer::addFrom (const int destChannel,
  21886. const int destStartSample,
  21887. const float* source,
  21888. int numSamples,
  21889. const float gain) throw()
  21890. {
  21891. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21892. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21893. jassert (source != 0);
  21894. if (gain != 0.0f && numSamples > 0)
  21895. {
  21896. float* d = channels [destChannel] + destStartSample;
  21897. if (gain != 1.0f)
  21898. {
  21899. while (--numSamples >= 0)
  21900. *d++ += gain * *source++;
  21901. }
  21902. else
  21903. {
  21904. while (--numSamples >= 0)
  21905. *d++ += *source++;
  21906. }
  21907. }
  21908. }
  21909. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  21910. const int destStartSample,
  21911. const float* source,
  21912. int numSamples,
  21913. float startGain,
  21914. const float endGain) throw()
  21915. {
  21916. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21917. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21918. jassert (source != 0);
  21919. if (startGain == endGain)
  21920. {
  21921. addFrom (destChannel,
  21922. destStartSample,
  21923. source,
  21924. numSamples,
  21925. startGain);
  21926. }
  21927. else
  21928. {
  21929. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  21930. {
  21931. const float increment = (endGain - startGain) / numSamples;
  21932. float* d = channels [destChannel] + destStartSample;
  21933. while (--numSamples >= 0)
  21934. {
  21935. *d++ += startGain * *source++;
  21936. startGain += increment;
  21937. }
  21938. }
  21939. }
  21940. }
  21941. void AudioSampleBuffer::copyFrom (const int destChannel,
  21942. const int destStartSample,
  21943. const AudioSampleBuffer& source,
  21944. const int sourceChannel,
  21945. const int sourceStartSample,
  21946. int numSamples) throw()
  21947. {
  21948. jassert (&source != this || sourceChannel != destChannel);
  21949. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21950. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21951. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  21952. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  21953. if (numSamples > 0)
  21954. {
  21955. memcpy (channels [destChannel] + destStartSample,
  21956. source.channels [sourceChannel] + sourceStartSample,
  21957. sizeof (float) * numSamples);
  21958. }
  21959. }
  21960. void AudioSampleBuffer::copyFrom (const int destChannel,
  21961. const int destStartSample,
  21962. const float* source,
  21963. int numSamples) throw()
  21964. {
  21965. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21966. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21967. jassert (source != 0);
  21968. if (numSamples > 0)
  21969. {
  21970. memcpy (channels [destChannel] + destStartSample,
  21971. source,
  21972. sizeof (float) * numSamples);
  21973. }
  21974. }
  21975. void AudioSampleBuffer::copyFrom (const int destChannel,
  21976. const int destStartSample,
  21977. const float* source,
  21978. int numSamples,
  21979. const float gain) throw()
  21980. {
  21981. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  21982. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  21983. jassert (source != 0);
  21984. if (numSamples > 0)
  21985. {
  21986. float* d = channels [destChannel] + destStartSample;
  21987. if (gain != 1.0f)
  21988. {
  21989. if (gain == 0)
  21990. {
  21991. zeromem (d, sizeof (float) * numSamples);
  21992. }
  21993. else
  21994. {
  21995. while (--numSamples >= 0)
  21996. *d++ = gain * *source++;
  21997. }
  21998. }
  21999. else
  22000. {
  22001. memcpy (d, source, sizeof (float) * numSamples);
  22002. }
  22003. }
  22004. }
  22005. void AudioSampleBuffer::copyFromWithRamp (const int destChannel,
  22006. const int destStartSample,
  22007. const float* source,
  22008. int numSamples,
  22009. float startGain,
  22010. float endGain) throw()
  22011. {
  22012. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  22013. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  22014. jassert (source != 0);
  22015. if (startGain == endGain)
  22016. {
  22017. copyFrom (destChannel,
  22018. destStartSample,
  22019. source,
  22020. numSamples,
  22021. startGain);
  22022. }
  22023. else
  22024. {
  22025. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  22026. {
  22027. const float increment = (endGain - startGain) / numSamples;
  22028. float* d = channels [destChannel] + destStartSample;
  22029. while (--numSamples >= 0)
  22030. {
  22031. *d++ = startGain * *source++;
  22032. startGain += increment;
  22033. }
  22034. }
  22035. }
  22036. }
  22037. void AudioSampleBuffer::findMinMax (const int channel,
  22038. const int startSample,
  22039. int numSamples,
  22040. float& minVal,
  22041. float& maxVal) const throw()
  22042. {
  22043. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22044. jassert (startSample >= 0 && startSample + numSamples <= size);
  22045. if (numSamples <= 0)
  22046. {
  22047. minVal = 0.0f;
  22048. maxVal = 0.0f;
  22049. }
  22050. else
  22051. {
  22052. const float* d = channels [channel] + startSample;
  22053. float mn = *d++;
  22054. float mx = mn;
  22055. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  22056. {
  22057. const float samp = *d++;
  22058. if (samp > mx)
  22059. mx = samp;
  22060. if (samp < mn)
  22061. mn = samp;
  22062. }
  22063. maxVal = mx;
  22064. minVal = mn;
  22065. }
  22066. }
  22067. float AudioSampleBuffer::getMagnitude (const int channel,
  22068. const int startSample,
  22069. const int numSamples) const throw()
  22070. {
  22071. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22072. jassert (startSample >= 0 && startSample + numSamples <= size);
  22073. float mn, mx;
  22074. findMinMax (channel, startSample, numSamples, mn, mx);
  22075. return jmax (mn, -mn, mx, -mx);
  22076. }
  22077. float AudioSampleBuffer::getMagnitude (const int startSample,
  22078. const int numSamples) const throw()
  22079. {
  22080. float mag = 0.0f;
  22081. for (int i = 0; i < numChannels; ++i)
  22082. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  22083. return mag;
  22084. }
  22085. float AudioSampleBuffer::getRMSLevel (const int channel,
  22086. const int startSample,
  22087. const int numSamples) const throw()
  22088. {
  22089. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  22090. jassert (startSample >= 0 && startSample + numSamples <= size);
  22091. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  22092. return 0.0f;
  22093. const float* const data = channels [channel] + startSample;
  22094. double sum = 0.0;
  22095. for (int i = 0; i < numSamples; ++i)
  22096. {
  22097. const float sample = data [i];
  22098. sum += sample * sample;
  22099. }
  22100. return (float) std::sqrt (sum / numSamples);
  22101. }
  22102. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  22103. const int startSample,
  22104. const int numSamples,
  22105. const int readerStartSample,
  22106. const bool useLeftChan,
  22107. const bool useRightChan)
  22108. {
  22109. jassert (reader != 0);
  22110. jassert (startSample >= 0 && startSample + numSamples <= size);
  22111. if (numSamples > 0)
  22112. {
  22113. int* chans[3];
  22114. if (useLeftChan == useRightChan)
  22115. {
  22116. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22117. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? reinterpret_cast<int*> (getSampleData (1, startSample)) : 0;
  22118. }
  22119. else if (useLeftChan || (reader->numChannels == 1))
  22120. {
  22121. chans[0] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22122. chans[1] = 0;
  22123. }
  22124. else if (useRightChan)
  22125. {
  22126. chans[0] = 0;
  22127. chans[1] = reinterpret_cast<int*> (getSampleData (0, startSample));
  22128. }
  22129. chans[2] = 0;
  22130. reader->read (chans, 2, readerStartSample, numSamples, true);
  22131. if (! reader->usesFloatingPointData)
  22132. {
  22133. for (int j = 0; j < 2; ++j)
  22134. {
  22135. float* const d = reinterpret_cast <float*> (chans[j]);
  22136. if (d != 0)
  22137. {
  22138. const float multiplier = 1.0f / 0x7fffffff;
  22139. for (int i = 0; i < numSamples; ++i)
  22140. d[i] = *reinterpret_cast<int*> (d + i) * multiplier;
  22141. }
  22142. }
  22143. }
  22144. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  22145. {
  22146. // if this is a stereo buffer and the source was mono, dupe the first channel..
  22147. memcpy (getSampleData (1, startSample),
  22148. getSampleData (0, startSample),
  22149. sizeof (float) * numSamples);
  22150. }
  22151. }
  22152. }
  22153. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  22154. const int startSample,
  22155. const int numSamples) const
  22156. {
  22157. jassert (writer != 0);
  22158. writer->writeFromAudioSampleBuffer (*this, startSample, numSamples);
  22159. }
  22160. END_JUCE_NAMESPACE
  22161. /*** End of inlined file: juce_AudioSampleBuffer.cpp ***/
  22162. /*** Start of inlined file: juce_IIRFilter.cpp ***/
  22163. BEGIN_JUCE_NAMESPACE
  22164. IIRFilter::IIRFilter()
  22165. : active (false)
  22166. {
  22167. reset();
  22168. }
  22169. IIRFilter::IIRFilter (const IIRFilter& other)
  22170. : active (other.active)
  22171. {
  22172. const ScopedLock sl (other.processLock);
  22173. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22174. reset();
  22175. }
  22176. IIRFilter::~IIRFilter()
  22177. {
  22178. }
  22179. void IIRFilter::reset() throw()
  22180. {
  22181. const ScopedLock sl (processLock);
  22182. x1 = 0;
  22183. x2 = 0;
  22184. y1 = 0;
  22185. y2 = 0;
  22186. }
  22187. float IIRFilter::processSingleSampleRaw (const float in) throw()
  22188. {
  22189. float out = coefficients[0] * in
  22190. + coefficients[1] * x1
  22191. + coefficients[2] * x2
  22192. - coefficients[4] * y1
  22193. - coefficients[5] * y2;
  22194. #if JUCE_INTEL
  22195. if (! (out < -1.0e-8 || out > 1.0e-8))
  22196. out = 0;
  22197. #endif
  22198. x2 = x1;
  22199. x1 = in;
  22200. y2 = y1;
  22201. y1 = out;
  22202. return out;
  22203. }
  22204. void IIRFilter::processSamples (float* const samples,
  22205. const int numSamples) throw()
  22206. {
  22207. const ScopedLock sl (processLock);
  22208. if (active)
  22209. {
  22210. for (int i = 0; i < numSamples; ++i)
  22211. {
  22212. const float in = samples[i];
  22213. float out = coefficients[0] * in
  22214. + coefficients[1] * x1
  22215. + coefficients[2] * x2
  22216. - coefficients[4] * y1
  22217. - coefficients[5] * y2;
  22218. #if JUCE_INTEL
  22219. if (! (out < -1.0e-8 || out > 1.0e-8))
  22220. out = 0;
  22221. #endif
  22222. x2 = x1;
  22223. x1 = in;
  22224. y2 = y1;
  22225. y1 = out;
  22226. samples[i] = out;
  22227. }
  22228. }
  22229. }
  22230. void IIRFilter::makeLowPass (const double sampleRate,
  22231. const double frequency) throw()
  22232. {
  22233. jassert (sampleRate > 0);
  22234. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  22235. const double nSquared = n * n;
  22236. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22237. setCoefficients (c1,
  22238. c1 * 2.0f,
  22239. c1,
  22240. 1.0,
  22241. c1 * 2.0 * (1.0 - nSquared),
  22242. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22243. }
  22244. void IIRFilter::makeHighPass (const double sampleRate,
  22245. const double frequency) throw()
  22246. {
  22247. const double n = tan (double_Pi * frequency / sampleRate);
  22248. const double nSquared = n * n;
  22249. const double c1 = 1.0 / (1.0 + std::sqrt (2.0) * n + nSquared);
  22250. setCoefficients (c1,
  22251. c1 * -2.0f,
  22252. c1,
  22253. 1.0,
  22254. c1 * 2.0 * (nSquared - 1.0),
  22255. c1 * (1.0 - std::sqrt (2.0) * n + nSquared));
  22256. }
  22257. void IIRFilter::makeLowShelf (const double sampleRate,
  22258. const double cutOffFrequency,
  22259. const double Q,
  22260. const float gainFactor) throw()
  22261. {
  22262. jassert (sampleRate > 0);
  22263. jassert (Q > 0);
  22264. const double A = jmax (0.0f, gainFactor);
  22265. const double aminus1 = A - 1.0;
  22266. const double aplus1 = A + 1.0;
  22267. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22268. const double coso = std::cos (omega);
  22269. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22270. const double aminus1TimesCoso = aminus1 * coso;
  22271. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  22272. A * 2.0 * (aminus1 - aplus1 * coso),
  22273. A * (aplus1 - aminus1TimesCoso - beta),
  22274. aplus1 + aminus1TimesCoso + beta,
  22275. -2.0 * (aminus1 + aplus1 * coso),
  22276. aplus1 + aminus1TimesCoso - beta);
  22277. }
  22278. void IIRFilter::makeHighShelf (const double sampleRate,
  22279. const double cutOffFrequency,
  22280. const double Q,
  22281. const float gainFactor) throw()
  22282. {
  22283. jassert (sampleRate > 0);
  22284. jassert (Q > 0);
  22285. const double A = jmax (0.0f, gainFactor);
  22286. const double aminus1 = A - 1.0;
  22287. const double aplus1 = A + 1.0;
  22288. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  22289. const double coso = std::cos (omega);
  22290. const double beta = std::sin (omega) * std::sqrt (A) / Q;
  22291. const double aminus1TimesCoso = aminus1 * coso;
  22292. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  22293. A * -2.0 * (aminus1 + aplus1 * coso),
  22294. A * (aplus1 + aminus1TimesCoso - beta),
  22295. aplus1 - aminus1TimesCoso + beta,
  22296. 2.0 * (aminus1 - aplus1 * coso),
  22297. aplus1 - aminus1TimesCoso - beta);
  22298. }
  22299. void IIRFilter::makeBandPass (const double sampleRate,
  22300. const double centreFrequency,
  22301. const double Q,
  22302. const float gainFactor) throw()
  22303. {
  22304. jassert (sampleRate > 0);
  22305. jassert (Q > 0);
  22306. const double A = jmax (0.0f, gainFactor);
  22307. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  22308. const double alpha = 0.5 * std::sin (omega) / Q;
  22309. const double c2 = -2.0 * std::cos (omega);
  22310. const double alphaTimesA = alpha * A;
  22311. const double alphaOverA = alpha / A;
  22312. setCoefficients (1.0 + alphaTimesA,
  22313. c2,
  22314. 1.0 - alphaTimesA,
  22315. 1.0 + alphaOverA,
  22316. c2,
  22317. 1.0 - alphaOverA);
  22318. }
  22319. void IIRFilter::makeInactive() throw()
  22320. {
  22321. const ScopedLock sl (processLock);
  22322. active = false;
  22323. }
  22324. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  22325. {
  22326. const ScopedLock sl (processLock);
  22327. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  22328. active = other.active;
  22329. }
  22330. void IIRFilter::setCoefficients (double c1,
  22331. double c2,
  22332. double c3,
  22333. double c4,
  22334. double c5,
  22335. double c6) throw()
  22336. {
  22337. const double a = 1.0 / c4;
  22338. c1 *= a;
  22339. c2 *= a;
  22340. c3 *= a;
  22341. c5 *= a;
  22342. c6 *= a;
  22343. const ScopedLock sl (processLock);
  22344. coefficients[0] = (float) c1;
  22345. coefficients[1] = (float) c2;
  22346. coefficients[2] = (float) c3;
  22347. coefficients[3] = (float) c4;
  22348. coefficients[4] = (float) c5;
  22349. coefficients[5] = (float) c6;
  22350. active = true;
  22351. }
  22352. END_JUCE_NAMESPACE
  22353. /*** End of inlined file: juce_IIRFilter.cpp ***/
  22354. /*** Start of inlined file: juce_MidiBuffer.cpp ***/
  22355. BEGIN_JUCE_NAMESPACE
  22356. MidiBuffer::MidiBuffer() throw()
  22357. : bytesUsed (0)
  22358. {
  22359. }
  22360. MidiBuffer::MidiBuffer (const MidiMessage& message) throw()
  22361. : bytesUsed (0)
  22362. {
  22363. addEvent (message, 0);
  22364. }
  22365. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  22366. : data (other.data),
  22367. bytesUsed (other.bytesUsed)
  22368. {
  22369. }
  22370. MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  22371. {
  22372. bytesUsed = other.bytesUsed;
  22373. data = other.data;
  22374. return *this;
  22375. }
  22376. void MidiBuffer::swapWith (MidiBuffer& other) throw()
  22377. {
  22378. data.swapWith (other.data);
  22379. swapVariables <int> (bytesUsed, other.bytesUsed);
  22380. }
  22381. MidiBuffer::~MidiBuffer()
  22382. {
  22383. }
  22384. inline uint8* MidiBuffer::getData() const throw()
  22385. {
  22386. return static_cast <uint8*> (data.getData());
  22387. }
  22388. inline int MidiBuffer::getEventTime (const void* const d) throw()
  22389. {
  22390. return *static_cast <const int*> (d);
  22391. }
  22392. inline uint16 MidiBuffer::getEventDataSize (const void* const d) throw()
  22393. {
  22394. return *reinterpret_cast <const uint16*> (static_cast <const char*> (d) + sizeof (int));
  22395. }
  22396. inline uint16 MidiBuffer::getEventTotalSize (const void* const d) throw()
  22397. {
  22398. return getEventDataSize (d) + sizeof (int) + sizeof (uint16);
  22399. }
  22400. void MidiBuffer::clear() throw()
  22401. {
  22402. bytesUsed = 0;
  22403. }
  22404. void MidiBuffer::clear (const int startSample, const int numSamples)
  22405. {
  22406. uint8* const start = findEventAfter (getData(), startSample - 1);
  22407. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  22408. if (end > start)
  22409. {
  22410. const int bytesToMove = bytesUsed - (int) (end - getData());
  22411. if (bytesToMove > 0)
  22412. memmove (start, end, bytesToMove);
  22413. bytesUsed -= (int) (end - start);
  22414. }
  22415. }
  22416. void MidiBuffer::addEvent (const MidiMessage& m, const int sampleNumber)
  22417. {
  22418. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  22419. }
  22420. namespace MidiBufferHelpers
  22421. {
  22422. int findActualEventLength (const uint8* const data, const int maxBytes) throw()
  22423. {
  22424. unsigned int byte = (unsigned int) *data;
  22425. int size = 0;
  22426. if (byte == 0xf0 || byte == 0xf7)
  22427. {
  22428. const uint8* d = data + 1;
  22429. while (d < data + maxBytes)
  22430. if (*d++ == 0xf7)
  22431. break;
  22432. size = (int) (d - data);
  22433. }
  22434. else if (byte == 0xff)
  22435. {
  22436. int n;
  22437. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  22438. size = jmin (maxBytes, n + 2 + bytesLeft);
  22439. }
  22440. else if (byte >= 0x80)
  22441. {
  22442. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  22443. }
  22444. return size;
  22445. }
  22446. }
  22447. void MidiBuffer::addEvent (const void* const newData, const int maxBytes, const int sampleNumber)
  22448. {
  22449. const int numBytes = MidiBufferHelpers::findActualEventLength (static_cast <const uint8*> (newData), maxBytes);
  22450. if (numBytes > 0)
  22451. {
  22452. int spaceNeeded = bytesUsed + numBytes + sizeof (int) + sizeof (uint16);
  22453. data.ensureSize ((spaceNeeded + spaceNeeded / 2 + 8) & ~7);
  22454. uint8* d = findEventAfter (getData(), sampleNumber);
  22455. const int bytesToMove = bytesUsed - (int) (d - getData());
  22456. if (bytesToMove > 0)
  22457. memmove (d + numBytes + sizeof (int) + sizeof (uint16), d, bytesToMove);
  22458. *reinterpret_cast <int*> (d) = sampleNumber;
  22459. d += sizeof (int);
  22460. *reinterpret_cast <uint16*> (d) = (uint16) numBytes;
  22461. d += sizeof (uint16);
  22462. memcpy (d, newData, numBytes);
  22463. bytesUsed += numBytes + sizeof (int) + sizeof (uint16);
  22464. }
  22465. }
  22466. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  22467. const int startSample,
  22468. const int numSamples,
  22469. const int sampleDeltaToAdd)
  22470. {
  22471. Iterator i (otherBuffer);
  22472. i.setNextSamplePosition (startSample);
  22473. const uint8* eventData;
  22474. int eventSize, position;
  22475. while (i.getNextEvent (eventData, eventSize, position)
  22476. && (position < startSample + numSamples || numSamples < 0))
  22477. {
  22478. addEvent (eventData, eventSize, position + sampleDeltaToAdd);
  22479. }
  22480. }
  22481. void MidiBuffer::ensureSize (size_t minimumNumBytes)
  22482. {
  22483. data.ensureSize (minimumNumBytes);
  22484. }
  22485. bool MidiBuffer::isEmpty() const throw()
  22486. {
  22487. return bytesUsed == 0;
  22488. }
  22489. int MidiBuffer::getNumEvents() const throw()
  22490. {
  22491. int n = 0;
  22492. const uint8* d = getData();
  22493. const uint8* const end = d + bytesUsed;
  22494. while (d < end)
  22495. {
  22496. d += getEventTotalSize (d);
  22497. ++n;
  22498. }
  22499. return n;
  22500. }
  22501. int MidiBuffer::getFirstEventTime() const throw()
  22502. {
  22503. return bytesUsed > 0 ? getEventTime (data.getData()) : 0;
  22504. }
  22505. int MidiBuffer::getLastEventTime() const throw()
  22506. {
  22507. if (bytesUsed == 0)
  22508. return 0;
  22509. const uint8* d = getData();
  22510. const uint8* const endData = d + bytesUsed;
  22511. for (;;)
  22512. {
  22513. const uint8* const nextOne = d + getEventTotalSize (d);
  22514. if (nextOne >= endData)
  22515. return getEventTime (d);
  22516. d = nextOne;
  22517. }
  22518. }
  22519. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  22520. {
  22521. const uint8* const endData = getData() + bytesUsed;
  22522. while (d < endData && getEventTime (d) <= samplePosition)
  22523. d += getEventTotalSize (d);
  22524. return d;
  22525. }
  22526. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer_) throw()
  22527. : buffer (buffer_),
  22528. data (buffer_.getData())
  22529. {
  22530. }
  22531. MidiBuffer::Iterator::~Iterator() throw()
  22532. {
  22533. }
  22534. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  22535. {
  22536. data = buffer.getData();
  22537. const uint8* dataEnd = data + buffer.bytesUsed;
  22538. while (data < dataEnd && getEventTime (data) < samplePosition)
  22539. data += getEventTotalSize (data);
  22540. }
  22541. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData, int& numBytes, int& samplePosition) throw()
  22542. {
  22543. if (data >= buffer.getData() + buffer.bytesUsed)
  22544. return false;
  22545. samplePosition = getEventTime (data);
  22546. numBytes = getEventDataSize (data);
  22547. data += sizeof (int) + sizeof (uint16);
  22548. midiData = data;
  22549. data += numBytes;
  22550. return true;
  22551. }
  22552. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result, int& samplePosition) throw()
  22553. {
  22554. if (data >= buffer.getData() + buffer.bytesUsed)
  22555. return false;
  22556. samplePosition = getEventTime (data);
  22557. const int numBytes = getEventDataSize (data);
  22558. data += sizeof (int) + sizeof (uint16);
  22559. result = MidiMessage (data, numBytes, samplePosition);
  22560. data += numBytes;
  22561. return true;
  22562. }
  22563. END_JUCE_NAMESPACE
  22564. /*** End of inlined file: juce_MidiBuffer.cpp ***/
  22565. /*** Start of inlined file: juce_MidiFile.cpp ***/
  22566. BEGIN_JUCE_NAMESPACE
  22567. namespace MidiFileHelpers
  22568. {
  22569. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  22570. {
  22571. unsigned int buffer = v & 0x7F;
  22572. while ((v >>= 7) != 0)
  22573. {
  22574. buffer <<= 8;
  22575. buffer |= ((v & 0x7F) | 0x80);
  22576. }
  22577. for (;;)
  22578. {
  22579. out.writeByte ((char) buffer);
  22580. if (buffer & 0x80)
  22581. buffer >>= 8;
  22582. else
  22583. break;
  22584. }
  22585. }
  22586. static bool parseMidiHeader (const uint8* &data, short& timeFormat, short& fileType, short& numberOfTracks) throw()
  22587. {
  22588. unsigned int ch = (int) ByteOrder::bigEndianInt (data);
  22589. data += 4;
  22590. if (ch != ByteOrder::bigEndianInt ("MThd"))
  22591. {
  22592. bool ok = false;
  22593. if (ch == ByteOrder::bigEndianInt ("RIFF"))
  22594. {
  22595. for (int i = 0; i < 8; ++i)
  22596. {
  22597. ch = ByteOrder::bigEndianInt (data);
  22598. data += 4;
  22599. if (ch == ByteOrder::bigEndianInt ("MThd"))
  22600. {
  22601. ok = true;
  22602. break;
  22603. }
  22604. }
  22605. }
  22606. if (! ok)
  22607. return false;
  22608. }
  22609. unsigned int bytesRemaining = ByteOrder::bigEndianInt (data);
  22610. data += 4;
  22611. fileType = (short) ByteOrder::bigEndianShort (data);
  22612. data += 2;
  22613. numberOfTracks = (short) ByteOrder::bigEndianShort (data);
  22614. data += 2;
  22615. timeFormat = (short) ByteOrder::bigEndianShort (data);
  22616. data += 2;
  22617. bytesRemaining -= 6;
  22618. data += bytesRemaining;
  22619. return true;
  22620. }
  22621. static double convertTicksToSeconds (const double time,
  22622. const MidiMessageSequence& tempoEvents,
  22623. const int timeFormat)
  22624. {
  22625. if (timeFormat > 0)
  22626. {
  22627. int numer = 4, denom = 4;
  22628. double tempoTime = 0.0, correctedTempoTime = 0.0;
  22629. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  22630. double secsPerTick = 0.5 * tickLen;
  22631. const int numEvents = tempoEvents.getNumEvents();
  22632. for (int i = 0; i < numEvents; ++i)
  22633. {
  22634. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  22635. if (time <= m.getTimeStamp())
  22636. break;
  22637. if (timeFormat > 0)
  22638. {
  22639. correctedTempoTime = correctedTempoTime
  22640. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  22641. }
  22642. else
  22643. {
  22644. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22645. }
  22646. tempoTime = m.getTimeStamp();
  22647. if (m.isTempoMetaEvent())
  22648. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  22649. else if (m.isTimeSignatureMetaEvent())
  22650. m.getTimeSignatureInfo (numer, denom);
  22651. while (i + 1 < numEvents)
  22652. {
  22653. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  22654. if (m2.getTimeStamp() == tempoTime)
  22655. {
  22656. ++i;
  22657. if (m2.isTempoMetaEvent())
  22658. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  22659. else if (m2.isTimeSignatureMetaEvent())
  22660. m2.getTimeSignatureInfo (numer, denom);
  22661. }
  22662. else
  22663. {
  22664. break;
  22665. }
  22666. }
  22667. }
  22668. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  22669. }
  22670. else
  22671. {
  22672. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  22673. }
  22674. }
  22675. // a comparator that puts all the note-offs before note-ons that have the same time
  22676. struct Sorter
  22677. {
  22678. static int compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  22679. const MidiMessageSequence::MidiEventHolder* const second) throw()
  22680. {
  22681. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  22682. if (diff == 0)
  22683. {
  22684. if (first->message.isNoteOff() && second->message.isNoteOn())
  22685. return -1;
  22686. else if (first->message.isNoteOn() && second->message.isNoteOff())
  22687. return 1;
  22688. else
  22689. return 0;
  22690. }
  22691. else
  22692. {
  22693. return (diff > 0) ? 1 : -1;
  22694. }
  22695. }
  22696. };
  22697. }
  22698. MidiFile::MidiFile()
  22699. : timeFormat ((short) (unsigned short) 0xe728)
  22700. {
  22701. }
  22702. MidiFile::~MidiFile()
  22703. {
  22704. clear();
  22705. }
  22706. void MidiFile::clear()
  22707. {
  22708. tracks.clear();
  22709. }
  22710. int MidiFile::getNumTracks() const throw()
  22711. {
  22712. return tracks.size();
  22713. }
  22714. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  22715. {
  22716. return tracks [index];
  22717. }
  22718. void MidiFile::addTrack (const MidiMessageSequence& trackSequence)
  22719. {
  22720. tracks.add (new MidiMessageSequence (trackSequence));
  22721. }
  22722. short MidiFile::getTimeFormat() const throw()
  22723. {
  22724. return timeFormat;
  22725. }
  22726. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  22727. {
  22728. timeFormat = (short) ticks;
  22729. }
  22730. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  22731. const int subframeResolution) throw()
  22732. {
  22733. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  22734. }
  22735. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  22736. {
  22737. for (int i = tracks.size(); --i >= 0;)
  22738. {
  22739. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22740. for (int j = 0; j < numEvents; ++j)
  22741. {
  22742. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22743. if (m.isTempoMetaEvent())
  22744. tempoChangeEvents.addEvent (m);
  22745. }
  22746. }
  22747. }
  22748. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  22749. {
  22750. for (int i = tracks.size(); --i >= 0;)
  22751. {
  22752. const int numEvents = tracks.getUnchecked(i)->getNumEvents();
  22753. for (int j = 0; j < numEvents; ++j)
  22754. {
  22755. const MidiMessage& m = tracks.getUnchecked(i)->getEventPointer (j)->message;
  22756. if (m.isTimeSignatureMetaEvent())
  22757. timeSigEvents.addEvent (m);
  22758. }
  22759. }
  22760. }
  22761. double MidiFile::getLastTimestamp() const
  22762. {
  22763. double t = 0.0;
  22764. for (int i = tracks.size(); --i >= 0;)
  22765. t = jmax (t, tracks.getUnchecked(i)->getEndTime());
  22766. return t;
  22767. }
  22768. bool MidiFile::readFrom (InputStream& sourceStream)
  22769. {
  22770. clear();
  22771. MemoryBlock data;
  22772. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  22773. // (put a sanity-check on the file size, as midi files are generally small)
  22774. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  22775. {
  22776. size_t size = data.getSize();
  22777. const uint8* d = static_cast <const uint8*> (data.getData());
  22778. short fileType, expectedTracks;
  22779. if (size > 16 && MidiFileHelpers::parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  22780. {
  22781. size -= (int) (d - static_cast <const uint8*> (data.getData()));
  22782. int track = 0;
  22783. while (size > 0 && track < expectedTracks)
  22784. {
  22785. const int chunkType = (int) ByteOrder::bigEndianInt (d);
  22786. d += 4;
  22787. const int chunkSize = (int) ByteOrder::bigEndianInt (d);
  22788. d += 4;
  22789. if (chunkSize <= 0)
  22790. break;
  22791. if (size < 0)
  22792. return false;
  22793. if (chunkType == (int) ByteOrder::bigEndianInt ("MTrk"))
  22794. {
  22795. readNextTrack (d, chunkSize);
  22796. }
  22797. size -= chunkSize + 8;
  22798. d += chunkSize;
  22799. ++track;
  22800. }
  22801. return true;
  22802. }
  22803. }
  22804. return false;
  22805. }
  22806. void MidiFile::readNextTrack (const uint8* data, int size)
  22807. {
  22808. double time = 0;
  22809. char lastStatusByte = 0;
  22810. MidiMessageSequence result;
  22811. while (size > 0)
  22812. {
  22813. int bytesUsed;
  22814. const int delay = MidiMessage::readVariableLengthVal (data, bytesUsed);
  22815. data += bytesUsed;
  22816. size -= bytesUsed;
  22817. time += delay;
  22818. int messSize = 0;
  22819. const MidiMessage mm (data, size, messSize, lastStatusByte, time);
  22820. if (messSize <= 0)
  22821. break;
  22822. size -= messSize;
  22823. data += messSize;
  22824. result.addEvent (mm);
  22825. const char firstByte = *(mm.getRawData());
  22826. if ((firstByte & 0xf0) != 0xf0)
  22827. lastStatusByte = firstByte;
  22828. }
  22829. // use a sort that puts all the note-offs before note-ons that have the same time
  22830. MidiFileHelpers::Sorter sorter;
  22831. result.list.sort (sorter, true);
  22832. result.updateMatchedPairs();
  22833. addTrack (result);
  22834. }
  22835. void MidiFile::convertTimestampTicksToSeconds()
  22836. {
  22837. MidiMessageSequence tempoEvents;
  22838. findAllTempoEvents (tempoEvents);
  22839. findAllTimeSigEvents (tempoEvents);
  22840. for (int i = 0; i < tracks.size(); ++i)
  22841. {
  22842. MidiMessageSequence& ms = *tracks.getUnchecked(i);
  22843. for (int j = ms.getNumEvents(); --j >= 0;)
  22844. {
  22845. MidiMessage& m = ms.getEventPointer(j)->message;
  22846. m.setTimeStamp (MidiFileHelpers::convertTicksToSeconds (m.getTimeStamp(),
  22847. tempoEvents,
  22848. timeFormat));
  22849. }
  22850. }
  22851. }
  22852. bool MidiFile::writeTo (OutputStream& out)
  22853. {
  22854. out.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MThd"));
  22855. out.writeIntBigEndian (6);
  22856. out.writeShortBigEndian (1); // type
  22857. out.writeShortBigEndian ((short) tracks.size());
  22858. out.writeShortBigEndian (timeFormat);
  22859. for (int i = 0; i < tracks.size(); ++i)
  22860. writeTrack (out, i);
  22861. out.flush();
  22862. return true;
  22863. }
  22864. void MidiFile::writeTrack (OutputStream& mainOut,
  22865. const int trackNum)
  22866. {
  22867. MemoryOutputStream out;
  22868. const MidiMessageSequence& ms = *tracks[trackNum];
  22869. int lastTick = 0;
  22870. char lastStatusByte = 0;
  22871. for (int i = 0; i < ms.getNumEvents(); ++i)
  22872. {
  22873. const MidiMessage& mm = ms.getEventPointer(i)->message;
  22874. const int tick = roundToInt (mm.getTimeStamp());
  22875. const int delta = jmax (0, tick - lastTick);
  22876. MidiFileHelpers::writeVariableLengthInt (out, delta);
  22877. lastTick = tick;
  22878. const char statusByte = *(mm.getRawData());
  22879. if ((statusByte == lastStatusByte)
  22880. && ((statusByte & 0xf0) != 0xf0)
  22881. && i > 0
  22882. && mm.getRawDataSize() > 1)
  22883. {
  22884. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  22885. }
  22886. else
  22887. {
  22888. out.write (mm.getRawData(), mm.getRawDataSize());
  22889. }
  22890. lastStatusByte = statusByte;
  22891. }
  22892. out.writeByte (0);
  22893. const MidiMessage m (MidiMessage::endOfTrack());
  22894. out.write (m.getRawData(),
  22895. m.getRawDataSize());
  22896. mainOut.writeIntBigEndian ((int) ByteOrder::bigEndianInt ("MTrk"));
  22897. mainOut.writeIntBigEndian ((int) out.getDataSize());
  22898. mainOut.write (out.getData(), (int) out.getDataSize());
  22899. }
  22900. END_JUCE_NAMESPACE
  22901. /*** End of inlined file: juce_MidiFile.cpp ***/
  22902. /*** Start of inlined file: juce_MidiKeyboardState.cpp ***/
  22903. BEGIN_JUCE_NAMESPACE
  22904. MidiKeyboardState::MidiKeyboardState()
  22905. {
  22906. zerostruct (noteStates);
  22907. }
  22908. MidiKeyboardState::~MidiKeyboardState()
  22909. {
  22910. }
  22911. void MidiKeyboardState::reset()
  22912. {
  22913. const ScopedLock sl (lock);
  22914. zerostruct (noteStates);
  22915. eventsToAdd.clear();
  22916. }
  22917. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  22918. {
  22919. jassert (midiChannel >= 0 && midiChannel <= 16);
  22920. return ((unsigned int) n) < 128
  22921. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  22922. }
  22923. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  22924. {
  22925. return ((unsigned int) n) < 128
  22926. && (noteStates[n] & midiChannelMask) != 0;
  22927. }
  22928. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  22929. {
  22930. jassert (midiChannel >= 0 && midiChannel <= 16);
  22931. jassert (((unsigned int) midiNoteNumber) < 128);
  22932. const ScopedLock sl (lock);
  22933. if (((unsigned int) midiNoteNumber) < 128)
  22934. {
  22935. const int timeNow = (int) Time::getMillisecondCounter();
  22936. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  22937. eventsToAdd.clear (0, timeNow - 500);
  22938. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  22939. }
  22940. }
  22941. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  22942. {
  22943. if (((unsigned int) midiNoteNumber) < 128)
  22944. {
  22945. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  22946. for (int i = listeners.size(); --i >= 0;)
  22947. listeners.getUnchecked(i)->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  22948. }
  22949. }
  22950. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  22951. {
  22952. const ScopedLock sl (lock);
  22953. if (isNoteOn (midiChannel, midiNoteNumber))
  22954. {
  22955. const int timeNow = (int) Time::getMillisecondCounter();
  22956. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  22957. eventsToAdd.clear (0, timeNow - 500);
  22958. noteOffInternal (midiChannel, midiNoteNumber);
  22959. }
  22960. }
  22961. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  22962. {
  22963. if (isNoteOn (midiChannel, midiNoteNumber))
  22964. {
  22965. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  22966. for (int i = listeners.size(); --i >= 0;)
  22967. listeners.getUnchecked(i)->handleNoteOff (this, midiChannel, midiNoteNumber);
  22968. }
  22969. }
  22970. void MidiKeyboardState::allNotesOff (const int midiChannel)
  22971. {
  22972. const ScopedLock sl (lock);
  22973. if (midiChannel <= 0)
  22974. {
  22975. for (int i = 1; i <= 16; ++i)
  22976. allNotesOff (i);
  22977. }
  22978. else
  22979. {
  22980. for (int i = 0; i < 128; ++i)
  22981. noteOff (midiChannel, i);
  22982. }
  22983. }
  22984. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  22985. {
  22986. if (message.isNoteOn())
  22987. {
  22988. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  22989. }
  22990. else if (message.isNoteOff())
  22991. {
  22992. noteOffInternal (message.getChannel(), message.getNoteNumber());
  22993. }
  22994. else if (message.isAllNotesOff())
  22995. {
  22996. for (int i = 0; i < 128; ++i)
  22997. noteOffInternal (message.getChannel(), i);
  22998. }
  22999. }
  23000. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  23001. const int startSample,
  23002. const int numSamples,
  23003. const bool injectIndirectEvents)
  23004. {
  23005. MidiBuffer::Iterator i (buffer);
  23006. MidiMessage message (0xf4, 0.0);
  23007. int time;
  23008. const ScopedLock sl (lock);
  23009. while (i.getNextEvent (message, time))
  23010. processNextMidiEvent (message);
  23011. if (injectIndirectEvents)
  23012. {
  23013. MidiBuffer::Iterator i2 (eventsToAdd);
  23014. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  23015. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  23016. while (i2.getNextEvent (message, time))
  23017. {
  23018. const int pos = jlimit (0, numSamples - 1, roundToInt ((time - firstEventToAdd) * scaleFactor));
  23019. buffer.addEvent (message, startSample + pos);
  23020. }
  23021. }
  23022. eventsToAdd.clear();
  23023. }
  23024. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener)
  23025. {
  23026. const ScopedLock sl (lock);
  23027. listeners.addIfNotAlreadyThere (listener);
  23028. }
  23029. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener)
  23030. {
  23031. const ScopedLock sl (lock);
  23032. listeners.removeValue (listener);
  23033. }
  23034. END_JUCE_NAMESPACE
  23035. /*** End of inlined file: juce_MidiKeyboardState.cpp ***/
  23036. /*** Start of inlined file: juce_MidiMessage.cpp ***/
  23037. BEGIN_JUCE_NAMESPACE
  23038. int MidiMessage::readVariableLengthVal (const uint8* data, int& numBytesUsed) throw()
  23039. {
  23040. numBytesUsed = 0;
  23041. int v = 0;
  23042. int i;
  23043. do
  23044. {
  23045. i = (int) *data++;
  23046. if (++numBytesUsed > 6)
  23047. break;
  23048. v = (v << 7) + (i & 0x7f);
  23049. } while (i & 0x80);
  23050. return v;
  23051. }
  23052. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  23053. {
  23054. // this method only works for valid starting bytes of a short midi message
  23055. jassert (firstByte >= 0x80
  23056. && firstByte != 0xf0
  23057. && firstByte != 0xf7);
  23058. static const char messageLengths[] =
  23059. {
  23060. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23061. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23062. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23063. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23064. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23065. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  23066. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  23067. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  23068. };
  23069. return messageLengths [firstByte & 0x7f];
  23070. }
  23071. MidiMessage::MidiMessage (const void* const d, const int dataSize, const double t)
  23072. : timeStamp (t),
  23073. size (dataSize)
  23074. {
  23075. jassert (dataSize > 0);
  23076. if (dataSize <= 4)
  23077. data = static_cast<uint8*> (preallocatedData.asBytes);
  23078. else
  23079. data = new uint8 [dataSize];
  23080. memcpy (data, d, dataSize);
  23081. // check that the length matches the data..
  23082. jassert (size > 3 || data[0] >= 0xf0 || getMessageLengthFromFirstByte (data[0]) == size);
  23083. }
  23084. MidiMessage::MidiMessage (const int byte1, const double t) throw()
  23085. : timeStamp (t),
  23086. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23087. size (1)
  23088. {
  23089. data[0] = (uint8) byte1;
  23090. // check that the length matches the data..
  23091. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  23092. }
  23093. MidiMessage::MidiMessage (const int byte1, const int byte2, const double t) throw()
  23094. : timeStamp (t),
  23095. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23096. size (2)
  23097. {
  23098. data[0] = (uint8) byte1;
  23099. data[1] = (uint8) byte2;
  23100. // check that the length matches the data..
  23101. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  23102. }
  23103. MidiMessage::MidiMessage (const int byte1, const int byte2, const int byte3, const double t) throw()
  23104. : timeStamp (t),
  23105. data (static_cast<uint8*> (preallocatedData.asBytes)),
  23106. size (3)
  23107. {
  23108. data[0] = (uint8) byte1;
  23109. data[1] = (uint8) byte2;
  23110. data[2] = (uint8) byte3;
  23111. // check that the length matches the data..
  23112. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  23113. }
  23114. MidiMessage::MidiMessage (const MidiMessage& other)
  23115. : timeStamp (other.timeStamp),
  23116. size (other.size)
  23117. {
  23118. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23119. {
  23120. data = new uint8 [size];
  23121. memcpy (data, other.data, size);
  23122. }
  23123. else
  23124. {
  23125. data = static_cast<uint8*> (preallocatedData.asBytes);
  23126. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23127. }
  23128. }
  23129. MidiMessage::MidiMessage (const MidiMessage& other, const double newTimeStamp)
  23130. : timeStamp (newTimeStamp),
  23131. size (other.size)
  23132. {
  23133. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23134. {
  23135. data = new uint8 [size];
  23136. memcpy (data, other.data, size);
  23137. }
  23138. else
  23139. {
  23140. data = static_cast<uint8*> (preallocatedData.asBytes);
  23141. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23142. }
  23143. }
  23144. MidiMessage::MidiMessage (const void* src_, int sz, int& numBytesUsed, const uint8 lastStatusByte, double t)
  23145. : timeStamp (t),
  23146. data (static_cast<uint8*> (preallocatedData.asBytes))
  23147. {
  23148. const uint8* src = static_cast <const uint8*> (src_);
  23149. unsigned int byte = (unsigned int) *src;
  23150. if (byte < 0x80)
  23151. {
  23152. byte = (unsigned int) (uint8) lastStatusByte;
  23153. numBytesUsed = -1;
  23154. }
  23155. else
  23156. {
  23157. numBytesUsed = 0;
  23158. --sz;
  23159. ++src;
  23160. }
  23161. if (byte >= 0x80)
  23162. {
  23163. if (byte == 0xf0)
  23164. {
  23165. const uint8* d = src;
  23166. while (d < src + sz)
  23167. {
  23168. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  23169. {
  23170. if (*d == 0xf7) // include an 0xf7 if we hit one
  23171. ++d;
  23172. break;
  23173. }
  23174. ++d;
  23175. }
  23176. size = 1 + (int) (d - src);
  23177. data = new uint8 [size];
  23178. *data = (uint8) byte;
  23179. memcpy (data + 1, src, size - 1);
  23180. }
  23181. else if (byte == 0xff)
  23182. {
  23183. int n;
  23184. const int bytesLeft = readVariableLengthVal (src + 1, n);
  23185. size = jmin (sz + 1, n + 2 + bytesLeft);
  23186. data = new uint8 [size];
  23187. *data = (uint8) byte;
  23188. memcpy (data + 1, src, size - 1);
  23189. }
  23190. else
  23191. {
  23192. preallocatedData.asInt32 = 0;
  23193. size = getMessageLengthFromFirstByte ((uint8) byte);
  23194. data[0] = (uint8) byte;
  23195. if (size > 1)
  23196. {
  23197. data[1] = src[0];
  23198. if (size > 2)
  23199. data[2] = src[1];
  23200. }
  23201. }
  23202. numBytesUsed += size;
  23203. }
  23204. else
  23205. {
  23206. preallocatedData.asInt32 = 0;
  23207. size = 0;
  23208. }
  23209. }
  23210. MidiMessage& MidiMessage::operator= (const MidiMessage& other)
  23211. {
  23212. if (this != &other)
  23213. {
  23214. timeStamp = other.timeStamp;
  23215. size = other.size;
  23216. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23217. delete[] data;
  23218. if (other.data != static_cast <const uint8*> (other.preallocatedData.asBytes))
  23219. {
  23220. data = new uint8 [size];
  23221. memcpy (data, other.data, size);
  23222. }
  23223. else
  23224. {
  23225. data = static_cast<uint8*> (preallocatedData.asBytes);
  23226. preallocatedData.asInt32 = other.preallocatedData.asInt32;
  23227. }
  23228. }
  23229. return *this;
  23230. }
  23231. MidiMessage::~MidiMessage()
  23232. {
  23233. if (data != static_cast <const uint8*> (preallocatedData.asBytes))
  23234. delete[] data;
  23235. }
  23236. int MidiMessage::getChannel() const throw()
  23237. {
  23238. if ((data[0] & 0xf0) != 0xf0)
  23239. return (data[0] & 0xf) + 1;
  23240. else
  23241. return 0;
  23242. }
  23243. bool MidiMessage::isForChannel (const int channel) const throw()
  23244. {
  23245. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23246. return ((data[0] & 0xf) == channel - 1)
  23247. && ((data[0] & 0xf0) != 0xf0);
  23248. }
  23249. void MidiMessage::setChannel (const int channel) throw()
  23250. {
  23251. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23252. if ((data[0] & 0xf0) != (uint8) 0xf0)
  23253. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  23254. | (uint8)(channel - 1));
  23255. }
  23256. bool MidiMessage::isNoteOn (const bool returnTrueForVelocity0) const throw()
  23257. {
  23258. return ((data[0] & 0xf0) == 0x90)
  23259. && (returnTrueForVelocity0 || data[2] != 0);
  23260. }
  23261. bool MidiMessage::isNoteOff (const bool returnTrueForNoteOnVelocity0) const throw()
  23262. {
  23263. return ((data[0] & 0xf0) == 0x80)
  23264. || (returnTrueForNoteOnVelocity0 && (data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  23265. }
  23266. bool MidiMessage::isNoteOnOrOff() const throw()
  23267. {
  23268. const int d = data[0] & 0xf0;
  23269. return (d == 0x90) || (d == 0x80);
  23270. }
  23271. int MidiMessage::getNoteNumber() const throw()
  23272. {
  23273. return data[1];
  23274. }
  23275. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  23276. {
  23277. if (isNoteOnOrOff())
  23278. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  23279. }
  23280. uint8 MidiMessage::getVelocity() const throw()
  23281. {
  23282. if (isNoteOnOrOff())
  23283. return data[2];
  23284. else
  23285. return 0;
  23286. }
  23287. float MidiMessage::getFloatVelocity() const throw()
  23288. {
  23289. return getVelocity() * (1.0f / 127.0f);
  23290. }
  23291. void MidiMessage::setVelocity (const float newVelocity) throw()
  23292. {
  23293. if (isNoteOnOrOff())
  23294. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (newVelocity * 127.0f));
  23295. }
  23296. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  23297. {
  23298. if (isNoteOnOrOff())
  23299. data[2] = (uint8) jlimit (0, 0x7f, roundToInt (scaleFactor * data[2]));
  23300. }
  23301. bool MidiMessage::isAftertouch() const throw()
  23302. {
  23303. return (data[0] & 0xf0) == 0xa0;
  23304. }
  23305. int MidiMessage::getAfterTouchValue() const throw()
  23306. {
  23307. return data[2];
  23308. }
  23309. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  23310. const int noteNum,
  23311. const int aftertouchValue) throw()
  23312. {
  23313. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23314. jassert (((unsigned int) noteNum) <= 127);
  23315. jassert (((unsigned int) aftertouchValue) <= 127);
  23316. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  23317. noteNum & 0x7f,
  23318. aftertouchValue & 0x7f);
  23319. }
  23320. bool MidiMessage::isChannelPressure() const throw()
  23321. {
  23322. return (data[0] & 0xf0) == 0xd0;
  23323. }
  23324. int MidiMessage::getChannelPressureValue() const throw()
  23325. {
  23326. jassert (isChannelPressure());
  23327. return data[1];
  23328. }
  23329. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  23330. const int pressure) throw()
  23331. {
  23332. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23333. jassert (((unsigned int) pressure) <= 127);
  23334. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  23335. pressure & 0x7f);
  23336. }
  23337. bool MidiMessage::isProgramChange() const throw()
  23338. {
  23339. return (data[0] & 0xf0) == 0xc0;
  23340. }
  23341. int MidiMessage::getProgramChangeNumber() const throw()
  23342. {
  23343. return data[1];
  23344. }
  23345. const MidiMessage MidiMessage::programChange (const int channel,
  23346. const int programNumber) throw()
  23347. {
  23348. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23349. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  23350. programNumber & 0x7f);
  23351. }
  23352. bool MidiMessage::isPitchWheel() const throw()
  23353. {
  23354. return (data[0] & 0xf0) == 0xe0;
  23355. }
  23356. int MidiMessage::getPitchWheelValue() const throw()
  23357. {
  23358. return data[1] | (data[2] << 7);
  23359. }
  23360. const MidiMessage MidiMessage::pitchWheel (const int channel,
  23361. const int position) throw()
  23362. {
  23363. jassert (channel > 0 && channel <= 16); // valid channels are numbered 1 to 16
  23364. jassert (((unsigned int) position) <= 0x3fff);
  23365. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  23366. position & 127,
  23367. (position >> 7) & 127);
  23368. }
  23369. bool MidiMessage::isController() const throw()
  23370. {
  23371. return (data[0] & 0xf0) == 0xb0;
  23372. }
  23373. int MidiMessage::getControllerNumber() const throw()
  23374. {
  23375. jassert (isController());
  23376. return data[1];
  23377. }
  23378. int MidiMessage::getControllerValue() const throw()
  23379. {
  23380. jassert (isController());
  23381. return data[2];
  23382. }
  23383. const MidiMessage MidiMessage::controllerEvent (const int channel,
  23384. const int controllerType,
  23385. const int value) throw()
  23386. {
  23387. // the channel must be between 1 and 16 inclusive
  23388. jassert (channel > 0 && channel <= 16);
  23389. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  23390. controllerType & 127,
  23391. value & 127);
  23392. }
  23393. const MidiMessage MidiMessage::noteOn (const int channel,
  23394. const int noteNumber,
  23395. const float velocity) throw()
  23396. {
  23397. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  23398. }
  23399. const MidiMessage MidiMessage::noteOn (const int channel,
  23400. const int noteNumber,
  23401. const uint8 velocity) throw()
  23402. {
  23403. jassert (channel > 0 && channel <= 16);
  23404. jassert (((unsigned int) noteNumber) <= 127);
  23405. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  23406. noteNumber & 127,
  23407. jlimit (0, 127, roundToInt (velocity)));
  23408. }
  23409. const MidiMessage MidiMessage::noteOff (const int channel,
  23410. const int noteNumber) throw()
  23411. {
  23412. jassert (channel > 0 && channel <= 16);
  23413. jassert (((unsigned int) noteNumber) <= 127);
  23414. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  23415. }
  23416. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  23417. {
  23418. return controllerEvent (channel, 123, 0);
  23419. }
  23420. bool MidiMessage::isAllNotesOff() const throw()
  23421. {
  23422. return (data[0] & 0xf0) == 0xb0
  23423. && data[1] == 123;
  23424. }
  23425. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  23426. {
  23427. return controllerEvent (channel, 120, 0);
  23428. }
  23429. bool MidiMessage::isAllSoundOff() const throw()
  23430. {
  23431. return (data[0] & 0xf0) == 0xb0
  23432. && data[1] == 120;
  23433. }
  23434. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  23435. {
  23436. return controllerEvent (channel, 121, 0);
  23437. }
  23438. const MidiMessage MidiMessage::masterVolume (const float volume)
  23439. {
  23440. const int vol = jlimit (0, 0x3fff, roundToInt (volume * 0x4000));
  23441. uint8 buf[8];
  23442. buf[0] = 0xf0;
  23443. buf[1] = 0x7f;
  23444. buf[2] = 0x7f;
  23445. buf[3] = 0x04;
  23446. buf[4] = 0x01;
  23447. buf[5] = (uint8) (vol & 0x7f);
  23448. buf[6] = (uint8) (vol >> 7);
  23449. buf[7] = 0xf7;
  23450. return MidiMessage (buf, 8);
  23451. }
  23452. bool MidiMessage::isSysEx() const throw()
  23453. {
  23454. return *data == 0xf0;
  23455. }
  23456. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData, const int dataSize)
  23457. {
  23458. MemoryBlock mm (dataSize + 2);
  23459. uint8* const m = static_cast <uint8*> (mm.getData());
  23460. m[0] = 0xf0;
  23461. memcpy (m + 1, sysexData, dataSize);
  23462. m[dataSize + 1] = 0xf7;
  23463. return MidiMessage (m, dataSize + 2);
  23464. }
  23465. const uint8* MidiMessage::getSysExData() const throw()
  23466. {
  23467. return (isSysEx()) ? getRawData() + 1 : 0;
  23468. }
  23469. int MidiMessage::getSysExDataSize() const throw()
  23470. {
  23471. return (isSysEx()) ? size - 2 : 0;
  23472. }
  23473. bool MidiMessage::isMetaEvent() const throw()
  23474. {
  23475. return *data == 0xff;
  23476. }
  23477. bool MidiMessage::isActiveSense() const throw()
  23478. {
  23479. return *data == 0xfe;
  23480. }
  23481. int MidiMessage::getMetaEventType() const throw()
  23482. {
  23483. if (*data != 0xff)
  23484. return -1;
  23485. else
  23486. return data[1];
  23487. }
  23488. int MidiMessage::getMetaEventLength() const throw()
  23489. {
  23490. if (*data == 0xff)
  23491. {
  23492. int n;
  23493. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  23494. }
  23495. return 0;
  23496. }
  23497. const uint8* MidiMessage::getMetaEventData() const throw()
  23498. {
  23499. int n;
  23500. const uint8* d = data + 2;
  23501. readVariableLengthVal (d, n);
  23502. return d + n;
  23503. }
  23504. bool MidiMessage::isTrackMetaEvent() const throw()
  23505. {
  23506. return getMetaEventType() == 0;
  23507. }
  23508. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  23509. {
  23510. return getMetaEventType() == 47;
  23511. }
  23512. bool MidiMessage::isTextMetaEvent() const throw()
  23513. {
  23514. const int t = getMetaEventType();
  23515. return t > 0 && t < 16;
  23516. }
  23517. const String MidiMessage::getTextFromTextMetaEvent() const
  23518. {
  23519. return String (reinterpret_cast <const char*> (getMetaEventData()), getMetaEventLength());
  23520. }
  23521. bool MidiMessage::isTrackNameEvent() const throw()
  23522. {
  23523. return (data[1] == 3)
  23524. && (*data == 0xff);
  23525. }
  23526. bool MidiMessage::isTempoMetaEvent() const throw()
  23527. {
  23528. return (data[1] == 81)
  23529. && (*data == 0xff);
  23530. }
  23531. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  23532. {
  23533. return (data[1] == 0x20)
  23534. && (*data == 0xff)
  23535. && (data[2] == 1);
  23536. }
  23537. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  23538. {
  23539. return data[3] + 1;
  23540. }
  23541. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  23542. {
  23543. if (! isTempoMetaEvent())
  23544. return 0.0;
  23545. const uint8* const d = getMetaEventData();
  23546. return (((unsigned int) d[0] << 16)
  23547. | ((unsigned int) d[1] << 8)
  23548. | d[2])
  23549. / 1000000.0;
  23550. }
  23551. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  23552. {
  23553. if (timeFormat > 0)
  23554. {
  23555. if (! isTempoMetaEvent())
  23556. return 0.5 / timeFormat;
  23557. return getTempoSecondsPerQuarterNote() / timeFormat;
  23558. }
  23559. else
  23560. {
  23561. const int frameCode = (-timeFormat) >> 8;
  23562. double framesPerSecond;
  23563. switch (frameCode)
  23564. {
  23565. case 24: framesPerSecond = 24.0; break;
  23566. case 25: framesPerSecond = 25.0; break;
  23567. case 29: framesPerSecond = 29.97; break;
  23568. case 30: framesPerSecond = 30.0; break;
  23569. default: framesPerSecond = 30.0; break;
  23570. }
  23571. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  23572. }
  23573. }
  23574. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  23575. {
  23576. uint8 d[8];
  23577. d[0] = 0xff;
  23578. d[1] = 81;
  23579. d[2] = 3;
  23580. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  23581. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  23582. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  23583. return MidiMessage (d, 6, 0.0);
  23584. }
  23585. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  23586. {
  23587. return (data[1] == 0x58)
  23588. && (*data == (uint8) 0xff);
  23589. }
  23590. void MidiMessage::getTimeSignatureInfo (int& numerator, int& denominator) const throw()
  23591. {
  23592. if (isTimeSignatureMetaEvent())
  23593. {
  23594. const uint8* const d = getMetaEventData();
  23595. numerator = d[0];
  23596. denominator = 1 << d[1];
  23597. }
  23598. else
  23599. {
  23600. numerator = 4;
  23601. denominator = 4;
  23602. }
  23603. }
  23604. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator, const int denominator)
  23605. {
  23606. uint8 d[8];
  23607. d[0] = 0xff;
  23608. d[1] = 0x58;
  23609. d[2] = 0x04;
  23610. d[3] = (uint8) numerator;
  23611. int n = 1;
  23612. int powerOfTwo = 0;
  23613. while (n < denominator)
  23614. {
  23615. n <<= 1;
  23616. ++powerOfTwo;
  23617. }
  23618. d[4] = (uint8) powerOfTwo;
  23619. d[5] = 0x01;
  23620. d[6] = 96;
  23621. return MidiMessage (d, 7, 0.0);
  23622. }
  23623. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  23624. {
  23625. uint8 d[8];
  23626. d[0] = 0xff;
  23627. d[1] = 0x20;
  23628. d[2] = 0x01;
  23629. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  23630. return MidiMessage (d, 4, 0.0);
  23631. }
  23632. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  23633. {
  23634. return getMetaEventType() == 89;
  23635. }
  23636. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  23637. {
  23638. return (int) *getMetaEventData();
  23639. }
  23640. const MidiMessage MidiMessage::endOfTrack() throw()
  23641. {
  23642. return MidiMessage (0xff, 0x2f, 0, 0.0);
  23643. }
  23644. bool MidiMessage::isSongPositionPointer() const throw()
  23645. {
  23646. return *data == 0xf2;
  23647. }
  23648. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  23649. {
  23650. return data[1] | (data[2] << 7);
  23651. }
  23652. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  23653. {
  23654. return MidiMessage (0xf2,
  23655. positionInMidiBeats & 127,
  23656. (positionInMidiBeats >> 7) & 127);
  23657. }
  23658. bool MidiMessage::isMidiStart() const throw()
  23659. {
  23660. return *data == 0xfa;
  23661. }
  23662. const MidiMessage MidiMessage::midiStart() throw()
  23663. {
  23664. return MidiMessage (0xfa);
  23665. }
  23666. bool MidiMessage::isMidiContinue() const throw()
  23667. {
  23668. return *data == 0xfb;
  23669. }
  23670. const MidiMessage MidiMessage::midiContinue() throw()
  23671. {
  23672. return MidiMessage (0xfb);
  23673. }
  23674. bool MidiMessage::isMidiStop() const throw()
  23675. {
  23676. return *data == 0xfc;
  23677. }
  23678. const MidiMessage MidiMessage::midiStop() throw()
  23679. {
  23680. return MidiMessage (0xfc);
  23681. }
  23682. bool MidiMessage::isMidiClock() const throw()
  23683. {
  23684. return *data == 0xf8;
  23685. }
  23686. const MidiMessage MidiMessage::midiClock() throw()
  23687. {
  23688. return MidiMessage (0xf8);
  23689. }
  23690. bool MidiMessage::isQuarterFrame() const throw()
  23691. {
  23692. return *data == 0xf1;
  23693. }
  23694. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  23695. {
  23696. return ((int) data[1]) >> 4;
  23697. }
  23698. int MidiMessage::getQuarterFrameValue() const throw()
  23699. {
  23700. return ((int) data[1]) & 0x0f;
  23701. }
  23702. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  23703. const int value) throw()
  23704. {
  23705. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  23706. }
  23707. bool MidiMessage::isFullFrame() const throw()
  23708. {
  23709. return data[0] == 0xf0
  23710. && data[1] == 0x7f
  23711. && size >= 10
  23712. && data[3] == 0x01
  23713. && data[4] == 0x01;
  23714. }
  23715. void MidiMessage::getFullFrameParameters (int& hours,
  23716. int& minutes,
  23717. int& seconds,
  23718. int& frames,
  23719. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  23720. {
  23721. jassert (isFullFrame());
  23722. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  23723. hours = data[5] & 0x1f;
  23724. minutes = data[6];
  23725. seconds = data[7];
  23726. frames = data[8];
  23727. }
  23728. const MidiMessage MidiMessage::fullFrame (const int hours,
  23729. const int minutes,
  23730. const int seconds,
  23731. const int frames,
  23732. MidiMessage::SmpteTimecodeType timecodeType)
  23733. {
  23734. uint8 d[10];
  23735. d[0] = 0xf0;
  23736. d[1] = 0x7f;
  23737. d[2] = 0x7f;
  23738. d[3] = 0x01;
  23739. d[4] = 0x01;
  23740. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  23741. d[6] = (uint8) minutes;
  23742. d[7] = (uint8) seconds;
  23743. d[8] = (uint8) frames;
  23744. d[9] = 0xf7;
  23745. return MidiMessage (d, 10, 0.0);
  23746. }
  23747. bool MidiMessage::isMidiMachineControlMessage() const throw()
  23748. {
  23749. return data[0] == 0xf0
  23750. && data[1] == 0x7f
  23751. && data[3] == 0x06
  23752. && size > 5;
  23753. }
  23754. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  23755. {
  23756. jassert (isMidiMachineControlMessage());
  23757. return (MidiMachineControlCommand) data[4];
  23758. }
  23759. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  23760. {
  23761. uint8 d[6];
  23762. d[0] = 0xf0;
  23763. d[1] = 0x7f;
  23764. d[2] = 0x00;
  23765. d[3] = 0x06;
  23766. d[4] = (uint8) command;
  23767. d[5] = 0xf7;
  23768. return MidiMessage (d, 6, 0.0);
  23769. }
  23770. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  23771. int& minutes,
  23772. int& seconds,
  23773. int& frames) const throw()
  23774. {
  23775. if (size >= 12
  23776. && data[0] == 0xf0
  23777. && data[1] == 0x7f
  23778. && data[3] == 0x06
  23779. && data[4] == 0x44
  23780. && data[5] == 0x06
  23781. && data[6] == 0x01)
  23782. {
  23783. hours = data[7] % 24; // (that some machines send out hours > 24)
  23784. minutes = data[8];
  23785. seconds = data[9];
  23786. frames = data[10];
  23787. return true;
  23788. }
  23789. return false;
  23790. }
  23791. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  23792. int minutes,
  23793. int seconds,
  23794. int frames)
  23795. {
  23796. uint8 d[12];
  23797. d[0] = 0xf0;
  23798. d[1] = 0x7f;
  23799. d[2] = 0x00;
  23800. d[3] = 0x06;
  23801. d[4] = 0x44;
  23802. d[5] = 0x06;
  23803. d[6] = 0x01;
  23804. d[7] = (uint8) hours;
  23805. d[8] = (uint8) minutes;
  23806. d[9] = (uint8) seconds;
  23807. d[10] = (uint8) frames;
  23808. d[11] = 0xf7;
  23809. return MidiMessage (d, 12, 0.0);
  23810. }
  23811. const String MidiMessage::getMidiNoteName (int note, bool useSharps, bool includeOctaveNumber, int octaveNumForMiddleC)
  23812. {
  23813. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" };
  23814. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E", "F", "Gb", "G", "Ab", "A", "Bb", "B" };
  23815. if (((unsigned int) note) < 128)
  23816. {
  23817. String s (useSharps ? sharpNoteNames [note % 12]
  23818. : flatNoteNames [note % 12]);
  23819. if (includeOctaveNumber)
  23820. s << (note / 12 + (octaveNumForMiddleC - 5));
  23821. return s;
  23822. }
  23823. return String::empty;
  23824. }
  23825. const double MidiMessage::getMidiNoteInHertz (int noteNumber, const double frequencyOfA) throw()
  23826. {
  23827. noteNumber -= 12 * 6 + 9; // now 0 = A
  23828. return frequencyOfA * pow (2.0, noteNumber / 12.0);
  23829. }
  23830. const String MidiMessage::getGMInstrumentName (const int n)
  23831. {
  23832. const char* names[] =
  23833. {
  23834. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  23835. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  23836. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  23837. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  23838. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  23839. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  23840. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  23841. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  23842. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  23843. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  23844. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  23845. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  23846. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  23847. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  23848. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  23849. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  23850. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  23851. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  23852. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  23853. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  23854. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  23855. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  23856. "Applause", "Gunshot"
  23857. };
  23858. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23859. }
  23860. const String MidiMessage::getGMInstrumentBankName (const int n)
  23861. {
  23862. const char* names[] =
  23863. {
  23864. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  23865. "Bass", "Strings", "Ensemble", "Brass",
  23866. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  23867. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  23868. };
  23869. return (((unsigned int) n) <= 15) ? names[n] : (const char*) 0;
  23870. }
  23871. const String MidiMessage::getRhythmInstrumentName (const int n)
  23872. {
  23873. const char* names[] =
  23874. {
  23875. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  23876. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  23877. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  23878. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  23879. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  23880. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  23881. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  23882. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  23883. "Mute Triangle", "Open Triangle"
  23884. };
  23885. return (n >= 35 && n <= 81) ? names [n - 35] : (const char*) 0;
  23886. }
  23887. const String MidiMessage::getControllerName (const int n)
  23888. {
  23889. const char* names[] =
  23890. {
  23891. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  23892. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  23893. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  23894. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  23895. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  23896. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  23897. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  23898. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  23899. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  23900. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  23901. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  23902. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  23903. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  23904. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  23905. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  23906. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  23907. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  23908. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  23909. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  23910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  23911. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  23912. "Poly Operation"
  23913. };
  23914. return (((unsigned int) n) < 128) ? names[n] : (const char*) 0;
  23915. }
  23916. END_JUCE_NAMESPACE
  23917. /*** End of inlined file: juce_MidiMessage.cpp ***/
  23918. /*** Start of inlined file: juce_MidiMessageCollector.cpp ***/
  23919. BEGIN_JUCE_NAMESPACE
  23920. MidiMessageCollector::MidiMessageCollector()
  23921. : lastCallbackTime (0),
  23922. sampleRate (44100.0001)
  23923. {
  23924. }
  23925. MidiMessageCollector::~MidiMessageCollector()
  23926. {
  23927. }
  23928. void MidiMessageCollector::reset (const double sampleRate_)
  23929. {
  23930. jassert (sampleRate_ > 0);
  23931. const ScopedLock sl (midiCallbackLock);
  23932. sampleRate = sampleRate_;
  23933. incomingMessages.clear();
  23934. lastCallbackTime = Time::getMillisecondCounterHiRes();
  23935. }
  23936. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  23937. {
  23938. // you need to call reset() to set the correct sample rate before using this object
  23939. jassert (sampleRate != 44100.0001);
  23940. // the messages that come in here need to be time-stamped correctly - see MidiInput
  23941. // for details of what the number should be.
  23942. jassert (message.getTimeStamp() != 0);
  23943. const ScopedLock sl (midiCallbackLock);
  23944. const int sampleNumber
  23945. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  23946. incomingMessages.addEvent (message, sampleNumber);
  23947. // if the messages don't get used for over a second, we'd better
  23948. // get rid of any old ones to avoid the queue getting too big
  23949. if (sampleNumber > sampleRate)
  23950. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  23951. }
  23952. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  23953. const int numSamples)
  23954. {
  23955. // you need to call reset() to set the correct sample rate before using this object
  23956. jassert (sampleRate != 44100.0001);
  23957. const double timeNow = Time::getMillisecondCounterHiRes();
  23958. const double msElapsed = timeNow - lastCallbackTime;
  23959. const ScopedLock sl (midiCallbackLock);
  23960. lastCallbackTime = timeNow;
  23961. if (! incomingMessages.isEmpty())
  23962. {
  23963. int numSourceSamples = jmax (1, roundToInt (msElapsed * 0.001 * sampleRate));
  23964. int startSample = 0;
  23965. int scale = 1 << 16;
  23966. const uint8* midiData;
  23967. int numBytes, samplePosition;
  23968. MidiBuffer::Iterator iter (incomingMessages);
  23969. if (numSourceSamples > numSamples)
  23970. {
  23971. // if our list of events is longer than the buffer we're being
  23972. // asked for, scale them down to squeeze them all in..
  23973. const int maxBlockLengthToUse = numSamples << 5;
  23974. if (numSourceSamples > maxBlockLengthToUse)
  23975. {
  23976. startSample = numSourceSamples - maxBlockLengthToUse;
  23977. numSourceSamples = maxBlockLengthToUse;
  23978. iter.setNextSamplePosition (startSample);
  23979. }
  23980. scale = (numSamples << 10) / numSourceSamples;
  23981. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23982. {
  23983. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  23984. destBuffer.addEvent (midiData, numBytes,
  23985. jlimit (0, numSamples - 1, samplePosition));
  23986. }
  23987. }
  23988. else
  23989. {
  23990. // if our event list is shorter than the number we need, put them
  23991. // towards the end of the buffer
  23992. startSample = numSamples - numSourceSamples;
  23993. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  23994. {
  23995. destBuffer.addEvent (midiData, numBytes,
  23996. jlimit (0, numSamples - 1, samplePosition + startSample));
  23997. }
  23998. }
  23999. incomingMessages.clear();
  24000. }
  24001. }
  24002. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  24003. {
  24004. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  24005. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24006. addMessageToQueue (m);
  24007. }
  24008. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  24009. {
  24010. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  24011. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  24012. addMessageToQueue (m);
  24013. }
  24014. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  24015. {
  24016. addMessageToQueue (message);
  24017. }
  24018. END_JUCE_NAMESPACE
  24019. /*** End of inlined file: juce_MidiMessageCollector.cpp ***/
  24020. /*** Start of inlined file: juce_MidiMessageSequence.cpp ***/
  24021. BEGIN_JUCE_NAMESPACE
  24022. MidiMessageSequence::MidiMessageSequence()
  24023. {
  24024. }
  24025. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  24026. {
  24027. list.ensureStorageAllocated (other.list.size());
  24028. for (int i = 0; i < other.list.size(); ++i)
  24029. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  24030. }
  24031. MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  24032. {
  24033. MidiMessageSequence otherCopy (other);
  24034. swapWith (otherCopy);
  24035. return *this;
  24036. }
  24037. void MidiMessageSequence::swapWith (MidiMessageSequence& other) throw()
  24038. {
  24039. list.swapWithArray (other.list);
  24040. }
  24041. MidiMessageSequence::~MidiMessageSequence()
  24042. {
  24043. }
  24044. void MidiMessageSequence::clear()
  24045. {
  24046. list.clear();
  24047. }
  24048. int MidiMessageSequence::getNumEvents() const
  24049. {
  24050. return list.size();
  24051. }
  24052. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  24053. {
  24054. return list [index];
  24055. }
  24056. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  24057. {
  24058. const MidiEventHolder* const meh = list [index];
  24059. if (meh != 0 && meh->noteOffObject != 0)
  24060. return meh->noteOffObject->message.getTimeStamp();
  24061. else
  24062. return 0.0;
  24063. }
  24064. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  24065. {
  24066. const MidiEventHolder* const meh = list [index];
  24067. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  24068. }
  24069. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  24070. {
  24071. return list.indexOf (event);
  24072. }
  24073. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  24074. {
  24075. const int numEvents = list.size();
  24076. int i;
  24077. for (i = 0; i < numEvents; ++i)
  24078. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  24079. break;
  24080. return i;
  24081. }
  24082. double MidiMessageSequence::getStartTime() const
  24083. {
  24084. if (list.size() > 0)
  24085. return list.getUnchecked(0)->message.getTimeStamp();
  24086. else
  24087. return 0;
  24088. }
  24089. double MidiMessageSequence::getEndTime() const
  24090. {
  24091. if (list.size() > 0)
  24092. return list.getLast()->message.getTimeStamp();
  24093. else
  24094. return 0;
  24095. }
  24096. double MidiMessageSequence::getEventTime (const int index) const
  24097. {
  24098. if (((unsigned int) index) < (unsigned int) list.size())
  24099. return list.getUnchecked (index)->message.getTimeStamp();
  24100. return 0.0;
  24101. }
  24102. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  24103. double timeAdjustment)
  24104. {
  24105. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  24106. timeAdjustment += newMessage.getTimeStamp();
  24107. newOne->message.setTimeStamp (timeAdjustment);
  24108. int i;
  24109. for (i = list.size(); --i >= 0;)
  24110. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  24111. break;
  24112. list.insert (i + 1, newOne);
  24113. }
  24114. void MidiMessageSequence::deleteEvent (const int index,
  24115. const bool deleteMatchingNoteUp)
  24116. {
  24117. if (((unsigned int) index) < (unsigned int) list.size())
  24118. {
  24119. if (deleteMatchingNoteUp)
  24120. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  24121. list.remove (index);
  24122. }
  24123. }
  24124. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  24125. double timeAdjustment,
  24126. double firstAllowableTime,
  24127. double endOfAllowableDestTimes)
  24128. {
  24129. firstAllowableTime -= timeAdjustment;
  24130. endOfAllowableDestTimes -= timeAdjustment;
  24131. for (int i = 0; i < other.list.size(); ++i)
  24132. {
  24133. const MidiMessage& m = other.list.getUnchecked(i)->message;
  24134. const double t = m.getTimeStamp();
  24135. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  24136. {
  24137. MidiEventHolder* const newOne = new MidiEventHolder (m);
  24138. newOne->message.setTimeStamp (timeAdjustment + t);
  24139. list.add (newOne);
  24140. }
  24141. }
  24142. sort();
  24143. }
  24144. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  24145. const MidiMessageSequence::MidiEventHolder* const second) throw()
  24146. {
  24147. const double diff = first->message.getTimeStamp()
  24148. - second->message.getTimeStamp();
  24149. return (diff > 0) - (diff < 0);
  24150. }
  24151. void MidiMessageSequence::sort()
  24152. {
  24153. list.sort (*this, true);
  24154. }
  24155. void MidiMessageSequence::updateMatchedPairs()
  24156. {
  24157. for (int i = 0; i < list.size(); ++i)
  24158. {
  24159. const MidiMessage& m1 = list.getUnchecked(i)->message;
  24160. if (m1.isNoteOn())
  24161. {
  24162. list.getUnchecked(i)->noteOffObject = 0;
  24163. const int note = m1.getNoteNumber();
  24164. const int chan = m1.getChannel();
  24165. const int len = list.size();
  24166. for (int j = i + 1; j < len; ++j)
  24167. {
  24168. const MidiMessage& m = list.getUnchecked(j)->message;
  24169. if (m.getNoteNumber() == note && m.getChannel() == chan)
  24170. {
  24171. if (m.isNoteOff())
  24172. {
  24173. list.getUnchecked(i)->noteOffObject = list[j];
  24174. break;
  24175. }
  24176. else if (m.isNoteOn())
  24177. {
  24178. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  24179. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  24180. list.getUnchecked(i)->noteOffObject = list[j];
  24181. break;
  24182. }
  24183. }
  24184. }
  24185. }
  24186. }
  24187. }
  24188. void MidiMessageSequence::addTimeToMessages (const double delta)
  24189. {
  24190. for (int i = list.size(); --i >= 0;)
  24191. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  24192. + delta);
  24193. }
  24194. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  24195. MidiMessageSequence& destSequence,
  24196. const bool alsoIncludeMetaEvents) const
  24197. {
  24198. for (int i = 0; i < list.size(); ++i)
  24199. {
  24200. const MidiMessage& mm = list.getUnchecked(i)->message;
  24201. if (mm.isForChannel (channelNumberToExtract)
  24202. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  24203. {
  24204. destSequence.addEvent (mm);
  24205. }
  24206. }
  24207. }
  24208. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  24209. {
  24210. for (int i = 0; i < list.size(); ++i)
  24211. {
  24212. const MidiMessage& mm = list.getUnchecked(i)->message;
  24213. if (mm.isSysEx())
  24214. destSequence.addEvent (mm);
  24215. }
  24216. }
  24217. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  24218. {
  24219. for (int i = list.size(); --i >= 0;)
  24220. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  24221. list.remove(i);
  24222. }
  24223. void MidiMessageSequence::deleteSysExMessages()
  24224. {
  24225. for (int i = list.size(); --i >= 0;)
  24226. if (list.getUnchecked(i)->message.isSysEx())
  24227. list.remove(i);
  24228. }
  24229. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  24230. const double time,
  24231. OwnedArray<MidiMessage>& dest)
  24232. {
  24233. bool doneProg = false;
  24234. bool donePitchWheel = false;
  24235. Array <int> doneControllers;
  24236. doneControllers.ensureStorageAllocated (32);
  24237. for (int i = list.size(); --i >= 0;)
  24238. {
  24239. const MidiMessage& mm = list.getUnchecked(i)->message;
  24240. if (mm.isForChannel (channelNumber)
  24241. && mm.getTimeStamp() <= time)
  24242. {
  24243. if (mm.isProgramChange())
  24244. {
  24245. if (! doneProg)
  24246. {
  24247. dest.add (new MidiMessage (mm, 0.0));
  24248. doneProg = true;
  24249. }
  24250. }
  24251. else if (mm.isController())
  24252. {
  24253. if (! doneControllers.contains (mm.getControllerNumber()))
  24254. {
  24255. dest.add (new MidiMessage (mm, 0.0));
  24256. doneControllers.add (mm.getControllerNumber());
  24257. }
  24258. }
  24259. else if (mm.isPitchWheel())
  24260. {
  24261. if (! donePitchWheel)
  24262. {
  24263. dest.add (new MidiMessage (mm, 0.0));
  24264. donePitchWheel = true;
  24265. }
  24266. }
  24267. }
  24268. }
  24269. }
  24270. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  24271. : message (message_),
  24272. noteOffObject (0)
  24273. {
  24274. }
  24275. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  24276. {
  24277. }
  24278. END_JUCE_NAMESPACE
  24279. /*** End of inlined file: juce_MidiMessageSequence.cpp ***/
  24280. /*** Start of inlined file: juce_AudioPluginFormat.cpp ***/
  24281. BEGIN_JUCE_NAMESPACE
  24282. AudioPluginFormat::AudioPluginFormat() throw()
  24283. {
  24284. }
  24285. AudioPluginFormat::~AudioPluginFormat()
  24286. {
  24287. }
  24288. END_JUCE_NAMESPACE
  24289. /*** End of inlined file: juce_AudioPluginFormat.cpp ***/
  24290. /*** Start of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24291. BEGIN_JUCE_NAMESPACE
  24292. AudioPluginFormatManager::AudioPluginFormatManager()
  24293. {
  24294. }
  24295. AudioPluginFormatManager::~AudioPluginFormatManager()
  24296. {
  24297. clearSingletonInstance();
  24298. }
  24299. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  24300. void AudioPluginFormatManager::addDefaultFormats()
  24301. {
  24302. #if JUCE_DEBUG
  24303. // you should only call this method once!
  24304. for (int i = formats.size(); --i >= 0;)
  24305. {
  24306. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24307. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  24308. #endif
  24309. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24310. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  24311. #endif
  24312. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24313. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  24314. #endif
  24315. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24316. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  24317. #endif
  24318. }
  24319. #endif
  24320. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  24321. formats.add (new AudioUnitPluginFormat());
  24322. #endif
  24323. #if JUCE_PLUGINHOST_VST && ! (JUCE_MAC && JUCE_64BIT)
  24324. formats.add (new VSTPluginFormat());
  24325. #endif
  24326. #if JUCE_PLUGINHOST_DX && JUCE_WINDOWS
  24327. formats.add (new DirectXPluginFormat());
  24328. #endif
  24329. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  24330. formats.add (new LADSPAPluginFormat());
  24331. #endif
  24332. }
  24333. int AudioPluginFormatManager::getNumFormats()
  24334. {
  24335. return formats.size();
  24336. }
  24337. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index)
  24338. {
  24339. return formats [index];
  24340. }
  24341. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format)
  24342. {
  24343. formats.add (format);
  24344. }
  24345. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  24346. String& errorMessage) const
  24347. {
  24348. AudioPluginInstance* result = 0;
  24349. for (int i = 0; i < formats.size(); ++i)
  24350. {
  24351. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  24352. if (result != 0)
  24353. break;
  24354. }
  24355. if (result == 0)
  24356. {
  24357. if (! doesPluginStillExist (description))
  24358. errorMessage = TRANS ("This plug-in file no longer exists");
  24359. else
  24360. errorMessage = TRANS ("This plug-in failed to load correctly");
  24361. }
  24362. return result;
  24363. }
  24364. bool AudioPluginFormatManager::doesPluginStillExist (const PluginDescription& description) const
  24365. {
  24366. for (int i = 0; i < formats.size(); ++i)
  24367. if (formats.getUnchecked(i)->getName() == description.pluginFormatName)
  24368. return formats.getUnchecked(i)->doesPluginStillExist (description);
  24369. return false;
  24370. }
  24371. END_JUCE_NAMESPACE
  24372. /*** End of inlined file: juce_AudioPluginFormatManager.cpp ***/
  24373. /*** Start of inlined file: juce_AudioPluginInstance.cpp ***/
  24374. #define JUCE_PLUGIN_HOST 1
  24375. BEGIN_JUCE_NAMESPACE
  24376. AudioPluginInstance::AudioPluginInstance()
  24377. {
  24378. }
  24379. AudioPluginInstance::~AudioPluginInstance()
  24380. {
  24381. }
  24382. END_JUCE_NAMESPACE
  24383. /*** End of inlined file: juce_AudioPluginInstance.cpp ***/
  24384. /*** Start of inlined file: juce_KnownPluginList.cpp ***/
  24385. BEGIN_JUCE_NAMESPACE
  24386. KnownPluginList::KnownPluginList()
  24387. {
  24388. }
  24389. KnownPluginList::~KnownPluginList()
  24390. {
  24391. }
  24392. void KnownPluginList::clear()
  24393. {
  24394. if (types.size() > 0)
  24395. {
  24396. types.clear();
  24397. sendChangeMessage (this);
  24398. }
  24399. }
  24400. PluginDescription* KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
  24401. {
  24402. for (int i = 0; i < types.size(); ++i)
  24403. if (types.getUnchecked(i)->fileOrIdentifier == fileOrIdentifier)
  24404. return types.getUnchecked(i);
  24405. return 0;
  24406. }
  24407. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
  24408. {
  24409. for (int i = 0; i < types.size(); ++i)
  24410. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  24411. return types.getUnchecked(i);
  24412. return 0;
  24413. }
  24414. bool KnownPluginList::addType (const PluginDescription& type)
  24415. {
  24416. for (int i = types.size(); --i >= 0;)
  24417. {
  24418. if (types.getUnchecked(i)->isDuplicateOf (type))
  24419. {
  24420. // strange - found a duplicate plugin with different info..
  24421. jassert (types.getUnchecked(i)->name == type.name);
  24422. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  24423. *types.getUnchecked(i) = type;
  24424. return false;
  24425. }
  24426. }
  24427. types.add (new PluginDescription (type));
  24428. sendChangeMessage (this);
  24429. return true;
  24430. }
  24431. void KnownPluginList::removeType (const int index)
  24432. {
  24433. types.remove (index);
  24434. sendChangeMessage (this);
  24435. }
  24436. namespace
  24437. {
  24438. const Time getPluginFileModTime (const String& fileOrIdentifier)
  24439. {
  24440. if (fileOrIdentifier.startsWithChar ('/') || fileOrIdentifier[1] == ':')
  24441. return File (fileOrIdentifier).getLastModificationTime();
  24442. return Time (0);
  24443. }
  24444. bool timesAreDifferent (const Time& t1, const Time& t2) throw()
  24445. {
  24446. return t1 != t2 || t1 == Time (0);
  24447. }
  24448. }
  24449. bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier) const
  24450. {
  24451. if (getTypeForFile (fileOrIdentifier) == 0)
  24452. return false;
  24453. for (int i = types.size(); --i >= 0;)
  24454. {
  24455. const PluginDescription* const d = types.getUnchecked(i);
  24456. if (d->fileOrIdentifier == fileOrIdentifier
  24457. && timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24458. {
  24459. return false;
  24460. }
  24461. }
  24462. return true;
  24463. }
  24464. bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
  24465. const bool dontRescanIfAlreadyInList,
  24466. OwnedArray <PluginDescription>& typesFound,
  24467. AudioPluginFormat& format)
  24468. {
  24469. bool addedOne = false;
  24470. if (dontRescanIfAlreadyInList
  24471. && getTypeForFile (fileOrIdentifier) != 0)
  24472. {
  24473. bool needsRescanning = false;
  24474. for (int i = types.size(); --i >= 0;)
  24475. {
  24476. const PluginDescription* const d = types.getUnchecked(i);
  24477. if (d->fileOrIdentifier == fileOrIdentifier)
  24478. {
  24479. if (timesAreDifferent (d->lastFileModTime, getPluginFileModTime (fileOrIdentifier)))
  24480. needsRescanning = true;
  24481. else
  24482. typesFound.add (new PluginDescription (*d));
  24483. }
  24484. }
  24485. if (! needsRescanning)
  24486. return false;
  24487. }
  24488. OwnedArray <PluginDescription> found;
  24489. format.findAllTypesForFile (found, fileOrIdentifier);
  24490. for (int i = 0; i < found.size(); ++i)
  24491. {
  24492. PluginDescription* const desc = found.getUnchecked(i);
  24493. jassert (desc != 0);
  24494. if (addType (*desc))
  24495. addedOne = true;
  24496. typesFound.add (new PluginDescription (*desc));
  24497. }
  24498. return addedOne;
  24499. }
  24500. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  24501. OwnedArray <PluginDescription>& typesFound)
  24502. {
  24503. for (int i = 0; i < files.size(); ++i)
  24504. {
  24505. bool loaded = false;
  24506. for (int j = 0; j < AudioPluginFormatManager::getInstance()->getNumFormats(); ++j)
  24507. {
  24508. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (j);
  24509. if (scanAndAddFile (files[i], true, typesFound, *format))
  24510. loaded = true;
  24511. }
  24512. if (! loaded)
  24513. {
  24514. const File f (files[i]);
  24515. if (f.isDirectory())
  24516. {
  24517. StringArray s;
  24518. {
  24519. Array<File> subFiles;
  24520. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  24521. for (int j = 0; j < subFiles.size(); ++j)
  24522. s.add (subFiles.getReference(j).getFullPathName());
  24523. }
  24524. scanAndAddDragAndDroppedFiles (s, typesFound);
  24525. }
  24526. }
  24527. }
  24528. }
  24529. class PluginSorter
  24530. {
  24531. public:
  24532. KnownPluginList::SortMethod method;
  24533. PluginSorter() throw() {}
  24534. int compareElements (const PluginDescription* const first,
  24535. const PluginDescription* const second) const
  24536. {
  24537. int diff = 0;
  24538. if (method == KnownPluginList::sortByCategory)
  24539. diff = first->category.compareLexicographically (second->category);
  24540. else if (method == KnownPluginList::sortByManufacturer)
  24541. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  24542. else if (method == KnownPluginList::sortByFileSystemLocation)
  24543. diff = first->fileOrIdentifier.replaceCharacter ('\\', '/')
  24544. .upToLastOccurrenceOf ("/", false, false)
  24545. .compare (second->fileOrIdentifier.replaceCharacter ('\\', '/')
  24546. .upToLastOccurrenceOf ("/", false, false));
  24547. if (diff == 0)
  24548. diff = first->name.compareLexicographically (second->name);
  24549. return diff;
  24550. }
  24551. };
  24552. void KnownPluginList::sort (const SortMethod method)
  24553. {
  24554. if (method != defaultOrder)
  24555. {
  24556. PluginSorter sorter;
  24557. sorter.method = method;
  24558. types.sort (sorter, true);
  24559. sendChangeMessage (this);
  24560. }
  24561. }
  24562. XmlElement* KnownPluginList::createXml() const
  24563. {
  24564. XmlElement* const e = new XmlElement ("KNOWNPLUGINS");
  24565. for (int i = 0; i < types.size(); ++i)
  24566. e->addChildElement (types.getUnchecked(i)->createXml());
  24567. return e;
  24568. }
  24569. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  24570. {
  24571. clear();
  24572. if (xml.hasTagName ("KNOWNPLUGINS"))
  24573. {
  24574. forEachXmlChildElement (xml, e)
  24575. {
  24576. PluginDescription info;
  24577. if (info.loadFromXml (*e))
  24578. addType (info);
  24579. }
  24580. }
  24581. }
  24582. const int menuIdBase = 0x324503f4;
  24583. // This is used to turn a bunch of paths into a nested menu structure.
  24584. struct PluginFilesystemTree
  24585. {
  24586. private:
  24587. String folder;
  24588. OwnedArray <PluginFilesystemTree> subFolders;
  24589. Array <PluginDescription*> plugins;
  24590. void addPlugin (PluginDescription* const pd, const String& path)
  24591. {
  24592. if (path.isEmpty())
  24593. {
  24594. plugins.add (pd);
  24595. }
  24596. else
  24597. {
  24598. const String firstSubFolder (path.upToFirstOccurrenceOf ("/", false, false));
  24599. const String remainingPath (path.fromFirstOccurrenceOf ("/", false, false));
  24600. for (int i = subFolders.size(); --i >= 0;)
  24601. {
  24602. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  24603. {
  24604. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  24605. return;
  24606. }
  24607. }
  24608. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  24609. newFolder->folder = firstSubFolder;
  24610. subFolders.add (newFolder);
  24611. newFolder->addPlugin (pd, remainingPath);
  24612. }
  24613. }
  24614. // removes any deeply nested folders that don't contain any actual plugins
  24615. void optimise()
  24616. {
  24617. for (int i = subFolders.size(); --i >= 0;)
  24618. {
  24619. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24620. sub->optimise();
  24621. if (sub->plugins.size() == 0)
  24622. {
  24623. for (int j = 0; j < sub->subFolders.size(); ++j)
  24624. subFolders.add (sub->subFolders.getUnchecked(j));
  24625. sub->subFolders.clear (false);
  24626. subFolders.remove (i);
  24627. }
  24628. }
  24629. }
  24630. public:
  24631. void buildTree (const Array <PluginDescription*>& allPlugins)
  24632. {
  24633. for (int i = 0; i < allPlugins.size(); ++i)
  24634. {
  24635. String path (allPlugins.getUnchecked(i)
  24636. ->fileOrIdentifier.replaceCharacter ('\\', '/')
  24637. .upToLastOccurrenceOf ("/", false, false));
  24638. if (path.substring (1, 2) == ":")
  24639. path = path.substring (2);
  24640. addPlugin (allPlugins.getUnchecked(i), path);
  24641. }
  24642. optimise();
  24643. }
  24644. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  24645. {
  24646. int i;
  24647. for (i = 0; i < subFolders.size(); ++i)
  24648. {
  24649. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  24650. PopupMenu subMenu;
  24651. sub->addToMenu (subMenu, allPlugins);
  24652. #if JUCE_MAC
  24653. // avoid the special AU formatting nonsense on Mac..
  24654. m.addSubMenu (sub->folder.fromFirstOccurrenceOf (":", false, false), subMenu);
  24655. #else
  24656. m.addSubMenu (sub->folder, subMenu);
  24657. #endif
  24658. }
  24659. for (i = 0; i < plugins.size(); ++i)
  24660. {
  24661. PluginDescription* const plugin = plugins.getUnchecked(i);
  24662. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  24663. plugin->name, true, false);
  24664. }
  24665. }
  24666. };
  24667. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  24668. {
  24669. Array <PluginDescription*> sorted;
  24670. {
  24671. PluginSorter sorter;
  24672. sorter.method = sortMethod;
  24673. for (int i = 0; i < types.size(); ++i)
  24674. sorted.addSorted (sorter, types.getUnchecked(i));
  24675. }
  24676. if (sortMethod == sortByCategory
  24677. || sortMethod == sortByManufacturer)
  24678. {
  24679. String lastSubMenuName;
  24680. PopupMenu sub;
  24681. for (int i = 0; i < sorted.size(); ++i)
  24682. {
  24683. const PluginDescription* const pd = sorted.getUnchecked(i);
  24684. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  24685. : pd->manufacturerName);
  24686. if (! thisSubMenuName.containsNonWhitespaceChars())
  24687. thisSubMenuName = "Other";
  24688. if (thisSubMenuName != lastSubMenuName)
  24689. {
  24690. if (sub.getNumItems() > 0)
  24691. {
  24692. menu.addSubMenu (lastSubMenuName, sub);
  24693. sub.clear();
  24694. }
  24695. lastSubMenuName = thisSubMenuName;
  24696. }
  24697. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24698. }
  24699. if (sub.getNumItems() > 0)
  24700. menu.addSubMenu (lastSubMenuName, sub);
  24701. }
  24702. else if (sortMethod == sortByFileSystemLocation)
  24703. {
  24704. PluginFilesystemTree root;
  24705. root.buildTree (sorted);
  24706. root.addToMenu (menu, types);
  24707. }
  24708. else
  24709. {
  24710. for (int i = 0; i < sorted.size(); ++i)
  24711. {
  24712. const PluginDescription* const pd = sorted.getUnchecked(i);
  24713. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  24714. }
  24715. }
  24716. }
  24717. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  24718. {
  24719. const int i = menuResultCode - menuIdBase;
  24720. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  24721. }
  24722. END_JUCE_NAMESPACE
  24723. /*** End of inlined file: juce_KnownPluginList.cpp ***/
  24724. /*** Start of inlined file: juce_PluginDescription.cpp ***/
  24725. BEGIN_JUCE_NAMESPACE
  24726. PluginDescription::PluginDescription()
  24727. : uid (0),
  24728. isInstrument (false),
  24729. numInputChannels (0),
  24730. numOutputChannels (0)
  24731. {
  24732. }
  24733. PluginDescription::~PluginDescription()
  24734. {
  24735. }
  24736. PluginDescription::PluginDescription (const PluginDescription& other)
  24737. : name (other.name),
  24738. pluginFormatName (other.pluginFormatName),
  24739. category (other.category),
  24740. manufacturerName (other.manufacturerName),
  24741. version (other.version),
  24742. fileOrIdentifier (other.fileOrIdentifier),
  24743. lastFileModTime (other.lastFileModTime),
  24744. uid (other.uid),
  24745. isInstrument (other.isInstrument),
  24746. numInputChannels (other.numInputChannels),
  24747. numOutputChannels (other.numOutputChannels)
  24748. {
  24749. }
  24750. PluginDescription& PluginDescription::operator= (const PluginDescription& other)
  24751. {
  24752. name = other.name;
  24753. pluginFormatName = other.pluginFormatName;
  24754. category = other.category;
  24755. manufacturerName = other.manufacturerName;
  24756. version = other.version;
  24757. fileOrIdentifier = other.fileOrIdentifier;
  24758. uid = other.uid;
  24759. isInstrument = other.isInstrument;
  24760. lastFileModTime = other.lastFileModTime;
  24761. numInputChannels = other.numInputChannels;
  24762. numOutputChannels = other.numOutputChannels;
  24763. return *this;
  24764. }
  24765. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  24766. {
  24767. return fileOrIdentifier == other.fileOrIdentifier
  24768. && uid == other.uid;
  24769. }
  24770. const String PluginDescription::createIdentifierString() const
  24771. {
  24772. return pluginFormatName
  24773. + "-" + name
  24774. + "-" + String::toHexString (fileOrIdentifier.hashCode())
  24775. + "-" + String::toHexString (uid);
  24776. }
  24777. XmlElement* PluginDescription::createXml() const
  24778. {
  24779. XmlElement* const e = new XmlElement ("PLUGIN");
  24780. e->setAttribute ("name", name);
  24781. e->setAttribute ("format", pluginFormatName);
  24782. e->setAttribute ("category", category);
  24783. e->setAttribute ("manufacturer", manufacturerName);
  24784. e->setAttribute ("version", version);
  24785. e->setAttribute ("file", fileOrIdentifier);
  24786. e->setAttribute ("uid", String::toHexString (uid));
  24787. e->setAttribute ("isInstrument", isInstrument);
  24788. e->setAttribute ("fileTime", String::toHexString (lastFileModTime.toMilliseconds()));
  24789. e->setAttribute ("numInputs", numInputChannels);
  24790. e->setAttribute ("numOutputs", numOutputChannels);
  24791. return e;
  24792. }
  24793. bool PluginDescription::loadFromXml (const XmlElement& xml)
  24794. {
  24795. if (xml.hasTagName ("PLUGIN"))
  24796. {
  24797. name = xml.getStringAttribute ("name");
  24798. pluginFormatName = xml.getStringAttribute ("format");
  24799. category = xml.getStringAttribute ("category");
  24800. manufacturerName = xml.getStringAttribute ("manufacturer");
  24801. version = xml.getStringAttribute ("version");
  24802. fileOrIdentifier = xml.getStringAttribute ("file");
  24803. uid = xml.getStringAttribute ("uid").getHexValue32();
  24804. isInstrument = xml.getBoolAttribute ("isInstrument", false);
  24805. lastFileModTime = Time (xml.getStringAttribute ("fileTime").getHexValue64());
  24806. numInputChannels = xml.getIntAttribute ("numInputs");
  24807. numOutputChannels = xml.getIntAttribute ("numOutputs");
  24808. return true;
  24809. }
  24810. return false;
  24811. }
  24812. END_JUCE_NAMESPACE
  24813. /*** End of inlined file: juce_PluginDescription.cpp ***/
  24814. /*** Start of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24815. BEGIN_JUCE_NAMESPACE
  24816. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  24817. AudioPluginFormat& formatToLookFor,
  24818. FileSearchPath directoriesToSearch,
  24819. const bool recursive,
  24820. const File& deadMansPedalFile_)
  24821. : list (listToAddTo),
  24822. format (formatToLookFor),
  24823. deadMansPedalFile (deadMansPedalFile_),
  24824. nextIndex (0),
  24825. progress (0)
  24826. {
  24827. directoriesToSearch.removeRedundantPaths();
  24828. filesOrIdentifiersToScan = format.searchPathsForPlugins (directoriesToSearch, recursive);
  24829. // If any plugins have crashed recently when being loaded, move them to the
  24830. // end of the list to give the others a chance to load correctly..
  24831. const StringArray crashedPlugins (getDeadMansPedalFile());
  24832. for (int i = 0; i < crashedPlugins.size(); ++i)
  24833. {
  24834. const String f = crashedPlugins[i];
  24835. for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
  24836. if (f == filesOrIdentifiersToScan[j])
  24837. filesOrIdentifiersToScan.move (j, -1);
  24838. }
  24839. }
  24840. PluginDirectoryScanner::~PluginDirectoryScanner()
  24841. {
  24842. }
  24843. const String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
  24844. {
  24845. return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex]);
  24846. }
  24847. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  24848. {
  24849. String file (filesOrIdentifiersToScan [nextIndex]);
  24850. if (file.isNotEmpty() && ! list.isListingUpToDate (file))
  24851. {
  24852. OwnedArray <PluginDescription> typesFound;
  24853. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  24854. StringArray crashedPlugins (getDeadMansPedalFile());
  24855. crashedPlugins.removeString (file);
  24856. crashedPlugins.add (file);
  24857. setDeadMansPedalFile (crashedPlugins);
  24858. list.scanAndAddFile (file,
  24859. dontRescanIfAlreadyInList,
  24860. typesFound,
  24861. format);
  24862. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  24863. crashedPlugins.removeString (file);
  24864. setDeadMansPedalFile (crashedPlugins);
  24865. if (typesFound.size() == 0)
  24866. failedFiles.add (file);
  24867. }
  24868. return skipNextFile();
  24869. }
  24870. bool PluginDirectoryScanner::skipNextFile()
  24871. {
  24872. if (nextIndex >= filesOrIdentifiersToScan.size())
  24873. return false;
  24874. progress = ++nextIndex / (float) filesOrIdentifiersToScan.size();
  24875. return nextIndex < filesOrIdentifiersToScan.size();
  24876. }
  24877. const StringArray PluginDirectoryScanner::getDeadMansPedalFile()
  24878. {
  24879. StringArray lines;
  24880. if (deadMansPedalFile != File::nonexistent)
  24881. {
  24882. lines.addLines (deadMansPedalFile.loadFileAsString());
  24883. lines.removeEmptyStrings();
  24884. }
  24885. return lines;
  24886. }
  24887. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
  24888. {
  24889. if (deadMansPedalFile != File::nonexistent)
  24890. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  24891. }
  24892. END_JUCE_NAMESPACE
  24893. /*** End of inlined file: juce_PluginDirectoryScanner.cpp ***/
  24894. /*** Start of inlined file: juce_PluginListComponent.cpp ***/
  24895. BEGIN_JUCE_NAMESPACE
  24896. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  24897. const File& deadMansPedalFile_,
  24898. PropertiesFile* const propertiesToUse_)
  24899. : list (listToEdit),
  24900. deadMansPedalFile (deadMansPedalFile_),
  24901. optionsButton ("Options..."),
  24902. propertiesToUse (propertiesToUse_)
  24903. {
  24904. listBox.setModel (this);
  24905. addAndMakeVisible (&listBox);
  24906. addAndMakeVisible (&optionsButton);
  24907. optionsButton.addButtonListener (this);
  24908. optionsButton.setTriggeredOnMouseDown (true);
  24909. setSize (400, 600);
  24910. list.addChangeListener (this);
  24911. changeListenerCallback (0);
  24912. }
  24913. PluginListComponent::~PluginListComponent()
  24914. {
  24915. list.removeChangeListener (this);
  24916. }
  24917. void PluginListComponent::resized()
  24918. {
  24919. listBox.setBounds (0, 0, getWidth(), getHeight() - 30);
  24920. optionsButton.changeWidthToFitText (24);
  24921. optionsButton.setTopLeftPosition (8, getHeight() - 28);
  24922. }
  24923. void PluginListComponent::changeListenerCallback (void*)
  24924. {
  24925. listBox.updateContent();
  24926. listBox.repaint();
  24927. }
  24928. int PluginListComponent::getNumRows()
  24929. {
  24930. return list.getNumTypes();
  24931. }
  24932. void PluginListComponent::paintListBoxItem (int row,
  24933. Graphics& g,
  24934. int width, int height,
  24935. bool rowIsSelected)
  24936. {
  24937. if (rowIsSelected)
  24938. g.fillAll (findColour (TextEditor::highlightColourId));
  24939. const PluginDescription* const pd = list.getType (row);
  24940. if (pd != 0)
  24941. {
  24942. GlyphArrangement ga;
  24943. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  24944. g.setColour (Colours::black);
  24945. ga.draw (g);
  24946. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  24947. String desc;
  24948. desc << pd->pluginFormatName
  24949. << (pd->isInstrument ? " instrument" : " effect")
  24950. << " - "
  24951. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  24952. << " / "
  24953. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  24954. if (pd->manufacturerName.isNotEmpty())
  24955. desc << " - " << pd->manufacturerName;
  24956. if (pd->version.isNotEmpty())
  24957. desc << " - " << pd->version;
  24958. if (pd->category.isNotEmpty())
  24959. desc << " - category: '" << pd->category << '\'';
  24960. g.setColour (Colours::grey);
  24961. ga.clear();
  24962. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, bb.getRight() + 10.0f, height * 0.8f, width - bb.getRight() - 12.0f, true);
  24963. ga.draw (g);
  24964. }
  24965. }
  24966. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  24967. {
  24968. list.removeType (lastRowSelected);
  24969. }
  24970. void PluginListComponent::buttonClicked (Button* button)
  24971. {
  24972. if (button == &optionsButton)
  24973. {
  24974. PopupMenu menu;
  24975. menu.addItem (1, TRANS("Clear list"));
  24976. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox.getNumSelectedRows() > 0);
  24977. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox.getNumSelectedRows() > 0);
  24978. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  24979. menu.addSeparator();
  24980. menu.addItem (2, TRANS("Sort alphabetically"));
  24981. menu.addItem (3, TRANS("Sort by category"));
  24982. menu.addItem (4, TRANS("Sort by manufacturer"));
  24983. menu.addSeparator();
  24984. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  24985. {
  24986. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  24987. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  24988. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  24989. }
  24990. const int r = menu.showAt (&optionsButton);
  24991. if (r == 1)
  24992. {
  24993. list.clear();
  24994. }
  24995. else if (r == 2)
  24996. {
  24997. list.sort (KnownPluginList::sortAlphabetically);
  24998. }
  24999. else if (r == 3)
  25000. {
  25001. list.sort (KnownPluginList::sortByCategory);
  25002. }
  25003. else if (r == 4)
  25004. {
  25005. list.sort (KnownPluginList::sortByManufacturer);
  25006. }
  25007. else if (r == 5)
  25008. {
  25009. const SparseSet <int> selected (listBox.getSelectedRows());
  25010. for (int i = list.getNumTypes(); --i >= 0;)
  25011. if (selected.contains (i))
  25012. list.removeType (i);
  25013. }
  25014. else if (r == 6)
  25015. {
  25016. const PluginDescription* const desc = list.getType (listBox.getSelectedRow());
  25017. if (desc != 0)
  25018. {
  25019. if (File (desc->fileOrIdentifier).existsAsFile())
  25020. File (desc->fileOrIdentifier).getParentDirectory().startAsProcess();
  25021. }
  25022. }
  25023. else if (r == 7)
  25024. {
  25025. for (int i = list.getNumTypes(); --i >= 0;)
  25026. {
  25027. if (! AudioPluginFormatManager::getInstance()->doesPluginStillExist (*list.getType (i)))
  25028. {
  25029. list.removeType (i);
  25030. }
  25031. }
  25032. }
  25033. else if (r != 0)
  25034. {
  25035. typeToScan = r - 10;
  25036. startTimer (1);
  25037. }
  25038. }
  25039. }
  25040. void PluginListComponent::timerCallback()
  25041. {
  25042. stopTimer();
  25043. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  25044. }
  25045. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  25046. {
  25047. return true;
  25048. }
  25049. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  25050. {
  25051. OwnedArray <PluginDescription> typesFound;
  25052. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  25053. }
  25054. void PluginListComponent::scanFor (AudioPluginFormat* format)
  25055. {
  25056. if (format == 0)
  25057. return;
  25058. FileSearchPath path (format->getDefaultLocationsToSearch());
  25059. if (propertiesToUse != 0)
  25060. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25061. {
  25062. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  25063. FileSearchPathListComponent pathList;
  25064. pathList.setSize (500, 300);
  25065. pathList.setPath (path);
  25066. aw.addCustomComponent (&pathList);
  25067. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  25068. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25069. if (aw.runModalLoop() == 0)
  25070. return;
  25071. path = pathList.getPath();
  25072. }
  25073. if (propertiesToUse != 0)
  25074. {
  25075. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  25076. propertiesToUse->saveIfNeeded();
  25077. }
  25078. double progress = 0.0;
  25079. AlertWindow aw (TRANS("Scanning for plugins..."),
  25080. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  25081. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  25082. aw.addProgressBarComponent (progress);
  25083. aw.enterModalState();
  25084. MessageManager::getInstance()->runDispatchLoopUntil (300);
  25085. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  25086. for (;;)
  25087. {
  25088. aw.setMessage (TRANS("Testing:\n\n")
  25089. + scanner.getNextPluginFileThatWillBeScanned());
  25090. MessageManager::getInstance()->runDispatchLoopUntil (20);
  25091. if (! scanner.scanNextFile (true))
  25092. break;
  25093. if (! aw.isCurrentlyModal())
  25094. break;
  25095. progress = scanner.getProgress();
  25096. }
  25097. if (scanner.getFailedFiles().size() > 0)
  25098. {
  25099. StringArray shortNames;
  25100. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  25101. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  25102. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  25103. TRANS("Scan complete"),
  25104. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  25105. + shortNames.joinIntoString (", "));
  25106. }
  25107. }
  25108. END_JUCE_NAMESPACE
  25109. /*** End of inlined file: juce_PluginListComponent.cpp ***/
  25110. /*** Start of inlined file: juce_AudioUnitPluginFormat.mm ***/
  25111. #if JUCE_PLUGINHOST_AU && ! (JUCE_LINUX || JUCE_WINDOWS)
  25112. #include <AudioUnit/AudioUnit.h>
  25113. #include <AudioUnit/AUCocoaUIView.h>
  25114. #include <CoreAudioKit/AUGenericView.h>
  25115. #if JUCE_SUPPORT_CARBON
  25116. #include <AudioToolbox/AudioUnitUtilities.h>
  25117. #include <AudioUnit/AudioUnitCarbonView.h>
  25118. #endif
  25119. BEGIN_JUCE_NAMESPACE
  25120. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  25121. #endif
  25122. #if JUCE_MAC
  25123. // Change this to disable logging of various activities
  25124. #ifndef AU_LOGGING
  25125. #define AU_LOGGING 1
  25126. #endif
  25127. #if AU_LOGGING
  25128. #define log(a) Logger::writeToLog(a);
  25129. #else
  25130. #define log(a)
  25131. #endif
  25132. namespace AudioUnitFormatHelpers
  25133. {
  25134. static int insideCallback = 0;
  25135. static const String osTypeToString (OSType type)
  25136. {
  25137. char s[4];
  25138. s[0] = (char) (((uint32) type) >> 24);
  25139. s[1] = (char) (((uint32) type) >> 16);
  25140. s[2] = (char) (((uint32) type) >> 8);
  25141. s[3] = (char) ((uint32) type);
  25142. return String (s, 4);
  25143. }
  25144. static OSType stringToOSType (const String& s1)
  25145. {
  25146. const String s (s1 + " ");
  25147. return (((OSType) (unsigned char) s[0]) << 24)
  25148. | (((OSType) (unsigned char) s[1]) << 16)
  25149. | (((OSType) (unsigned char) s[2]) << 8)
  25150. | ((OSType) (unsigned char) s[3]);
  25151. }
  25152. static const char* auIdentifierPrefix = "AudioUnit:";
  25153. static const String createAUPluginIdentifier (const ComponentDescription& desc)
  25154. {
  25155. jassert (osTypeToString ('abcd') == "abcd"); // agh, must have got the endianness wrong..
  25156. jassert (stringToOSType ("abcd") == (OSType) 'abcd'); // ditto
  25157. String s (auIdentifierPrefix);
  25158. if (desc.componentType == kAudioUnitType_MusicDevice)
  25159. s << "Synths/";
  25160. else if (desc.componentType == kAudioUnitType_MusicEffect
  25161. || desc.componentType == kAudioUnitType_Effect)
  25162. s << "Effects/";
  25163. else if (desc.componentType == kAudioUnitType_Generator)
  25164. s << "Generators/";
  25165. else if (desc.componentType == kAudioUnitType_Panner)
  25166. s << "Panners/";
  25167. s << osTypeToString (desc.componentType) << ","
  25168. << osTypeToString (desc.componentSubType) << ","
  25169. << osTypeToString (desc.componentManufacturer);
  25170. return s;
  25171. }
  25172. static void getAUDetails (ComponentRecord* comp, String& name, String& manufacturer)
  25173. {
  25174. Handle componentNameHandle = NewHandle (sizeof (void*));
  25175. Handle componentInfoHandle = NewHandle (sizeof (void*));
  25176. if (componentNameHandle != 0 && componentInfoHandle != 0)
  25177. {
  25178. ComponentDescription desc;
  25179. if (GetComponentInfo (comp, &desc, componentNameHandle, componentInfoHandle, 0) == noErr)
  25180. {
  25181. ConstStr255Param nameString = (ConstStr255Param) (*componentNameHandle);
  25182. ConstStr255Param infoString = (ConstStr255Param) (*componentInfoHandle);
  25183. if (nameString != 0 && nameString[0] != 0)
  25184. {
  25185. const String all ((const char*) nameString + 1, nameString[0]);
  25186. DBG ("name: "+ all);
  25187. manufacturer = all.upToFirstOccurrenceOf (":", false, false).trim();
  25188. name = all.fromFirstOccurrenceOf (":", false, false).trim();
  25189. }
  25190. if (infoString != 0 && infoString[0] != 0)
  25191. {
  25192. DBG ("info: " + String ((const char*) infoString + 1, infoString[0]));
  25193. }
  25194. if (name.isEmpty())
  25195. name = "<Unknown>";
  25196. }
  25197. DisposeHandle (componentNameHandle);
  25198. DisposeHandle (componentInfoHandle);
  25199. }
  25200. }
  25201. static bool getComponentDescFromIdentifier (const String& fileOrIdentifier, ComponentDescription& desc,
  25202. String& name, String& version, String& manufacturer)
  25203. {
  25204. zerostruct (desc);
  25205. if (fileOrIdentifier.startsWithIgnoreCase (auIdentifierPrefix))
  25206. {
  25207. String s (fileOrIdentifier.substring (jmax (fileOrIdentifier.lastIndexOfChar (':'),
  25208. fileOrIdentifier.lastIndexOfChar ('/')) + 1));
  25209. StringArray tokens;
  25210. tokens.addTokens (s, ",", String::empty);
  25211. tokens.trim();
  25212. tokens.removeEmptyStrings();
  25213. if (tokens.size() == 3)
  25214. {
  25215. desc.componentType = stringToOSType (tokens[0]);
  25216. desc.componentSubType = stringToOSType (tokens[1]);
  25217. desc.componentManufacturer = stringToOSType (tokens[2]);
  25218. ComponentRecord* comp = FindNextComponent (0, &desc);
  25219. if (comp != 0)
  25220. {
  25221. getAUDetails (comp, name, manufacturer);
  25222. return true;
  25223. }
  25224. }
  25225. }
  25226. return false;
  25227. }
  25228. }
  25229. class AudioUnitPluginWindowCarbon;
  25230. class AudioUnitPluginWindowCocoa;
  25231. class AudioUnitPluginInstance : public AudioPluginInstance
  25232. {
  25233. public:
  25234. ~AudioUnitPluginInstance();
  25235. void initialise();
  25236. // AudioPluginInstance methods:
  25237. void fillInPluginDescription (PluginDescription& desc) const
  25238. {
  25239. desc.name = pluginName;
  25240. desc.fileOrIdentifier = AudioUnitFormatHelpers::createAUPluginIdentifier (componentDesc);
  25241. desc.uid = ((int) componentDesc.componentType)
  25242. ^ ((int) componentDesc.componentSubType)
  25243. ^ ((int) componentDesc.componentManufacturer);
  25244. desc.lastFileModTime = 0;
  25245. desc.pluginFormatName = "AudioUnit";
  25246. desc.category = getCategory();
  25247. desc.manufacturerName = manufacturer;
  25248. desc.version = version;
  25249. desc.numInputChannels = getNumInputChannels();
  25250. desc.numOutputChannels = getNumOutputChannels();
  25251. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  25252. }
  25253. const String getName() const { return pluginName; }
  25254. bool acceptsMidi() const { return wantsMidiMessages; }
  25255. bool producesMidi() const { return false; }
  25256. // AudioProcessor methods:
  25257. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  25258. void releaseResources();
  25259. void processBlock (AudioSampleBuffer& buffer,
  25260. MidiBuffer& midiMessages);
  25261. bool hasEditor() const;
  25262. AudioProcessorEditor* createEditor();
  25263. const String getInputChannelName (int index) const;
  25264. bool isInputChannelStereoPair (int index) const;
  25265. const String getOutputChannelName (int index) const;
  25266. bool isOutputChannelStereoPair (int index) const;
  25267. int getNumParameters();
  25268. float getParameter (int index);
  25269. void setParameter (int index, float newValue);
  25270. const String getParameterName (int index);
  25271. const String getParameterText (int index);
  25272. bool isParameterAutomatable (int index) const;
  25273. int getNumPrograms();
  25274. int getCurrentProgram();
  25275. void setCurrentProgram (int index);
  25276. const String getProgramName (int index);
  25277. void changeProgramName (int index, const String& newName);
  25278. void getStateInformation (MemoryBlock& destData);
  25279. void getCurrentProgramStateInformation (MemoryBlock& destData);
  25280. void setStateInformation (const void* data, int sizeInBytes);
  25281. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  25282. juce_UseDebuggingNewOperator
  25283. private:
  25284. friend class AudioUnitPluginWindowCarbon;
  25285. friend class AudioUnitPluginWindowCocoa;
  25286. friend class AudioUnitPluginFormat;
  25287. ComponentDescription componentDesc;
  25288. String pluginName, manufacturer, version;
  25289. String fileOrIdentifier;
  25290. CriticalSection lock;
  25291. bool wantsMidiMessages, wasPlaying, prepared;
  25292. HeapBlock <AudioBufferList> outputBufferList;
  25293. AudioTimeStamp timeStamp;
  25294. AudioSampleBuffer* currentBuffer;
  25295. AudioUnit audioUnit;
  25296. Array <int> parameterIds;
  25297. bool getComponentDescFromFile (const String& fileOrIdentifier);
  25298. void setPluginCallbacks();
  25299. void getParameterListFromPlugin();
  25300. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25301. const AudioTimeStamp* inTimeStamp,
  25302. UInt32 inBusNumber,
  25303. UInt32 inNumberFrames,
  25304. AudioBufferList* ioData) const;
  25305. static OSStatus renderGetInputCallback (void* inRefCon,
  25306. AudioUnitRenderActionFlags* ioActionFlags,
  25307. const AudioTimeStamp* inTimeStamp,
  25308. UInt32 inBusNumber,
  25309. UInt32 inNumberFrames,
  25310. AudioBufferList* ioData)
  25311. {
  25312. return ((AudioUnitPluginInstance*) inRefCon)
  25313. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  25314. }
  25315. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  25316. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  25317. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  25318. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25319. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25320. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  25321. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  25322. {
  25323. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  25324. }
  25325. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  25326. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  25327. Float64* outCurrentMeasureDownBeat)
  25328. {
  25329. return ((AudioUnitPluginInstance*) inHostUserData)
  25330. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  25331. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  25332. }
  25333. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  25334. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  25335. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  25336. {
  25337. return ((AudioUnitPluginInstance*) inHostUserData)
  25338. ->getTransportState (outIsPlaying, outTransportStateChanged,
  25339. outCurrentSampleInTimeLine, outIsCycling,
  25340. outCycleStartBeat, outCycleEndBeat);
  25341. }
  25342. void getNumChannels (int& numIns, int& numOuts)
  25343. {
  25344. numIns = 0;
  25345. numOuts = 0;
  25346. AUChannelInfo supportedChannels [128];
  25347. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  25348. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  25349. 0, supportedChannels, &supportedChannelsSize) == noErr
  25350. && supportedChannelsSize > 0)
  25351. {
  25352. int explicitNumIns = 0;
  25353. int explicitNumOuts = 0;
  25354. int maximumNumIns = 0;
  25355. int maximumNumOuts = 0;
  25356. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  25357. {
  25358. const int inChannels = (int) supportedChannels[i].inChannels;
  25359. const int outChannels = (int) supportedChannels[i].outChannels;
  25360. if (inChannels < 0)
  25361. maximumNumIns = jmin (maximumNumIns, inChannels);
  25362. else
  25363. explicitNumIns = jmax (explicitNumIns, inChannels);
  25364. if (outChannels < 0)
  25365. maximumNumOuts = jmin (maximumNumOuts, outChannels);
  25366. else
  25367. explicitNumOuts = jmax (explicitNumOuts, outChannels);
  25368. }
  25369. if ((maximumNumIns == -1 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, as long as they match)
  25370. || (maximumNumIns == -2 && maximumNumOuts == -1) // (special meaning: any number of ins/outs, even if they don't match)
  25371. || (maximumNumIns == -1 && maximumNumOuts == -2))
  25372. {
  25373. numIns = numOuts = 2;
  25374. }
  25375. else
  25376. {
  25377. numIns = explicitNumIns;
  25378. numOuts = explicitNumOuts;
  25379. if (maximumNumIns == -1 || (maximumNumIns < 0 && explicitNumIns <= -maximumNumIns))
  25380. numIns = 2;
  25381. if (maximumNumOuts == -1 || (maximumNumOuts < 0 && explicitNumOuts <= -maximumNumOuts))
  25382. numOuts = 2;
  25383. }
  25384. }
  25385. else
  25386. {
  25387. // (this really means the plugin will take any number of ins/outs as long
  25388. // as they are the same)
  25389. numIns = numOuts = 2;
  25390. }
  25391. }
  25392. const String getCategory() const;
  25393. AudioUnitPluginInstance (const String& fileOrIdentifier);
  25394. };
  25395. AudioUnitPluginInstance::AudioUnitPluginInstance (const String& fileOrIdentifier)
  25396. : fileOrIdentifier (fileOrIdentifier),
  25397. wantsMidiMessages (false), wasPlaying (false), prepared (false),
  25398. audioUnit (0),
  25399. currentBuffer (0)
  25400. {
  25401. using namespace AudioUnitFormatHelpers;
  25402. try
  25403. {
  25404. ++insideCallback;
  25405. log ("Opening AU: " + fileOrIdentifier);
  25406. if (getComponentDescFromFile (fileOrIdentifier))
  25407. {
  25408. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  25409. if (comp != 0)
  25410. {
  25411. audioUnit = (AudioUnit) OpenComponent (comp);
  25412. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  25413. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  25414. }
  25415. }
  25416. --insideCallback;
  25417. }
  25418. catch (...)
  25419. {
  25420. --insideCallback;
  25421. }
  25422. }
  25423. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  25424. {
  25425. const ScopedLock sl (lock);
  25426. jassert (AudioUnitFormatHelpers::insideCallback == 0);
  25427. if (audioUnit != 0)
  25428. {
  25429. AudioUnitUninitialize (audioUnit);
  25430. CloseComponent (audioUnit);
  25431. audioUnit = 0;
  25432. }
  25433. }
  25434. bool AudioUnitPluginInstance::getComponentDescFromFile (const String& fileOrIdentifier)
  25435. {
  25436. zerostruct (componentDesc);
  25437. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, componentDesc, pluginName, version, manufacturer))
  25438. return true;
  25439. const File file (fileOrIdentifier);
  25440. if (! file.hasFileExtension (".component"))
  25441. return false;
  25442. const char* const utf8 = fileOrIdentifier.toUTF8();
  25443. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  25444. strlen (utf8), file.isDirectory());
  25445. if (url != 0)
  25446. {
  25447. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  25448. CFRelease (url);
  25449. if (bundleRef != 0)
  25450. {
  25451. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  25452. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  25453. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  25454. if (pluginName.isEmpty())
  25455. pluginName = file.getFileNameWithoutExtension();
  25456. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  25457. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  25458. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  25459. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  25460. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  25461. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  25462. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  25463. UseResFile (resFileId);
  25464. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  25465. {
  25466. Handle h = Get1IndResource ('thng', i);
  25467. if (h != 0)
  25468. {
  25469. HLock (h);
  25470. const uint32* const types = (const uint32*) *h;
  25471. if (types[0] == kAudioUnitType_MusicDevice
  25472. || types[0] == kAudioUnitType_MusicEffect
  25473. || types[0] == kAudioUnitType_Effect
  25474. || types[0] == kAudioUnitType_Generator
  25475. || types[0] == kAudioUnitType_Panner)
  25476. {
  25477. componentDesc.componentType = types[0];
  25478. componentDesc.componentSubType = types[1];
  25479. componentDesc.componentManufacturer = types[2];
  25480. break;
  25481. }
  25482. HUnlock (h);
  25483. ReleaseResource (h);
  25484. }
  25485. }
  25486. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  25487. CFRelease (bundleRef);
  25488. }
  25489. }
  25490. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  25491. }
  25492. void AudioUnitPluginInstance::initialise()
  25493. {
  25494. getParameterListFromPlugin();
  25495. setPluginCallbacks();
  25496. int numIns, numOuts;
  25497. getNumChannels (numIns, numOuts);
  25498. setPlayConfigDetails (numIns, numOuts, 0, 0);
  25499. setLatencySamples (0);
  25500. }
  25501. void AudioUnitPluginInstance::getParameterListFromPlugin()
  25502. {
  25503. parameterIds.clear();
  25504. if (audioUnit != 0)
  25505. {
  25506. UInt32 paramListSize = 0;
  25507. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25508. 0, 0, &paramListSize);
  25509. if (paramListSize > 0)
  25510. {
  25511. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  25512. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  25513. 0, &parameterIds.getReference(0), &paramListSize);
  25514. }
  25515. }
  25516. }
  25517. void AudioUnitPluginInstance::setPluginCallbacks()
  25518. {
  25519. if (audioUnit != 0)
  25520. {
  25521. {
  25522. AURenderCallbackStruct info;
  25523. zerostruct (info);
  25524. info.inputProcRefCon = this;
  25525. info.inputProc = renderGetInputCallback;
  25526. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  25527. 0, &info, sizeof (info));
  25528. }
  25529. {
  25530. HostCallbackInfo info;
  25531. zerostruct (info);
  25532. info.hostUserData = this;
  25533. info.beatAndTempoProc = getBeatAndTempoCallback;
  25534. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  25535. info.transportStateProc = getTransportStateCallback;
  25536. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  25537. 0, &info, sizeof (info));
  25538. }
  25539. }
  25540. }
  25541. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  25542. int samplesPerBlockExpected)
  25543. {
  25544. if (audioUnit != 0)
  25545. {
  25546. releaseResources();
  25547. Float64 sampleRateIn = 0, sampleRateOut = 0;
  25548. UInt32 sampleRateSize = sizeof (sampleRateIn);
  25549. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sampleRateIn, &sampleRateSize);
  25550. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sampleRateOut, &sampleRateSize);
  25551. if (sampleRateIn != sampleRate_ || sampleRateOut != sampleRate_)
  25552. {
  25553. Float64 sr = sampleRate_;
  25554. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Input, 0, &sr, sizeof (Float64));
  25555. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SampleRate, kAudioUnitScope_Output, 0, &sr, sizeof (Float64));
  25556. }
  25557. int numIns, numOuts;
  25558. getNumChannels (numIns, numOuts);
  25559. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  25560. Float64 latencySecs = 0.0;
  25561. UInt32 latencySize = sizeof (latencySecs);
  25562. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  25563. 0, &latencySecs, &latencySize);
  25564. setLatencySamples (roundToInt (latencySecs * sampleRate_));
  25565. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25566. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25567. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25568. {
  25569. AudioStreamBasicDescription stream;
  25570. zerostruct (stream);
  25571. stream.mSampleRate = sampleRate_;
  25572. stream.mFormatID = kAudioFormatLinearPCM;
  25573. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  25574. stream.mFramesPerPacket = 1;
  25575. stream.mBytesPerPacket = 4;
  25576. stream.mBytesPerFrame = 4;
  25577. stream.mBitsPerChannel = 32;
  25578. stream.mChannelsPerFrame = numIns;
  25579. OSStatus err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input,
  25580. 0, &stream, sizeof (stream));
  25581. stream.mChannelsPerFrame = numOuts;
  25582. err = AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output,
  25583. 0, &stream, sizeof (stream));
  25584. }
  25585. outputBufferList.calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1), 1);
  25586. outputBufferList->mNumberBuffers = numOuts;
  25587. for (int i = numOuts; --i >= 0;)
  25588. outputBufferList->mBuffers[i].mNumberChannels = 1;
  25589. zerostruct (timeStamp);
  25590. timeStamp.mSampleTime = 0;
  25591. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25592. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  25593. currentBuffer = 0;
  25594. wasPlaying = false;
  25595. prepared = (AudioUnitInitialize (audioUnit) == noErr);
  25596. }
  25597. }
  25598. void AudioUnitPluginInstance::releaseResources()
  25599. {
  25600. if (prepared)
  25601. {
  25602. AudioUnitUninitialize (audioUnit);
  25603. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  25604. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  25605. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  25606. outputBufferList.free();
  25607. currentBuffer = 0;
  25608. prepared = false;
  25609. }
  25610. }
  25611. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  25612. const AudioTimeStamp* inTimeStamp,
  25613. UInt32 inBusNumber,
  25614. UInt32 inNumberFrames,
  25615. AudioBufferList* ioData) const
  25616. {
  25617. if (inBusNumber == 0
  25618. && currentBuffer != 0)
  25619. {
  25620. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  25621. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  25622. {
  25623. if (i < currentBuffer->getNumChannels())
  25624. {
  25625. memcpy (ioData->mBuffers[i].mData,
  25626. currentBuffer->getSampleData (i, 0),
  25627. sizeof (float) * inNumberFrames);
  25628. }
  25629. else
  25630. {
  25631. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  25632. }
  25633. }
  25634. }
  25635. return noErr;
  25636. }
  25637. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  25638. MidiBuffer& midiMessages)
  25639. {
  25640. const int numSamples = buffer.getNumSamples();
  25641. if (prepared)
  25642. {
  25643. AudioUnitRenderActionFlags flags = 0;
  25644. timeStamp.mHostTime = AudioGetCurrentHostTime();
  25645. for (int i = getNumOutputChannels(); --i >= 0;)
  25646. {
  25647. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  25648. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  25649. }
  25650. currentBuffer = &buffer;
  25651. if (wantsMidiMessages)
  25652. {
  25653. const uint8* midiEventData;
  25654. int midiEventSize, midiEventPosition;
  25655. MidiBuffer::Iterator i (midiMessages);
  25656. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  25657. {
  25658. if (midiEventSize <= 3)
  25659. MusicDeviceMIDIEvent (audioUnit,
  25660. midiEventData[0], midiEventData[1], midiEventData[2],
  25661. midiEventPosition);
  25662. else
  25663. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  25664. }
  25665. midiMessages.clear();
  25666. }
  25667. AudioUnitRender (audioUnit, &flags, &timeStamp,
  25668. 0, numSamples, outputBufferList);
  25669. timeStamp.mSampleTime += numSamples;
  25670. }
  25671. else
  25672. {
  25673. // Plugin not working correctly, so just bypass..
  25674. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  25675. buffer.clear (i, 0, buffer.getNumSamples());
  25676. }
  25677. }
  25678. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  25679. {
  25680. AudioPlayHead* const ph = getPlayHead();
  25681. AudioPlayHead::CurrentPositionInfo result;
  25682. if (ph != 0 && ph->getCurrentPosition (result))
  25683. {
  25684. if (outCurrentBeat != 0)
  25685. *outCurrentBeat = result.ppqPosition;
  25686. if (outCurrentTempo != 0)
  25687. *outCurrentTempo = result.bpm;
  25688. }
  25689. else
  25690. {
  25691. if (outCurrentBeat != 0)
  25692. *outCurrentBeat = 0;
  25693. if (outCurrentTempo != 0)
  25694. *outCurrentTempo = 120.0;
  25695. }
  25696. return noErr;
  25697. }
  25698. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  25699. Float32* outTimeSig_Numerator,
  25700. UInt32* outTimeSig_Denominator,
  25701. Float64* outCurrentMeasureDownBeat) const
  25702. {
  25703. AudioPlayHead* const ph = getPlayHead();
  25704. AudioPlayHead::CurrentPositionInfo result;
  25705. if (ph != 0 && ph->getCurrentPosition (result))
  25706. {
  25707. if (outTimeSig_Numerator != 0)
  25708. *outTimeSig_Numerator = result.timeSigNumerator;
  25709. if (outTimeSig_Denominator != 0)
  25710. *outTimeSig_Denominator = result.timeSigDenominator;
  25711. if (outDeltaSampleOffsetToNextBeat != 0)
  25712. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  25713. if (outCurrentMeasureDownBeat != 0)
  25714. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  25715. }
  25716. else
  25717. {
  25718. if (outDeltaSampleOffsetToNextBeat != 0)
  25719. *outDeltaSampleOffsetToNextBeat = 0;
  25720. if (outTimeSig_Numerator != 0)
  25721. *outTimeSig_Numerator = 4;
  25722. if (outTimeSig_Denominator != 0)
  25723. *outTimeSig_Denominator = 4;
  25724. if (outCurrentMeasureDownBeat != 0)
  25725. *outCurrentMeasureDownBeat = 0;
  25726. }
  25727. return noErr;
  25728. }
  25729. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  25730. Boolean* outTransportStateChanged,
  25731. Float64* outCurrentSampleInTimeLine,
  25732. Boolean* outIsCycling,
  25733. Float64* outCycleStartBeat,
  25734. Float64* outCycleEndBeat)
  25735. {
  25736. AudioPlayHead* const ph = getPlayHead();
  25737. AudioPlayHead::CurrentPositionInfo result;
  25738. if (ph != 0 && ph->getCurrentPosition (result))
  25739. {
  25740. if (outIsPlaying != 0)
  25741. *outIsPlaying = result.isPlaying;
  25742. if (outTransportStateChanged != 0)
  25743. {
  25744. *outTransportStateChanged = result.isPlaying != wasPlaying;
  25745. wasPlaying = result.isPlaying;
  25746. }
  25747. if (outCurrentSampleInTimeLine != 0)
  25748. *outCurrentSampleInTimeLine = roundToInt (result.timeInSeconds * getSampleRate());
  25749. if (outIsCycling != 0)
  25750. *outIsCycling = false;
  25751. if (outCycleStartBeat != 0)
  25752. *outCycleStartBeat = 0;
  25753. if (outCycleEndBeat != 0)
  25754. *outCycleEndBeat = 0;
  25755. }
  25756. else
  25757. {
  25758. if (outIsPlaying != 0)
  25759. *outIsPlaying = false;
  25760. if (outTransportStateChanged != 0)
  25761. *outTransportStateChanged = false;
  25762. if (outCurrentSampleInTimeLine != 0)
  25763. *outCurrentSampleInTimeLine = 0;
  25764. if (outIsCycling != 0)
  25765. *outIsCycling = false;
  25766. if (outCycleStartBeat != 0)
  25767. *outCycleStartBeat = 0;
  25768. if (outCycleEndBeat != 0)
  25769. *outCycleEndBeat = 0;
  25770. }
  25771. return noErr;
  25772. }
  25773. class AudioUnitPluginWindowCocoa : public AudioProcessorEditor,
  25774. public Timer
  25775. {
  25776. public:
  25777. AudioUnitPluginWindowCocoa (AudioUnitPluginInstance& plugin_, const bool createGenericViewIfNeeded)
  25778. : AudioProcessorEditor (&plugin_),
  25779. plugin (plugin_)
  25780. {
  25781. addAndMakeVisible (&wrapper);
  25782. setOpaque (true);
  25783. setVisible (true);
  25784. setSize (100, 100);
  25785. createView (createGenericViewIfNeeded);
  25786. }
  25787. ~AudioUnitPluginWindowCocoa()
  25788. {
  25789. const bool wasValid = isValid();
  25790. wrapper.setView (0);
  25791. if (wasValid)
  25792. plugin.editorBeingDeleted (this);
  25793. }
  25794. bool isValid() const { return wrapper.getView() != 0; }
  25795. void paint (Graphics& g)
  25796. {
  25797. g.fillAll (Colours::white);
  25798. }
  25799. void resized()
  25800. {
  25801. wrapper.setSize (getWidth(), getHeight());
  25802. }
  25803. void timerCallback()
  25804. {
  25805. wrapper.resizeToFitView();
  25806. startTimer (jmin (713, getTimerInterval() + 51));
  25807. }
  25808. void childBoundsChanged (Component* child)
  25809. {
  25810. setSize (wrapper.getWidth(), wrapper.getHeight());
  25811. startTimer (70);
  25812. }
  25813. private:
  25814. AudioUnitPluginInstance& plugin;
  25815. NSViewComponent wrapper;
  25816. bool createView (const bool createGenericViewIfNeeded)
  25817. {
  25818. NSView* pluginView = 0;
  25819. UInt32 dataSize = 0;
  25820. Boolean isWritable = false;
  25821. AudioUnitInitialize (plugin.audioUnit);
  25822. if (AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25823. 0, &dataSize, &isWritable) == noErr
  25824. && dataSize != 0
  25825. && AudioUnitGetPropertyInfo (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25826. 0, &dataSize, &isWritable) == noErr)
  25827. {
  25828. HeapBlock <AudioUnitCocoaViewInfo> info;
  25829. info.calloc (dataSize, 1);
  25830. if (AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
  25831. 0, info, &dataSize) == noErr)
  25832. {
  25833. NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
  25834. NSString* path = (NSString*) CFURLCopyPath (info->mCocoaAUViewBundleLocation);
  25835. NSBundle* viewBundle = [NSBundle bundleWithPath: [path autorelease]];
  25836. Class viewClass = [viewBundle classNamed: viewClassName];
  25837. if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
  25838. && [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
  25839. && [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
  25840. {
  25841. id factory = [[[viewClass alloc] init] autorelease];
  25842. pluginView = [factory uiViewForAudioUnit: plugin.audioUnit
  25843. withSize: NSMakeSize (getWidth(), getHeight())];
  25844. }
  25845. for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
  25846. CFRelease (info->mCocoaAUViewClass[i]);
  25847. CFRelease (info->mCocoaAUViewBundleLocation);
  25848. }
  25849. }
  25850. if (createGenericViewIfNeeded && (pluginView == 0))
  25851. pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.audioUnit];
  25852. wrapper.setView (pluginView);
  25853. if (pluginView != 0)
  25854. {
  25855. timerCallback();
  25856. startTimer (70);
  25857. }
  25858. return pluginView != 0;
  25859. }
  25860. };
  25861. #if JUCE_SUPPORT_CARBON
  25862. class AudioUnitPluginWindowCarbon : public AudioProcessorEditor
  25863. {
  25864. public:
  25865. AudioUnitPluginWindowCarbon (AudioUnitPluginInstance& plugin_)
  25866. : AudioProcessorEditor (&plugin_),
  25867. plugin (plugin_),
  25868. viewComponent (0)
  25869. {
  25870. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  25871. setOpaque (true);
  25872. setVisible (true);
  25873. setSize (400, 300);
  25874. ComponentDescription viewList [16];
  25875. UInt32 viewListSize = sizeof (viewList);
  25876. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  25877. 0, &viewList, &viewListSize);
  25878. componentRecord = FindNextComponent (0, &viewList[0]);
  25879. }
  25880. ~AudioUnitPluginWindowCarbon()
  25881. {
  25882. innerWrapper = 0;
  25883. if (isValid())
  25884. plugin.editorBeingDeleted (this);
  25885. }
  25886. bool isValid() const throw() { return componentRecord != 0; }
  25887. void paint (Graphics& g)
  25888. {
  25889. g.fillAll (Colours::black);
  25890. }
  25891. void resized()
  25892. {
  25893. innerWrapper->setSize (getWidth(), getHeight());
  25894. }
  25895. bool keyStateChanged (bool)
  25896. {
  25897. return false;
  25898. }
  25899. bool keyPressed (const KeyPress&)
  25900. {
  25901. return false;
  25902. }
  25903. AudioUnit getAudioUnit() const { return plugin.audioUnit; }
  25904. AudioUnitCarbonView getViewComponent()
  25905. {
  25906. if (viewComponent == 0 && componentRecord != 0)
  25907. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  25908. return viewComponent;
  25909. }
  25910. void closeViewComponent()
  25911. {
  25912. if (viewComponent != 0)
  25913. {
  25914. log ("Closing AU GUI: " + plugin.getName());
  25915. CloseComponent (viewComponent);
  25916. viewComponent = 0;
  25917. }
  25918. }
  25919. juce_UseDebuggingNewOperator
  25920. private:
  25921. AudioUnitPluginInstance& plugin;
  25922. ComponentRecord* componentRecord;
  25923. AudioUnitCarbonView viewComponent;
  25924. class InnerWrapperComponent : public CarbonViewWrapperComponent
  25925. {
  25926. public:
  25927. InnerWrapperComponent (AudioUnitPluginWindowCarbon* const owner_)
  25928. : owner (owner_)
  25929. {
  25930. }
  25931. ~InnerWrapperComponent()
  25932. {
  25933. deleteWindow();
  25934. }
  25935. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  25936. {
  25937. log ("Opening AU GUI: " + owner->plugin.getName());
  25938. AudioUnitCarbonView viewComponent = owner->getViewComponent();
  25939. if (viewComponent == 0)
  25940. return 0;
  25941. Float32Point pos = { 0, 0 };
  25942. Float32Point size = { 250, 200 };
  25943. HIViewRef pluginView = 0;
  25944. AudioUnitCarbonViewCreate (viewComponent,
  25945. owner->getAudioUnit(),
  25946. windowRef,
  25947. rootView,
  25948. &pos,
  25949. &size,
  25950. (ControlRef*) &pluginView);
  25951. return pluginView;
  25952. }
  25953. void removeView (HIViewRef)
  25954. {
  25955. owner->closeViewComponent();
  25956. }
  25957. private:
  25958. AudioUnitPluginWindowCarbon* const owner;
  25959. };
  25960. friend class InnerWrapperComponent;
  25961. ScopedPointer<InnerWrapperComponent> innerWrapper;
  25962. };
  25963. #endif
  25964. bool AudioUnitPluginInstance::hasEditor() const
  25965. {
  25966. return true;
  25967. }
  25968. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  25969. {
  25970. ScopedPointer<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
  25971. if (! static_cast <AudioUnitPluginWindowCocoa*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25972. w = 0;
  25973. #if JUCE_SUPPORT_CARBON
  25974. if (w == 0)
  25975. {
  25976. w = new AudioUnitPluginWindowCarbon (*this);
  25977. if (! static_cast <AudioUnitPluginWindowCarbon*> (static_cast <AudioProcessorEditor*> (w))->isValid())
  25978. w = 0;
  25979. }
  25980. #endif
  25981. if (w == 0)
  25982. w = new AudioUnitPluginWindowCocoa (*this, true); // use AUGenericView as a fallback
  25983. return w.release();
  25984. }
  25985. const String AudioUnitPluginInstance::getCategory() const
  25986. {
  25987. const char* result = 0;
  25988. switch (componentDesc.componentType)
  25989. {
  25990. case kAudioUnitType_Effect:
  25991. case kAudioUnitType_MusicEffect:
  25992. result = "Effect";
  25993. break;
  25994. case kAudioUnitType_MusicDevice:
  25995. result = "Synth";
  25996. break;
  25997. case kAudioUnitType_Generator:
  25998. result = "Generator";
  25999. break;
  26000. case kAudioUnitType_Panner:
  26001. result = "Panner";
  26002. break;
  26003. default:
  26004. break;
  26005. }
  26006. return result;
  26007. }
  26008. int AudioUnitPluginInstance::getNumParameters()
  26009. {
  26010. return parameterIds.size();
  26011. }
  26012. float AudioUnitPluginInstance::getParameter (int index)
  26013. {
  26014. const ScopedLock sl (lock);
  26015. Float32 value = 0.0f;
  26016. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26017. {
  26018. AudioUnitGetParameter (audioUnit,
  26019. (UInt32) parameterIds.getUnchecked (index),
  26020. kAudioUnitScope_Global, 0,
  26021. &value);
  26022. }
  26023. return value;
  26024. }
  26025. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  26026. {
  26027. const ScopedLock sl (lock);
  26028. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  26029. {
  26030. AudioUnitSetParameter (audioUnit,
  26031. (UInt32) parameterIds.getUnchecked (index),
  26032. kAudioUnitScope_Global, 0,
  26033. newValue, 0);
  26034. }
  26035. }
  26036. const String AudioUnitPluginInstance::getParameterName (int index)
  26037. {
  26038. AudioUnitParameterInfo info;
  26039. zerostruct (info);
  26040. UInt32 sz = sizeof (info);
  26041. String name;
  26042. if (AudioUnitGetProperty (audioUnit,
  26043. kAudioUnitProperty_ParameterInfo,
  26044. kAudioUnitScope_Global,
  26045. parameterIds [index], &info, &sz) == noErr)
  26046. {
  26047. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  26048. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  26049. else
  26050. name = String (info.name, sizeof (info.name));
  26051. }
  26052. return name;
  26053. }
  26054. const String AudioUnitPluginInstance::getParameterText (int index)
  26055. {
  26056. return String (getParameter (index));
  26057. }
  26058. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  26059. {
  26060. AudioUnitParameterInfo info;
  26061. UInt32 sz = sizeof (info);
  26062. if (AudioUnitGetProperty (audioUnit,
  26063. kAudioUnitProperty_ParameterInfo,
  26064. kAudioUnitScope_Global,
  26065. parameterIds [index], &info, &sz) == noErr)
  26066. {
  26067. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  26068. }
  26069. return true;
  26070. }
  26071. int AudioUnitPluginInstance::getNumPrograms()
  26072. {
  26073. CFArrayRef presets;
  26074. UInt32 sz = sizeof (CFArrayRef);
  26075. int num = 0;
  26076. if (AudioUnitGetProperty (audioUnit,
  26077. kAudioUnitProperty_FactoryPresets,
  26078. kAudioUnitScope_Global,
  26079. 0, &presets, &sz) == noErr)
  26080. {
  26081. num = (int) CFArrayGetCount (presets);
  26082. CFRelease (presets);
  26083. }
  26084. return num;
  26085. }
  26086. int AudioUnitPluginInstance::getCurrentProgram()
  26087. {
  26088. AUPreset current;
  26089. current.presetNumber = 0;
  26090. UInt32 sz = sizeof (AUPreset);
  26091. AudioUnitGetProperty (audioUnit,
  26092. kAudioUnitProperty_FactoryPresets,
  26093. kAudioUnitScope_Global,
  26094. 0, &current, &sz);
  26095. return current.presetNumber;
  26096. }
  26097. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  26098. {
  26099. AUPreset current;
  26100. current.presetNumber = newIndex;
  26101. current.presetName = 0;
  26102. AudioUnitSetProperty (audioUnit,
  26103. kAudioUnitProperty_FactoryPresets,
  26104. kAudioUnitScope_Global,
  26105. 0, &current, sizeof (AUPreset));
  26106. }
  26107. const String AudioUnitPluginInstance::getProgramName (int index)
  26108. {
  26109. String s;
  26110. CFArrayRef presets;
  26111. UInt32 sz = sizeof (CFArrayRef);
  26112. if (AudioUnitGetProperty (audioUnit,
  26113. kAudioUnitProperty_FactoryPresets,
  26114. kAudioUnitScope_Global,
  26115. 0, &presets, &sz) == noErr)
  26116. {
  26117. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  26118. {
  26119. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  26120. if (p != 0 && p->presetNumber == index)
  26121. {
  26122. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  26123. break;
  26124. }
  26125. }
  26126. CFRelease (presets);
  26127. }
  26128. return s;
  26129. }
  26130. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  26131. {
  26132. jassertfalse; // xxx not implemented!
  26133. }
  26134. const String AudioUnitPluginInstance::getInputChannelName (int index) const
  26135. {
  26136. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  26137. return "Input " + String (index + 1);
  26138. return String::empty;
  26139. }
  26140. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  26141. {
  26142. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  26143. return false;
  26144. return true;
  26145. }
  26146. const String AudioUnitPluginInstance::getOutputChannelName (int index) const
  26147. {
  26148. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  26149. return "Output " + String (index + 1);
  26150. return String::empty;
  26151. }
  26152. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  26153. {
  26154. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  26155. return false;
  26156. return true;
  26157. }
  26158. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  26159. {
  26160. getCurrentProgramStateInformation (destData);
  26161. }
  26162. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  26163. {
  26164. CFPropertyListRef propertyList = 0;
  26165. UInt32 sz = sizeof (CFPropertyListRef);
  26166. if (AudioUnitGetProperty (audioUnit,
  26167. kAudioUnitProperty_ClassInfo,
  26168. kAudioUnitScope_Global,
  26169. 0, &propertyList, &sz) == noErr)
  26170. {
  26171. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  26172. CFWriteStreamOpen (stream);
  26173. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  26174. CFWriteStreamClose (stream);
  26175. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  26176. destData.setSize (bytesWritten);
  26177. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  26178. CFRelease (data);
  26179. CFRelease (stream);
  26180. CFRelease (propertyList);
  26181. }
  26182. }
  26183. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  26184. {
  26185. setCurrentProgramStateInformation (data, sizeInBytes);
  26186. }
  26187. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26188. {
  26189. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  26190. (const UInt8*) data,
  26191. sizeInBytes,
  26192. kCFAllocatorNull);
  26193. CFReadStreamOpen (stream);
  26194. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  26195. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  26196. stream,
  26197. 0,
  26198. kCFPropertyListImmutable,
  26199. &format,
  26200. 0);
  26201. CFRelease (stream);
  26202. if (propertyList != 0)
  26203. AudioUnitSetProperty (audioUnit,
  26204. kAudioUnitProperty_ClassInfo,
  26205. kAudioUnitScope_Global,
  26206. 0, &propertyList, sizeof (propertyList));
  26207. }
  26208. AudioUnitPluginFormat::AudioUnitPluginFormat()
  26209. {
  26210. }
  26211. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  26212. {
  26213. }
  26214. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  26215. const String& fileOrIdentifier)
  26216. {
  26217. if (! fileMightContainThisPluginType (fileOrIdentifier))
  26218. return;
  26219. PluginDescription desc;
  26220. desc.fileOrIdentifier = fileOrIdentifier;
  26221. desc.uid = 0;
  26222. try
  26223. {
  26224. ScopedPointer <AudioPluginInstance> createdInstance (createInstanceFromDescription (desc));
  26225. AudioUnitPluginInstance* const auInstance = dynamic_cast <AudioUnitPluginInstance*> ((AudioPluginInstance*) createdInstance);
  26226. if (auInstance != 0)
  26227. {
  26228. auInstance->fillInPluginDescription (desc);
  26229. results.add (new PluginDescription (desc));
  26230. }
  26231. }
  26232. catch (...)
  26233. {
  26234. // crashed while loading...
  26235. }
  26236. }
  26237. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  26238. {
  26239. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  26240. {
  26241. ScopedPointer <AudioUnitPluginInstance> result (new AudioUnitPluginInstance (desc.fileOrIdentifier));
  26242. if (result->audioUnit != 0)
  26243. {
  26244. result->initialise();
  26245. return result.release();
  26246. }
  26247. }
  26248. return 0;
  26249. }
  26250. const StringArray AudioUnitPluginFormat::searchPathsForPlugins (const FileSearchPath& /*directoriesToSearch*/,
  26251. const bool /*recursive*/)
  26252. {
  26253. StringArray result;
  26254. ComponentRecord* comp = 0;
  26255. ComponentDescription desc;
  26256. zerostruct (desc);
  26257. for (;;)
  26258. {
  26259. zerostruct (desc);
  26260. comp = FindNextComponent (comp, &desc);
  26261. if (comp == 0)
  26262. break;
  26263. GetComponentInfo (comp, &desc, 0, 0, 0);
  26264. if (desc.componentType == kAudioUnitType_MusicDevice
  26265. || desc.componentType == kAudioUnitType_MusicEffect
  26266. || desc.componentType == kAudioUnitType_Effect
  26267. || desc.componentType == kAudioUnitType_Generator
  26268. || desc.componentType == kAudioUnitType_Panner)
  26269. {
  26270. const String s (AudioUnitFormatHelpers::createAUPluginIdentifier (desc));
  26271. DBG (s);
  26272. result.add (s);
  26273. }
  26274. }
  26275. return result;
  26276. }
  26277. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  26278. {
  26279. ComponentDescription desc;
  26280. String name, version, manufacturer;
  26281. if (AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer))
  26282. return FindNextComponent (0, &desc) != 0;
  26283. const File f (fileOrIdentifier);
  26284. return f.hasFileExtension (".component")
  26285. && f.isDirectory();
  26286. }
  26287. const String AudioUnitPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  26288. {
  26289. ComponentDescription desc;
  26290. String name, version, manufacturer;
  26291. AudioUnitFormatHelpers::getComponentDescFromIdentifier (fileOrIdentifier, desc, name, version, manufacturer);
  26292. if (name.isEmpty())
  26293. name = fileOrIdentifier;
  26294. return name;
  26295. }
  26296. bool AudioUnitPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  26297. {
  26298. if (desc.fileOrIdentifier.startsWithIgnoreCase (AudioUnitFormatHelpers::auIdentifierPrefix))
  26299. return fileMightContainThisPluginType (desc.fileOrIdentifier);
  26300. else
  26301. return File (desc.fileOrIdentifier).exists();
  26302. }
  26303. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  26304. {
  26305. return FileSearchPath ("/(Default AudioUnit locations)");
  26306. }
  26307. #endif
  26308. END_JUCE_NAMESPACE
  26309. #undef log
  26310. #endif
  26311. /*** End of inlined file: juce_AudioUnitPluginFormat.mm ***/
  26312. /*** Start of inlined file: juce_VSTPluginFormat.mm ***/
  26313. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  26314. #define JUCE_MAC_VST_INCLUDED 1
  26315. /*** Start of inlined file: juce_VSTPluginFormat.cpp ***/
  26316. #if JUCE_PLUGINHOST_VST && (JUCE_MAC_VST_INCLUDED || ! JUCE_MAC)
  26317. #if JUCE_WINDOWS
  26318. #undef _WIN32_WINNT
  26319. #define _WIN32_WINNT 0x500
  26320. #undef STRICT
  26321. #define STRICT
  26322. #include <windows.h>
  26323. #include <float.h>
  26324. #pragma warning (disable : 4312 4355)
  26325. #elif JUCE_LINUX
  26326. #include <float.h>
  26327. #include <sys/time.h>
  26328. #include <X11/Xlib.h>
  26329. #include <X11/Xutil.h>
  26330. #include <X11/Xatom.h>
  26331. #undef Font
  26332. #undef KeyPress
  26333. #undef Drawable
  26334. #undef Time
  26335. #else
  26336. #include <Cocoa/Cocoa.h>
  26337. #include <Carbon/Carbon.h>
  26338. #endif
  26339. #if ! (JUCE_MAC && JUCE_64BIT)
  26340. BEGIN_JUCE_NAMESPACE
  26341. #if JUCE_MAC && JUCE_SUPPORT_CARBON
  26342. #endif
  26343. #undef PRAGMA_ALIGN_SUPPORTED
  26344. #define VST_FORCE_DEPRECATED 0
  26345. #if JUCE_MSVC
  26346. #pragma warning (push)
  26347. #pragma warning (disable: 4996)
  26348. #endif
  26349. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  26350. your include path if you want to add VST support.
  26351. If you're not interested in VSTs, you can disable them by changing the
  26352. JUCE_PLUGINHOST_VST flag in juce_Config.h
  26353. */
  26354. #include "pluginterfaces/vst2.x/aeffectx.h"
  26355. #if JUCE_MSVC
  26356. #pragma warning (pop)
  26357. #endif
  26358. #if JUCE_LINUX
  26359. #define Font JUCE_NAMESPACE::Font
  26360. #define KeyPress JUCE_NAMESPACE::KeyPress
  26361. #define Drawable JUCE_NAMESPACE::Drawable
  26362. #define Time JUCE_NAMESPACE::Time
  26363. #endif
  26364. /*** Start of inlined file: juce_VSTMidiEventList.h ***/
  26365. #ifdef __aeffect__
  26366. #ifndef __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26367. #define __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26368. /** Holds a set of VSTMidiEvent objects and makes it easy to add
  26369. events to the list.
  26370. This is used by both the VST hosting code and the plugin wrapper.
  26371. */
  26372. class VSTMidiEventList
  26373. {
  26374. public:
  26375. VSTMidiEventList()
  26376. : numEventsUsed (0), numEventsAllocated (0)
  26377. {
  26378. }
  26379. ~VSTMidiEventList()
  26380. {
  26381. freeEvents();
  26382. }
  26383. void clear()
  26384. {
  26385. numEventsUsed = 0;
  26386. if (events != 0)
  26387. events->numEvents = 0;
  26388. }
  26389. void addEvent (const void* const midiData, const int numBytes, const int frameOffset)
  26390. {
  26391. ensureSize (numEventsUsed + 1);
  26392. VstMidiEvent* const e = (VstMidiEvent*) (events->events [numEventsUsed]);
  26393. events->numEvents = ++numEventsUsed;
  26394. if (numBytes <= 4)
  26395. {
  26396. if (e->type == kVstSysExType)
  26397. {
  26398. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26399. e->type = kVstMidiType;
  26400. e->byteSize = sizeof (VstMidiEvent);
  26401. e->noteLength = 0;
  26402. e->noteOffset = 0;
  26403. e->detune = 0;
  26404. e->noteOffVelocity = 0;
  26405. }
  26406. e->deltaFrames = frameOffset;
  26407. memcpy (e->midiData, midiData, numBytes);
  26408. }
  26409. else
  26410. {
  26411. VstMidiSysexEvent* const se = (VstMidiSysexEvent*) e;
  26412. if (se->type == kVstSysExType)
  26413. se->sysexDump = (char*) juce_realloc (se->sysexDump, numBytes);
  26414. else
  26415. se->sysexDump = (char*) juce_malloc (numBytes);
  26416. memcpy (se->sysexDump, midiData, numBytes);
  26417. se->type = kVstSysExType;
  26418. se->byteSize = sizeof (VstMidiSysexEvent);
  26419. se->deltaFrames = frameOffset;
  26420. se->flags = 0;
  26421. se->dumpBytes = numBytes;
  26422. se->resvd1 = 0;
  26423. se->resvd2 = 0;
  26424. }
  26425. }
  26426. // Handy method to pull the events out of an event buffer supplied by the host
  26427. // or plugin.
  26428. static void addEventsToMidiBuffer (const VstEvents* events, MidiBuffer& dest)
  26429. {
  26430. for (int i = 0; i < events->numEvents; ++i)
  26431. {
  26432. const VstEvent* const e = events->events[i];
  26433. if (e != 0)
  26434. {
  26435. if (e->type == kVstMidiType)
  26436. {
  26437. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiEvent*) e)->midiData,
  26438. 4, e->deltaFrames);
  26439. }
  26440. else if (e->type == kVstSysExType)
  26441. {
  26442. dest.addEvent ((const JUCE_NAMESPACE::uint8*) ((const VstMidiSysexEvent*) e)->sysexDump,
  26443. (int) ((const VstMidiSysexEvent*) e)->dumpBytes,
  26444. e->deltaFrames);
  26445. }
  26446. }
  26447. }
  26448. }
  26449. void ensureSize (int numEventsNeeded)
  26450. {
  26451. if (numEventsNeeded > numEventsAllocated)
  26452. {
  26453. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  26454. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  26455. if (events == 0)
  26456. events.calloc (size, 1);
  26457. else
  26458. events.realloc (size, 1);
  26459. for (int i = numEventsAllocated; i < numEventsNeeded; ++i)
  26460. {
  26461. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (jmax ((int) sizeof (VstMidiEvent),
  26462. (int) sizeof (VstMidiSysexEvent)));
  26463. e->type = kVstMidiType;
  26464. e->byteSize = sizeof (VstMidiEvent);
  26465. events->events[i] = (VstEvent*) e;
  26466. }
  26467. numEventsAllocated = numEventsNeeded;
  26468. }
  26469. }
  26470. void freeEvents()
  26471. {
  26472. if (events != 0)
  26473. {
  26474. for (int i = numEventsAllocated; --i >= 0;)
  26475. {
  26476. VstMidiEvent* const e = (VstMidiEvent*) (events->events[i]);
  26477. if (e->type == kVstSysExType)
  26478. juce_free (((VstMidiSysexEvent*) e)->sysexDump);
  26479. juce_free (e);
  26480. }
  26481. events.free();
  26482. numEventsUsed = 0;
  26483. numEventsAllocated = 0;
  26484. }
  26485. }
  26486. HeapBlock <VstEvents> events;
  26487. private:
  26488. int numEventsUsed, numEventsAllocated;
  26489. };
  26490. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26491. #endif // __JUCE_VSTMIDIEVENTLIST_JUCEHEADER__
  26492. /*** End of inlined file: juce_VSTMidiEventList.h ***/
  26493. #if ! JUCE_WINDOWS
  26494. static void _fpreset() {}
  26495. static void _clearfp() {}
  26496. #endif
  26497. extern void juce_callAnyTimersSynchronously();
  26498. const int fxbVersionNum = 1;
  26499. struct fxProgram
  26500. {
  26501. long chunkMagic; // 'CcnK'
  26502. long byteSize; // of this chunk, excl. magic + byteSize
  26503. long fxMagic; // 'FxCk'
  26504. long version;
  26505. long fxID; // fx unique id
  26506. long fxVersion;
  26507. long numParams;
  26508. char prgName[28];
  26509. float params[1]; // variable no. of parameters
  26510. };
  26511. struct fxSet
  26512. {
  26513. long chunkMagic; // 'CcnK'
  26514. long byteSize; // of this chunk, excl. magic + byteSize
  26515. long fxMagic; // 'FxBk'
  26516. long version;
  26517. long fxID; // fx unique id
  26518. long fxVersion;
  26519. long numPrograms;
  26520. char future[128];
  26521. fxProgram programs[1]; // variable no. of programs
  26522. };
  26523. struct fxChunkSet
  26524. {
  26525. long chunkMagic; // 'CcnK'
  26526. long byteSize; // of this chunk, excl. magic + byteSize
  26527. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26528. long version;
  26529. long fxID; // fx unique id
  26530. long fxVersion;
  26531. long numPrograms;
  26532. char future[128];
  26533. long chunkSize;
  26534. char chunk[8]; // variable
  26535. };
  26536. struct fxProgramSet
  26537. {
  26538. long chunkMagic; // 'CcnK'
  26539. long byteSize; // of this chunk, excl. magic + byteSize
  26540. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  26541. long version;
  26542. long fxID; // fx unique id
  26543. long fxVersion;
  26544. long numPrograms;
  26545. char name[28];
  26546. long chunkSize;
  26547. char chunk[8]; // variable
  26548. };
  26549. namespace
  26550. {
  26551. long vst_swap (const long x) throw()
  26552. {
  26553. #ifdef JUCE_LITTLE_ENDIAN
  26554. return (long) ByteOrder::swap ((uint32) x);
  26555. #else
  26556. return x;
  26557. #endif
  26558. }
  26559. float vst_swapFloat (const float x) throw()
  26560. {
  26561. #ifdef JUCE_LITTLE_ENDIAN
  26562. union { uint32 asInt; float asFloat; } n;
  26563. n.asFloat = x;
  26564. n.asInt = ByteOrder::swap (n.asInt);
  26565. return n.asFloat;
  26566. #else
  26567. return x;
  26568. #endif
  26569. }
  26570. double getVSTHostTimeNanoseconds()
  26571. {
  26572. #if JUCE_WINDOWS
  26573. return timeGetTime() * 1000000.0;
  26574. #elif JUCE_LINUX
  26575. timeval micro;
  26576. gettimeofday (&micro, 0);
  26577. return micro.tv_usec * 1000.0;
  26578. #elif JUCE_MAC
  26579. UnsignedWide micro;
  26580. Microseconds (&micro);
  26581. return micro.lo * 1000.0;
  26582. #endif
  26583. }
  26584. }
  26585. typedef AEffect* (*MainCall) (audioMasterCallback);
  26586. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  26587. static int shellUIDToCreate = 0;
  26588. static int insideVSTCallback = 0;
  26589. class VSTPluginWindow;
  26590. // Change this to disable logging of various VST activities
  26591. #ifndef VST_LOGGING
  26592. #define VST_LOGGING 1
  26593. #endif
  26594. #if VST_LOGGING
  26595. #define log(a) Logger::writeToLog(a);
  26596. #else
  26597. #define log(a)
  26598. #endif
  26599. #if JUCE_MAC && JUCE_PPC
  26600. static void* NewCFMFromMachO (void* const machofp) throw()
  26601. {
  26602. void* result = juce_malloc (8);
  26603. ((void**) result)[0] = machofp;
  26604. ((void**) result)[1] = result;
  26605. return result;
  26606. }
  26607. #endif
  26608. #if JUCE_LINUX
  26609. extern Display* display;
  26610. extern XContext windowHandleXContext;
  26611. typedef void (*EventProcPtr) (XEvent* ev);
  26612. static bool xErrorTriggered;
  26613. namespace
  26614. {
  26615. int temporaryErrorHandler (Display*, XErrorEvent*)
  26616. {
  26617. xErrorTriggered = true;
  26618. return 0;
  26619. }
  26620. int getPropertyFromXWindow (Window handle, Atom atom)
  26621. {
  26622. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  26623. xErrorTriggered = false;
  26624. int userSize;
  26625. unsigned long bytes, userCount;
  26626. unsigned char* data;
  26627. Atom userType;
  26628. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  26629. &userType, &userSize, &userCount, &bytes, &data);
  26630. XSetErrorHandler (oldErrorHandler);
  26631. return (userCount == 1 && ! xErrorTriggered) ? *reinterpret_cast<int*> (data)
  26632. : 0;
  26633. }
  26634. Window getChildWindow (Window windowToCheck)
  26635. {
  26636. Window rootWindow, parentWindow;
  26637. Window* childWindows;
  26638. unsigned int numChildren;
  26639. XQueryTree (display,
  26640. windowToCheck,
  26641. &rootWindow,
  26642. &parentWindow,
  26643. &childWindows,
  26644. &numChildren);
  26645. if (numChildren > 0)
  26646. return childWindows [0];
  26647. return 0;
  26648. }
  26649. void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  26650. {
  26651. if (e.mods.isLeftButtonDown())
  26652. {
  26653. ev.xbutton.button = Button1;
  26654. ev.xbutton.state |= Button1Mask;
  26655. }
  26656. else if (e.mods.isRightButtonDown())
  26657. {
  26658. ev.xbutton.button = Button3;
  26659. ev.xbutton.state |= Button3Mask;
  26660. }
  26661. else if (e.mods.isMiddleButtonDown())
  26662. {
  26663. ev.xbutton.button = Button2;
  26664. ev.xbutton.state |= Button2Mask;
  26665. }
  26666. }
  26667. void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  26668. {
  26669. if (e.mods.isLeftButtonDown()) ev.xmotion.state |= Button1Mask;
  26670. else if (e.mods.isRightButtonDown()) ev.xmotion.state |= Button3Mask;
  26671. else if (e.mods.isMiddleButtonDown()) ev.xmotion.state |= Button2Mask;
  26672. }
  26673. void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  26674. {
  26675. if (e.mods.isLeftButtonDown()) ev.xcrossing.state |= Button1Mask;
  26676. else if (e.mods.isRightButtonDown()) ev.xcrossing.state |= Button3Mask;
  26677. else if (e.mods.isMiddleButtonDown()) ev.xcrossing.state |= Button2Mask;
  26678. }
  26679. void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  26680. {
  26681. if (increment < 0)
  26682. {
  26683. ev.xbutton.button = Button5;
  26684. ev.xbutton.state |= Button5Mask;
  26685. }
  26686. else if (increment > 0)
  26687. {
  26688. ev.xbutton.button = Button4;
  26689. ev.xbutton.state |= Button4Mask;
  26690. }
  26691. }
  26692. }
  26693. #endif
  26694. class ModuleHandle : public ReferenceCountedObject
  26695. {
  26696. public:
  26697. File file;
  26698. MainCall moduleMain;
  26699. String pluginName;
  26700. static Array <ModuleHandle*>& getActiveModules()
  26701. {
  26702. static Array <ModuleHandle*> activeModules;
  26703. return activeModules;
  26704. }
  26705. static ModuleHandle* findOrCreateModule (const File& file)
  26706. {
  26707. for (int i = getActiveModules().size(); --i >= 0;)
  26708. {
  26709. ModuleHandle* const module = getActiveModules().getUnchecked(i);
  26710. if (module->file == file)
  26711. return module;
  26712. }
  26713. _fpreset(); // (doesn't do any harm)
  26714. ++insideVSTCallback;
  26715. shellUIDToCreate = 0;
  26716. log ("Attempting to load VST: " + file.getFullPathName());
  26717. ScopedPointer <ModuleHandle> m (new ModuleHandle (file));
  26718. if (! m->open())
  26719. m = 0;
  26720. --insideVSTCallback;
  26721. _fpreset(); // (doesn't do any harm)
  26722. return m.release();
  26723. }
  26724. ModuleHandle (const File& file_)
  26725. : file (file_),
  26726. moduleMain (0),
  26727. #if JUCE_WINDOWS || JUCE_LINUX
  26728. hModule (0)
  26729. #elif JUCE_MAC
  26730. fragId (0),
  26731. resHandle (0),
  26732. bundleRef (0),
  26733. resFileId (0)
  26734. #endif
  26735. {
  26736. getActiveModules().add (this);
  26737. #if JUCE_WINDOWS || JUCE_LINUX
  26738. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  26739. #elif JUCE_MAC
  26740. FSRef ref;
  26741. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  26742. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  26743. #endif
  26744. }
  26745. ~ModuleHandle()
  26746. {
  26747. getActiveModules().removeValue (this);
  26748. close();
  26749. }
  26750. juce_UseDebuggingNewOperator
  26751. #if JUCE_WINDOWS || JUCE_LINUX
  26752. void* hModule;
  26753. String fullParentDirectoryPathName;
  26754. bool open()
  26755. {
  26756. #if JUCE_WINDOWS
  26757. static bool timePeriodSet = false;
  26758. if (! timePeriodSet)
  26759. {
  26760. timePeriodSet = true;
  26761. timeBeginPeriod (2);
  26762. }
  26763. #endif
  26764. pluginName = file.getFileNameWithoutExtension();
  26765. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  26766. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  26767. if (moduleMain == 0)
  26768. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  26769. return moduleMain != 0;
  26770. }
  26771. void close()
  26772. {
  26773. _fpreset(); // (doesn't do any harm)
  26774. PlatformUtilities::freeDynamicLibrary (hModule);
  26775. }
  26776. void closeEffect (AEffect* eff)
  26777. {
  26778. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26779. }
  26780. #else
  26781. CFragConnectionID fragId;
  26782. Handle resHandle;
  26783. CFBundleRef bundleRef;
  26784. FSSpec parentDirFSSpec;
  26785. short resFileId;
  26786. bool open()
  26787. {
  26788. bool ok = false;
  26789. const String filename (file.getFullPathName());
  26790. if (file.hasFileExtension (".vst"))
  26791. {
  26792. const char* const utf8 = filename.toUTF8();
  26793. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  26794. strlen (utf8), file.isDirectory());
  26795. if (url != 0)
  26796. {
  26797. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  26798. CFRelease (url);
  26799. if (bundleRef != 0)
  26800. {
  26801. if (CFBundleLoadExecutable (bundleRef))
  26802. {
  26803. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  26804. if (moduleMain == 0)
  26805. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  26806. if (moduleMain != 0)
  26807. {
  26808. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  26809. if (name != 0)
  26810. {
  26811. if (CFGetTypeID (name) == CFStringGetTypeID())
  26812. {
  26813. char buffer[1024];
  26814. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  26815. pluginName = buffer;
  26816. }
  26817. }
  26818. if (pluginName.isEmpty())
  26819. pluginName = file.getFileNameWithoutExtension();
  26820. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  26821. ok = true;
  26822. }
  26823. }
  26824. if (! ok)
  26825. {
  26826. CFBundleUnloadExecutable (bundleRef);
  26827. CFRelease (bundleRef);
  26828. bundleRef = 0;
  26829. }
  26830. }
  26831. }
  26832. }
  26833. #if JUCE_PPC
  26834. else
  26835. {
  26836. FSRef fn;
  26837. if (FSPathMakeRef ((UInt8*) filename.toUTF8(), &fn, 0) == noErr)
  26838. {
  26839. resFileId = FSOpenResFile (&fn, fsRdPerm);
  26840. if (resFileId != -1)
  26841. {
  26842. const int numEffs = Count1Resources ('aEff');
  26843. for (int i = 0; i < numEffs; ++i)
  26844. {
  26845. resHandle = Get1IndResource ('aEff', i + 1);
  26846. if (resHandle != 0)
  26847. {
  26848. OSType type;
  26849. Str255 name;
  26850. SInt16 id;
  26851. GetResInfo (resHandle, &id, &type, name);
  26852. pluginName = String ((const char*) name + 1, name[0]);
  26853. DetachResource (resHandle);
  26854. HLock (resHandle);
  26855. Ptr ptr;
  26856. Str255 errorText;
  26857. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  26858. name, kPrivateCFragCopy,
  26859. &fragId, &ptr, errorText);
  26860. if (err == noErr)
  26861. {
  26862. moduleMain = (MainCall) newMachOFromCFM (ptr);
  26863. ok = true;
  26864. }
  26865. else
  26866. {
  26867. HUnlock (resHandle);
  26868. }
  26869. break;
  26870. }
  26871. }
  26872. if (! ok)
  26873. CloseResFile (resFileId);
  26874. }
  26875. }
  26876. }
  26877. #endif
  26878. return ok;
  26879. }
  26880. void close()
  26881. {
  26882. #if JUCE_PPC
  26883. if (fragId != 0)
  26884. {
  26885. if (moduleMain != 0)
  26886. disposeMachOFromCFM ((void*) moduleMain);
  26887. CloseConnection (&fragId);
  26888. HUnlock (resHandle);
  26889. if (resFileId != 0)
  26890. CloseResFile (resFileId);
  26891. }
  26892. else
  26893. #endif
  26894. if (bundleRef != 0)
  26895. {
  26896. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  26897. if (CFGetRetainCount (bundleRef) == 1)
  26898. CFBundleUnloadExecutable (bundleRef);
  26899. if (CFGetRetainCount (bundleRef) > 0)
  26900. CFRelease (bundleRef);
  26901. }
  26902. }
  26903. void closeEffect (AEffect* eff)
  26904. {
  26905. #if JUCE_PPC
  26906. if (fragId != 0)
  26907. {
  26908. Array<void*> thingsToDelete;
  26909. thingsToDelete.add ((void*) eff->dispatcher);
  26910. thingsToDelete.add ((void*) eff->process);
  26911. thingsToDelete.add ((void*) eff->setParameter);
  26912. thingsToDelete.add ((void*) eff->getParameter);
  26913. thingsToDelete.add ((void*) eff->processReplacing);
  26914. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26915. for (int i = thingsToDelete.size(); --i >= 0;)
  26916. disposeMachOFromCFM (thingsToDelete[i]);
  26917. }
  26918. else
  26919. #endif
  26920. {
  26921. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  26922. }
  26923. }
  26924. #if JUCE_PPC
  26925. static void* newMachOFromCFM (void* cfmfp)
  26926. {
  26927. if (cfmfp == 0)
  26928. return 0;
  26929. UInt32* const mfp = new UInt32[6];
  26930. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  26931. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  26932. mfp[2] = 0x800c0000;
  26933. mfp[3] = 0x804c0004;
  26934. mfp[4] = 0x7c0903a6;
  26935. mfp[5] = 0x4e800420;
  26936. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  26937. return mfp;
  26938. }
  26939. static void disposeMachOFromCFM (void* ptr)
  26940. {
  26941. delete[] static_cast <UInt32*> (ptr);
  26942. }
  26943. void coerceAEffectFunctionCalls (AEffect* eff)
  26944. {
  26945. if (fragId != 0)
  26946. {
  26947. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  26948. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  26949. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  26950. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  26951. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  26952. }
  26953. }
  26954. #endif
  26955. #endif
  26956. };
  26957. /**
  26958. An instance of a plugin, created by a VSTPluginFormat.
  26959. */
  26960. class VSTPluginInstance : public AudioPluginInstance,
  26961. private Timer,
  26962. private AsyncUpdater
  26963. {
  26964. public:
  26965. ~VSTPluginInstance();
  26966. // AudioPluginInstance methods:
  26967. void fillInPluginDescription (PluginDescription& desc) const
  26968. {
  26969. desc.name = name;
  26970. desc.fileOrIdentifier = module->file.getFullPathName();
  26971. desc.uid = getUID();
  26972. desc.lastFileModTime = module->file.getLastModificationTime();
  26973. desc.pluginFormatName = "VST";
  26974. desc.category = getCategory();
  26975. {
  26976. char buffer [kVstMaxVendorStrLen + 8];
  26977. zerostruct (buffer);
  26978. dispatch (effGetVendorString, 0, 0, buffer, 0);
  26979. desc.manufacturerName = buffer;
  26980. }
  26981. desc.version = getVersion();
  26982. desc.numInputChannels = getNumInputChannels();
  26983. desc.numOutputChannels = getNumOutputChannels();
  26984. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  26985. }
  26986. const String getName() const { return name; }
  26987. int getUID() const;
  26988. bool acceptsMidi() const { return wantsMidiMessages; }
  26989. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  26990. // AudioProcessor methods:
  26991. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  26992. void releaseResources();
  26993. void processBlock (AudioSampleBuffer& buffer,
  26994. MidiBuffer& midiMessages);
  26995. bool hasEditor() const { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  26996. AudioProcessorEditor* createEditor();
  26997. const String getInputChannelName (int index) const;
  26998. bool isInputChannelStereoPair (int index) const;
  26999. const String getOutputChannelName (int index) const;
  27000. bool isOutputChannelStereoPair (int index) const;
  27001. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  27002. float getParameter (int index);
  27003. void setParameter (int index, float newValue);
  27004. const String getParameterName (int index);
  27005. const String getParameterText (int index);
  27006. bool isParameterAutomatable (int index) const;
  27007. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  27008. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  27009. void setCurrentProgram (int index);
  27010. const String getProgramName (int index);
  27011. void changeProgramName (int index, const String& newName);
  27012. void getStateInformation (MemoryBlock& destData);
  27013. void getCurrentProgramStateInformation (MemoryBlock& destData);
  27014. void setStateInformation (const void* data, int sizeInBytes);
  27015. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  27016. void timerCallback();
  27017. void handleAsyncUpdate();
  27018. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  27019. juce_UseDebuggingNewOperator
  27020. private:
  27021. friend class VSTPluginWindow;
  27022. friend class VSTPluginFormat;
  27023. AEffect* effect;
  27024. String name;
  27025. CriticalSection lock;
  27026. bool wantsMidiMessages, initialised, isPowerOn;
  27027. mutable StringArray programNames;
  27028. AudioSampleBuffer tempBuffer;
  27029. CriticalSection midiInLock;
  27030. MidiBuffer incomingMidi;
  27031. VSTMidiEventList midiEventsToSend;
  27032. VstTimeInfo vstHostTime;
  27033. ReferenceCountedObjectPtr <ModuleHandle> module;
  27034. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  27035. bool restoreProgramSettings (const fxProgram* const prog);
  27036. const String getCurrentProgramName();
  27037. void setParamsInProgramBlock (fxProgram* const prog);
  27038. void updateStoredProgramNames();
  27039. void initialise();
  27040. void handleMidiFromPlugin (const VstEvents* const events);
  27041. void createTempParameterStore (MemoryBlock& dest);
  27042. void restoreFromTempParameterStore (const MemoryBlock& mb);
  27043. const String getParameterLabel (int index) const;
  27044. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  27045. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  27046. void setChunkData (const char* data, int size, bool isPreset);
  27047. bool loadFromFXBFile (const void* data, int numBytes);
  27048. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  27049. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  27050. const String getVersion() const;
  27051. const String getCategory() const;
  27052. void setPower (const bool on);
  27053. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  27054. };
  27055. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  27056. : effect (0),
  27057. wantsMidiMessages (false),
  27058. initialised (false),
  27059. isPowerOn (false),
  27060. tempBuffer (1, 1),
  27061. module (module_)
  27062. {
  27063. try
  27064. {
  27065. _fpreset();
  27066. ++insideVSTCallback;
  27067. name = module->pluginName;
  27068. log ("Creating VST instance: " + name);
  27069. #if JUCE_MAC
  27070. if (module->resFileId != 0)
  27071. UseResFile (module->resFileId);
  27072. #if JUCE_PPC
  27073. if (module->fragId != 0)
  27074. {
  27075. static void* audioMasterCoerced = 0;
  27076. if (audioMasterCoerced == 0)
  27077. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  27078. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  27079. }
  27080. else
  27081. #endif
  27082. #endif
  27083. {
  27084. effect = module->moduleMain (&audioMaster);
  27085. }
  27086. --insideVSTCallback;
  27087. if (effect != 0 && effect->magic == kEffectMagic)
  27088. {
  27089. #if JUCE_PPC
  27090. module->coerceAEffectFunctionCalls (effect);
  27091. #endif
  27092. jassert (effect->resvd2 == 0);
  27093. jassert (effect->object != 0);
  27094. _fpreset(); // some dodgy plugs fuck around with this
  27095. }
  27096. else
  27097. {
  27098. effect = 0;
  27099. }
  27100. }
  27101. catch (...)
  27102. {
  27103. --insideVSTCallback;
  27104. }
  27105. }
  27106. VSTPluginInstance::~VSTPluginInstance()
  27107. {
  27108. const ScopedLock sl (lock);
  27109. jassert (insideVSTCallback == 0);
  27110. if (effect != 0 && effect->magic == kEffectMagic)
  27111. {
  27112. try
  27113. {
  27114. #if JUCE_MAC
  27115. if (module->resFileId != 0)
  27116. UseResFile (module->resFileId);
  27117. #endif
  27118. // Must delete any editors before deleting the plugin instance!
  27119. jassert (getActiveEditor() == 0);
  27120. _fpreset(); // some dodgy plugs fuck around with this
  27121. module->closeEffect (effect);
  27122. }
  27123. catch (...)
  27124. {}
  27125. }
  27126. module = 0;
  27127. effect = 0;
  27128. }
  27129. void VSTPluginInstance::initialise()
  27130. {
  27131. if (initialised || effect == 0)
  27132. return;
  27133. log ("Initialising VST: " + module->pluginName);
  27134. initialised = true;
  27135. dispatch (effIdentify, 0, 0, 0, 0);
  27136. // this code would ask the plugin for its name, but so few plugins
  27137. // actually bother implementing this correctly, that it's better to
  27138. // just ignore it and use the file name instead.
  27139. /* {
  27140. char buffer [256];
  27141. zerostruct (buffer);
  27142. dispatch (effGetEffectName, 0, 0, buffer, 0);
  27143. name = String (buffer).trim();
  27144. if (name.isEmpty())
  27145. name = module->pluginName;
  27146. }
  27147. */
  27148. if (getSampleRate() > 0)
  27149. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  27150. if (getBlockSize() > 0)
  27151. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  27152. dispatch (effOpen, 0, 0, 0, 0);
  27153. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27154. getSampleRate(), getBlockSize());
  27155. if (getNumPrograms() > 1)
  27156. setCurrentProgram (0);
  27157. else
  27158. dispatch (effSetProgram, 0, 0, 0, 0);
  27159. int i;
  27160. for (i = effect->numInputs; --i >= 0;)
  27161. dispatch (effConnectInput, i, 1, 0, 0);
  27162. for (i = effect->numOutputs; --i >= 0;)
  27163. dispatch (effConnectOutput, i, 1, 0, 0);
  27164. updateStoredProgramNames();
  27165. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  27166. setLatencySamples (effect->initialDelay);
  27167. }
  27168. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  27169. int samplesPerBlockExpected)
  27170. {
  27171. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  27172. sampleRate_, samplesPerBlockExpected);
  27173. setLatencySamples (effect->initialDelay);
  27174. vstHostTime.tempo = 120.0;
  27175. vstHostTime.timeSigNumerator = 4;
  27176. vstHostTime.timeSigDenominator = 4;
  27177. vstHostTime.sampleRate = sampleRate_;
  27178. vstHostTime.samplePos = 0;
  27179. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  27180. initialise();
  27181. if (initialised)
  27182. {
  27183. wantsMidiMessages = wantsMidiMessages
  27184. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  27185. if (wantsMidiMessages)
  27186. midiEventsToSend.ensureSize (256);
  27187. else
  27188. midiEventsToSend.freeEvents();
  27189. incomingMidi.clear();
  27190. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  27191. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  27192. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  27193. if (! isPowerOn)
  27194. setPower (true);
  27195. // dodgy hack to force some plugins to initialise the sample rate..
  27196. if ((! hasEditor()) && getNumParameters() > 0)
  27197. {
  27198. const float old = getParameter (0);
  27199. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  27200. setParameter (0, old);
  27201. }
  27202. dispatch (effStartProcess, 0, 0, 0, 0);
  27203. }
  27204. }
  27205. void VSTPluginInstance::releaseResources()
  27206. {
  27207. if (initialised)
  27208. {
  27209. dispatch (effStopProcess, 0, 0, 0, 0);
  27210. setPower (false);
  27211. }
  27212. tempBuffer.setSize (1, 1);
  27213. incomingMidi.clear();
  27214. midiEventsToSend.freeEvents();
  27215. }
  27216. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  27217. MidiBuffer& midiMessages)
  27218. {
  27219. const int numSamples = buffer.getNumSamples();
  27220. if (initialised)
  27221. {
  27222. AudioPlayHead* playHead = getPlayHead();
  27223. if (playHead != 0)
  27224. {
  27225. AudioPlayHead::CurrentPositionInfo position;
  27226. playHead->getCurrentPosition (position);
  27227. vstHostTime.tempo = position.bpm;
  27228. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  27229. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  27230. vstHostTime.ppqPos = position.ppqPosition;
  27231. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  27232. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  27233. if (position.isPlaying)
  27234. vstHostTime.flags |= kVstTransportPlaying;
  27235. else
  27236. vstHostTime.flags &= ~kVstTransportPlaying;
  27237. }
  27238. vstHostTime.nanoSeconds = getVSTHostTimeNanoseconds();
  27239. if (wantsMidiMessages)
  27240. {
  27241. midiEventsToSend.clear();
  27242. midiEventsToSend.ensureSize (1);
  27243. MidiBuffer::Iterator iter (midiMessages);
  27244. const uint8* midiData;
  27245. int numBytesOfMidiData, samplePosition;
  27246. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  27247. {
  27248. midiEventsToSend.addEvent (midiData, numBytesOfMidiData,
  27249. jlimit (0, numSamples - 1, samplePosition));
  27250. }
  27251. try
  27252. {
  27253. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend.events, 0);
  27254. }
  27255. catch (...)
  27256. {}
  27257. }
  27258. _clearfp();
  27259. if ((effect->flags & effFlagsCanReplacing) != 0)
  27260. {
  27261. try
  27262. {
  27263. effect->processReplacing (effect, buffer.getArrayOfChannels(), buffer.getArrayOfChannels(), numSamples);
  27264. }
  27265. catch (...)
  27266. {}
  27267. }
  27268. else
  27269. {
  27270. tempBuffer.setSize (effect->numOutputs, numSamples);
  27271. tempBuffer.clear();
  27272. try
  27273. {
  27274. effect->process (effect, buffer.getArrayOfChannels(), tempBuffer.getArrayOfChannels(), numSamples);
  27275. }
  27276. catch (...)
  27277. {}
  27278. for (int i = effect->numOutputs; --i >= 0;)
  27279. buffer.copyFrom (i, 0, tempBuffer.getSampleData (i), numSamples);
  27280. }
  27281. }
  27282. else
  27283. {
  27284. // Not initialised, so just bypass..
  27285. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  27286. buffer.clear (i, 0, buffer.getNumSamples());
  27287. }
  27288. {
  27289. // copy any incoming midi..
  27290. const ScopedLock sl (midiInLock);
  27291. midiMessages.swapWith (incomingMidi);
  27292. incomingMidi.clear();
  27293. }
  27294. }
  27295. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  27296. {
  27297. if (events != 0)
  27298. {
  27299. const ScopedLock sl (midiInLock);
  27300. VSTMidiEventList::addEventsToMidiBuffer (events, incomingMidi);
  27301. }
  27302. }
  27303. static Array <VSTPluginWindow*> activeVSTWindows;
  27304. class VSTPluginWindow : public AudioProcessorEditor,
  27305. #if ! JUCE_MAC
  27306. public ComponentMovementWatcher,
  27307. #endif
  27308. public Timer
  27309. {
  27310. public:
  27311. VSTPluginWindow (VSTPluginInstance& plugin_)
  27312. : AudioProcessorEditor (&plugin_),
  27313. #if ! JUCE_MAC
  27314. ComponentMovementWatcher (this),
  27315. #endif
  27316. plugin (plugin_),
  27317. isOpen (false),
  27318. wasShowing (false),
  27319. pluginRefusesToResize (false),
  27320. pluginWantsKeys (false),
  27321. alreadyInside (false),
  27322. recursiveResize (false)
  27323. {
  27324. #if JUCE_WINDOWS
  27325. sizeCheckCount = 0;
  27326. pluginHWND = 0;
  27327. #elif JUCE_LINUX
  27328. pluginWindow = None;
  27329. pluginProc = None;
  27330. #else
  27331. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  27332. #endif
  27333. activeVSTWindows.add (this);
  27334. setSize (1, 1);
  27335. setOpaque (true);
  27336. setVisible (true);
  27337. }
  27338. ~VSTPluginWindow()
  27339. {
  27340. #if JUCE_MAC
  27341. innerWrapper = 0;
  27342. #else
  27343. closePluginWindow();
  27344. #endif
  27345. activeVSTWindows.removeValue (this);
  27346. plugin.editorBeingDeleted (this);
  27347. }
  27348. #if ! JUCE_MAC
  27349. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  27350. {
  27351. if (recursiveResize)
  27352. return;
  27353. Component* const topComp = getTopLevelComponent();
  27354. if (topComp->getPeer() != 0)
  27355. {
  27356. const Point<int> pos (relativePositionToOtherComponent (topComp, Point<int>()));
  27357. recursiveResize = true;
  27358. #if JUCE_WINDOWS
  27359. if (pluginHWND != 0)
  27360. MoveWindow (pluginHWND, pos.getX(), pos.getY(), getWidth(), getHeight(), TRUE);
  27361. #elif JUCE_LINUX
  27362. if (pluginWindow != 0)
  27363. {
  27364. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  27365. XMoveWindow (display, pluginWindow, pos.getX(), pos.getY());
  27366. XMapRaised (display, pluginWindow);
  27367. }
  27368. #endif
  27369. recursiveResize = false;
  27370. }
  27371. }
  27372. void componentVisibilityChanged (Component&)
  27373. {
  27374. const bool isShowingNow = isShowing();
  27375. if (wasShowing != isShowingNow)
  27376. {
  27377. wasShowing = isShowingNow;
  27378. if (isShowingNow)
  27379. openPluginWindow();
  27380. else
  27381. closePluginWindow();
  27382. }
  27383. componentMovedOrResized (true, true);
  27384. }
  27385. void componentPeerChanged()
  27386. {
  27387. closePluginWindow();
  27388. openPluginWindow();
  27389. }
  27390. #endif
  27391. bool keyStateChanged (bool)
  27392. {
  27393. return pluginWantsKeys;
  27394. }
  27395. bool keyPressed (const KeyPress&)
  27396. {
  27397. return pluginWantsKeys;
  27398. }
  27399. #if JUCE_MAC
  27400. void paint (Graphics& g)
  27401. {
  27402. g.fillAll (Colours::black);
  27403. }
  27404. #else
  27405. void paint (Graphics& g)
  27406. {
  27407. if (isOpen)
  27408. {
  27409. ComponentPeer* const peer = getPeer();
  27410. if (peer != 0)
  27411. {
  27412. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27413. peer->addMaskedRegion (pos.getX(), pos.getY(), getWidth(), getHeight());
  27414. #if JUCE_LINUX
  27415. if (pluginWindow != 0)
  27416. {
  27417. const Rectangle<int> clip (g.getClipBounds());
  27418. XEvent ev;
  27419. zerostruct (ev);
  27420. ev.xexpose.type = Expose;
  27421. ev.xexpose.display = display;
  27422. ev.xexpose.window = pluginWindow;
  27423. ev.xexpose.x = clip.getX();
  27424. ev.xexpose.y = clip.getY();
  27425. ev.xexpose.width = clip.getWidth();
  27426. ev.xexpose.height = clip.getHeight();
  27427. sendEventToChild (&ev);
  27428. }
  27429. #endif
  27430. }
  27431. }
  27432. else
  27433. {
  27434. g.fillAll (Colours::black);
  27435. }
  27436. }
  27437. #endif
  27438. void timerCallback()
  27439. {
  27440. #if JUCE_WINDOWS
  27441. if (--sizeCheckCount <= 0)
  27442. {
  27443. sizeCheckCount = 10;
  27444. checkPluginWindowSize();
  27445. }
  27446. #endif
  27447. try
  27448. {
  27449. static bool reentrant = false;
  27450. if (! reentrant)
  27451. {
  27452. reentrant = true;
  27453. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  27454. reentrant = false;
  27455. }
  27456. }
  27457. catch (...)
  27458. {}
  27459. }
  27460. void mouseDown (const MouseEvent& e)
  27461. {
  27462. #if JUCE_LINUX
  27463. if (pluginWindow == 0)
  27464. return;
  27465. toFront (true);
  27466. XEvent ev;
  27467. zerostruct (ev);
  27468. ev.xbutton.display = display;
  27469. ev.xbutton.type = ButtonPress;
  27470. ev.xbutton.window = pluginWindow;
  27471. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27472. ev.xbutton.time = CurrentTime;
  27473. ev.xbutton.x = e.x;
  27474. ev.xbutton.y = e.y;
  27475. ev.xbutton.x_root = e.getScreenX();
  27476. ev.xbutton.y_root = e.getScreenY();
  27477. translateJuceToXButtonModifiers (e, ev);
  27478. sendEventToChild (&ev);
  27479. #elif JUCE_WINDOWS
  27480. (void) e;
  27481. toFront (true);
  27482. #endif
  27483. }
  27484. void broughtToFront()
  27485. {
  27486. activeVSTWindows.removeValue (this);
  27487. activeVSTWindows.add (this);
  27488. #if JUCE_MAC
  27489. dispatch (effEditTop, 0, 0, 0, 0);
  27490. #endif
  27491. }
  27492. juce_UseDebuggingNewOperator
  27493. private:
  27494. VSTPluginInstance& plugin;
  27495. bool isOpen, wasShowing, recursiveResize;
  27496. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  27497. #if JUCE_WINDOWS
  27498. HWND pluginHWND;
  27499. void* originalWndProc;
  27500. int sizeCheckCount;
  27501. #elif JUCE_LINUX
  27502. Window pluginWindow;
  27503. EventProcPtr pluginProc;
  27504. #endif
  27505. #if JUCE_MAC
  27506. void openPluginWindow (WindowRef parentWindow)
  27507. {
  27508. if (isOpen || parentWindow == 0)
  27509. return;
  27510. isOpen = true;
  27511. ERect* rect = 0;
  27512. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27513. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  27514. // do this before and after like in the steinberg example
  27515. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27516. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27517. // Install keyboard hooks
  27518. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27519. // double-check it's not too tiny
  27520. int w = 250, h = 150;
  27521. if (rect != 0)
  27522. {
  27523. w = rect->right - rect->left;
  27524. h = rect->bottom - rect->top;
  27525. if (w == 0 || h == 0)
  27526. {
  27527. w = 250;
  27528. h = 150;
  27529. }
  27530. }
  27531. w = jmax (w, 32);
  27532. h = jmax (h, 32);
  27533. setSize (w, h);
  27534. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27535. repaint();
  27536. }
  27537. #else
  27538. void openPluginWindow()
  27539. {
  27540. if (isOpen || getWindowHandle() == 0)
  27541. return;
  27542. log ("Opening VST UI: " + plugin.name);
  27543. isOpen = true;
  27544. ERect* rect = 0;
  27545. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27546. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  27547. // do this before and after like in the steinberg example
  27548. dispatch (effEditGetRect, 0, 0, &rect, 0);
  27549. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  27550. // Install keyboard hooks
  27551. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  27552. #if JUCE_WINDOWS
  27553. originalWndProc = 0;
  27554. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  27555. if (pluginHWND == 0)
  27556. {
  27557. isOpen = false;
  27558. setSize (300, 150);
  27559. return;
  27560. }
  27561. #pragma warning (push)
  27562. #pragma warning (disable: 4244)
  27563. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
  27564. if (! pluginWantsKeys)
  27565. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
  27566. #pragma warning (pop)
  27567. int w, h;
  27568. RECT r;
  27569. GetWindowRect (pluginHWND, &r);
  27570. w = r.right - r.left;
  27571. h = r.bottom - r.top;
  27572. if (rect != 0)
  27573. {
  27574. const int rw = rect->right - rect->left;
  27575. const int rh = rect->bottom - rect->top;
  27576. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  27577. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  27578. {
  27579. // very dodgy logic to decide which size is right.
  27580. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  27581. {
  27582. SetWindowPos (pluginHWND, 0,
  27583. 0, 0, rw, rh,
  27584. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  27585. GetWindowRect (pluginHWND, &r);
  27586. w = r.right - r.left;
  27587. h = r.bottom - r.top;
  27588. pluginRefusesToResize = (w != rw) || (h != rh);
  27589. w = rw;
  27590. h = rh;
  27591. }
  27592. }
  27593. }
  27594. #elif JUCE_LINUX
  27595. pluginWindow = getChildWindow ((Window) getWindowHandle());
  27596. if (pluginWindow != 0)
  27597. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  27598. XInternAtom (display, "_XEventProc", False));
  27599. int w = 250, h = 150;
  27600. if (rect != 0)
  27601. {
  27602. w = rect->right - rect->left;
  27603. h = rect->bottom - rect->top;
  27604. if (w == 0 || h == 0)
  27605. {
  27606. w = 250;
  27607. h = 150;
  27608. }
  27609. }
  27610. if (pluginWindow != 0)
  27611. XMapRaised (display, pluginWindow);
  27612. #endif
  27613. // double-check it's not too tiny
  27614. w = jmax (w, 32);
  27615. h = jmax (h, 32);
  27616. setSize (w, h);
  27617. #if JUCE_WINDOWS
  27618. checkPluginWindowSize();
  27619. #endif
  27620. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  27621. repaint();
  27622. }
  27623. #endif
  27624. #if ! JUCE_MAC
  27625. void closePluginWindow()
  27626. {
  27627. if (isOpen)
  27628. {
  27629. log ("Closing VST UI: " + plugin.getName());
  27630. isOpen = false;
  27631. dispatch (effEditClose, 0, 0, 0, 0);
  27632. #if JUCE_WINDOWS
  27633. #pragma warning (push)
  27634. #pragma warning (disable: 4244)
  27635. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27636. SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
  27637. #pragma warning (pop)
  27638. stopTimer();
  27639. if (pluginHWND != 0 && IsWindow (pluginHWND))
  27640. DestroyWindow (pluginHWND);
  27641. pluginHWND = 0;
  27642. #elif JUCE_LINUX
  27643. stopTimer();
  27644. pluginWindow = 0;
  27645. pluginProc = 0;
  27646. #endif
  27647. }
  27648. }
  27649. #endif
  27650. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  27651. {
  27652. return plugin.dispatch (opcode, index, value, ptr, opt);
  27653. }
  27654. #if JUCE_WINDOWS
  27655. void checkPluginWindowSize()
  27656. {
  27657. RECT r;
  27658. GetWindowRect (pluginHWND, &r);
  27659. const int w = r.right - r.left;
  27660. const int h = r.bottom - r.top;
  27661. if (isShowing() && w > 0 && h > 0
  27662. && (w != getWidth() || h != getHeight())
  27663. && ! pluginRefusesToResize)
  27664. {
  27665. setSize (w, h);
  27666. sizeCheckCount = 0;
  27667. }
  27668. }
  27669. // hooks to get keyboard events from VST windows..
  27670. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  27671. {
  27672. for (int i = activeVSTWindows.size(); --i >= 0;)
  27673. {
  27674. const VSTPluginWindow* const w = activeVSTWindows.getUnchecked (i);
  27675. if (w->pluginHWND == hW)
  27676. {
  27677. if (message == WM_CHAR
  27678. || message == WM_KEYDOWN
  27679. || message == WM_SYSKEYDOWN
  27680. || message == WM_KEYUP
  27681. || message == WM_SYSKEYUP
  27682. || message == WM_APPCOMMAND)
  27683. {
  27684. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  27685. message, wParam, lParam);
  27686. }
  27687. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  27688. (HWND) w->pluginHWND,
  27689. message,
  27690. wParam,
  27691. lParam);
  27692. }
  27693. }
  27694. return DefWindowProc (hW, message, wParam, lParam);
  27695. }
  27696. #endif
  27697. #if JUCE_LINUX
  27698. // overload mouse/keyboard events to forward them to the plugin's inner window..
  27699. void sendEventToChild (XEvent* event)
  27700. {
  27701. if (pluginProc != 0)
  27702. {
  27703. // if the plugin publishes an event procedure, pass the event directly..
  27704. pluginProc (event);
  27705. }
  27706. else if (pluginWindow != 0)
  27707. {
  27708. // if the plugin has a window, then send the event to the window so that
  27709. // its message thread will pick it up..
  27710. XSendEvent (display, pluginWindow, False, 0L, event);
  27711. XFlush (display);
  27712. }
  27713. }
  27714. void mouseEnter (const MouseEvent& e)
  27715. {
  27716. if (pluginWindow != 0)
  27717. {
  27718. XEvent ev;
  27719. zerostruct (ev);
  27720. ev.xcrossing.display = display;
  27721. ev.xcrossing.type = EnterNotify;
  27722. ev.xcrossing.window = pluginWindow;
  27723. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27724. ev.xcrossing.time = CurrentTime;
  27725. ev.xcrossing.x = e.x;
  27726. ev.xcrossing.y = e.y;
  27727. ev.xcrossing.x_root = e.getScreenX();
  27728. ev.xcrossing.y_root = e.getScreenY();
  27729. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27730. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27731. translateJuceToXCrossingModifiers (e, ev);
  27732. sendEventToChild (&ev);
  27733. }
  27734. }
  27735. void mouseExit (const MouseEvent& e)
  27736. {
  27737. if (pluginWindow != 0)
  27738. {
  27739. XEvent ev;
  27740. zerostruct (ev);
  27741. ev.xcrossing.display = display;
  27742. ev.xcrossing.type = LeaveNotify;
  27743. ev.xcrossing.window = pluginWindow;
  27744. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  27745. ev.xcrossing.time = CurrentTime;
  27746. ev.xcrossing.x = e.x;
  27747. ev.xcrossing.y = e.y;
  27748. ev.xcrossing.x_root = e.getScreenX();
  27749. ev.xcrossing.y_root = e.getScreenY();
  27750. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  27751. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  27752. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  27753. translateJuceToXCrossingModifiers (e, ev);
  27754. sendEventToChild (&ev);
  27755. }
  27756. }
  27757. void mouseMove (const MouseEvent& e)
  27758. {
  27759. if (pluginWindow != 0)
  27760. {
  27761. XEvent ev;
  27762. zerostruct (ev);
  27763. ev.xmotion.display = display;
  27764. ev.xmotion.type = MotionNotify;
  27765. ev.xmotion.window = pluginWindow;
  27766. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27767. ev.xmotion.time = CurrentTime;
  27768. ev.xmotion.is_hint = NotifyNormal;
  27769. ev.xmotion.x = e.x;
  27770. ev.xmotion.y = e.y;
  27771. ev.xmotion.x_root = e.getScreenX();
  27772. ev.xmotion.y_root = e.getScreenY();
  27773. sendEventToChild (&ev);
  27774. }
  27775. }
  27776. void mouseDrag (const MouseEvent& e)
  27777. {
  27778. if (pluginWindow != 0)
  27779. {
  27780. XEvent ev;
  27781. zerostruct (ev);
  27782. ev.xmotion.display = display;
  27783. ev.xmotion.type = MotionNotify;
  27784. ev.xmotion.window = pluginWindow;
  27785. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  27786. ev.xmotion.time = CurrentTime;
  27787. ev.xmotion.x = e.x ;
  27788. ev.xmotion.y = e.y;
  27789. ev.xmotion.x_root = e.getScreenX();
  27790. ev.xmotion.y_root = e.getScreenY();
  27791. ev.xmotion.is_hint = NotifyNormal;
  27792. translateJuceToXMotionModifiers (e, ev);
  27793. sendEventToChild (&ev);
  27794. }
  27795. }
  27796. void mouseUp (const MouseEvent& e)
  27797. {
  27798. if (pluginWindow != 0)
  27799. {
  27800. XEvent ev;
  27801. zerostruct (ev);
  27802. ev.xbutton.display = display;
  27803. ev.xbutton.type = ButtonRelease;
  27804. ev.xbutton.window = pluginWindow;
  27805. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27806. ev.xbutton.time = CurrentTime;
  27807. ev.xbutton.x = e.x;
  27808. ev.xbutton.y = e.y;
  27809. ev.xbutton.x_root = e.getScreenX();
  27810. ev.xbutton.y_root = e.getScreenY();
  27811. translateJuceToXButtonModifiers (e, ev);
  27812. sendEventToChild (&ev);
  27813. }
  27814. }
  27815. void mouseWheelMove (const MouseEvent& e,
  27816. float incrementX,
  27817. float incrementY)
  27818. {
  27819. if (pluginWindow != 0)
  27820. {
  27821. XEvent ev;
  27822. zerostruct (ev);
  27823. ev.xbutton.display = display;
  27824. ev.xbutton.type = ButtonPress;
  27825. ev.xbutton.window = pluginWindow;
  27826. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  27827. ev.xbutton.time = CurrentTime;
  27828. ev.xbutton.x = e.x;
  27829. ev.xbutton.y = e.y;
  27830. ev.xbutton.x_root = e.getScreenX();
  27831. ev.xbutton.y_root = e.getScreenY();
  27832. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  27833. sendEventToChild (&ev);
  27834. // TODO - put a usleep here ?
  27835. ev.xbutton.type = ButtonRelease;
  27836. sendEventToChild (&ev);
  27837. }
  27838. }
  27839. #endif
  27840. #if JUCE_MAC
  27841. #if ! JUCE_SUPPORT_CARBON
  27842. #error "To build VSTs, you need to enable the JUCE_SUPPORT_CARBON flag in your config!"
  27843. #endif
  27844. class InnerWrapperComponent : public CarbonViewWrapperComponent
  27845. {
  27846. public:
  27847. InnerWrapperComponent (VSTPluginWindow* const owner_)
  27848. : owner (owner_),
  27849. alreadyInside (false)
  27850. {
  27851. }
  27852. ~InnerWrapperComponent()
  27853. {
  27854. deleteWindow();
  27855. }
  27856. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  27857. {
  27858. owner->openPluginWindow (windowRef);
  27859. return 0;
  27860. }
  27861. void removeView (HIViewRef)
  27862. {
  27863. owner->dispatch (effEditClose, 0, 0, 0, 0);
  27864. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  27865. }
  27866. bool getEmbeddedViewSize (int& w, int& h)
  27867. {
  27868. ERect* rect = 0;
  27869. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  27870. w = rect->right - rect->left;
  27871. h = rect->bottom - rect->top;
  27872. return true;
  27873. }
  27874. void mouseDown (int x, int y)
  27875. {
  27876. if (! alreadyInside)
  27877. {
  27878. alreadyInside = true;
  27879. getTopLevelComponent()->toFront (true);
  27880. owner->dispatch (effEditMouse, x, y, 0, 0);
  27881. alreadyInside = false;
  27882. }
  27883. else
  27884. {
  27885. PostEvent (::mouseDown, 0);
  27886. }
  27887. }
  27888. void paint()
  27889. {
  27890. ComponentPeer* const peer = getPeer();
  27891. if (peer != 0)
  27892. {
  27893. const Point<int> pos (getScreenPosition() - peer->getScreenPosition());
  27894. ERect r;
  27895. r.left = pos.getX();
  27896. r.right = r.left + getWidth();
  27897. r.top = pos.getY();
  27898. r.bottom = r.top + getHeight();
  27899. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  27900. }
  27901. }
  27902. private:
  27903. VSTPluginWindow* const owner;
  27904. bool alreadyInside;
  27905. };
  27906. friend class InnerWrapperComponent;
  27907. ScopedPointer <InnerWrapperComponent> innerWrapper;
  27908. void resized()
  27909. {
  27910. innerWrapper->setSize (getWidth(), getHeight());
  27911. }
  27912. #endif
  27913. };
  27914. AudioProcessorEditor* VSTPluginInstance::createEditor()
  27915. {
  27916. if (hasEditor())
  27917. return new VSTPluginWindow (*this);
  27918. return 0;
  27919. }
  27920. void VSTPluginInstance::handleAsyncUpdate()
  27921. {
  27922. // indicates that something about the plugin has changed..
  27923. updateHostDisplay();
  27924. }
  27925. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  27926. {
  27927. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  27928. {
  27929. changeProgramName (getCurrentProgram(), prog->prgName);
  27930. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27931. setParameter (i, vst_swapFloat (prog->params[i]));
  27932. return true;
  27933. }
  27934. return false;
  27935. }
  27936. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  27937. const int dataSize)
  27938. {
  27939. if (dataSize < 28)
  27940. return false;
  27941. const fxSet* const set = (const fxSet*) data;
  27942. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  27943. || vst_swap (set->version) > fxbVersionNum)
  27944. return false;
  27945. if (vst_swap (set->fxMagic) == 'FxBk')
  27946. {
  27947. // bank of programs
  27948. if (vst_swap (set->numPrograms) >= 0)
  27949. {
  27950. const int oldProg = getCurrentProgram();
  27951. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  27952. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  27953. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  27954. {
  27955. if (i != oldProg)
  27956. {
  27957. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  27958. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27959. return false;
  27960. if (vst_swap (set->numPrograms) > 0)
  27961. setCurrentProgram (i);
  27962. if (! restoreProgramSettings (prog))
  27963. return false;
  27964. }
  27965. }
  27966. if (vst_swap (set->numPrograms) > 0)
  27967. setCurrentProgram (oldProg);
  27968. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  27969. if (((const char*) prog) - ((const char*) set) >= dataSize)
  27970. return false;
  27971. if (! restoreProgramSettings (prog))
  27972. return false;
  27973. }
  27974. }
  27975. else if (vst_swap (set->fxMagic) == 'FxCk')
  27976. {
  27977. // single program
  27978. const fxProgram* const prog = (const fxProgram*) data;
  27979. if (vst_swap (prog->chunkMagic) != 'CcnK')
  27980. return false;
  27981. changeProgramName (getCurrentProgram(), prog->prgName);
  27982. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  27983. setParameter (i, vst_swapFloat (prog->params[i]));
  27984. }
  27985. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  27986. {
  27987. // non-preset chunk
  27988. const fxChunkSet* const cset = (const fxChunkSet*) data;
  27989. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  27990. return false;
  27991. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  27992. }
  27993. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  27994. {
  27995. // preset chunk
  27996. const fxProgramSet* const cset = (const fxProgramSet*) data;
  27997. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  27998. return false;
  27999. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  28000. changeProgramName (getCurrentProgram(), cset->name);
  28001. }
  28002. else
  28003. {
  28004. return false;
  28005. }
  28006. return true;
  28007. }
  28008. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog)
  28009. {
  28010. const int numParams = getNumParameters();
  28011. prog->chunkMagic = vst_swap ('CcnK');
  28012. prog->byteSize = 0;
  28013. prog->fxMagic = vst_swap ('FxCk');
  28014. prog->version = vst_swap (fxbVersionNum);
  28015. prog->fxID = vst_swap (getUID());
  28016. prog->fxVersion = vst_swap (getVersionNumber());
  28017. prog->numParams = vst_swap (numParams);
  28018. getCurrentProgramName().copyToCString (prog->prgName, sizeof (prog->prgName) - 1);
  28019. for (int i = 0; i < numParams; ++i)
  28020. prog->params[i] = vst_swapFloat (getParameter (i));
  28021. }
  28022. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  28023. {
  28024. const int numPrograms = getNumPrograms();
  28025. const int numParams = getNumParameters();
  28026. if (usesChunks())
  28027. {
  28028. if (isFXB)
  28029. {
  28030. MemoryBlock chunk;
  28031. getChunkData (chunk, false, maxSizeMB);
  28032. const size_t totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  28033. dest.setSize (totalLen, true);
  28034. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  28035. set->chunkMagic = vst_swap ('CcnK');
  28036. set->byteSize = 0;
  28037. set->fxMagic = vst_swap ('FBCh');
  28038. set->version = vst_swap (fxbVersionNum);
  28039. set->fxID = vst_swap (getUID());
  28040. set->fxVersion = vst_swap (getVersionNumber());
  28041. set->numPrograms = vst_swap (numPrograms);
  28042. set->chunkSize = vst_swap ((long) chunk.getSize());
  28043. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28044. }
  28045. else
  28046. {
  28047. MemoryBlock chunk;
  28048. getChunkData (chunk, true, maxSizeMB);
  28049. const size_t totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  28050. dest.setSize (totalLen, true);
  28051. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  28052. set->chunkMagic = vst_swap ('CcnK');
  28053. set->byteSize = 0;
  28054. set->fxMagic = vst_swap ('FPCh');
  28055. set->version = vst_swap (fxbVersionNum);
  28056. set->fxID = vst_swap (getUID());
  28057. set->fxVersion = vst_swap (getVersionNumber());
  28058. set->numPrograms = vst_swap (numPrograms);
  28059. set->chunkSize = vst_swap ((long) chunk.getSize());
  28060. getCurrentProgramName().copyToCString (set->name, sizeof (set->name) - 1);
  28061. chunk.copyTo (set->chunk, 0, chunk.getSize());
  28062. }
  28063. }
  28064. else
  28065. {
  28066. if (isFXB)
  28067. {
  28068. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28069. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  28070. dest.setSize (len, true);
  28071. fxSet* const set = (fxSet*) dest.getData();
  28072. set->chunkMagic = vst_swap ('CcnK');
  28073. set->byteSize = 0;
  28074. set->fxMagic = vst_swap ('FxBk');
  28075. set->version = vst_swap (fxbVersionNum);
  28076. set->fxID = vst_swap (getUID());
  28077. set->fxVersion = vst_swap (getVersionNumber());
  28078. set->numPrograms = vst_swap (numPrograms);
  28079. const int oldProgram = getCurrentProgram();
  28080. MemoryBlock oldSettings;
  28081. createTempParameterStore (oldSettings);
  28082. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  28083. for (int i = 0; i < numPrograms; ++i)
  28084. {
  28085. if (i != oldProgram)
  28086. {
  28087. setCurrentProgram (i);
  28088. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  28089. }
  28090. }
  28091. setCurrentProgram (oldProgram);
  28092. restoreFromTempParameterStore (oldSettings);
  28093. }
  28094. else
  28095. {
  28096. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  28097. dest.setSize (totalLen, true);
  28098. setParamsInProgramBlock ((fxProgram*) dest.getData());
  28099. }
  28100. }
  28101. return true;
  28102. }
  28103. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  28104. {
  28105. if (usesChunks())
  28106. {
  28107. void* data = 0;
  28108. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  28109. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  28110. {
  28111. mb.setSize (bytes);
  28112. mb.copyFrom (data, 0, bytes);
  28113. }
  28114. }
  28115. }
  28116. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  28117. {
  28118. if (size > 0 && usesChunks())
  28119. {
  28120. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  28121. if (! isPreset)
  28122. updateStoredProgramNames();
  28123. }
  28124. }
  28125. void VSTPluginInstance::timerCallback()
  28126. {
  28127. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  28128. stopTimer();
  28129. }
  28130. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  28131. {
  28132. const ScopedLock sl (lock);
  28133. ++insideVSTCallback;
  28134. int result = 0;
  28135. try
  28136. {
  28137. if (effect != 0)
  28138. {
  28139. #if JUCE_MAC
  28140. if (module->resFileId != 0)
  28141. UseResFile (module->resFileId);
  28142. #endif
  28143. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  28144. #if JUCE_MAC
  28145. module->resFileId = CurResFile();
  28146. #endif
  28147. --insideVSTCallback;
  28148. return result;
  28149. }
  28150. }
  28151. catch (...)
  28152. {
  28153. }
  28154. --insideVSTCallback;
  28155. return result;
  28156. }
  28157. namespace
  28158. {
  28159. static const int defaultVSTSampleRateValue = 16384;
  28160. static const int defaultVSTBlockSizeValue = 512;
  28161. // handles non plugin-specific callbacks..
  28162. VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28163. {
  28164. (void) index;
  28165. (void) value;
  28166. (void) opt;
  28167. switch (opcode)
  28168. {
  28169. case audioMasterCanDo:
  28170. {
  28171. static const char* canDos[] = { "supplyIdle",
  28172. "sendVstEvents",
  28173. "sendVstMidiEvent",
  28174. "sendVstTimeInfo",
  28175. "receiveVstEvents",
  28176. "receiveVstMidiEvent",
  28177. "supportShell",
  28178. "shellCategory" };
  28179. for (int i = 0; i < numElementsInArray (canDos); ++i)
  28180. if (strcmp (canDos[i], (const char*) ptr) == 0)
  28181. return 1;
  28182. return 0;
  28183. }
  28184. case audioMasterVersion: return 0x2400;
  28185. case audioMasterCurrentId: return shellUIDToCreate;
  28186. case audioMasterGetNumAutomatableParameters: return 0;
  28187. case audioMasterGetAutomationState: return 1;
  28188. case audioMasterGetVendorVersion: return 0x0101;
  28189. case audioMasterGetVendorString:
  28190. case audioMasterGetProductString:
  28191. {
  28192. String hostName ("Juce VST Host");
  28193. if (JUCEApplication::getInstance() != 0)
  28194. hostName = JUCEApplication::getInstance()->getApplicationName();
  28195. hostName.copyToCString ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  28196. break;
  28197. }
  28198. case audioMasterGetSampleRate: return (VstIntPtr) defaultVSTSampleRateValue;
  28199. case audioMasterGetBlockSize: return (VstIntPtr) defaultVSTBlockSizeValue;
  28200. case audioMasterSetOutputSampleRate: return 0;
  28201. default:
  28202. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  28203. break;
  28204. }
  28205. return 0;
  28206. }
  28207. }
  28208. // handles callbacks for a specific plugin
  28209. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  28210. {
  28211. switch (opcode)
  28212. {
  28213. case audioMasterAutomate:
  28214. sendParamChangeMessageToListeners (index, opt);
  28215. break;
  28216. case audioMasterProcessEvents:
  28217. handleMidiFromPlugin ((const VstEvents*) ptr);
  28218. break;
  28219. case audioMasterGetTime:
  28220. #if JUCE_MSVC
  28221. #pragma warning (push)
  28222. #pragma warning (disable: 4311)
  28223. #endif
  28224. return (VstIntPtr) &vstHostTime;
  28225. #if JUCE_MSVC
  28226. #pragma warning (pop)
  28227. #endif
  28228. break;
  28229. case audioMasterIdle:
  28230. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  28231. {
  28232. ++insideVSTCallback;
  28233. #if JUCE_MAC
  28234. if (getActiveEditor() != 0)
  28235. dispatch (effEditIdle, 0, 0, 0, 0);
  28236. #endif
  28237. juce_callAnyTimersSynchronously();
  28238. handleUpdateNowIfNeeded();
  28239. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  28240. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  28241. --insideVSTCallback;
  28242. }
  28243. break;
  28244. case audioMasterUpdateDisplay:
  28245. triggerAsyncUpdate();
  28246. break;
  28247. case audioMasterTempoAt:
  28248. // returns (10000 * bpm)
  28249. break;
  28250. case audioMasterNeedIdle:
  28251. startTimer (50);
  28252. break;
  28253. case audioMasterSizeWindow:
  28254. if (getActiveEditor() != 0)
  28255. getActiveEditor()->setSize (index, value);
  28256. return 1;
  28257. case audioMasterGetSampleRate:
  28258. return (VstIntPtr) (getSampleRate() > 0 ? getSampleRate() : defaultVSTSampleRateValue);
  28259. case audioMasterGetBlockSize:
  28260. return (VstIntPtr) (getBlockSize() > 0 ? getBlockSize() : defaultVSTBlockSizeValue);
  28261. case audioMasterWantMidi:
  28262. wantsMidiMessages = true;
  28263. break;
  28264. case audioMasterGetDirectory:
  28265. #if JUCE_MAC
  28266. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  28267. #else
  28268. return (VstIntPtr) (pointer_sized_uint) module->fullParentDirectoryPathName.toUTF8();
  28269. #endif
  28270. case audioMasterGetAutomationState:
  28271. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  28272. break;
  28273. // none of these are handled (yet)..
  28274. case audioMasterBeginEdit:
  28275. case audioMasterEndEdit:
  28276. case audioMasterSetTime:
  28277. case audioMasterPinConnected:
  28278. case audioMasterGetParameterQuantization:
  28279. case audioMasterIOChanged:
  28280. case audioMasterGetInputLatency:
  28281. case audioMasterGetOutputLatency:
  28282. case audioMasterGetPreviousPlug:
  28283. case audioMasterGetNextPlug:
  28284. case audioMasterWillReplaceOrAccumulate:
  28285. case audioMasterGetCurrentProcessLevel:
  28286. case audioMasterOfflineStart:
  28287. case audioMasterOfflineRead:
  28288. case audioMasterOfflineWrite:
  28289. case audioMasterOfflineGetCurrentPass:
  28290. case audioMasterOfflineGetCurrentMetaPass:
  28291. case audioMasterVendorSpecific:
  28292. case audioMasterSetIcon:
  28293. case audioMasterGetLanguage:
  28294. case audioMasterOpenWindow:
  28295. case audioMasterCloseWindow:
  28296. break;
  28297. default:
  28298. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28299. }
  28300. return 0;
  28301. }
  28302. // entry point for all callbacks from the plugin
  28303. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  28304. {
  28305. try
  28306. {
  28307. if (effect != 0 && effect->resvd2 != 0)
  28308. {
  28309. return ((VSTPluginInstance*)(effect->resvd2))
  28310. ->handleCallback (opcode, index, value, ptr, opt);
  28311. }
  28312. return handleGeneralCallback (opcode, index, value, ptr, opt);
  28313. }
  28314. catch (...)
  28315. {
  28316. return 0;
  28317. }
  28318. }
  28319. const String VSTPluginInstance::getVersion() const
  28320. {
  28321. unsigned int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  28322. String s;
  28323. if (v == 0 || v == -1)
  28324. v = getVersionNumber();
  28325. if (v != 0)
  28326. {
  28327. int versionBits[4];
  28328. int n = 0;
  28329. while (v != 0)
  28330. {
  28331. versionBits [n++] = (v & 0xff);
  28332. v >>= 8;
  28333. }
  28334. s << 'V';
  28335. while (n > 0)
  28336. {
  28337. s << versionBits [--n];
  28338. if (n > 0)
  28339. s << '.';
  28340. }
  28341. }
  28342. return s;
  28343. }
  28344. int VSTPluginInstance::getUID() const
  28345. {
  28346. int uid = effect != 0 ? effect->uniqueID : 0;
  28347. if (uid == 0)
  28348. uid = module->file.hashCode();
  28349. return uid;
  28350. }
  28351. const String VSTPluginInstance::getCategory() const
  28352. {
  28353. const char* result = 0;
  28354. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  28355. {
  28356. case kPlugCategEffect: result = "Effect"; break;
  28357. case kPlugCategSynth: result = "Synth"; break;
  28358. case kPlugCategAnalysis: result = "Anaylsis"; break;
  28359. case kPlugCategMastering: result = "Mastering"; break;
  28360. case kPlugCategSpacializer: result = "Spacial"; break;
  28361. case kPlugCategRoomFx: result = "Reverb"; break;
  28362. case kPlugSurroundFx: result = "Surround"; break;
  28363. case kPlugCategRestoration: result = "Restoration"; break;
  28364. case kPlugCategGenerator: result = "Tone generation"; break;
  28365. default: break;
  28366. }
  28367. return result;
  28368. }
  28369. float VSTPluginInstance::getParameter (int index)
  28370. {
  28371. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28372. {
  28373. try
  28374. {
  28375. const ScopedLock sl (lock);
  28376. return effect->getParameter (effect, index);
  28377. }
  28378. catch (...)
  28379. {
  28380. }
  28381. }
  28382. return 0.0f;
  28383. }
  28384. void VSTPluginInstance::setParameter (int index, float newValue)
  28385. {
  28386. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  28387. {
  28388. try
  28389. {
  28390. const ScopedLock sl (lock);
  28391. if (effect->getParameter (effect, index) != newValue)
  28392. effect->setParameter (effect, index, newValue);
  28393. }
  28394. catch (...)
  28395. {
  28396. }
  28397. }
  28398. }
  28399. const String VSTPluginInstance::getParameterName (int index)
  28400. {
  28401. if (effect != 0)
  28402. {
  28403. jassert (index >= 0 && index < effect->numParams);
  28404. char nm [256];
  28405. zerostruct (nm);
  28406. dispatch (effGetParamName, index, 0, nm, 0);
  28407. return String (nm).trim();
  28408. }
  28409. return String::empty;
  28410. }
  28411. const String VSTPluginInstance::getParameterLabel (int index) const
  28412. {
  28413. if (effect != 0)
  28414. {
  28415. jassert (index >= 0 && index < effect->numParams);
  28416. char nm [256];
  28417. zerostruct (nm);
  28418. dispatch (effGetParamLabel, index, 0, nm, 0);
  28419. return String (nm).trim();
  28420. }
  28421. return String::empty;
  28422. }
  28423. const String VSTPluginInstance::getParameterText (int index)
  28424. {
  28425. if (effect != 0)
  28426. {
  28427. jassert (index >= 0 && index < effect->numParams);
  28428. char nm [256];
  28429. zerostruct (nm);
  28430. dispatch (effGetParamDisplay, index, 0, nm, 0);
  28431. return String (nm).trim();
  28432. }
  28433. return String::empty;
  28434. }
  28435. bool VSTPluginInstance::isParameterAutomatable (int index) const
  28436. {
  28437. if (effect != 0)
  28438. {
  28439. jassert (index >= 0 && index < effect->numParams);
  28440. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  28441. }
  28442. return false;
  28443. }
  28444. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  28445. {
  28446. dest.setSize (64 + 4 * getNumParameters());
  28447. dest.fillWith (0);
  28448. getCurrentProgramName().copyToCString ((char*) dest.getData(), 63);
  28449. float* const p = (float*) (((char*) dest.getData()) + 64);
  28450. for (int i = 0; i < getNumParameters(); ++i)
  28451. p[i] = getParameter(i);
  28452. }
  28453. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  28454. {
  28455. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  28456. float* p = (float*) (((char*) m.getData()) + 64);
  28457. for (int i = 0; i < getNumParameters(); ++i)
  28458. setParameter (i, p[i]);
  28459. }
  28460. void VSTPluginInstance::setCurrentProgram (int newIndex)
  28461. {
  28462. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  28463. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  28464. }
  28465. const String VSTPluginInstance::getProgramName (int index)
  28466. {
  28467. if (index == getCurrentProgram())
  28468. {
  28469. return getCurrentProgramName();
  28470. }
  28471. else if (effect != 0)
  28472. {
  28473. char nm [256];
  28474. zerostruct (nm);
  28475. if (dispatch (effGetProgramNameIndexed,
  28476. jlimit (0, getNumPrograms(), index),
  28477. -1, nm, 0) != 0)
  28478. {
  28479. return String (nm).trim();
  28480. }
  28481. }
  28482. return programNames [index];
  28483. }
  28484. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  28485. {
  28486. if (index == getCurrentProgram())
  28487. {
  28488. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  28489. dispatch (effSetProgramName, 0, 0, (void*) newName.substring (0, 24).toCString(), 0.0f);
  28490. }
  28491. else
  28492. {
  28493. jassertfalse; // xxx not implemented!
  28494. }
  28495. }
  28496. void VSTPluginInstance::updateStoredProgramNames()
  28497. {
  28498. if (effect != 0 && getNumPrograms() > 0)
  28499. {
  28500. char nm [256];
  28501. zerostruct (nm);
  28502. // only do this if the plugin can't use indexed names..
  28503. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  28504. {
  28505. const int oldProgram = getCurrentProgram();
  28506. MemoryBlock oldSettings;
  28507. createTempParameterStore (oldSettings);
  28508. for (int i = 0; i < getNumPrograms(); ++i)
  28509. {
  28510. setCurrentProgram (i);
  28511. getCurrentProgramName(); // (this updates the list)
  28512. }
  28513. setCurrentProgram (oldProgram);
  28514. restoreFromTempParameterStore (oldSettings);
  28515. }
  28516. }
  28517. }
  28518. const String VSTPluginInstance::getCurrentProgramName()
  28519. {
  28520. if (effect != 0)
  28521. {
  28522. char nm [256];
  28523. zerostruct (nm);
  28524. dispatch (effGetProgramName, 0, 0, nm, 0);
  28525. const int index = getCurrentProgram();
  28526. if (programNames[index].isEmpty())
  28527. {
  28528. while (programNames.size() < index)
  28529. programNames.add (String::empty);
  28530. programNames.set (index, String (nm).trim());
  28531. }
  28532. return String (nm).trim();
  28533. }
  28534. return String::empty;
  28535. }
  28536. const String VSTPluginInstance::getInputChannelName (int index) const
  28537. {
  28538. if (index >= 0 && index < getNumInputChannels())
  28539. {
  28540. VstPinProperties pinProps;
  28541. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28542. return String (pinProps.label, sizeof (pinProps.label));
  28543. }
  28544. return String::empty;
  28545. }
  28546. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  28547. {
  28548. if (index < 0 || index >= getNumInputChannels())
  28549. return false;
  28550. VstPinProperties pinProps;
  28551. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  28552. return (pinProps.flags & kVstPinIsStereo) != 0;
  28553. return true;
  28554. }
  28555. const String VSTPluginInstance::getOutputChannelName (int index) const
  28556. {
  28557. if (index >= 0 && index < getNumOutputChannels())
  28558. {
  28559. VstPinProperties pinProps;
  28560. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28561. return String (pinProps.label, sizeof (pinProps.label));
  28562. }
  28563. return String::empty;
  28564. }
  28565. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  28566. {
  28567. if (index < 0 || index >= getNumOutputChannels())
  28568. return false;
  28569. VstPinProperties pinProps;
  28570. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  28571. return (pinProps.flags & kVstPinIsStereo) != 0;
  28572. return true;
  28573. }
  28574. void VSTPluginInstance::setPower (const bool on)
  28575. {
  28576. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  28577. isPowerOn = on;
  28578. }
  28579. const int defaultMaxSizeMB = 64;
  28580. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  28581. {
  28582. saveToFXBFile (destData, true, defaultMaxSizeMB);
  28583. }
  28584. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  28585. {
  28586. saveToFXBFile (destData, false, defaultMaxSizeMB);
  28587. }
  28588. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  28589. {
  28590. loadFromFXBFile (data, sizeInBytes);
  28591. }
  28592. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28593. {
  28594. loadFromFXBFile (data, sizeInBytes);
  28595. }
  28596. VSTPluginFormat::VSTPluginFormat()
  28597. {
  28598. }
  28599. VSTPluginFormat::~VSTPluginFormat()
  28600. {
  28601. }
  28602. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  28603. const String& fileOrIdentifier)
  28604. {
  28605. if (! fileMightContainThisPluginType (fileOrIdentifier))
  28606. return;
  28607. PluginDescription desc;
  28608. desc.fileOrIdentifier = fileOrIdentifier;
  28609. desc.uid = 0;
  28610. ScopedPointer <VSTPluginInstance> instance (dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc)));
  28611. if (instance == 0)
  28612. return;
  28613. try
  28614. {
  28615. #if JUCE_MAC
  28616. if (instance->module->resFileId != 0)
  28617. UseResFile (instance->module->resFileId);
  28618. #endif
  28619. instance->fillInPluginDescription (desc);
  28620. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  28621. if (category != kPlugCategShell)
  28622. {
  28623. // Normal plugin...
  28624. results.add (new PluginDescription (desc));
  28625. ++insideVSTCallback;
  28626. instance->dispatch (effOpen, 0, 0, 0, 0);
  28627. --insideVSTCallback;
  28628. }
  28629. else
  28630. {
  28631. // It's a shell plugin, so iterate all the subtypes...
  28632. char shellEffectName [64];
  28633. for (;;)
  28634. {
  28635. zerostruct (shellEffectName);
  28636. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  28637. if (uid == 0)
  28638. {
  28639. break;
  28640. }
  28641. else
  28642. {
  28643. desc.uid = uid;
  28644. desc.name = shellEffectName;
  28645. bool alreadyThere = false;
  28646. for (int i = results.size(); --i >= 0;)
  28647. {
  28648. PluginDescription* const d = results.getUnchecked(i);
  28649. if (d->isDuplicateOf (desc))
  28650. {
  28651. alreadyThere = true;
  28652. break;
  28653. }
  28654. }
  28655. if (! alreadyThere)
  28656. results.add (new PluginDescription (desc));
  28657. }
  28658. }
  28659. }
  28660. }
  28661. catch (...)
  28662. {
  28663. // crashed while loading...
  28664. }
  28665. }
  28666. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  28667. {
  28668. ScopedPointer <VSTPluginInstance> result;
  28669. if (fileMightContainThisPluginType (desc.fileOrIdentifier))
  28670. {
  28671. File file (desc.fileOrIdentifier);
  28672. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  28673. file.getParentDirectory().setAsCurrentWorkingDirectory();
  28674. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (file));
  28675. if (module != 0)
  28676. {
  28677. shellUIDToCreate = desc.uid;
  28678. result = new VSTPluginInstance (module);
  28679. if (result->effect != 0)
  28680. {
  28681. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) (VSTPluginInstance*) result;
  28682. result->initialise();
  28683. }
  28684. else
  28685. {
  28686. result = 0;
  28687. }
  28688. }
  28689. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  28690. }
  28691. return result.release();
  28692. }
  28693. bool VSTPluginFormat::fileMightContainThisPluginType (const String& fileOrIdentifier)
  28694. {
  28695. const File f (fileOrIdentifier);
  28696. #if JUCE_MAC
  28697. if (f.isDirectory() && f.hasFileExtension (".vst"))
  28698. return true;
  28699. #if JUCE_PPC
  28700. FSRef fileRef;
  28701. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  28702. {
  28703. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  28704. if (resFileId != -1)
  28705. {
  28706. const int numEffects = Count1Resources ('aEff');
  28707. CloseResFile (resFileId);
  28708. if (numEffects > 0)
  28709. return true;
  28710. }
  28711. }
  28712. #endif
  28713. return false;
  28714. #elif JUCE_WINDOWS
  28715. return f.existsAsFile() && f.hasFileExtension (".dll");
  28716. #elif JUCE_LINUX
  28717. return f.existsAsFile() && f.hasFileExtension (".so");
  28718. #endif
  28719. }
  28720. const String VSTPluginFormat::getNameOfPluginFromIdentifier (const String& fileOrIdentifier)
  28721. {
  28722. return fileOrIdentifier;
  28723. }
  28724. bool VSTPluginFormat::doesPluginStillExist (const PluginDescription& desc)
  28725. {
  28726. return File (desc.fileOrIdentifier).exists();
  28727. }
  28728. const StringArray VSTPluginFormat::searchPathsForPlugins (const FileSearchPath& directoriesToSearch, const bool recursive)
  28729. {
  28730. StringArray results;
  28731. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  28732. recursiveFileSearch (results, directoriesToSearch [j], recursive);
  28733. return results;
  28734. }
  28735. void VSTPluginFormat::recursiveFileSearch (StringArray& results, const File& dir, const bool recursive)
  28736. {
  28737. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  28738. // .component or .vst directories.
  28739. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  28740. while (iter.next())
  28741. {
  28742. const File f (iter.getFile());
  28743. bool isPlugin = false;
  28744. if (fileMightContainThisPluginType (f.getFullPathName()))
  28745. {
  28746. isPlugin = true;
  28747. results.add (f.getFullPathName());
  28748. }
  28749. if (recursive && (! isPlugin) && f.isDirectory())
  28750. recursiveFileSearch (results, f, true);
  28751. }
  28752. }
  28753. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  28754. {
  28755. #if JUCE_MAC
  28756. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  28757. #elif JUCE_WINDOWS
  28758. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  28759. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  28760. #elif JUCE_LINUX
  28761. return FileSearchPath ("/usr/lib/vst");
  28762. #endif
  28763. }
  28764. END_JUCE_NAMESPACE
  28765. #endif
  28766. #undef log
  28767. #endif
  28768. /*** End of inlined file: juce_VSTPluginFormat.cpp ***/
  28769. /*** End of inlined file: juce_VSTPluginFormat.mm ***/
  28770. /*** Start of inlined file: juce_AudioProcessor.cpp ***/
  28771. BEGIN_JUCE_NAMESPACE
  28772. AudioProcessor::AudioProcessor()
  28773. : playHead (0),
  28774. activeEditor (0),
  28775. sampleRate (0),
  28776. blockSize (0),
  28777. numInputChannels (0),
  28778. numOutputChannels (0),
  28779. latencySamples (0),
  28780. suspended (false),
  28781. nonRealtime (false)
  28782. {
  28783. }
  28784. AudioProcessor::~AudioProcessor()
  28785. {
  28786. // ooh, nasty - the editor should have been deleted before the filter
  28787. // that it refers to is deleted..
  28788. jassert (activeEditor == 0);
  28789. #if JUCE_DEBUG
  28790. // This will fail if you've called beginParameterChangeGesture() for one
  28791. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  28792. jassert (changingParams.countNumberOfSetBits() == 0);
  28793. #endif
  28794. }
  28795. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  28796. {
  28797. playHead = newPlayHead;
  28798. }
  28799. void AudioProcessor::addListener (AudioProcessorListener* const newListener)
  28800. {
  28801. const ScopedLock sl (listenerLock);
  28802. listeners.addIfNotAlreadyThere (newListener);
  28803. }
  28804. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove)
  28805. {
  28806. const ScopedLock sl (listenerLock);
  28807. listeners.removeValue (listenerToRemove);
  28808. }
  28809. void AudioProcessor::setPlayConfigDetails (const int numIns,
  28810. const int numOuts,
  28811. const double sampleRate_,
  28812. const int blockSize_) throw()
  28813. {
  28814. numInputChannels = numIns;
  28815. numOutputChannels = numOuts;
  28816. sampleRate = sampleRate_;
  28817. blockSize = blockSize_;
  28818. }
  28819. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  28820. {
  28821. nonRealtime = nonRealtime_;
  28822. }
  28823. void AudioProcessor::setLatencySamples (const int newLatency)
  28824. {
  28825. if (latencySamples != newLatency)
  28826. {
  28827. latencySamples = newLatency;
  28828. updateHostDisplay();
  28829. }
  28830. }
  28831. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  28832. const float newValue)
  28833. {
  28834. setParameter (parameterIndex, newValue);
  28835. sendParamChangeMessageToListeners (parameterIndex, newValue);
  28836. }
  28837. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  28838. {
  28839. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28840. for (int i = listeners.size(); --i >= 0;)
  28841. {
  28842. AudioProcessorListener* l;
  28843. {
  28844. const ScopedLock sl (listenerLock);
  28845. l = listeners [i];
  28846. }
  28847. if (l != 0)
  28848. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  28849. }
  28850. }
  28851. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  28852. {
  28853. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28854. #if JUCE_DEBUG
  28855. // This means you've called beginParameterChangeGesture twice in succession without a matching
  28856. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  28857. jassert (! changingParams [parameterIndex]);
  28858. changingParams.setBit (parameterIndex);
  28859. #endif
  28860. for (int i = listeners.size(); --i >= 0;)
  28861. {
  28862. AudioProcessorListener* l;
  28863. {
  28864. const ScopedLock sl (listenerLock);
  28865. l = listeners [i];
  28866. }
  28867. if (l != 0)
  28868. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  28869. }
  28870. }
  28871. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  28872. {
  28873. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  28874. #if JUCE_DEBUG
  28875. // This means you've called endParameterChangeGesture without having previously called
  28876. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  28877. // calls matched correctly.
  28878. jassert (changingParams [parameterIndex]);
  28879. changingParams.clearBit (parameterIndex);
  28880. #endif
  28881. for (int i = listeners.size(); --i >= 0;)
  28882. {
  28883. AudioProcessorListener* l;
  28884. {
  28885. const ScopedLock sl (listenerLock);
  28886. l = listeners [i];
  28887. }
  28888. if (l != 0)
  28889. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  28890. }
  28891. }
  28892. void AudioProcessor::updateHostDisplay()
  28893. {
  28894. for (int i = listeners.size(); --i >= 0;)
  28895. {
  28896. AudioProcessorListener* l;
  28897. {
  28898. const ScopedLock sl (listenerLock);
  28899. l = listeners [i];
  28900. }
  28901. if (l != 0)
  28902. l->audioProcessorChanged (this);
  28903. }
  28904. }
  28905. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  28906. {
  28907. return true;
  28908. }
  28909. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  28910. {
  28911. return false;
  28912. }
  28913. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  28914. {
  28915. const ScopedLock sl (callbackLock);
  28916. suspended = shouldBeSuspended;
  28917. }
  28918. void AudioProcessor::reset()
  28919. {
  28920. }
  28921. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  28922. {
  28923. const ScopedLock sl (callbackLock);
  28924. jassert (activeEditor == editor);
  28925. if (activeEditor == editor)
  28926. activeEditor = 0;
  28927. }
  28928. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  28929. {
  28930. if (activeEditor != 0)
  28931. return activeEditor;
  28932. AudioProcessorEditor* const ed = createEditor();
  28933. // You must make your hasEditor() method return a consistent result!
  28934. jassert (hasEditor() == (ed != 0));
  28935. if (ed != 0)
  28936. {
  28937. // you must give your editor comp a size before returning it..
  28938. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  28939. const ScopedLock sl (callbackLock);
  28940. activeEditor = ed;
  28941. }
  28942. return ed;
  28943. }
  28944. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  28945. {
  28946. getStateInformation (destData);
  28947. }
  28948. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  28949. {
  28950. setStateInformation (data, sizeInBytes);
  28951. }
  28952. // magic number to identify memory blocks that we've stored as XML
  28953. const uint32 magicXmlNumber = 0x21324356;
  28954. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  28955. JUCE_NAMESPACE::MemoryBlock& destData)
  28956. {
  28957. const String xmlString (xml.createDocument (String::empty, true, false));
  28958. const int stringLength = xmlString.getNumBytesAsUTF8();
  28959. destData.setSize (stringLength + 10);
  28960. char* const d = static_cast<char*> (destData.getData());
  28961. *(uint32*) d = ByteOrder::swapIfBigEndian ((const uint32) magicXmlNumber);
  28962. *(uint32*) (d + 4) = ByteOrder::swapIfBigEndian ((const uint32) stringLength);
  28963. xmlString.copyToUTF8 (d + 8, stringLength + 1);
  28964. }
  28965. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  28966. const int sizeInBytes)
  28967. {
  28968. if (sizeInBytes > 8
  28969. && ByteOrder::littleEndianInt (data) == magicXmlNumber)
  28970. {
  28971. const int stringLength = (int) ByteOrder::littleEndianInt (addBytesToPointer (data, 4));
  28972. if (stringLength > 0)
  28973. {
  28974. XmlDocument doc (String::fromUTF8 (static_cast<const char*> (data) + 8,
  28975. jmin ((sizeInBytes - 8), stringLength)));
  28976. return doc.getDocumentElement();
  28977. }
  28978. }
  28979. return 0;
  28980. }
  28981. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int) {}
  28982. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int) {}
  28983. bool AudioPlayHead::CurrentPositionInfo::operator== (const CurrentPositionInfo& other) const throw()
  28984. {
  28985. return timeInSeconds == other.timeInSeconds
  28986. && ppqPosition == other.ppqPosition
  28987. && editOriginTime == other.editOriginTime
  28988. && ppqPositionOfLastBarStart == other.ppqPositionOfLastBarStart
  28989. && frameRate == other.frameRate
  28990. && isPlaying == other.isPlaying
  28991. && isRecording == other.isRecording
  28992. && bpm == other.bpm
  28993. && timeSigNumerator == other.timeSigNumerator
  28994. && timeSigDenominator == other.timeSigDenominator;
  28995. }
  28996. bool AudioPlayHead::CurrentPositionInfo::operator!= (const CurrentPositionInfo& other) const throw()
  28997. {
  28998. return ! operator== (other);
  28999. }
  29000. void AudioPlayHead::CurrentPositionInfo::resetToDefault()
  29001. {
  29002. zerostruct (*this);
  29003. timeSigNumerator = 4;
  29004. timeSigDenominator = 4;
  29005. bpm = 120;
  29006. }
  29007. END_JUCE_NAMESPACE
  29008. /*** End of inlined file: juce_AudioProcessor.cpp ***/
  29009. /*** Start of inlined file: juce_AudioProcessorEditor.cpp ***/
  29010. BEGIN_JUCE_NAMESPACE
  29011. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  29012. : owner (owner_)
  29013. {
  29014. // the filter must be valid..
  29015. jassert (owner != 0);
  29016. }
  29017. AudioProcessorEditor::~AudioProcessorEditor()
  29018. {
  29019. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  29020. // filter for some reason..
  29021. jassert (owner->getActiveEditor() != this);
  29022. }
  29023. END_JUCE_NAMESPACE
  29024. /*** End of inlined file: juce_AudioProcessorEditor.cpp ***/
  29025. /*** Start of inlined file: juce_AudioProcessorGraph.cpp ***/
  29026. BEGIN_JUCE_NAMESPACE
  29027. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  29028. AudioProcessorGraph::Node::Node (const uint32 id_, AudioProcessor* const processor_)
  29029. : id (id_),
  29030. processor (processor_),
  29031. isPrepared (false)
  29032. {
  29033. jassert (processor_ != 0);
  29034. }
  29035. AudioProcessorGraph::Node::~Node()
  29036. {
  29037. }
  29038. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  29039. AudioProcessorGraph* const graph)
  29040. {
  29041. if (! isPrepared)
  29042. {
  29043. isPrepared = true;
  29044. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29045. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (processor));
  29046. if (ioProc != 0)
  29047. ioProc->setParentGraph (graph);
  29048. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  29049. processor->getNumOutputChannels(),
  29050. sampleRate, blockSize);
  29051. processor->prepareToPlay (sampleRate, blockSize);
  29052. }
  29053. }
  29054. void AudioProcessorGraph::Node::unprepare()
  29055. {
  29056. if (isPrepared)
  29057. {
  29058. isPrepared = false;
  29059. processor->releaseResources();
  29060. }
  29061. }
  29062. AudioProcessorGraph::AudioProcessorGraph()
  29063. : lastNodeId (0),
  29064. renderingBuffers (1, 1),
  29065. currentAudioOutputBuffer (1, 1)
  29066. {
  29067. }
  29068. AudioProcessorGraph::~AudioProcessorGraph()
  29069. {
  29070. clearRenderingSequence();
  29071. clear();
  29072. }
  29073. const String AudioProcessorGraph::getName() const
  29074. {
  29075. return "Audio Graph";
  29076. }
  29077. void AudioProcessorGraph::clear()
  29078. {
  29079. nodes.clear();
  29080. connections.clear();
  29081. triggerAsyncUpdate();
  29082. }
  29083. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const
  29084. {
  29085. for (int i = nodes.size(); --i >= 0;)
  29086. if (nodes.getUnchecked(i)->id == nodeId)
  29087. return nodes.getUnchecked(i);
  29088. return 0;
  29089. }
  29090. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  29091. uint32 nodeId)
  29092. {
  29093. if (newProcessor == 0)
  29094. {
  29095. jassertfalse;
  29096. return 0;
  29097. }
  29098. if (nodeId == 0)
  29099. {
  29100. nodeId = ++lastNodeId;
  29101. }
  29102. else
  29103. {
  29104. // you can't add a node with an id that already exists in the graph..
  29105. jassert (getNodeForId (nodeId) == 0);
  29106. removeNode (nodeId);
  29107. }
  29108. lastNodeId = nodeId;
  29109. Node* const n = new Node (nodeId, newProcessor);
  29110. nodes.add (n);
  29111. triggerAsyncUpdate();
  29112. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29113. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (n->processor));
  29114. if (ioProc != 0)
  29115. ioProc->setParentGraph (this);
  29116. return n;
  29117. }
  29118. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  29119. {
  29120. disconnectNode (nodeId);
  29121. for (int i = nodes.size(); --i >= 0;)
  29122. {
  29123. if (nodes.getUnchecked(i)->id == nodeId)
  29124. {
  29125. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  29126. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (static_cast<AudioProcessor*> (nodes.getUnchecked(i)->processor));
  29127. if (ioProc != 0)
  29128. ioProc->setParentGraph (0);
  29129. nodes.remove (i);
  29130. triggerAsyncUpdate();
  29131. return true;
  29132. }
  29133. }
  29134. return false;
  29135. }
  29136. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  29137. const int sourceChannelIndex,
  29138. const uint32 destNodeId,
  29139. const int destChannelIndex) const
  29140. {
  29141. for (int i = connections.size(); --i >= 0;)
  29142. {
  29143. const Connection* const c = connections.getUnchecked(i);
  29144. if (c->sourceNodeId == sourceNodeId
  29145. && c->destNodeId == destNodeId
  29146. && c->sourceChannelIndex == sourceChannelIndex
  29147. && c->destChannelIndex == destChannelIndex)
  29148. {
  29149. return c;
  29150. }
  29151. }
  29152. return 0;
  29153. }
  29154. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  29155. const uint32 possibleDestNodeId) const
  29156. {
  29157. for (int i = connections.size(); --i >= 0;)
  29158. {
  29159. const Connection* const c = connections.getUnchecked(i);
  29160. if (c->sourceNodeId == possibleSourceNodeId
  29161. && c->destNodeId == possibleDestNodeId)
  29162. {
  29163. return true;
  29164. }
  29165. }
  29166. return false;
  29167. }
  29168. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  29169. const int sourceChannelIndex,
  29170. const uint32 destNodeId,
  29171. const int destChannelIndex) const
  29172. {
  29173. if (sourceChannelIndex < 0
  29174. || destChannelIndex < 0
  29175. || sourceNodeId == destNodeId
  29176. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  29177. return false;
  29178. const Node* const source = getNodeForId (sourceNodeId);
  29179. if (source == 0
  29180. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  29181. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  29182. return false;
  29183. const Node* const dest = getNodeForId (destNodeId);
  29184. if (dest == 0
  29185. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  29186. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  29187. return false;
  29188. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  29189. destNodeId, destChannelIndex) == 0;
  29190. }
  29191. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  29192. const int sourceChannelIndex,
  29193. const uint32 destNodeId,
  29194. const int destChannelIndex)
  29195. {
  29196. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  29197. return false;
  29198. Connection* const c = new Connection();
  29199. c->sourceNodeId = sourceNodeId;
  29200. c->sourceChannelIndex = sourceChannelIndex;
  29201. c->destNodeId = destNodeId;
  29202. c->destChannelIndex = destChannelIndex;
  29203. connections.add (c);
  29204. triggerAsyncUpdate();
  29205. return true;
  29206. }
  29207. void AudioProcessorGraph::removeConnection (const int index)
  29208. {
  29209. connections.remove (index);
  29210. triggerAsyncUpdate();
  29211. }
  29212. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  29213. const uint32 destNodeId, const int destChannelIndex)
  29214. {
  29215. bool doneAnything = false;
  29216. for (int i = connections.size(); --i >= 0;)
  29217. {
  29218. const Connection* const c = connections.getUnchecked(i);
  29219. if (c->sourceNodeId == sourceNodeId
  29220. && c->destNodeId == destNodeId
  29221. && c->sourceChannelIndex == sourceChannelIndex
  29222. && c->destChannelIndex == destChannelIndex)
  29223. {
  29224. removeConnection (i);
  29225. doneAnything = true;
  29226. triggerAsyncUpdate();
  29227. }
  29228. }
  29229. return doneAnything;
  29230. }
  29231. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  29232. {
  29233. bool doneAnything = false;
  29234. for (int i = connections.size(); --i >= 0;)
  29235. {
  29236. const Connection* const c = connections.getUnchecked(i);
  29237. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  29238. {
  29239. removeConnection (i);
  29240. doneAnything = true;
  29241. triggerAsyncUpdate();
  29242. }
  29243. }
  29244. return doneAnything;
  29245. }
  29246. bool AudioProcessorGraph::removeIllegalConnections()
  29247. {
  29248. bool doneAnything = false;
  29249. for (int i = connections.size(); --i >= 0;)
  29250. {
  29251. const Connection* const c = connections.getUnchecked(i);
  29252. const Node* const source = getNodeForId (c->sourceNodeId);
  29253. const Node* const dest = getNodeForId (c->destNodeId);
  29254. if (source == 0 || dest == 0
  29255. || (c->sourceChannelIndex != midiChannelIndex
  29256. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  29257. || (c->sourceChannelIndex == midiChannelIndex
  29258. && ! source->processor->producesMidi())
  29259. || (c->destChannelIndex != midiChannelIndex
  29260. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  29261. || (c->destChannelIndex == midiChannelIndex
  29262. && ! dest->processor->acceptsMidi()))
  29263. {
  29264. removeConnection (i);
  29265. doneAnything = true;
  29266. triggerAsyncUpdate();
  29267. }
  29268. }
  29269. return doneAnything;
  29270. }
  29271. namespace GraphRenderingOps
  29272. {
  29273. class AudioGraphRenderingOp
  29274. {
  29275. public:
  29276. AudioGraphRenderingOp() {}
  29277. virtual ~AudioGraphRenderingOp() {}
  29278. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  29279. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  29280. const int numSamples) = 0;
  29281. juce_UseDebuggingNewOperator
  29282. };
  29283. class ClearChannelOp : public AudioGraphRenderingOp
  29284. {
  29285. public:
  29286. ClearChannelOp (const int channelNum_)
  29287. : channelNum (channelNum_)
  29288. {}
  29289. ~ClearChannelOp() {}
  29290. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29291. {
  29292. sharedBufferChans.clear (channelNum, 0, numSamples);
  29293. }
  29294. private:
  29295. const int channelNum;
  29296. ClearChannelOp (const ClearChannelOp&);
  29297. ClearChannelOp& operator= (const ClearChannelOp&);
  29298. };
  29299. class CopyChannelOp : public AudioGraphRenderingOp
  29300. {
  29301. public:
  29302. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29303. : srcChannelNum (srcChannelNum_),
  29304. dstChannelNum (dstChannelNum_)
  29305. {}
  29306. ~CopyChannelOp() {}
  29307. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29308. {
  29309. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29310. }
  29311. private:
  29312. const int srcChannelNum, dstChannelNum;
  29313. CopyChannelOp (const CopyChannelOp&);
  29314. CopyChannelOp& operator= (const CopyChannelOp&);
  29315. };
  29316. class AddChannelOp : public AudioGraphRenderingOp
  29317. {
  29318. public:
  29319. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_)
  29320. : srcChannelNum (srcChannelNum_),
  29321. dstChannelNum (dstChannelNum_)
  29322. {}
  29323. ~AddChannelOp() {}
  29324. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples)
  29325. {
  29326. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  29327. }
  29328. private:
  29329. const int srcChannelNum, dstChannelNum;
  29330. AddChannelOp (const AddChannelOp&);
  29331. AddChannelOp& operator= (const AddChannelOp&);
  29332. };
  29333. class ClearMidiBufferOp : public AudioGraphRenderingOp
  29334. {
  29335. public:
  29336. ClearMidiBufferOp (const int bufferNum_)
  29337. : bufferNum (bufferNum_)
  29338. {}
  29339. ~ClearMidiBufferOp() {}
  29340. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29341. {
  29342. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  29343. }
  29344. private:
  29345. const int bufferNum;
  29346. ClearMidiBufferOp (const ClearMidiBufferOp&);
  29347. ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  29348. };
  29349. class CopyMidiBufferOp : public AudioGraphRenderingOp
  29350. {
  29351. public:
  29352. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29353. : srcBufferNum (srcBufferNum_),
  29354. dstBufferNum (dstBufferNum_)
  29355. {}
  29356. ~CopyMidiBufferOp() {}
  29357. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int)
  29358. {
  29359. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  29360. }
  29361. private:
  29362. const int srcBufferNum, dstBufferNum;
  29363. CopyMidiBufferOp (const CopyMidiBufferOp&);
  29364. CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  29365. };
  29366. class AddMidiBufferOp : public AudioGraphRenderingOp
  29367. {
  29368. public:
  29369. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_)
  29370. : srcBufferNum (srcBufferNum_),
  29371. dstBufferNum (dstBufferNum_)
  29372. {}
  29373. ~AddMidiBufferOp() {}
  29374. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29375. {
  29376. sharedMidiBuffers.getUnchecked (dstBufferNum)
  29377. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  29378. }
  29379. private:
  29380. const int srcBufferNum, dstBufferNum;
  29381. AddMidiBufferOp (const AddMidiBufferOp&);
  29382. AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  29383. };
  29384. class ProcessBufferOp : public AudioGraphRenderingOp
  29385. {
  29386. public:
  29387. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  29388. const Array <int>& audioChannelsToUse_,
  29389. const int totalChans_,
  29390. const int midiBufferToUse_)
  29391. : node (node_),
  29392. processor (node_->getProcessor()),
  29393. audioChannelsToUse (audioChannelsToUse_),
  29394. totalChans (jmax (1, totalChans_)),
  29395. midiBufferToUse (midiBufferToUse_)
  29396. {
  29397. channels.calloc (totalChans);
  29398. while (audioChannelsToUse.size() < totalChans)
  29399. audioChannelsToUse.add (0);
  29400. }
  29401. ~ProcessBufferOp()
  29402. {
  29403. }
  29404. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples)
  29405. {
  29406. for (int i = totalChans; --i >= 0;)
  29407. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  29408. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  29409. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  29410. }
  29411. const AudioProcessorGraph::Node::Ptr node;
  29412. AudioProcessor* const processor;
  29413. private:
  29414. Array <int> audioChannelsToUse;
  29415. HeapBlock <float*> channels;
  29416. int totalChans;
  29417. int midiBufferToUse;
  29418. ProcessBufferOp (const ProcessBufferOp&);
  29419. ProcessBufferOp& operator= (const ProcessBufferOp&);
  29420. };
  29421. /** Used to calculate the correct sequence of rendering ops needed, based on
  29422. the best re-use of shared buffers at each stage.
  29423. */
  29424. class RenderingOpSequenceCalculator
  29425. {
  29426. public:
  29427. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  29428. const Array<void*>& orderedNodes_,
  29429. Array<void*>& renderingOps)
  29430. : graph (graph_),
  29431. orderedNodes (orderedNodes_)
  29432. {
  29433. nodeIds.add (-2); // first buffer is read-only zeros
  29434. channels.add (0);
  29435. midiNodeIds.add (-2);
  29436. for (int i = 0; i < orderedNodes.size(); ++i)
  29437. {
  29438. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  29439. renderingOps, i);
  29440. markAnyUnusedBuffersAsFree (i);
  29441. }
  29442. }
  29443. int getNumBuffersNeeded() const { return nodeIds.size(); }
  29444. int getNumMidiBuffersNeeded() const { return midiNodeIds.size(); }
  29445. juce_UseDebuggingNewOperator
  29446. private:
  29447. AudioProcessorGraph& graph;
  29448. const Array<void*>& orderedNodes;
  29449. Array <int> nodeIds, channels, midiNodeIds;
  29450. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  29451. Array<void*>& renderingOps,
  29452. const int ourRenderingIndex)
  29453. {
  29454. const int numIns = node->getProcessor()->getNumInputChannels();
  29455. const int numOuts = node->getProcessor()->getNumOutputChannels();
  29456. const int totalChans = jmax (numIns, numOuts);
  29457. Array <int> audioChannelsToUse;
  29458. int midiBufferToUse = -1;
  29459. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  29460. {
  29461. // get a list of all the inputs to this node
  29462. Array <int> sourceNodes, sourceOutputChans;
  29463. for (int i = graph.getNumConnections(); --i >= 0;)
  29464. {
  29465. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29466. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  29467. {
  29468. sourceNodes.add (c->sourceNodeId);
  29469. sourceOutputChans.add (c->sourceChannelIndex);
  29470. }
  29471. }
  29472. int bufIndex = -1;
  29473. if (sourceNodes.size() == 0)
  29474. {
  29475. // unconnected input channel
  29476. if (inputChan >= numOuts)
  29477. {
  29478. bufIndex = getReadOnlyEmptyBuffer();
  29479. jassert (bufIndex >= 0);
  29480. }
  29481. else
  29482. {
  29483. bufIndex = getFreeBuffer (false);
  29484. renderingOps.add (new ClearChannelOp (bufIndex));
  29485. }
  29486. }
  29487. else if (sourceNodes.size() == 1)
  29488. {
  29489. // channel with a straightforward single input..
  29490. const int srcNode = sourceNodes.getUnchecked(0);
  29491. const int srcChan = sourceOutputChans.getUnchecked(0);
  29492. bufIndex = getBufferContaining (srcNode, srcChan);
  29493. if (bufIndex < 0)
  29494. {
  29495. // if not found, this is probably a feedback loop
  29496. bufIndex = getReadOnlyEmptyBuffer();
  29497. jassert (bufIndex >= 0);
  29498. }
  29499. if (inputChan < numOuts
  29500. && isBufferNeededLater (ourRenderingIndex,
  29501. inputChan,
  29502. srcNode, srcChan))
  29503. {
  29504. // can't mess up this channel because it's needed later by another node, so we
  29505. // need to use a copy of it..
  29506. const int newFreeBuffer = getFreeBuffer (false);
  29507. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  29508. bufIndex = newFreeBuffer;
  29509. }
  29510. }
  29511. else
  29512. {
  29513. // channel with a mix of several inputs..
  29514. // try to find a re-usable channel from our inputs..
  29515. int reusableInputIndex = -1;
  29516. for (int i = 0; i < sourceNodes.size(); ++i)
  29517. {
  29518. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  29519. sourceOutputChans.getUnchecked(i));
  29520. if (sourceBufIndex >= 0
  29521. && ! isBufferNeededLater (ourRenderingIndex,
  29522. inputChan,
  29523. sourceNodes.getUnchecked(i),
  29524. sourceOutputChans.getUnchecked(i)))
  29525. {
  29526. // we've found one of our input chans that can be re-used..
  29527. reusableInputIndex = i;
  29528. bufIndex = sourceBufIndex;
  29529. break;
  29530. }
  29531. }
  29532. if (reusableInputIndex < 0)
  29533. {
  29534. // can't re-use any of our input chans, so get a new one and copy everything into it..
  29535. bufIndex = getFreeBuffer (false);
  29536. jassert (bufIndex != 0);
  29537. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  29538. sourceOutputChans.getUnchecked (0));
  29539. if (srcIndex < 0)
  29540. {
  29541. // if not found, this is probably a feedback loop
  29542. renderingOps.add (new ClearChannelOp (bufIndex));
  29543. }
  29544. else
  29545. {
  29546. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  29547. }
  29548. reusableInputIndex = 0;
  29549. }
  29550. for (int j = 0; j < sourceNodes.size(); ++j)
  29551. {
  29552. if (j != reusableInputIndex)
  29553. {
  29554. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  29555. sourceOutputChans.getUnchecked(j));
  29556. if (srcIndex >= 0)
  29557. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  29558. }
  29559. }
  29560. }
  29561. jassert (bufIndex >= 0);
  29562. audioChannelsToUse.add (bufIndex);
  29563. if (inputChan < numOuts)
  29564. markBufferAsContaining (bufIndex, node->id, inputChan);
  29565. }
  29566. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  29567. {
  29568. const int bufIndex = getFreeBuffer (false);
  29569. jassert (bufIndex != 0);
  29570. audioChannelsToUse.add (bufIndex);
  29571. markBufferAsContaining (bufIndex, node->id, outputChan);
  29572. }
  29573. // Now the same thing for midi..
  29574. Array <int> midiSourceNodes;
  29575. for (int i = graph.getNumConnections(); --i >= 0;)
  29576. {
  29577. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  29578. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  29579. midiSourceNodes.add (c->sourceNodeId);
  29580. }
  29581. if (midiSourceNodes.size() == 0)
  29582. {
  29583. // No midi inputs..
  29584. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29585. if (node->getProcessor()->acceptsMidi() || node->getProcessor()->producesMidi())
  29586. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29587. }
  29588. else if (midiSourceNodes.size() == 1)
  29589. {
  29590. // One midi input..
  29591. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29592. AudioProcessorGraph::midiChannelIndex);
  29593. if (midiBufferToUse >= 0)
  29594. {
  29595. if (isBufferNeededLater (ourRenderingIndex,
  29596. AudioProcessorGraph::midiChannelIndex,
  29597. midiSourceNodes.getUnchecked(0),
  29598. AudioProcessorGraph::midiChannelIndex))
  29599. {
  29600. // can't mess up this channel because it's needed later by another node, so we
  29601. // need to use a copy of it..
  29602. const int newFreeBuffer = getFreeBuffer (true);
  29603. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  29604. midiBufferToUse = newFreeBuffer;
  29605. }
  29606. }
  29607. else
  29608. {
  29609. // probably a feedback loop, so just use an empty one..
  29610. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  29611. }
  29612. }
  29613. else
  29614. {
  29615. // More than one midi input being mixed..
  29616. int reusableInputIndex = -1;
  29617. for (int i = 0; i < midiSourceNodes.size(); ++i)
  29618. {
  29619. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  29620. AudioProcessorGraph::midiChannelIndex);
  29621. if (sourceBufIndex >= 0
  29622. && ! isBufferNeededLater (ourRenderingIndex,
  29623. AudioProcessorGraph::midiChannelIndex,
  29624. midiSourceNodes.getUnchecked(i),
  29625. AudioProcessorGraph::midiChannelIndex))
  29626. {
  29627. // we've found one of our input buffers that can be re-used..
  29628. reusableInputIndex = i;
  29629. midiBufferToUse = sourceBufIndex;
  29630. break;
  29631. }
  29632. }
  29633. if (reusableInputIndex < 0)
  29634. {
  29635. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  29636. midiBufferToUse = getFreeBuffer (true);
  29637. jassert (midiBufferToUse >= 0);
  29638. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  29639. AudioProcessorGraph::midiChannelIndex);
  29640. if (srcIndex >= 0)
  29641. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  29642. else
  29643. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  29644. reusableInputIndex = 0;
  29645. }
  29646. for (int j = 0; j < midiSourceNodes.size(); ++j)
  29647. {
  29648. if (j != reusableInputIndex)
  29649. {
  29650. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  29651. AudioProcessorGraph::midiChannelIndex);
  29652. if (srcIndex >= 0)
  29653. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  29654. }
  29655. }
  29656. }
  29657. if (node->getProcessor()->producesMidi())
  29658. markBufferAsContaining (midiBufferToUse, node->id,
  29659. AudioProcessorGraph::midiChannelIndex);
  29660. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  29661. totalChans, midiBufferToUse));
  29662. }
  29663. int getFreeBuffer (const bool forMidi)
  29664. {
  29665. if (forMidi)
  29666. {
  29667. for (int i = 1; i < midiNodeIds.size(); ++i)
  29668. if (midiNodeIds.getUnchecked(i) < 0)
  29669. return i;
  29670. midiNodeIds.add (-1);
  29671. return midiNodeIds.size() - 1;
  29672. }
  29673. else
  29674. {
  29675. for (int i = 1; i < nodeIds.size(); ++i)
  29676. if (nodeIds.getUnchecked(i) < 0)
  29677. return i;
  29678. nodeIds.add (-1);
  29679. channels.add (0);
  29680. return nodeIds.size() - 1;
  29681. }
  29682. }
  29683. int getReadOnlyEmptyBuffer() const
  29684. {
  29685. return 0;
  29686. }
  29687. int getBufferContaining (const int nodeId, const int outputChannel) const
  29688. {
  29689. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  29690. {
  29691. for (int i = midiNodeIds.size(); --i >= 0;)
  29692. if (midiNodeIds.getUnchecked(i) == nodeId)
  29693. return i;
  29694. }
  29695. else
  29696. {
  29697. for (int i = nodeIds.size(); --i >= 0;)
  29698. if (nodeIds.getUnchecked(i) == nodeId
  29699. && channels.getUnchecked(i) == outputChannel)
  29700. return i;
  29701. }
  29702. return -1;
  29703. }
  29704. void markAnyUnusedBuffersAsFree (const int stepIndex)
  29705. {
  29706. int i;
  29707. for (i = 0; i < nodeIds.size(); ++i)
  29708. {
  29709. if (nodeIds.getUnchecked(i) >= 0
  29710. && ! isBufferNeededLater (stepIndex, -1,
  29711. nodeIds.getUnchecked(i),
  29712. channels.getUnchecked(i)))
  29713. {
  29714. nodeIds.set (i, -1);
  29715. }
  29716. }
  29717. for (i = 0; i < midiNodeIds.size(); ++i)
  29718. {
  29719. if (midiNodeIds.getUnchecked(i) >= 0
  29720. && ! isBufferNeededLater (stepIndex, -1,
  29721. midiNodeIds.getUnchecked(i),
  29722. AudioProcessorGraph::midiChannelIndex))
  29723. {
  29724. midiNodeIds.set (i, -1);
  29725. }
  29726. }
  29727. }
  29728. bool isBufferNeededLater (int stepIndexToSearchFrom,
  29729. int inputChannelOfIndexToIgnore,
  29730. const int nodeId,
  29731. const int outputChanIndex) const
  29732. {
  29733. while (stepIndexToSearchFrom < orderedNodes.size())
  29734. {
  29735. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  29736. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  29737. {
  29738. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  29739. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  29740. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  29741. return true;
  29742. }
  29743. else
  29744. {
  29745. for (int i = 0; i < node->getProcessor()->getNumInputChannels(); ++i)
  29746. if (i != inputChannelOfIndexToIgnore
  29747. && graph.getConnectionBetween (nodeId, outputChanIndex,
  29748. node->id, i) != 0)
  29749. return true;
  29750. }
  29751. inputChannelOfIndexToIgnore = -1;
  29752. ++stepIndexToSearchFrom;
  29753. }
  29754. return false;
  29755. }
  29756. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  29757. {
  29758. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  29759. {
  29760. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  29761. midiNodeIds.set (bufferNum, nodeId);
  29762. }
  29763. else
  29764. {
  29765. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  29766. nodeIds.set (bufferNum, nodeId);
  29767. channels.set (bufferNum, outputIndex);
  29768. }
  29769. }
  29770. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  29771. RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  29772. };
  29773. }
  29774. void AudioProcessorGraph::clearRenderingSequence()
  29775. {
  29776. const ScopedLock sl (renderLock);
  29777. for (int i = renderingOps.size(); --i >= 0;)
  29778. {
  29779. GraphRenderingOps::AudioGraphRenderingOp* const r
  29780. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29781. renderingOps.remove (i);
  29782. delete r;
  29783. }
  29784. }
  29785. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  29786. const uint32 possibleDestinationId,
  29787. const int recursionCheck) const
  29788. {
  29789. if (recursionCheck > 0)
  29790. {
  29791. for (int i = connections.size(); --i >= 0;)
  29792. {
  29793. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  29794. if (c->destNodeId == possibleDestinationId
  29795. && (c->sourceNodeId == possibleInputId
  29796. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  29797. return true;
  29798. }
  29799. }
  29800. return false;
  29801. }
  29802. void AudioProcessorGraph::buildRenderingSequence()
  29803. {
  29804. Array<void*> newRenderingOps;
  29805. int numRenderingBuffersNeeded = 2;
  29806. int numMidiBuffersNeeded = 1;
  29807. {
  29808. MessageManagerLock mml;
  29809. Array<void*> orderedNodes;
  29810. int i;
  29811. for (i = 0; i < nodes.size(); ++i)
  29812. {
  29813. Node* const node = nodes.getUnchecked(i);
  29814. node->prepare (getSampleRate(), getBlockSize(), this);
  29815. int j = 0;
  29816. for (; j < orderedNodes.size(); ++j)
  29817. if (isAnInputTo (node->id,
  29818. ((Node*) orderedNodes.getUnchecked (j))->id,
  29819. nodes.size() + 1))
  29820. break;
  29821. orderedNodes.insert (j, node);
  29822. }
  29823. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  29824. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  29825. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  29826. }
  29827. Array<void*> oldRenderingOps (renderingOps);
  29828. {
  29829. // swap over to the new rendering sequence..
  29830. const ScopedLock sl (renderLock);
  29831. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  29832. renderingBuffers.clear();
  29833. for (int i = midiBuffers.size(); --i >= 0;)
  29834. midiBuffers.getUnchecked(i)->clear();
  29835. while (midiBuffers.size() < numMidiBuffersNeeded)
  29836. midiBuffers.add (new MidiBuffer());
  29837. renderingOps = newRenderingOps;
  29838. }
  29839. for (int i = oldRenderingOps.size(); --i >= 0;)
  29840. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  29841. }
  29842. void AudioProcessorGraph::handleAsyncUpdate()
  29843. {
  29844. buildRenderingSequence();
  29845. }
  29846. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  29847. {
  29848. currentAudioInputBuffer = 0;
  29849. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  29850. currentMidiInputBuffer = 0;
  29851. currentMidiOutputBuffer.clear();
  29852. clearRenderingSequence();
  29853. buildRenderingSequence();
  29854. }
  29855. void AudioProcessorGraph::releaseResources()
  29856. {
  29857. for (int i = 0; i < nodes.size(); ++i)
  29858. nodes.getUnchecked(i)->unprepare();
  29859. renderingBuffers.setSize (1, 1);
  29860. midiBuffers.clear();
  29861. currentAudioInputBuffer = 0;
  29862. currentAudioOutputBuffer.setSize (1, 1);
  29863. currentMidiInputBuffer = 0;
  29864. currentMidiOutputBuffer.clear();
  29865. }
  29866. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  29867. {
  29868. const int numSamples = buffer.getNumSamples();
  29869. const ScopedLock sl (renderLock);
  29870. currentAudioInputBuffer = &buffer;
  29871. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  29872. currentAudioOutputBuffer.clear();
  29873. currentMidiInputBuffer = &midiMessages;
  29874. currentMidiOutputBuffer.clear();
  29875. int i;
  29876. for (i = 0; i < renderingOps.size(); ++i)
  29877. {
  29878. GraphRenderingOps::AudioGraphRenderingOp* const op
  29879. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  29880. op->perform (renderingBuffers, midiBuffers, numSamples);
  29881. }
  29882. for (i = 0; i < buffer.getNumChannels(); ++i)
  29883. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  29884. midiMessages.clear();
  29885. midiMessages.addEvents (currentMidiOutputBuffer, 0, buffer.getNumSamples(), 0);
  29886. }
  29887. const String AudioProcessorGraph::getInputChannelName (int channelIndex) const
  29888. {
  29889. return "Input " + String (channelIndex + 1);
  29890. }
  29891. const String AudioProcessorGraph::getOutputChannelName (int channelIndex) const
  29892. {
  29893. return "Output " + String (channelIndex + 1);
  29894. }
  29895. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const { return true; }
  29896. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const { return true; }
  29897. bool AudioProcessorGraph::acceptsMidi() const { return true; }
  29898. bool AudioProcessorGraph::producesMidi() const { return true; }
  29899. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/) {}
  29900. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/) {}
  29901. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  29902. : type (type_),
  29903. graph (0)
  29904. {
  29905. }
  29906. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  29907. {
  29908. }
  29909. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  29910. {
  29911. switch (type)
  29912. {
  29913. case audioOutputNode: return "Audio Output";
  29914. case audioInputNode: return "Audio Input";
  29915. case midiOutputNode: return "Midi Output";
  29916. case midiInputNode: return "Midi Input";
  29917. default: break;
  29918. }
  29919. return String::empty;
  29920. }
  29921. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  29922. {
  29923. d.name = getName();
  29924. d.uid = d.name.hashCode();
  29925. d.category = "I/O devices";
  29926. d.pluginFormatName = "Internal";
  29927. d.manufacturerName = "Raw Material Software";
  29928. d.version = "1.0";
  29929. d.isInstrument = false;
  29930. d.numInputChannels = getNumInputChannels();
  29931. if (type == audioOutputNode && graph != 0)
  29932. d.numInputChannels = graph->getNumInputChannels();
  29933. d.numOutputChannels = getNumOutputChannels();
  29934. if (type == audioInputNode && graph != 0)
  29935. d.numOutputChannels = graph->getNumOutputChannels();
  29936. }
  29937. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  29938. {
  29939. jassert (graph != 0);
  29940. }
  29941. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  29942. {
  29943. }
  29944. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  29945. MidiBuffer& midiMessages)
  29946. {
  29947. jassert (graph != 0);
  29948. switch (type)
  29949. {
  29950. case audioOutputNode:
  29951. {
  29952. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  29953. buffer.getNumChannels()); --i >= 0;)
  29954. {
  29955. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  29956. }
  29957. break;
  29958. }
  29959. case audioInputNode:
  29960. {
  29961. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  29962. buffer.getNumChannels()); --i >= 0;)
  29963. {
  29964. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  29965. }
  29966. break;
  29967. }
  29968. case midiOutputNode:
  29969. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  29970. break;
  29971. case midiInputNode:
  29972. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  29973. break;
  29974. default:
  29975. break;
  29976. }
  29977. }
  29978. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  29979. {
  29980. return type == midiOutputNode;
  29981. }
  29982. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  29983. {
  29984. return type == midiInputNode;
  29985. }
  29986. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (int channelIndex) const
  29987. {
  29988. switch (type)
  29989. {
  29990. case audioOutputNode: return "Output " + String (channelIndex + 1);
  29991. case midiOutputNode: return "Midi Output";
  29992. default: break;
  29993. }
  29994. return String::empty;
  29995. }
  29996. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (int channelIndex) const
  29997. {
  29998. switch (type)
  29999. {
  30000. case audioInputNode: return "Input " + String (channelIndex + 1);
  30001. case midiInputNode: return "Midi Input";
  30002. default: break;
  30003. }
  30004. return String::empty;
  30005. }
  30006. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  30007. {
  30008. return type == audioInputNode || type == audioOutputNode;
  30009. }
  30010. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  30011. {
  30012. return isInputChannelStereoPair (index);
  30013. }
  30014. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const
  30015. {
  30016. return type == audioInputNode || type == midiInputNode;
  30017. }
  30018. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const
  30019. {
  30020. return type == audioOutputNode || type == midiOutputNode;
  30021. }
  30022. bool AudioProcessorGraph::AudioGraphIOProcessor::hasEditor() const { return false; }
  30023. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor() { return 0; }
  30024. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  30025. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  30026. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  30027. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  30028. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  30029. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  30030. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  30031. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  30032. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  30033. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  30034. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  30035. {
  30036. }
  30037. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  30038. {
  30039. }
  30040. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph)
  30041. {
  30042. graph = newGraph;
  30043. if (graph != 0)
  30044. {
  30045. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  30046. type == audioInputNode ? graph->getNumInputChannels() : 0,
  30047. getSampleRate(),
  30048. getBlockSize());
  30049. updateHostDisplay();
  30050. }
  30051. }
  30052. END_JUCE_NAMESPACE
  30053. /*** End of inlined file: juce_AudioProcessorGraph.cpp ***/
  30054. /*** Start of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30055. BEGIN_JUCE_NAMESPACE
  30056. AudioProcessorPlayer::AudioProcessorPlayer()
  30057. : processor (0),
  30058. sampleRate (0),
  30059. blockSize (0),
  30060. isPrepared (false),
  30061. numInputChans (0),
  30062. numOutputChans (0),
  30063. tempBuffer (1, 1)
  30064. {
  30065. }
  30066. AudioProcessorPlayer::~AudioProcessorPlayer()
  30067. {
  30068. setProcessor (0);
  30069. }
  30070. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  30071. {
  30072. if (processor != processorToPlay)
  30073. {
  30074. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  30075. {
  30076. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  30077. sampleRate, blockSize);
  30078. processorToPlay->prepareToPlay (sampleRate, blockSize);
  30079. }
  30080. AudioProcessor* oldOne;
  30081. {
  30082. const ScopedLock sl (lock);
  30083. oldOne = isPrepared ? processor : 0;
  30084. processor = processorToPlay;
  30085. isPrepared = true;
  30086. }
  30087. if (oldOne != 0)
  30088. oldOne->releaseResources();
  30089. }
  30090. }
  30091. void AudioProcessorPlayer::audioDeviceIOCallback (const float** const inputChannelData,
  30092. const int numInputChannels,
  30093. float** const outputChannelData,
  30094. const int numOutputChannels,
  30095. const int numSamples)
  30096. {
  30097. // these should have been prepared by audioDeviceAboutToStart()...
  30098. jassert (sampleRate > 0 && blockSize > 0);
  30099. incomingMidi.clear();
  30100. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  30101. int i, totalNumChans = 0;
  30102. if (numInputChannels > numOutputChannels)
  30103. {
  30104. // if there aren't enough output channels for the number of
  30105. // inputs, we need to create some temporary extra ones (can't
  30106. // use the input data in case it gets written to)
  30107. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  30108. false, false, true);
  30109. for (i = 0; i < numOutputChannels; ++i)
  30110. {
  30111. channels[totalNumChans] = outputChannelData[i];
  30112. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30113. ++totalNumChans;
  30114. }
  30115. for (i = numOutputChannels; i < numInputChannels; ++i)
  30116. {
  30117. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  30118. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30119. ++totalNumChans;
  30120. }
  30121. }
  30122. else
  30123. {
  30124. for (i = 0; i < numInputChannels; ++i)
  30125. {
  30126. channels[totalNumChans] = outputChannelData[i];
  30127. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  30128. ++totalNumChans;
  30129. }
  30130. for (i = numInputChannels; i < numOutputChannels; ++i)
  30131. {
  30132. channels[totalNumChans] = outputChannelData[i];
  30133. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  30134. ++totalNumChans;
  30135. }
  30136. }
  30137. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  30138. const ScopedLock sl (lock);
  30139. if (processor != 0)
  30140. {
  30141. const ScopedLock sl (processor->getCallbackLock());
  30142. if (processor->isSuspended())
  30143. {
  30144. for (i = 0; i < numOutputChannels; ++i)
  30145. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  30146. }
  30147. else
  30148. {
  30149. processor->processBlock (buffer, incomingMidi);
  30150. }
  30151. }
  30152. }
  30153. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  30154. {
  30155. const ScopedLock sl (lock);
  30156. sampleRate = device->getCurrentSampleRate();
  30157. blockSize = device->getCurrentBufferSizeSamples();
  30158. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  30159. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  30160. messageCollector.reset (sampleRate);
  30161. zeromem (channels, sizeof (channels));
  30162. if (processor != 0)
  30163. {
  30164. if (isPrepared)
  30165. processor->releaseResources();
  30166. AudioProcessor* const oldProcessor = processor;
  30167. setProcessor (0);
  30168. setProcessor (oldProcessor);
  30169. }
  30170. }
  30171. void AudioProcessorPlayer::audioDeviceStopped()
  30172. {
  30173. const ScopedLock sl (lock);
  30174. if (processor != 0 && isPrepared)
  30175. processor->releaseResources();
  30176. sampleRate = 0.0;
  30177. blockSize = 0;
  30178. isPrepared = false;
  30179. tempBuffer.setSize (1, 1);
  30180. }
  30181. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  30182. {
  30183. messageCollector.addMessageToQueue (message);
  30184. }
  30185. END_JUCE_NAMESPACE
  30186. /*** End of inlined file: juce_AudioProcessorPlayer.cpp ***/
  30187. /*** Start of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30188. BEGIN_JUCE_NAMESPACE
  30189. class ProcessorParameterPropertyComp : public PropertyComponent,
  30190. public AudioProcessorListener,
  30191. public Timer
  30192. {
  30193. public:
  30194. ProcessorParameterPropertyComp (const String& name, AudioProcessor& owner_, const int index_)
  30195. : PropertyComponent (name),
  30196. owner (owner_),
  30197. index (index_),
  30198. paramHasChanged (false),
  30199. slider (owner_, index_)
  30200. {
  30201. startTimer (100);
  30202. addAndMakeVisible (&slider);
  30203. owner_.addListener (this);
  30204. }
  30205. ~ProcessorParameterPropertyComp()
  30206. {
  30207. owner.removeListener (this);
  30208. }
  30209. void refresh()
  30210. {
  30211. paramHasChanged = false;
  30212. slider.setValue (owner.getParameter (index), false);
  30213. }
  30214. void audioProcessorChanged (AudioProcessor*) {}
  30215. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  30216. {
  30217. if (parameterIndex == index)
  30218. paramHasChanged = true;
  30219. }
  30220. void timerCallback()
  30221. {
  30222. if (paramHasChanged)
  30223. {
  30224. refresh();
  30225. startTimer (1000 / 50);
  30226. }
  30227. else
  30228. {
  30229. startTimer (jmin (1000 / 4, getTimerInterval() + 10));
  30230. }
  30231. }
  30232. juce_UseDebuggingNewOperator
  30233. private:
  30234. class ParamSlider : public Slider
  30235. {
  30236. public:
  30237. ParamSlider (AudioProcessor& owner_, const int index_)
  30238. : owner (owner_),
  30239. index (index_)
  30240. {
  30241. setRange (0.0, 1.0, 0.0);
  30242. setSliderStyle (Slider::LinearBar);
  30243. setTextBoxIsEditable (false);
  30244. setScrollWheelEnabled (false);
  30245. }
  30246. void valueChanged()
  30247. {
  30248. const float newVal = (float) getValue();
  30249. if (owner.getParameter (index) != newVal)
  30250. owner.setParameter (index, newVal);
  30251. }
  30252. const String getTextFromValue (double /*value*/)
  30253. {
  30254. return owner.getParameterText (index);
  30255. }
  30256. juce_UseDebuggingNewOperator
  30257. private:
  30258. AudioProcessor& owner;
  30259. const int index;
  30260. ParamSlider (const ParamSlider&);
  30261. ParamSlider& operator= (const ParamSlider&);
  30262. };
  30263. AudioProcessor& owner;
  30264. const int index;
  30265. bool volatile paramHasChanged;
  30266. ParamSlider slider;
  30267. ProcessorParameterPropertyComp (const ProcessorParameterPropertyComp&);
  30268. ProcessorParameterPropertyComp& operator= (const ProcessorParameterPropertyComp&);
  30269. };
  30270. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner_)
  30271. : AudioProcessorEditor (owner_)
  30272. {
  30273. jassert (owner_ != 0);
  30274. setOpaque (true);
  30275. addAndMakeVisible (&panel);
  30276. Array <PropertyComponent*> params;
  30277. const int numParams = owner_->getNumParameters();
  30278. int totalHeight = 0;
  30279. for (int i = 0; i < numParams; ++i)
  30280. {
  30281. String name (owner_->getParameterName (i));
  30282. if (name.trim().isEmpty())
  30283. name = "Unnamed";
  30284. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, *owner_, i);
  30285. params.add (pc);
  30286. totalHeight += pc->getPreferredHeight();
  30287. }
  30288. panel.addProperties (params);
  30289. setSize (400, jlimit (25, 400, totalHeight));
  30290. }
  30291. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  30292. {
  30293. }
  30294. void GenericAudioProcessorEditor::paint (Graphics& g)
  30295. {
  30296. g.fillAll (Colours::white);
  30297. }
  30298. void GenericAudioProcessorEditor::resized()
  30299. {
  30300. panel.setBounds (getLocalBounds());
  30301. }
  30302. END_JUCE_NAMESPACE
  30303. /*** End of inlined file: juce_GenericAudioProcessorEditor.cpp ***/
  30304. /*** Start of inlined file: juce_Sampler.cpp ***/
  30305. BEGIN_JUCE_NAMESPACE
  30306. SamplerSound::SamplerSound (const String& name_,
  30307. AudioFormatReader& source,
  30308. const BigInteger& midiNotes_,
  30309. const int midiNoteForNormalPitch,
  30310. const double attackTimeSecs,
  30311. const double releaseTimeSecs,
  30312. const double maxSampleLengthSeconds)
  30313. : name (name_),
  30314. midiNotes (midiNotes_),
  30315. midiRootNote (midiNoteForNormalPitch)
  30316. {
  30317. sourceSampleRate = source.sampleRate;
  30318. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  30319. {
  30320. length = 0;
  30321. attackSamples = 0;
  30322. releaseSamples = 0;
  30323. }
  30324. else
  30325. {
  30326. length = jmin ((int) source.lengthInSamples,
  30327. (int) (maxSampleLengthSeconds * sourceSampleRate));
  30328. data = new AudioSampleBuffer (jmin (2, (int) source.numChannels), length + 4);
  30329. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  30330. attackSamples = roundToInt (attackTimeSecs * sourceSampleRate);
  30331. releaseSamples = roundToInt (releaseTimeSecs * sourceSampleRate);
  30332. }
  30333. }
  30334. SamplerSound::~SamplerSound()
  30335. {
  30336. }
  30337. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  30338. {
  30339. return midiNotes [midiNoteNumber];
  30340. }
  30341. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  30342. {
  30343. return true;
  30344. }
  30345. SamplerVoice::SamplerVoice()
  30346. : pitchRatio (0.0),
  30347. sourceSamplePosition (0.0),
  30348. lgain (0.0f),
  30349. rgain (0.0f),
  30350. isInAttack (false),
  30351. isInRelease (false)
  30352. {
  30353. }
  30354. SamplerVoice::~SamplerVoice()
  30355. {
  30356. }
  30357. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  30358. {
  30359. return dynamic_cast <const SamplerSound*> (sound) != 0;
  30360. }
  30361. void SamplerVoice::startNote (const int midiNoteNumber,
  30362. const float velocity,
  30363. SynthesiserSound* s,
  30364. const int /*currentPitchWheelPosition*/)
  30365. {
  30366. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  30367. jassert (sound != 0); // this object can only play SamplerSounds!
  30368. if (sound != 0)
  30369. {
  30370. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  30371. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  30372. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  30373. sourceSamplePosition = 0.0;
  30374. lgain = velocity;
  30375. rgain = velocity;
  30376. isInAttack = (sound->attackSamples > 0);
  30377. isInRelease = false;
  30378. if (isInAttack)
  30379. {
  30380. attackReleaseLevel = 0.0f;
  30381. attackDelta = (float) (pitchRatio / sound->attackSamples);
  30382. }
  30383. else
  30384. {
  30385. attackReleaseLevel = 1.0f;
  30386. attackDelta = 0.0f;
  30387. }
  30388. if (sound->releaseSamples > 0)
  30389. {
  30390. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  30391. }
  30392. else
  30393. {
  30394. releaseDelta = 0.0f;
  30395. }
  30396. }
  30397. }
  30398. void SamplerVoice::stopNote (const bool allowTailOff)
  30399. {
  30400. if (allowTailOff)
  30401. {
  30402. isInAttack = false;
  30403. isInRelease = true;
  30404. }
  30405. else
  30406. {
  30407. clearCurrentNote();
  30408. }
  30409. }
  30410. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  30411. {
  30412. }
  30413. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  30414. const int /*newValue*/)
  30415. {
  30416. }
  30417. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  30418. {
  30419. const SamplerSound* const playingSound = static_cast <SamplerSound*> (getCurrentlyPlayingSound().getObject());
  30420. if (playingSound != 0)
  30421. {
  30422. const float* const inL = playingSound->data->getSampleData (0, 0);
  30423. const float* const inR = playingSound->data->getNumChannels() > 1
  30424. ? playingSound->data->getSampleData (1, 0) : 0;
  30425. float* outL = outputBuffer.getSampleData (0, startSample);
  30426. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  30427. while (--numSamples >= 0)
  30428. {
  30429. const int pos = (int) sourceSamplePosition;
  30430. const float alpha = (float) (sourceSamplePosition - pos);
  30431. const float invAlpha = 1.0f - alpha;
  30432. // just using a very simple linear interpolation here..
  30433. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  30434. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  30435. : l;
  30436. l *= lgain;
  30437. r *= rgain;
  30438. if (isInAttack)
  30439. {
  30440. l *= attackReleaseLevel;
  30441. r *= attackReleaseLevel;
  30442. attackReleaseLevel += attackDelta;
  30443. if (attackReleaseLevel >= 1.0f)
  30444. {
  30445. attackReleaseLevel = 1.0f;
  30446. isInAttack = false;
  30447. }
  30448. }
  30449. else if (isInRelease)
  30450. {
  30451. l *= attackReleaseLevel;
  30452. r *= attackReleaseLevel;
  30453. attackReleaseLevel += releaseDelta;
  30454. if (attackReleaseLevel <= 0.0f)
  30455. {
  30456. stopNote (false);
  30457. break;
  30458. }
  30459. }
  30460. if (outR != 0)
  30461. {
  30462. *outL++ += l;
  30463. *outR++ += r;
  30464. }
  30465. else
  30466. {
  30467. *outL++ += (l + r) * 0.5f;
  30468. }
  30469. sourceSamplePosition += pitchRatio;
  30470. if (sourceSamplePosition > playingSound->length)
  30471. {
  30472. stopNote (false);
  30473. break;
  30474. }
  30475. }
  30476. }
  30477. }
  30478. END_JUCE_NAMESPACE
  30479. /*** End of inlined file: juce_Sampler.cpp ***/
  30480. /*** Start of inlined file: juce_Synthesiser.cpp ***/
  30481. BEGIN_JUCE_NAMESPACE
  30482. SynthesiserSound::SynthesiserSound()
  30483. {
  30484. }
  30485. SynthesiserSound::~SynthesiserSound()
  30486. {
  30487. }
  30488. SynthesiserVoice::SynthesiserVoice()
  30489. : currentSampleRate (44100.0),
  30490. currentlyPlayingNote (-1),
  30491. noteOnTime (0),
  30492. currentlyPlayingSound (0)
  30493. {
  30494. }
  30495. SynthesiserVoice::~SynthesiserVoice()
  30496. {
  30497. }
  30498. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  30499. {
  30500. return currentlyPlayingSound != 0
  30501. && currentlyPlayingSound->appliesToChannel (midiChannel);
  30502. }
  30503. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  30504. {
  30505. currentSampleRate = newRate;
  30506. }
  30507. void SynthesiserVoice::clearCurrentNote()
  30508. {
  30509. currentlyPlayingNote = -1;
  30510. currentlyPlayingSound = 0;
  30511. }
  30512. Synthesiser::Synthesiser()
  30513. : sampleRate (0),
  30514. lastNoteOnCounter (0),
  30515. shouldStealNotes (true)
  30516. {
  30517. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  30518. lastPitchWheelValues[i] = 0x2000;
  30519. }
  30520. Synthesiser::~Synthesiser()
  30521. {
  30522. }
  30523. SynthesiserVoice* Synthesiser::getVoice (const int index) const
  30524. {
  30525. const ScopedLock sl (lock);
  30526. return voices [index];
  30527. }
  30528. void Synthesiser::clearVoices()
  30529. {
  30530. const ScopedLock sl (lock);
  30531. voices.clear();
  30532. }
  30533. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  30534. {
  30535. const ScopedLock sl (lock);
  30536. voices.add (newVoice);
  30537. }
  30538. void Synthesiser::removeVoice (const int index)
  30539. {
  30540. const ScopedLock sl (lock);
  30541. voices.remove (index);
  30542. }
  30543. void Synthesiser::clearSounds()
  30544. {
  30545. const ScopedLock sl (lock);
  30546. sounds.clear();
  30547. }
  30548. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  30549. {
  30550. const ScopedLock sl (lock);
  30551. sounds.add (newSound);
  30552. }
  30553. void Synthesiser::removeSound (const int index)
  30554. {
  30555. const ScopedLock sl (lock);
  30556. sounds.remove (index);
  30557. }
  30558. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  30559. {
  30560. shouldStealNotes = shouldStealNotes_;
  30561. }
  30562. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  30563. {
  30564. if (sampleRate != newRate)
  30565. {
  30566. const ScopedLock sl (lock);
  30567. allNotesOff (0, false);
  30568. sampleRate = newRate;
  30569. for (int i = voices.size(); --i >= 0;)
  30570. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  30571. }
  30572. }
  30573. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  30574. const MidiBuffer& midiData,
  30575. int startSample,
  30576. int numSamples)
  30577. {
  30578. // must set the sample rate before using this!
  30579. jassert (sampleRate != 0);
  30580. const ScopedLock sl (lock);
  30581. MidiBuffer::Iterator midiIterator (midiData);
  30582. midiIterator.setNextSamplePosition (startSample);
  30583. MidiMessage m (0xf4, 0.0);
  30584. while (numSamples > 0)
  30585. {
  30586. int midiEventPos;
  30587. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  30588. && midiEventPos < startSample + numSamples;
  30589. const int numThisTime = useEvent ? midiEventPos - startSample
  30590. : numSamples;
  30591. if (numThisTime > 0)
  30592. {
  30593. for (int i = voices.size(); --i >= 0;)
  30594. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  30595. }
  30596. if (useEvent)
  30597. {
  30598. if (m.isNoteOn())
  30599. {
  30600. const int channel = m.getChannel();
  30601. noteOn (channel,
  30602. m.getNoteNumber(),
  30603. m.getFloatVelocity());
  30604. }
  30605. else if (m.isNoteOff())
  30606. {
  30607. noteOff (m.getChannel(),
  30608. m.getNoteNumber(),
  30609. true);
  30610. }
  30611. else if (m.isAllNotesOff() || m.isAllSoundOff())
  30612. {
  30613. allNotesOff (m.getChannel(), true);
  30614. }
  30615. else if (m.isPitchWheel())
  30616. {
  30617. const int channel = m.getChannel();
  30618. const int wheelPos = m.getPitchWheelValue();
  30619. lastPitchWheelValues [channel - 1] = wheelPos;
  30620. handlePitchWheel (channel, wheelPos);
  30621. }
  30622. else if (m.isController())
  30623. {
  30624. handleController (m.getChannel(),
  30625. m.getControllerNumber(),
  30626. m.getControllerValue());
  30627. }
  30628. }
  30629. startSample += numThisTime;
  30630. numSamples -= numThisTime;
  30631. }
  30632. }
  30633. void Synthesiser::noteOn (const int midiChannel,
  30634. const int midiNoteNumber,
  30635. const float velocity)
  30636. {
  30637. const ScopedLock sl (lock);
  30638. for (int i = sounds.size(); --i >= 0;)
  30639. {
  30640. SynthesiserSound* const sound = sounds.getUnchecked(i);
  30641. if (sound->appliesToNote (midiNoteNumber)
  30642. && sound->appliesToChannel (midiChannel))
  30643. {
  30644. startVoice (findFreeVoice (sound, shouldStealNotes),
  30645. sound, midiChannel, midiNoteNumber, velocity);
  30646. }
  30647. }
  30648. }
  30649. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  30650. SynthesiserSound* const sound,
  30651. const int midiChannel,
  30652. const int midiNoteNumber,
  30653. const float velocity)
  30654. {
  30655. if (voice != 0 && sound != 0)
  30656. {
  30657. if (voice->currentlyPlayingSound != 0)
  30658. voice->stopNote (false);
  30659. voice->startNote (midiNoteNumber,
  30660. velocity,
  30661. sound,
  30662. lastPitchWheelValues [midiChannel - 1]);
  30663. voice->currentlyPlayingNote = midiNoteNumber;
  30664. voice->noteOnTime = ++lastNoteOnCounter;
  30665. voice->currentlyPlayingSound = sound;
  30666. }
  30667. }
  30668. void Synthesiser::noteOff (const int midiChannel,
  30669. const int midiNoteNumber,
  30670. const bool allowTailOff)
  30671. {
  30672. const ScopedLock sl (lock);
  30673. for (int i = voices.size(); --i >= 0;)
  30674. {
  30675. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30676. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  30677. {
  30678. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  30679. if (sound != 0
  30680. && sound->appliesToNote (midiNoteNumber)
  30681. && sound->appliesToChannel (midiChannel))
  30682. {
  30683. voice->stopNote (allowTailOff);
  30684. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  30685. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  30686. }
  30687. }
  30688. }
  30689. }
  30690. void Synthesiser::allNotesOff (const int midiChannel,
  30691. const bool allowTailOff)
  30692. {
  30693. const ScopedLock sl (lock);
  30694. for (int i = voices.size(); --i >= 0;)
  30695. {
  30696. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30697. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30698. voice->stopNote (allowTailOff);
  30699. }
  30700. }
  30701. void Synthesiser::handlePitchWheel (const int midiChannel,
  30702. const int wheelValue)
  30703. {
  30704. const ScopedLock sl (lock);
  30705. for (int i = voices.size(); --i >= 0;)
  30706. {
  30707. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30708. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30709. {
  30710. voice->pitchWheelMoved (wheelValue);
  30711. }
  30712. }
  30713. }
  30714. void Synthesiser::handleController (const int midiChannel,
  30715. const int controllerNumber,
  30716. const int controllerValue)
  30717. {
  30718. const ScopedLock sl (lock);
  30719. for (int i = voices.size(); --i >= 0;)
  30720. {
  30721. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30722. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  30723. voice->controllerMoved (controllerNumber, controllerValue);
  30724. }
  30725. }
  30726. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  30727. const bool stealIfNoneAvailable) const
  30728. {
  30729. const ScopedLock sl (lock);
  30730. for (int i = voices.size(); --i >= 0;)
  30731. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  30732. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  30733. return voices.getUnchecked (i);
  30734. if (stealIfNoneAvailable)
  30735. {
  30736. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  30737. SynthesiserVoice* oldest = 0;
  30738. for (int i = voices.size(); --i >= 0;)
  30739. {
  30740. SynthesiserVoice* const voice = voices.getUnchecked (i);
  30741. if (voice->canPlaySound (soundToPlay)
  30742. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  30743. oldest = voice;
  30744. }
  30745. jassert (oldest != 0);
  30746. return oldest;
  30747. }
  30748. return 0;
  30749. }
  30750. END_JUCE_NAMESPACE
  30751. /*** End of inlined file: juce_Synthesiser.cpp ***/
  30752. /*** Start of inlined file: juce_ActionBroadcaster.cpp ***/
  30753. BEGIN_JUCE_NAMESPACE
  30754. ActionBroadcaster::ActionBroadcaster() throw()
  30755. {
  30756. // are you trying to create this object before or after juce has been intialised??
  30757. jassert (MessageManager::instance != 0);
  30758. }
  30759. ActionBroadcaster::~ActionBroadcaster()
  30760. {
  30761. // all event-based objects must be deleted BEFORE juce is shut down!
  30762. jassert (MessageManager::instance != 0);
  30763. }
  30764. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  30765. {
  30766. actionListenerList.addActionListener (listener);
  30767. }
  30768. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  30769. {
  30770. jassert (actionListenerList.isValidMessageListener());
  30771. if (actionListenerList.isValidMessageListener())
  30772. actionListenerList.removeActionListener (listener);
  30773. }
  30774. void ActionBroadcaster::removeAllActionListeners()
  30775. {
  30776. actionListenerList.removeAllActionListeners();
  30777. }
  30778. void ActionBroadcaster::sendActionMessage (const String& message) const
  30779. {
  30780. actionListenerList.sendActionMessage (message);
  30781. }
  30782. END_JUCE_NAMESPACE
  30783. /*** End of inlined file: juce_ActionBroadcaster.cpp ***/
  30784. /*** Start of inlined file: juce_ActionListenerList.cpp ***/
  30785. BEGIN_JUCE_NAMESPACE
  30786. // special message of our own with a string in it
  30787. class ActionMessage : public Message
  30788. {
  30789. public:
  30790. const String message;
  30791. ActionMessage (const String& messageText, void* const listener_) throw()
  30792. : message (messageText)
  30793. {
  30794. pointerParameter = listener_;
  30795. }
  30796. ~ActionMessage() throw()
  30797. {
  30798. }
  30799. private:
  30800. ActionMessage (const ActionMessage&);
  30801. ActionMessage& operator= (const ActionMessage&);
  30802. };
  30803. ActionListenerList::ActionListenerList()
  30804. {
  30805. }
  30806. ActionListenerList::~ActionListenerList()
  30807. {
  30808. }
  30809. void ActionListenerList::addActionListener (ActionListener* const listener)
  30810. {
  30811. const ScopedLock sl (actionListenerLock_);
  30812. jassert (listener != 0);
  30813. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  30814. if (listener != 0)
  30815. actionListeners_.add (listener);
  30816. }
  30817. void ActionListenerList::removeActionListener (ActionListener* const listener)
  30818. {
  30819. const ScopedLock sl (actionListenerLock_);
  30820. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  30821. actionListeners_.removeValue (listener);
  30822. }
  30823. void ActionListenerList::removeAllActionListeners()
  30824. {
  30825. const ScopedLock sl (actionListenerLock_);
  30826. actionListeners_.clear();
  30827. }
  30828. void ActionListenerList::sendActionMessage (const String& message) const
  30829. {
  30830. const ScopedLock sl (actionListenerLock_);
  30831. for (int i = actionListeners_.size(); --i >= 0;)
  30832. postMessage (new ActionMessage (message, static_cast <ActionListener*> (actionListeners_.getUnchecked(i))));
  30833. }
  30834. void ActionListenerList::handleMessage (const Message& message)
  30835. {
  30836. const ActionMessage& am = (const ActionMessage&) message;
  30837. if (actionListeners_.contains (am.pointerParameter))
  30838. static_cast <ActionListener*> (am.pointerParameter)->actionListenerCallback (am.message);
  30839. }
  30840. END_JUCE_NAMESPACE
  30841. /*** End of inlined file: juce_ActionListenerList.cpp ***/
  30842. /*** Start of inlined file: juce_AsyncUpdater.cpp ***/
  30843. BEGIN_JUCE_NAMESPACE
  30844. AsyncUpdater::AsyncUpdater() throw()
  30845. : asyncMessagePending (false)
  30846. {
  30847. internalAsyncHandler.owner = this;
  30848. }
  30849. AsyncUpdater::~AsyncUpdater()
  30850. {
  30851. }
  30852. void AsyncUpdater::triggerAsyncUpdate()
  30853. {
  30854. if (! asyncMessagePending)
  30855. {
  30856. asyncMessagePending = true;
  30857. internalAsyncHandler.postMessage (new Message());
  30858. }
  30859. }
  30860. void AsyncUpdater::cancelPendingUpdate() throw()
  30861. {
  30862. asyncMessagePending = false;
  30863. }
  30864. void AsyncUpdater::handleUpdateNowIfNeeded()
  30865. {
  30866. if (asyncMessagePending)
  30867. {
  30868. asyncMessagePending = false;
  30869. handleAsyncUpdate();
  30870. }
  30871. }
  30872. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  30873. {
  30874. owner->handleUpdateNowIfNeeded();
  30875. }
  30876. END_JUCE_NAMESPACE
  30877. /*** End of inlined file: juce_AsyncUpdater.cpp ***/
  30878. /*** Start of inlined file: juce_ChangeBroadcaster.cpp ***/
  30879. BEGIN_JUCE_NAMESPACE
  30880. ChangeBroadcaster::ChangeBroadcaster() throw()
  30881. {
  30882. // are you trying to create this object before or after juce has been intialised??
  30883. jassert (MessageManager::instance != 0);
  30884. }
  30885. ChangeBroadcaster::~ChangeBroadcaster()
  30886. {
  30887. // all event-based objects must be deleted BEFORE juce is shut down!
  30888. jassert (MessageManager::instance != 0);
  30889. }
  30890. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener)
  30891. {
  30892. changeListenerList.addChangeListener (listener);
  30893. }
  30894. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener)
  30895. {
  30896. jassert (changeListenerList.isValidMessageListener());
  30897. if (changeListenerList.isValidMessageListener())
  30898. changeListenerList.removeChangeListener (listener);
  30899. }
  30900. void ChangeBroadcaster::removeAllChangeListeners()
  30901. {
  30902. changeListenerList.removeAllChangeListeners();
  30903. }
  30904. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged)
  30905. {
  30906. changeListenerList.sendChangeMessage (objectThatHasChanged);
  30907. }
  30908. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  30909. {
  30910. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  30911. }
  30912. void ChangeBroadcaster::dispatchPendingMessages()
  30913. {
  30914. changeListenerList.dispatchPendingMessages();
  30915. }
  30916. END_JUCE_NAMESPACE
  30917. /*** End of inlined file: juce_ChangeBroadcaster.cpp ***/
  30918. /*** Start of inlined file: juce_ChangeListenerList.cpp ***/
  30919. BEGIN_JUCE_NAMESPACE
  30920. ChangeListenerList::ChangeListenerList()
  30921. : lastChangedObject (0),
  30922. messagePending (false)
  30923. {
  30924. }
  30925. ChangeListenerList::~ChangeListenerList()
  30926. {
  30927. }
  30928. void ChangeListenerList::addChangeListener (ChangeListener* const listener)
  30929. {
  30930. const ScopedLock sl (lock);
  30931. jassert (listener != 0);
  30932. if (listener != 0)
  30933. listeners.add (listener);
  30934. }
  30935. void ChangeListenerList::removeChangeListener (ChangeListener* const listener)
  30936. {
  30937. const ScopedLock sl (lock);
  30938. listeners.removeValue (listener);
  30939. }
  30940. void ChangeListenerList::removeAllChangeListeners()
  30941. {
  30942. const ScopedLock sl (lock);
  30943. listeners.clear();
  30944. }
  30945. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged)
  30946. {
  30947. const ScopedLock sl (lock);
  30948. if ((! messagePending) && (listeners.size() > 0))
  30949. {
  30950. lastChangedObject = objectThatHasChanged;
  30951. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  30952. messagePending = true;
  30953. }
  30954. }
  30955. void ChangeListenerList::handleMessage (const Message& message)
  30956. {
  30957. sendSynchronousChangeMessage (message.pointerParameter);
  30958. }
  30959. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  30960. {
  30961. const ScopedLock sl (lock);
  30962. messagePending = false;
  30963. for (int i = listeners.size(); --i >= 0;)
  30964. {
  30965. ChangeListener* const l = static_cast <ChangeListener*> (listeners.getUnchecked (i));
  30966. {
  30967. const ScopedUnlock tempUnlocker (lock);
  30968. l->changeListenerCallback (objectThatHasChanged);
  30969. }
  30970. i = jmin (i, listeners.size());
  30971. }
  30972. }
  30973. void ChangeListenerList::dispatchPendingMessages()
  30974. {
  30975. if (messagePending)
  30976. sendSynchronousChangeMessage (lastChangedObject);
  30977. }
  30978. END_JUCE_NAMESPACE
  30979. /*** End of inlined file: juce_ChangeListenerList.cpp ***/
  30980. /*** Start of inlined file: juce_InterprocessConnection.cpp ***/
  30981. BEGIN_JUCE_NAMESPACE
  30982. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  30983. const uint32 magicMessageHeaderNumber)
  30984. : Thread ("Juce IPC connection"),
  30985. callbackConnectionState (false),
  30986. useMessageThread (callbacksOnMessageThread),
  30987. magicMessageHeader (magicMessageHeaderNumber),
  30988. pipeReceiveMessageTimeout (-1)
  30989. {
  30990. }
  30991. InterprocessConnection::~InterprocessConnection()
  30992. {
  30993. callbackConnectionState = false;
  30994. disconnect();
  30995. }
  30996. bool InterprocessConnection::connectToSocket (const String& hostName,
  30997. const int portNumber,
  30998. const int timeOutMillisecs)
  30999. {
  31000. disconnect();
  31001. const ScopedLock sl (pipeAndSocketLock);
  31002. socket = new StreamingSocket();
  31003. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  31004. {
  31005. connectionMadeInt();
  31006. startThread();
  31007. return true;
  31008. }
  31009. else
  31010. {
  31011. socket = 0;
  31012. return false;
  31013. }
  31014. }
  31015. bool InterprocessConnection::connectToPipe (const String& pipeName,
  31016. const int pipeReceiveMessageTimeoutMs)
  31017. {
  31018. disconnect();
  31019. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31020. if (newPipe->openExisting (pipeName))
  31021. {
  31022. const ScopedLock sl (pipeAndSocketLock);
  31023. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31024. initialiseWithPipe (newPipe.release());
  31025. return true;
  31026. }
  31027. return false;
  31028. }
  31029. bool InterprocessConnection::createPipe (const String& pipeName,
  31030. const int pipeReceiveMessageTimeoutMs)
  31031. {
  31032. disconnect();
  31033. ScopedPointer <NamedPipe> newPipe (new NamedPipe());
  31034. if (newPipe->createNewPipe (pipeName))
  31035. {
  31036. const ScopedLock sl (pipeAndSocketLock);
  31037. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  31038. initialiseWithPipe (newPipe.release());
  31039. return true;
  31040. }
  31041. return false;
  31042. }
  31043. void InterprocessConnection::disconnect()
  31044. {
  31045. if (socket != 0)
  31046. socket->close();
  31047. if (pipe != 0)
  31048. {
  31049. pipe->cancelPendingReads();
  31050. pipe->close();
  31051. }
  31052. stopThread (4000);
  31053. {
  31054. const ScopedLock sl (pipeAndSocketLock);
  31055. socket = 0;
  31056. pipe = 0;
  31057. }
  31058. connectionLostInt();
  31059. }
  31060. bool InterprocessConnection::isConnected() const
  31061. {
  31062. const ScopedLock sl (pipeAndSocketLock);
  31063. return ((socket != 0 && socket->isConnected())
  31064. || (pipe != 0 && pipe->isOpen()))
  31065. && isThreadRunning();
  31066. }
  31067. const String InterprocessConnection::getConnectedHostName() const
  31068. {
  31069. if (pipe != 0)
  31070. {
  31071. return "localhost";
  31072. }
  31073. else if (socket != 0)
  31074. {
  31075. if (! socket->isLocal())
  31076. return socket->getHostName();
  31077. return "localhost";
  31078. }
  31079. return String::empty;
  31080. }
  31081. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  31082. {
  31083. uint32 messageHeader[2];
  31084. messageHeader [0] = ByteOrder::swapIfBigEndian (magicMessageHeader);
  31085. messageHeader [1] = ByteOrder::swapIfBigEndian ((uint32) message.getSize());
  31086. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  31087. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  31088. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  31089. size_t bytesWritten = 0;
  31090. const ScopedLock sl (pipeAndSocketLock);
  31091. if (socket != 0)
  31092. {
  31093. bytesWritten = socket->write (messageData.getData(), (int) messageData.getSize());
  31094. }
  31095. else if (pipe != 0)
  31096. {
  31097. bytesWritten = pipe->write (messageData.getData(), (int) messageData.getSize());
  31098. }
  31099. if (bytesWritten < 0)
  31100. {
  31101. // error..
  31102. return false;
  31103. }
  31104. return (bytesWritten == messageData.getSize());
  31105. }
  31106. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  31107. {
  31108. jassert (socket == 0);
  31109. socket = socket_;
  31110. connectionMadeInt();
  31111. startThread();
  31112. }
  31113. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  31114. {
  31115. jassert (pipe == 0);
  31116. pipe = pipe_;
  31117. connectionMadeInt();
  31118. startThread();
  31119. }
  31120. const int messageMagicNumber = 0xb734128b;
  31121. void InterprocessConnection::handleMessage (const Message& message)
  31122. {
  31123. if (message.intParameter1 == messageMagicNumber)
  31124. {
  31125. switch (message.intParameter2)
  31126. {
  31127. case 0:
  31128. {
  31129. ScopedPointer <MemoryBlock> data (static_cast <MemoryBlock*> (message.pointerParameter));
  31130. messageReceived (*data);
  31131. break;
  31132. }
  31133. case 1:
  31134. connectionMade();
  31135. break;
  31136. case 2:
  31137. connectionLost();
  31138. break;
  31139. }
  31140. }
  31141. }
  31142. void InterprocessConnection::connectionMadeInt()
  31143. {
  31144. if (! callbackConnectionState)
  31145. {
  31146. callbackConnectionState = true;
  31147. if (useMessageThread)
  31148. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  31149. else
  31150. connectionMade();
  31151. }
  31152. }
  31153. void InterprocessConnection::connectionLostInt()
  31154. {
  31155. if (callbackConnectionState)
  31156. {
  31157. callbackConnectionState = false;
  31158. if (useMessageThread)
  31159. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  31160. else
  31161. connectionLost();
  31162. }
  31163. }
  31164. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  31165. {
  31166. jassert (callbackConnectionState);
  31167. if (useMessageThread)
  31168. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  31169. else
  31170. messageReceived (data);
  31171. }
  31172. bool InterprocessConnection::readNextMessageInt()
  31173. {
  31174. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  31175. uint32 messageHeader[2];
  31176. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader), true)
  31177. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  31178. if (bytes == sizeof (messageHeader)
  31179. && ByteOrder::swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  31180. {
  31181. int bytesInMessage = (int) ByteOrder::swapIfBigEndian (messageHeader[1]);
  31182. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  31183. {
  31184. MemoryBlock messageData (bytesInMessage, true);
  31185. int bytesRead = 0;
  31186. while (bytesInMessage > 0)
  31187. {
  31188. if (threadShouldExit())
  31189. return false;
  31190. const int numThisTime = jmin (bytesInMessage, 65536);
  31191. const int bytesIn = (socket != 0) ? socket->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, true)
  31192. : pipe->read (static_cast <char*> (messageData.getData()) + bytesRead, numThisTime, pipeReceiveMessageTimeout);
  31193. if (bytesIn <= 0)
  31194. break;
  31195. bytesRead += bytesIn;
  31196. bytesInMessage -= bytesIn;
  31197. }
  31198. if (bytesRead >= 0)
  31199. deliverDataInt (messageData);
  31200. }
  31201. }
  31202. else if (bytes < 0)
  31203. {
  31204. {
  31205. const ScopedLock sl (pipeAndSocketLock);
  31206. socket = 0;
  31207. }
  31208. connectionLostInt();
  31209. return false;
  31210. }
  31211. return true;
  31212. }
  31213. void InterprocessConnection::run()
  31214. {
  31215. while (! threadShouldExit())
  31216. {
  31217. if (socket != 0)
  31218. {
  31219. const int ready = socket->waitUntilReady (true, 0);
  31220. if (ready < 0)
  31221. {
  31222. {
  31223. const ScopedLock sl (pipeAndSocketLock);
  31224. socket = 0;
  31225. }
  31226. connectionLostInt();
  31227. break;
  31228. }
  31229. else if (ready > 0)
  31230. {
  31231. if (! readNextMessageInt())
  31232. break;
  31233. }
  31234. else
  31235. {
  31236. Thread::sleep (2);
  31237. }
  31238. }
  31239. else if (pipe != 0)
  31240. {
  31241. if (! pipe->isOpen())
  31242. {
  31243. {
  31244. const ScopedLock sl (pipeAndSocketLock);
  31245. pipe = 0;
  31246. }
  31247. connectionLostInt();
  31248. break;
  31249. }
  31250. else
  31251. {
  31252. if (! readNextMessageInt())
  31253. break;
  31254. }
  31255. }
  31256. else
  31257. {
  31258. break;
  31259. }
  31260. }
  31261. }
  31262. END_JUCE_NAMESPACE
  31263. /*** End of inlined file: juce_InterprocessConnection.cpp ***/
  31264. /*** Start of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31265. BEGIN_JUCE_NAMESPACE
  31266. InterprocessConnectionServer::InterprocessConnectionServer()
  31267. : Thread ("Juce IPC server")
  31268. {
  31269. }
  31270. InterprocessConnectionServer::~InterprocessConnectionServer()
  31271. {
  31272. stop();
  31273. }
  31274. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  31275. {
  31276. stop();
  31277. socket = new StreamingSocket();
  31278. if (socket->createListener (portNumber))
  31279. {
  31280. startThread();
  31281. return true;
  31282. }
  31283. socket = 0;
  31284. return false;
  31285. }
  31286. void InterprocessConnectionServer::stop()
  31287. {
  31288. signalThreadShouldExit();
  31289. if (socket != 0)
  31290. socket->close();
  31291. stopThread (4000);
  31292. socket = 0;
  31293. }
  31294. void InterprocessConnectionServer::run()
  31295. {
  31296. while ((! threadShouldExit()) && socket != 0)
  31297. {
  31298. ScopedPointer <StreamingSocket> clientSocket (socket->waitForNextConnection());
  31299. if (clientSocket != 0)
  31300. {
  31301. InterprocessConnection* newConnection = createConnectionObject();
  31302. if (newConnection != 0)
  31303. newConnection->initialiseWithSocket (clientSocket.release());
  31304. }
  31305. }
  31306. }
  31307. END_JUCE_NAMESPACE
  31308. /*** End of inlined file: juce_InterprocessConnectionServer.cpp ***/
  31309. /*** Start of inlined file: juce_Message.cpp ***/
  31310. BEGIN_JUCE_NAMESPACE
  31311. Message::Message() throw()
  31312. : intParameter1 (0),
  31313. intParameter2 (0),
  31314. intParameter3 (0),
  31315. pointerParameter (0)
  31316. {
  31317. }
  31318. Message::Message (const int intParameter1_,
  31319. const int intParameter2_,
  31320. const int intParameter3_,
  31321. void* const pointerParameter_) throw()
  31322. : intParameter1 (intParameter1_),
  31323. intParameter2 (intParameter2_),
  31324. intParameter3 (intParameter3_),
  31325. pointerParameter (pointerParameter_)
  31326. {
  31327. }
  31328. Message::~Message() throw()
  31329. {
  31330. }
  31331. END_JUCE_NAMESPACE
  31332. /*** End of inlined file: juce_Message.cpp ***/
  31333. /*** Start of inlined file: juce_MessageListener.cpp ***/
  31334. BEGIN_JUCE_NAMESPACE
  31335. MessageListener::MessageListener() throw()
  31336. {
  31337. // are you trying to create a messagelistener before or after juce has been intialised??
  31338. jassert (MessageManager::instance != 0);
  31339. if (MessageManager::instance != 0)
  31340. MessageManager::instance->messageListeners.add (this);
  31341. }
  31342. MessageListener::~MessageListener()
  31343. {
  31344. if (MessageManager::instance != 0)
  31345. MessageManager::instance->messageListeners.removeValue (this);
  31346. }
  31347. void MessageListener::postMessage (Message* const message) const throw()
  31348. {
  31349. message->messageRecipient = const_cast <MessageListener*> (this);
  31350. if (MessageManager::instance == 0)
  31351. MessageManager::getInstance();
  31352. MessageManager::instance->postMessageToQueue (message);
  31353. }
  31354. bool MessageListener::isValidMessageListener() const throw()
  31355. {
  31356. return (MessageManager::instance != 0)
  31357. && MessageManager::instance->messageListeners.contains (this);
  31358. }
  31359. END_JUCE_NAMESPACE
  31360. /*** End of inlined file: juce_MessageListener.cpp ***/
  31361. /*** Start of inlined file: juce_MessageManager.cpp ***/
  31362. BEGIN_JUCE_NAMESPACE
  31363. // platform-specific functions..
  31364. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  31365. bool juce_postMessageToSystemQueue (Message* message);
  31366. MessageManager* MessageManager::instance = 0;
  31367. static const int quitMessageId = 0xfffff321;
  31368. MessageManager::MessageManager() throw()
  31369. : quitMessagePosted (false),
  31370. quitMessageReceived (false),
  31371. threadWithLock (0)
  31372. {
  31373. messageThreadId = Thread::getCurrentThreadId();
  31374. }
  31375. MessageManager::~MessageManager() throw()
  31376. {
  31377. broadcastListeners = 0;
  31378. doPlatformSpecificShutdown();
  31379. // If you hit this assertion, then you've probably leaked a Component or some other
  31380. // kind of MessageListener object...
  31381. jassert (messageListeners.size() == 0);
  31382. jassert (instance == this);
  31383. instance = 0; // do this last in case this instance is still needed by doPlatformSpecificShutdown()
  31384. }
  31385. MessageManager* MessageManager::getInstance() throw()
  31386. {
  31387. if (instance == 0)
  31388. {
  31389. instance = new MessageManager();
  31390. doPlatformSpecificInitialisation();
  31391. }
  31392. return instance;
  31393. }
  31394. void MessageManager::postMessageToQueue (Message* const message)
  31395. {
  31396. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  31397. delete message;
  31398. }
  31399. CallbackMessage::CallbackMessage() throw() {}
  31400. CallbackMessage::~CallbackMessage() throw() {}
  31401. void CallbackMessage::post()
  31402. {
  31403. if (MessageManager::instance != 0)
  31404. MessageManager::instance->postCallbackMessage (this);
  31405. }
  31406. void MessageManager::postCallbackMessage (Message* const message)
  31407. {
  31408. message->messageRecipient = 0;
  31409. postMessageToQueue (message);
  31410. }
  31411. // not for public use..
  31412. void MessageManager::deliverMessage (Message* const message)
  31413. {
  31414. const ScopedPointer <Message> messageDeleter (message);
  31415. MessageListener* const recipient = message->messageRecipient;
  31416. JUCE_TRY
  31417. {
  31418. if (messageListeners.contains (recipient))
  31419. {
  31420. recipient->handleMessage (*message);
  31421. }
  31422. else if (recipient == 0)
  31423. {
  31424. if (message->intParameter1 == quitMessageId)
  31425. {
  31426. quitMessageReceived = true;
  31427. }
  31428. else
  31429. {
  31430. CallbackMessage* const cm = dynamic_cast <CallbackMessage*> (message);
  31431. if (cm != 0)
  31432. cm->messageCallback();
  31433. }
  31434. }
  31435. }
  31436. JUCE_CATCH_EXCEPTION
  31437. }
  31438. #if ! (JUCE_MAC || JUCE_IOS)
  31439. void MessageManager::runDispatchLoop()
  31440. {
  31441. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31442. runDispatchLoopUntil (-1);
  31443. }
  31444. void MessageManager::stopDispatchLoop()
  31445. {
  31446. Message* const m = new Message (quitMessageId, 0, 0, 0);
  31447. m->messageRecipient = 0;
  31448. postMessageToQueue (m);
  31449. quitMessagePosted = true;
  31450. }
  31451. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  31452. {
  31453. jassert (isThisTheMessageThread()); // must only be called by the message thread
  31454. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  31455. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  31456. && ! quitMessageReceived)
  31457. {
  31458. JUCE_TRY
  31459. {
  31460. if (! juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0))
  31461. {
  31462. const int msToWait = (int) (endTime - Time::currentTimeMillis());
  31463. if (msToWait > 0)
  31464. Thread::sleep (jmin (5, msToWait));
  31465. }
  31466. }
  31467. JUCE_CATCH_EXCEPTION
  31468. }
  31469. return ! quitMessageReceived;
  31470. }
  31471. #endif
  31472. void MessageManager::deliverBroadcastMessage (const String& value)
  31473. {
  31474. if (broadcastListeners != 0)
  31475. broadcastListeners->sendActionMessage (value);
  31476. }
  31477. void MessageManager::registerBroadcastListener (ActionListener* const listener)
  31478. {
  31479. if (broadcastListeners == 0)
  31480. broadcastListeners = new ActionListenerList();
  31481. broadcastListeners->addActionListener (listener);
  31482. }
  31483. void MessageManager::deregisterBroadcastListener (ActionListener* const listener)
  31484. {
  31485. if (broadcastListeners != 0)
  31486. broadcastListeners->removeActionListener (listener);
  31487. }
  31488. bool MessageManager::isThisTheMessageThread() const throw()
  31489. {
  31490. return Thread::getCurrentThreadId() == messageThreadId;
  31491. }
  31492. void MessageManager::setCurrentThreadAsMessageThread()
  31493. {
  31494. if (messageThreadId != Thread::getCurrentThreadId())
  31495. {
  31496. messageThreadId = Thread::getCurrentThreadId();
  31497. // This is needed on windows to make sure the message window is created by this thread
  31498. doPlatformSpecificShutdown();
  31499. doPlatformSpecificInitialisation();
  31500. }
  31501. }
  31502. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  31503. {
  31504. const Thread::ThreadID thisThread = Thread::getCurrentThreadId();
  31505. return thisThread == messageThreadId || thisThread == threadWithLock;
  31506. }
  31507. /* The only safe way to lock the message thread while another thread does
  31508. some work is by posting a special message, whose purpose is to tie up the event
  31509. loop until the other thread has finished its business.
  31510. Any other approach can get horribly deadlocked if the OS uses its own hidden locks which
  31511. get locked before making an event callback, because if the same OS lock gets indirectly
  31512. accessed from another thread inside a MM lock, you're screwed. (this is exactly what happens
  31513. in Cocoa).
  31514. */
  31515. class MessageManagerLock::SharedEvents : public ReferenceCountedObject
  31516. {
  31517. public:
  31518. SharedEvents() {}
  31519. ~SharedEvents() {}
  31520. /* This class just holds a couple of events to communicate between the BlockingMessage
  31521. and the MessageManagerLock. Because both of these objects may be deleted at any time,
  31522. this shared data must be kept in a separate, ref-counted container. */
  31523. WaitableEvent lockedEvent, releaseEvent;
  31524. private:
  31525. SharedEvents (const SharedEvents&);
  31526. SharedEvents& operator= (const SharedEvents&);
  31527. };
  31528. class MessageManagerLock::BlockingMessage : public CallbackMessage
  31529. {
  31530. public:
  31531. BlockingMessage (MessageManagerLock::SharedEvents* const events_) : events (events_) {}
  31532. ~BlockingMessage() throw() {}
  31533. void messageCallback()
  31534. {
  31535. events->lockedEvent.signal();
  31536. events->releaseEvent.wait();
  31537. }
  31538. juce_UseDebuggingNewOperator
  31539. private:
  31540. ReferenceCountedObjectPtr <MessageManagerLock::SharedEvents> events;
  31541. BlockingMessage (const BlockingMessage&);
  31542. BlockingMessage& operator= (const BlockingMessage&);
  31543. };
  31544. MessageManagerLock::MessageManagerLock (Thread* const threadToCheck)
  31545. : sharedEvents (0),
  31546. locked (false)
  31547. {
  31548. init (threadToCheck, 0);
  31549. }
  31550. MessageManagerLock::MessageManagerLock (ThreadPoolJob* const jobToCheckForExitSignal)
  31551. : sharedEvents (0),
  31552. locked (false)
  31553. {
  31554. init (0, jobToCheckForExitSignal);
  31555. }
  31556. void MessageManagerLock::init (Thread* const threadToCheck, ThreadPoolJob* const job)
  31557. {
  31558. if (MessageManager::instance != 0)
  31559. {
  31560. if (MessageManager::instance->currentThreadHasLockedMessageManager())
  31561. {
  31562. locked = true; // either we're on the message thread, or this is a re-entrant call.
  31563. }
  31564. else
  31565. {
  31566. if (threadToCheck == 0 && job == 0)
  31567. {
  31568. MessageManager::instance->lockingLock.enter();
  31569. }
  31570. else
  31571. {
  31572. while (! MessageManager::instance->lockingLock.tryEnter())
  31573. {
  31574. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31575. || (job != 0 && job->shouldExit()))
  31576. return;
  31577. Thread::sleep (1);
  31578. }
  31579. }
  31580. sharedEvents = new SharedEvents();
  31581. sharedEvents->incReferenceCount();
  31582. (new BlockingMessage (sharedEvents))->post();
  31583. while (! sharedEvents->lockedEvent.wait (50))
  31584. {
  31585. if ((threadToCheck != 0 && threadToCheck->threadShouldExit())
  31586. || (job != 0 && job->shouldExit()))
  31587. {
  31588. sharedEvents->releaseEvent.signal();
  31589. sharedEvents->decReferenceCount();
  31590. sharedEvents = 0;
  31591. MessageManager::instance->lockingLock.exit();
  31592. return;
  31593. }
  31594. }
  31595. jassert (MessageManager::instance->threadWithLock == 0);
  31596. MessageManager::instance->threadWithLock = Thread::getCurrentThreadId();
  31597. locked = true;
  31598. }
  31599. }
  31600. }
  31601. MessageManagerLock::~MessageManagerLock() throw()
  31602. {
  31603. if (sharedEvents != 0)
  31604. {
  31605. jassert (MessageManager::instance == 0 || MessageManager::instance->currentThreadHasLockedMessageManager());
  31606. sharedEvents->releaseEvent.signal();
  31607. sharedEvents->decReferenceCount();
  31608. if (MessageManager::instance != 0)
  31609. {
  31610. MessageManager::instance->threadWithLock = 0;
  31611. MessageManager::instance->lockingLock.exit();
  31612. }
  31613. }
  31614. }
  31615. END_JUCE_NAMESPACE
  31616. /*** End of inlined file: juce_MessageManager.cpp ***/
  31617. /*** Start of inlined file: juce_MultiTimer.cpp ***/
  31618. BEGIN_JUCE_NAMESPACE
  31619. class MultiTimer::MultiTimerCallback : public Timer
  31620. {
  31621. public:
  31622. MultiTimerCallback (const int timerId_, MultiTimer& owner_)
  31623. : timerId (timerId_),
  31624. owner (owner_)
  31625. {
  31626. }
  31627. ~MultiTimerCallback()
  31628. {
  31629. }
  31630. void timerCallback()
  31631. {
  31632. owner.timerCallback (timerId);
  31633. }
  31634. const int timerId;
  31635. private:
  31636. MultiTimer& owner;
  31637. };
  31638. MultiTimer::MultiTimer() throw()
  31639. {
  31640. }
  31641. MultiTimer::MultiTimer (const MultiTimer&) throw()
  31642. {
  31643. }
  31644. MultiTimer::~MultiTimer()
  31645. {
  31646. const ScopedLock sl (timerListLock);
  31647. timers.clear();
  31648. }
  31649. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  31650. {
  31651. const ScopedLock sl (timerListLock);
  31652. for (int i = timers.size(); --i >= 0;)
  31653. {
  31654. MultiTimerCallback* const t = timers.getUnchecked(i);
  31655. if (t->timerId == timerId)
  31656. {
  31657. t->startTimer (intervalInMilliseconds);
  31658. return;
  31659. }
  31660. }
  31661. MultiTimerCallback* const newTimer = new MultiTimerCallback (timerId, *this);
  31662. timers.add (newTimer);
  31663. newTimer->startTimer (intervalInMilliseconds);
  31664. }
  31665. void MultiTimer::stopTimer (const int timerId) throw()
  31666. {
  31667. const ScopedLock sl (timerListLock);
  31668. for (int i = timers.size(); --i >= 0;)
  31669. {
  31670. MultiTimerCallback* const t = timers.getUnchecked(i);
  31671. if (t->timerId == timerId)
  31672. t->stopTimer();
  31673. }
  31674. }
  31675. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  31676. {
  31677. const ScopedLock sl (timerListLock);
  31678. for (int i = timers.size(); --i >= 0;)
  31679. {
  31680. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31681. if (t->timerId == timerId)
  31682. return t->isTimerRunning();
  31683. }
  31684. return false;
  31685. }
  31686. int MultiTimer::getTimerInterval (const int timerId) const throw()
  31687. {
  31688. const ScopedLock sl (timerListLock);
  31689. for (int i = timers.size(); --i >= 0;)
  31690. {
  31691. const MultiTimerCallback* const t = timers.getUnchecked(i);
  31692. if (t->timerId == timerId)
  31693. return t->getTimerInterval();
  31694. }
  31695. return 0;
  31696. }
  31697. END_JUCE_NAMESPACE
  31698. /*** End of inlined file: juce_MultiTimer.cpp ***/
  31699. /*** Start of inlined file: juce_Timer.cpp ***/
  31700. BEGIN_JUCE_NAMESPACE
  31701. class InternalTimerThread : private Thread,
  31702. private MessageListener,
  31703. private DeletedAtShutdown,
  31704. private AsyncUpdater
  31705. {
  31706. public:
  31707. InternalTimerThread()
  31708. : Thread ("Juce Timer"),
  31709. firstTimer (0),
  31710. callbackNeeded (0)
  31711. {
  31712. triggerAsyncUpdate();
  31713. }
  31714. ~InternalTimerThread() throw()
  31715. {
  31716. stopThread (4000);
  31717. jassert (instance == this || instance == 0);
  31718. if (instance == this)
  31719. instance = 0;
  31720. }
  31721. void run()
  31722. {
  31723. uint32 lastTime = Time::getMillisecondCounter();
  31724. while (! threadShouldExit())
  31725. {
  31726. const uint32 now = Time::getMillisecondCounter();
  31727. if (now <= lastTime)
  31728. {
  31729. wait (2);
  31730. continue;
  31731. }
  31732. const int elapsed = now - lastTime;
  31733. lastTime = now;
  31734. int timeUntilFirstTimer = 1000;
  31735. {
  31736. const ScopedLock sl (lock);
  31737. decrementAllCounters (elapsed);
  31738. if (firstTimer != 0)
  31739. timeUntilFirstTimer = firstTimer->countdownMs;
  31740. }
  31741. if (timeUntilFirstTimer <= 0)
  31742. {
  31743. /* If we managed to set the atomic boolean to true then send a message, this is needed
  31744. as a memory barrier so the message won't be sent before callbackNeeded is set to true,
  31745. but if it fails it means the message-thread changed the value from under us so at least
  31746. some processing is happenening and we can just loop around and try again
  31747. */
  31748. if (callbackNeeded.compareAndSetBool (1, 0))
  31749. {
  31750. postMessage (new Message());
  31751. /* Sometimes our message can get discarded by the OS (e.g. when running as an RTAS
  31752. when the app has a modal loop), so this is how long to wait before assuming the
  31753. message has been lost and trying again.
  31754. */
  31755. const uint32 messageDeliveryTimeout = now + 2000;
  31756. while (callbackNeeded.get() != 0)
  31757. {
  31758. wait (4);
  31759. if (threadShouldExit())
  31760. return;
  31761. if (Time::getMillisecondCounter() > messageDeliveryTimeout)
  31762. break;
  31763. }
  31764. }
  31765. }
  31766. else
  31767. {
  31768. // don't wait for too long because running this loop also helps keep the
  31769. // Time::getApproximateMillisecondTimer value stay up-to-date
  31770. wait (jlimit (1, 50, timeUntilFirstTimer));
  31771. }
  31772. }
  31773. }
  31774. void callTimers()
  31775. {
  31776. const ScopedLock sl (lock);
  31777. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  31778. {
  31779. Timer* const t = firstTimer;
  31780. t->countdownMs = t->periodMs;
  31781. removeTimer (t);
  31782. addTimer (t);
  31783. const ScopedUnlock ul (lock);
  31784. JUCE_TRY
  31785. {
  31786. t->timerCallback();
  31787. }
  31788. JUCE_CATCH_EXCEPTION
  31789. }
  31790. /* This is needed as a memory barrier to make sure all processing of current timers is done
  31791. before the boolean is set. This set should never fail since if it was false in the first place,
  31792. we wouldn't get a message (so it can't be changed from false to true from under us), and if we
  31793. get a message then the value is true and the other thread can only set it to true again and
  31794. we will get another callback to set it to false.
  31795. */
  31796. callbackNeeded.set (0);
  31797. }
  31798. void handleMessage (const Message&)
  31799. {
  31800. callTimers();
  31801. }
  31802. void callTimersSynchronously()
  31803. {
  31804. if (! isThreadRunning())
  31805. {
  31806. // (This is relied on by some plugins in cases where the MM has
  31807. // had to restart and the async callback never started)
  31808. cancelPendingUpdate();
  31809. triggerAsyncUpdate();
  31810. }
  31811. callTimers();
  31812. }
  31813. static void callAnyTimersSynchronously()
  31814. {
  31815. if (InternalTimerThread::instance != 0)
  31816. InternalTimerThread::instance->callTimersSynchronously();
  31817. }
  31818. static inline void add (Timer* const tim) throw()
  31819. {
  31820. if (instance == 0)
  31821. instance = new InternalTimerThread();
  31822. const ScopedLock sl (instance->lock);
  31823. instance->addTimer (tim);
  31824. }
  31825. static inline void remove (Timer* const tim) throw()
  31826. {
  31827. if (instance != 0)
  31828. {
  31829. const ScopedLock sl (instance->lock);
  31830. instance->removeTimer (tim);
  31831. }
  31832. }
  31833. static inline void resetCounter (Timer* const tim,
  31834. const int newCounter) throw()
  31835. {
  31836. if (instance != 0)
  31837. {
  31838. tim->countdownMs = newCounter;
  31839. tim->periodMs = newCounter;
  31840. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  31841. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  31842. {
  31843. const ScopedLock sl (instance->lock);
  31844. instance->removeTimer (tim);
  31845. instance->addTimer (tim);
  31846. }
  31847. }
  31848. }
  31849. private:
  31850. friend class Timer;
  31851. static InternalTimerThread* instance;
  31852. static CriticalSection lock;
  31853. Timer* volatile firstTimer;
  31854. Atomic <int> callbackNeeded;
  31855. void addTimer (Timer* const t) throw()
  31856. {
  31857. #if JUCE_DEBUG
  31858. Timer* tt = firstTimer;
  31859. while (tt != 0)
  31860. {
  31861. // trying to add a timer that's already here - shouldn't get to this point,
  31862. // so if you get this assertion, let me know!
  31863. jassert (tt != t);
  31864. tt = tt->next;
  31865. }
  31866. jassert (t->previous == 0 && t->next == 0);
  31867. #endif
  31868. Timer* i = firstTimer;
  31869. if (i == 0 || i->countdownMs > t->countdownMs)
  31870. {
  31871. t->next = firstTimer;
  31872. firstTimer = t;
  31873. }
  31874. else
  31875. {
  31876. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  31877. i = i->next;
  31878. jassert (i != 0);
  31879. t->next = i->next;
  31880. t->previous = i;
  31881. i->next = t;
  31882. }
  31883. if (t->next != 0)
  31884. t->next->previous = t;
  31885. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  31886. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  31887. notify();
  31888. }
  31889. void removeTimer (Timer* const t) throw()
  31890. {
  31891. #if JUCE_DEBUG
  31892. Timer* tt = firstTimer;
  31893. bool found = false;
  31894. while (tt != 0)
  31895. {
  31896. if (tt == t)
  31897. {
  31898. found = true;
  31899. break;
  31900. }
  31901. tt = tt->next;
  31902. }
  31903. // trying to remove a timer that's not here - shouldn't get to this point,
  31904. // so if you get this assertion, let me know!
  31905. jassert (found);
  31906. #endif
  31907. if (t->previous != 0)
  31908. {
  31909. jassert (firstTimer != t);
  31910. t->previous->next = t->next;
  31911. }
  31912. else
  31913. {
  31914. jassert (firstTimer == t);
  31915. firstTimer = t->next;
  31916. }
  31917. if (t->next != 0)
  31918. t->next->previous = t->previous;
  31919. t->next = 0;
  31920. t->previous = 0;
  31921. }
  31922. void decrementAllCounters (const int numMillisecs) const
  31923. {
  31924. Timer* t = firstTimer;
  31925. while (t != 0)
  31926. {
  31927. t->countdownMs -= numMillisecs;
  31928. t = t->next;
  31929. }
  31930. }
  31931. void handleAsyncUpdate()
  31932. {
  31933. startThread (7);
  31934. }
  31935. InternalTimerThread (const InternalTimerThread&);
  31936. InternalTimerThread& operator= (const InternalTimerThread&);
  31937. };
  31938. InternalTimerThread* InternalTimerThread::instance = 0;
  31939. CriticalSection InternalTimerThread::lock;
  31940. void juce_callAnyTimersSynchronously()
  31941. {
  31942. InternalTimerThread::callAnyTimersSynchronously();
  31943. }
  31944. #if JUCE_DEBUG
  31945. static SortedSet <Timer*> activeTimers;
  31946. #endif
  31947. Timer::Timer() throw()
  31948. : countdownMs (0),
  31949. periodMs (0),
  31950. previous (0),
  31951. next (0)
  31952. {
  31953. #if JUCE_DEBUG
  31954. activeTimers.add (this);
  31955. #endif
  31956. }
  31957. Timer::Timer (const Timer&) throw()
  31958. : countdownMs (0),
  31959. periodMs (0),
  31960. previous (0),
  31961. next (0)
  31962. {
  31963. #if JUCE_DEBUG
  31964. activeTimers.add (this);
  31965. #endif
  31966. }
  31967. Timer::~Timer()
  31968. {
  31969. stopTimer();
  31970. #if JUCE_DEBUG
  31971. activeTimers.removeValue (this);
  31972. #endif
  31973. }
  31974. void Timer::startTimer (const int interval) throw()
  31975. {
  31976. const ScopedLock sl (InternalTimerThread::lock);
  31977. #if JUCE_DEBUG
  31978. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31979. jassert (activeTimers.contains (this));
  31980. #endif
  31981. if (periodMs == 0)
  31982. {
  31983. countdownMs = interval;
  31984. periodMs = jmax (1, interval);
  31985. InternalTimerThread::add (this);
  31986. }
  31987. else
  31988. {
  31989. InternalTimerThread::resetCounter (this, interval);
  31990. }
  31991. }
  31992. void Timer::stopTimer() throw()
  31993. {
  31994. const ScopedLock sl (InternalTimerThread::lock);
  31995. #if JUCE_DEBUG
  31996. // this isn't a valid object! Your timer might be a dangling pointer or something..
  31997. jassert (activeTimers.contains (this));
  31998. #endif
  31999. if (periodMs > 0)
  32000. {
  32001. InternalTimerThread::remove (this);
  32002. periodMs = 0;
  32003. }
  32004. }
  32005. END_JUCE_NAMESPACE
  32006. /*** End of inlined file: juce_Timer.cpp ***/
  32007. #endif
  32008. #if JUCE_BUILD_GUI
  32009. /*** Start of inlined file: juce_Component.cpp ***/
  32010. BEGIN_JUCE_NAMESPACE
  32011. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  32012. enum ComponentMessageNumbers
  32013. {
  32014. customCommandMessage = 0x7fff0001,
  32015. exitModalStateMessage = 0x7fff0002
  32016. };
  32017. static uint32 nextComponentUID = 0;
  32018. Component* Component::currentlyFocusedComponent = 0;
  32019. Component::Component()
  32020. : parentComponent_ (0),
  32021. componentUID (++nextComponentUID),
  32022. numDeepMouseListeners (0),
  32023. lookAndFeel_ (0),
  32024. effect_ (0),
  32025. bufferedImage_ (0),
  32026. mouseListeners_ (0),
  32027. keyListeners_ (0),
  32028. componentFlags_ (0),
  32029. componentTransparency (0)
  32030. {
  32031. }
  32032. Component::Component (const String& name)
  32033. : componentName_ (name),
  32034. parentComponent_ (0),
  32035. componentUID (++nextComponentUID),
  32036. numDeepMouseListeners (0),
  32037. lookAndFeel_ (0),
  32038. effect_ (0),
  32039. bufferedImage_ (0),
  32040. mouseListeners_ (0),
  32041. keyListeners_ (0),
  32042. componentFlags_ (0),
  32043. componentTransparency (0)
  32044. {
  32045. }
  32046. Component::~Component()
  32047. {
  32048. static_jassert (sizeof (flags) <= sizeof (componentFlags_));
  32049. componentListeners.call (&ComponentListener::componentBeingDeleted, *this);
  32050. if (parentComponent_ != 0)
  32051. {
  32052. parentComponent_->removeChildComponent (this);
  32053. }
  32054. else if ((currentlyFocusedComponent == this)
  32055. || isParentOf (currentlyFocusedComponent))
  32056. {
  32057. giveAwayFocus();
  32058. }
  32059. if (flags.hasHeavyweightPeerFlag)
  32060. removeFromDesktop();
  32061. for (int i = childComponentList_.size(); --i >= 0;)
  32062. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  32063. delete mouseListeners_;
  32064. delete keyListeners_;
  32065. }
  32066. void Component::setName (const String& name)
  32067. {
  32068. // if component methods are being called from threads other than the message
  32069. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32070. checkMessageManagerIsLocked
  32071. if (componentName_ != name)
  32072. {
  32073. componentName_ = name;
  32074. if (flags.hasHeavyweightPeerFlag)
  32075. {
  32076. ComponentPeer* const peer = getPeer();
  32077. jassert (peer != 0);
  32078. if (peer != 0)
  32079. peer->setTitle (name);
  32080. }
  32081. BailOutChecker checker (this);
  32082. componentListeners.callChecked (checker, &ComponentListener::componentNameChanged, *this);
  32083. }
  32084. }
  32085. void Component::setVisible (bool shouldBeVisible)
  32086. {
  32087. if (flags.visibleFlag != shouldBeVisible)
  32088. {
  32089. // if component methods are being called from threads other than the message
  32090. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32091. checkMessageManagerIsLocked
  32092. SafePointer<Component> safePointer (this);
  32093. flags.visibleFlag = shouldBeVisible;
  32094. internalRepaint (0, 0, getWidth(), getHeight());
  32095. sendFakeMouseMove();
  32096. if (! shouldBeVisible)
  32097. {
  32098. if (currentlyFocusedComponent == this
  32099. || isParentOf (currentlyFocusedComponent))
  32100. {
  32101. if (parentComponent_ != 0)
  32102. parentComponent_->grabKeyboardFocus();
  32103. else
  32104. giveAwayFocus();
  32105. }
  32106. }
  32107. if (safePointer != 0)
  32108. {
  32109. sendVisibilityChangeMessage();
  32110. if (safePointer != 0 && flags.hasHeavyweightPeerFlag)
  32111. {
  32112. ComponentPeer* const peer = getPeer();
  32113. jassert (peer != 0);
  32114. if (peer != 0)
  32115. {
  32116. peer->setVisible (shouldBeVisible);
  32117. internalHierarchyChanged();
  32118. }
  32119. }
  32120. }
  32121. }
  32122. }
  32123. void Component::visibilityChanged()
  32124. {
  32125. }
  32126. void Component::sendVisibilityChangeMessage()
  32127. {
  32128. BailOutChecker checker (this);
  32129. visibilityChanged();
  32130. if (! checker.shouldBailOut())
  32131. componentListeners.callChecked (checker, &ComponentListener::componentVisibilityChanged, *this);
  32132. }
  32133. bool Component::isShowing() const
  32134. {
  32135. if (flags.visibleFlag)
  32136. {
  32137. if (parentComponent_ != 0)
  32138. {
  32139. return parentComponent_->isShowing();
  32140. }
  32141. else
  32142. {
  32143. const ComponentPeer* const peer = getPeer();
  32144. return peer != 0 && ! peer->isMinimised();
  32145. }
  32146. }
  32147. return false;
  32148. }
  32149. bool Component::isValidComponent() const
  32150. {
  32151. return (this != 0) && isValidMessageListener();
  32152. }
  32153. void* Component::getWindowHandle() const
  32154. {
  32155. const ComponentPeer* const peer = getPeer();
  32156. if (peer != 0)
  32157. return peer->getNativeHandle();
  32158. return 0;
  32159. }
  32160. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  32161. {
  32162. // if component methods are being called from threads other than the message
  32163. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32164. checkMessageManagerIsLocked
  32165. if (isOpaque())
  32166. styleWanted &= ~ComponentPeer::windowIsSemiTransparent;
  32167. else
  32168. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  32169. int currentStyleFlags = 0;
  32170. // don't use getPeer(), so that we only get the peer that's specifically
  32171. // for this comp, and not for one of its parents.
  32172. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  32173. if (peer != 0)
  32174. currentStyleFlags = peer->getStyleFlags();
  32175. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  32176. {
  32177. SafePointer<Component> safePointer (this);
  32178. #if JUCE_LINUX
  32179. // it's wise to give the component a non-zero size before
  32180. // putting it on the desktop, as X windows get confused by this, and
  32181. // a (1, 1) minimum size is enforced here.
  32182. setSize (jmax (1, getWidth()),
  32183. jmax (1, getHeight()));
  32184. #endif
  32185. const Point<int> topLeft (relativePositionToGlobal (Point<int> (0, 0)));
  32186. bool wasFullscreen = false;
  32187. bool wasMinimised = false;
  32188. ComponentBoundsConstrainer* currentConstainer = 0;
  32189. Rectangle<int> oldNonFullScreenBounds;
  32190. if (peer != 0)
  32191. {
  32192. wasFullscreen = peer->isFullScreen();
  32193. wasMinimised = peer->isMinimised();
  32194. currentConstainer = peer->getConstrainer();
  32195. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  32196. removeFromDesktop();
  32197. setTopLeftPosition (topLeft.getX(), topLeft.getY());
  32198. }
  32199. if (parentComponent_ != 0)
  32200. parentComponent_->removeChildComponent (this);
  32201. if (safePointer != 0)
  32202. {
  32203. flags.hasHeavyweightPeerFlag = true;
  32204. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  32205. Desktop::getInstance().addDesktopComponent (this);
  32206. bounds_.setPosition (topLeft);
  32207. peer->setBounds (topLeft.getX(), topLeft.getY(), getWidth(), getHeight(), false);
  32208. peer->setVisible (isVisible());
  32209. if (wasFullscreen)
  32210. {
  32211. peer->setFullScreen (true);
  32212. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  32213. }
  32214. if (wasMinimised)
  32215. peer->setMinimised (true);
  32216. if (isAlwaysOnTop())
  32217. peer->setAlwaysOnTop (true);
  32218. peer->setConstrainer (currentConstainer);
  32219. repaint();
  32220. }
  32221. internalHierarchyChanged();
  32222. }
  32223. }
  32224. void Component::removeFromDesktop()
  32225. {
  32226. // if component methods are being called from threads other than the message
  32227. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32228. checkMessageManagerIsLocked
  32229. if (flags.hasHeavyweightPeerFlag)
  32230. {
  32231. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32232. flags.hasHeavyweightPeerFlag = false;
  32233. jassert (peer != 0);
  32234. delete peer;
  32235. Desktop::getInstance().removeDesktopComponent (this);
  32236. }
  32237. }
  32238. bool Component::isOnDesktop() const throw()
  32239. {
  32240. return flags.hasHeavyweightPeerFlag;
  32241. }
  32242. void Component::userTriedToCloseWindow()
  32243. {
  32244. /* This means that the user's trying to get rid of your window with the 'close window' system
  32245. menu option (on windows) or possibly the task manager - you should really handle this
  32246. and delete or hide your component in an appropriate way.
  32247. If you want to ignore the event and don't want to trigger this assertion, just override
  32248. this method and do nothing.
  32249. */
  32250. jassertfalse;
  32251. }
  32252. void Component::minimisationStateChanged (bool)
  32253. {
  32254. }
  32255. void Component::setOpaque (const bool shouldBeOpaque)
  32256. {
  32257. if (shouldBeOpaque != flags.opaqueFlag)
  32258. {
  32259. flags.opaqueFlag = shouldBeOpaque;
  32260. if (flags.hasHeavyweightPeerFlag)
  32261. {
  32262. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  32263. if (peer != 0)
  32264. {
  32265. // to make it recreate the heavyweight window
  32266. addToDesktop (peer->getStyleFlags());
  32267. }
  32268. }
  32269. repaint();
  32270. }
  32271. }
  32272. bool Component::isOpaque() const throw()
  32273. {
  32274. return flags.opaqueFlag;
  32275. }
  32276. void Component::setBufferedToImage (const bool shouldBeBuffered)
  32277. {
  32278. if (shouldBeBuffered != flags.bufferToImageFlag)
  32279. {
  32280. bufferedImage_ = Image::null;
  32281. flags.bufferToImageFlag = shouldBeBuffered;
  32282. }
  32283. }
  32284. void Component::toFront (const bool setAsForeground)
  32285. {
  32286. // if component methods are being called from threads other than the message
  32287. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32288. checkMessageManagerIsLocked
  32289. if (flags.hasHeavyweightPeerFlag)
  32290. {
  32291. ComponentPeer* const peer = getPeer();
  32292. if (peer != 0)
  32293. {
  32294. peer->toFront (setAsForeground);
  32295. if (setAsForeground && ! hasKeyboardFocus (true))
  32296. grabKeyboardFocus();
  32297. }
  32298. }
  32299. else if (parentComponent_ != 0)
  32300. {
  32301. Array<Component*>& childList = parentComponent_->childComponentList_;
  32302. if (childList.getLast() != this)
  32303. {
  32304. const int index = childList.indexOf (this);
  32305. if (index >= 0)
  32306. {
  32307. int insertIndex = -1;
  32308. if (! flags.alwaysOnTopFlag)
  32309. {
  32310. insertIndex = childList.size() - 1;
  32311. while (insertIndex > 0 && childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32312. --insertIndex;
  32313. }
  32314. if (index != insertIndex)
  32315. {
  32316. childList.move (index, insertIndex);
  32317. sendFakeMouseMove();
  32318. repaintParent();
  32319. }
  32320. }
  32321. }
  32322. if (setAsForeground)
  32323. {
  32324. internalBroughtToFront();
  32325. grabKeyboardFocus();
  32326. }
  32327. }
  32328. }
  32329. void Component::toBehind (Component* const other)
  32330. {
  32331. if (other != 0 && other != this)
  32332. {
  32333. // the two components must belong to the same parent..
  32334. jassert (parentComponent_ == other->parentComponent_);
  32335. if (parentComponent_ != 0)
  32336. {
  32337. Array<Component*>& childList = parentComponent_->childComponentList_;
  32338. const int index = childList.indexOf (this);
  32339. if (index >= 0 && childList [index + 1] != other)
  32340. {
  32341. int otherIndex = childList.indexOf (other);
  32342. if (otherIndex >= 0)
  32343. {
  32344. if (index < otherIndex)
  32345. --otherIndex;
  32346. childList.move (index, otherIndex);
  32347. sendFakeMouseMove();
  32348. repaintParent();
  32349. }
  32350. }
  32351. }
  32352. else if (isOnDesktop())
  32353. {
  32354. jassert (other->isOnDesktop());
  32355. if (other->isOnDesktop())
  32356. {
  32357. ComponentPeer* const us = getPeer();
  32358. ComponentPeer* const them = other->getPeer();
  32359. jassert (us != 0 && them != 0);
  32360. if (us != 0 && them != 0)
  32361. us->toBehind (them);
  32362. }
  32363. }
  32364. }
  32365. }
  32366. void Component::toBack()
  32367. {
  32368. Array<Component*>& childList = parentComponent_->childComponentList_;
  32369. if (isOnDesktop())
  32370. {
  32371. jassertfalse; //xxx need to add this to native window
  32372. }
  32373. else if (parentComponent_ != 0 && childList.getFirst() != this)
  32374. {
  32375. const int index = childList.indexOf (this);
  32376. if (index > 0)
  32377. {
  32378. int insertIndex = 0;
  32379. if (flags.alwaysOnTopFlag)
  32380. {
  32381. while (insertIndex < childList.size()
  32382. && ! childList.getUnchecked (insertIndex)->isAlwaysOnTop())
  32383. {
  32384. ++insertIndex;
  32385. }
  32386. }
  32387. if (index != insertIndex)
  32388. {
  32389. childList.move (index, insertIndex);
  32390. sendFakeMouseMove();
  32391. repaintParent();
  32392. }
  32393. }
  32394. }
  32395. }
  32396. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  32397. {
  32398. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  32399. {
  32400. flags.alwaysOnTopFlag = shouldStayOnTop;
  32401. if (isOnDesktop())
  32402. {
  32403. ComponentPeer* const peer = getPeer();
  32404. jassert (peer != 0);
  32405. if (peer != 0)
  32406. {
  32407. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  32408. {
  32409. // some kinds of peer can't change their always-on-top status, so
  32410. // for these, we'll need to create a new window
  32411. const int oldFlags = peer->getStyleFlags();
  32412. removeFromDesktop();
  32413. addToDesktop (oldFlags);
  32414. }
  32415. }
  32416. }
  32417. if (shouldStayOnTop)
  32418. toFront (false);
  32419. internalHierarchyChanged();
  32420. }
  32421. }
  32422. bool Component::isAlwaysOnTop() const throw()
  32423. {
  32424. return flags.alwaysOnTopFlag;
  32425. }
  32426. int Component::proportionOfWidth (const float proportion) const throw()
  32427. {
  32428. return roundToInt (proportion * bounds_.getWidth());
  32429. }
  32430. int Component::proportionOfHeight (const float proportion) const throw()
  32431. {
  32432. return roundToInt (proportion * bounds_.getHeight());
  32433. }
  32434. int Component::getParentWidth() const throw()
  32435. {
  32436. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  32437. : getParentMonitorArea().getWidth();
  32438. }
  32439. int Component::getParentHeight() const throw()
  32440. {
  32441. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  32442. : getParentMonitorArea().getHeight();
  32443. }
  32444. int Component::getScreenX() const
  32445. {
  32446. return getScreenPosition().getX();
  32447. }
  32448. int Component::getScreenY() const
  32449. {
  32450. return getScreenPosition().getY();
  32451. }
  32452. const Point<int> Component::getScreenPosition() const
  32453. {
  32454. return (parentComponent_ != 0) ? parentComponent_->getScreenPosition() + getPosition()
  32455. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenPosition()
  32456. : getPosition());
  32457. }
  32458. const Rectangle<int> Component::getScreenBounds() const
  32459. {
  32460. return bounds_.withPosition (getScreenPosition());
  32461. }
  32462. const Point<int> Component::relativePositionToGlobal (const Point<int>& relativePosition) const
  32463. {
  32464. const Component* c = this;
  32465. Point<int> p (relativePosition);
  32466. do
  32467. {
  32468. if (c->flags.hasHeavyweightPeerFlag)
  32469. return c->getPeer()->relativePositionToGlobal (p);
  32470. p += c->getPosition();
  32471. c = c->parentComponent_;
  32472. }
  32473. while (c != 0);
  32474. return p;
  32475. }
  32476. const Point<int> Component::globalPositionToRelative (const Point<int>& screenPosition) const
  32477. {
  32478. if (flags.hasHeavyweightPeerFlag)
  32479. {
  32480. return getPeer()->globalPositionToRelative (screenPosition);
  32481. }
  32482. else
  32483. {
  32484. if (parentComponent_ != 0)
  32485. return parentComponent_->globalPositionToRelative (screenPosition) - getPosition();
  32486. return screenPosition - getPosition();
  32487. }
  32488. }
  32489. const Point<int> Component::relativePositionToOtherComponent (const Component* const targetComponent, const Point<int>& positionRelativeToThis) const
  32490. {
  32491. Point<int> p (positionRelativeToThis);
  32492. if (targetComponent != 0)
  32493. {
  32494. const Component* c = this;
  32495. do
  32496. {
  32497. if (c == targetComponent)
  32498. return p;
  32499. if (c->flags.hasHeavyweightPeerFlag)
  32500. {
  32501. p = c->getPeer()->relativePositionToGlobal (p);
  32502. break;
  32503. }
  32504. p += c->getPosition();
  32505. c = c->parentComponent_;
  32506. }
  32507. while (c != 0);
  32508. p = targetComponent->globalPositionToRelative (p);
  32509. }
  32510. return p;
  32511. }
  32512. void Component::setBounds (const int x, const int y, int w, int h)
  32513. {
  32514. // if component methods are being called from threads other than the message
  32515. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32516. checkMessageManagerIsLocked
  32517. if (w < 0) w = 0;
  32518. if (h < 0) h = 0;
  32519. const bool wasResized = (getWidth() != w || getHeight() != h);
  32520. const bool wasMoved = (getX() != x || getY() != y);
  32521. #if JUCE_DEBUG
  32522. // It's a very bad idea to try to resize a window during its paint() method!
  32523. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  32524. #endif
  32525. if (wasMoved || wasResized)
  32526. {
  32527. if (flags.visibleFlag)
  32528. {
  32529. // send a fake mouse move to trigger enter/exit messages if needed..
  32530. sendFakeMouseMove();
  32531. if (! flags.hasHeavyweightPeerFlag)
  32532. repaintParent();
  32533. }
  32534. bounds_.setBounds (x, y, w, h);
  32535. if (wasResized)
  32536. repaint();
  32537. else if (! flags.hasHeavyweightPeerFlag)
  32538. repaintParent();
  32539. if (flags.hasHeavyweightPeerFlag)
  32540. {
  32541. ComponentPeer* const peer = getPeer();
  32542. if (peer != 0)
  32543. {
  32544. if (wasMoved && wasResized)
  32545. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  32546. else if (wasMoved)
  32547. peer->setPosition (getX(), getY());
  32548. else if (wasResized)
  32549. peer->setSize (getWidth(), getHeight());
  32550. }
  32551. }
  32552. sendMovedResizedMessages (wasMoved, wasResized);
  32553. }
  32554. }
  32555. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  32556. {
  32557. JUCE_TRY
  32558. {
  32559. if (wasMoved)
  32560. moved();
  32561. if (wasResized)
  32562. {
  32563. resized();
  32564. for (int i = childComponentList_.size(); --i >= 0;)
  32565. {
  32566. childComponentList_.getUnchecked(i)->parentSizeChanged();
  32567. i = jmin (i, childComponentList_.size());
  32568. }
  32569. }
  32570. BailOutChecker checker (this);
  32571. if (parentComponent_ != 0)
  32572. parentComponent_->childBoundsChanged (this);
  32573. if (! checker.shouldBailOut())
  32574. componentListeners.callChecked (checker, &ComponentListener::componentMovedOrResized,
  32575. *this, wasMoved, wasResized);
  32576. }
  32577. JUCE_CATCH_EXCEPTION
  32578. }
  32579. void Component::setSize (const int w, const int h)
  32580. {
  32581. setBounds (getX(), getY(), w, h);
  32582. }
  32583. void Component::setTopLeftPosition (const int x, const int y)
  32584. {
  32585. setBounds (x, y, getWidth(), getHeight());
  32586. }
  32587. void Component::setTopRightPosition (const int x, const int y)
  32588. {
  32589. setTopLeftPosition (x - getWidth(), y);
  32590. }
  32591. void Component::setBounds (const Rectangle<int>& r)
  32592. {
  32593. setBounds (r.getX(),
  32594. r.getY(),
  32595. r.getWidth(),
  32596. r.getHeight());
  32597. }
  32598. void Component::setBoundsRelative (const float x, const float y,
  32599. const float w, const float h)
  32600. {
  32601. const int pw = getParentWidth();
  32602. const int ph = getParentHeight();
  32603. setBounds (roundToInt (x * pw),
  32604. roundToInt (y * ph),
  32605. roundToInt (w * pw),
  32606. roundToInt (h * ph));
  32607. }
  32608. void Component::setCentrePosition (const int x, const int y)
  32609. {
  32610. setTopLeftPosition (x - getWidth() / 2,
  32611. y - getHeight() / 2);
  32612. }
  32613. void Component::setCentreRelative (const float x, const float y)
  32614. {
  32615. setCentrePosition (roundToInt (getParentWidth() * x),
  32616. roundToInt (getParentHeight() * y));
  32617. }
  32618. void Component::centreWithSize (const int width, const int height)
  32619. {
  32620. const Rectangle<int> parentArea (getParentOrMainMonitorBounds());
  32621. setBounds (parentArea.getCentreX() - width / 2,
  32622. parentArea.getCentreY() - height / 2,
  32623. width, height);
  32624. }
  32625. void Component::setBoundsInset (const BorderSize& borders)
  32626. {
  32627. setBounds (borders.subtractedFrom (getParentOrMainMonitorBounds()));
  32628. }
  32629. void Component::setBoundsToFit (int x, int y, int width, int height,
  32630. const Justification& justification,
  32631. const bool onlyReduceInSize)
  32632. {
  32633. // it's no good calling this method unless both the component and
  32634. // target rectangle have a finite size.
  32635. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  32636. if (getWidth() > 0 && getHeight() > 0
  32637. && width > 0 && height > 0)
  32638. {
  32639. int newW, newH;
  32640. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  32641. {
  32642. newW = getWidth();
  32643. newH = getHeight();
  32644. }
  32645. else
  32646. {
  32647. const double imageRatio = getHeight() / (double) getWidth();
  32648. const double targetRatio = height / (double) width;
  32649. if (imageRatio <= targetRatio)
  32650. {
  32651. newW = width;
  32652. newH = jmin (height, roundToInt (newW * imageRatio));
  32653. }
  32654. else
  32655. {
  32656. newH = height;
  32657. newW = jmin (width, roundToInt (newH / imageRatio));
  32658. }
  32659. }
  32660. if (newW > 0 && newH > 0)
  32661. {
  32662. int newX, newY;
  32663. justification.applyToRectangle (newX, newY, newW, newH,
  32664. x, y, width, height);
  32665. setBounds (newX, newY, newW, newH);
  32666. }
  32667. }
  32668. }
  32669. bool Component::hitTest (int x, int y)
  32670. {
  32671. if (! flags.ignoresMouseClicksFlag)
  32672. return true;
  32673. if (flags.allowChildMouseClicksFlag)
  32674. {
  32675. for (int i = getNumChildComponents(); --i >= 0;)
  32676. {
  32677. Component* const c = getChildComponent (i);
  32678. if (c->isVisible()
  32679. && c->bounds_.contains (x, y)
  32680. && c->hitTest (x - c->getX(),
  32681. y - c->getY()))
  32682. {
  32683. return true;
  32684. }
  32685. }
  32686. }
  32687. return false;
  32688. }
  32689. void Component::setInterceptsMouseClicks (const bool allowClicks,
  32690. const bool allowClicksOnChildComponents) throw()
  32691. {
  32692. flags.ignoresMouseClicksFlag = ! allowClicks;
  32693. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  32694. }
  32695. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  32696. bool& allowsClicksOnChildComponents) const throw()
  32697. {
  32698. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  32699. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  32700. }
  32701. bool Component::contains (const int x, const int y)
  32702. {
  32703. if (((unsigned int) x) < (unsigned int) getWidth()
  32704. && ((unsigned int) y) < (unsigned int) getHeight()
  32705. && hitTest (x, y))
  32706. {
  32707. if (parentComponent_ != 0)
  32708. {
  32709. return parentComponent_->contains (x + getX(),
  32710. y + getY());
  32711. }
  32712. else if (flags.hasHeavyweightPeerFlag)
  32713. {
  32714. const ComponentPeer* const peer = getPeer();
  32715. if (peer != 0)
  32716. return peer->contains (Point<int> (x, y), true);
  32717. }
  32718. }
  32719. return false;
  32720. }
  32721. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  32722. {
  32723. if (! contains (x, y))
  32724. return false;
  32725. Component* p = this;
  32726. while (p->parentComponent_ != 0)
  32727. {
  32728. x += p->getX();
  32729. y += p->getY();
  32730. p = p->parentComponent_;
  32731. }
  32732. const Component* const c = p->getComponentAt (x, y);
  32733. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  32734. }
  32735. Component* Component::getComponentAt (const Point<int>& position)
  32736. {
  32737. return getComponentAt (position.getX(), position.getY());
  32738. }
  32739. Component* Component::getComponentAt (const int x, const int y)
  32740. {
  32741. if (flags.visibleFlag
  32742. && ((unsigned int) x) < (unsigned int) getWidth()
  32743. && ((unsigned int) y) < (unsigned int) getHeight()
  32744. && hitTest (x, y))
  32745. {
  32746. for (int i = childComponentList_.size(); --i >= 0;)
  32747. {
  32748. Component* const child = childComponentList_.getUnchecked(i);
  32749. Component* const c = child->getComponentAt (x - child->getX(),
  32750. y - child->getY());
  32751. if (c != 0)
  32752. return c;
  32753. }
  32754. return this;
  32755. }
  32756. return 0;
  32757. }
  32758. void Component::addChildComponent (Component* const child, int zOrder)
  32759. {
  32760. // if component methods are being called from threads other than the message
  32761. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32762. checkMessageManagerIsLocked
  32763. if (child != 0 && child->parentComponent_ != this)
  32764. {
  32765. if (child->parentComponent_ != 0)
  32766. child->parentComponent_->removeChildComponent (child);
  32767. else
  32768. child->removeFromDesktop();
  32769. child->parentComponent_ = this;
  32770. if (child->isVisible())
  32771. child->repaintParent();
  32772. if (! child->isAlwaysOnTop())
  32773. {
  32774. if (zOrder < 0 || zOrder > childComponentList_.size())
  32775. zOrder = childComponentList_.size();
  32776. while (zOrder > 0)
  32777. {
  32778. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  32779. break;
  32780. --zOrder;
  32781. }
  32782. }
  32783. childComponentList_.insert (zOrder, child);
  32784. child->internalHierarchyChanged();
  32785. internalChildrenChanged();
  32786. }
  32787. }
  32788. void Component::addAndMakeVisible (Component* const child, int zOrder)
  32789. {
  32790. if (child != 0)
  32791. {
  32792. child->setVisible (true);
  32793. addChildComponent (child, zOrder);
  32794. }
  32795. }
  32796. void Component::removeChildComponent (Component* const child)
  32797. {
  32798. removeChildComponent (childComponentList_.indexOf (child));
  32799. }
  32800. Component* Component::removeChildComponent (const int index)
  32801. {
  32802. // if component methods are being called from threads other than the message
  32803. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32804. checkMessageManagerIsLocked
  32805. Component* const child = childComponentList_ [index];
  32806. if (child != 0)
  32807. {
  32808. sendFakeMouseMove();
  32809. child->repaintParent();
  32810. childComponentList_.remove (index);
  32811. child->parentComponent_ = 0;
  32812. JUCE_TRY
  32813. {
  32814. if ((currentlyFocusedComponent == child)
  32815. || child->isParentOf (currentlyFocusedComponent))
  32816. {
  32817. // get rid first to force the grabKeyboardFocus to change to us.
  32818. giveAwayFocus();
  32819. grabKeyboardFocus();
  32820. }
  32821. }
  32822. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  32823. catch (const std::exception& e)
  32824. {
  32825. currentlyFocusedComponent = 0;
  32826. Desktop::getInstance().triggerFocusCallback();
  32827. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  32828. }
  32829. catch (...)
  32830. {
  32831. currentlyFocusedComponent = 0;
  32832. Desktop::getInstance().triggerFocusCallback();
  32833. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  32834. }
  32835. #endif
  32836. child->internalHierarchyChanged();
  32837. internalChildrenChanged();
  32838. }
  32839. return child;
  32840. }
  32841. void Component::removeAllChildren()
  32842. {
  32843. while (childComponentList_.size() > 0)
  32844. removeChildComponent (childComponentList_.size() - 1);
  32845. }
  32846. void Component::deleteAllChildren()
  32847. {
  32848. while (childComponentList_.size() > 0)
  32849. delete (removeChildComponent (childComponentList_.size() - 1));
  32850. }
  32851. int Component::getNumChildComponents() const throw()
  32852. {
  32853. return childComponentList_.size();
  32854. }
  32855. Component* Component::getChildComponent (const int index) const throw()
  32856. {
  32857. return childComponentList_ [index];
  32858. }
  32859. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  32860. {
  32861. return childComponentList_.indexOf (const_cast <Component*> (child));
  32862. }
  32863. Component* Component::getTopLevelComponent() const throw()
  32864. {
  32865. const Component* comp = this;
  32866. while (comp->parentComponent_ != 0)
  32867. comp = comp->parentComponent_;
  32868. return const_cast <Component*> (comp);
  32869. }
  32870. bool Component::isParentOf (const Component* possibleChild) const throw()
  32871. {
  32872. if (! possibleChild->isValidComponent())
  32873. {
  32874. jassert (possibleChild == 0);
  32875. return false;
  32876. }
  32877. while (possibleChild != 0)
  32878. {
  32879. possibleChild = possibleChild->parentComponent_;
  32880. if (possibleChild == this)
  32881. return true;
  32882. }
  32883. return false;
  32884. }
  32885. void Component::parentHierarchyChanged()
  32886. {
  32887. }
  32888. void Component::childrenChanged()
  32889. {
  32890. }
  32891. void Component::internalChildrenChanged()
  32892. {
  32893. if (componentListeners.isEmpty())
  32894. {
  32895. childrenChanged();
  32896. }
  32897. else
  32898. {
  32899. BailOutChecker checker (this);
  32900. childrenChanged();
  32901. if (! checker.shouldBailOut())
  32902. componentListeners.callChecked (checker, &ComponentListener::componentChildrenChanged, *this);
  32903. }
  32904. }
  32905. void Component::internalHierarchyChanged()
  32906. {
  32907. BailOutChecker checker (this);
  32908. parentHierarchyChanged();
  32909. if (checker.shouldBailOut())
  32910. return;
  32911. componentListeners.callChecked (checker, &ComponentListener::componentParentHierarchyChanged, *this);
  32912. if (checker.shouldBailOut())
  32913. return;
  32914. for (int i = childComponentList_.size(); --i >= 0;)
  32915. {
  32916. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  32917. if (checker.shouldBailOut())
  32918. {
  32919. // you really shouldn't delete the parent component during a callback telling you
  32920. // that it's changed..
  32921. jassertfalse;
  32922. return;
  32923. }
  32924. i = jmin (i, childComponentList_.size());
  32925. }
  32926. }
  32927. void* Component::runModalLoopCallback (void* userData)
  32928. {
  32929. return (void*) (pointer_sized_int) static_cast <Component*> (userData)->runModalLoop();
  32930. }
  32931. int Component::runModalLoop()
  32932. {
  32933. if (! MessageManager::getInstance()->isThisTheMessageThread())
  32934. {
  32935. // use a callback so this can be called from non-gui threads
  32936. return (int) (pointer_sized_int) MessageManager::getInstance()
  32937. ->callFunctionOnMessageThread (&runModalLoopCallback, this);
  32938. }
  32939. if (! isCurrentlyModal())
  32940. enterModalState (true);
  32941. return ModalComponentManager::getInstance()->runEventLoopForCurrentComponent();
  32942. }
  32943. void Component::enterModalState (const bool takeKeyboardFocus_, ModalComponentManager::Callback* const callback)
  32944. {
  32945. // if component methods are being called from threads other than the message
  32946. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32947. checkMessageManagerIsLocked
  32948. // Check for an attempt to make a component modal when it already is!
  32949. // This can cause nasty problems..
  32950. jassert (! flags.currentlyModalFlag);
  32951. if (! isCurrentlyModal())
  32952. {
  32953. ModalComponentManager::getInstance()->startModal (this, callback);
  32954. flags.currentlyModalFlag = true;
  32955. setVisible (true);
  32956. if (takeKeyboardFocus_)
  32957. grabKeyboardFocus();
  32958. }
  32959. }
  32960. void Component::exitModalState (const int returnValue)
  32961. {
  32962. if (isCurrentlyModal())
  32963. {
  32964. if (MessageManager::getInstance()->isThisTheMessageThread())
  32965. {
  32966. ModalComponentManager::getInstance()->endModal (this, returnValue);
  32967. flags.currentlyModalFlag = false;
  32968. bringModalComponentToFront();
  32969. }
  32970. else
  32971. {
  32972. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  32973. }
  32974. }
  32975. }
  32976. bool Component::isCurrentlyModal() const throw()
  32977. {
  32978. return flags.currentlyModalFlag
  32979. && getCurrentlyModalComponent() == this;
  32980. }
  32981. bool Component::isCurrentlyBlockedByAnotherModalComponent() const
  32982. {
  32983. Component* const mc = getCurrentlyModalComponent();
  32984. return mc != 0
  32985. && mc != this
  32986. && (! mc->isParentOf (this))
  32987. && ! mc->canModalEventBeSentToComponent (this);
  32988. }
  32989. int JUCE_CALLTYPE Component::getNumCurrentlyModalComponents() throw()
  32990. {
  32991. return ModalComponentManager::getInstance()->getNumModalComponents();
  32992. }
  32993. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent (int index) throw()
  32994. {
  32995. return ModalComponentManager::getInstance()->getModalComponent (index);
  32996. }
  32997. void Component::bringModalComponentToFront()
  32998. {
  32999. ComponentPeer* lastOne = 0;
  33000. for (int i = 0; i < getNumCurrentlyModalComponents(); ++i)
  33001. {
  33002. Component* const c = getCurrentlyModalComponent (i);
  33003. if (c == 0)
  33004. break;
  33005. ComponentPeer* peer = c->getPeer();
  33006. if (peer != 0 && peer != lastOne)
  33007. {
  33008. if (lastOne == 0)
  33009. {
  33010. peer->toFront (true);
  33011. peer->grabFocus();
  33012. }
  33013. else
  33014. peer->toBehind (lastOne);
  33015. lastOne = peer;
  33016. }
  33017. }
  33018. }
  33019. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  33020. {
  33021. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  33022. }
  33023. bool Component::isBroughtToFrontOnMouseClick() const throw()
  33024. {
  33025. return flags.bringToFrontOnClickFlag;
  33026. }
  33027. void Component::setMouseCursor (const MouseCursor& cursor)
  33028. {
  33029. if (cursor_ != cursor)
  33030. {
  33031. cursor_ = cursor;
  33032. if (flags.visibleFlag)
  33033. updateMouseCursor();
  33034. }
  33035. }
  33036. const MouseCursor Component::getMouseCursor()
  33037. {
  33038. return cursor_;
  33039. }
  33040. void Component::updateMouseCursor() const
  33041. {
  33042. sendFakeMouseMove();
  33043. }
  33044. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  33045. {
  33046. flags.repaintOnMouseActivityFlag = shouldRepaint;
  33047. }
  33048. void Component::setAlpha (const float newAlpha)
  33049. {
  33050. const uint8 newIntAlpha = (uint8) (255 - jlimit (0, 255, roundToInt (newAlpha * 255.0)));
  33051. if (componentTransparency != newIntAlpha)
  33052. {
  33053. componentTransparency = newIntAlpha;
  33054. if (flags.hasHeavyweightPeerFlag)
  33055. {
  33056. ComponentPeer* const peer = getPeer();
  33057. if (peer != 0)
  33058. peer->setAlpha (newAlpha);
  33059. }
  33060. else
  33061. {
  33062. repaint();
  33063. }
  33064. }
  33065. }
  33066. float Component::getAlpha() const
  33067. {
  33068. return (255 - componentTransparency) / 255.0f;
  33069. }
  33070. void Component::repaintParent()
  33071. {
  33072. if (flags.visibleFlag)
  33073. internalRepaint (0, 0, getWidth(), getHeight());
  33074. }
  33075. void Component::repaint()
  33076. {
  33077. repaint (0, 0, getWidth(), getHeight());
  33078. }
  33079. void Component::repaint (const int x, const int y,
  33080. const int w, const int h)
  33081. {
  33082. bufferedImage_ = Image::null;
  33083. if (flags.visibleFlag)
  33084. internalRepaint (x, y, w, h);
  33085. }
  33086. void Component::repaint (const Rectangle<int>& area)
  33087. {
  33088. repaint (area.getX(), area.getY(), area.getWidth(), area.getHeight());
  33089. }
  33090. void Component::internalRepaint (int x, int y, int w, int h)
  33091. {
  33092. // if component methods are being called from threads other than the message
  33093. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33094. checkMessageManagerIsLocked
  33095. if (x < 0)
  33096. {
  33097. w += x;
  33098. x = 0;
  33099. }
  33100. if (x + w > getWidth())
  33101. w = getWidth() - x;
  33102. if (w > 0)
  33103. {
  33104. if (y < 0)
  33105. {
  33106. h += y;
  33107. y = 0;
  33108. }
  33109. if (y + h > getHeight())
  33110. h = getHeight() - y;
  33111. if (h > 0)
  33112. {
  33113. if (parentComponent_ != 0)
  33114. {
  33115. x += getX();
  33116. y += getY();
  33117. if (parentComponent_->flags.visibleFlag)
  33118. parentComponent_->internalRepaint (x, y, w, h);
  33119. }
  33120. else if (flags.hasHeavyweightPeerFlag)
  33121. {
  33122. ComponentPeer* const peer = getPeer();
  33123. if (peer != 0)
  33124. peer->repaint (Rectangle<int> (x, y, w, h));
  33125. }
  33126. }
  33127. }
  33128. }
  33129. void Component::renderComponent (Graphics& g)
  33130. {
  33131. const Rectangle<int> clipBounds (g.getClipBounds());
  33132. g.saveState();
  33133. clipObscuredRegions (g, clipBounds, 0, 0);
  33134. if (! g.isClipEmpty())
  33135. {
  33136. if (flags.bufferToImageFlag)
  33137. {
  33138. if (bufferedImage_.isNull())
  33139. {
  33140. bufferedImage_ = Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33141. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33142. Graphics imG (bufferedImage_);
  33143. paint (imG);
  33144. }
  33145. g.setColour (Colours::black.withAlpha (getAlpha()));
  33146. g.drawImageAt (bufferedImage_, 0, 0);
  33147. }
  33148. else
  33149. {
  33150. paint (g);
  33151. }
  33152. }
  33153. g.restoreState();
  33154. for (int i = 0; i < childComponentList_.size(); ++i)
  33155. {
  33156. Component* const child = childComponentList_.getUnchecked (i);
  33157. if (child->isVisible() && clipBounds.intersects (child->getBounds()))
  33158. {
  33159. g.saveState();
  33160. if (g.reduceClipRegion (child->getBounds()))
  33161. {
  33162. for (int j = i + 1; j < childComponentList_.size(); ++j)
  33163. {
  33164. const Component* const sibling = childComponentList_.getUnchecked (j);
  33165. if (sibling->flags.opaqueFlag && sibling->isVisible())
  33166. g.excludeClipRegion (sibling->getBounds());
  33167. }
  33168. if (! g.isClipEmpty())
  33169. {
  33170. g.setOrigin (child->getX(), child->getY());
  33171. child->paintEntireComponent (g, false);
  33172. }
  33173. }
  33174. g.restoreState();
  33175. }
  33176. }
  33177. g.saveState();
  33178. paintOverChildren (g);
  33179. g.restoreState();
  33180. }
  33181. void Component::paintEntireComponent (Graphics& g, bool ignoreAlphaLevel)
  33182. {
  33183. jassert (! g.isClipEmpty());
  33184. #if JUCE_DEBUG
  33185. flags.isInsidePaintCall = true;
  33186. #endif
  33187. if (effect_ != 0)
  33188. {
  33189. Image effectImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33190. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33191. {
  33192. Graphics g2 (effectImage);
  33193. renderComponent (g2);
  33194. }
  33195. effect_->applyEffect (effectImage, g, ignoreAlphaLevel ? 1.0f : getAlpha());
  33196. }
  33197. else
  33198. {
  33199. if (componentTransparency > 0 && ! ignoreAlphaLevel)
  33200. {
  33201. if (componentTransparency < 255)
  33202. {
  33203. Image temp (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33204. getWidth(), getHeight(), ! flags.opaqueFlag, Image::NativeImage);
  33205. {
  33206. Graphics tempG (temp);
  33207. tempG.reduceClipRegion (g.getClipBounds());
  33208. paintEntireComponent (tempG, true);
  33209. }
  33210. g.setColour (Colours::black.withAlpha (getAlpha()));
  33211. g.drawImageAt (temp, 0, 0);
  33212. }
  33213. }
  33214. else
  33215. {
  33216. renderComponent (g);
  33217. }
  33218. }
  33219. #if JUCE_DEBUG
  33220. flags.isInsidePaintCall = false;
  33221. #endif
  33222. }
  33223. const Image Component::createComponentSnapshot (const Rectangle<int>& areaToGrab,
  33224. const bool clipImageToComponentBounds)
  33225. {
  33226. Rectangle<int> r (areaToGrab);
  33227. if (clipImageToComponentBounds)
  33228. r = r.getIntersection (getLocalBounds());
  33229. Image componentImage (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  33230. jmax (1, r.getWidth()),
  33231. jmax (1, r.getHeight()),
  33232. true);
  33233. Graphics imageContext (componentImage);
  33234. imageContext.setOrigin (-r.getX(), -r.getY());
  33235. paintEntireComponent (imageContext, true);
  33236. return componentImage;
  33237. }
  33238. void Component::setComponentEffect (ImageEffectFilter* const effect)
  33239. {
  33240. if (effect_ != effect)
  33241. {
  33242. effect_ = effect;
  33243. repaint();
  33244. }
  33245. }
  33246. LookAndFeel& Component::getLookAndFeel() const throw()
  33247. {
  33248. const Component* c = this;
  33249. do
  33250. {
  33251. if (c->lookAndFeel_ != 0)
  33252. return *(c->lookAndFeel_);
  33253. c = c->parentComponent_;
  33254. }
  33255. while (c != 0);
  33256. return LookAndFeel::getDefaultLookAndFeel();
  33257. }
  33258. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  33259. {
  33260. if (lookAndFeel_ != newLookAndFeel)
  33261. {
  33262. lookAndFeel_ = newLookAndFeel;
  33263. sendLookAndFeelChange();
  33264. }
  33265. }
  33266. void Component::lookAndFeelChanged()
  33267. {
  33268. }
  33269. void Component::sendLookAndFeelChange()
  33270. {
  33271. repaint();
  33272. lookAndFeelChanged();
  33273. // (it's not a great idea to do anything that would delete this component
  33274. // during the lookAndFeelChanged() callback)
  33275. jassert (isValidComponent());
  33276. SafePointer<Component> safePointer (this);
  33277. for (int i = childComponentList_.size(); --i >= 0;)
  33278. {
  33279. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  33280. if (safePointer == 0)
  33281. return;
  33282. i = jmin (i, childComponentList_.size());
  33283. }
  33284. }
  33285. namespace ComponentHelpers
  33286. {
  33287. const Identifier getColourPropertyId (const int colourId)
  33288. {
  33289. String s;
  33290. s.preallocateStorage (18);
  33291. s << "jcclr_" << String::toHexString (colourId);
  33292. return s;
  33293. }
  33294. }
  33295. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const
  33296. {
  33297. var* const v = properties.getVarPointer (ComponentHelpers::getColourPropertyId (colourId));
  33298. if (v != 0)
  33299. return Colour ((int) *v);
  33300. if (inheritFromParent && parentComponent_ != 0)
  33301. return parentComponent_->findColour (colourId, true);
  33302. return getLookAndFeel().findColour (colourId);
  33303. }
  33304. bool Component::isColourSpecified (const int colourId) const
  33305. {
  33306. return properties.contains (ComponentHelpers::getColourPropertyId (colourId));
  33307. }
  33308. void Component::removeColour (const int colourId)
  33309. {
  33310. if (properties.remove (ComponentHelpers::getColourPropertyId (colourId)))
  33311. colourChanged();
  33312. }
  33313. void Component::setColour (const int colourId, const Colour& colour)
  33314. {
  33315. if (properties.set (ComponentHelpers::getColourPropertyId (colourId), (int) colour.getARGB()))
  33316. colourChanged();
  33317. }
  33318. void Component::copyAllExplicitColoursTo (Component& target) const
  33319. {
  33320. bool changed = false;
  33321. for (int i = properties.size(); --i >= 0;)
  33322. {
  33323. const Identifier name (properties.getName(i));
  33324. if (name.toString().startsWith ("jcclr_"))
  33325. if (target.properties.set (name, properties [name]))
  33326. changed = true;
  33327. }
  33328. if (changed)
  33329. target.colourChanged();
  33330. }
  33331. void Component::colourChanged()
  33332. {
  33333. }
  33334. const Rectangle<int> Component::getLocalBounds() const throw()
  33335. {
  33336. return Rectangle<int> (getWidth(), getHeight());
  33337. }
  33338. const Rectangle<int> Component::getParentOrMainMonitorBounds() const
  33339. {
  33340. return parentComponent_ != 0 ? parentComponent_->getLocalBounds()
  33341. : Desktop::getInstance().getMainMonitorArea();
  33342. }
  33343. const Rectangle<int> Component::getUnclippedArea() const
  33344. {
  33345. int x = 0, y = 0, w = getWidth(), h = getHeight();
  33346. Component* p = parentComponent_;
  33347. int px = getX();
  33348. int py = getY();
  33349. while (p != 0)
  33350. {
  33351. if (! Rectangle<int>::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  33352. return Rectangle<int>();
  33353. px += p->getX();
  33354. py += p->getY();
  33355. p = p->parentComponent_;
  33356. }
  33357. return Rectangle<int> (x, y, w, h);
  33358. }
  33359. void Component::clipObscuredRegions (Graphics& g, const Rectangle<int>& clipRect,
  33360. const int deltaX, const int deltaY) const
  33361. {
  33362. for (int i = childComponentList_.size(); --i >= 0;)
  33363. {
  33364. const Component* const c = childComponentList_.getUnchecked(i);
  33365. if (c->isVisible())
  33366. {
  33367. const Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33368. if (! newClip.isEmpty())
  33369. {
  33370. if (c->isOpaque())
  33371. {
  33372. g.excludeClipRegion (newClip.translated (deltaX, deltaY));
  33373. }
  33374. else
  33375. {
  33376. c->clipObscuredRegions (g, newClip.translated (-c->getX(), -c->getY()),
  33377. c->getX() + deltaX,
  33378. c->getY() + deltaY);
  33379. }
  33380. }
  33381. }
  33382. }
  33383. }
  33384. void Component::getVisibleArea (RectangleList& result, const bool includeSiblings) const
  33385. {
  33386. result.clear();
  33387. const Rectangle<int> unclipped (getUnclippedArea());
  33388. if (! unclipped.isEmpty())
  33389. {
  33390. result.add (unclipped);
  33391. if (includeSiblings)
  33392. {
  33393. const Component* const c = getTopLevelComponent();
  33394. c->subtractObscuredRegions (result, c->relativePositionToOtherComponent (this, Point<int>()),
  33395. c->getLocalBounds(), this);
  33396. }
  33397. subtractObscuredRegions (result, Point<int>(), unclipped, 0);
  33398. result.consolidate();
  33399. }
  33400. }
  33401. void Component::subtractObscuredRegions (RectangleList& result,
  33402. const Point<int>& delta,
  33403. const Rectangle<int>& clipRect,
  33404. const Component* const compToAvoid) const
  33405. {
  33406. for (int i = childComponentList_.size(); --i >= 0;)
  33407. {
  33408. const Component* const c = childComponentList_.getUnchecked(i);
  33409. if (c != compToAvoid && c->isVisible())
  33410. {
  33411. if (c->isOpaque())
  33412. {
  33413. Rectangle<int> childBounds (c->bounds_.getIntersection (clipRect));
  33414. childBounds.translate (delta.getX(), delta.getY());
  33415. result.subtract (childBounds);
  33416. }
  33417. else
  33418. {
  33419. Rectangle<int> newClip (clipRect.getIntersection (c->bounds_));
  33420. newClip.translate (-c->getX(), -c->getY());
  33421. c->subtractObscuredRegions (result, c->getPosition() + delta,
  33422. newClip, compToAvoid);
  33423. }
  33424. }
  33425. }
  33426. }
  33427. void Component::mouseEnter (const MouseEvent&)
  33428. {
  33429. // base class does nothing
  33430. }
  33431. void Component::mouseExit (const MouseEvent&)
  33432. {
  33433. // base class does nothing
  33434. }
  33435. void Component::mouseDown (const MouseEvent&)
  33436. {
  33437. // base class does nothing
  33438. }
  33439. void Component::mouseUp (const MouseEvent&)
  33440. {
  33441. // base class does nothing
  33442. }
  33443. void Component::mouseDrag (const MouseEvent&)
  33444. {
  33445. // base class does nothing
  33446. }
  33447. void Component::mouseMove (const MouseEvent&)
  33448. {
  33449. // base class does nothing
  33450. }
  33451. void Component::mouseDoubleClick (const MouseEvent&)
  33452. {
  33453. // base class does nothing
  33454. }
  33455. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  33456. {
  33457. // the base class just passes this event up to its parent..
  33458. if (parentComponent_ != 0)
  33459. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  33460. wheelIncrementX, wheelIncrementY);
  33461. }
  33462. void Component::resized()
  33463. {
  33464. // base class does nothing
  33465. }
  33466. void Component::moved()
  33467. {
  33468. // base class does nothing
  33469. }
  33470. void Component::childBoundsChanged (Component*)
  33471. {
  33472. // base class does nothing
  33473. }
  33474. void Component::parentSizeChanged()
  33475. {
  33476. // base class does nothing
  33477. }
  33478. void Component::addComponentListener (ComponentListener* const newListener)
  33479. {
  33480. jassert (isValidComponent());
  33481. componentListeners.add (newListener);
  33482. }
  33483. void Component::removeComponentListener (ComponentListener* const listenerToRemove)
  33484. {
  33485. jassert (isValidComponent());
  33486. componentListeners.remove (listenerToRemove);
  33487. }
  33488. void Component::inputAttemptWhenModal()
  33489. {
  33490. bringModalComponentToFront();
  33491. getLookAndFeel().playAlertSound();
  33492. }
  33493. bool Component::canModalEventBeSentToComponent (const Component*)
  33494. {
  33495. return false;
  33496. }
  33497. void Component::internalModalInputAttempt()
  33498. {
  33499. Component* const current = getCurrentlyModalComponent();
  33500. if (current != 0)
  33501. current->inputAttemptWhenModal();
  33502. }
  33503. void Component::paint (Graphics&)
  33504. {
  33505. // all painting is done in the subclasses
  33506. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  33507. }
  33508. void Component::paintOverChildren (Graphics&)
  33509. {
  33510. // all painting is done in the subclasses
  33511. }
  33512. void Component::handleMessage (const Message& message)
  33513. {
  33514. if (message.intParameter1 == exitModalStateMessage)
  33515. {
  33516. exitModalState (message.intParameter2);
  33517. }
  33518. else if (message.intParameter1 == customCommandMessage)
  33519. {
  33520. handleCommandMessage (message.intParameter2);
  33521. }
  33522. }
  33523. void Component::postCommandMessage (const int commandId)
  33524. {
  33525. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  33526. }
  33527. void Component::handleCommandMessage (int)
  33528. {
  33529. // used by subclasses
  33530. }
  33531. void Component::addMouseListener (MouseListener* const newListener,
  33532. const bool wantsEventsForAllNestedChildComponents)
  33533. {
  33534. // if component methods are being called from threads other than the message
  33535. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33536. checkMessageManagerIsLocked
  33537. // If you register a component as a mouselistener for itself, it'll receive all the events
  33538. // twice - once via the direct callback that all components get anyway, and then again as a listener!
  33539. jassert ((newListener != this) || wantsEventsForAllNestedChildComponents);
  33540. if (mouseListeners_ == 0)
  33541. mouseListeners_ = new Array<MouseListener*>();
  33542. if (! mouseListeners_->contains (newListener))
  33543. {
  33544. if (wantsEventsForAllNestedChildComponents)
  33545. {
  33546. mouseListeners_->insert (0, newListener);
  33547. ++numDeepMouseListeners;
  33548. }
  33549. else
  33550. {
  33551. mouseListeners_->add (newListener);
  33552. }
  33553. }
  33554. }
  33555. void Component::removeMouseListener (MouseListener* const listenerToRemove)
  33556. {
  33557. // if component methods are being called from threads other than the message
  33558. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  33559. checkMessageManagerIsLocked
  33560. if (mouseListeners_ != 0)
  33561. {
  33562. const int index = mouseListeners_->indexOf (listenerToRemove);
  33563. if (index >= 0)
  33564. {
  33565. if (index < numDeepMouseListeners)
  33566. --numDeepMouseListeners;
  33567. mouseListeners_->remove (index);
  33568. }
  33569. }
  33570. }
  33571. void Component::internalMouseEnter (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33572. {
  33573. if (isCurrentlyBlockedByAnotherModalComponent())
  33574. {
  33575. // if something else is modal, always just show a normal mouse cursor
  33576. source.showMouseCursor (MouseCursor::NormalCursor);
  33577. return;
  33578. }
  33579. if (! flags.mouseInsideFlag)
  33580. {
  33581. flags.mouseInsideFlag = true;
  33582. flags.mouseOverFlag = true;
  33583. flags.draggingFlag = false;
  33584. BailOutChecker checker (this);
  33585. if (flags.repaintOnMouseActivityFlag)
  33586. repaint();
  33587. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33588. this, this, time, relativePos,
  33589. time, 0, false);
  33590. mouseEnter (me);
  33591. if (checker.shouldBailOut())
  33592. return;
  33593. Desktop::getInstance().resetTimer();
  33594. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseEnter, me);
  33595. if (checker.shouldBailOut())
  33596. return;
  33597. if (mouseListeners_ != 0)
  33598. {
  33599. for (int i = mouseListeners_->size(); --i >= 0;)
  33600. {
  33601. mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33602. if (checker.shouldBailOut())
  33603. return;
  33604. i = jmin (i, mouseListeners_->size());
  33605. }
  33606. }
  33607. Component* p = parentComponent_;
  33608. while (p != 0)
  33609. {
  33610. if (p->numDeepMouseListeners > 0)
  33611. {
  33612. BailOutChecker checker2 (this, p);
  33613. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33614. {
  33615. p->mouseListeners_->getUnchecked(i)->mouseEnter (me);
  33616. if (checker2.shouldBailOut())
  33617. return;
  33618. i = jmin (i, p->numDeepMouseListeners);
  33619. }
  33620. }
  33621. p = p->parentComponent_;
  33622. }
  33623. }
  33624. }
  33625. void Component::internalMouseExit (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33626. {
  33627. BailOutChecker checker (this);
  33628. if (flags.draggingFlag)
  33629. {
  33630. internalMouseUp (source, relativePos, time, source.getCurrentModifiers().getRawFlags());
  33631. if (checker.shouldBailOut())
  33632. return;
  33633. }
  33634. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  33635. {
  33636. flags.mouseInsideFlag = false;
  33637. flags.mouseOverFlag = false;
  33638. flags.draggingFlag = false;
  33639. if (flags.repaintOnMouseActivityFlag)
  33640. repaint();
  33641. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33642. this, this, time, relativePos,
  33643. time, 0, false);
  33644. mouseExit (me);
  33645. if (checker.shouldBailOut())
  33646. return;
  33647. Desktop::getInstance().resetTimer();
  33648. Desktop::getInstance().mouseListeners.callChecked (checker, &MouseListener::mouseExit, me);
  33649. if (checker.shouldBailOut())
  33650. return;
  33651. if (mouseListeners_ != 0)
  33652. {
  33653. for (int i = mouseListeners_->size(); --i >= 0;)
  33654. {
  33655. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  33656. if (checker.shouldBailOut())
  33657. return;
  33658. i = jmin (i, mouseListeners_->size());
  33659. }
  33660. }
  33661. Component* p = parentComponent_;
  33662. while (p != 0)
  33663. {
  33664. if (p->numDeepMouseListeners > 0)
  33665. {
  33666. BailOutChecker checker2 (this, p);
  33667. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33668. {
  33669. p->mouseListeners_->getUnchecked (i)->mouseExit (me);
  33670. if (checker2.shouldBailOut())
  33671. return;
  33672. i = jmin (i, p->numDeepMouseListeners);
  33673. }
  33674. }
  33675. p = p->parentComponent_;
  33676. }
  33677. }
  33678. }
  33679. class InternalDragRepeater : public Timer
  33680. {
  33681. public:
  33682. InternalDragRepeater()
  33683. {}
  33684. ~InternalDragRepeater()
  33685. {
  33686. clearSingletonInstance();
  33687. }
  33688. juce_DeclareSingleton_SingleThreaded_Minimal (InternalDragRepeater)
  33689. void timerCallback()
  33690. {
  33691. Desktop& desktop = Desktop::getInstance();
  33692. int numMiceDown = 0;
  33693. for (int i = desktop.getNumMouseSources(); --i >= 0;)
  33694. {
  33695. MouseInputSource* const source = desktop.getMouseSource(i);
  33696. if (source->isDragging())
  33697. {
  33698. source->triggerFakeMove();
  33699. ++numMiceDown;
  33700. }
  33701. }
  33702. if (numMiceDown == 0)
  33703. deleteInstance();
  33704. }
  33705. juce_UseDebuggingNewOperator
  33706. private:
  33707. InternalDragRepeater (const InternalDragRepeater&);
  33708. InternalDragRepeater& operator= (const InternalDragRepeater&);
  33709. };
  33710. juce_ImplementSingleton_SingleThreaded (InternalDragRepeater)
  33711. void Component::beginDragAutoRepeat (const int interval)
  33712. {
  33713. if (interval > 0)
  33714. {
  33715. if (InternalDragRepeater::getInstance()->getTimerInterval() != interval)
  33716. InternalDragRepeater::getInstance()->startTimer (interval);
  33717. }
  33718. else
  33719. {
  33720. InternalDragRepeater::deleteInstance();
  33721. }
  33722. }
  33723. void Component::internalMouseDown (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33724. {
  33725. Desktop& desktop = Desktop::getInstance();
  33726. BailOutChecker checker (this);
  33727. if (isCurrentlyBlockedByAnotherModalComponent())
  33728. {
  33729. internalModalInputAttempt();
  33730. if (checker.shouldBailOut())
  33731. return;
  33732. // If processing the input attempt has exited the modal loop, we'll allow the event
  33733. // to be delivered..
  33734. if (isCurrentlyBlockedByAnotherModalComponent())
  33735. {
  33736. // allow blocked mouse-events to go to global listeners..
  33737. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33738. this, this, time, relativePos, time,
  33739. source.getNumberOfMultipleClicks(), false);
  33740. desktop.resetTimer();
  33741. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33742. return;
  33743. }
  33744. }
  33745. {
  33746. Component* c = this;
  33747. while (c != 0)
  33748. {
  33749. if (c->isBroughtToFrontOnMouseClick())
  33750. {
  33751. c->toFront (true);
  33752. if (checker.shouldBailOut())
  33753. return;
  33754. }
  33755. c = c->parentComponent_;
  33756. }
  33757. }
  33758. if (! flags.dontFocusOnMouseClickFlag)
  33759. {
  33760. grabFocusInternal (focusChangedByMouseClick);
  33761. if (checker.shouldBailOut())
  33762. return;
  33763. }
  33764. flags.draggingFlag = true;
  33765. flags.mouseOverFlag = true;
  33766. if (flags.repaintOnMouseActivityFlag)
  33767. repaint();
  33768. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33769. this, this, time, relativePos, time,
  33770. source.getNumberOfMultipleClicks(), false);
  33771. mouseDown (me);
  33772. if (checker.shouldBailOut())
  33773. return;
  33774. desktop.resetTimer();
  33775. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDown, me);
  33776. if (checker.shouldBailOut())
  33777. return;
  33778. if (mouseListeners_ != 0)
  33779. {
  33780. for (int i = mouseListeners_->size(); --i >= 0;)
  33781. {
  33782. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  33783. if (checker.shouldBailOut())
  33784. return;
  33785. i = jmin (i, mouseListeners_->size());
  33786. }
  33787. }
  33788. Component* p = parentComponent_;
  33789. while (p != 0)
  33790. {
  33791. if (p->numDeepMouseListeners > 0)
  33792. {
  33793. BailOutChecker checker2 (this, p);
  33794. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33795. {
  33796. p->mouseListeners_->getUnchecked (i)->mouseDown (me);
  33797. if (checker2.shouldBailOut())
  33798. return;
  33799. i = jmin (i, p->numDeepMouseListeners);
  33800. }
  33801. }
  33802. p = p->parentComponent_;
  33803. }
  33804. }
  33805. void Component::internalMouseUp (MouseInputSource& source, const Point<int>& relativePos, const Time& time, const ModifierKeys& oldModifiers)
  33806. {
  33807. if (flags.draggingFlag)
  33808. {
  33809. Desktop& desktop = Desktop::getInstance();
  33810. flags.draggingFlag = false;
  33811. BailOutChecker checker (this);
  33812. if (flags.repaintOnMouseActivityFlag)
  33813. repaint();
  33814. const MouseEvent me (source, relativePos,
  33815. oldModifiers, this, this, time,
  33816. globalPositionToRelative (source.getLastMouseDownPosition()),
  33817. source.getLastMouseDownTime(),
  33818. source.getNumberOfMultipleClicks(),
  33819. source.hasMouseMovedSignificantlySincePressed());
  33820. mouseUp (me);
  33821. if (checker.shouldBailOut())
  33822. return;
  33823. desktop.resetTimer();
  33824. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseUp, me);
  33825. if (checker.shouldBailOut())
  33826. return;
  33827. if (mouseListeners_ != 0)
  33828. {
  33829. for (int i = mouseListeners_->size(); --i >= 0;)
  33830. {
  33831. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  33832. if (checker.shouldBailOut())
  33833. return;
  33834. i = jmin (i, mouseListeners_->size());
  33835. }
  33836. }
  33837. {
  33838. Component* p = parentComponent_;
  33839. while (p != 0)
  33840. {
  33841. if (p->numDeepMouseListeners > 0)
  33842. {
  33843. BailOutChecker checker2 (this, p);
  33844. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33845. {
  33846. p->mouseListeners_->getUnchecked (i)->mouseUp (me);
  33847. if (checker2.shouldBailOut())
  33848. return;
  33849. i = jmin (i, p->numDeepMouseListeners);
  33850. }
  33851. }
  33852. p = p->parentComponent_;
  33853. }
  33854. }
  33855. // check for double-click
  33856. if (me.getNumberOfClicks() >= 2)
  33857. {
  33858. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  33859. mouseDoubleClick (me);
  33860. if (checker.shouldBailOut())
  33861. return;
  33862. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDoubleClick, me);
  33863. if (checker.shouldBailOut())
  33864. return;
  33865. for (int i = numListeners; --i >= 0;)
  33866. {
  33867. if (checker.shouldBailOut())
  33868. return;
  33869. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  33870. if (ml != 0)
  33871. ml->mouseDoubleClick (me);
  33872. }
  33873. if (checker.shouldBailOut())
  33874. return;
  33875. Component* p = parentComponent_;
  33876. while (p != 0)
  33877. {
  33878. if (p->numDeepMouseListeners > 0)
  33879. {
  33880. BailOutChecker checker2 (this, p);
  33881. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33882. {
  33883. p->mouseListeners_->getUnchecked (i)->mouseDoubleClick (me);
  33884. if (checker2.shouldBailOut())
  33885. return;
  33886. i = jmin (i, p->numDeepMouseListeners);
  33887. }
  33888. }
  33889. p = p->parentComponent_;
  33890. }
  33891. }
  33892. }
  33893. }
  33894. void Component::internalMouseDrag (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33895. {
  33896. if (flags.draggingFlag)
  33897. {
  33898. Desktop& desktop = Desktop::getInstance();
  33899. flags.mouseOverFlag = reallyContains (relativePos.getX(), relativePos.getY(), false);
  33900. BailOutChecker checker (this);
  33901. const MouseEvent me (source, relativePos,
  33902. source.getCurrentModifiers(), this, this, time,
  33903. globalPositionToRelative (source.getLastMouseDownPosition()),
  33904. source.getLastMouseDownTime(),
  33905. source.getNumberOfMultipleClicks(),
  33906. source.hasMouseMovedSignificantlySincePressed());
  33907. mouseDrag (me);
  33908. if (checker.shouldBailOut())
  33909. return;
  33910. desktop.resetTimer();
  33911. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  33912. if (checker.shouldBailOut())
  33913. return;
  33914. if (mouseListeners_ != 0)
  33915. {
  33916. for (int i = mouseListeners_->size(); --i >= 0;)
  33917. {
  33918. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  33919. if (checker.shouldBailOut())
  33920. return;
  33921. i = jmin (i, mouseListeners_->size());
  33922. }
  33923. }
  33924. Component* p = parentComponent_;
  33925. while (p != 0)
  33926. {
  33927. if (p->numDeepMouseListeners > 0)
  33928. {
  33929. BailOutChecker checker2 (this, p);
  33930. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33931. {
  33932. p->mouseListeners_->getUnchecked (i)->mouseDrag (me);
  33933. if (checker2.shouldBailOut())
  33934. return;
  33935. i = jmin (i, p->numDeepMouseListeners);
  33936. }
  33937. }
  33938. p = p->parentComponent_;
  33939. }
  33940. }
  33941. }
  33942. void Component::internalMouseMove (MouseInputSource& source, const Point<int>& relativePos, const Time& time)
  33943. {
  33944. Desktop& desktop = Desktop::getInstance();
  33945. BailOutChecker checker (this);
  33946. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  33947. this, this, time, relativePos,
  33948. time, 0, false);
  33949. if (isCurrentlyBlockedByAnotherModalComponent())
  33950. {
  33951. // allow blocked mouse-events to go to global listeners..
  33952. desktop.sendMouseMove();
  33953. }
  33954. else
  33955. {
  33956. flags.mouseOverFlag = true;
  33957. mouseMove (me);
  33958. if (checker.shouldBailOut())
  33959. return;
  33960. desktop.resetTimer();
  33961. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  33962. if (checker.shouldBailOut())
  33963. return;
  33964. if (mouseListeners_ != 0)
  33965. {
  33966. for (int i = mouseListeners_->size(); --i >= 0;)
  33967. {
  33968. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  33969. if (checker.shouldBailOut())
  33970. return;
  33971. i = jmin (i, mouseListeners_->size());
  33972. }
  33973. }
  33974. Component* p = parentComponent_;
  33975. while (p != 0)
  33976. {
  33977. if (p->numDeepMouseListeners > 0)
  33978. {
  33979. BailOutChecker checker2 (this, p);
  33980. for (int i = p->numDeepMouseListeners; --i >= 0;)
  33981. {
  33982. p->mouseListeners_->getUnchecked (i)->mouseMove (me);
  33983. if (checker2.shouldBailOut())
  33984. return;
  33985. i = jmin (i, p->numDeepMouseListeners);
  33986. }
  33987. }
  33988. p = p->parentComponent_;
  33989. }
  33990. }
  33991. }
  33992. void Component::internalMouseWheel (MouseInputSource& source, const Point<int>& relativePos,
  33993. const Time& time, const float amountX, const float amountY)
  33994. {
  33995. Desktop& desktop = Desktop::getInstance();
  33996. BailOutChecker checker (this);
  33997. const float wheelIncrementX = amountX / 256.0f;
  33998. const float wheelIncrementY = amountY / 256.0f;
  33999. const MouseEvent me (source, relativePos, source.getCurrentModifiers(),
  34000. this, this, time, relativePos, time, 0, false);
  34001. if (isCurrentlyBlockedByAnotherModalComponent())
  34002. {
  34003. // allow blocked mouse-events to go to global listeners..
  34004. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  34005. }
  34006. else
  34007. {
  34008. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34009. if (checker.shouldBailOut())
  34010. return;
  34011. desktop.mouseListeners.callChecked (checker, &MouseListener::mouseWheelMove, me, wheelIncrementX, wheelIncrementY);
  34012. if (checker.shouldBailOut())
  34013. return;
  34014. if (mouseListeners_ != 0)
  34015. {
  34016. for (int i = mouseListeners_->size(); --i >= 0;)
  34017. {
  34018. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34019. if (checker.shouldBailOut())
  34020. return;
  34021. i = jmin (i, mouseListeners_->size());
  34022. }
  34023. }
  34024. Component* p = parentComponent_;
  34025. while (p != 0)
  34026. {
  34027. if (p->numDeepMouseListeners > 0)
  34028. {
  34029. BailOutChecker checker2 (this, p);
  34030. for (int i = p->numDeepMouseListeners; --i >= 0;)
  34031. {
  34032. p->mouseListeners_->getUnchecked (i)->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  34033. if (checker2.shouldBailOut())
  34034. return;
  34035. i = jmin (i, p->numDeepMouseListeners);
  34036. }
  34037. }
  34038. p = p->parentComponent_;
  34039. }
  34040. }
  34041. }
  34042. void Component::sendFakeMouseMove() const
  34043. {
  34044. Desktop::getInstance().getMainMouseSource().triggerFakeMove();
  34045. }
  34046. void Component::broughtToFront()
  34047. {
  34048. }
  34049. void Component::internalBroughtToFront()
  34050. {
  34051. if (! isValidComponent())
  34052. return;
  34053. if (flags.hasHeavyweightPeerFlag)
  34054. Desktop::getInstance().componentBroughtToFront (this);
  34055. BailOutChecker checker (this);
  34056. broughtToFront();
  34057. if (checker.shouldBailOut())
  34058. return;
  34059. componentListeners.callChecked (checker, &ComponentListener::componentBroughtToFront, *this);
  34060. if (checker.shouldBailOut())
  34061. return;
  34062. // When brought to the front and there's a modal component blocking this one,
  34063. // we need to bring the modal one to the front instead..
  34064. Component* const cm = getCurrentlyModalComponent();
  34065. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  34066. bringModalComponentToFront();
  34067. }
  34068. void Component::focusGained (FocusChangeType)
  34069. {
  34070. // base class does nothing
  34071. }
  34072. void Component::internalFocusGain (const FocusChangeType cause)
  34073. {
  34074. SafePointer<Component> safePointer (this);
  34075. focusGained (cause);
  34076. if (safePointer != 0)
  34077. internalChildFocusChange (cause);
  34078. }
  34079. void Component::focusLost (FocusChangeType)
  34080. {
  34081. // base class does nothing
  34082. }
  34083. void Component::internalFocusLoss (const FocusChangeType cause)
  34084. {
  34085. SafePointer<Component> safePointer (this);
  34086. focusLost (focusChangedDirectly);
  34087. if (safePointer != 0)
  34088. internalChildFocusChange (cause);
  34089. }
  34090. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  34091. {
  34092. // base class does nothing
  34093. }
  34094. void Component::internalChildFocusChange (FocusChangeType cause)
  34095. {
  34096. const bool childIsNowFocused = hasKeyboardFocus (true);
  34097. if (flags.childCompFocusedFlag != childIsNowFocused)
  34098. {
  34099. flags.childCompFocusedFlag = childIsNowFocused;
  34100. SafePointer<Component> safePointer (this);
  34101. focusOfChildComponentChanged (cause);
  34102. if (safePointer == 0)
  34103. return;
  34104. }
  34105. if (parentComponent_ != 0)
  34106. parentComponent_->internalChildFocusChange (cause);
  34107. }
  34108. bool Component::isEnabled() const throw()
  34109. {
  34110. return (! flags.isDisabledFlag)
  34111. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  34112. }
  34113. void Component::setEnabled (const bool shouldBeEnabled)
  34114. {
  34115. if (flags.isDisabledFlag == shouldBeEnabled)
  34116. {
  34117. flags.isDisabledFlag = ! shouldBeEnabled;
  34118. // if any parent components are disabled, setting our flag won't make a difference,
  34119. // so no need to send a change message
  34120. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  34121. sendEnablementChangeMessage();
  34122. }
  34123. }
  34124. void Component::sendEnablementChangeMessage()
  34125. {
  34126. SafePointer<Component> safePointer (this);
  34127. enablementChanged();
  34128. if (safePointer == 0)
  34129. return;
  34130. for (int i = getNumChildComponents(); --i >= 0;)
  34131. {
  34132. Component* const c = getChildComponent (i);
  34133. if (c != 0)
  34134. {
  34135. c->sendEnablementChangeMessage();
  34136. if (safePointer == 0)
  34137. return;
  34138. }
  34139. }
  34140. }
  34141. void Component::enablementChanged()
  34142. {
  34143. }
  34144. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  34145. {
  34146. flags.wantsFocusFlag = wantsFocus;
  34147. }
  34148. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  34149. {
  34150. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  34151. }
  34152. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  34153. {
  34154. return ! flags.dontFocusOnMouseClickFlag;
  34155. }
  34156. bool Component::getWantsKeyboardFocus() const throw()
  34157. {
  34158. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  34159. }
  34160. void Component::setFocusContainer (const bool shouldBeFocusContainer) throw()
  34161. {
  34162. flags.isFocusContainerFlag = shouldBeFocusContainer;
  34163. }
  34164. bool Component::isFocusContainer() const throw()
  34165. {
  34166. return flags.isFocusContainerFlag;
  34167. }
  34168. static const Identifier juce_explicitFocusOrderId ("_jexfo");
  34169. int Component::getExplicitFocusOrder() const
  34170. {
  34171. return properties [juce_explicitFocusOrderId];
  34172. }
  34173. void Component::setExplicitFocusOrder (const int newFocusOrderIndex)
  34174. {
  34175. properties.set (juce_explicitFocusOrderId, newFocusOrderIndex);
  34176. }
  34177. KeyboardFocusTraverser* Component::createFocusTraverser()
  34178. {
  34179. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  34180. return new KeyboardFocusTraverser();
  34181. return parentComponent_->createFocusTraverser();
  34182. }
  34183. void Component::takeKeyboardFocus (const FocusChangeType cause)
  34184. {
  34185. // give the focus to this component
  34186. if (currentlyFocusedComponent != this)
  34187. {
  34188. JUCE_TRY
  34189. {
  34190. // get the focus onto our desktop window
  34191. ComponentPeer* const peer = getPeer();
  34192. if (peer != 0)
  34193. {
  34194. SafePointer<Component> safePointer (this);
  34195. peer->grabFocus();
  34196. if (peer->isFocused() && currentlyFocusedComponent != this)
  34197. {
  34198. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34199. currentlyFocusedComponent = this;
  34200. Desktop::getInstance().triggerFocusCallback();
  34201. // call this after setting currentlyFocusedComponent so that the one that's
  34202. // losing it has a chance to see where focus is going
  34203. if (componentLosingFocus != 0)
  34204. componentLosingFocus->internalFocusLoss (cause);
  34205. if (currentlyFocusedComponent == this)
  34206. {
  34207. focusGained (cause);
  34208. if (safePointer != 0)
  34209. internalChildFocusChange (cause);
  34210. }
  34211. }
  34212. }
  34213. }
  34214. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  34215. catch (const std::exception& e)
  34216. {
  34217. currentlyFocusedComponent = 0;
  34218. Desktop::getInstance().triggerFocusCallback();
  34219. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  34220. }
  34221. catch (...)
  34222. {
  34223. currentlyFocusedComponent = 0;
  34224. Desktop::getInstance().triggerFocusCallback();
  34225. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  34226. }
  34227. #endif
  34228. }
  34229. }
  34230. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  34231. {
  34232. if (isShowing())
  34233. {
  34234. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  34235. {
  34236. takeKeyboardFocus (cause);
  34237. }
  34238. else
  34239. {
  34240. if (isParentOf (currentlyFocusedComponent)
  34241. && currentlyFocusedComponent->isShowing())
  34242. {
  34243. // do nothing if the focused component is actually a child of ours..
  34244. }
  34245. else
  34246. {
  34247. // find the default child component..
  34248. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34249. if (traverser != 0)
  34250. {
  34251. Component* const defaultComp = traverser->getDefaultComponent (this);
  34252. traverser = 0;
  34253. if (defaultComp != 0)
  34254. {
  34255. defaultComp->grabFocusInternal (cause, false);
  34256. return;
  34257. }
  34258. }
  34259. if (canTryParent && parentComponent_ != 0)
  34260. {
  34261. // if no children want it and we're allowed to try our parent comp,
  34262. // then pass up to parent, which will try our siblings.
  34263. parentComponent_->grabFocusInternal (cause, true);
  34264. }
  34265. }
  34266. }
  34267. }
  34268. }
  34269. void Component::grabKeyboardFocus()
  34270. {
  34271. // if component methods are being called from threads other than the message
  34272. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34273. checkMessageManagerIsLocked
  34274. grabFocusInternal (focusChangedDirectly);
  34275. }
  34276. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  34277. {
  34278. // if component methods are being called from threads other than the message
  34279. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  34280. checkMessageManagerIsLocked
  34281. if (parentComponent_ != 0)
  34282. {
  34283. ScopedPointer <KeyboardFocusTraverser> traverser (createFocusTraverser());
  34284. if (traverser != 0)
  34285. {
  34286. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  34287. : traverser->getPreviousComponent (this);
  34288. traverser = 0;
  34289. if (nextComp != 0)
  34290. {
  34291. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34292. {
  34293. SafePointer<Component> nextCompPointer (nextComp);
  34294. internalModalInputAttempt();
  34295. if (nextCompPointer == 0 || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  34296. return;
  34297. }
  34298. nextComp->grabFocusInternal (focusChangedByTabKey);
  34299. return;
  34300. }
  34301. }
  34302. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  34303. }
  34304. }
  34305. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const
  34306. {
  34307. return (currentlyFocusedComponent == this)
  34308. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  34309. }
  34310. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  34311. {
  34312. return currentlyFocusedComponent;
  34313. }
  34314. void Component::giveAwayFocus()
  34315. {
  34316. // use a copy so we can clear the value before the call
  34317. SafePointer<Component> componentLosingFocus (currentlyFocusedComponent);
  34318. currentlyFocusedComponent = 0;
  34319. Desktop::getInstance().triggerFocusCallback();
  34320. if (componentLosingFocus != 0)
  34321. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  34322. }
  34323. bool Component::isMouseOver() const throw()
  34324. {
  34325. return flags.mouseOverFlag;
  34326. }
  34327. bool Component::isMouseButtonDown() const throw()
  34328. {
  34329. return flags.draggingFlag;
  34330. }
  34331. bool Component::isMouseOverOrDragging() const throw()
  34332. {
  34333. return flags.mouseOverFlag || flags.draggingFlag;
  34334. }
  34335. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  34336. {
  34337. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  34338. }
  34339. const Point<int> Component::getMouseXYRelative() const
  34340. {
  34341. return globalPositionToRelative (Desktop::getMousePosition());
  34342. }
  34343. const Rectangle<int> Component::getParentMonitorArea() const
  34344. {
  34345. return Desktop::getInstance()
  34346. .getMonitorAreaContaining (relativePositionToGlobal (getLocalBounds().getCentre()));
  34347. }
  34348. void Component::addKeyListener (KeyListener* const newListener)
  34349. {
  34350. if (keyListeners_ == 0)
  34351. keyListeners_ = new Array <KeyListener*>();
  34352. keyListeners_->addIfNotAlreadyThere (newListener);
  34353. }
  34354. void Component::removeKeyListener (KeyListener* const listenerToRemove)
  34355. {
  34356. if (keyListeners_ != 0)
  34357. keyListeners_->removeValue (listenerToRemove);
  34358. }
  34359. bool Component::keyPressed (const KeyPress&)
  34360. {
  34361. return false;
  34362. }
  34363. bool Component::keyStateChanged (const bool /*isKeyDown*/)
  34364. {
  34365. return false;
  34366. }
  34367. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  34368. {
  34369. if (parentComponent_ != 0)
  34370. parentComponent_->modifierKeysChanged (modifiers);
  34371. }
  34372. void Component::internalModifierKeysChanged()
  34373. {
  34374. sendFakeMouseMove();
  34375. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  34376. }
  34377. ComponentPeer* Component::getPeer() const
  34378. {
  34379. if (flags.hasHeavyweightPeerFlag)
  34380. return ComponentPeer::getPeerFor (this);
  34381. else if (parentComponent_ != 0)
  34382. return parentComponent_->getPeer();
  34383. else
  34384. return 0;
  34385. }
  34386. Component::BailOutChecker::BailOutChecker (Component* const component1, Component* const component2_)
  34387. : safePointer1 (component1), safePointer2 (component2_), component2 (component2_)
  34388. {
  34389. jassert (component1 != 0);
  34390. }
  34391. bool Component::BailOutChecker::shouldBailOut() const throw()
  34392. {
  34393. return safePointer1 == 0 || safePointer2.getComponent() != component2;
  34394. }
  34395. END_JUCE_NAMESPACE
  34396. /*** End of inlined file: juce_Component.cpp ***/
  34397. /*** Start of inlined file: juce_ComponentListener.cpp ***/
  34398. BEGIN_JUCE_NAMESPACE
  34399. void ComponentListener::componentMovedOrResized (Component&, bool, bool) {}
  34400. void ComponentListener::componentBroughtToFront (Component&) {}
  34401. void ComponentListener::componentVisibilityChanged (Component&) {}
  34402. void ComponentListener::componentChildrenChanged (Component&) {}
  34403. void ComponentListener::componentParentHierarchyChanged (Component&) {}
  34404. void ComponentListener::componentNameChanged (Component&) {}
  34405. void ComponentListener::componentBeingDeleted (Component&) {}
  34406. END_JUCE_NAMESPACE
  34407. /*** End of inlined file: juce_ComponentListener.cpp ***/
  34408. /*** Start of inlined file: juce_Desktop.cpp ***/
  34409. BEGIN_JUCE_NAMESPACE
  34410. Desktop::Desktop()
  34411. : mouseClickCounter (0),
  34412. kioskModeComponent (0),
  34413. allowedOrientations (allOrientations)
  34414. {
  34415. createMouseInputSources();
  34416. refreshMonitorSizes();
  34417. }
  34418. Desktop::~Desktop()
  34419. {
  34420. jassert (instance == this);
  34421. instance = 0;
  34422. // doh! If you don't delete all your windows before exiting, you're going to
  34423. // be leaking memory!
  34424. jassert (desktopComponents.size() == 0);
  34425. }
  34426. Desktop& JUCE_CALLTYPE Desktop::getInstance()
  34427. {
  34428. if (instance == 0)
  34429. instance = new Desktop();
  34430. return *instance;
  34431. }
  34432. Desktop* Desktop::instance = 0;
  34433. extern void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords,
  34434. const bool clipToWorkArea);
  34435. void Desktop::refreshMonitorSizes()
  34436. {
  34437. const Array <Rectangle<int> > oldClipped (monitorCoordsClipped);
  34438. const Array <Rectangle<int> > oldUnclipped (monitorCoordsUnclipped);
  34439. monitorCoordsClipped.clear();
  34440. monitorCoordsUnclipped.clear();
  34441. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  34442. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  34443. jassert (monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  34444. if (oldClipped != monitorCoordsClipped
  34445. || oldUnclipped != monitorCoordsUnclipped)
  34446. {
  34447. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  34448. {
  34449. ComponentPeer* const p = ComponentPeer::getPeer (i);
  34450. if (p != 0)
  34451. p->handleScreenSizeChange();
  34452. }
  34453. }
  34454. }
  34455. int Desktop::getNumDisplayMonitors() const throw()
  34456. {
  34457. return monitorCoordsClipped.size();
  34458. }
  34459. const Rectangle<int> Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  34460. {
  34461. return clippedToWorkArea ? monitorCoordsClipped [index]
  34462. : monitorCoordsUnclipped [index];
  34463. }
  34464. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  34465. {
  34466. RectangleList rl;
  34467. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  34468. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34469. return rl;
  34470. }
  34471. const Rectangle<int> Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  34472. {
  34473. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  34474. }
  34475. const Rectangle<int> Desktop::getMonitorAreaContaining (const Point<int>& position, const bool clippedToWorkArea) const
  34476. {
  34477. Rectangle<int> best (getMainMonitorArea (clippedToWorkArea));
  34478. double bestDistance = 1.0e10;
  34479. for (int i = getNumDisplayMonitors(); --i >= 0;)
  34480. {
  34481. const Rectangle<int> rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  34482. if (rect.contains (position))
  34483. return rect;
  34484. const double distance = rect.getCentre().getDistanceFrom (position);
  34485. if (distance < bestDistance)
  34486. {
  34487. bestDistance = distance;
  34488. best = rect;
  34489. }
  34490. }
  34491. return best;
  34492. }
  34493. int Desktop::getNumComponents() const throw()
  34494. {
  34495. return desktopComponents.size();
  34496. }
  34497. Component* Desktop::getComponent (const int index) const throw()
  34498. {
  34499. return desktopComponents [index];
  34500. }
  34501. Component* Desktop::findComponentAt (const Point<int>& screenPosition) const
  34502. {
  34503. for (int i = desktopComponents.size(); --i >= 0;)
  34504. {
  34505. Component* const c = desktopComponents.getUnchecked(i);
  34506. const Point<int> relative (c->globalPositionToRelative (screenPosition));
  34507. if (c->contains (relative.getX(), relative.getY()))
  34508. return c->getComponentAt (relative.getX(), relative.getY());
  34509. }
  34510. return 0;
  34511. }
  34512. void Desktop::addDesktopComponent (Component* const c)
  34513. {
  34514. jassert (c != 0);
  34515. jassert (! desktopComponents.contains (c));
  34516. desktopComponents.addIfNotAlreadyThere (c);
  34517. }
  34518. void Desktop::removeDesktopComponent (Component* const c)
  34519. {
  34520. desktopComponents.removeValue (c);
  34521. }
  34522. void Desktop::componentBroughtToFront (Component* const c)
  34523. {
  34524. const int index = desktopComponents.indexOf (c);
  34525. jassert (index >= 0);
  34526. if (index >= 0)
  34527. {
  34528. int newIndex = -1;
  34529. if (! c->isAlwaysOnTop())
  34530. {
  34531. newIndex = desktopComponents.size();
  34532. while (newIndex > 0 && desktopComponents.getUnchecked (newIndex - 1)->isAlwaysOnTop())
  34533. --newIndex;
  34534. --newIndex;
  34535. }
  34536. desktopComponents.move (index, newIndex);
  34537. }
  34538. }
  34539. const Point<int> Desktop::getLastMouseDownPosition() throw()
  34540. {
  34541. return getInstance().getMainMouseSource().getLastMouseDownPosition();
  34542. }
  34543. int Desktop::getMouseButtonClickCounter() throw()
  34544. {
  34545. return getInstance().mouseClickCounter;
  34546. }
  34547. void Desktop::incrementMouseClickCounter() throw()
  34548. {
  34549. ++mouseClickCounter;
  34550. }
  34551. int Desktop::getNumDraggingMouseSources() const throw()
  34552. {
  34553. int num = 0;
  34554. for (int i = mouseSources.size(); --i >= 0;)
  34555. if (mouseSources.getUnchecked(i)->isDragging())
  34556. ++num;
  34557. return num;
  34558. }
  34559. MouseInputSource* Desktop::getDraggingMouseSource (int index) const throw()
  34560. {
  34561. int num = 0;
  34562. for (int i = mouseSources.size(); --i >= 0;)
  34563. {
  34564. MouseInputSource* const mi = mouseSources.getUnchecked(i);
  34565. if (mi->isDragging())
  34566. {
  34567. if (index == num)
  34568. return mi;
  34569. ++num;
  34570. }
  34571. }
  34572. return 0;
  34573. }
  34574. void Desktop::addFocusChangeListener (FocusChangeListener* const listener)
  34575. {
  34576. focusListeners.add (listener);
  34577. }
  34578. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener)
  34579. {
  34580. focusListeners.remove (listener);
  34581. }
  34582. void Desktop::triggerFocusCallback()
  34583. {
  34584. triggerAsyncUpdate();
  34585. }
  34586. void Desktop::handleAsyncUpdate()
  34587. {
  34588. Component* currentFocus = Component::getCurrentlyFocusedComponent();
  34589. focusListeners.call (&FocusChangeListener::globalFocusChanged, currentFocus);
  34590. }
  34591. void Desktop::addGlobalMouseListener (MouseListener* const listener)
  34592. {
  34593. mouseListeners.add (listener);
  34594. resetTimer();
  34595. }
  34596. void Desktop::removeGlobalMouseListener (MouseListener* const listener)
  34597. {
  34598. mouseListeners.remove (listener);
  34599. resetTimer();
  34600. }
  34601. void Desktop::timerCallback()
  34602. {
  34603. if (lastFakeMouseMove != getMousePosition())
  34604. sendMouseMove();
  34605. }
  34606. void Desktop::sendMouseMove()
  34607. {
  34608. if (! mouseListeners.isEmpty())
  34609. {
  34610. startTimer (20);
  34611. lastFakeMouseMove = getMousePosition();
  34612. Component* const target = findComponentAt (lastFakeMouseMove);
  34613. if (target != 0)
  34614. {
  34615. Component::BailOutChecker checker (target);
  34616. const Point<int> pos (target->globalPositionToRelative (lastFakeMouseMove));
  34617. const Time now (Time::getCurrentTime());
  34618. const MouseEvent me (getMainMouseSource(), pos, ModifierKeys::getCurrentModifiers(),
  34619. target, target, now, pos, now, 0, false);
  34620. if (me.mods.isAnyMouseButtonDown())
  34621. mouseListeners.callChecked (checker, &MouseListener::mouseDrag, me);
  34622. else
  34623. mouseListeners.callChecked (checker, &MouseListener::mouseMove, me);
  34624. }
  34625. }
  34626. }
  34627. void Desktop::resetTimer()
  34628. {
  34629. if (mouseListeners.size() == 0)
  34630. stopTimer();
  34631. else
  34632. startTimer (100);
  34633. lastFakeMouseMove = getMousePosition();
  34634. }
  34635. extern void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars);
  34636. void Desktop::setKioskModeComponent (Component* componentToUse, const bool allowMenusAndBars)
  34637. {
  34638. if (kioskModeComponent != componentToUse)
  34639. {
  34640. // agh! Don't delete a component without first stopping it being the kiosk comp
  34641. jassert (kioskModeComponent == 0 || kioskModeComponent->isValidComponent());
  34642. // agh! Don't remove a component from the desktop if it's the kiosk comp!
  34643. jassert (kioskModeComponent == 0 || kioskModeComponent->isOnDesktop());
  34644. if (kioskModeComponent->isValidComponent())
  34645. {
  34646. juce_setKioskComponent (kioskModeComponent, false, allowMenusAndBars);
  34647. kioskModeComponent->setBounds (kioskComponentOriginalBounds);
  34648. }
  34649. kioskModeComponent = componentToUse;
  34650. if (kioskModeComponent != 0)
  34651. {
  34652. jassert (kioskModeComponent->isValidComponent());
  34653. // Only components that are already on the desktop can be put into kiosk mode!
  34654. jassert (kioskModeComponent->isOnDesktop());
  34655. kioskComponentOriginalBounds = kioskModeComponent->getBounds();
  34656. juce_setKioskComponent (kioskModeComponent, true, allowMenusAndBars);
  34657. }
  34658. }
  34659. }
  34660. void Desktop::setOrientationsEnabled (const int newOrientations)
  34661. {
  34662. // Dodgy set of flags being passed here! Make sure you specify at least one permitted orientation.
  34663. jassert (newOrientations != 0 && (newOrientations & ~allOrientations) == 0);
  34664. allowedOrientations = newOrientations;
  34665. }
  34666. bool Desktop::isOrientationEnabled (const DisplayOrientation orientation) const throw()
  34667. {
  34668. // Make sure you only pass one valid flag in here...
  34669. jassert (orientation == upright || orientation == upsideDown || orientation == rotatedClockwise || orientation == rotatedAntiClockwise);
  34670. return (allowedOrientations & orientation) != 0;
  34671. }
  34672. END_JUCE_NAMESPACE
  34673. /*** End of inlined file: juce_Desktop.cpp ***/
  34674. /*** Start of inlined file: juce_ModalComponentManager.cpp ***/
  34675. BEGIN_JUCE_NAMESPACE
  34676. class ModalComponentManager::ModalItem : public ComponentListener
  34677. {
  34678. public:
  34679. ModalItem (Component* const comp, Callback* const callback)
  34680. : component (comp), returnValue (0), isActive (true), isDeleted (false)
  34681. {
  34682. if (callback != 0)
  34683. callbacks.add (callback);
  34684. jassert (comp != 0);
  34685. component->addComponentListener (this);
  34686. }
  34687. ~ModalItem()
  34688. {
  34689. if (! isDeleted)
  34690. component->removeComponentListener (this);
  34691. }
  34692. void componentBeingDeleted (Component&)
  34693. {
  34694. isDeleted = true;
  34695. cancel();
  34696. }
  34697. void componentVisibilityChanged (Component&)
  34698. {
  34699. if (! component->isShowing())
  34700. cancel();
  34701. }
  34702. void componentParentHierarchyChanged (Component&)
  34703. {
  34704. if (! component->isShowing())
  34705. cancel();
  34706. }
  34707. void cancel()
  34708. {
  34709. if (isActive)
  34710. {
  34711. isActive = false;
  34712. ModalComponentManager::getInstance()->triggerAsyncUpdate();
  34713. }
  34714. }
  34715. Component* component;
  34716. OwnedArray<Callback> callbacks;
  34717. int returnValue;
  34718. bool isActive, isDeleted;
  34719. private:
  34720. ModalItem (const ModalItem&);
  34721. ModalItem& operator= (const ModalItem&);
  34722. };
  34723. ModalComponentManager::ModalComponentManager()
  34724. {
  34725. }
  34726. ModalComponentManager::~ModalComponentManager()
  34727. {
  34728. clearSingletonInstance();
  34729. }
  34730. juce_ImplementSingleton_SingleThreaded (ModalComponentManager);
  34731. void ModalComponentManager::startModal (Component* component, Callback* callback)
  34732. {
  34733. if (component != 0)
  34734. stack.add (new ModalItem (component, callback));
  34735. }
  34736. void ModalComponentManager::attachCallback (Component* component, Callback* callback)
  34737. {
  34738. if (callback != 0)
  34739. {
  34740. ScopedPointer<Callback> callbackDeleter (callback);
  34741. for (int i = stack.size(); --i >= 0;)
  34742. {
  34743. ModalItem* const item = stack.getUnchecked(i);
  34744. if (item->component == component)
  34745. {
  34746. item->callbacks.add (callback);
  34747. callbackDeleter.release();
  34748. break;
  34749. }
  34750. }
  34751. }
  34752. }
  34753. void ModalComponentManager::endModal (Component* component)
  34754. {
  34755. for (int i = stack.size(); --i >= 0;)
  34756. {
  34757. ModalItem* const item = stack.getUnchecked(i);
  34758. if (item->component == component)
  34759. item->cancel();
  34760. }
  34761. }
  34762. void ModalComponentManager::endModal (Component* component, int returnValue)
  34763. {
  34764. for (int i = stack.size(); --i >= 0;)
  34765. {
  34766. ModalItem* const item = stack.getUnchecked(i);
  34767. if (item->component == component)
  34768. {
  34769. item->returnValue = returnValue;
  34770. item->cancel();
  34771. }
  34772. }
  34773. }
  34774. int ModalComponentManager::getNumModalComponents() const
  34775. {
  34776. int n = 0;
  34777. for (int i = 0; i < stack.size(); ++i)
  34778. if (stack.getUnchecked(i)->isActive)
  34779. ++n;
  34780. return n;
  34781. }
  34782. Component* ModalComponentManager::getModalComponent (const int index) const
  34783. {
  34784. int n = 0;
  34785. for (int i = stack.size(); --i >= 0;)
  34786. {
  34787. const ModalItem* const item = stack.getUnchecked(i);
  34788. if (item->isActive)
  34789. if (n++ == index)
  34790. return item->component;
  34791. }
  34792. return 0;
  34793. }
  34794. bool ModalComponentManager::isModal (Component* const comp) const
  34795. {
  34796. for (int i = stack.size(); --i >= 0;)
  34797. {
  34798. const ModalItem* const item = stack.getUnchecked(i);
  34799. if (item->isActive && item->component == comp)
  34800. return true;
  34801. }
  34802. return false;
  34803. }
  34804. bool ModalComponentManager::isFrontModalComponent (Component* const comp) const
  34805. {
  34806. return comp == getModalComponent (0);
  34807. }
  34808. void ModalComponentManager::handleAsyncUpdate()
  34809. {
  34810. for (int i = stack.size(); --i >= 0;)
  34811. {
  34812. const ModalItem* const item = stack.getUnchecked(i);
  34813. if (! item->isActive)
  34814. {
  34815. for (int j = item->callbacks.size(); --j >= 0;)
  34816. item->callbacks.getUnchecked(j)->modalStateFinished (item->returnValue);
  34817. stack.remove (i);
  34818. }
  34819. }
  34820. }
  34821. class ModalComponentManager::ReturnValueRetriever : public ModalComponentManager::Callback
  34822. {
  34823. public:
  34824. ReturnValueRetriever (int& value_, bool& finished_) : value (value_), finished (finished_) {}
  34825. ~ReturnValueRetriever() {}
  34826. void modalStateFinished (int returnValue)
  34827. {
  34828. finished = true;
  34829. value = returnValue;
  34830. }
  34831. private:
  34832. int& value;
  34833. bool& finished;
  34834. ReturnValueRetriever (const ReturnValueRetriever&);
  34835. ReturnValueRetriever& operator= (const ReturnValueRetriever&);
  34836. };
  34837. int ModalComponentManager::runEventLoopForCurrentComponent()
  34838. {
  34839. // This can only be run from the message thread!
  34840. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  34841. Component* currentlyModal = getModalComponent (0);
  34842. if (currentlyModal == 0)
  34843. return 0;
  34844. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  34845. int returnValue = 0;
  34846. bool finished = false;
  34847. attachCallback (currentlyModal, new ReturnValueRetriever (returnValue, finished));
  34848. JUCE_TRY
  34849. {
  34850. while (! finished)
  34851. {
  34852. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  34853. break;
  34854. }
  34855. }
  34856. JUCE_CATCH_EXCEPTION
  34857. if (prevFocused != 0)
  34858. prevFocused->grabKeyboardFocus();
  34859. return returnValue;
  34860. }
  34861. END_JUCE_NAMESPACE
  34862. /*** End of inlined file: juce_ModalComponentManager.cpp ***/
  34863. /*** Start of inlined file: juce_ArrowButton.cpp ***/
  34864. BEGIN_JUCE_NAMESPACE
  34865. ArrowButton::ArrowButton (const String& name,
  34866. float arrowDirectionInRadians,
  34867. const Colour& arrowColour)
  34868. : Button (name),
  34869. colour (arrowColour)
  34870. {
  34871. path.lineTo (0.0f, 1.0f);
  34872. path.lineTo (1.0f, 0.5f);
  34873. path.closeSubPath();
  34874. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  34875. 0.5f, 0.5f));
  34876. setComponentEffect (&shadow);
  34877. buttonStateChanged();
  34878. }
  34879. ArrowButton::~ArrowButton()
  34880. {
  34881. }
  34882. void ArrowButton::paintButton (Graphics& g,
  34883. bool /*isMouseOverButton*/,
  34884. bool /*isButtonDown*/)
  34885. {
  34886. g.setColour (colour);
  34887. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  34888. (float) offset,
  34889. (float) (getWidth() - 3),
  34890. (float) (getHeight() - 3),
  34891. false));
  34892. }
  34893. void ArrowButton::buttonStateChanged()
  34894. {
  34895. offset = (isDown()) ? 1 : 0;
  34896. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  34897. 0.3f, -1, 0);
  34898. }
  34899. END_JUCE_NAMESPACE
  34900. /*** End of inlined file: juce_ArrowButton.cpp ***/
  34901. /*** Start of inlined file: juce_Button.cpp ***/
  34902. BEGIN_JUCE_NAMESPACE
  34903. class Button::RepeatTimer : public Timer
  34904. {
  34905. public:
  34906. RepeatTimer (Button& owner_) : owner (owner_) {}
  34907. void timerCallback() { owner.repeatTimerCallback(); }
  34908. juce_UseDebuggingNewOperator
  34909. private:
  34910. Button& owner;
  34911. RepeatTimer (const RepeatTimer&);
  34912. RepeatTimer& operator= (const RepeatTimer&);
  34913. };
  34914. Button::Button (const String& name)
  34915. : Component (name),
  34916. text (name),
  34917. buttonPressTime (0),
  34918. lastTimeCallbackTime (0),
  34919. commandManagerToUse (0),
  34920. autoRepeatDelay (-1),
  34921. autoRepeatSpeed (0),
  34922. autoRepeatMinimumDelay (-1),
  34923. radioGroupId (0),
  34924. commandID (0),
  34925. connectedEdgeFlags (0),
  34926. buttonState (buttonNormal),
  34927. lastToggleState (false),
  34928. clickTogglesState (false),
  34929. needsToRelease (false),
  34930. needsRepainting (false),
  34931. isKeyDown (false),
  34932. triggerOnMouseDown (false),
  34933. generateTooltip (false)
  34934. {
  34935. setWantsKeyboardFocus (true);
  34936. isOn.addListener (this);
  34937. }
  34938. Button::~Button()
  34939. {
  34940. isOn.removeListener (this);
  34941. if (commandManagerToUse != 0)
  34942. commandManagerToUse->removeListener (this);
  34943. repeatTimer = 0;
  34944. clearShortcuts();
  34945. }
  34946. void Button::setButtonText (const String& newText)
  34947. {
  34948. if (text != newText)
  34949. {
  34950. text = newText;
  34951. repaint();
  34952. }
  34953. }
  34954. void Button::setTooltip (const String& newTooltip)
  34955. {
  34956. SettableTooltipClient::setTooltip (newTooltip);
  34957. generateTooltip = false;
  34958. }
  34959. const String Button::getTooltip()
  34960. {
  34961. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  34962. {
  34963. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  34964. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  34965. for (int i = 0; i < keyPresses.size(); ++i)
  34966. {
  34967. const String key (keyPresses.getReference(i).getTextDescription());
  34968. tt << " [";
  34969. if (key.length() == 1)
  34970. tt << TRANS("shortcut") << ": '" << key << "']";
  34971. else
  34972. tt << key << ']';
  34973. }
  34974. return tt;
  34975. }
  34976. return SettableTooltipClient::getTooltip();
  34977. }
  34978. void Button::setConnectedEdges (const int connectedEdgeFlags_)
  34979. {
  34980. if (connectedEdgeFlags != connectedEdgeFlags_)
  34981. {
  34982. connectedEdgeFlags = connectedEdgeFlags_;
  34983. repaint();
  34984. }
  34985. }
  34986. void Button::setToggleState (const bool shouldBeOn,
  34987. const bool sendChangeNotification)
  34988. {
  34989. if (shouldBeOn != lastToggleState)
  34990. {
  34991. if (isOn != shouldBeOn) // this test means that if the value is void rather than explicitly set to
  34992. isOn = shouldBeOn; // false, it won't be changed unless the required value is true.
  34993. lastToggleState = shouldBeOn;
  34994. repaint();
  34995. if (sendChangeNotification)
  34996. {
  34997. Component::SafePointer<Component> deletionWatcher (this);
  34998. sendClickMessage (ModifierKeys());
  34999. if (deletionWatcher == 0)
  35000. return;
  35001. }
  35002. if (lastToggleState)
  35003. turnOffOtherButtonsInGroup (sendChangeNotification);
  35004. }
  35005. }
  35006. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  35007. {
  35008. clickTogglesState = shouldToggle;
  35009. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35010. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35011. // it is that this button represents, and the button will update its state to reflect this
  35012. // in the applicationCommandListChanged() method.
  35013. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35014. }
  35015. bool Button::getClickingTogglesState() const throw()
  35016. {
  35017. return clickTogglesState;
  35018. }
  35019. void Button::valueChanged (Value& value)
  35020. {
  35021. if (value.refersToSameSourceAs (isOn))
  35022. setToggleState (isOn.getValue(), true);
  35023. }
  35024. void Button::setRadioGroupId (const int newGroupId)
  35025. {
  35026. if (radioGroupId != newGroupId)
  35027. {
  35028. radioGroupId = newGroupId;
  35029. if (lastToggleState)
  35030. turnOffOtherButtonsInGroup (true);
  35031. }
  35032. }
  35033. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  35034. {
  35035. Component* const p = getParentComponent();
  35036. if (p != 0 && radioGroupId != 0)
  35037. {
  35038. Component::SafePointer<Component> deletionWatcher (this);
  35039. for (int i = p->getNumChildComponents(); --i >= 0;)
  35040. {
  35041. Component* const c = p->getChildComponent (i);
  35042. if (c != this)
  35043. {
  35044. Button* const b = dynamic_cast <Button*> (c);
  35045. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  35046. {
  35047. b->setToggleState (false, sendChangeNotification);
  35048. if (deletionWatcher == 0)
  35049. return;
  35050. }
  35051. }
  35052. }
  35053. }
  35054. }
  35055. void Button::enablementChanged()
  35056. {
  35057. updateState (0);
  35058. repaint();
  35059. }
  35060. Button::ButtonState Button::updateState (const MouseEvent* const e)
  35061. {
  35062. ButtonState state = buttonNormal;
  35063. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  35064. {
  35065. Point<int> mousePos;
  35066. if (e == 0)
  35067. mousePos = getMouseXYRelative();
  35068. else
  35069. mousePos = e->getEventRelativeTo (this).getPosition();
  35070. const bool over = reallyContains (mousePos.getX(), mousePos.getY(), true);
  35071. const bool down = isMouseButtonDown();
  35072. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  35073. state = buttonDown;
  35074. else if (over)
  35075. state = buttonOver;
  35076. }
  35077. setState (state);
  35078. return state;
  35079. }
  35080. void Button::setState (const ButtonState newState)
  35081. {
  35082. if (buttonState != newState)
  35083. {
  35084. buttonState = newState;
  35085. repaint();
  35086. if (buttonState == buttonDown)
  35087. {
  35088. buttonPressTime = Time::getApproximateMillisecondCounter();
  35089. lastTimeCallbackTime = buttonPressTime;
  35090. }
  35091. sendStateMessage();
  35092. }
  35093. }
  35094. bool Button::isDown() const throw()
  35095. {
  35096. return buttonState == buttonDown;
  35097. }
  35098. bool Button::isOver() const throw()
  35099. {
  35100. return buttonState != buttonNormal;
  35101. }
  35102. void Button::buttonStateChanged()
  35103. {
  35104. }
  35105. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  35106. {
  35107. const uint32 now = Time::getApproximateMillisecondCounter();
  35108. return now > buttonPressTime ? now - buttonPressTime : 0;
  35109. }
  35110. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  35111. {
  35112. triggerOnMouseDown = isTriggeredOnMouseDown;
  35113. }
  35114. void Button::clicked()
  35115. {
  35116. }
  35117. void Button::clicked (const ModifierKeys& /*modifiers*/)
  35118. {
  35119. clicked();
  35120. }
  35121. static const int clickMessageId = 0x2f3f4f99;
  35122. void Button::triggerClick()
  35123. {
  35124. postCommandMessage (clickMessageId);
  35125. }
  35126. void Button::internalClickCallback (const ModifierKeys& modifiers)
  35127. {
  35128. if (clickTogglesState)
  35129. setToggleState ((radioGroupId != 0) || ! lastToggleState, false);
  35130. sendClickMessage (modifiers);
  35131. }
  35132. void Button::flashButtonState()
  35133. {
  35134. if (isEnabled())
  35135. {
  35136. needsToRelease = true;
  35137. setState (buttonDown);
  35138. getRepeatTimer().startTimer (100);
  35139. }
  35140. }
  35141. void Button::handleCommandMessage (int commandId)
  35142. {
  35143. if (commandId == clickMessageId)
  35144. {
  35145. if (isEnabled())
  35146. {
  35147. flashButtonState();
  35148. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35149. }
  35150. }
  35151. else
  35152. {
  35153. Component::handleCommandMessage (commandId);
  35154. }
  35155. }
  35156. void Button::addButtonListener (Listener* const newListener)
  35157. {
  35158. buttonListeners.add (newListener);
  35159. }
  35160. void Button::removeButtonListener (Listener* const listener)
  35161. {
  35162. buttonListeners.remove (listener);
  35163. }
  35164. void Button::sendClickMessage (const ModifierKeys& modifiers)
  35165. {
  35166. Component::BailOutChecker checker (this);
  35167. if (commandManagerToUse != 0 && commandID != 0)
  35168. {
  35169. ApplicationCommandTarget::InvocationInfo info (commandID);
  35170. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  35171. info.originatingComponent = this;
  35172. commandManagerToUse->invoke (info, true);
  35173. }
  35174. clicked (modifiers);
  35175. if (! checker.shouldBailOut())
  35176. buttonListeners.callChecked (checker, &ButtonListener::buttonClicked, this); // (can't use Button::Listener due to idiotic VC2005 bug)
  35177. }
  35178. void Button::sendStateMessage()
  35179. {
  35180. Component::BailOutChecker checker (this);
  35181. buttonStateChanged();
  35182. if (! checker.shouldBailOut())
  35183. buttonListeners.callChecked (checker, &ButtonListener::buttonStateChanged, this);
  35184. }
  35185. void Button::paint (Graphics& g)
  35186. {
  35187. if (needsToRelease && isEnabled())
  35188. {
  35189. needsToRelease = false;
  35190. needsRepainting = true;
  35191. }
  35192. paintButton (g, isOver(), isDown());
  35193. }
  35194. void Button::mouseEnter (const MouseEvent& e)
  35195. {
  35196. updateState (&e);
  35197. }
  35198. void Button::mouseExit (const MouseEvent& e)
  35199. {
  35200. updateState (&e);
  35201. }
  35202. void Button::mouseDown (const MouseEvent& e)
  35203. {
  35204. updateState (&e);
  35205. if (isDown())
  35206. {
  35207. if (autoRepeatDelay >= 0)
  35208. getRepeatTimer().startTimer (autoRepeatDelay);
  35209. if (triggerOnMouseDown)
  35210. internalClickCallback (e.mods);
  35211. }
  35212. }
  35213. void Button::mouseUp (const MouseEvent& e)
  35214. {
  35215. const bool wasDown = isDown();
  35216. updateState (&e);
  35217. if (wasDown && isOver() && ! triggerOnMouseDown)
  35218. internalClickCallback (e.mods);
  35219. }
  35220. void Button::mouseDrag (const MouseEvent& e)
  35221. {
  35222. const ButtonState oldState = buttonState;
  35223. updateState (&e);
  35224. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  35225. getRepeatTimer().startTimer (autoRepeatSpeed);
  35226. }
  35227. void Button::focusGained (FocusChangeType)
  35228. {
  35229. updateState (0);
  35230. repaint();
  35231. }
  35232. void Button::focusLost (FocusChangeType)
  35233. {
  35234. updateState (0);
  35235. repaint();
  35236. }
  35237. void Button::setVisible (bool shouldBeVisible)
  35238. {
  35239. if (shouldBeVisible != isVisible())
  35240. {
  35241. Component::setVisible (shouldBeVisible);
  35242. if (! shouldBeVisible)
  35243. needsToRelease = false;
  35244. updateState (0);
  35245. }
  35246. else
  35247. {
  35248. Component::setVisible (shouldBeVisible);
  35249. }
  35250. }
  35251. void Button::parentHierarchyChanged()
  35252. {
  35253. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  35254. if (newKeySource != keySource.getComponent())
  35255. {
  35256. if (keySource != 0)
  35257. keySource->removeKeyListener (this);
  35258. keySource = newKeySource;
  35259. if (keySource != 0)
  35260. keySource->addKeyListener (this);
  35261. }
  35262. }
  35263. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  35264. const int commandID_,
  35265. const bool generateTooltip_)
  35266. {
  35267. commandID = commandID_;
  35268. generateTooltip = generateTooltip_;
  35269. if (commandManagerToUse != commandManagerToUse_)
  35270. {
  35271. if (commandManagerToUse != 0)
  35272. commandManagerToUse->removeListener (this);
  35273. commandManagerToUse = commandManagerToUse_;
  35274. if (commandManagerToUse != 0)
  35275. commandManagerToUse->addListener (this);
  35276. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  35277. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  35278. // it is that this button represents, and the button will update its state to reflect this
  35279. // in the applicationCommandListChanged() method.
  35280. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  35281. }
  35282. if (commandManagerToUse != 0)
  35283. applicationCommandListChanged();
  35284. else
  35285. setEnabled (true);
  35286. }
  35287. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  35288. {
  35289. if (info.commandID == commandID
  35290. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  35291. {
  35292. flashButtonState();
  35293. }
  35294. }
  35295. void Button::applicationCommandListChanged()
  35296. {
  35297. if (commandManagerToUse != 0)
  35298. {
  35299. ApplicationCommandInfo info (0);
  35300. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  35301. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  35302. if (target != 0)
  35303. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  35304. }
  35305. }
  35306. void Button::addShortcut (const KeyPress& key)
  35307. {
  35308. if (key.isValid())
  35309. {
  35310. jassert (! isRegisteredForShortcut (key)); // already registered!
  35311. shortcuts.add (key);
  35312. parentHierarchyChanged();
  35313. }
  35314. }
  35315. void Button::clearShortcuts()
  35316. {
  35317. shortcuts.clear();
  35318. parentHierarchyChanged();
  35319. }
  35320. bool Button::isShortcutPressed() const
  35321. {
  35322. if (! isCurrentlyBlockedByAnotherModalComponent())
  35323. {
  35324. for (int i = shortcuts.size(); --i >= 0;)
  35325. if (shortcuts.getReference(i).isCurrentlyDown())
  35326. return true;
  35327. }
  35328. return false;
  35329. }
  35330. bool Button::isRegisteredForShortcut (const KeyPress& key) const
  35331. {
  35332. for (int i = shortcuts.size(); --i >= 0;)
  35333. if (key == shortcuts.getReference(i))
  35334. return true;
  35335. return false;
  35336. }
  35337. bool Button::keyStateChanged (const bool, Component*)
  35338. {
  35339. if (! isEnabled())
  35340. return false;
  35341. const bool wasDown = isKeyDown;
  35342. isKeyDown = isShortcutPressed();
  35343. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  35344. getRepeatTimer().startTimer (autoRepeatDelay);
  35345. updateState (0);
  35346. if (isEnabled() && wasDown && ! isKeyDown)
  35347. {
  35348. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35349. // (return immediately - this button may now have been deleted)
  35350. return true;
  35351. }
  35352. return wasDown || isKeyDown;
  35353. }
  35354. bool Button::keyPressed (const KeyPress&, Component*)
  35355. {
  35356. // returning true will avoid forwarding events for keys that we're using as shortcuts
  35357. return isShortcutPressed();
  35358. }
  35359. bool Button::keyPressed (const KeyPress& key)
  35360. {
  35361. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  35362. {
  35363. triggerClick();
  35364. return true;
  35365. }
  35366. return false;
  35367. }
  35368. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  35369. const int repeatMillisecs,
  35370. const int minimumDelayInMillisecs) throw()
  35371. {
  35372. autoRepeatDelay = initialDelayMillisecs;
  35373. autoRepeatSpeed = repeatMillisecs;
  35374. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  35375. }
  35376. void Button::repeatTimerCallback()
  35377. {
  35378. if (needsRepainting)
  35379. {
  35380. getRepeatTimer().stopTimer();
  35381. updateState (0);
  35382. needsRepainting = false;
  35383. }
  35384. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  35385. {
  35386. int repeatSpeed = autoRepeatSpeed;
  35387. if (autoRepeatMinimumDelay >= 0)
  35388. {
  35389. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  35390. timeHeldDown *= timeHeldDown;
  35391. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  35392. }
  35393. repeatSpeed = jmax (1, repeatSpeed);
  35394. getRepeatTimer().startTimer (repeatSpeed);
  35395. const uint32 now = Time::getApproximateMillisecondCounter();
  35396. const int numTimesToCallback = (now > lastTimeCallbackTime) ? jmax (1, (int) (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  35397. lastTimeCallbackTime = now;
  35398. Component::SafePointer<Component> deletionWatcher (this);
  35399. for (int i = numTimesToCallback; --i >= 0;)
  35400. {
  35401. internalClickCallback (ModifierKeys::getCurrentModifiers());
  35402. if (deletionWatcher == 0 || ! isDown())
  35403. return;
  35404. }
  35405. }
  35406. else if (! needsToRelease)
  35407. {
  35408. getRepeatTimer().stopTimer();
  35409. }
  35410. }
  35411. Button::RepeatTimer& Button::getRepeatTimer()
  35412. {
  35413. if (repeatTimer == 0)
  35414. repeatTimer = new RepeatTimer (*this);
  35415. return *repeatTimer;
  35416. }
  35417. END_JUCE_NAMESPACE
  35418. /*** End of inlined file: juce_Button.cpp ***/
  35419. /*** Start of inlined file: juce_DrawableButton.cpp ***/
  35420. BEGIN_JUCE_NAMESPACE
  35421. DrawableButton::DrawableButton (const String& name,
  35422. const DrawableButton::ButtonStyle buttonStyle)
  35423. : Button (name),
  35424. style (buttonStyle),
  35425. edgeIndent (3)
  35426. {
  35427. if (buttonStyle == ImageOnButtonBackground)
  35428. {
  35429. backgroundOff = Colour (0xffbbbbff);
  35430. backgroundOn = Colour (0xff3333ff);
  35431. }
  35432. else
  35433. {
  35434. backgroundOff = Colours::transparentBlack;
  35435. backgroundOn = Colour (0xaabbbbff);
  35436. }
  35437. }
  35438. DrawableButton::~DrawableButton()
  35439. {
  35440. deleteImages();
  35441. }
  35442. void DrawableButton::deleteImages()
  35443. {
  35444. }
  35445. void DrawableButton::setImages (const Drawable* normal,
  35446. const Drawable* over,
  35447. const Drawable* down,
  35448. const Drawable* disabled,
  35449. const Drawable* normalOn,
  35450. const Drawable* overOn,
  35451. const Drawable* downOn,
  35452. const Drawable* disabledOn)
  35453. {
  35454. deleteImages();
  35455. jassert (normal != 0); // you really need to give it at least a normal image..
  35456. if (normal != 0)
  35457. normalImage = normal->createCopy();
  35458. if (over != 0)
  35459. overImage = over->createCopy();
  35460. if (down != 0)
  35461. downImage = down->createCopy();
  35462. if (disabled != 0)
  35463. disabledImage = disabled->createCopy();
  35464. if (normalOn != 0)
  35465. normalImageOn = normalOn->createCopy();
  35466. if (overOn != 0)
  35467. overImageOn = overOn->createCopy();
  35468. if (downOn != 0)
  35469. downImageOn = downOn->createCopy();
  35470. if (disabledOn != 0)
  35471. disabledImageOn = disabledOn->createCopy();
  35472. repaint();
  35473. }
  35474. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  35475. {
  35476. if (style != newStyle)
  35477. {
  35478. style = newStyle;
  35479. repaint();
  35480. }
  35481. }
  35482. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  35483. const Colour& toggledOnColour)
  35484. {
  35485. if (backgroundOff != toggledOffColour
  35486. || backgroundOn != toggledOnColour)
  35487. {
  35488. backgroundOff = toggledOffColour;
  35489. backgroundOn = toggledOnColour;
  35490. repaint();
  35491. }
  35492. }
  35493. const Colour& DrawableButton::getBackgroundColour() const throw()
  35494. {
  35495. return getToggleState() ? backgroundOn
  35496. : backgroundOff;
  35497. }
  35498. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  35499. {
  35500. edgeIndent = numPixelsIndent;
  35501. repaint();
  35502. }
  35503. void DrawableButton::paintButton (Graphics& g,
  35504. bool isMouseOverButton,
  35505. bool isButtonDown)
  35506. {
  35507. Rectangle<int> imageSpace;
  35508. if (style == ImageOnButtonBackground)
  35509. {
  35510. const int insetX = getWidth() / 4;
  35511. const int insetY = getHeight() / 4;
  35512. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  35513. getLookAndFeel().drawButtonBackground (g, *this,
  35514. getBackgroundColour(),
  35515. isMouseOverButton,
  35516. isButtonDown);
  35517. }
  35518. else
  35519. {
  35520. g.fillAll (getBackgroundColour());
  35521. const int textH = (style == ImageAboveTextLabel)
  35522. ? jmin (16, proportionOfHeight (0.25f))
  35523. : 0;
  35524. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  35525. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  35526. imageSpace.setBounds (indentX, indentY,
  35527. getWidth() - indentX * 2,
  35528. getHeight() - indentY * 2 - textH);
  35529. if (textH > 0)
  35530. {
  35531. g.setFont ((float) textH);
  35532. g.setColour (findColour (DrawableButton::textColourId)
  35533. .withMultipliedAlpha (isEnabled() ? 1.0f : 0.4f));
  35534. g.drawFittedText (getButtonText(),
  35535. 2, getHeight() - textH - 1,
  35536. getWidth() - 4, textH,
  35537. Justification::centred, 1);
  35538. }
  35539. }
  35540. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  35541. g.setOpacity (1.0f);
  35542. const Drawable* imageToDraw = 0;
  35543. if (isEnabled())
  35544. {
  35545. imageToDraw = getCurrentImage();
  35546. }
  35547. else
  35548. {
  35549. imageToDraw = getToggleState() ? disabledImageOn
  35550. : disabledImage;
  35551. if (imageToDraw == 0)
  35552. {
  35553. g.setOpacity (0.4f);
  35554. imageToDraw = getNormalImage();
  35555. }
  35556. }
  35557. if (imageToDraw != 0)
  35558. {
  35559. if (style == ImageRaw)
  35560. imageToDraw->draw (g, 1.0f);
  35561. else
  35562. imageToDraw->drawWithin (g, imageSpace.toFloat(), RectanglePlacement::centred, 1.0f);
  35563. }
  35564. }
  35565. const Drawable* DrawableButton::getCurrentImage() const throw()
  35566. {
  35567. if (isDown())
  35568. return getDownImage();
  35569. if (isOver())
  35570. return getOverImage();
  35571. return getNormalImage();
  35572. }
  35573. const Drawable* DrawableButton::getNormalImage() const throw()
  35574. {
  35575. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  35576. : normalImage;
  35577. }
  35578. const Drawable* DrawableButton::getOverImage() const throw()
  35579. {
  35580. const Drawable* d = normalImage;
  35581. if (getToggleState())
  35582. {
  35583. if (overImageOn != 0)
  35584. d = overImageOn;
  35585. else if (normalImageOn != 0)
  35586. d = normalImageOn;
  35587. else if (overImage != 0)
  35588. d = overImage;
  35589. }
  35590. else
  35591. {
  35592. if (overImage != 0)
  35593. d = overImage;
  35594. }
  35595. return d;
  35596. }
  35597. const Drawable* DrawableButton::getDownImage() const throw()
  35598. {
  35599. const Drawable* d = normalImage;
  35600. if (getToggleState())
  35601. {
  35602. if (downImageOn != 0)
  35603. d = downImageOn;
  35604. else if (overImageOn != 0)
  35605. d = overImageOn;
  35606. else if (normalImageOn != 0)
  35607. d = normalImageOn;
  35608. else if (downImage != 0)
  35609. d = downImage;
  35610. else
  35611. d = getOverImage();
  35612. }
  35613. else
  35614. {
  35615. if (downImage != 0)
  35616. d = downImage;
  35617. else
  35618. d = getOverImage();
  35619. }
  35620. return d;
  35621. }
  35622. END_JUCE_NAMESPACE
  35623. /*** End of inlined file: juce_DrawableButton.cpp ***/
  35624. /*** Start of inlined file: juce_HyperlinkButton.cpp ***/
  35625. BEGIN_JUCE_NAMESPACE
  35626. HyperlinkButton::HyperlinkButton (const String& linkText,
  35627. const URL& linkURL)
  35628. : Button (linkText),
  35629. url (linkURL),
  35630. font (14.0f, Font::underlined),
  35631. resizeFont (true),
  35632. justification (Justification::centred)
  35633. {
  35634. setMouseCursor (MouseCursor::PointingHandCursor);
  35635. setTooltip (linkURL.toString (false));
  35636. }
  35637. HyperlinkButton::~HyperlinkButton()
  35638. {
  35639. }
  35640. void HyperlinkButton::setFont (const Font& newFont,
  35641. const bool resizeToMatchComponentHeight,
  35642. const Justification& justificationType)
  35643. {
  35644. font = newFont;
  35645. resizeFont = resizeToMatchComponentHeight;
  35646. justification = justificationType;
  35647. repaint();
  35648. }
  35649. void HyperlinkButton::setURL (const URL& newURL) throw()
  35650. {
  35651. url = newURL;
  35652. setTooltip (newURL.toString (false));
  35653. }
  35654. const Font HyperlinkButton::getFontToUse() const
  35655. {
  35656. Font f (font);
  35657. if (resizeFont)
  35658. f.setHeight (getHeight() * 0.7f);
  35659. return f;
  35660. }
  35661. void HyperlinkButton::changeWidthToFitText()
  35662. {
  35663. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  35664. }
  35665. void HyperlinkButton::colourChanged()
  35666. {
  35667. repaint();
  35668. }
  35669. void HyperlinkButton::clicked()
  35670. {
  35671. if (url.isWellFormed())
  35672. url.launchInDefaultBrowser();
  35673. }
  35674. void HyperlinkButton::paintButton (Graphics& g,
  35675. bool isMouseOverButton,
  35676. bool isButtonDown)
  35677. {
  35678. const Colour textColour (findColour (textColourId));
  35679. if (isEnabled())
  35680. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  35681. : textColour);
  35682. else
  35683. g.setColour (textColour.withMultipliedAlpha (0.4f));
  35684. g.setFont (getFontToUse());
  35685. g.drawText (getButtonText(),
  35686. 2, 0, getWidth() - 2, getHeight(),
  35687. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  35688. true);
  35689. }
  35690. END_JUCE_NAMESPACE
  35691. /*** End of inlined file: juce_HyperlinkButton.cpp ***/
  35692. /*** Start of inlined file: juce_ImageButton.cpp ***/
  35693. BEGIN_JUCE_NAMESPACE
  35694. ImageButton::ImageButton (const String& text_)
  35695. : Button (text_),
  35696. scaleImageToFit (true),
  35697. preserveProportions (true),
  35698. alphaThreshold (0),
  35699. imageX (0),
  35700. imageY (0),
  35701. imageW (0),
  35702. imageH (0),
  35703. normalImage (0),
  35704. overImage (0),
  35705. downImage (0)
  35706. {
  35707. }
  35708. ImageButton::~ImageButton()
  35709. {
  35710. }
  35711. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  35712. const bool rescaleImagesWhenButtonSizeChanges,
  35713. const bool preserveImageProportions,
  35714. const Image& normalImage_,
  35715. const float imageOpacityWhenNormal,
  35716. const Colour& overlayColourWhenNormal,
  35717. const Image& overImage_,
  35718. const float imageOpacityWhenOver,
  35719. const Colour& overlayColourWhenOver,
  35720. const Image& downImage_,
  35721. const float imageOpacityWhenDown,
  35722. const Colour& overlayColourWhenDown,
  35723. const float hitTestAlphaThreshold)
  35724. {
  35725. normalImage = normalImage_;
  35726. overImage = overImage_;
  35727. downImage = downImage_;
  35728. if (resizeButtonNowToFitThisImage && normalImage.isValid())
  35729. {
  35730. imageW = normalImage.getWidth();
  35731. imageH = normalImage.getHeight();
  35732. setSize (imageW, imageH);
  35733. }
  35734. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  35735. preserveProportions = preserveImageProportions;
  35736. normalOpacity = imageOpacityWhenNormal;
  35737. normalOverlay = overlayColourWhenNormal;
  35738. overOpacity = imageOpacityWhenOver;
  35739. overOverlay = overlayColourWhenOver;
  35740. downOpacity = imageOpacityWhenDown;
  35741. downOverlay = overlayColourWhenDown;
  35742. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundToInt (255.0f * hitTestAlphaThreshold));
  35743. repaint();
  35744. }
  35745. const Image ImageButton::getCurrentImage() const
  35746. {
  35747. if (isDown() || getToggleState())
  35748. return getDownImage();
  35749. if (isOver())
  35750. return getOverImage();
  35751. return getNormalImage();
  35752. }
  35753. const Image ImageButton::getNormalImage() const
  35754. {
  35755. return normalImage;
  35756. }
  35757. const Image ImageButton::getOverImage() const
  35758. {
  35759. return overImage.isValid() ? overImage
  35760. : normalImage;
  35761. }
  35762. const Image ImageButton::getDownImage() const
  35763. {
  35764. return downImage.isValid() ? downImage
  35765. : getOverImage();
  35766. }
  35767. void ImageButton::paintButton (Graphics& g,
  35768. bool isMouseOverButton,
  35769. bool isButtonDown)
  35770. {
  35771. if (! isEnabled())
  35772. {
  35773. isMouseOverButton = false;
  35774. isButtonDown = false;
  35775. }
  35776. Image im (getCurrentImage());
  35777. if (im.isValid())
  35778. {
  35779. const int iw = im.getWidth();
  35780. const int ih = im.getHeight();
  35781. imageW = getWidth();
  35782. imageH = getHeight();
  35783. imageX = (imageW - iw) >> 1;
  35784. imageY = (imageH - ih) >> 1;
  35785. if (scaleImageToFit)
  35786. {
  35787. if (preserveProportions)
  35788. {
  35789. int newW, newH;
  35790. const float imRatio = ih / (float)iw;
  35791. const float destRatio = imageH / (float)imageW;
  35792. if (imRatio > destRatio)
  35793. {
  35794. newW = roundToInt (imageH / imRatio);
  35795. newH = imageH;
  35796. }
  35797. else
  35798. {
  35799. newW = imageW;
  35800. newH = roundToInt (imageW * imRatio);
  35801. }
  35802. imageX = (imageW - newW) / 2;
  35803. imageY = (imageH - newH) / 2;
  35804. imageW = newW;
  35805. imageH = newH;
  35806. }
  35807. else
  35808. {
  35809. imageX = 0;
  35810. imageY = 0;
  35811. }
  35812. }
  35813. if (! scaleImageToFit)
  35814. {
  35815. imageW = iw;
  35816. imageH = ih;
  35817. }
  35818. getLookAndFeel().drawImageButton (g, &im, imageX, imageY, imageW, imageH,
  35819. isButtonDown ? downOverlay
  35820. : (isMouseOverButton ? overOverlay
  35821. : normalOverlay),
  35822. isButtonDown ? downOpacity
  35823. : (isMouseOverButton ? overOpacity
  35824. : normalOpacity),
  35825. *this);
  35826. }
  35827. }
  35828. bool ImageButton::hitTest (int x, int y)
  35829. {
  35830. if (alphaThreshold == 0)
  35831. return true;
  35832. Image im (getCurrentImage());
  35833. return im.isNull() || (imageW > 0 && imageH > 0
  35834. && alphaThreshold < im.getPixelAt (((x - imageX) * im.getWidth()) / imageW,
  35835. ((y - imageY) * im.getHeight()) / imageH).getAlpha());
  35836. }
  35837. END_JUCE_NAMESPACE
  35838. /*** End of inlined file: juce_ImageButton.cpp ***/
  35839. /*** Start of inlined file: juce_ShapeButton.cpp ***/
  35840. BEGIN_JUCE_NAMESPACE
  35841. ShapeButton::ShapeButton (const String& text_,
  35842. const Colour& normalColour_,
  35843. const Colour& overColour_,
  35844. const Colour& downColour_)
  35845. : Button (text_),
  35846. normalColour (normalColour_),
  35847. overColour (overColour_),
  35848. downColour (downColour_),
  35849. maintainShapeProportions (false),
  35850. outlineWidth (0.0f)
  35851. {
  35852. }
  35853. ShapeButton::~ShapeButton()
  35854. {
  35855. }
  35856. void ShapeButton::setColours (const Colour& newNormalColour,
  35857. const Colour& newOverColour,
  35858. const Colour& newDownColour)
  35859. {
  35860. normalColour = newNormalColour;
  35861. overColour = newOverColour;
  35862. downColour = newDownColour;
  35863. }
  35864. void ShapeButton::setOutline (const Colour& newOutlineColour,
  35865. const float newOutlineWidth)
  35866. {
  35867. outlineColour = newOutlineColour;
  35868. outlineWidth = newOutlineWidth;
  35869. }
  35870. void ShapeButton::setShape (const Path& newShape,
  35871. const bool resizeNowToFitThisShape,
  35872. const bool maintainShapeProportions_,
  35873. const bool hasShadow)
  35874. {
  35875. shape = newShape;
  35876. maintainShapeProportions = maintainShapeProportions_;
  35877. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  35878. setComponentEffect ((hasShadow) ? &shadow : 0);
  35879. if (resizeNowToFitThisShape)
  35880. {
  35881. Rectangle<float> bounds (shape.getBounds());
  35882. if (hasShadow)
  35883. bounds.expand (4.0f, 4.0f);
  35884. shape.applyTransform (AffineTransform::translation (-bounds.getX(), -bounds.getY()));
  35885. setSize (1 + (int) (bounds.getWidth() + outlineWidth),
  35886. 1 + (int) (bounds.getHeight() + outlineWidth));
  35887. }
  35888. }
  35889. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  35890. {
  35891. if (! isEnabled())
  35892. {
  35893. isMouseOverButton = false;
  35894. isButtonDown = false;
  35895. }
  35896. g.setColour ((isButtonDown) ? downColour
  35897. : (isMouseOverButton) ? overColour
  35898. : normalColour);
  35899. int w = getWidth();
  35900. int h = getHeight();
  35901. if (getComponentEffect() != 0)
  35902. {
  35903. w -= 4;
  35904. h -= 4;
  35905. }
  35906. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  35907. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  35908. w - offset - outlineWidth,
  35909. h - offset - outlineWidth,
  35910. maintainShapeProportions));
  35911. g.fillPath (shape, trans);
  35912. if (outlineWidth > 0.0f)
  35913. {
  35914. g.setColour (outlineColour);
  35915. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  35916. }
  35917. }
  35918. END_JUCE_NAMESPACE
  35919. /*** End of inlined file: juce_ShapeButton.cpp ***/
  35920. /*** Start of inlined file: juce_TextButton.cpp ***/
  35921. BEGIN_JUCE_NAMESPACE
  35922. TextButton::TextButton (const String& name,
  35923. const String& toolTip)
  35924. : Button (name)
  35925. {
  35926. setTooltip (toolTip);
  35927. }
  35928. TextButton::~TextButton()
  35929. {
  35930. }
  35931. void TextButton::paintButton (Graphics& g,
  35932. bool isMouseOverButton,
  35933. bool isButtonDown)
  35934. {
  35935. getLookAndFeel().drawButtonBackground (g, *this,
  35936. findColour (getToggleState() ? buttonOnColourId
  35937. : buttonColourId),
  35938. isMouseOverButton,
  35939. isButtonDown);
  35940. getLookAndFeel().drawButtonText (g, *this,
  35941. isMouseOverButton,
  35942. isButtonDown);
  35943. }
  35944. void TextButton::colourChanged()
  35945. {
  35946. repaint();
  35947. }
  35948. const Font TextButton::getFont()
  35949. {
  35950. return Font (jmin (15.0f, getHeight() * 0.6f));
  35951. }
  35952. void TextButton::changeWidthToFitText (const int newHeight)
  35953. {
  35954. if (newHeight >= 0)
  35955. setSize (jmax (1, getWidth()), newHeight);
  35956. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  35957. getHeight());
  35958. }
  35959. END_JUCE_NAMESPACE
  35960. /*** End of inlined file: juce_TextButton.cpp ***/
  35961. /*** Start of inlined file: juce_ToggleButton.cpp ***/
  35962. BEGIN_JUCE_NAMESPACE
  35963. ToggleButton::ToggleButton (const String& buttonText)
  35964. : Button (buttonText)
  35965. {
  35966. setClickingTogglesState (true);
  35967. }
  35968. ToggleButton::~ToggleButton()
  35969. {
  35970. }
  35971. void ToggleButton::paintButton (Graphics& g,
  35972. bool isMouseOverButton,
  35973. bool isButtonDown)
  35974. {
  35975. getLookAndFeel().drawToggleButton (g, *this,
  35976. isMouseOverButton,
  35977. isButtonDown);
  35978. }
  35979. void ToggleButton::changeWidthToFitText()
  35980. {
  35981. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  35982. }
  35983. void ToggleButton::colourChanged()
  35984. {
  35985. repaint();
  35986. }
  35987. END_JUCE_NAMESPACE
  35988. /*** End of inlined file: juce_ToggleButton.cpp ***/
  35989. /*** Start of inlined file: juce_ToolbarButton.cpp ***/
  35990. BEGIN_JUCE_NAMESPACE
  35991. ToolbarButton::ToolbarButton (const int itemId_,
  35992. const String& buttonText,
  35993. Drawable* const normalImage_,
  35994. Drawable* const toggledOnImage_)
  35995. : ToolbarItemComponent (itemId_, buttonText, true),
  35996. normalImage (normalImage_),
  35997. toggledOnImage (toggledOnImage_)
  35998. {
  35999. jassert (normalImage_ != 0);
  36000. }
  36001. ToolbarButton::~ToolbarButton()
  36002. {
  36003. }
  36004. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  36005. bool /*isToolbarVertical*/,
  36006. int& preferredSize,
  36007. int& minSize, int& maxSize)
  36008. {
  36009. preferredSize = minSize = maxSize = toolbarDepth;
  36010. return true;
  36011. }
  36012. void ToolbarButton::paintButtonArea (Graphics& g,
  36013. int width, int height,
  36014. bool /*isMouseOver*/,
  36015. bool /*isMouseDown*/)
  36016. {
  36017. Drawable* d = normalImage;
  36018. if (getToggleState() && toggledOnImage != 0)
  36019. d = toggledOnImage;
  36020. const Rectangle<float> area (0.0f, 0.0f, (float) width, (float) height);
  36021. if (! isEnabled())
  36022. {
  36023. Image im (Image::ARGB, width, height, true);
  36024. {
  36025. Graphics g2 (im);
  36026. d->drawWithin (g2, area, RectanglePlacement::centred, 1.0f);
  36027. }
  36028. im.desaturate();
  36029. g.drawImageAt (im, 0, 0);
  36030. }
  36031. else
  36032. {
  36033. d->drawWithin (g, area, RectanglePlacement::centred, 1.0f);
  36034. }
  36035. }
  36036. void ToolbarButton::contentAreaChanged (const Rectangle<int>&)
  36037. {
  36038. }
  36039. END_JUCE_NAMESPACE
  36040. /*** End of inlined file: juce_ToolbarButton.cpp ***/
  36041. /*** Start of inlined file: juce_CodeDocument.cpp ***/
  36042. BEGIN_JUCE_NAMESPACE
  36043. class CodeDocumentLine
  36044. {
  36045. public:
  36046. CodeDocumentLine (const juce_wchar* const line_,
  36047. const int lineLength_,
  36048. const int numNewLineChars,
  36049. const int lineStartInFile_)
  36050. : line (line_, lineLength_),
  36051. lineStartInFile (lineStartInFile_),
  36052. lineLength (lineLength_),
  36053. lineLengthWithoutNewLines (lineLength_ - numNewLineChars)
  36054. {
  36055. }
  36056. ~CodeDocumentLine()
  36057. {
  36058. }
  36059. static void createLines (Array <CodeDocumentLine*>& newLines, const String& text)
  36060. {
  36061. const juce_wchar* const t = text;
  36062. int pos = 0;
  36063. while (t [pos] != 0)
  36064. {
  36065. const int startOfLine = pos;
  36066. int numNewLineChars = 0;
  36067. while (t[pos] != 0)
  36068. {
  36069. if (t[pos] == '\r')
  36070. {
  36071. ++numNewLineChars;
  36072. ++pos;
  36073. if (t[pos] == '\n')
  36074. {
  36075. ++numNewLineChars;
  36076. ++pos;
  36077. }
  36078. break;
  36079. }
  36080. if (t[pos] == '\n')
  36081. {
  36082. ++numNewLineChars;
  36083. ++pos;
  36084. break;
  36085. }
  36086. ++pos;
  36087. }
  36088. newLines.add (new CodeDocumentLine (t + startOfLine, pos - startOfLine,
  36089. numNewLineChars, startOfLine));
  36090. }
  36091. jassert (pos == text.length());
  36092. }
  36093. bool endsWithLineBreak() const throw()
  36094. {
  36095. return lineLengthWithoutNewLines != lineLength;
  36096. }
  36097. void updateLength() throw()
  36098. {
  36099. lineLengthWithoutNewLines = lineLength = line.length();
  36100. while (lineLengthWithoutNewLines > 0
  36101. && (line [lineLengthWithoutNewLines - 1] == '\n'
  36102. || line [lineLengthWithoutNewLines - 1] == '\r'))
  36103. {
  36104. --lineLengthWithoutNewLines;
  36105. }
  36106. }
  36107. String line;
  36108. int lineStartInFile, lineLength, lineLengthWithoutNewLines;
  36109. };
  36110. CodeDocument::Iterator::Iterator (CodeDocument* const document_)
  36111. : document (document_),
  36112. currentLine (document_->lines[0]),
  36113. line (0),
  36114. position (0)
  36115. {
  36116. }
  36117. CodeDocument::Iterator::Iterator (const CodeDocument::Iterator& other)
  36118. : document (other.document),
  36119. currentLine (other.currentLine),
  36120. line (other.line),
  36121. position (other.position)
  36122. {
  36123. }
  36124. CodeDocument::Iterator& CodeDocument::Iterator::operator= (const CodeDocument::Iterator& other) throw()
  36125. {
  36126. document = other.document;
  36127. currentLine = other.currentLine;
  36128. line = other.line;
  36129. position = other.position;
  36130. return *this;
  36131. }
  36132. CodeDocument::Iterator::~Iterator() throw()
  36133. {
  36134. }
  36135. juce_wchar CodeDocument::Iterator::nextChar()
  36136. {
  36137. if (currentLine == 0)
  36138. return 0;
  36139. jassert (currentLine == document->lines.getUnchecked (line));
  36140. const juce_wchar result = currentLine->line [position - currentLine->lineStartInFile];
  36141. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36142. {
  36143. ++line;
  36144. currentLine = document->lines [line];
  36145. }
  36146. return result;
  36147. }
  36148. void CodeDocument::Iterator::skip()
  36149. {
  36150. if (currentLine != 0)
  36151. {
  36152. jassert (currentLine == document->lines.getUnchecked (line));
  36153. if (++position >= currentLine->lineStartInFile + currentLine->lineLength)
  36154. {
  36155. ++line;
  36156. currentLine = document->lines [line];
  36157. }
  36158. }
  36159. }
  36160. void CodeDocument::Iterator::skipToEndOfLine()
  36161. {
  36162. if (currentLine != 0)
  36163. {
  36164. jassert (currentLine == document->lines.getUnchecked (line));
  36165. ++line;
  36166. currentLine = document->lines [line];
  36167. if (currentLine != 0)
  36168. position = currentLine->lineStartInFile;
  36169. else
  36170. position = document->getNumCharacters();
  36171. }
  36172. }
  36173. juce_wchar CodeDocument::Iterator::peekNextChar() const
  36174. {
  36175. if (currentLine == 0)
  36176. return 0;
  36177. jassert (currentLine == document->lines.getUnchecked (line));
  36178. return const_cast <const String&> (currentLine->line) [position - currentLine->lineStartInFile];
  36179. }
  36180. void CodeDocument::Iterator::skipWhitespace()
  36181. {
  36182. while (CharacterFunctions::isWhitespace (peekNextChar()))
  36183. skip();
  36184. }
  36185. bool CodeDocument::Iterator::isEOF() const throw()
  36186. {
  36187. return currentLine == 0;
  36188. }
  36189. CodeDocument::Position::Position() throw()
  36190. : owner (0), characterPos (0), line (0),
  36191. indexInLine (0), positionMaintained (false)
  36192. {
  36193. }
  36194. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36195. const int line_, const int indexInLine_) throw()
  36196. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36197. characterPos (0), line (line_),
  36198. indexInLine (indexInLine_), positionMaintained (false)
  36199. {
  36200. setLineAndIndex (line_, indexInLine_);
  36201. }
  36202. CodeDocument::Position::Position (const CodeDocument* const ownerDocument,
  36203. const int characterPos_) throw()
  36204. : owner (const_cast <CodeDocument*> (ownerDocument)),
  36205. positionMaintained (false)
  36206. {
  36207. setPosition (characterPos_);
  36208. }
  36209. CodeDocument::Position::Position (const Position& other) throw()
  36210. : owner (other.owner), characterPos (other.characterPos), line (other.line),
  36211. indexInLine (other.indexInLine), positionMaintained (false)
  36212. {
  36213. jassert (*this == other);
  36214. }
  36215. CodeDocument::Position::~Position()
  36216. {
  36217. setPositionMaintained (false);
  36218. }
  36219. CodeDocument::Position& CodeDocument::Position::operator= (const Position& other)
  36220. {
  36221. if (this != &other)
  36222. {
  36223. const bool wasPositionMaintained = positionMaintained;
  36224. if (owner != other.owner)
  36225. setPositionMaintained (false);
  36226. owner = other.owner;
  36227. line = other.line;
  36228. indexInLine = other.indexInLine;
  36229. characterPos = other.characterPos;
  36230. setPositionMaintained (wasPositionMaintained);
  36231. jassert (*this == other);
  36232. }
  36233. return *this;
  36234. }
  36235. bool CodeDocument::Position::operator== (const Position& other) const throw()
  36236. {
  36237. jassert ((characterPos == other.characterPos)
  36238. == (line == other.line && indexInLine == other.indexInLine));
  36239. return characterPos == other.characterPos
  36240. && line == other.line
  36241. && indexInLine == other.indexInLine
  36242. && owner == other.owner;
  36243. }
  36244. bool CodeDocument::Position::operator!= (const Position& other) const throw()
  36245. {
  36246. return ! operator== (other);
  36247. }
  36248. void CodeDocument::Position::setLineAndIndex (const int newLine, const int newIndexInLine)
  36249. {
  36250. jassert (owner != 0);
  36251. if (owner->lines.size() == 0)
  36252. {
  36253. line = 0;
  36254. indexInLine = 0;
  36255. characterPos = 0;
  36256. }
  36257. else
  36258. {
  36259. if (newLine >= owner->lines.size())
  36260. {
  36261. line = owner->lines.size() - 1;
  36262. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36263. jassert (l != 0);
  36264. indexInLine = l->lineLengthWithoutNewLines;
  36265. characterPos = l->lineStartInFile + indexInLine;
  36266. }
  36267. else
  36268. {
  36269. line = jmax (0, newLine);
  36270. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36271. jassert (l != 0);
  36272. if (l->lineLengthWithoutNewLines > 0)
  36273. indexInLine = jlimit (0, l->lineLengthWithoutNewLines, newIndexInLine);
  36274. else
  36275. indexInLine = 0;
  36276. characterPos = l->lineStartInFile + indexInLine;
  36277. }
  36278. }
  36279. }
  36280. void CodeDocument::Position::setPosition (const int newPosition)
  36281. {
  36282. jassert (owner != 0);
  36283. line = 0;
  36284. indexInLine = 0;
  36285. characterPos = 0;
  36286. if (newPosition > 0)
  36287. {
  36288. int lineStart = 0;
  36289. int lineEnd = owner->lines.size();
  36290. for (;;)
  36291. {
  36292. if (lineEnd - lineStart < 4)
  36293. {
  36294. for (int i = lineStart; i < lineEnd; ++i)
  36295. {
  36296. CodeDocumentLine* const l = owner->lines.getUnchecked (i);
  36297. int index = newPosition - l->lineStartInFile;
  36298. if (index >= 0 && (index < l->lineLength || i == lineEnd - 1))
  36299. {
  36300. line = i;
  36301. indexInLine = jmin (l->lineLengthWithoutNewLines, index);
  36302. characterPos = l->lineStartInFile + indexInLine;
  36303. }
  36304. }
  36305. break;
  36306. }
  36307. else
  36308. {
  36309. const int midIndex = (lineStart + lineEnd + 1) / 2;
  36310. CodeDocumentLine* const mid = owner->lines.getUnchecked (midIndex);
  36311. if (newPosition >= mid->lineStartInFile)
  36312. lineStart = midIndex;
  36313. else
  36314. lineEnd = midIndex;
  36315. }
  36316. }
  36317. }
  36318. }
  36319. void CodeDocument::Position::moveBy (int characterDelta)
  36320. {
  36321. jassert (owner != 0);
  36322. if (characterDelta == 1)
  36323. {
  36324. setPosition (getPosition());
  36325. // If moving right, make sure we don't get stuck between the \r and \n characters..
  36326. if (line < owner->lines.size())
  36327. {
  36328. CodeDocumentLine* const l = owner->lines.getUnchecked (line);
  36329. if (indexInLine + characterDelta < l->lineLength
  36330. && indexInLine + characterDelta >= l->lineLengthWithoutNewLines + 1)
  36331. ++characterDelta;
  36332. }
  36333. }
  36334. setPosition (characterPos + characterDelta);
  36335. }
  36336. const CodeDocument::Position CodeDocument::Position::movedBy (const int characterDelta) const
  36337. {
  36338. CodeDocument::Position p (*this);
  36339. p.moveBy (characterDelta);
  36340. return p;
  36341. }
  36342. const CodeDocument::Position CodeDocument::Position::movedByLines (const int deltaLines) const
  36343. {
  36344. CodeDocument::Position p (*this);
  36345. p.setLineAndIndex (getLineNumber() + deltaLines, getIndexInLine());
  36346. return p;
  36347. }
  36348. const juce_wchar CodeDocument::Position::getCharacter() const
  36349. {
  36350. const CodeDocumentLine* const l = owner->lines [line];
  36351. return l == 0 ? 0 : l->line [getIndexInLine()];
  36352. }
  36353. const String CodeDocument::Position::getLineText() const
  36354. {
  36355. const CodeDocumentLine* const l = owner->lines [line];
  36356. return l == 0 ? String::empty : l->line;
  36357. }
  36358. void CodeDocument::Position::setPositionMaintained (const bool isMaintained)
  36359. {
  36360. if (isMaintained != positionMaintained)
  36361. {
  36362. positionMaintained = isMaintained;
  36363. if (owner != 0)
  36364. {
  36365. if (isMaintained)
  36366. {
  36367. jassert (! owner->positionsToMaintain.contains (this));
  36368. owner->positionsToMaintain.add (this);
  36369. }
  36370. else
  36371. {
  36372. // If this happens, you may have deleted the document while there are Position objects that are still using it...
  36373. jassert (owner->positionsToMaintain.contains (this));
  36374. owner->positionsToMaintain.removeValue (this);
  36375. }
  36376. }
  36377. }
  36378. }
  36379. CodeDocument::CodeDocument()
  36380. : undoManager (std::numeric_limits<int>::max(), 10000),
  36381. currentActionIndex (0),
  36382. indexOfSavedState (-1),
  36383. maximumLineLength (-1),
  36384. newLineChars ("\r\n")
  36385. {
  36386. }
  36387. CodeDocument::~CodeDocument()
  36388. {
  36389. }
  36390. const String CodeDocument::getAllContent() const
  36391. {
  36392. return getTextBetween (Position (this, 0),
  36393. Position (this, lines.size(), 0));
  36394. }
  36395. const String CodeDocument::getTextBetween (const Position& start, const Position& end) const
  36396. {
  36397. if (end.getPosition() <= start.getPosition())
  36398. return String::empty;
  36399. const int startLine = start.getLineNumber();
  36400. const int endLine = end.getLineNumber();
  36401. if (startLine == endLine)
  36402. {
  36403. CodeDocumentLine* const line = lines [startLine];
  36404. return (line == 0) ? String::empty : line->line.substring (start.getIndexInLine(), end.getIndexInLine());
  36405. }
  36406. String result;
  36407. result.preallocateStorage (end.getPosition() - start.getPosition() + 4);
  36408. String::Concatenator concatenator (result);
  36409. const int maxLine = jmin (lines.size() - 1, endLine);
  36410. for (int i = jmax (0, startLine); i <= maxLine; ++i)
  36411. {
  36412. const CodeDocumentLine* line = lines.getUnchecked(i);
  36413. int len = line->lineLength;
  36414. if (i == startLine)
  36415. {
  36416. const int index = start.getIndexInLine();
  36417. concatenator.append (line->line.substring (index, len));
  36418. }
  36419. else if (i == endLine)
  36420. {
  36421. len = end.getIndexInLine();
  36422. concatenator.append (line->line.substring (0, len));
  36423. }
  36424. else
  36425. {
  36426. concatenator.append (line->line);
  36427. }
  36428. }
  36429. return result;
  36430. }
  36431. int CodeDocument::getNumCharacters() const throw()
  36432. {
  36433. const CodeDocumentLine* const lastLine = lines.getLast();
  36434. return (lastLine == 0) ? 0 : lastLine->lineStartInFile + lastLine->lineLength;
  36435. }
  36436. const String CodeDocument::getLine (const int lineIndex) const throw()
  36437. {
  36438. const CodeDocumentLine* const line = lines [lineIndex];
  36439. return (line == 0) ? String::empty : line->line;
  36440. }
  36441. int CodeDocument::getMaximumLineLength() throw()
  36442. {
  36443. if (maximumLineLength < 0)
  36444. {
  36445. maximumLineLength = 0;
  36446. for (int i = lines.size(); --i >= 0;)
  36447. maximumLineLength = jmax (maximumLineLength, lines.getUnchecked(i)->lineLength);
  36448. }
  36449. return maximumLineLength;
  36450. }
  36451. void CodeDocument::deleteSection (const Position& startPosition, const Position& endPosition)
  36452. {
  36453. remove (startPosition.getPosition(), endPosition.getPosition(), true);
  36454. }
  36455. void CodeDocument::insertText (const Position& position, const String& text)
  36456. {
  36457. insert (text, position.getPosition(), true);
  36458. }
  36459. void CodeDocument::replaceAllContent (const String& newContent)
  36460. {
  36461. remove (0, getNumCharacters(), true);
  36462. insert (newContent, 0, true);
  36463. }
  36464. bool CodeDocument::loadFromStream (InputStream& stream)
  36465. {
  36466. replaceAllContent (stream.readEntireStreamAsString());
  36467. setSavePoint();
  36468. clearUndoHistory();
  36469. return true;
  36470. }
  36471. bool CodeDocument::writeToStream (OutputStream& stream)
  36472. {
  36473. for (int i = 0; i < lines.size(); ++i)
  36474. {
  36475. String temp (lines.getUnchecked(i)->line); // use a copy to avoid bloating the memory footprint of the stored string.
  36476. const char* utf8 = temp.toUTF8();
  36477. if (! stream.write (utf8, (int) strlen (utf8)))
  36478. return false;
  36479. }
  36480. return true;
  36481. }
  36482. void CodeDocument::setNewLineCharacters (const String& newLine) throw()
  36483. {
  36484. jassert (newLine == "\r\n" || newLine == "\n" || newLine == "\r");
  36485. newLineChars = newLine;
  36486. }
  36487. void CodeDocument::newTransaction()
  36488. {
  36489. undoManager.beginNewTransaction (String::empty);
  36490. }
  36491. void CodeDocument::undo()
  36492. {
  36493. newTransaction();
  36494. undoManager.undo();
  36495. }
  36496. void CodeDocument::redo()
  36497. {
  36498. undoManager.redo();
  36499. }
  36500. void CodeDocument::clearUndoHistory()
  36501. {
  36502. undoManager.clearUndoHistory();
  36503. }
  36504. void CodeDocument::setSavePoint() throw()
  36505. {
  36506. indexOfSavedState = currentActionIndex;
  36507. }
  36508. bool CodeDocument::hasChangedSinceSavePoint() const throw()
  36509. {
  36510. return currentActionIndex != indexOfSavedState;
  36511. }
  36512. namespace CodeDocumentHelpers
  36513. {
  36514. int getCharacterType (const juce_wchar character) throw()
  36515. {
  36516. return (CharacterFunctions::isLetterOrDigit (character) || character == '_')
  36517. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  36518. }
  36519. }
  36520. const CodeDocument::Position CodeDocument::findWordBreakAfter (const Position& position) const throw()
  36521. {
  36522. Position p (position);
  36523. const int maxDistance = 256;
  36524. int i = 0;
  36525. while (i < maxDistance
  36526. && CharacterFunctions::isWhitespace (p.getCharacter())
  36527. && (i == 0 || (p.getCharacter() != '\n'
  36528. && p.getCharacter() != '\r')))
  36529. {
  36530. ++i;
  36531. p.moveBy (1);
  36532. }
  36533. if (i == 0)
  36534. {
  36535. const int type = CodeDocumentHelpers::getCharacterType (p.getCharacter());
  36536. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.getCharacter()))
  36537. {
  36538. ++i;
  36539. p.moveBy (1);
  36540. }
  36541. while (i < maxDistance
  36542. && CharacterFunctions::isWhitespace (p.getCharacter())
  36543. && (i == 0 || (p.getCharacter() != '\n'
  36544. && p.getCharacter() != '\r')))
  36545. {
  36546. ++i;
  36547. p.moveBy (1);
  36548. }
  36549. }
  36550. return p;
  36551. }
  36552. const CodeDocument::Position CodeDocument::findWordBreakBefore (const Position& position) const throw()
  36553. {
  36554. Position p (position);
  36555. const int maxDistance = 256;
  36556. int i = 0;
  36557. bool stoppedAtLineStart = false;
  36558. while (i < maxDistance)
  36559. {
  36560. const juce_wchar c = p.movedBy (-1).getCharacter();
  36561. if (c == '\r' || c == '\n')
  36562. {
  36563. stoppedAtLineStart = true;
  36564. if (i > 0)
  36565. break;
  36566. }
  36567. if (! CharacterFunctions::isWhitespace (c))
  36568. break;
  36569. p.moveBy (-1);
  36570. ++i;
  36571. }
  36572. if (i < maxDistance && ! stoppedAtLineStart)
  36573. {
  36574. const int type = CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter());
  36575. while (i < maxDistance && type == CodeDocumentHelpers::getCharacterType (p.movedBy (-1).getCharacter()))
  36576. {
  36577. p.moveBy (-1);
  36578. ++i;
  36579. }
  36580. }
  36581. return p;
  36582. }
  36583. void CodeDocument::checkLastLineStatus()
  36584. {
  36585. while (lines.size() > 0
  36586. && lines.getLast()->lineLength == 0
  36587. && (lines.size() == 1 || ! lines.getUnchecked (lines.size() - 2)->endsWithLineBreak()))
  36588. {
  36589. // remove any empty lines at the end if the preceding line doesn't end in a newline.
  36590. lines.removeLast();
  36591. }
  36592. const CodeDocumentLine* const lastLine = lines.getLast();
  36593. if (lastLine != 0 && lastLine->endsWithLineBreak())
  36594. {
  36595. // check that there's an empty line at the end if the preceding one ends in a newline..
  36596. lines.add (new CodeDocumentLine (String::empty, 0, 0, lastLine->lineStartInFile + lastLine->lineLength));
  36597. }
  36598. }
  36599. void CodeDocument::addListener (CodeDocument::Listener* const listener) throw()
  36600. {
  36601. listeners.add (listener);
  36602. }
  36603. void CodeDocument::removeListener (CodeDocument::Listener* const listener) throw()
  36604. {
  36605. listeners.remove (listener);
  36606. }
  36607. void CodeDocument::sendListenerChangeMessage (const int startLine, const int endLine)
  36608. {
  36609. Position startPos (this, startLine, 0);
  36610. Position endPos (this, endLine, 0);
  36611. listeners.call (&CodeDocument::Listener::codeDocumentChanged, startPos, endPos);
  36612. }
  36613. class CodeDocumentInsertAction : public UndoableAction
  36614. {
  36615. CodeDocument& owner;
  36616. const String text;
  36617. int insertPos;
  36618. CodeDocumentInsertAction (const CodeDocumentInsertAction&);
  36619. CodeDocumentInsertAction& operator= (const CodeDocumentInsertAction&);
  36620. public:
  36621. CodeDocumentInsertAction (CodeDocument& owner_, const String& text_, const int insertPos_) throw()
  36622. : owner (owner_),
  36623. text (text_),
  36624. insertPos (insertPos_)
  36625. {
  36626. }
  36627. ~CodeDocumentInsertAction() {}
  36628. bool perform()
  36629. {
  36630. owner.currentActionIndex++;
  36631. owner.insert (text, insertPos, false);
  36632. return true;
  36633. }
  36634. bool undo()
  36635. {
  36636. owner.currentActionIndex--;
  36637. owner.remove (insertPos, insertPos + text.length(), false);
  36638. return true;
  36639. }
  36640. int getSizeInUnits() { return text.length() + 32; }
  36641. };
  36642. void CodeDocument::insert (const String& text, const int insertPos, const bool undoable)
  36643. {
  36644. if (text.isEmpty())
  36645. return;
  36646. if (undoable)
  36647. {
  36648. undoManager.perform (new CodeDocumentInsertAction (*this, text, insertPos));
  36649. }
  36650. else
  36651. {
  36652. Position pos (this, insertPos);
  36653. const int firstAffectedLine = pos.getLineNumber();
  36654. int lastAffectedLine = firstAffectedLine + 1;
  36655. CodeDocumentLine* const firstLine = lines [firstAffectedLine];
  36656. String textInsideOriginalLine (text);
  36657. if (firstLine != 0)
  36658. {
  36659. const int index = pos.getIndexInLine();
  36660. textInsideOriginalLine = firstLine->line.substring (0, index)
  36661. + textInsideOriginalLine
  36662. + firstLine->line.substring (index);
  36663. }
  36664. maximumLineLength = -1;
  36665. Array <CodeDocumentLine*> newLines;
  36666. CodeDocumentLine::createLines (newLines, textInsideOriginalLine);
  36667. jassert (newLines.size() > 0);
  36668. CodeDocumentLine* const newFirstLine = newLines.getUnchecked (0);
  36669. newFirstLine->lineStartInFile = firstLine != 0 ? firstLine->lineStartInFile : 0;
  36670. lines.set (firstAffectedLine, newFirstLine);
  36671. if (newLines.size() > 1)
  36672. {
  36673. for (int i = 1; i < newLines.size(); ++i)
  36674. {
  36675. CodeDocumentLine* const l = newLines.getUnchecked (i);
  36676. lines.insert (firstAffectedLine + i, l);
  36677. }
  36678. lastAffectedLine = lines.size();
  36679. }
  36680. int i, lineStart = newFirstLine->lineStartInFile;
  36681. for (i = firstAffectedLine; i < lines.size(); ++i)
  36682. {
  36683. CodeDocumentLine* const l = lines.getUnchecked (i);
  36684. l->lineStartInFile = lineStart;
  36685. lineStart += l->lineLength;
  36686. }
  36687. checkLastLineStatus();
  36688. const int newTextLength = text.length();
  36689. for (i = 0; i < positionsToMaintain.size(); ++i)
  36690. {
  36691. CodeDocument::Position* const p = positionsToMaintain.getUnchecked(i);
  36692. if (p->getPosition() >= insertPos)
  36693. p->setPosition (p->getPosition() + newTextLength);
  36694. }
  36695. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36696. }
  36697. }
  36698. class CodeDocumentDeleteAction : public UndoableAction
  36699. {
  36700. CodeDocument& owner;
  36701. int startPos, endPos;
  36702. String removedText;
  36703. CodeDocumentDeleteAction (const CodeDocumentDeleteAction&);
  36704. CodeDocumentDeleteAction& operator= (const CodeDocumentDeleteAction&);
  36705. public:
  36706. CodeDocumentDeleteAction (CodeDocument& owner_, const int startPos_, const int endPos_) throw()
  36707. : owner (owner_),
  36708. startPos (startPos_),
  36709. endPos (endPos_)
  36710. {
  36711. removedText = owner.getTextBetween (CodeDocument::Position (&owner, startPos),
  36712. CodeDocument::Position (&owner, endPos));
  36713. }
  36714. ~CodeDocumentDeleteAction() {}
  36715. bool perform()
  36716. {
  36717. owner.currentActionIndex++;
  36718. owner.remove (startPos, endPos, false);
  36719. return true;
  36720. }
  36721. bool undo()
  36722. {
  36723. owner.currentActionIndex--;
  36724. owner.insert (removedText, startPos, false);
  36725. return true;
  36726. }
  36727. int getSizeInUnits() { return removedText.length() + 32; }
  36728. };
  36729. void CodeDocument::remove (const int startPos, const int endPos, const bool undoable)
  36730. {
  36731. if (endPos <= startPos)
  36732. return;
  36733. if (undoable)
  36734. {
  36735. undoManager.perform (new CodeDocumentDeleteAction (*this, startPos, endPos));
  36736. }
  36737. else
  36738. {
  36739. Position startPosition (this, startPos);
  36740. Position endPosition (this, endPos);
  36741. maximumLineLength = -1;
  36742. const int firstAffectedLine = startPosition.getLineNumber();
  36743. const int endLine = endPosition.getLineNumber();
  36744. int lastAffectedLine = firstAffectedLine + 1;
  36745. CodeDocumentLine* const firstLine = lines.getUnchecked (firstAffectedLine);
  36746. if (firstAffectedLine == endLine)
  36747. {
  36748. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36749. + firstLine->line.substring (endPosition.getIndexInLine());
  36750. firstLine->updateLength();
  36751. }
  36752. else
  36753. {
  36754. lastAffectedLine = lines.size();
  36755. CodeDocumentLine* const lastLine = lines.getUnchecked (endLine);
  36756. jassert (lastLine != 0);
  36757. firstLine->line = firstLine->line.substring (0, startPosition.getIndexInLine())
  36758. + lastLine->line.substring (endPosition.getIndexInLine());
  36759. firstLine->updateLength();
  36760. int numLinesToRemove = endLine - firstAffectedLine;
  36761. lines.removeRange (firstAffectedLine + 1, numLinesToRemove);
  36762. }
  36763. int i;
  36764. for (i = firstAffectedLine + 1; i < lines.size(); ++i)
  36765. {
  36766. CodeDocumentLine* const l = lines.getUnchecked (i);
  36767. const CodeDocumentLine* const previousLine = lines.getUnchecked (i - 1);
  36768. l->lineStartInFile = previousLine->lineStartInFile + previousLine->lineLength;
  36769. }
  36770. checkLastLineStatus();
  36771. const int totalChars = getNumCharacters();
  36772. for (i = 0; i < positionsToMaintain.size(); ++i)
  36773. {
  36774. CodeDocument::Position* p = positionsToMaintain.getUnchecked(i);
  36775. if (p->getPosition() > startPosition.getPosition())
  36776. p->setPosition (jmax (startPos, p->getPosition() + startPos - endPos));
  36777. if (p->getPosition() > totalChars)
  36778. p->setPosition (totalChars);
  36779. }
  36780. sendListenerChangeMessage (firstAffectedLine, lastAffectedLine);
  36781. }
  36782. }
  36783. END_JUCE_NAMESPACE
  36784. /*** End of inlined file: juce_CodeDocument.cpp ***/
  36785. /*** Start of inlined file: juce_CodeEditorComponent.cpp ***/
  36786. BEGIN_JUCE_NAMESPACE
  36787. class CodeEditorComponent::CaretComponent : public Component,
  36788. public Timer
  36789. {
  36790. public:
  36791. CaretComponent (CodeEditorComponent& owner_)
  36792. : owner (owner_)
  36793. {
  36794. setAlwaysOnTop (true);
  36795. setInterceptsMouseClicks (false, false);
  36796. }
  36797. void paint (Graphics& g)
  36798. {
  36799. g.fillAll (findColour (CodeEditorComponent::caretColourId));
  36800. }
  36801. void timerCallback()
  36802. {
  36803. setVisible (shouldBeShown() && ! isVisible());
  36804. }
  36805. void updatePosition()
  36806. {
  36807. startTimer (400);
  36808. setVisible (shouldBeShown());
  36809. setBounds (owner.getCharacterBounds (owner.getCaretPos()).withWidth (2));
  36810. }
  36811. private:
  36812. CodeEditorComponent& owner;
  36813. CaretComponent (const CaretComponent&);
  36814. CaretComponent& operator= (const CaretComponent&);
  36815. bool shouldBeShown() const { return owner.hasKeyboardFocus (true); }
  36816. };
  36817. class CodeEditorComponent::CodeEditorLine
  36818. {
  36819. public:
  36820. CodeEditorLine() throw()
  36821. : highlightColumnStart (0), highlightColumnEnd (0)
  36822. {
  36823. }
  36824. ~CodeEditorLine() throw()
  36825. {
  36826. }
  36827. bool update (CodeDocument& document, int lineNum,
  36828. CodeDocument::Iterator& source,
  36829. CodeTokeniser* analyser, const int spacesPerTab,
  36830. const CodeDocument::Position& selectionStart,
  36831. const CodeDocument::Position& selectionEnd)
  36832. {
  36833. Array <SyntaxToken> newTokens;
  36834. newTokens.ensureStorageAllocated (8);
  36835. if (analyser == 0)
  36836. {
  36837. newTokens.add (SyntaxToken (document.getLine (lineNum), -1));
  36838. }
  36839. else if (lineNum < document.getNumLines())
  36840. {
  36841. const CodeDocument::Position pos (&document, lineNum, 0);
  36842. createTokens (pos.getPosition(), pos.getLineText(),
  36843. source, analyser, newTokens);
  36844. }
  36845. replaceTabsWithSpaces (newTokens, spacesPerTab);
  36846. int newHighlightStart = 0;
  36847. int newHighlightEnd = 0;
  36848. if (selectionStart.getLineNumber() <= lineNum && selectionEnd.getLineNumber() >= lineNum)
  36849. {
  36850. const String line (document.getLine (lineNum));
  36851. CodeDocument::Position lineStart (&document, lineNum, 0), lineEnd (&document, lineNum + 1, 0);
  36852. newHighlightStart = indexToColumn (jmax (0, selectionStart.getPosition() - lineStart.getPosition()),
  36853. line, spacesPerTab);
  36854. newHighlightEnd = indexToColumn (jmin (lineEnd.getPosition() - lineStart.getPosition(), selectionEnd.getPosition() - lineStart.getPosition()),
  36855. line, spacesPerTab);
  36856. }
  36857. if (newHighlightStart != highlightColumnStart || newHighlightEnd != highlightColumnEnd)
  36858. {
  36859. highlightColumnStart = newHighlightStart;
  36860. highlightColumnEnd = newHighlightEnd;
  36861. }
  36862. else
  36863. {
  36864. if (tokens.size() == newTokens.size())
  36865. {
  36866. bool allTheSame = true;
  36867. for (int i = newTokens.size(); --i >= 0;)
  36868. {
  36869. if (tokens.getReference(i) != newTokens.getReference(i))
  36870. {
  36871. allTheSame = false;
  36872. break;
  36873. }
  36874. }
  36875. if (allTheSame)
  36876. return false;
  36877. }
  36878. }
  36879. tokens.swapWithArray (newTokens);
  36880. return true;
  36881. }
  36882. void draw (CodeEditorComponent& owner, Graphics& g, const Font& font,
  36883. float x, const int y, const int baselineOffset, const int lineHeight,
  36884. const Colour& highlightColour) const
  36885. {
  36886. if (highlightColumnStart < highlightColumnEnd)
  36887. {
  36888. g.setColour (highlightColour);
  36889. g.fillRect (roundToInt (x + highlightColumnStart * owner.getCharWidth()), y,
  36890. roundToInt ((highlightColumnEnd - highlightColumnStart) * owner.getCharWidth()), lineHeight);
  36891. }
  36892. int lastType = std::numeric_limits<int>::min();
  36893. for (int i = 0; i < tokens.size(); ++i)
  36894. {
  36895. SyntaxToken& token = tokens.getReference(i);
  36896. if (lastType != token.tokenType)
  36897. {
  36898. lastType = token.tokenType;
  36899. g.setColour (owner.getColourForTokenType (lastType));
  36900. }
  36901. g.drawSingleLineText (token.text, roundToInt (x), y + baselineOffset);
  36902. if (i < tokens.size() - 1)
  36903. {
  36904. if (token.width < 0)
  36905. token.width = font.getStringWidthFloat (token.text);
  36906. x += token.width;
  36907. }
  36908. }
  36909. }
  36910. private:
  36911. struct SyntaxToken
  36912. {
  36913. String text;
  36914. int tokenType;
  36915. float width;
  36916. SyntaxToken (const String& text_, const int type) throw()
  36917. : text (text_), tokenType (type), width (-1.0f)
  36918. {
  36919. }
  36920. bool operator!= (const SyntaxToken& other) const throw()
  36921. {
  36922. return text != other.text || tokenType != other.tokenType;
  36923. }
  36924. };
  36925. Array <SyntaxToken> tokens;
  36926. int highlightColumnStart, highlightColumnEnd;
  36927. static void createTokens (int startPosition, const String& lineText,
  36928. CodeDocument::Iterator& source,
  36929. CodeTokeniser* analyser,
  36930. Array <SyntaxToken>& newTokens)
  36931. {
  36932. CodeDocument::Iterator lastIterator (source);
  36933. const int lineLength = lineText.length();
  36934. for (;;)
  36935. {
  36936. int tokenType = analyser->readNextToken (source);
  36937. int tokenStart = lastIterator.getPosition();
  36938. int tokenEnd = source.getPosition();
  36939. if (tokenEnd <= tokenStart)
  36940. break;
  36941. tokenEnd -= startPosition;
  36942. if (tokenEnd > 0)
  36943. {
  36944. tokenStart -= startPosition;
  36945. newTokens.add (SyntaxToken (lineText.substring (jmax (0, tokenStart), tokenEnd),
  36946. tokenType));
  36947. if (tokenEnd >= lineLength)
  36948. break;
  36949. }
  36950. lastIterator = source;
  36951. }
  36952. source = lastIterator;
  36953. }
  36954. static void replaceTabsWithSpaces (Array <SyntaxToken>& tokens, const int spacesPerTab)
  36955. {
  36956. int x = 0;
  36957. for (int i = 0; i < tokens.size(); ++i)
  36958. {
  36959. SyntaxToken& t = tokens.getReference(i);
  36960. for (;;)
  36961. {
  36962. int tabPos = t.text.indexOfChar ('\t');
  36963. if (tabPos < 0)
  36964. break;
  36965. const int spacesNeeded = spacesPerTab - ((tabPos + x) % spacesPerTab);
  36966. t.text = t.text.replaceSection (tabPos, 1, String::repeatedString (" ", spacesNeeded));
  36967. }
  36968. x += t.text.length();
  36969. }
  36970. }
  36971. int indexToColumn (int index, const String& line, int spacesPerTab) const throw()
  36972. {
  36973. jassert (index <= line.length());
  36974. int col = 0;
  36975. for (int i = 0; i < index; ++i)
  36976. {
  36977. if (line[i] != '\t')
  36978. ++col;
  36979. else
  36980. col += spacesPerTab - (col % spacesPerTab);
  36981. }
  36982. return col;
  36983. }
  36984. };
  36985. CodeEditorComponent::CodeEditorComponent (CodeDocument& document_,
  36986. CodeTokeniser* const codeTokeniser_)
  36987. : document (document_),
  36988. firstLineOnScreen (0),
  36989. gutter (5),
  36990. spacesPerTab (4),
  36991. lineHeight (0),
  36992. linesOnScreen (0),
  36993. columnsOnScreen (0),
  36994. scrollbarThickness (16),
  36995. columnToTryToMaintain (-1),
  36996. useSpacesForTabs (false),
  36997. xOffset (0),
  36998. verticalScrollBar (true),
  36999. horizontalScrollBar (false),
  37000. codeTokeniser (codeTokeniser_)
  37001. {
  37002. caretPos = CodeDocument::Position (&document_, 0, 0);
  37003. caretPos.setPositionMaintained (true);
  37004. selectionStart = CodeDocument::Position (&document_, 0, 0);
  37005. selectionStart.setPositionMaintained (true);
  37006. selectionEnd = CodeDocument::Position (&document_, 0, 0);
  37007. selectionEnd.setPositionMaintained (true);
  37008. setOpaque (true);
  37009. setMouseCursor (MouseCursor (MouseCursor::IBeamCursor));
  37010. setWantsKeyboardFocus (true);
  37011. addAndMakeVisible (&verticalScrollBar);
  37012. verticalScrollBar.setSingleStepSize (1.0);
  37013. addAndMakeVisible (&horizontalScrollBar);
  37014. horizontalScrollBar.setSingleStepSize (1.0);
  37015. addAndMakeVisible (caret = new CaretComponent (*this));
  37016. Font f (12.0f);
  37017. f.setTypefaceName (Font::getDefaultMonospacedFontName());
  37018. setFont (f);
  37019. resetToDefaultColours();
  37020. verticalScrollBar.addListener (this);
  37021. horizontalScrollBar.addListener (this);
  37022. document.addListener (this);
  37023. }
  37024. CodeEditorComponent::~CodeEditorComponent()
  37025. {
  37026. document.removeListener (this);
  37027. }
  37028. void CodeEditorComponent::loadContent (const String& newContent)
  37029. {
  37030. clearCachedIterators (0);
  37031. document.replaceAllContent (newContent);
  37032. document.clearUndoHistory();
  37033. document.setSavePoint();
  37034. caretPos.setPosition (0);
  37035. selectionStart.setPosition (0);
  37036. selectionEnd.setPosition (0);
  37037. scrollToLine (0);
  37038. }
  37039. bool CodeEditorComponent::isTextInputActive() const
  37040. {
  37041. return true;
  37042. }
  37043. void CodeEditorComponent::codeDocumentChanged (const CodeDocument::Position& affectedTextStart,
  37044. const CodeDocument::Position& affectedTextEnd)
  37045. {
  37046. clearCachedIterators (affectedTextStart.getLineNumber());
  37047. triggerAsyncUpdate();
  37048. caret->updatePosition();
  37049. columnToTryToMaintain = -1;
  37050. if (affectedTextEnd.getPosition() >= selectionStart.getPosition()
  37051. && affectedTextStart.getPosition() <= selectionEnd.getPosition())
  37052. deselectAll();
  37053. if (caretPos.getPosition() > affectedTextEnd.getPosition()
  37054. || caretPos.getPosition() < affectedTextStart.getPosition())
  37055. moveCaretTo (affectedTextStart, false);
  37056. updateScrollBars();
  37057. }
  37058. void CodeEditorComponent::resized()
  37059. {
  37060. linesOnScreen = (getHeight() - scrollbarThickness) / lineHeight;
  37061. columnsOnScreen = (int) ((getWidth() - scrollbarThickness) / charWidth);
  37062. lines.clear();
  37063. rebuildLineTokens();
  37064. caret->updatePosition();
  37065. verticalScrollBar.setBounds (getWidth() - scrollbarThickness, 0, scrollbarThickness, getHeight() - scrollbarThickness);
  37066. horizontalScrollBar.setBounds (gutter, getHeight() - scrollbarThickness, getWidth() - scrollbarThickness - gutter, scrollbarThickness);
  37067. updateScrollBars();
  37068. }
  37069. void CodeEditorComponent::paint (Graphics& g)
  37070. {
  37071. handleUpdateNowIfNeeded();
  37072. g.fillAll (findColour (CodeEditorComponent::backgroundColourId));
  37073. g.reduceClipRegion (gutter, 0, verticalScrollBar.getX() - gutter, horizontalScrollBar.getY());
  37074. g.setFont (font);
  37075. const int baselineOffset = (int) font.getAscent();
  37076. const Colour defaultColour (findColour (CodeEditorComponent::defaultTextColourId));
  37077. const Colour highlightColour (findColour (CodeEditorComponent::highlightColourId));
  37078. const Rectangle<int> clip (g.getClipBounds());
  37079. const int firstLineToDraw = jmax (0, clip.getY() / lineHeight);
  37080. const int lastLineToDraw = jmin (lines.size(), clip.getBottom() / lineHeight + 1);
  37081. for (int j = firstLineToDraw; j < lastLineToDraw; ++j)
  37082. {
  37083. lines.getUnchecked(j)->draw (*this, g, font,
  37084. (float) (gutter - xOffset * charWidth),
  37085. lineHeight * j, baselineOffset, lineHeight,
  37086. highlightColour);
  37087. }
  37088. }
  37089. void CodeEditorComponent::setScrollbarThickness (const int thickness)
  37090. {
  37091. if (scrollbarThickness != thickness)
  37092. {
  37093. scrollbarThickness = thickness;
  37094. resized();
  37095. }
  37096. }
  37097. void CodeEditorComponent::handleAsyncUpdate()
  37098. {
  37099. rebuildLineTokens();
  37100. }
  37101. void CodeEditorComponent::rebuildLineTokens()
  37102. {
  37103. cancelPendingUpdate();
  37104. const int numNeeded = linesOnScreen + 1;
  37105. int minLineToRepaint = numNeeded;
  37106. int maxLineToRepaint = 0;
  37107. if (numNeeded != lines.size())
  37108. {
  37109. lines.clear();
  37110. for (int i = numNeeded; --i >= 0;)
  37111. lines.add (new CodeEditorLine());
  37112. minLineToRepaint = 0;
  37113. maxLineToRepaint = numNeeded;
  37114. }
  37115. jassert (numNeeded == lines.size());
  37116. CodeDocument::Iterator source (&document);
  37117. getIteratorForPosition (CodeDocument::Position (&document, firstLineOnScreen, 0).getPosition(), source);
  37118. for (int i = 0; i < numNeeded; ++i)
  37119. {
  37120. CodeEditorLine* const line = lines.getUnchecked(i);
  37121. if (line->update (document, firstLineOnScreen + i, source, codeTokeniser, spacesPerTab,
  37122. selectionStart, selectionEnd))
  37123. {
  37124. minLineToRepaint = jmin (minLineToRepaint, i);
  37125. maxLineToRepaint = jmax (maxLineToRepaint, i);
  37126. }
  37127. }
  37128. if (minLineToRepaint <= maxLineToRepaint)
  37129. {
  37130. repaint (gutter, lineHeight * minLineToRepaint - 1,
  37131. verticalScrollBar.getX() - gutter,
  37132. lineHeight * (1 + maxLineToRepaint - minLineToRepaint) + 2);
  37133. }
  37134. }
  37135. void CodeEditorComponent::moveCaretTo (const CodeDocument::Position& newPos, const bool highlighting)
  37136. {
  37137. caretPos = newPos;
  37138. columnToTryToMaintain = -1;
  37139. if (highlighting)
  37140. {
  37141. if (dragType == notDragging)
  37142. {
  37143. if (abs (caretPos.getPosition() - selectionStart.getPosition())
  37144. < abs (caretPos.getPosition() - selectionEnd.getPosition()))
  37145. dragType = draggingSelectionStart;
  37146. else
  37147. dragType = draggingSelectionEnd;
  37148. }
  37149. if (dragType == draggingSelectionStart)
  37150. {
  37151. selectionStart = caretPos;
  37152. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37153. {
  37154. const CodeDocument::Position temp (selectionStart);
  37155. selectionStart = selectionEnd;
  37156. selectionEnd = temp;
  37157. dragType = draggingSelectionEnd;
  37158. }
  37159. }
  37160. else
  37161. {
  37162. selectionEnd = caretPos;
  37163. if (selectionEnd.getPosition() < selectionStart.getPosition())
  37164. {
  37165. const CodeDocument::Position temp (selectionStart);
  37166. selectionStart = selectionEnd;
  37167. selectionEnd = temp;
  37168. dragType = draggingSelectionStart;
  37169. }
  37170. }
  37171. triggerAsyncUpdate();
  37172. }
  37173. else
  37174. {
  37175. deselectAll();
  37176. }
  37177. caret->updatePosition();
  37178. scrollToKeepCaretOnScreen();
  37179. updateScrollBars();
  37180. }
  37181. void CodeEditorComponent::deselectAll()
  37182. {
  37183. if (selectionStart != selectionEnd)
  37184. triggerAsyncUpdate();
  37185. selectionStart = caretPos;
  37186. selectionEnd = caretPos;
  37187. }
  37188. void CodeEditorComponent::updateScrollBars()
  37189. {
  37190. verticalScrollBar.setRangeLimits (0, jmax (document.getNumLines(), firstLineOnScreen + linesOnScreen));
  37191. verticalScrollBar.setCurrentRange (firstLineOnScreen, linesOnScreen);
  37192. horizontalScrollBar.setRangeLimits (0, jmax ((double) document.getMaximumLineLength(), xOffset + columnsOnScreen));
  37193. horizontalScrollBar.setCurrentRange (xOffset, columnsOnScreen);
  37194. }
  37195. void CodeEditorComponent::scrollToLineInternal (int newFirstLineOnScreen)
  37196. {
  37197. newFirstLineOnScreen = jlimit (0, jmax (0, document.getNumLines() - 1),
  37198. newFirstLineOnScreen);
  37199. if (newFirstLineOnScreen != firstLineOnScreen)
  37200. {
  37201. firstLineOnScreen = newFirstLineOnScreen;
  37202. caret->updatePosition();
  37203. updateCachedIterators (firstLineOnScreen);
  37204. triggerAsyncUpdate();
  37205. }
  37206. }
  37207. void CodeEditorComponent::scrollToColumnInternal (double column)
  37208. {
  37209. const double newOffset = jlimit (0.0, document.getMaximumLineLength() + 3.0, column);
  37210. if (xOffset != newOffset)
  37211. {
  37212. xOffset = newOffset;
  37213. caret->updatePosition();
  37214. repaint();
  37215. }
  37216. }
  37217. void CodeEditorComponent::scrollToLine (int newFirstLineOnScreen)
  37218. {
  37219. scrollToLineInternal (newFirstLineOnScreen);
  37220. updateScrollBars();
  37221. }
  37222. void CodeEditorComponent::scrollToColumn (int newFirstColumnOnScreen)
  37223. {
  37224. scrollToColumnInternal (newFirstColumnOnScreen);
  37225. updateScrollBars();
  37226. }
  37227. void CodeEditorComponent::scrollBy (int deltaLines)
  37228. {
  37229. scrollToLine (firstLineOnScreen + deltaLines);
  37230. }
  37231. void CodeEditorComponent::scrollToKeepCaretOnScreen()
  37232. {
  37233. if (caretPos.getLineNumber() < firstLineOnScreen)
  37234. scrollBy (caretPos.getLineNumber() - firstLineOnScreen);
  37235. else if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37236. scrollBy (caretPos.getLineNumber() - (firstLineOnScreen + linesOnScreen - 1));
  37237. const int column = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37238. if (column >= xOffset + columnsOnScreen - 1)
  37239. scrollToColumn (column + 1 - columnsOnScreen);
  37240. else if (column < xOffset)
  37241. scrollToColumn (column);
  37242. }
  37243. const Rectangle<int> CodeEditorComponent::getCharacterBounds (const CodeDocument::Position& pos) const
  37244. {
  37245. return Rectangle<int> (roundToInt ((gutter - xOffset * charWidth) + indexToColumn (pos.getLineNumber(), pos.getIndexInLine()) * charWidth),
  37246. (pos.getLineNumber() - firstLineOnScreen) * lineHeight,
  37247. roundToInt (charWidth),
  37248. lineHeight);
  37249. }
  37250. const CodeDocument::Position CodeEditorComponent::getPositionAt (int x, int y)
  37251. {
  37252. const int line = y / lineHeight + firstLineOnScreen;
  37253. const int column = roundToInt ((x - (gutter - xOffset * charWidth)) / charWidth);
  37254. const int index = columnToIndex (line, column);
  37255. return CodeDocument::Position (&document, line, index);
  37256. }
  37257. void CodeEditorComponent::insertTextAtCaret (const String& newText)
  37258. {
  37259. document.deleteSection (selectionStart, selectionEnd);
  37260. if (newText.isNotEmpty())
  37261. document.insertText (caretPos, newText);
  37262. scrollToKeepCaretOnScreen();
  37263. }
  37264. void CodeEditorComponent::insertTabAtCaret()
  37265. {
  37266. if (CharacterFunctions::isWhitespace (caretPos.getCharacter())
  37267. && caretPos.getLineNumber() == caretPos.movedBy (1).getLineNumber())
  37268. {
  37269. moveCaretTo (document.findWordBreakAfter (caretPos), false);
  37270. }
  37271. if (useSpacesForTabs)
  37272. {
  37273. const int caretCol = indexToColumn (caretPos.getLineNumber(), caretPos.getIndexInLine());
  37274. const int spacesNeeded = spacesPerTab - (caretCol % spacesPerTab);
  37275. insertTextAtCaret (String::repeatedString (" ", spacesNeeded));
  37276. }
  37277. else
  37278. {
  37279. insertTextAtCaret ("\t");
  37280. }
  37281. }
  37282. void CodeEditorComponent::cut()
  37283. {
  37284. insertTextAtCaret (String::empty);
  37285. }
  37286. void CodeEditorComponent::copy()
  37287. {
  37288. newTransaction();
  37289. const String selection (document.getTextBetween (selectionStart, selectionEnd));
  37290. if (selection.isNotEmpty())
  37291. SystemClipboard::copyTextToClipboard (selection);
  37292. }
  37293. void CodeEditorComponent::copyThenCut()
  37294. {
  37295. copy();
  37296. cut();
  37297. newTransaction();
  37298. }
  37299. void CodeEditorComponent::paste()
  37300. {
  37301. newTransaction();
  37302. const String clip (SystemClipboard::getTextFromClipboard());
  37303. if (clip.isNotEmpty())
  37304. insertTextAtCaret (clip);
  37305. newTransaction();
  37306. }
  37307. void CodeEditorComponent::cursorLeft (const bool moveInWholeWordSteps, const bool selecting)
  37308. {
  37309. newTransaction();
  37310. if (moveInWholeWordSteps)
  37311. moveCaretTo (document.findWordBreakBefore (caretPos), selecting);
  37312. else
  37313. moveCaretTo (caretPos.movedBy (-1), selecting);
  37314. }
  37315. void CodeEditorComponent::cursorRight (const bool moveInWholeWordSteps, const bool selecting)
  37316. {
  37317. newTransaction();
  37318. if (moveInWholeWordSteps)
  37319. moveCaretTo (document.findWordBreakAfter (caretPos), selecting);
  37320. else
  37321. moveCaretTo (caretPos.movedBy (1), selecting);
  37322. }
  37323. void CodeEditorComponent::moveLineDelta (const int delta, const bool selecting)
  37324. {
  37325. CodeDocument::Position pos (caretPos);
  37326. const int newLineNum = pos.getLineNumber() + delta;
  37327. if (columnToTryToMaintain < 0)
  37328. columnToTryToMaintain = indexToColumn (pos.getLineNumber(), pos.getIndexInLine());
  37329. pos.setLineAndIndex (newLineNum, columnToIndex (newLineNum, columnToTryToMaintain));
  37330. const int colToMaintain = columnToTryToMaintain;
  37331. moveCaretTo (pos, selecting);
  37332. columnToTryToMaintain = colToMaintain;
  37333. }
  37334. void CodeEditorComponent::cursorDown (const bool selecting)
  37335. {
  37336. newTransaction();
  37337. if (caretPos.getLineNumber() == document.getNumLines() - 1)
  37338. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37339. else
  37340. moveLineDelta (1, selecting);
  37341. }
  37342. void CodeEditorComponent::cursorUp (const bool selecting)
  37343. {
  37344. newTransaction();
  37345. if (caretPos.getLineNumber() == 0)
  37346. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37347. else
  37348. moveLineDelta (-1, selecting);
  37349. }
  37350. void CodeEditorComponent::pageDown (const bool selecting)
  37351. {
  37352. newTransaction();
  37353. scrollBy (jlimit (0, linesOnScreen, 1 + document.getNumLines() - firstLineOnScreen - linesOnScreen));
  37354. moveLineDelta (linesOnScreen, selecting);
  37355. }
  37356. void CodeEditorComponent::pageUp (const bool selecting)
  37357. {
  37358. newTransaction();
  37359. scrollBy (-linesOnScreen);
  37360. moveLineDelta (-linesOnScreen, selecting);
  37361. }
  37362. void CodeEditorComponent::scrollUp()
  37363. {
  37364. newTransaction();
  37365. scrollBy (1);
  37366. if (caretPos.getLineNumber() < firstLineOnScreen)
  37367. moveLineDelta (1, false);
  37368. }
  37369. void CodeEditorComponent::scrollDown()
  37370. {
  37371. newTransaction();
  37372. scrollBy (-1);
  37373. if (caretPos.getLineNumber() >= firstLineOnScreen + linesOnScreen)
  37374. moveLineDelta (-1, false);
  37375. }
  37376. void CodeEditorComponent::goToStartOfDocument (const bool selecting)
  37377. {
  37378. newTransaction();
  37379. moveCaretTo (CodeDocument::Position (&document, 0, 0), selecting);
  37380. }
  37381. namespace CodeEditorHelpers
  37382. {
  37383. int findFirstNonWhitespaceChar (const String& line) throw()
  37384. {
  37385. const int len = line.length();
  37386. for (int i = 0; i < len; ++i)
  37387. if (! CharacterFunctions::isWhitespace (line [i]))
  37388. return i;
  37389. return 0;
  37390. }
  37391. }
  37392. void CodeEditorComponent::goToStartOfLine (const bool selecting)
  37393. {
  37394. newTransaction();
  37395. int index = CodeEditorHelpers::findFirstNonWhitespaceChar (caretPos.getLineText());
  37396. if (index >= caretPos.getIndexInLine() && caretPos.getIndexInLine() > 0)
  37397. index = 0;
  37398. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), index), selecting);
  37399. }
  37400. void CodeEditorComponent::goToEndOfDocument (const bool selecting)
  37401. {
  37402. newTransaction();
  37403. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), selecting);
  37404. }
  37405. void CodeEditorComponent::goToEndOfLine (const bool selecting)
  37406. {
  37407. newTransaction();
  37408. moveCaretTo (CodeDocument::Position (&document, caretPos.getLineNumber(), std::numeric_limits<int>::max()), selecting);
  37409. }
  37410. void CodeEditorComponent::backspace (const bool moveInWholeWordSteps)
  37411. {
  37412. if (moveInWholeWordSteps)
  37413. {
  37414. cut(); // in case something is already highlighted
  37415. moveCaretTo (document.findWordBreakBefore (caretPos), true);
  37416. }
  37417. else
  37418. {
  37419. if (selectionStart == selectionEnd)
  37420. selectionStart.moveBy (-1);
  37421. }
  37422. cut();
  37423. }
  37424. void CodeEditorComponent::deleteForward (const bool moveInWholeWordSteps)
  37425. {
  37426. if (moveInWholeWordSteps)
  37427. {
  37428. cut(); // in case something is already highlighted
  37429. moveCaretTo (document.findWordBreakAfter (caretPos), true);
  37430. }
  37431. else
  37432. {
  37433. if (selectionStart == selectionEnd)
  37434. selectionEnd.moveBy (1);
  37435. else
  37436. newTransaction();
  37437. }
  37438. cut();
  37439. }
  37440. void CodeEditorComponent::selectAll()
  37441. {
  37442. newTransaction();
  37443. moveCaretTo (CodeDocument::Position (&document, std::numeric_limits<int>::max(), std::numeric_limits<int>::max()), false);
  37444. moveCaretTo (CodeDocument::Position (&document, 0, 0), true);
  37445. }
  37446. void CodeEditorComponent::undo()
  37447. {
  37448. document.undo();
  37449. scrollToKeepCaretOnScreen();
  37450. }
  37451. void CodeEditorComponent::redo()
  37452. {
  37453. document.redo();
  37454. scrollToKeepCaretOnScreen();
  37455. }
  37456. void CodeEditorComponent::newTransaction()
  37457. {
  37458. document.newTransaction();
  37459. startTimer (600);
  37460. }
  37461. void CodeEditorComponent::timerCallback()
  37462. {
  37463. newTransaction();
  37464. }
  37465. const Range<int> CodeEditorComponent::getHighlightedRegion() const
  37466. {
  37467. return Range<int> (selectionStart.getPosition(), selectionEnd.getPosition());
  37468. }
  37469. void CodeEditorComponent::setHighlightedRegion (const Range<int>& newRange)
  37470. {
  37471. moveCaretTo (CodeDocument::Position (&document, newRange.getStart()), false);
  37472. moveCaretTo (CodeDocument::Position (&document, newRange.getEnd()), true);
  37473. }
  37474. const String CodeEditorComponent::getTextInRange (const Range<int>& range) const
  37475. {
  37476. return document.getTextBetween (CodeDocument::Position (&document, range.getStart()),
  37477. CodeDocument::Position (&document, range.getEnd()));
  37478. }
  37479. bool CodeEditorComponent::keyPressed (const KeyPress& key)
  37480. {
  37481. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  37482. const bool shiftDown = key.getModifiers().isShiftDown();
  37483. if (key.isKeyCode (KeyPress::leftKey))
  37484. {
  37485. cursorLeft (moveInWholeWordSteps, shiftDown);
  37486. }
  37487. else if (key.isKeyCode (KeyPress::rightKey))
  37488. {
  37489. cursorRight (moveInWholeWordSteps, shiftDown);
  37490. }
  37491. else if (key.isKeyCode (KeyPress::upKey))
  37492. {
  37493. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37494. scrollDown();
  37495. #if JUCE_MAC
  37496. else if (key.getModifiers().isCommandDown())
  37497. goToStartOfDocument (shiftDown);
  37498. #endif
  37499. else
  37500. cursorUp (shiftDown);
  37501. }
  37502. else if (key.isKeyCode (KeyPress::downKey))
  37503. {
  37504. if (key.getModifiers().isCtrlDown() && ! shiftDown)
  37505. scrollUp();
  37506. #if JUCE_MAC
  37507. else if (key.getModifiers().isCommandDown())
  37508. goToEndOfDocument (shiftDown);
  37509. #endif
  37510. else
  37511. cursorDown (shiftDown);
  37512. }
  37513. else if (key.isKeyCode (KeyPress::pageDownKey))
  37514. {
  37515. pageDown (shiftDown);
  37516. }
  37517. else if (key.isKeyCode (KeyPress::pageUpKey))
  37518. {
  37519. pageUp (shiftDown);
  37520. }
  37521. else if (key.isKeyCode (KeyPress::homeKey))
  37522. {
  37523. if (moveInWholeWordSteps)
  37524. goToStartOfDocument (shiftDown);
  37525. else
  37526. goToStartOfLine (shiftDown);
  37527. }
  37528. else if (key.isKeyCode (KeyPress::endKey))
  37529. {
  37530. if (moveInWholeWordSteps)
  37531. goToEndOfDocument (shiftDown);
  37532. else
  37533. goToEndOfLine (shiftDown);
  37534. }
  37535. else if (key.isKeyCode (KeyPress::backspaceKey))
  37536. {
  37537. backspace (moveInWholeWordSteps);
  37538. }
  37539. else if (key.isKeyCode (KeyPress::deleteKey))
  37540. {
  37541. deleteForward (moveInWholeWordSteps);
  37542. }
  37543. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0))
  37544. {
  37545. copy();
  37546. }
  37547. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  37548. {
  37549. copyThenCut();
  37550. }
  37551. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0))
  37552. {
  37553. paste();
  37554. }
  37555. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  37556. {
  37557. undo();
  37558. }
  37559. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0)
  37560. || key == KeyPress ('z', ModifierKeys::commandModifier | ModifierKeys::shiftModifier, 0))
  37561. {
  37562. redo();
  37563. }
  37564. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  37565. {
  37566. selectAll();
  37567. }
  37568. else if (key == KeyPress::tabKey || key.getTextCharacter() == '\t')
  37569. {
  37570. insertTabAtCaret();
  37571. }
  37572. else if (key == KeyPress::returnKey)
  37573. {
  37574. newTransaction();
  37575. insertTextAtCaret (document.getNewLineCharacters());
  37576. }
  37577. else if (key.isKeyCode (KeyPress::escapeKey))
  37578. {
  37579. newTransaction();
  37580. }
  37581. else if (key.getTextCharacter() >= ' ')
  37582. {
  37583. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  37584. }
  37585. else
  37586. {
  37587. return false;
  37588. }
  37589. return true;
  37590. }
  37591. void CodeEditorComponent::mouseDown (const MouseEvent& e)
  37592. {
  37593. newTransaction();
  37594. dragType = notDragging;
  37595. if (! e.mods.isPopupMenu())
  37596. {
  37597. beginDragAutoRepeat (100);
  37598. moveCaretTo (getPositionAt (e.x, e.y), e.mods.isShiftDown());
  37599. }
  37600. else
  37601. {
  37602. /*PopupMenu m;
  37603. addPopupMenuItems (m, &e);
  37604. const int result = m.show();
  37605. if (result != 0)
  37606. performPopupMenuAction (result);
  37607. */
  37608. }
  37609. }
  37610. void CodeEditorComponent::mouseDrag (const MouseEvent& e)
  37611. {
  37612. if (! e.mods.isPopupMenu())
  37613. moveCaretTo (getPositionAt (e.x, e.y), true);
  37614. }
  37615. void CodeEditorComponent::mouseUp (const MouseEvent&)
  37616. {
  37617. newTransaction();
  37618. beginDragAutoRepeat (0);
  37619. dragType = notDragging;
  37620. }
  37621. void CodeEditorComponent::mouseDoubleClick (const MouseEvent& e)
  37622. {
  37623. CodeDocument::Position tokenStart (getPositionAt (e.x, e.y));
  37624. CodeDocument::Position tokenEnd (tokenStart);
  37625. if (e.getNumberOfClicks() > 2)
  37626. {
  37627. tokenStart.setLineAndIndex (tokenStart.getLineNumber(), 0);
  37628. tokenEnd.setLineAndIndex (tokenStart.getLineNumber() + 1, 0);
  37629. }
  37630. else
  37631. {
  37632. while (CharacterFunctions::isLetterOrDigit (tokenEnd.getCharacter()))
  37633. tokenEnd.moveBy (1);
  37634. tokenStart = tokenEnd;
  37635. while (tokenStart.getIndexInLine() > 0
  37636. && CharacterFunctions::isLetterOrDigit (tokenStart.movedBy (-1).getCharacter()))
  37637. tokenStart.moveBy (-1);
  37638. }
  37639. moveCaretTo (tokenEnd, false);
  37640. moveCaretTo (tokenStart, true);
  37641. }
  37642. void CodeEditorComponent::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  37643. {
  37644. if ((verticalScrollBar.isVisible() && wheelIncrementY != 0)
  37645. || (horizontalScrollBar.isVisible() && wheelIncrementX != 0))
  37646. {
  37647. verticalScrollBar.mouseWheelMove (e, 0, wheelIncrementY);
  37648. horizontalScrollBar.mouseWheelMove (e, wheelIncrementX, 0);
  37649. }
  37650. else
  37651. {
  37652. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  37653. }
  37654. }
  37655. void CodeEditorComponent::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  37656. {
  37657. if (scrollBarThatHasMoved == &verticalScrollBar)
  37658. scrollToLineInternal ((int) newRangeStart);
  37659. else
  37660. scrollToColumnInternal (newRangeStart);
  37661. }
  37662. void CodeEditorComponent::focusGained (FocusChangeType)
  37663. {
  37664. caret->updatePosition();
  37665. }
  37666. void CodeEditorComponent::focusLost (FocusChangeType)
  37667. {
  37668. caret->updatePosition();
  37669. }
  37670. void CodeEditorComponent::setTabSize (const int numSpaces, const bool insertSpaces)
  37671. {
  37672. useSpacesForTabs = insertSpaces;
  37673. if (spacesPerTab != numSpaces)
  37674. {
  37675. spacesPerTab = numSpaces;
  37676. triggerAsyncUpdate();
  37677. }
  37678. }
  37679. int CodeEditorComponent::indexToColumn (int lineNum, int index) const throw()
  37680. {
  37681. const String line (document.getLine (lineNum));
  37682. jassert (index <= line.length());
  37683. int col = 0;
  37684. for (int i = 0; i < index; ++i)
  37685. {
  37686. if (line[i] != '\t')
  37687. ++col;
  37688. else
  37689. col += getTabSize() - (col % getTabSize());
  37690. }
  37691. return col;
  37692. }
  37693. int CodeEditorComponent::columnToIndex (int lineNum, int column) const throw()
  37694. {
  37695. const String line (document.getLine (lineNum));
  37696. const int lineLength = line.length();
  37697. int i, col = 0;
  37698. for (i = 0; i < lineLength; ++i)
  37699. {
  37700. if (line[i] != '\t')
  37701. ++col;
  37702. else
  37703. col += getTabSize() - (col % getTabSize());
  37704. if (col > column)
  37705. break;
  37706. }
  37707. return i;
  37708. }
  37709. void CodeEditorComponent::setFont (const Font& newFont)
  37710. {
  37711. font = newFont;
  37712. charWidth = font.getStringWidthFloat ("0");
  37713. lineHeight = roundToInt (font.getHeight());
  37714. resized();
  37715. }
  37716. void CodeEditorComponent::resetToDefaultColours()
  37717. {
  37718. coloursForTokenCategories.clear();
  37719. if (codeTokeniser != 0)
  37720. {
  37721. for (int i = codeTokeniser->getTokenTypes().size(); --i >= 0;)
  37722. setColourForTokenType (i, codeTokeniser->getDefaultColour (i));
  37723. }
  37724. }
  37725. void CodeEditorComponent::setColourForTokenType (const int tokenType, const Colour& colour)
  37726. {
  37727. jassert (tokenType < 256);
  37728. while (coloursForTokenCategories.size() < tokenType)
  37729. coloursForTokenCategories.add (Colours::black);
  37730. coloursForTokenCategories.set (tokenType, colour);
  37731. repaint();
  37732. }
  37733. const Colour CodeEditorComponent::getColourForTokenType (const int tokenType) const
  37734. {
  37735. if (((unsigned int) tokenType) >= (unsigned int) coloursForTokenCategories.size())
  37736. return findColour (CodeEditorComponent::defaultTextColourId);
  37737. return coloursForTokenCategories.getReference (tokenType);
  37738. }
  37739. void CodeEditorComponent::clearCachedIterators (const int firstLineToBeInvalid)
  37740. {
  37741. int i;
  37742. for (i = cachedIterators.size(); --i >= 0;)
  37743. if (cachedIterators.getUnchecked (i)->getLine() < firstLineToBeInvalid)
  37744. break;
  37745. cachedIterators.removeRange (jmax (0, i - 1), cachedIterators.size());
  37746. }
  37747. void CodeEditorComponent::updateCachedIterators (int maxLineNum)
  37748. {
  37749. const int maxNumCachedPositions = 5000;
  37750. const int linesBetweenCachedSources = jmax (10, document.getNumLines() / maxNumCachedPositions);
  37751. if (cachedIterators.size() == 0)
  37752. cachedIterators.add (new CodeDocument::Iterator (&document));
  37753. if (codeTokeniser == 0)
  37754. return;
  37755. for (;;)
  37756. {
  37757. CodeDocument::Iterator* last = cachedIterators.getLast();
  37758. if (last->getLine() >= maxLineNum)
  37759. break;
  37760. CodeDocument::Iterator* t = new CodeDocument::Iterator (*last);
  37761. cachedIterators.add (t);
  37762. const int targetLine = last->getLine() + linesBetweenCachedSources;
  37763. for (;;)
  37764. {
  37765. codeTokeniser->readNextToken (*t);
  37766. if (t->getLine() >= targetLine)
  37767. break;
  37768. if (t->isEOF())
  37769. return;
  37770. }
  37771. }
  37772. }
  37773. void CodeEditorComponent::getIteratorForPosition (int position, CodeDocument::Iterator& source)
  37774. {
  37775. if (codeTokeniser == 0)
  37776. return;
  37777. for (int i = cachedIterators.size(); --i >= 0;)
  37778. {
  37779. CodeDocument::Iterator* t = cachedIterators.getUnchecked (i);
  37780. if (t->getPosition() <= position)
  37781. {
  37782. source = *t;
  37783. break;
  37784. }
  37785. }
  37786. while (source.getPosition() < position)
  37787. {
  37788. const CodeDocument::Iterator original (source);
  37789. codeTokeniser->readNextToken (source);
  37790. if (source.getPosition() > position || source.isEOF())
  37791. {
  37792. source = original;
  37793. break;
  37794. }
  37795. }
  37796. }
  37797. END_JUCE_NAMESPACE
  37798. /*** End of inlined file: juce_CodeEditorComponent.cpp ***/
  37799. /*** Start of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  37800. BEGIN_JUCE_NAMESPACE
  37801. CPlusPlusCodeTokeniser::CPlusPlusCodeTokeniser()
  37802. {
  37803. }
  37804. CPlusPlusCodeTokeniser::~CPlusPlusCodeTokeniser()
  37805. {
  37806. }
  37807. namespace CppTokeniser
  37808. {
  37809. static bool isIdentifierStart (const juce_wchar c) throw()
  37810. {
  37811. return CharacterFunctions::isLetter (c)
  37812. || c == '_' || c == '@';
  37813. }
  37814. static bool isIdentifierBody (const juce_wchar c) throw()
  37815. {
  37816. return CharacterFunctions::isLetterOrDigit (c)
  37817. || c == '_' || c == '@';
  37818. }
  37819. static bool isReservedKeyword (const juce_wchar* const token, const int tokenLength) throw()
  37820. {
  37821. static const juce_wchar* const keywords2Char[] =
  37822. { JUCE_T("if"), JUCE_T("do"), JUCE_T("or"), JUCE_T("id"), 0 };
  37823. static const juce_wchar* const keywords3Char[] =
  37824. { 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 };
  37825. static const juce_wchar* const keywords4Char[] =
  37826. { JUCE_T("bool"), JUCE_T("void"), JUCE_T("this"), JUCE_T("true"), JUCE_T("long"), JUCE_T("else"), JUCE_T("char"),
  37827. JUCE_T("enum"), JUCE_T("case"), JUCE_T("goto"), JUCE_T("auto"), 0 };
  37828. static const juce_wchar* const keywords5Char[] =
  37829. { JUCE_T("while"), JUCE_T("bitor"), JUCE_T("break"), JUCE_T("catch"), JUCE_T("class"), JUCE_T("compl"), JUCE_T("const"), JUCE_T("false"),
  37830. JUCE_T("float"), JUCE_T("short"), JUCE_T("throw"), JUCE_T("union"), JUCE_T("using"), JUCE_T("or_eq"), 0 };
  37831. static const juce_wchar* const keywords6Char[] =
  37832. { JUCE_T("return"), JUCE_T("struct"), JUCE_T("and_eq"), JUCE_T("bitand"), JUCE_T("delete"), JUCE_T("double"), JUCE_T("extern"),
  37833. JUCE_T("friend"), JUCE_T("inline"), JUCE_T("not_eq"), JUCE_T("public"), JUCE_T("sizeof"), JUCE_T("static"), JUCE_T("signed"),
  37834. JUCE_T("switch"), JUCE_T("typeid"), JUCE_T("wchar_t"), JUCE_T("xor_eq"), 0};
  37835. static const juce_wchar* const keywordsOther[] =
  37836. { JUCE_T("const_cast"), JUCE_T("continue"), JUCE_T("default"), JUCE_T("explicit"), JUCE_T("mutable"), JUCE_T("namespace"),
  37837. JUCE_T("operator"), JUCE_T("private"), JUCE_T("protected"), JUCE_T("register"), JUCE_T("reinterpret_cast"), JUCE_T("static_cast"),
  37838. JUCE_T("template"), JUCE_T("typedef"), JUCE_T("typename"), JUCE_T("unsigned"), JUCE_T("virtual"), JUCE_T("volatile"),
  37839. JUCE_T("@implementation"), JUCE_T("@interface"), JUCE_T("@end"), JUCE_T("@synthesize"), JUCE_T("@dynamic"), JUCE_T("@public"),
  37840. JUCE_T("@private"), JUCE_T("@property"), JUCE_T("@protected"), JUCE_T("@class"), 0 };
  37841. const juce_wchar* const* k;
  37842. switch (tokenLength)
  37843. {
  37844. case 2: k = keywords2Char; break;
  37845. case 3: k = keywords3Char; break;
  37846. case 4: k = keywords4Char; break;
  37847. case 5: k = keywords5Char; break;
  37848. case 6: k = keywords6Char; break;
  37849. default:
  37850. if (tokenLength < 2 || tokenLength > 16)
  37851. return false;
  37852. k = keywordsOther;
  37853. break;
  37854. }
  37855. int i = 0;
  37856. while (k[i] != 0)
  37857. {
  37858. if (k[i][0] == token[0] && CharacterFunctions::compare (k[i], token) == 0)
  37859. return true;
  37860. ++i;
  37861. }
  37862. return false;
  37863. }
  37864. static int parseIdentifier (CodeDocument::Iterator& source) throw()
  37865. {
  37866. int tokenLength = 0;
  37867. juce_wchar possibleIdentifier [19];
  37868. while (isIdentifierBody (source.peekNextChar()))
  37869. {
  37870. const juce_wchar c = source.nextChar();
  37871. if (tokenLength < numElementsInArray (possibleIdentifier) - 1)
  37872. possibleIdentifier [tokenLength] = c;
  37873. ++tokenLength;
  37874. }
  37875. if (tokenLength > 1 && tokenLength <= 16)
  37876. {
  37877. possibleIdentifier [tokenLength] = 0;
  37878. if (isReservedKeyword (possibleIdentifier, tokenLength))
  37879. return CPlusPlusCodeTokeniser::tokenType_builtInKeyword;
  37880. }
  37881. return CPlusPlusCodeTokeniser::tokenType_identifier;
  37882. }
  37883. static bool skipNumberSuffix (CodeDocument::Iterator& source)
  37884. {
  37885. const juce_wchar c = source.peekNextChar();
  37886. if (c == 'l' || c == 'L' || c == 'u' || c == 'U')
  37887. source.skip();
  37888. if (CharacterFunctions::isLetterOrDigit (source.peekNextChar()))
  37889. return false;
  37890. return true;
  37891. }
  37892. static bool isHexDigit (const juce_wchar c) throw()
  37893. {
  37894. return (c >= '0' && c <= '9')
  37895. || (c >= 'a' && c <= 'f')
  37896. || (c >= 'A' && c <= 'F');
  37897. }
  37898. static bool parseHexLiteral (CodeDocument::Iterator& source) throw()
  37899. {
  37900. if (source.nextChar() != '0')
  37901. return false;
  37902. juce_wchar c = source.nextChar();
  37903. if (c != 'x' && c != 'X')
  37904. return false;
  37905. int numDigits = 0;
  37906. while (isHexDigit (source.peekNextChar()))
  37907. {
  37908. ++numDigits;
  37909. source.skip();
  37910. }
  37911. if (numDigits == 0)
  37912. return false;
  37913. return skipNumberSuffix (source);
  37914. }
  37915. static bool isOctalDigit (const juce_wchar c) throw()
  37916. {
  37917. return c >= '0' && c <= '7';
  37918. }
  37919. static bool parseOctalLiteral (CodeDocument::Iterator& source) throw()
  37920. {
  37921. if (source.nextChar() != '0')
  37922. return false;
  37923. if (! isOctalDigit (source.nextChar()))
  37924. return false;
  37925. while (isOctalDigit (source.peekNextChar()))
  37926. source.skip();
  37927. return skipNumberSuffix (source);
  37928. }
  37929. static bool isDecimalDigit (const juce_wchar c) throw()
  37930. {
  37931. return c >= '0' && c <= '9';
  37932. }
  37933. static bool parseDecimalLiteral (CodeDocument::Iterator& source) throw()
  37934. {
  37935. int numChars = 0;
  37936. while (isDecimalDigit (source.peekNextChar()))
  37937. {
  37938. ++numChars;
  37939. source.skip();
  37940. }
  37941. if (numChars == 0)
  37942. return false;
  37943. return skipNumberSuffix (source);
  37944. }
  37945. static bool parseFloatLiteral (CodeDocument::Iterator& source) throw()
  37946. {
  37947. int numDigits = 0;
  37948. while (isDecimalDigit (source.peekNextChar()))
  37949. {
  37950. source.skip();
  37951. ++numDigits;
  37952. }
  37953. const bool hasPoint = (source.peekNextChar() == '.');
  37954. if (hasPoint)
  37955. {
  37956. source.skip();
  37957. while (isDecimalDigit (source.peekNextChar()))
  37958. {
  37959. source.skip();
  37960. ++numDigits;
  37961. }
  37962. }
  37963. if (numDigits == 0)
  37964. return false;
  37965. juce_wchar c = source.peekNextChar();
  37966. const bool hasExponent = (c == 'e' || c == 'E');
  37967. if (hasExponent)
  37968. {
  37969. source.skip();
  37970. c = source.peekNextChar();
  37971. if (c == '+' || c == '-')
  37972. source.skip();
  37973. int numExpDigits = 0;
  37974. while (isDecimalDigit (source.peekNextChar()))
  37975. {
  37976. source.skip();
  37977. ++numExpDigits;
  37978. }
  37979. if (numExpDigits == 0)
  37980. return false;
  37981. }
  37982. c = source.peekNextChar();
  37983. if (c == 'f' || c == 'F')
  37984. source.skip();
  37985. else if (! (hasExponent || hasPoint))
  37986. return false;
  37987. return true;
  37988. }
  37989. static int parseNumber (CodeDocument::Iterator& source)
  37990. {
  37991. const CodeDocument::Iterator original (source);
  37992. if (parseFloatLiteral (source))
  37993. return CPlusPlusCodeTokeniser::tokenType_floatLiteral;
  37994. source = original;
  37995. if (parseHexLiteral (source))
  37996. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  37997. source = original;
  37998. if (parseOctalLiteral (source))
  37999. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38000. source = original;
  38001. if (parseDecimalLiteral (source))
  38002. return CPlusPlusCodeTokeniser::tokenType_integerLiteral;
  38003. source = original;
  38004. source.skip();
  38005. return CPlusPlusCodeTokeniser::tokenType_error;
  38006. }
  38007. static void skipQuotedString (CodeDocument::Iterator& source) throw()
  38008. {
  38009. const juce_wchar quote = source.nextChar();
  38010. for (;;)
  38011. {
  38012. const juce_wchar c = source.nextChar();
  38013. if (c == quote || c == 0)
  38014. break;
  38015. if (c == '\\')
  38016. source.skip();
  38017. }
  38018. }
  38019. static void skipComment (CodeDocument::Iterator& source) throw()
  38020. {
  38021. bool lastWasStar = false;
  38022. for (;;)
  38023. {
  38024. const juce_wchar c = source.nextChar();
  38025. if (c == 0 || (c == '/' && lastWasStar))
  38026. break;
  38027. lastWasStar = (c == '*');
  38028. }
  38029. }
  38030. }
  38031. int CPlusPlusCodeTokeniser::readNextToken (CodeDocument::Iterator& source)
  38032. {
  38033. int result = tokenType_error;
  38034. source.skipWhitespace();
  38035. juce_wchar firstChar = source.peekNextChar();
  38036. switch (firstChar)
  38037. {
  38038. case 0:
  38039. source.skip();
  38040. break;
  38041. case '0':
  38042. case '1':
  38043. case '2':
  38044. case '3':
  38045. case '4':
  38046. case '5':
  38047. case '6':
  38048. case '7':
  38049. case '8':
  38050. case '9':
  38051. result = CppTokeniser::parseNumber (source);
  38052. break;
  38053. case '.':
  38054. result = CppTokeniser::parseNumber (source);
  38055. if (result == tokenType_error)
  38056. result = tokenType_punctuation;
  38057. break;
  38058. case ',':
  38059. case ';':
  38060. case ':':
  38061. source.skip();
  38062. result = tokenType_punctuation;
  38063. break;
  38064. case '(':
  38065. case ')':
  38066. case '{':
  38067. case '}':
  38068. case '[':
  38069. case ']':
  38070. source.skip();
  38071. result = tokenType_bracket;
  38072. break;
  38073. case '"':
  38074. case '\'':
  38075. CppTokeniser::skipQuotedString (source);
  38076. result = tokenType_stringLiteral;
  38077. break;
  38078. case '+':
  38079. result = tokenType_operator;
  38080. source.skip();
  38081. if (source.peekNextChar() == '+')
  38082. source.skip();
  38083. else if (source.peekNextChar() == '=')
  38084. source.skip();
  38085. break;
  38086. case '-':
  38087. source.skip();
  38088. result = CppTokeniser::parseNumber (source);
  38089. if (result == tokenType_error)
  38090. {
  38091. result = tokenType_operator;
  38092. if (source.peekNextChar() == '-')
  38093. source.skip();
  38094. else if (source.peekNextChar() == '=')
  38095. source.skip();
  38096. }
  38097. break;
  38098. case '*':
  38099. case '%':
  38100. case '=':
  38101. case '!':
  38102. result = tokenType_operator;
  38103. source.skip();
  38104. if (source.peekNextChar() == '=')
  38105. source.skip();
  38106. break;
  38107. case '/':
  38108. result = tokenType_operator;
  38109. source.skip();
  38110. if (source.peekNextChar() == '=')
  38111. {
  38112. source.skip();
  38113. }
  38114. else if (source.peekNextChar() == '/')
  38115. {
  38116. result = tokenType_comment;
  38117. source.skipToEndOfLine();
  38118. }
  38119. else if (source.peekNextChar() == '*')
  38120. {
  38121. source.skip();
  38122. result = tokenType_comment;
  38123. CppTokeniser::skipComment (source);
  38124. }
  38125. break;
  38126. case '?':
  38127. case '~':
  38128. source.skip();
  38129. result = tokenType_operator;
  38130. break;
  38131. case '<':
  38132. source.skip();
  38133. result = tokenType_operator;
  38134. if (source.peekNextChar() == '=')
  38135. {
  38136. source.skip();
  38137. }
  38138. else if (source.peekNextChar() == '<')
  38139. {
  38140. source.skip();
  38141. if (source.peekNextChar() == '=')
  38142. source.skip();
  38143. }
  38144. break;
  38145. case '>':
  38146. source.skip();
  38147. result = tokenType_operator;
  38148. if (source.peekNextChar() == '=')
  38149. {
  38150. source.skip();
  38151. }
  38152. else if (source.peekNextChar() == '<')
  38153. {
  38154. source.skip();
  38155. if (source.peekNextChar() == '=')
  38156. source.skip();
  38157. }
  38158. break;
  38159. case '|':
  38160. source.skip();
  38161. result = tokenType_operator;
  38162. if (source.peekNextChar() == '=')
  38163. {
  38164. source.skip();
  38165. }
  38166. else if (source.peekNextChar() == '|')
  38167. {
  38168. source.skip();
  38169. if (source.peekNextChar() == '=')
  38170. source.skip();
  38171. }
  38172. break;
  38173. case '&':
  38174. source.skip();
  38175. result = tokenType_operator;
  38176. if (source.peekNextChar() == '=')
  38177. {
  38178. source.skip();
  38179. }
  38180. else if (source.peekNextChar() == '&')
  38181. {
  38182. source.skip();
  38183. if (source.peekNextChar() == '=')
  38184. source.skip();
  38185. }
  38186. break;
  38187. case '^':
  38188. source.skip();
  38189. result = tokenType_operator;
  38190. if (source.peekNextChar() == '=')
  38191. {
  38192. source.skip();
  38193. }
  38194. else if (source.peekNextChar() == '^')
  38195. {
  38196. source.skip();
  38197. if (source.peekNextChar() == '=')
  38198. source.skip();
  38199. }
  38200. break;
  38201. case '#':
  38202. result = tokenType_preprocessor;
  38203. source.skipToEndOfLine();
  38204. break;
  38205. default:
  38206. if (CppTokeniser::isIdentifierStart (firstChar))
  38207. result = CppTokeniser::parseIdentifier (source);
  38208. else
  38209. source.skip();
  38210. break;
  38211. }
  38212. return result;
  38213. }
  38214. const StringArray CPlusPlusCodeTokeniser::getTokenTypes()
  38215. {
  38216. const char* const types[] =
  38217. {
  38218. "Error",
  38219. "Comment",
  38220. "C++ keyword",
  38221. "Identifier",
  38222. "Integer literal",
  38223. "Float literal",
  38224. "String literal",
  38225. "Operator",
  38226. "Bracket",
  38227. "Punctuation",
  38228. "Preprocessor line",
  38229. 0
  38230. };
  38231. return StringArray (types);
  38232. }
  38233. const Colour CPlusPlusCodeTokeniser::getDefaultColour (const int tokenType)
  38234. {
  38235. const uint32 colours[] =
  38236. {
  38237. 0xffcc0000, // error
  38238. 0xff00aa00, // comment
  38239. 0xff0000cc, // keyword
  38240. 0xff000000, // identifier
  38241. 0xff880000, // int literal
  38242. 0xff885500, // float literal
  38243. 0xff990099, // string literal
  38244. 0xff225500, // operator
  38245. 0xff000055, // bracket
  38246. 0xff004400, // punctuation
  38247. 0xff660000 // preprocessor
  38248. };
  38249. if (tokenType >= 0 && tokenType < numElementsInArray (colours))
  38250. return Colour (colours [tokenType]);
  38251. return Colours::black;
  38252. }
  38253. bool CPlusPlusCodeTokeniser::isReservedKeyword (const String& token) throw()
  38254. {
  38255. return CppTokeniser::isReservedKeyword (token, token.length());
  38256. }
  38257. END_JUCE_NAMESPACE
  38258. /*** End of inlined file: juce_CPlusPlusCodeTokeniser.cpp ***/
  38259. /*** Start of inlined file: juce_ComboBox.cpp ***/
  38260. BEGIN_JUCE_NAMESPACE
  38261. ComboBox::ComboBox (const String& name)
  38262. : Component (name),
  38263. lastCurrentId (0),
  38264. isButtonDown (false),
  38265. separatorPending (false),
  38266. menuActive (false),
  38267. label (0)
  38268. {
  38269. noChoicesMessage = TRANS("(no choices)");
  38270. setRepaintsOnMouseActivity (true);
  38271. lookAndFeelChanged();
  38272. currentId.addListener (this);
  38273. }
  38274. ComboBox::~ComboBox()
  38275. {
  38276. currentId.removeListener (this);
  38277. if (menuActive)
  38278. PopupMenu::dismissAllActiveMenus();
  38279. label = 0;
  38280. deleteAllChildren();
  38281. }
  38282. void ComboBox::setEditableText (const bool isEditable)
  38283. {
  38284. if (label->isEditableOnSingleClick() != isEditable || label->isEditableOnDoubleClick() != isEditable)
  38285. {
  38286. label->setEditable (isEditable, isEditable, false);
  38287. setWantsKeyboardFocus (! isEditable);
  38288. resized();
  38289. }
  38290. }
  38291. bool ComboBox::isTextEditable() const throw()
  38292. {
  38293. return label->isEditable();
  38294. }
  38295. void ComboBox::setJustificationType (const Justification& justification)
  38296. {
  38297. label->setJustificationType (justification);
  38298. }
  38299. const Justification ComboBox::getJustificationType() const throw()
  38300. {
  38301. return label->getJustificationType();
  38302. }
  38303. void ComboBox::setTooltip (const String& newTooltip)
  38304. {
  38305. SettableTooltipClient::setTooltip (newTooltip);
  38306. label->setTooltip (newTooltip);
  38307. }
  38308. void ComboBox::addItem (const String& newItemText, const int newItemId)
  38309. {
  38310. // you can't add empty strings to the list..
  38311. jassert (newItemText.isNotEmpty());
  38312. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  38313. jassert (newItemId != 0);
  38314. // you shouldn't use duplicate item IDs!
  38315. jassert (getItemForId (newItemId) == 0);
  38316. if (newItemText.isNotEmpty() && newItemId != 0)
  38317. {
  38318. if (separatorPending)
  38319. {
  38320. separatorPending = false;
  38321. ItemInfo* const item = new ItemInfo();
  38322. item->itemId = 0;
  38323. item->isEnabled = false;
  38324. item->isHeading = false;
  38325. items.add (item);
  38326. }
  38327. ItemInfo* const item = new ItemInfo();
  38328. item->name = newItemText;
  38329. item->itemId = newItemId;
  38330. item->isEnabled = true;
  38331. item->isHeading = false;
  38332. items.add (item);
  38333. }
  38334. }
  38335. void ComboBox::addSeparator()
  38336. {
  38337. separatorPending = (items.size() > 0);
  38338. }
  38339. void ComboBox::addSectionHeading (const String& headingName)
  38340. {
  38341. // you can't add empty strings to the list..
  38342. jassert (headingName.isNotEmpty());
  38343. if (headingName.isNotEmpty())
  38344. {
  38345. if (separatorPending)
  38346. {
  38347. separatorPending = false;
  38348. ItemInfo* const item = new ItemInfo();
  38349. item->itemId = 0;
  38350. item->isEnabled = false;
  38351. item->isHeading = false;
  38352. items.add (item);
  38353. }
  38354. ItemInfo* const item = new ItemInfo();
  38355. item->name = headingName;
  38356. item->itemId = 0;
  38357. item->isEnabled = true;
  38358. item->isHeading = true;
  38359. items.add (item);
  38360. }
  38361. }
  38362. void ComboBox::setItemEnabled (const int itemId, const bool shouldBeEnabled)
  38363. {
  38364. ItemInfo* const item = getItemForId (itemId);
  38365. if (item != 0)
  38366. item->isEnabled = shouldBeEnabled;
  38367. }
  38368. void ComboBox::changeItemText (const int itemId, const String& newText)
  38369. {
  38370. ItemInfo* const item = getItemForId (itemId);
  38371. jassert (item != 0);
  38372. if (item != 0)
  38373. item->name = newText;
  38374. }
  38375. void ComboBox::clear (const bool dontSendChangeMessage)
  38376. {
  38377. items.clear();
  38378. separatorPending = false;
  38379. if (! label->isEditable())
  38380. setSelectedItemIndex (-1, dontSendChangeMessage);
  38381. }
  38382. bool ComboBox::ItemInfo::isSeparator() const throw()
  38383. {
  38384. return name.isEmpty();
  38385. }
  38386. bool ComboBox::ItemInfo::isRealItem() const throw()
  38387. {
  38388. return ! (isHeading || name.isEmpty());
  38389. }
  38390. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  38391. {
  38392. if (itemId != 0)
  38393. {
  38394. for (int i = items.size(); --i >= 0;)
  38395. if (items.getUnchecked(i)->itemId == itemId)
  38396. return items.getUnchecked(i);
  38397. }
  38398. return 0;
  38399. }
  38400. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  38401. {
  38402. int n = 0;
  38403. for (int i = 0; i < items.size(); ++i)
  38404. {
  38405. ItemInfo* const item = items.getUnchecked(i);
  38406. if (item->isRealItem())
  38407. if (n++ == index)
  38408. return item;
  38409. }
  38410. return 0;
  38411. }
  38412. int ComboBox::getNumItems() const throw()
  38413. {
  38414. int n = 0;
  38415. for (int i = items.size(); --i >= 0;)
  38416. if (items.getUnchecked(i)->isRealItem())
  38417. ++n;
  38418. return n;
  38419. }
  38420. const String ComboBox::getItemText (const int index) const
  38421. {
  38422. const ItemInfo* const item = getItemForIndex (index);
  38423. if (item != 0)
  38424. return item->name;
  38425. return String::empty;
  38426. }
  38427. int ComboBox::getItemId (const int index) const throw()
  38428. {
  38429. const ItemInfo* const item = getItemForIndex (index);
  38430. return (item != 0) ? item->itemId : 0;
  38431. }
  38432. int ComboBox::indexOfItemId (const int itemId) const throw()
  38433. {
  38434. int n = 0;
  38435. for (int i = 0; i < items.size(); ++i)
  38436. {
  38437. const ItemInfo* const item = items.getUnchecked(i);
  38438. if (item->isRealItem())
  38439. {
  38440. if (item->itemId == itemId)
  38441. return n;
  38442. ++n;
  38443. }
  38444. }
  38445. return -1;
  38446. }
  38447. int ComboBox::getSelectedItemIndex() const
  38448. {
  38449. int index = indexOfItemId (currentId.getValue());
  38450. if (getText() != getItemText (index))
  38451. index = -1;
  38452. return index;
  38453. }
  38454. void ComboBox::setSelectedItemIndex (const int index, const bool dontSendChangeMessage)
  38455. {
  38456. setSelectedId (getItemId (index), dontSendChangeMessage);
  38457. }
  38458. int ComboBox::getSelectedId() const throw()
  38459. {
  38460. const ItemInfo* const item = getItemForId (currentId.getValue());
  38461. return (item != 0 && getText() == item->name) ? item->itemId : 0;
  38462. }
  38463. void ComboBox::setSelectedId (const int newItemId, const bool dontSendChangeMessage)
  38464. {
  38465. const ItemInfo* const item = getItemForId (newItemId);
  38466. const String newItemText (item != 0 ? item->name : String::empty);
  38467. if (lastCurrentId != newItemId || label->getText() != newItemText)
  38468. {
  38469. if (! dontSendChangeMessage)
  38470. triggerAsyncUpdate();
  38471. label->setText (newItemText, false);
  38472. lastCurrentId = newItemId;
  38473. currentId = newItemId;
  38474. repaint(); // for the benefit of the 'none selected' text
  38475. }
  38476. }
  38477. void ComboBox::valueChanged (Value&)
  38478. {
  38479. if (lastCurrentId != (int) currentId.getValue())
  38480. setSelectedId (currentId.getValue(), false);
  38481. }
  38482. const String ComboBox::getText() const
  38483. {
  38484. return label->getText();
  38485. }
  38486. void ComboBox::setText (const String& newText, const bool dontSendChangeMessage)
  38487. {
  38488. for (int i = items.size(); --i >= 0;)
  38489. {
  38490. const ItemInfo* const item = items.getUnchecked(i);
  38491. if (item->isRealItem()
  38492. && item->name == newText)
  38493. {
  38494. setSelectedId (item->itemId, dontSendChangeMessage);
  38495. return;
  38496. }
  38497. }
  38498. lastCurrentId = 0;
  38499. currentId = 0;
  38500. if (label->getText() != newText)
  38501. {
  38502. label->setText (newText, false);
  38503. if (! dontSendChangeMessage)
  38504. triggerAsyncUpdate();
  38505. }
  38506. repaint();
  38507. }
  38508. void ComboBox::showEditor()
  38509. {
  38510. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  38511. label->showEditor();
  38512. }
  38513. void ComboBox::setTextWhenNothingSelected (const String& newMessage)
  38514. {
  38515. if (textWhenNothingSelected != newMessage)
  38516. {
  38517. textWhenNothingSelected = newMessage;
  38518. repaint();
  38519. }
  38520. }
  38521. const String ComboBox::getTextWhenNothingSelected() const
  38522. {
  38523. return textWhenNothingSelected;
  38524. }
  38525. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage)
  38526. {
  38527. noChoicesMessage = newMessage;
  38528. }
  38529. const String ComboBox::getTextWhenNoChoicesAvailable() const
  38530. {
  38531. return noChoicesMessage;
  38532. }
  38533. void ComboBox::paint (Graphics& g)
  38534. {
  38535. getLookAndFeel().drawComboBox (g,
  38536. getWidth(),
  38537. getHeight(),
  38538. isButtonDown,
  38539. label->getRight(),
  38540. 0,
  38541. getWidth() - label->getRight(),
  38542. getHeight(),
  38543. *this);
  38544. if (textWhenNothingSelected.isNotEmpty()
  38545. && label->getText().isEmpty()
  38546. && ! label->isBeingEdited())
  38547. {
  38548. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  38549. g.setFont (label->getFont());
  38550. g.drawFittedText (textWhenNothingSelected,
  38551. label->getX() + 2, label->getY() + 1,
  38552. label->getWidth() - 4, label->getHeight() - 2,
  38553. label->getJustificationType(),
  38554. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  38555. }
  38556. }
  38557. void ComboBox::resized()
  38558. {
  38559. if (getHeight() > 0 && getWidth() > 0)
  38560. getLookAndFeel().positionComboBoxText (*this, *label);
  38561. }
  38562. void ComboBox::enablementChanged()
  38563. {
  38564. repaint();
  38565. }
  38566. void ComboBox::lookAndFeelChanged()
  38567. {
  38568. repaint();
  38569. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  38570. if (label != 0)
  38571. {
  38572. newLabel->setEditable (label->isEditable());
  38573. newLabel->setJustificationType (label->getJustificationType());
  38574. newLabel->setTooltip (label->getTooltip());
  38575. newLabel->setText (label->getText(), false);
  38576. }
  38577. label = newLabel;
  38578. addAndMakeVisible (newLabel);
  38579. newLabel->addListener (this);
  38580. newLabel->addMouseListener (this, false);
  38581. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  38582. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  38583. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  38584. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38585. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  38586. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38587. resized();
  38588. }
  38589. void ComboBox::colourChanged()
  38590. {
  38591. lookAndFeelChanged();
  38592. }
  38593. bool ComboBox::keyPressed (const KeyPress& key)
  38594. {
  38595. bool used = false;
  38596. if (key.isKeyCode (KeyPress::upKey)
  38597. || key.isKeyCode (KeyPress::leftKey))
  38598. {
  38599. setSelectedItemIndex (jmax (0, getSelectedItemIndex() - 1));
  38600. used = true;
  38601. }
  38602. else if (key.isKeyCode (KeyPress::downKey)
  38603. || key.isKeyCode (KeyPress::rightKey))
  38604. {
  38605. setSelectedItemIndex (jmin (getSelectedItemIndex() + 1, getNumItems() - 1));
  38606. used = true;
  38607. }
  38608. else if (key.isKeyCode (KeyPress::returnKey))
  38609. {
  38610. showPopup();
  38611. used = true;
  38612. }
  38613. return used;
  38614. }
  38615. bool ComboBox::keyStateChanged (const bool isKeyDown)
  38616. {
  38617. // only forward key events that aren't used by this component
  38618. return isKeyDown
  38619. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  38620. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  38621. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  38622. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey));
  38623. }
  38624. void ComboBox::focusGained (FocusChangeType)
  38625. {
  38626. repaint();
  38627. }
  38628. void ComboBox::focusLost (FocusChangeType)
  38629. {
  38630. repaint();
  38631. }
  38632. void ComboBox::labelTextChanged (Label*)
  38633. {
  38634. triggerAsyncUpdate();
  38635. }
  38636. class ComboBox::Callback : public ModalComponentManager::Callback
  38637. {
  38638. public:
  38639. Callback (ComboBox* const box_)
  38640. : box (box_)
  38641. {
  38642. }
  38643. void modalStateFinished (int returnValue)
  38644. {
  38645. if (box != 0)
  38646. {
  38647. box->menuActive = false;
  38648. if (returnValue != 0)
  38649. box->setSelectedId (returnValue);
  38650. }
  38651. }
  38652. private:
  38653. Component::SafePointer<ComboBox> box;
  38654. Callback (const Callback&);
  38655. Callback& operator= (const Callback&);
  38656. };
  38657. void ComboBox::showPopup()
  38658. {
  38659. if (! menuActive)
  38660. {
  38661. const int selectedId = getSelectedId();
  38662. PopupMenu menu;
  38663. menu.setLookAndFeel (&getLookAndFeel());
  38664. for (int i = 0; i < items.size(); ++i)
  38665. {
  38666. const ItemInfo* const item = items.getUnchecked(i);
  38667. if (item->isSeparator())
  38668. menu.addSeparator();
  38669. else if (item->isHeading)
  38670. menu.addSectionHeader (item->name);
  38671. else
  38672. menu.addItem (item->itemId, item->name,
  38673. item->isEnabled, item->itemId == selectedId);
  38674. }
  38675. if (items.size() == 0)
  38676. menu.addItem (1, noChoicesMessage, false);
  38677. menuActive = true;
  38678. menu.showAt (this, selectedId, getWidth(), 1, jlimit (12, 24, getHeight()),
  38679. new Callback (this));
  38680. }
  38681. }
  38682. void ComboBox::mouseDown (const MouseEvent& e)
  38683. {
  38684. beginDragAutoRepeat (300);
  38685. isButtonDown = isEnabled();
  38686. if (isButtonDown
  38687. && (e.eventComponent == this || ! label->isEditable()))
  38688. {
  38689. showPopup();
  38690. }
  38691. }
  38692. void ComboBox::mouseDrag (const MouseEvent& e)
  38693. {
  38694. beginDragAutoRepeat (50);
  38695. if (isButtonDown && ! e.mouseWasClicked())
  38696. showPopup();
  38697. }
  38698. void ComboBox::mouseUp (const MouseEvent& e2)
  38699. {
  38700. if (isButtonDown)
  38701. {
  38702. isButtonDown = false;
  38703. repaint();
  38704. const MouseEvent e (e2.getEventRelativeTo (this));
  38705. if (reallyContains (e.x, e.y, true)
  38706. && (e2.eventComponent == this || ! label->isEditable()))
  38707. {
  38708. showPopup();
  38709. }
  38710. }
  38711. }
  38712. void ComboBox::addListener (Listener* const listener)
  38713. {
  38714. listeners.add (listener);
  38715. }
  38716. void ComboBox::removeListener (Listener* const listener)
  38717. {
  38718. listeners.remove (listener);
  38719. }
  38720. void ComboBox::handleAsyncUpdate()
  38721. {
  38722. Component::BailOutChecker checker (this);
  38723. listeners.callChecked (checker, &ComboBoxListener::comboBoxChanged, this); // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  38724. }
  38725. END_JUCE_NAMESPACE
  38726. /*** End of inlined file: juce_ComboBox.cpp ***/
  38727. /*** Start of inlined file: juce_Label.cpp ***/
  38728. BEGIN_JUCE_NAMESPACE
  38729. Label::Label (const String& componentName,
  38730. const String& labelText)
  38731. : Component (componentName),
  38732. textValue (labelText),
  38733. lastTextValue (labelText),
  38734. font (15.0f),
  38735. justification (Justification::centredLeft),
  38736. ownerComponent (0),
  38737. horizontalBorderSize (5),
  38738. verticalBorderSize (1),
  38739. minimumHorizontalScale (0.7f),
  38740. editSingleClick (false),
  38741. editDoubleClick (false),
  38742. lossOfFocusDiscardsChanges (false)
  38743. {
  38744. setColour (TextEditor::textColourId, Colours::black);
  38745. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  38746. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  38747. textValue.addListener (this);
  38748. }
  38749. Label::~Label()
  38750. {
  38751. textValue.removeListener (this);
  38752. if (ownerComponent != 0)
  38753. ownerComponent->removeComponentListener (this);
  38754. editor = 0;
  38755. }
  38756. void Label::setText (const String& newText,
  38757. const bool broadcastChangeMessage)
  38758. {
  38759. hideEditor (true);
  38760. if (lastTextValue != newText)
  38761. {
  38762. lastTextValue = newText;
  38763. textValue = newText;
  38764. repaint();
  38765. textWasChanged();
  38766. if (ownerComponent != 0)
  38767. componentMovedOrResized (*ownerComponent, true, true);
  38768. if (broadcastChangeMessage)
  38769. callChangeListeners();
  38770. }
  38771. }
  38772. const String Label::getText (const bool returnActiveEditorContents) const
  38773. {
  38774. return (returnActiveEditorContents && isBeingEdited())
  38775. ? editor->getText()
  38776. : textValue.toString();
  38777. }
  38778. void Label::valueChanged (Value&)
  38779. {
  38780. if (lastTextValue != textValue.toString())
  38781. setText (textValue.toString(), true);
  38782. }
  38783. void Label::setFont (const Font& newFont)
  38784. {
  38785. if (font != newFont)
  38786. {
  38787. font = newFont;
  38788. repaint();
  38789. }
  38790. }
  38791. const Font& Label::getFont() const throw()
  38792. {
  38793. return font;
  38794. }
  38795. void Label::setEditable (const bool editOnSingleClick,
  38796. const bool editOnDoubleClick,
  38797. const bool lossOfFocusDiscardsChanges_)
  38798. {
  38799. editSingleClick = editOnSingleClick;
  38800. editDoubleClick = editOnDoubleClick;
  38801. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  38802. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  38803. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  38804. }
  38805. void Label::setJustificationType (const Justification& newJustification)
  38806. {
  38807. if (justification != newJustification)
  38808. {
  38809. justification = newJustification;
  38810. repaint();
  38811. }
  38812. }
  38813. void Label::setBorderSize (int h, int v)
  38814. {
  38815. if (horizontalBorderSize != h || verticalBorderSize != v)
  38816. {
  38817. horizontalBorderSize = h;
  38818. verticalBorderSize = v;
  38819. repaint();
  38820. }
  38821. }
  38822. Component* Label::getAttachedComponent() const
  38823. {
  38824. return static_cast<Component*> (ownerComponent);
  38825. }
  38826. void Label::attachToComponent (Component* owner,
  38827. const bool onLeft)
  38828. {
  38829. if (ownerComponent != 0)
  38830. ownerComponent->removeComponentListener (this);
  38831. ownerComponent = owner;
  38832. leftOfOwnerComp = onLeft;
  38833. if (ownerComponent != 0)
  38834. {
  38835. setVisible (owner->isVisible());
  38836. ownerComponent->addComponentListener (this);
  38837. componentParentHierarchyChanged (*ownerComponent);
  38838. componentMovedOrResized (*ownerComponent, true, true);
  38839. }
  38840. }
  38841. void Label::componentMovedOrResized (Component& component, bool /*wasMoved*/, bool /*wasResized*/)
  38842. {
  38843. if (leftOfOwnerComp)
  38844. {
  38845. setSize (jmin (getFont().getStringWidth (textValue.toString()) + 8, component.getX()),
  38846. component.getHeight());
  38847. setTopRightPosition (component.getX(), component.getY());
  38848. }
  38849. else
  38850. {
  38851. setSize (component.getWidth(),
  38852. 8 + roundToInt (getFont().getHeight()));
  38853. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  38854. }
  38855. }
  38856. void Label::componentParentHierarchyChanged (Component& component)
  38857. {
  38858. if (component.getParentComponent() != 0)
  38859. component.getParentComponent()->addChildComponent (this);
  38860. }
  38861. void Label::componentVisibilityChanged (Component& component)
  38862. {
  38863. setVisible (component.isVisible());
  38864. }
  38865. void Label::textWasEdited()
  38866. {
  38867. }
  38868. void Label::textWasChanged()
  38869. {
  38870. }
  38871. void Label::showEditor()
  38872. {
  38873. if (editor == 0)
  38874. {
  38875. addAndMakeVisible (editor = createEditorComponent());
  38876. editor->setText (getText(), false);
  38877. editor->addListener (this);
  38878. editor->grabKeyboardFocus();
  38879. editor->setHighlightedRegion (Range<int> (0, textValue.toString().length()));
  38880. editor->addListener (this);
  38881. resized();
  38882. repaint();
  38883. editorShown (editor);
  38884. enterModalState (false);
  38885. editor->grabKeyboardFocus();
  38886. }
  38887. }
  38888. void Label::editorShown (TextEditor* /*editorComponent*/)
  38889. {
  38890. }
  38891. void Label::editorAboutToBeHidden (TextEditor* /*editorComponent*/)
  38892. {
  38893. }
  38894. bool Label::updateFromTextEditorContents()
  38895. {
  38896. jassert (editor != 0);
  38897. const String newText (editor->getText());
  38898. if (textValue.toString() != newText)
  38899. {
  38900. lastTextValue = newText;
  38901. textValue = newText;
  38902. repaint();
  38903. textWasChanged();
  38904. if (ownerComponent != 0)
  38905. componentMovedOrResized (*ownerComponent, true, true);
  38906. return true;
  38907. }
  38908. return false;
  38909. }
  38910. void Label::hideEditor (const bool discardCurrentEditorContents)
  38911. {
  38912. if (editor != 0)
  38913. {
  38914. Component::SafePointer<Component> deletionChecker (this);
  38915. editorAboutToBeHidden (editor);
  38916. const bool changed = (! discardCurrentEditorContents)
  38917. && updateFromTextEditorContents();
  38918. editor = 0;
  38919. repaint();
  38920. if (changed)
  38921. textWasEdited();
  38922. if (deletionChecker != 0)
  38923. exitModalState (0);
  38924. if (changed && deletionChecker != 0)
  38925. callChangeListeners();
  38926. }
  38927. }
  38928. void Label::inputAttemptWhenModal()
  38929. {
  38930. if (editor != 0)
  38931. {
  38932. if (lossOfFocusDiscardsChanges)
  38933. textEditorEscapeKeyPressed (*editor);
  38934. else
  38935. textEditorReturnKeyPressed (*editor);
  38936. }
  38937. }
  38938. bool Label::isBeingEdited() const throw()
  38939. {
  38940. return editor != 0;
  38941. }
  38942. TextEditor* Label::createEditorComponent()
  38943. {
  38944. TextEditor* const ed = new TextEditor (getName());
  38945. ed->setFont (font);
  38946. // copy these colours from our own settings..
  38947. const int cols[] = { TextEditor::backgroundColourId,
  38948. TextEditor::textColourId,
  38949. TextEditor::highlightColourId,
  38950. TextEditor::highlightedTextColourId,
  38951. TextEditor::caretColourId,
  38952. TextEditor::outlineColourId,
  38953. TextEditor::focusedOutlineColourId,
  38954. TextEditor::shadowColourId };
  38955. for (int i = 0; i < numElementsInArray (cols); ++i)
  38956. ed->setColour (cols[i], findColour (cols[i]));
  38957. return ed;
  38958. }
  38959. void Label::paint (Graphics& g)
  38960. {
  38961. getLookAndFeel().drawLabel (g, *this);
  38962. }
  38963. void Label::mouseUp (const MouseEvent& e)
  38964. {
  38965. if (editSingleClick
  38966. && e.mouseWasClicked()
  38967. && contains (e.x, e.y)
  38968. && ! e.mods.isPopupMenu())
  38969. {
  38970. showEditor();
  38971. }
  38972. }
  38973. void Label::mouseDoubleClick (const MouseEvent& e)
  38974. {
  38975. if (editDoubleClick && ! e.mods.isPopupMenu())
  38976. showEditor();
  38977. }
  38978. void Label::resized()
  38979. {
  38980. if (editor != 0)
  38981. editor->setBoundsInset (BorderSize (0));
  38982. }
  38983. void Label::focusGained (FocusChangeType cause)
  38984. {
  38985. if (editSingleClick && cause == focusChangedByTabKey)
  38986. showEditor();
  38987. }
  38988. void Label::enablementChanged()
  38989. {
  38990. repaint();
  38991. }
  38992. void Label::colourChanged()
  38993. {
  38994. repaint();
  38995. }
  38996. void Label::setMinimumHorizontalScale (const float newScale)
  38997. {
  38998. if (minimumHorizontalScale != newScale)
  38999. {
  39000. minimumHorizontalScale = newScale;
  39001. repaint();
  39002. }
  39003. }
  39004. // We'll use a custom focus traverser here to make sure focus goes from the
  39005. // text editor to another component rather than back to the label itself.
  39006. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  39007. {
  39008. public:
  39009. LabelKeyboardFocusTraverser() {}
  39010. Component* getNextComponent (Component* current)
  39011. {
  39012. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  39013. ? current->getParentComponent() : current);
  39014. }
  39015. Component* getPreviousComponent (Component* current)
  39016. {
  39017. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  39018. ? current->getParentComponent() : current);
  39019. }
  39020. };
  39021. KeyboardFocusTraverser* Label::createFocusTraverser()
  39022. {
  39023. return new LabelKeyboardFocusTraverser();
  39024. }
  39025. void Label::addListener (Listener* const listener)
  39026. {
  39027. listeners.add (listener);
  39028. }
  39029. void Label::removeListener (Listener* const listener)
  39030. {
  39031. listeners.remove (listener);
  39032. }
  39033. void Label::callChangeListeners()
  39034. {
  39035. Component::BailOutChecker checker (this);
  39036. listeners.callChecked (checker, &LabelListener::labelTextChanged, this); // (can't use Label::Listener due to idiotic VC2005 bug)
  39037. }
  39038. void Label::textEditorTextChanged (TextEditor& ed)
  39039. {
  39040. if (editor != 0)
  39041. {
  39042. jassert (&ed == editor);
  39043. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  39044. {
  39045. if (lossOfFocusDiscardsChanges)
  39046. textEditorEscapeKeyPressed (ed);
  39047. else
  39048. textEditorReturnKeyPressed (ed);
  39049. }
  39050. }
  39051. }
  39052. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  39053. {
  39054. if (editor != 0)
  39055. {
  39056. jassert (&ed == editor);
  39057. (void) ed;
  39058. const bool changed = updateFromTextEditorContents();
  39059. hideEditor (true);
  39060. if (changed)
  39061. {
  39062. Component::SafePointer<Component> deletionChecker (this);
  39063. textWasEdited();
  39064. if (deletionChecker != 0)
  39065. callChangeListeners();
  39066. }
  39067. }
  39068. }
  39069. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  39070. {
  39071. if (editor != 0)
  39072. {
  39073. jassert (&ed == editor);
  39074. (void) ed;
  39075. editor->setText (textValue.toString(), false);
  39076. hideEditor (true);
  39077. }
  39078. }
  39079. void Label::textEditorFocusLost (TextEditor& ed)
  39080. {
  39081. textEditorTextChanged (ed);
  39082. }
  39083. END_JUCE_NAMESPACE
  39084. /*** End of inlined file: juce_Label.cpp ***/
  39085. /*** Start of inlined file: juce_ListBox.cpp ***/
  39086. BEGIN_JUCE_NAMESPACE
  39087. class ListBoxRowComponent : public Component,
  39088. public TooltipClient
  39089. {
  39090. public:
  39091. ListBoxRowComponent (ListBox& owner_)
  39092. : owner (owner_), row (-1),
  39093. selected (false), isDragging (false), selectRowOnMouseUp (false)
  39094. {
  39095. }
  39096. void paint (Graphics& g)
  39097. {
  39098. if (owner.getModel() != 0)
  39099. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  39100. }
  39101. void update (const int row_, const bool selected_)
  39102. {
  39103. if (row != row_ || selected != selected_)
  39104. {
  39105. repaint();
  39106. row = row_;
  39107. selected = selected_;
  39108. }
  39109. if (owner.getModel() != 0)
  39110. {
  39111. customComponent = owner.getModel()->refreshComponentForRow (row_, selected_, customComponent.release());
  39112. if (customComponent != 0)
  39113. {
  39114. addAndMakeVisible (customComponent);
  39115. customComponent->setBounds (getLocalBounds());
  39116. }
  39117. }
  39118. }
  39119. void mouseDown (const MouseEvent& e)
  39120. {
  39121. isDragging = false;
  39122. selectRowOnMouseUp = false;
  39123. if (isEnabled())
  39124. {
  39125. if (! selected)
  39126. {
  39127. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39128. if (owner.getModel() != 0)
  39129. owner.getModel()->listBoxItemClicked (row, e);
  39130. }
  39131. else
  39132. {
  39133. selectRowOnMouseUp = true;
  39134. }
  39135. }
  39136. }
  39137. void mouseUp (const MouseEvent& e)
  39138. {
  39139. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  39140. {
  39141. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  39142. if (owner.getModel() != 0)
  39143. owner.getModel()->listBoxItemClicked (row, e);
  39144. }
  39145. }
  39146. void mouseDoubleClick (const MouseEvent& e)
  39147. {
  39148. if (owner.getModel() != 0 && isEnabled())
  39149. owner.getModel()->listBoxItemDoubleClicked (row, e);
  39150. }
  39151. void mouseDrag (const MouseEvent& e)
  39152. {
  39153. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  39154. {
  39155. const SparseSet<int> selectedRows (owner.getSelectedRows());
  39156. if (selectedRows.size() > 0)
  39157. {
  39158. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  39159. if (dragDescription.isNotEmpty())
  39160. {
  39161. isDragging = true;
  39162. owner.startDragAndDrop (e, dragDescription);
  39163. }
  39164. }
  39165. }
  39166. }
  39167. void resized()
  39168. {
  39169. if (customComponent != 0)
  39170. customComponent->setBounds (getLocalBounds());
  39171. }
  39172. const String getTooltip()
  39173. {
  39174. if (owner.getModel() != 0)
  39175. return owner.getModel()->getTooltipForRow (row);
  39176. return String::empty;
  39177. }
  39178. juce_UseDebuggingNewOperator
  39179. ScopedPointer<Component> customComponent;
  39180. private:
  39181. ListBox& owner;
  39182. int row;
  39183. bool selected, isDragging, selectRowOnMouseUp;
  39184. ListBoxRowComponent (const ListBoxRowComponent&);
  39185. ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  39186. };
  39187. class ListViewport : public Viewport
  39188. {
  39189. public:
  39190. ListViewport (ListBox& owner_)
  39191. : owner (owner_)
  39192. {
  39193. setWantsKeyboardFocus (false);
  39194. Component* const content = new Component();
  39195. setViewedComponent (content);
  39196. content->addMouseListener (this, false);
  39197. content->setWantsKeyboardFocus (false);
  39198. }
  39199. ~ListViewport()
  39200. {
  39201. }
  39202. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  39203. {
  39204. return rows [row % jmax (1, rows.size())];
  39205. }
  39206. ListBoxRowComponent* getComponentForRowIfOnscreen (const int row) const throw()
  39207. {
  39208. return (row >= firstIndex && row < firstIndex + rows.size())
  39209. ? getComponentForRow (row) : 0;
  39210. }
  39211. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  39212. {
  39213. const int index = getIndexOfChildComponent (rowComponent);
  39214. const int num = rows.size();
  39215. for (int i = num; --i >= 0;)
  39216. if (((firstIndex + i) % jmax (1, num)) == index)
  39217. return firstIndex + i;
  39218. return -1;
  39219. }
  39220. void visibleAreaChanged (int, int, int, int)
  39221. {
  39222. updateVisibleArea (true);
  39223. if (owner.getModel() != 0)
  39224. owner.getModel()->listWasScrolled();
  39225. }
  39226. void updateVisibleArea (const bool makeSureItUpdatesContent)
  39227. {
  39228. hasUpdated = false;
  39229. const int newX = getViewedComponent()->getX();
  39230. int newY = getViewedComponent()->getY();
  39231. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  39232. const int newH = owner.totalItems * owner.getRowHeight();
  39233. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  39234. newY = getMaximumVisibleHeight() - newH;
  39235. getViewedComponent()->setBounds (newX, newY, newW, newH);
  39236. if (makeSureItUpdatesContent && ! hasUpdated)
  39237. updateContents();
  39238. }
  39239. void updateContents()
  39240. {
  39241. hasUpdated = true;
  39242. const int rowHeight = owner.getRowHeight();
  39243. if (rowHeight > 0)
  39244. {
  39245. const int y = getViewPositionY();
  39246. const int w = getViewedComponent()->getWidth();
  39247. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  39248. rows.removeRange (numNeeded, rows.size());
  39249. while (numNeeded > rows.size())
  39250. {
  39251. ListBoxRowComponent* newRow = new ListBoxRowComponent (owner);
  39252. rows.add (newRow);
  39253. getViewedComponent()->addAndMakeVisible (newRow);
  39254. }
  39255. firstIndex = y / rowHeight;
  39256. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  39257. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  39258. for (int i = 0; i < numNeeded; ++i)
  39259. {
  39260. const int row = i + firstIndex;
  39261. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  39262. if (rowComp != 0)
  39263. {
  39264. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  39265. rowComp->update (row, owner.isRowSelected (row));
  39266. }
  39267. }
  39268. }
  39269. if (owner.headerComponent != 0)
  39270. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  39271. owner.outlineThickness,
  39272. jmax (owner.getWidth() - owner.outlineThickness * 2,
  39273. getViewedComponent()->getWidth()),
  39274. owner.headerComponent->getHeight());
  39275. }
  39276. void selectRow (const int row, const int rowHeight, const bool dontScroll,
  39277. const int lastRowSelected, const int totalItems, const bool isMouseClick)
  39278. {
  39279. hasUpdated = false;
  39280. if (row < firstWholeIndex && ! dontScroll)
  39281. {
  39282. setViewPosition (getViewPositionX(), row * rowHeight);
  39283. }
  39284. else if (row >= lastWholeIndex && ! dontScroll)
  39285. {
  39286. const int rowsOnScreen = lastWholeIndex - firstWholeIndex;
  39287. if (row >= lastRowSelected + rowsOnScreen
  39288. && rowsOnScreen < totalItems - 1
  39289. && ! isMouseClick)
  39290. {
  39291. setViewPosition (getViewPositionX(),
  39292. jlimit (0, jmax (0, totalItems - rowsOnScreen), row) * rowHeight);
  39293. }
  39294. else
  39295. {
  39296. setViewPosition (getViewPositionX(),
  39297. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39298. }
  39299. }
  39300. if (! hasUpdated)
  39301. updateContents();
  39302. }
  39303. void scrollToEnsureRowIsOnscreen (const int row, const int rowHeight)
  39304. {
  39305. if (row < firstWholeIndex)
  39306. {
  39307. setViewPosition (getViewPositionX(), row * rowHeight);
  39308. }
  39309. else if (row >= lastWholeIndex)
  39310. {
  39311. setViewPosition (getViewPositionX(),
  39312. jmax (0, (row + 1) * rowHeight - getMaximumVisibleHeight()));
  39313. }
  39314. }
  39315. void paint (Graphics& g)
  39316. {
  39317. if (isOpaque())
  39318. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  39319. }
  39320. bool keyPressed (const KeyPress& key)
  39321. {
  39322. if (key.isKeyCode (KeyPress::upKey)
  39323. || key.isKeyCode (KeyPress::downKey)
  39324. || key.isKeyCode (KeyPress::pageUpKey)
  39325. || key.isKeyCode (KeyPress::pageDownKey)
  39326. || key.isKeyCode (KeyPress::homeKey)
  39327. || key.isKeyCode (KeyPress::endKey))
  39328. {
  39329. // we want to avoid these keypresses going to the viewport, and instead allow
  39330. // them to pass up to our listbox..
  39331. return false;
  39332. }
  39333. return Viewport::keyPressed (key);
  39334. }
  39335. juce_UseDebuggingNewOperator
  39336. private:
  39337. ListBox& owner;
  39338. OwnedArray<ListBoxRowComponent> rows;
  39339. int firstIndex, firstWholeIndex, lastWholeIndex;
  39340. bool hasUpdated;
  39341. ListViewport (const ListViewport&);
  39342. ListViewport& operator= (const ListViewport&);
  39343. };
  39344. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  39345. : Component (name),
  39346. model (model_),
  39347. totalItems (0),
  39348. rowHeight (22),
  39349. minimumRowWidth (0),
  39350. outlineThickness (0),
  39351. lastRowSelected (-1),
  39352. mouseMoveSelects (false),
  39353. multipleSelection (false),
  39354. hasDoneInitialUpdate (false)
  39355. {
  39356. addAndMakeVisible (viewport = new ListViewport (*this));
  39357. setWantsKeyboardFocus (true);
  39358. colourChanged();
  39359. }
  39360. ListBox::~ListBox()
  39361. {
  39362. headerComponent = 0;
  39363. viewport = 0;
  39364. }
  39365. void ListBox::setModel (ListBoxModel* const newModel)
  39366. {
  39367. if (model != newModel)
  39368. {
  39369. model = newModel;
  39370. updateContent();
  39371. }
  39372. }
  39373. void ListBox::setMultipleSelectionEnabled (bool b)
  39374. {
  39375. multipleSelection = b;
  39376. }
  39377. void ListBox::setMouseMoveSelectsRows (bool b)
  39378. {
  39379. mouseMoveSelects = b;
  39380. if (b)
  39381. addMouseListener (this, true);
  39382. }
  39383. void ListBox::paint (Graphics& g)
  39384. {
  39385. if (! hasDoneInitialUpdate)
  39386. updateContent();
  39387. g.fillAll (findColour (backgroundColourId));
  39388. }
  39389. void ListBox::paintOverChildren (Graphics& g)
  39390. {
  39391. if (outlineThickness > 0)
  39392. {
  39393. g.setColour (findColour (outlineColourId));
  39394. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  39395. }
  39396. }
  39397. void ListBox::resized()
  39398. {
  39399. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  39400. outlineThickness,
  39401. outlineThickness,
  39402. outlineThickness));
  39403. viewport->setSingleStepSizes (20, getRowHeight());
  39404. viewport->updateVisibleArea (false);
  39405. }
  39406. void ListBox::visibilityChanged()
  39407. {
  39408. viewport->updateVisibleArea (true);
  39409. }
  39410. Viewport* ListBox::getViewport() const throw()
  39411. {
  39412. return viewport;
  39413. }
  39414. void ListBox::updateContent()
  39415. {
  39416. hasDoneInitialUpdate = true;
  39417. totalItems = (model != 0) ? model->getNumRows() : 0;
  39418. bool selectionChanged = false;
  39419. if (selected [selected.size() - 1] >= totalItems)
  39420. {
  39421. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39422. lastRowSelected = getSelectedRow (0);
  39423. selectionChanged = true;
  39424. }
  39425. viewport->updateVisibleArea (isVisible());
  39426. viewport->resized();
  39427. if (selectionChanged && model != 0)
  39428. model->selectedRowsChanged (lastRowSelected);
  39429. }
  39430. void ListBox::selectRow (const int row,
  39431. bool dontScroll,
  39432. bool deselectOthersFirst)
  39433. {
  39434. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  39435. }
  39436. void ListBox::selectRowInternal (const int row,
  39437. bool dontScroll,
  39438. bool deselectOthersFirst,
  39439. bool isMouseClick)
  39440. {
  39441. if (! multipleSelection)
  39442. deselectOthersFirst = true;
  39443. if ((! isRowSelected (row))
  39444. || (deselectOthersFirst && getNumSelectedRows() > 1))
  39445. {
  39446. if (((unsigned int) row) < (unsigned int) totalItems)
  39447. {
  39448. if (deselectOthersFirst)
  39449. selected.clear();
  39450. selected.addRange (Range<int> (row, row + 1));
  39451. if (getHeight() == 0 || getWidth() == 0)
  39452. dontScroll = true;
  39453. viewport->selectRow (row, getRowHeight(), dontScroll,
  39454. lastRowSelected, totalItems, isMouseClick);
  39455. lastRowSelected = row;
  39456. model->selectedRowsChanged (row);
  39457. }
  39458. else
  39459. {
  39460. if (deselectOthersFirst)
  39461. deselectAllRows();
  39462. }
  39463. }
  39464. }
  39465. void ListBox::deselectRow (const int row)
  39466. {
  39467. if (selected.contains (row))
  39468. {
  39469. selected.removeRange (Range <int> (row, row + 1));
  39470. if (row == lastRowSelected)
  39471. lastRowSelected = getSelectedRow (0);
  39472. viewport->updateContents();
  39473. model->selectedRowsChanged (lastRowSelected);
  39474. }
  39475. }
  39476. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  39477. const bool sendNotificationEventToModel)
  39478. {
  39479. selected = setOfRowsToBeSelected;
  39480. selected.removeRange (Range <int> (totalItems, std::numeric_limits<int>::max()));
  39481. if (! isRowSelected (lastRowSelected))
  39482. lastRowSelected = getSelectedRow (0);
  39483. viewport->updateContents();
  39484. if ((model != 0) && sendNotificationEventToModel)
  39485. model->selectedRowsChanged (lastRowSelected);
  39486. }
  39487. const SparseSet<int> ListBox::getSelectedRows() const
  39488. {
  39489. return selected;
  39490. }
  39491. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  39492. {
  39493. if (multipleSelection && (firstRow != lastRow))
  39494. {
  39495. const int numRows = totalItems - 1;
  39496. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  39497. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  39498. selected.addRange (Range <int> (jmin (firstRow, lastRow),
  39499. jmax (firstRow, lastRow) + 1));
  39500. selected.removeRange (Range <int> (lastRow, lastRow + 1));
  39501. }
  39502. selectRowInternal (lastRow, false, false, true);
  39503. }
  39504. void ListBox::flipRowSelection (const int row)
  39505. {
  39506. if (isRowSelected (row))
  39507. deselectRow (row);
  39508. else
  39509. selectRowInternal (row, false, false, true);
  39510. }
  39511. void ListBox::deselectAllRows()
  39512. {
  39513. if (! selected.isEmpty())
  39514. {
  39515. selected.clear();
  39516. lastRowSelected = -1;
  39517. viewport->updateContents();
  39518. if (model != 0)
  39519. model->selectedRowsChanged (lastRowSelected);
  39520. }
  39521. }
  39522. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  39523. const ModifierKeys& mods)
  39524. {
  39525. if (multipleSelection && mods.isCommandDown())
  39526. {
  39527. flipRowSelection (row);
  39528. }
  39529. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  39530. {
  39531. selectRangeOfRows (lastRowSelected, row);
  39532. }
  39533. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  39534. {
  39535. selectRowInternal (row, false, true, true);
  39536. }
  39537. }
  39538. int ListBox::getNumSelectedRows() const
  39539. {
  39540. return selected.size();
  39541. }
  39542. int ListBox::getSelectedRow (const int index) const
  39543. {
  39544. return (((unsigned int) index) < (unsigned int) selected.size())
  39545. ? selected [index] : -1;
  39546. }
  39547. bool ListBox::isRowSelected (const int row) const
  39548. {
  39549. return selected.contains (row);
  39550. }
  39551. int ListBox::getLastRowSelected() const
  39552. {
  39553. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  39554. }
  39555. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  39556. {
  39557. if (((unsigned int) x) < (unsigned int) getWidth())
  39558. {
  39559. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  39560. if (((unsigned int) row) < (unsigned int) totalItems)
  39561. return row;
  39562. }
  39563. return -1;
  39564. }
  39565. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  39566. {
  39567. if (((unsigned int) x) < (unsigned int) getWidth())
  39568. {
  39569. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  39570. return jlimit (0, totalItems, row);
  39571. }
  39572. return -1;
  39573. }
  39574. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  39575. {
  39576. ListBoxRowComponent* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  39577. return listRowComp != 0 ? static_cast <Component*> (listRowComp->customComponent) : 0;
  39578. }
  39579. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  39580. {
  39581. return viewport->getRowNumberOfComponent (rowComponent);
  39582. }
  39583. const Rectangle<int> ListBox::getRowPosition (const int rowNumber,
  39584. const bool relativeToComponentTopLeft) const throw()
  39585. {
  39586. int y = viewport->getY() + rowHeight * rowNumber;
  39587. if (relativeToComponentTopLeft)
  39588. y -= viewport->getViewPositionY();
  39589. return Rectangle<int> (viewport->getX(), y,
  39590. viewport->getViewedComponent()->getWidth(), rowHeight);
  39591. }
  39592. void ListBox::setVerticalPosition (const double proportion)
  39593. {
  39594. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39595. viewport->setViewPosition (viewport->getViewPositionX(),
  39596. jmax (0, roundToInt (proportion * offscreen)));
  39597. }
  39598. double ListBox::getVerticalPosition() const
  39599. {
  39600. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  39601. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  39602. : 0;
  39603. }
  39604. int ListBox::getVisibleRowWidth() const throw()
  39605. {
  39606. return viewport->getViewWidth();
  39607. }
  39608. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  39609. {
  39610. viewport->scrollToEnsureRowIsOnscreen (row, getRowHeight());
  39611. }
  39612. bool ListBox::keyPressed (const KeyPress& key)
  39613. {
  39614. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  39615. const bool multiple = multipleSelection
  39616. && (lastRowSelected >= 0)
  39617. && (key.getModifiers().isShiftDown()
  39618. || key.getModifiers().isCtrlDown()
  39619. || key.getModifiers().isCommandDown());
  39620. if (key.isKeyCode (KeyPress::upKey))
  39621. {
  39622. if (multiple)
  39623. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  39624. else
  39625. selectRow (jmax (0, lastRowSelected - 1));
  39626. }
  39627. else if (key.isKeyCode (KeyPress::returnKey)
  39628. && isRowSelected (lastRowSelected))
  39629. {
  39630. if (model != 0)
  39631. model->returnKeyPressed (lastRowSelected);
  39632. }
  39633. else if (key.isKeyCode (KeyPress::pageUpKey))
  39634. {
  39635. if (multiple)
  39636. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  39637. else
  39638. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  39639. }
  39640. else if (key.isKeyCode (KeyPress::pageDownKey))
  39641. {
  39642. if (multiple)
  39643. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  39644. else
  39645. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  39646. }
  39647. else if (key.isKeyCode (KeyPress::homeKey))
  39648. {
  39649. if (multiple && key.getModifiers().isShiftDown())
  39650. selectRangeOfRows (lastRowSelected, 0);
  39651. else
  39652. selectRow (0);
  39653. }
  39654. else if (key.isKeyCode (KeyPress::endKey))
  39655. {
  39656. if (multiple && key.getModifiers().isShiftDown())
  39657. selectRangeOfRows (lastRowSelected, totalItems - 1);
  39658. else
  39659. selectRow (totalItems - 1);
  39660. }
  39661. else if (key.isKeyCode (KeyPress::downKey))
  39662. {
  39663. if (multiple)
  39664. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  39665. else
  39666. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  39667. }
  39668. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  39669. && isRowSelected (lastRowSelected))
  39670. {
  39671. if (model != 0)
  39672. model->deleteKeyPressed (lastRowSelected);
  39673. }
  39674. else if (multiple && key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  39675. {
  39676. selectRangeOfRows (0, std::numeric_limits<int>::max());
  39677. }
  39678. else
  39679. {
  39680. return false;
  39681. }
  39682. return true;
  39683. }
  39684. bool ListBox::keyStateChanged (const bool isKeyDown)
  39685. {
  39686. return isKeyDown
  39687. && (KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  39688. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  39689. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  39690. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  39691. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  39692. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  39693. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey));
  39694. }
  39695. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39696. {
  39697. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  39698. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  39699. }
  39700. void ListBox::mouseMove (const MouseEvent& e)
  39701. {
  39702. if (mouseMoveSelects)
  39703. {
  39704. const MouseEvent e2 (e.getEventRelativeTo (this));
  39705. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  39706. }
  39707. }
  39708. void ListBox::mouseExit (const MouseEvent& e)
  39709. {
  39710. mouseMove (e);
  39711. }
  39712. void ListBox::mouseUp (const MouseEvent& e)
  39713. {
  39714. if (e.mouseWasClicked() && model != 0)
  39715. model->backgroundClicked();
  39716. }
  39717. void ListBox::setRowHeight (const int newHeight)
  39718. {
  39719. rowHeight = jmax (1, newHeight);
  39720. viewport->setSingleStepSizes (20, rowHeight);
  39721. updateContent();
  39722. }
  39723. int ListBox::getNumRowsOnScreen() const throw()
  39724. {
  39725. return viewport->getMaximumVisibleHeight() / rowHeight;
  39726. }
  39727. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  39728. {
  39729. minimumRowWidth = newMinimumWidth;
  39730. updateContent();
  39731. }
  39732. int ListBox::getVisibleContentWidth() const throw()
  39733. {
  39734. return viewport->getMaximumVisibleWidth();
  39735. }
  39736. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  39737. {
  39738. return viewport->getVerticalScrollBar();
  39739. }
  39740. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  39741. {
  39742. return viewport->getHorizontalScrollBar();
  39743. }
  39744. void ListBox::colourChanged()
  39745. {
  39746. setOpaque (findColour (backgroundColourId).isOpaque());
  39747. viewport->setOpaque (isOpaque());
  39748. repaint();
  39749. }
  39750. void ListBox::setOutlineThickness (const int outlineThickness_)
  39751. {
  39752. outlineThickness = outlineThickness_;
  39753. resized();
  39754. }
  39755. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  39756. {
  39757. if (newHeaderComponent != headerComponent)
  39758. {
  39759. headerComponent = newHeaderComponent;
  39760. addAndMakeVisible (newHeaderComponent);
  39761. ListBox::resized();
  39762. }
  39763. }
  39764. void ListBox::repaintRow (const int rowNumber) throw()
  39765. {
  39766. repaint (getRowPosition (rowNumber, true));
  39767. }
  39768. const Image ListBox::createSnapshotOfSelectedRows (int& imageX, int& imageY)
  39769. {
  39770. Rectangle<int> imageArea;
  39771. const int firstRow = getRowContainingPosition (0, 0);
  39772. int i;
  39773. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39774. {
  39775. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39776. if (rowComp != 0 && isRowSelected (firstRow + i))
  39777. {
  39778. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39779. const Rectangle<int> rowRect (pos.getX(), pos.getY(), rowComp->getWidth(), rowComp->getHeight());
  39780. imageArea = imageArea.getUnion (rowRect);
  39781. }
  39782. }
  39783. imageArea = imageArea.getIntersection (getLocalBounds());
  39784. imageX = imageArea.getX();
  39785. imageY = imageArea.getY();
  39786. Image snapshot (Image::ARGB, imageArea.getWidth(), imageArea.getHeight(), true, Image::NativeImage);
  39787. for (i = getNumRowsOnScreen() + 2; --i >= 0;)
  39788. {
  39789. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  39790. if (rowComp != 0 && isRowSelected (firstRow + i))
  39791. {
  39792. const Point<int> pos (rowComp->relativePositionToOtherComponent (this, Point<int>()));
  39793. Graphics g (snapshot);
  39794. g.setOrigin (pos.getX() - imageX, pos.getY() - imageY);
  39795. if (g.reduceClipRegion (rowComp->getLocalBounds()))
  39796. rowComp->paintEntireComponent (g, false);
  39797. }
  39798. }
  39799. return snapshot;
  39800. }
  39801. void ListBox::startDragAndDrop (const MouseEvent& e, const String& dragDescription)
  39802. {
  39803. DragAndDropContainer* const dragContainer
  39804. = DragAndDropContainer::findParentDragContainerFor (this);
  39805. if (dragContainer != 0)
  39806. {
  39807. int x, y;
  39808. Image dragImage (createSnapshotOfSelectedRows (x, y));
  39809. dragImage.multiplyAllAlphas (0.6f);
  39810. MouseEvent e2 (e.getEventRelativeTo (this));
  39811. const Point<int> p (x - e2.x, y - e2.y);
  39812. dragContainer->startDragging (dragDescription, this, dragImage, true, &p);
  39813. }
  39814. else
  39815. {
  39816. // to be able to do a drag-and-drop operation, the listbox needs to
  39817. // be inside a component which is also a DragAndDropContainer.
  39818. jassertfalse;
  39819. }
  39820. }
  39821. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  39822. {
  39823. (void) existingComponentToUpdate;
  39824. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  39825. return 0;
  39826. }
  39827. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&) {}
  39828. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&) {}
  39829. void ListBoxModel::backgroundClicked() {}
  39830. void ListBoxModel::selectedRowsChanged (int) {}
  39831. void ListBoxModel::deleteKeyPressed (int) {}
  39832. void ListBoxModel::returnKeyPressed (int) {}
  39833. void ListBoxModel::listWasScrolled() {}
  39834. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&) { return String::empty; }
  39835. const String ListBoxModel::getTooltipForRow (int) { return String::empty; }
  39836. END_JUCE_NAMESPACE
  39837. /*** End of inlined file: juce_ListBox.cpp ***/
  39838. /*** Start of inlined file: juce_ProgressBar.cpp ***/
  39839. BEGIN_JUCE_NAMESPACE
  39840. ProgressBar::ProgressBar (double& progress_)
  39841. : progress (progress_),
  39842. displayPercentage (true),
  39843. lastCallbackTime (0)
  39844. {
  39845. currentValue = jlimit (0.0, 1.0, progress);
  39846. }
  39847. ProgressBar::~ProgressBar()
  39848. {
  39849. }
  39850. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  39851. {
  39852. displayPercentage = shouldDisplayPercentage;
  39853. repaint();
  39854. }
  39855. void ProgressBar::setTextToDisplay (const String& text)
  39856. {
  39857. displayPercentage = false;
  39858. displayedMessage = text;
  39859. }
  39860. void ProgressBar::lookAndFeelChanged()
  39861. {
  39862. setOpaque (findColour (backgroundColourId).isOpaque());
  39863. }
  39864. void ProgressBar::colourChanged()
  39865. {
  39866. lookAndFeelChanged();
  39867. }
  39868. void ProgressBar::paint (Graphics& g)
  39869. {
  39870. String text;
  39871. if (displayPercentage)
  39872. {
  39873. if (currentValue >= 0 && currentValue <= 1.0)
  39874. text << roundToInt (currentValue * 100.0) << '%';
  39875. }
  39876. else
  39877. {
  39878. text = displayedMessage;
  39879. }
  39880. getLookAndFeel().drawProgressBar (g, *this,
  39881. getWidth(), getHeight(),
  39882. currentValue, text);
  39883. }
  39884. void ProgressBar::visibilityChanged()
  39885. {
  39886. if (isVisible())
  39887. startTimer (30);
  39888. else
  39889. stopTimer();
  39890. }
  39891. void ProgressBar::timerCallback()
  39892. {
  39893. double newProgress = progress;
  39894. const uint32 now = Time::getMillisecondCounter();
  39895. const int timeSinceLastCallback = (int) (now - lastCallbackTime);
  39896. lastCallbackTime = now;
  39897. if (currentValue != newProgress
  39898. || newProgress < 0 || newProgress >= 1.0
  39899. || currentMessage != displayedMessage)
  39900. {
  39901. if (currentValue < newProgress
  39902. && newProgress >= 0 && newProgress < 1.0
  39903. && currentValue >= 0 && currentValue < 1.0)
  39904. {
  39905. newProgress = jmin (currentValue + 0.0008 * timeSinceLastCallback,
  39906. newProgress);
  39907. }
  39908. currentValue = newProgress;
  39909. currentMessage = displayedMessage;
  39910. repaint();
  39911. }
  39912. }
  39913. END_JUCE_NAMESPACE
  39914. /*** End of inlined file: juce_ProgressBar.cpp ***/
  39915. /*** Start of inlined file: juce_Slider.cpp ***/
  39916. BEGIN_JUCE_NAMESPACE
  39917. class SliderPopupDisplayComponent : public BubbleComponent
  39918. {
  39919. public:
  39920. SliderPopupDisplayComponent (Slider* const owner_)
  39921. : owner (owner_),
  39922. font (15.0f, Font::bold)
  39923. {
  39924. setAlwaysOnTop (true);
  39925. }
  39926. ~SliderPopupDisplayComponent()
  39927. {
  39928. }
  39929. void paintContent (Graphics& g, int w, int h)
  39930. {
  39931. g.setFont (font);
  39932. g.setColour (Colours::black);
  39933. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  39934. }
  39935. void getContentSize (int& w, int& h)
  39936. {
  39937. w = font.getStringWidth (text) + 18;
  39938. h = (int) (font.getHeight() * 1.6f);
  39939. }
  39940. void updatePosition (const String& newText)
  39941. {
  39942. if (text != newText)
  39943. {
  39944. text = newText;
  39945. repaint();
  39946. }
  39947. BubbleComponent::setPosition (owner);
  39948. }
  39949. juce_UseDebuggingNewOperator
  39950. private:
  39951. Slider* owner;
  39952. Font font;
  39953. String text;
  39954. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  39955. SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  39956. };
  39957. Slider::Slider (const String& name)
  39958. : Component (name),
  39959. lastCurrentValue (0),
  39960. lastValueMin (0),
  39961. lastValueMax (0),
  39962. minimum (0),
  39963. maximum (10),
  39964. interval (0),
  39965. skewFactor (1.0),
  39966. velocityModeSensitivity (1.0),
  39967. velocityModeOffset (0.0),
  39968. velocityModeThreshold (1),
  39969. rotaryStart (float_Pi * 1.2f),
  39970. rotaryEnd (float_Pi * 2.8f),
  39971. numDecimalPlaces (7),
  39972. sliderRegionStart (0),
  39973. sliderRegionSize (1),
  39974. sliderBeingDragged (-1),
  39975. pixelsForFullDragExtent (250),
  39976. style (LinearHorizontal),
  39977. textBoxPos (TextBoxLeft),
  39978. textBoxWidth (80),
  39979. textBoxHeight (20),
  39980. incDecButtonMode (incDecButtonsNotDraggable),
  39981. editableText (true),
  39982. doubleClickToValue (false),
  39983. isVelocityBased (false),
  39984. userKeyOverridesVelocity (true),
  39985. rotaryStop (true),
  39986. incDecButtonsSideBySide (false),
  39987. sendChangeOnlyOnRelease (false),
  39988. popupDisplayEnabled (false),
  39989. menuEnabled (false),
  39990. menuShown (false),
  39991. scrollWheelEnabled (true),
  39992. snapsToMousePos (true),
  39993. valueBox (0),
  39994. incButton (0),
  39995. decButton (0),
  39996. popupDisplay (0),
  39997. parentForPopupDisplay (0)
  39998. {
  39999. setWantsKeyboardFocus (false);
  40000. setRepaintsOnMouseActivity (true);
  40001. lookAndFeelChanged();
  40002. updateText();
  40003. currentValue.addListener (this);
  40004. valueMin.addListener (this);
  40005. valueMax.addListener (this);
  40006. }
  40007. Slider::~Slider()
  40008. {
  40009. currentValue.removeListener (this);
  40010. valueMin.removeListener (this);
  40011. valueMax.removeListener (this);
  40012. popupDisplay = 0;
  40013. deleteAllChildren();
  40014. }
  40015. void Slider::handleAsyncUpdate()
  40016. {
  40017. cancelPendingUpdate();
  40018. Component::BailOutChecker checker (this);
  40019. listeners.callChecked (checker, &SliderListener::sliderValueChanged, this); // (can't use Slider::Listener due to idiotic VC2005 bug)
  40020. }
  40021. void Slider::sendDragStart()
  40022. {
  40023. startedDragging();
  40024. Component::BailOutChecker checker (this);
  40025. listeners.callChecked (checker, &SliderListener::sliderDragStarted, this);
  40026. }
  40027. void Slider::sendDragEnd()
  40028. {
  40029. stoppedDragging();
  40030. sliderBeingDragged = -1;
  40031. Component::BailOutChecker checker (this);
  40032. listeners.callChecked (checker, &SliderListener::sliderDragEnded, this);
  40033. }
  40034. void Slider::addListener (Listener* const listener)
  40035. {
  40036. listeners.add (listener);
  40037. }
  40038. void Slider::removeListener (Listener* const listener)
  40039. {
  40040. listeners.remove (listener);
  40041. }
  40042. void Slider::setSliderStyle (const SliderStyle newStyle)
  40043. {
  40044. if (style != newStyle)
  40045. {
  40046. style = newStyle;
  40047. repaint();
  40048. lookAndFeelChanged();
  40049. }
  40050. }
  40051. void Slider::setRotaryParameters (const float startAngleRadians,
  40052. const float endAngleRadians,
  40053. const bool stopAtEnd)
  40054. {
  40055. // make sure the values are sensible..
  40056. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  40057. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  40058. jassert (rotaryStart < rotaryEnd);
  40059. rotaryStart = startAngleRadians;
  40060. rotaryEnd = endAngleRadians;
  40061. rotaryStop = stopAtEnd;
  40062. }
  40063. void Slider::setVelocityBasedMode (const bool velBased)
  40064. {
  40065. isVelocityBased = velBased;
  40066. }
  40067. void Slider::setVelocityModeParameters (const double sensitivity,
  40068. const int threshold,
  40069. const double offset,
  40070. const bool userCanPressKeyToSwapMode)
  40071. {
  40072. jassert (threshold >= 0);
  40073. jassert (sensitivity > 0);
  40074. jassert (offset >= 0);
  40075. velocityModeSensitivity = sensitivity;
  40076. velocityModeOffset = offset;
  40077. velocityModeThreshold = threshold;
  40078. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  40079. }
  40080. void Slider::setSkewFactor (const double factor)
  40081. {
  40082. skewFactor = factor;
  40083. }
  40084. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint)
  40085. {
  40086. if (maximum > minimum)
  40087. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  40088. / (maximum - minimum));
  40089. }
  40090. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  40091. {
  40092. jassert (distanceForFullScaleDrag > 0);
  40093. pixelsForFullDragExtent = distanceForFullScaleDrag;
  40094. }
  40095. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  40096. {
  40097. if (incDecButtonMode != mode)
  40098. {
  40099. incDecButtonMode = mode;
  40100. lookAndFeelChanged();
  40101. }
  40102. }
  40103. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  40104. const bool isReadOnly,
  40105. const int textEntryBoxWidth,
  40106. const int textEntryBoxHeight)
  40107. {
  40108. if (textBoxPos != newPosition
  40109. || editableText != (! isReadOnly)
  40110. || textBoxWidth != textEntryBoxWidth
  40111. || textBoxHeight != textEntryBoxHeight)
  40112. {
  40113. textBoxPos = newPosition;
  40114. editableText = ! isReadOnly;
  40115. textBoxWidth = textEntryBoxWidth;
  40116. textBoxHeight = textEntryBoxHeight;
  40117. repaint();
  40118. lookAndFeelChanged();
  40119. }
  40120. }
  40121. void Slider::setTextBoxIsEditable (const bool shouldBeEditable)
  40122. {
  40123. editableText = shouldBeEditable;
  40124. if (valueBox != 0)
  40125. valueBox->setEditable (shouldBeEditable && isEnabled());
  40126. }
  40127. void Slider::showTextBox()
  40128. {
  40129. jassert (editableText); // this should probably be avoided in read-only sliders.
  40130. if (valueBox != 0)
  40131. valueBox->showEditor();
  40132. }
  40133. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  40134. {
  40135. if (valueBox != 0)
  40136. {
  40137. valueBox->hideEditor (discardCurrentEditorContents);
  40138. if (discardCurrentEditorContents)
  40139. updateText();
  40140. }
  40141. }
  40142. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease)
  40143. {
  40144. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  40145. }
  40146. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse)
  40147. {
  40148. snapsToMousePos = shouldSnapToMouse;
  40149. }
  40150. void Slider::setPopupDisplayEnabled (const bool enabled,
  40151. Component* const parentComponentToUse)
  40152. {
  40153. popupDisplayEnabled = enabled;
  40154. parentForPopupDisplay = parentComponentToUse;
  40155. }
  40156. void Slider::colourChanged()
  40157. {
  40158. lookAndFeelChanged();
  40159. }
  40160. void Slider::lookAndFeelChanged()
  40161. {
  40162. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  40163. : getTextFromValue (currentValue.getValue()));
  40164. deleteAllChildren();
  40165. valueBox = 0;
  40166. LookAndFeel& lf = getLookAndFeel();
  40167. if (textBoxPos != NoTextBox)
  40168. {
  40169. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  40170. valueBox->setWantsKeyboardFocus (false);
  40171. valueBox->setText (previousTextBoxContent, false);
  40172. valueBox->setEditable (editableText && isEnabled());
  40173. valueBox->addListener (this);
  40174. if (style == LinearBar)
  40175. valueBox->addMouseListener (this, false);
  40176. valueBox->setTooltip (getTooltip());
  40177. }
  40178. if (style == IncDecButtons)
  40179. {
  40180. addAndMakeVisible (incButton = lf.createSliderButton (true));
  40181. incButton->addButtonListener (this);
  40182. addAndMakeVisible (decButton = lf.createSliderButton (false));
  40183. decButton->addButtonListener (this);
  40184. if (incDecButtonMode != incDecButtonsNotDraggable)
  40185. {
  40186. incButton->addMouseListener (this, false);
  40187. decButton->addMouseListener (this, false);
  40188. }
  40189. else
  40190. {
  40191. incButton->setRepeatSpeed (300, 100, 20);
  40192. incButton->addMouseListener (decButton, false);
  40193. decButton->setRepeatSpeed (300, 100, 20);
  40194. decButton->addMouseListener (incButton, false);
  40195. }
  40196. incButton->setTooltip (getTooltip());
  40197. decButton->setTooltip (getTooltip());
  40198. }
  40199. setComponentEffect (lf.getSliderEffect());
  40200. resized();
  40201. repaint();
  40202. }
  40203. void Slider::setRange (const double newMin,
  40204. const double newMax,
  40205. const double newInt)
  40206. {
  40207. if (minimum != newMin
  40208. || maximum != newMax
  40209. || interval != newInt)
  40210. {
  40211. minimum = newMin;
  40212. maximum = newMax;
  40213. interval = newInt;
  40214. // figure out the number of DPs needed to display all values at this
  40215. // interval setting.
  40216. numDecimalPlaces = 7;
  40217. if (newInt != 0)
  40218. {
  40219. int v = abs ((int) (newInt * 10000000));
  40220. while ((v % 10) == 0)
  40221. {
  40222. --numDecimalPlaces;
  40223. v /= 10;
  40224. }
  40225. }
  40226. // keep the current values inside the new range..
  40227. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40228. {
  40229. setValue (getValue(), false, false);
  40230. }
  40231. else
  40232. {
  40233. setMinValue (getMinValue(), false, false);
  40234. setMaxValue (getMaxValue(), false, false);
  40235. }
  40236. updateText();
  40237. }
  40238. }
  40239. void Slider::triggerChangeMessage (const bool synchronous)
  40240. {
  40241. if (synchronous)
  40242. handleAsyncUpdate();
  40243. else
  40244. triggerAsyncUpdate();
  40245. valueChanged();
  40246. }
  40247. void Slider::valueChanged (Value& value)
  40248. {
  40249. if (value.refersToSameSourceAs (currentValue))
  40250. {
  40251. if (style != TwoValueHorizontal && style != TwoValueVertical)
  40252. setValue (currentValue.getValue(), false, false);
  40253. }
  40254. else if (value.refersToSameSourceAs (valueMin))
  40255. setMinValue (valueMin.getValue(), false, false, true);
  40256. else if (value.refersToSameSourceAs (valueMax))
  40257. setMaxValue (valueMax.getValue(), false, false, true);
  40258. }
  40259. double Slider::getValue() const
  40260. {
  40261. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  40262. // methods to get the two values.
  40263. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40264. return currentValue.getValue();
  40265. }
  40266. void Slider::setValue (double newValue,
  40267. const bool sendUpdateMessage,
  40268. const bool sendMessageSynchronously)
  40269. {
  40270. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  40271. // methods to set the two values.
  40272. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  40273. newValue = constrainedValue (newValue);
  40274. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40275. {
  40276. jassert ((double) valueMin.getValue() <= (double) valueMax.getValue());
  40277. newValue = jlimit ((double) valueMin.getValue(),
  40278. (double) valueMax.getValue(),
  40279. newValue);
  40280. }
  40281. if (newValue != lastCurrentValue)
  40282. {
  40283. if (valueBox != 0)
  40284. valueBox->hideEditor (true);
  40285. lastCurrentValue = newValue;
  40286. currentValue = newValue;
  40287. updateText();
  40288. repaint();
  40289. if (popupDisplay != 0)
  40290. {
  40291. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40292. ->updatePosition (getTextFromValue (newValue));
  40293. popupDisplay->repaint();
  40294. }
  40295. if (sendUpdateMessage)
  40296. triggerChangeMessage (sendMessageSynchronously);
  40297. }
  40298. }
  40299. double Slider::getMinValue() const
  40300. {
  40301. // The minimum value only applies to sliders that are in two- or three-value mode.
  40302. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40303. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40304. return valueMin.getValue();
  40305. }
  40306. double Slider::getMaxValue() const
  40307. {
  40308. // The maximum value only applies to sliders that are in two- or three-value mode.
  40309. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40310. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40311. return valueMax.getValue();
  40312. }
  40313. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40314. {
  40315. // The minimum value only applies to sliders that are in two- or three-value mode.
  40316. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40317. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40318. newValue = constrainedValue (newValue);
  40319. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40320. {
  40321. if (allowNudgingOfOtherValues && newValue > (double) valueMax.getValue())
  40322. setMaxValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40323. newValue = jmin ((double) valueMax.getValue(), newValue);
  40324. }
  40325. else
  40326. {
  40327. if (allowNudgingOfOtherValues && newValue > lastCurrentValue)
  40328. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40329. newValue = jmin (lastCurrentValue, newValue);
  40330. }
  40331. if (lastValueMin != newValue)
  40332. {
  40333. lastValueMin = newValue;
  40334. valueMin = newValue;
  40335. repaint();
  40336. if (popupDisplay != 0)
  40337. {
  40338. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40339. ->updatePosition (getTextFromValue (newValue));
  40340. popupDisplay->repaint();
  40341. }
  40342. if (sendUpdateMessage)
  40343. triggerChangeMessage (sendMessageSynchronously);
  40344. }
  40345. }
  40346. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously, const bool allowNudgingOfOtherValues)
  40347. {
  40348. // The maximum value only applies to sliders that are in two- or three-value mode.
  40349. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  40350. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  40351. newValue = constrainedValue (newValue);
  40352. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40353. {
  40354. if (allowNudgingOfOtherValues && newValue < (double) valueMin.getValue())
  40355. setMinValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40356. newValue = jmax ((double) valueMin.getValue(), newValue);
  40357. }
  40358. else
  40359. {
  40360. if (allowNudgingOfOtherValues && newValue < lastCurrentValue)
  40361. setValue (newValue, sendUpdateMessage, sendMessageSynchronously);
  40362. newValue = jmax (lastCurrentValue, newValue);
  40363. }
  40364. if (lastValueMax != newValue)
  40365. {
  40366. lastValueMax = newValue;
  40367. valueMax = newValue;
  40368. repaint();
  40369. if (popupDisplay != 0)
  40370. {
  40371. static_cast <SliderPopupDisplayComponent*> (static_cast <Component*> (popupDisplay))
  40372. ->updatePosition (getTextFromValue (valueMax.getValue()));
  40373. popupDisplay->repaint();
  40374. }
  40375. if (sendUpdateMessage)
  40376. triggerChangeMessage (sendMessageSynchronously);
  40377. }
  40378. }
  40379. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  40380. const double valueToSetOnDoubleClick)
  40381. {
  40382. doubleClickToValue = isDoubleClickEnabled;
  40383. doubleClickReturnValue = valueToSetOnDoubleClick;
  40384. }
  40385. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const
  40386. {
  40387. isEnabled_ = doubleClickToValue;
  40388. return doubleClickReturnValue;
  40389. }
  40390. void Slider::updateText()
  40391. {
  40392. if (valueBox != 0)
  40393. valueBox->setText (getTextFromValue (currentValue.getValue()), false);
  40394. }
  40395. void Slider::setTextValueSuffix (const String& suffix)
  40396. {
  40397. if (textSuffix != suffix)
  40398. {
  40399. textSuffix = suffix;
  40400. updateText();
  40401. }
  40402. }
  40403. const String Slider::getTextValueSuffix() const
  40404. {
  40405. return textSuffix;
  40406. }
  40407. const String Slider::getTextFromValue (double v)
  40408. {
  40409. if (getNumDecimalPlacesToDisplay() > 0)
  40410. return String (v, getNumDecimalPlacesToDisplay()) + getTextValueSuffix();
  40411. else
  40412. return String (roundToInt (v)) + getTextValueSuffix();
  40413. }
  40414. double Slider::getValueFromText (const String& text)
  40415. {
  40416. String t (text.trimStart());
  40417. if (t.endsWith (textSuffix))
  40418. t = t.substring (0, t.length() - textSuffix.length());
  40419. while (t.startsWithChar ('+'))
  40420. t = t.substring (1).trimStart();
  40421. return t.initialSectionContainingOnly ("0123456789.,-")
  40422. .getDoubleValue();
  40423. }
  40424. double Slider::proportionOfLengthToValue (double proportion)
  40425. {
  40426. if (skewFactor != 1.0 && proportion > 0.0)
  40427. proportion = exp (log (proportion) / skewFactor);
  40428. return minimum + (maximum - minimum) * proportion;
  40429. }
  40430. double Slider::valueToProportionOfLength (double value)
  40431. {
  40432. const double n = (value - minimum) / (maximum - minimum);
  40433. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  40434. }
  40435. double Slider::snapValue (double attemptedValue, const bool)
  40436. {
  40437. return attemptedValue;
  40438. }
  40439. void Slider::startedDragging()
  40440. {
  40441. }
  40442. void Slider::stoppedDragging()
  40443. {
  40444. }
  40445. void Slider::valueChanged()
  40446. {
  40447. }
  40448. void Slider::enablementChanged()
  40449. {
  40450. repaint();
  40451. }
  40452. void Slider::setPopupMenuEnabled (const bool menuEnabled_)
  40453. {
  40454. menuEnabled = menuEnabled_;
  40455. }
  40456. void Slider::setScrollWheelEnabled (const bool enabled)
  40457. {
  40458. scrollWheelEnabled = enabled;
  40459. }
  40460. void Slider::labelTextChanged (Label* label)
  40461. {
  40462. const double newValue = snapValue (getValueFromText (label->getText()), false);
  40463. if (newValue != (double) currentValue.getValue())
  40464. {
  40465. sendDragStart();
  40466. setValue (newValue, true, true);
  40467. sendDragEnd();
  40468. }
  40469. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  40470. }
  40471. void Slider::buttonClicked (Button* button)
  40472. {
  40473. if (style == IncDecButtons)
  40474. {
  40475. sendDragStart();
  40476. if (button == incButton)
  40477. setValue (snapValue (getValue() + interval, false), true, true);
  40478. else if (button == decButton)
  40479. setValue (snapValue (getValue() - interval, false), true, true);
  40480. sendDragEnd();
  40481. }
  40482. }
  40483. double Slider::constrainedValue (double value) const
  40484. {
  40485. if (interval > 0)
  40486. value = minimum + interval * std::floor ((value - minimum) / interval + 0.5);
  40487. if (value <= minimum || maximum <= minimum)
  40488. value = minimum;
  40489. else if (value >= maximum)
  40490. value = maximum;
  40491. return value;
  40492. }
  40493. float Slider::getLinearSliderPos (const double value)
  40494. {
  40495. double sliderPosProportional;
  40496. if (maximum > minimum)
  40497. {
  40498. if (value < minimum)
  40499. {
  40500. sliderPosProportional = 0.0;
  40501. }
  40502. else if (value > maximum)
  40503. {
  40504. sliderPosProportional = 1.0;
  40505. }
  40506. else
  40507. {
  40508. sliderPosProportional = valueToProportionOfLength (value);
  40509. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  40510. }
  40511. }
  40512. else
  40513. {
  40514. sliderPosProportional = 0.5;
  40515. }
  40516. if (isVertical() || style == IncDecButtons)
  40517. sliderPosProportional = 1.0 - sliderPosProportional;
  40518. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  40519. }
  40520. bool Slider::isHorizontal() const
  40521. {
  40522. return style == LinearHorizontal
  40523. || style == LinearBar
  40524. || style == TwoValueHorizontal
  40525. || style == ThreeValueHorizontal;
  40526. }
  40527. bool Slider::isVertical() const
  40528. {
  40529. return style == LinearVertical
  40530. || style == TwoValueVertical
  40531. || style == ThreeValueVertical;
  40532. }
  40533. bool Slider::incDecDragDirectionIsHorizontal() const
  40534. {
  40535. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  40536. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  40537. }
  40538. float Slider::getPositionOfValue (const double value)
  40539. {
  40540. if (isHorizontal() || isVertical())
  40541. {
  40542. return getLinearSliderPos (value);
  40543. }
  40544. else
  40545. {
  40546. jassertfalse; // not a valid call on a slider that doesn't work linearly!
  40547. return 0.0f;
  40548. }
  40549. }
  40550. void Slider::paint (Graphics& g)
  40551. {
  40552. if (style != IncDecButtons)
  40553. {
  40554. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40555. {
  40556. const float sliderPos = (float) valueToProportionOfLength (lastCurrentValue);
  40557. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  40558. getLookAndFeel().drawRotarySlider (g,
  40559. sliderRect.getX(),
  40560. sliderRect.getY(),
  40561. sliderRect.getWidth(),
  40562. sliderRect.getHeight(),
  40563. sliderPos,
  40564. rotaryStart, rotaryEnd,
  40565. *this);
  40566. }
  40567. else
  40568. {
  40569. getLookAndFeel().drawLinearSlider (g,
  40570. sliderRect.getX(),
  40571. sliderRect.getY(),
  40572. sliderRect.getWidth(),
  40573. sliderRect.getHeight(),
  40574. getLinearSliderPos (lastCurrentValue),
  40575. getLinearSliderPos (lastValueMin),
  40576. getLinearSliderPos (lastValueMax),
  40577. style,
  40578. *this);
  40579. }
  40580. if (style == LinearBar && valueBox == 0)
  40581. {
  40582. g.setColour (findColour (Slider::textBoxOutlineColourId));
  40583. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  40584. }
  40585. }
  40586. }
  40587. void Slider::resized()
  40588. {
  40589. int minXSpace = 0;
  40590. int minYSpace = 0;
  40591. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40592. minXSpace = 30;
  40593. else
  40594. minYSpace = 15;
  40595. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  40596. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  40597. if (style == LinearBar)
  40598. {
  40599. if (valueBox != 0)
  40600. valueBox->setBounds (getLocalBounds());
  40601. }
  40602. else
  40603. {
  40604. if (textBoxPos == NoTextBox)
  40605. {
  40606. sliderRect = getLocalBounds();
  40607. }
  40608. else if (textBoxPos == TextBoxLeft)
  40609. {
  40610. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  40611. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  40612. }
  40613. else if (textBoxPos == TextBoxRight)
  40614. {
  40615. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  40616. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  40617. }
  40618. else if (textBoxPos == TextBoxAbove)
  40619. {
  40620. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  40621. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  40622. }
  40623. else if (textBoxPos == TextBoxBelow)
  40624. {
  40625. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  40626. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  40627. }
  40628. }
  40629. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  40630. if (style == LinearBar)
  40631. {
  40632. const int barIndent = 1;
  40633. sliderRegionStart = barIndent;
  40634. sliderRegionSize = getWidth() - barIndent * 2;
  40635. sliderRect.setBounds (sliderRegionStart, barIndent,
  40636. sliderRegionSize, getHeight() - barIndent * 2);
  40637. }
  40638. else if (isHorizontal())
  40639. {
  40640. sliderRegionStart = sliderRect.getX() + indent;
  40641. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  40642. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  40643. sliderRegionSize, sliderRect.getHeight());
  40644. }
  40645. else if (isVertical())
  40646. {
  40647. sliderRegionStart = sliderRect.getY() + indent;
  40648. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  40649. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  40650. sliderRect.getWidth(), sliderRegionSize);
  40651. }
  40652. else
  40653. {
  40654. sliderRegionStart = 0;
  40655. sliderRegionSize = 100;
  40656. }
  40657. if (style == IncDecButtons)
  40658. {
  40659. Rectangle<int> buttonRect (sliderRect);
  40660. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  40661. buttonRect.expand (-2, 0);
  40662. else
  40663. buttonRect.expand (0, -2);
  40664. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  40665. if (incDecButtonsSideBySide)
  40666. {
  40667. decButton->setBounds (buttonRect.getX(),
  40668. buttonRect.getY(),
  40669. buttonRect.getWidth() / 2,
  40670. buttonRect.getHeight());
  40671. decButton->setConnectedEdges (Button::ConnectedOnRight);
  40672. incButton->setBounds (buttonRect.getCentreX(),
  40673. buttonRect.getY(),
  40674. buttonRect.getWidth() / 2,
  40675. buttonRect.getHeight());
  40676. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  40677. }
  40678. else
  40679. {
  40680. incButton->setBounds (buttonRect.getX(),
  40681. buttonRect.getY(),
  40682. buttonRect.getWidth(),
  40683. buttonRect.getHeight() / 2);
  40684. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  40685. decButton->setBounds (buttonRect.getX(),
  40686. buttonRect.getCentreY(),
  40687. buttonRect.getWidth(),
  40688. buttonRect.getHeight() / 2);
  40689. decButton->setConnectedEdges (Button::ConnectedOnTop);
  40690. }
  40691. }
  40692. }
  40693. void Slider::focusOfChildComponentChanged (FocusChangeType)
  40694. {
  40695. repaint();
  40696. }
  40697. void Slider::mouseDown (const MouseEvent& e)
  40698. {
  40699. mouseWasHidden = false;
  40700. incDecDragged = false;
  40701. mouseXWhenLastDragged = e.x;
  40702. mouseYWhenLastDragged = e.y;
  40703. mouseDragStartX = e.getMouseDownX();
  40704. mouseDragStartY = e.getMouseDownY();
  40705. if (isEnabled())
  40706. {
  40707. if (e.mods.isPopupMenu() && menuEnabled)
  40708. {
  40709. menuShown = true;
  40710. PopupMenu m;
  40711. m.setLookAndFeel (&getLookAndFeel());
  40712. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  40713. m.addSeparator();
  40714. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40715. {
  40716. PopupMenu rotaryMenu;
  40717. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  40718. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  40719. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  40720. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  40721. }
  40722. const int r = m.show();
  40723. if (r == 1)
  40724. {
  40725. setVelocityBasedMode (! isVelocityBased);
  40726. }
  40727. else if (r == 2)
  40728. {
  40729. setSliderStyle (Rotary);
  40730. }
  40731. else if (r == 3)
  40732. {
  40733. setSliderStyle (RotaryHorizontalDrag);
  40734. }
  40735. else if (r == 4)
  40736. {
  40737. setSliderStyle (RotaryVerticalDrag);
  40738. }
  40739. }
  40740. else if (maximum > minimum)
  40741. {
  40742. menuShown = false;
  40743. if (valueBox != 0)
  40744. valueBox->hideEditor (true);
  40745. sliderBeingDragged = 0;
  40746. if (style == TwoValueHorizontal
  40747. || style == TwoValueVertical
  40748. || style == ThreeValueHorizontal
  40749. || style == ThreeValueVertical)
  40750. {
  40751. const float mousePos = (float) (isVertical() ? e.y : e.x);
  40752. const float normalPosDistance = std::abs (getLinearSliderPos (currentValue.getValue()) - mousePos);
  40753. const float minPosDistance = std::abs (getLinearSliderPos (valueMin.getValue()) - 0.1f - mousePos);
  40754. const float maxPosDistance = std::abs (getLinearSliderPos (valueMax.getValue()) + 0.1f - mousePos);
  40755. if (style == TwoValueHorizontal || style == TwoValueVertical)
  40756. {
  40757. if (maxPosDistance <= minPosDistance)
  40758. sliderBeingDragged = 2;
  40759. else
  40760. sliderBeingDragged = 1;
  40761. }
  40762. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  40763. {
  40764. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  40765. sliderBeingDragged = 1;
  40766. else if (normalPosDistance >= maxPosDistance)
  40767. sliderBeingDragged = 2;
  40768. }
  40769. }
  40770. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  40771. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  40772. * valueToProportionOfLength (currentValue.getValue());
  40773. valueWhenLastDragged = ((sliderBeingDragged == 2) ? valueMax
  40774. : ((sliderBeingDragged == 1) ? valueMin
  40775. : currentValue)).getValue();
  40776. valueOnMouseDown = valueWhenLastDragged;
  40777. if (popupDisplayEnabled)
  40778. {
  40779. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  40780. popupDisplay = popup;
  40781. if (parentForPopupDisplay != 0)
  40782. {
  40783. parentForPopupDisplay->addChildComponent (popup);
  40784. }
  40785. else
  40786. {
  40787. popup->addToDesktop (0);
  40788. }
  40789. popup->setVisible (true);
  40790. }
  40791. sendDragStart();
  40792. mouseDrag (e);
  40793. }
  40794. }
  40795. }
  40796. void Slider::mouseUp (const MouseEvent&)
  40797. {
  40798. if (isEnabled()
  40799. && (! menuShown)
  40800. && (maximum > minimum)
  40801. && (style != IncDecButtons || incDecDragged))
  40802. {
  40803. restoreMouseIfHidden();
  40804. if (sendChangeOnlyOnRelease && valueOnMouseDown != (double) currentValue.getValue())
  40805. triggerChangeMessage (false);
  40806. sendDragEnd();
  40807. popupDisplay = 0;
  40808. if (style == IncDecButtons)
  40809. {
  40810. incButton->setState (Button::buttonNormal);
  40811. decButton->setState (Button::buttonNormal);
  40812. }
  40813. }
  40814. }
  40815. void Slider::restoreMouseIfHidden()
  40816. {
  40817. if (mouseWasHidden)
  40818. {
  40819. mouseWasHidden = false;
  40820. for (int i = Desktop::getInstance().getNumMouseSources(); --i >= 0;)
  40821. Desktop::getInstance().getMouseSource(i)->enableUnboundedMouseMovement (false);
  40822. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  40823. : ((sliderBeingDragged == 1) ? getMinValue()
  40824. : (double) currentValue.getValue());
  40825. Point<int> mousePos;
  40826. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  40827. {
  40828. mousePos = Desktop::getLastMouseDownPosition();
  40829. if (style == RotaryHorizontalDrag)
  40830. {
  40831. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  40832. mousePos += Point<int> (roundToInt (pixelsForFullDragExtent * posDiff), 0);
  40833. }
  40834. else
  40835. {
  40836. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  40837. mousePos += Point<int> (0, roundToInt (pixelsForFullDragExtent * posDiff));
  40838. }
  40839. }
  40840. else
  40841. {
  40842. const int pixelPos = (int) getLinearSliderPos (pos);
  40843. mousePos = relativePositionToGlobal (Point<int> (isHorizontal() ? pixelPos : (getWidth() / 2),
  40844. isVertical() ? pixelPos : (getHeight() / 2)));
  40845. }
  40846. Desktop::setMousePosition (mousePos);
  40847. }
  40848. }
  40849. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  40850. {
  40851. if (isEnabled()
  40852. && style != IncDecButtons
  40853. && style != Rotary
  40854. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  40855. {
  40856. restoreMouseIfHidden();
  40857. }
  40858. }
  40859. namespace SliderHelpers
  40860. {
  40861. double smallestAngleBetween (double a1, double a2) throw()
  40862. {
  40863. return jmin (std::abs (a1 - a2),
  40864. std::abs (a1 + double_Pi * 2.0 - a2),
  40865. std::abs (a2 + double_Pi * 2.0 - a1));
  40866. }
  40867. }
  40868. void Slider::mouseDrag (const MouseEvent& e)
  40869. {
  40870. if (isEnabled()
  40871. && (! menuShown)
  40872. && (maximum > minimum))
  40873. {
  40874. if (style == Rotary)
  40875. {
  40876. int dx = e.x - sliderRect.getCentreX();
  40877. int dy = e.y - sliderRect.getCentreY();
  40878. if (dx * dx + dy * dy > 25)
  40879. {
  40880. double angle = std::atan2 ((double) dx, (double) -dy);
  40881. while (angle < 0.0)
  40882. angle += double_Pi * 2.0;
  40883. if (rotaryStop && ! e.mouseWasClicked())
  40884. {
  40885. if (std::abs (angle - lastAngle) > double_Pi)
  40886. {
  40887. if (angle >= lastAngle)
  40888. angle -= double_Pi * 2.0;
  40889. else
  40890. angle += double_Pi * 2.0;
  40891. }
  40892. if (angle >= lastAngle)
  40893. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  40894. else
  40895. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  40896. }
  40897. else
  40898. {
  40899. while (angle < rotaryStart)
  40900. angle += double_Pi * 2.0;
  40901. if (angle > rotaryEnd)
  40902. {
  40903. if (SliderHelpers::smallestAngleBetween (angle, rotaryStart)
  40904. <= SliderHelpers::smallestAngleBetween (angle, rotaryEnd))
  40905. angle = rotaryStart;
  40906. else
  40907. angle = rotaryEnd;
  40908. }
  40909. }
  40910. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  40911. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  40912. lastAngle = angle;
  40913. }
  40914. }
  40915. else
  40916. {
  40917. if (style == LinearBar && e.mouseWasClicked()
  40918. && valueBox != 0 && valueBox->isEditable())
  40919. return;
  40920. if (style == IncDecButtons && ! incDecDragged)
  40921. {
  40922. if (e.getDistanceFromDragStart() < 10 || e.mouseWasClicked())
  40923. return;
  40924. incDecDragged = true;
  40925. mouseDragStartX = e.x;
  40926. mouseDragStartY = e.y;
  40927. }
  40928. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  40929. : false))
  40930. || ((maximum - minimum) / sliderRegionSize < interval))
  40931. {
  40932. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  40933. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  40934. if (style == RotaryHorizontalDrag
  40935. || style == RotaryVerticalDrag
  40936. || style == IncDecButtons
  40937. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  40938. && ! snapsToMousePos))
  40939. {
  40940. const int mouseDiff = (style == RotaryHorizontalDrag
  40941. || style == LinearHorizontal
  40942. || style == LinearBar
  40943. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40944. ? e.x - mouseDragStartX
  40945. : mouseDragStartY - e.y;
  40946. double newPos = valueToProportionOfLength (valueOnMouseDown)
  40947. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  40948. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  40949. if (style == IncDecButtons)
  40950. {
  40951. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  40952. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  40953. }
  40954. }
  40955. else
  40956. {
  40957. if (isVertical())
  40958. scaledMousePos = 1.0 - scaledMousePos;
  40959. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  40960. }
  40961. }
  40962. else
  40963. {
  40964. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  40965. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  40966. ? e.x - mouseXWhenLastDragged
  40967. : e.y - mouseYWhenLastDragged;
  40968. const double maxSpeed = jmax (200, sliderRegionSize);
  40969. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  40970. if (speed != 0)
  40971. {
  40972. speed = 0.2 * velocityModeSensitivity
  40973. * (1.0 + std::sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  40974. + jmax (0.0, (double) (speed - velocityModeThreshold))
  40975. / maxSpeed))));
  40976. if (mouseDiff < 0)
  40977. speed = -speed;
  40978. if (isVertical() || style == RotaryVerticalDrag
  40979. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  40980. speed = -speed;
  40981. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  40982. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  40983. e.source.enableUnboundedMouseMovement (true, false);
  40984. mouseWasHidden = true;
  40985. }
  40986. }
  40987. }
  40988. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  40989. if (sliderBeingDragged == 0)
  40990. {
  40991. setValue (snapValue (valueWhenLastDragged, true),
  40992. ! sendChangeOnlyOnRelease, true);
  40993. }
  40994. else if (sliderBeingDragged == 1)
  40995. {
  40996. setMinValue (snapValue (valueWhenLastDragged, true),
  40997. ! sendChangeOnlyOnRelease, false, true);
  40998. if (e.mods.isShiftDown())
  40999. setMaxValue (getMinValue() + minMaxDiff, false, false, true);
  41000. else
  41001. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41002. }
  41003. else
  41004. {
  41005. jassert (sliderBeingDragged == 2);
  41006. setMaxValue (snapValue (valueWhenLastDragged, true),
  41007. ! sendChangeOnlyOnRelease, false, true);
  41008. if (e.mods.isShiftDown())
  41009. setMinValue (getMaxValue() - minMaxDiff, false, false, true);
  41010. else
  41011. minMaxDiff = (double) valueMax.getValue() - (double) valueMin.getValue();
  41012. }
  41013. mouseXWhenLastDragged = e.x;
  41014. mouseYWhenLastDragged = e.y;
  41015. }
  41016. }
  41017. void Slider::mouseDoubleClick (const MouseEvent&)
  41018. {
  41019. if (doubleClickToValue
  41020. && isEnabled()
  41021. && style != IncDecButtons
  41022. && minimum <= doubleClickReturnValue
  41023. && maximum >= doubleClickReturnValue)
  41024. {
  41025. sendDragStart();
  41026. setValue (doubleClickReturnValue, true, true);
  41027. sendDragEnd();
  41028. }
  41029. }
  41030. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  41031. {
  41032. if (scrollWheelEnabled && isEnabled()
  41033. && style != TwoValueHorizontal
  41034. && style != TwoValueVertical)
  41035. {
  41036. if (maximum > minimum && ! e.mods.isAnyMouseButtonDown())
  41037. {
  41038. if (valueBox != 0)
  41039. valueBox->hideEditor (false);
  41040. const double value = (double) currentValue.getValue();
  41041. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  41042. const double currentPos = valueToProportionOfLength (value);
  41043. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  41044. double delta = (newValue != value)
  41045. ? jmax (std::abs (newValue - value), interval) : 0;
  41046. if (value > newValue)
  41047. delta = -delta;
  41048. sendDragStart();
  41049. setValue (snapValue (value + delta, false), true, true);
  41050. sendDragEnd();
  41051. }
  41052. }
  41053. else
  41054. {
  41055. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  41056. }
  41057. }
  41058. void SliderListener::sliderDragStarted (Slider*) // (can't write Slider::Listener due to idiotic VC2005 bug)
  41059. {
  41060. }
  41061. void SliderListener::sliderDragEnded (Slider*)
  41062. {
  41063. }
  41064. END_JUCE_NAMESPACE
  41065. /*** End of inlined file: juce_Slider.cpp ***/
  41066. /*** Start of inlined file: juce_TableHeaderComponent.cpp ***/
  41067. BEGIN_JUCE_NAMESPACE
  41068. class DragOverlayComp : public Component
  41069. {
  41070. public:
  41071. DragOverlayComp (const Image& image_)
  41072. : image (image_)
  41073. {
  41074. image.duplicateIfShared();
  41075. image.multiplyAllAlphas (0.8f);
  41076. setAlwaysOnTop (true);
  41077. }
  41078. ~DragOverlayComp()
  41079. {
  41080. }
  41081. void paint (Graphics& g)
  41082. {
  41083. g.drawImageAt (image, 0, 0);
  41084. }
  41085. private:
  41086. Image image;
  41087. DragOverlayComp (const DragOverlayComp&);
  41088. DragOverlayComp& operator= (const DragOverlayComp&);
  41089. };
  41090. TableHeaderComponent::TableHeaderComponent()
  41091. : columnsChanged (false),
  41092. columnsResized (false),
  41093. sortChanged (false),
  41094. menuActive (true),
  41095. stretchToFit (false),
  41096. columnIdBeingResized (0),
  41097. columnIdBeingDragged (0),
  41098. columnIdUnderMouse (0),
  41099. lastDeliberateWidth (0)
  41100. {
  41101. }
  41102. TableHeaderComponent::~TableHeaderComponent()
  41103. {
  41104. dragOverlayComp = 0;
  41105. }
  41106. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  41107. {
  41108. menuActive = hasMenu;
  41109. }
  41110. bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
  41111. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
  41112. {
  41113. if (onlyCountVisibleColumns)
  41114. {
  41115. int num = 0;
  41116. for (int i = columns.size(); --i >= 0;)
  41117. if (columns.getUnchecked(i)->isVisible())
  41118. ++num;
  41119. return num;
  41120. }
  41121. else
  41122. {
  41123. return columns.size();
  41124. }
  41125. }
  41126. const String TableHeaderComponent::getColumnName (const int columnId) const
  41127. {
  41128. const ColumnInfo* const ci = getInfoForId (columnId);
  41129. return ci != 0 ? ci->name : String::empty;
  41130. }
  41131. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  41132. {
  41133. ColumnInfo* const ci = getInfoForId (columnId);
  41134. if (ci != 0 && ci->name != newName)
  41135. {
  41136. ci->name = newName;
  41137. sendColumnsChanged();
  41138. }
  41139. }
  41140. void TableHeaderComponent::addColumn (const String& columnName,
  41141. const int columnId,
  41142. const int width,
  41143. const int minimumWidth,
  41144. const int maximumWidth,
  41145. const int propertyFlags,
  41146. const int insertIndex)
  41147. {
  41148. // can't have a duplicate or null ID!
  41149. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  41150. jassert (width > 0);
  41151. ColumnInfo* const ci = new ColumnInfo();
  41152. ci->name = columnName;
  41153. ci->id = columnId;
  41154. ci->width = width;
  41155. ci->lastDeliberateWidth = width;
  41156. ci->minimumWidth = minimumWidth;
  41157. ci->maximumWidth = maximumWidth;
  41158. if (ci->maximumWidth < 0)
  41159. ci->maximumWidth = std::numeric_limits<int>::max();
  41160. jassert (ci->maximumWidth >= ci->minimumWidth);
  41161. ci->propertyFlags = propertyFlags;
  41162. columns.insert (insertIndex, ci);
  41163. sendColumnsChanged();
  41164. }
  41165. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  41166. {
  41167. const int index = getIndexOfColumnId (columnIdToRemove, false);
  41168. if (index >= 0)
  41169. {
  41170. columns.remove (index);
  41171. sortChanged = true;
  41172. sendColumnsChanged();
  41173. }
  41174. }
  41175. void TableHeaderComponent::removeAllColumns()
  41176. {
  41177. if (columns.size() > 0)
  41178. {
  41179. columns.clear();
  41180. sendColumnsChanged();
  41181. }
  41182. }
  41183. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  41184. {
  41185. const int currentIndex = getIndexOfColumnId (columnId, false);
  41186. newIndex = visibleIndexToTotalIndex (newIndex);
  41187. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  41188. {
  41189. columns.move (currentIndex, newIndex);
  41190. sendColumnsChanged();
  41191. }
  41192. }
  41193. int TableHeaderComponent::getColumnWidth (const int columnId) const
  41194. {
  41195. const ColumnInfo* const ci = getInfoForId (columnId);
  41196. return ci != 0 ? ci->width : 0;
  41197. }
  41198. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  41199. {
  41200. ColumnInfo* const ci = getInfoForId (columnId);
  41201. if (ci != 0 && ci->width != newWidth)
  41202. {
  41203. const int numColumns = getNumColumns (true);
  41204. ci->lastDeliberateWidth = ci->width
  41205. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  41206. if (stretchToFit)
  41207. {
  41208. const int index = getIndexOfColumnId (columnId, true) + 1;
  41209. if (((unsigned int) index) < (unsigned int) numColumns)
  41210. {
  41211. const int x = getColumnPosition (index).getX();
  41212. if (lastDeliberateWidth == 0)
  41213. lastDeliberateWidth = getTotalWidth();
  41214. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  41215. }
  41216. }
  41217. repaint();
  41218. columnsResized = true;
  41219. triggerAsyncUpdate();
  41220. }
  41221. }
  41222. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
  41223. {
  41224. int n = 0;
  41225. for (int i = 0; i < columns.size(); ++i)
  41226. {
  41227. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  41228. {
  41229. if (columns.getUnchecked(i)->id == columnId)
  41230. return n;
  41231. ++n;
  41232. }
  41233. }
  41234. return -1;
  41235. }
  41236. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
  41237. {
  41238. if (onlyCountVisibleColumns)
  41239. index = visibleIndexToTotalIndex (index);
  41240. const ColumnInfo* const ci = columns [index];
  41241. return (ci != 0) ? ci->id : 0;
  41242. }
  41243. const Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
  41244. {
  41245. int x = 0, width = 0, n = 0;
  41246. for (int i = 0; i < columns.size(); ++i)
  41247. {
  41248. x += width;
  41249. if (columns.getUnchecked(i)->isVisible())
  41250. {
  41251. width = columns.getUnchecked(i)->width;
  41252. if (n++ == index)
  41253. break;
  41254. }
  41255. else
  41256. {
  41257. width = 0;
  41258. }
  41259. }
  41260. return Rectangle<int> (x, 0, width, getHeight());
  41261. }
  41262. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
  41263. {
  41264. if (xToFind >= 0)
  41265. {
  41266. int x = 0;
  41267. for (int i = 0; i < columns.size(); ++i)
  41268. {
  41269. const ColumnInfo* const ci = columns.getUnchecked(i);
  41270. if (ci->isVisible())
  41271. {
  41272. x += ci->width;
  41273. if (xToFind < x)
  41274. return ci->id;
  41275. }
  41276. }
  41277. }
  41278. return 0;
  41279. }
  41280. int TableHeaderComponent::getTotalWidth() const
  41281. {
  41282. int w = 0;
  41283. for (int i = columns.size(); --i >= 0;)
  41284. if (columns.getUnchecked(i)->isVisible())
  41285. w += columns.getUnchecked(i)->width;
  41286. return w;
  41287. }
  41288. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  41289. {
  41290. stretchToFit = shouldStretchToFit;
  41291. lastDeliberateWidth = getTotalWidth();
  41292. resized();
  41293. }
  41294. bool TableHeaderComponent::isStretchToFitActive() const
  41295. {
  41296. return stretchToFit;
  41297. }
  41298. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  41299. {
  41300. if (stretchToFit && getWidth() > 0
  41301. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  41302. {
  41303. lastDeliberateWidth = targetTotalWidth;
  41304. resizeColumnsToFit (0, targetTotalWidth);
  41305. }
  41306. }
  41307. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  41308. {
  41309. targetTotalWidth = jmax (targetTotalWidth, 0);
  41310. StretchableObjectResizer sor;
  41311. int i;
  41312. for (i = firstColumnIndex; i < columns.size(); ++i)
  41313. {
  41314. ColumnInfo* const ci = columns.getUnchecked(i);
  41315. if (ci->isVisible())
  41316. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  41317. }
  41318. sor.resizeToFit (targetTotalWidth);
  41319. int visIndex = 0;
  41320. for (i = firstColumnIndex; i < columns.size(); ++i)
  41321. {
  41322. ColumnInfo* const ci = columns.getUnchecked(i);
  41323. if (ci->isVisible())
  41324. {
  41325. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  41326. (int) std::floor (sor.getItemSize (visIndex++)));
  41327. if (newWidth != ci->width)
  41328. {
  41329. ci->width = newWidth;
  41330. repaint();
  41331. columnsResized = true;
  41332. triggerAsyncUpdate();
  41333. }
  41334. }
  41335. }
  41336. }
  41337. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  41338. {
  41339. ColumnInfo* const ci = getInfoForId (columnId);
  41340. if (ci != 0 && shouldBeVisible != ci->isVisible())
  41341. {
  41342. if (shouldBeVisible)
  41343. ci->propertyFlags |= visible;
  41344. else
  41345. ci->propertyFlags &= ~visible;
  41346. sendColumnsChanged();
  41347. resized();
  41348. }
  41349. }
  41350. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  41351. {
  41352. const ColumnInfo* const ci = getInfoForId (columnId);
  41353. return ci != 0 && ci->isVisible();
  41354. }
  41355. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  41356. {
  41357. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  41358. {
  41359. for (int i = columns.size(); --i >= 0;)
  41360. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  41361. ColumnInfo* const ci = getInfoForId (columnId);
  41362. if (ci != 0)
  41363. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  41364. reSortTable();
  41365. }
  41366. }
  41367. int TableHeaderComponent::getSortColumnId() const
  41368. {
  41369. for (int i = columns.size(); --i >= 0;)
  41370. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41371. return columns.getUnchecked(i)->id;
  41372. return 0;
  41373. }
  41374. bool TableHeaderComponent::isSortedForwards() const
  41375. {
  41376. for (int i = columns.size(); --i >= 0;)
  41377. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  41378. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  41379. return true;
  41380. }
  41381. void TableHeaderComponent::reSortTable()
  41382. {
  41383. sortChanged = true;
  41384. repaint();
  41385. triggerAsyncUpdate();
  41386. }
  41387. const String TableHeaderComponent::toString() const
  41388. {
  41389. String s;
  41390. XmlElement doc ("TABLELAYOUT");
  41391. doc.setAttribute ("sortedCol", getSortColumnId());
  41392. doc.setAttribute ("sortForwards", isSortedForwards());
  41393. for (int i = 0; i < columns.size(); ++i)
  41394. {
  41395. const ColumnInfo* const ci = columns.getUnchecked (i);
  41396. XmlElement* const e = doc.createNewChildElement ("COLUMN");
  41397. e->setAttribute ("id", ci->id);
  41398. e->setAttribute ("visible", ci->isVisible());
  41399. e->setAttribute ("width", ci->width);
  41400. }
  41401. return doc.createDocument (String::empty, true, false);
  41402. }
  41403. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  41404. {
  41405. XmlDocument doc (storedVersion);
  41406. ScopedPointer <XmlElement> storedXml (doc.getDocumentElement());
  41407. int index = 0;
  41408. if (storedXml != 0 && storedXml->hasTagName ("TABLELAYOUT"))
  41409. {
  41410. forEachXmlChildElement (*storedXml, col)
  41411. {
  41412. const int tabId = col->getIntAttribute ("id");
  41413. ColumnInfo* const ci = getInfoForId (tabId);
  41414. if (ci != 0)
  41415. {
  41416. columns.move (columns.indexOf (ci), index);
  41417. ci->width = col->getIntAttribute ("width");
  41418. setColumnVisible (tabId, col->getBoolAttribute ("visible"));
  41419. }
  41420. ++index;
  41421. }
  41422. columnsResized = true;
  41423. sendColumnsChanged();
  41424. setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
  41425. storedXml->getBoolAttribute ("sortForwards", true));
  41426. }
  41427. }
  41428. void TableHeaderComponent::addListener (Listener* const newListener)
  41429. {
  41430. listeners.addIfNotAlreadyThere (newListener);
  41431. }
  41432. void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
  41433. {
  41434. listeners.removeValue (listenerToRemove);
  41435. }
  41436. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  41437. {
  41438. const ColumnInfo* const ci = getInfoForId (columnId);
  41439. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  41440. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  41441. }
  41442. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  41443. {
  41444. for (int i = 0; i < columns.size(); ++i)
  41445. {
  41446. const ColumnInfo* const ci = columns.getUnchecked(i);
  41447. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  41448. menu.addItem (ci->id, ci->name,
  41449. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  41450. isColumnVisible (ci->id));
  41451. }
  41452. }
  41453. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  41454. {
  41455. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  41456. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  41457. }
  41458. void TableHeaderComponent::paint (Graphics& g)
  41459. {
  41460. LookAndFeel& lf = getLookAndFeel();
  41461. lf.drawTableHeaderBackground (g, *this);
  41462. const Rectangle<int> clip (g.getClipBounds());
  41463. int x = 0;
  41464. for (int i = 0; i < columns.size(); ++i)
  41465. {
  41466. const ColumnInfo* const ci = columns.getUnchecked(i);
  41467. if (ci->isVisible())
  41468. {
  41469. if (x + ci->width > clip.getX()
  41470. && (ci->id != columnIdBeingDragged
  41471. || dragOverlayComp == 0
  41472. || ! dragOverlayComp->isVisible()))
  41473. {
  41474. g.saveState();
  41475. g.setOrigin (x, 0);
  41476. g.reduceClipRegion (0, 0, ci->width, getHeight());
  41477. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  41478. ci->id == columnIdUnderMouse,
  41479. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  41480. ci->propertyFlags);
  41481. g.restoreState();
  41482. }
  41483. x += ci->width;
  41484. if (x >= clip.getRight())
  41485. break;
  41486. }
  41487. }
  41488. }
  41489. void TableHeaderComponent::resized()
  41490. {
  41491. }
  41492. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  41493. {
  41494. updateColumnUnderMouse (e.x, e.y);
  41495. }
  41496. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  41497. {
  41498. updateColumnUnderMouse (e.x, e.y);
  41499. }
  41500. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  41501. {
  41502. updateColumnUnderMouse (e.x, e.y);
  41503. }
  41504. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  41505. {
  41506. repaint();
  41507. columnIdBeingResized = 0;
  41508. columnIdBeingDragged = 0;
  41509. if (columnIdUnderMouse != 0)
  41510. {
  41511. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  41512. if (e.mods.isPopupMenu())
  41513. columnClicked (columnIdUnderMouse, e.mods);
  41514. }
  41515. if (menuActive && e.mods.isPopupMenu())
  41516. showColumnChooserMenu (columnIdUnderMouse);
  41517. }
  41518. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  41519. {
  41520. if (columnIdBeingResized == 0
  41521. && columnIdBeingDragged == 0
  41522. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  41523. {
  41524. dragOverlayComp = 0;
  41525. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  41526. if (columnIdBeingResized != 0)
  41527. {
  41528. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41529. initialColumnWidth = ci->width;
  41530. }
  41531. else
  41532. {
  41533. beginDrag (e);
  41534. }
  41535. }
  41536. if (columnIdBeingResized != 0)
  41537. {
  41538. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  41539. if (ci != 0)
  41540. {
  41541. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  41542. initialColumnWidth + e.getDistanceFromDragStartX());
  41543. if (stretchToFit)
  41544. {
  41545. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  41546. int minWidthOnRight = 0;
  41547. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  41548. if (columns.getUnchecked (i)->isVisible())
  41549. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  41550. const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  41551. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  41552. }
  41553. setColumnWidth (columnIdBeingResized, w);
  41554. }
  41555. }
  41556. else if (columnIdBeingDragged != 0)
  41557. {
  41558. if (e.y >= -50 && e.y < getHeight() + 50)
  41559. {
  41560. if (dragOverlayComp != 0)
  41561. {
  41562. dragOverlayComp->setVisible (true);
  41563. dragOverlayComp->setBounds (jlimit (0,
  41564. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  41565. e.x - draggingColumnOffset),
  41566. 0,
  41567. dragOverlayComp->getWidth(),
  41568. getHeight());
  41569. for (int i = columns.size(); --i >= 0;)
  41570. {
  41571. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41572. int newIndex = currentIndex;
  41573. if (newIndex > 0)
  41574. {
  41575. // if the previous column isn't draggable, we can't move our column
  41576. // past it, because that'd change the undraggable column's position..
  41577. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  41578. if ((previous->propertyFlags & draggable) != 0)
  41579. {
  41580. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  41581. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  41582. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  41583. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  41584. {
  41585. --newIndex;
  41586. }
  41587. }
  41588. }
  41589. if (newIndex < columns.size() - 1)
  41590. {
  41591. // if the next column isn't draggable, we can't move our column
  41592. // past it, because that'd change the undraggable column's position..
  41593. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  41594. if ((nextCol->propertyFlags & draggable) != 0)
  41595. {
  41596. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  41597. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  41598. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  41599. > abs (dragOverlayComp->getRight() - rightOfNext))
  41600. {
  41601. ++newIndex;
  41602. }
  41603. }
  41604. }
  41605. if (newIndex != currentIndex)
  41606. moveColumn (columnIdBeingDragged, newIndex);
  41607. else
  41608. break;
  41609. }
  41610. }
  41611. }
  41612. else
  41613. {
  41614. endDrag (draggingColumnOriginalIndex);
  41615. }
  41616. }
  41617. }
  41618. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  41619. {
  41620. if (columnIdBeingDragged == 0)
  41621. {
  41622. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  41623. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  41624. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  41625. {
  41626. columnIdBeingDragged = 0;
  41627. }
  41628. else
  41629. {
  41630. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  41631. const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
  41632. const int temp = columnIdBeingDragged;
  41633. columnIdBeingDragged = 0;
  41634. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  41635. columnIdBeingDragged = temp;
  41636. dragOverlayComp->setBounds (columnRect);
  41637. for (int i = listeners.size(); --i >= 0;)
  41638. {
  41639. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  41640. i = jmin (i, listeners.size() - 1);
  41641. }
  41642. }
  41643. }
  41644. }
  41645. void TableHeaderComponent::endDrag (const int finalIndex)
  41646. {
  41647. if (columnIdBeingDragged != 0)
  41648. {
  41649. moveColumn (columnIdBeingDragged, finalIndex);
  41650. columnIdBeingDragged = 0;
  41651. repaint();
  41652. for (int i = listeners.size(); --i >= 0;)
  41653. {
  41654. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  41655. i = jmin (i, listeners.size() - 1);
  41656. }
  41657. }
  41658. }
  41659. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  41660. {
  41661. mouseDrag (e);
  41662. for (int i = columns.size(); --i >= 0;)
  41663. if (columns.getUnchecked (i)->isVisible())
  41664. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  41665. columnIdBeingResized = 0;
  41666. repaint();
  41667. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  41668. updateColumnUnderMouse (e.x, e.y);
  41669. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  41670. columnClicked (columnIdUnderMouse, e.mods);
  41671. dragOverlayComp = 0;
  41672. }
  41673. const MouseCursor TableHeaderComponent::getMouseCursor()
  41674. {
  41675. if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
  41676. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  41677. return Component::getMouseCursor();
  41678. }
  41679. bool TableHeaderComponent::ColumnInfo::isVisible() const
  41680. {
  41681. return (propertyFlags & TableHeaderComponent::visible) != 0;
  41682. }
  41683. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
  41684. {
  41685. for (int i = columns.size(); --i >= 0;)
  41686. if (columns.getUnchecked(i)->id == id)
  41687. return columns.getUnchecked(i);
  41688. return 0;
  41689. }
  41690. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
  41691. {
  41692. int n = 0;
  41693. for (int i = 0; i < columns.size(); ++i)
  41694. {
  41695. if (columns.getUnchecked(i)->isVisible())
  41696. {
  41697. if (n == visibleIndex)
  41698. return i;
  41699. ++n;
  41700. }
  41701. }
  41702. return -1;
  41703. }
  41704. void TableHeaderComponent::sendColumnsChanged()
  41705. {
  41706. if (stretchToFit && lastDeliberateWidth > 0)
  41707. resizeAllColumnsToFit (lastDeliberateWidth);
  41708. repaint();
  41709. columnsChanged = true;
  41710. triggerAsyncUpdate();
  41711. }
  41712. void TableHeaderComponent::handleAsyncUpdate()
  41713. {
  41714. const bool changed = columnsChanged || sortChanged;
  41715. const bool sized = columnsResized || changed;
  41716. const bool sorted = sortChanged;
  41717. columnsChanged = false;
  41718. columnsResized = false;
  41719. sortChanged = false;
  41720. if (sorted)
  41721. {
  41722. for (int i = listeners.size(); --i >= 0;)
  41723. {
  41724. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  41725. i = jmin (i, listeners.size() - 1);
  41726. }
  41727. }
  41728. if (changed)
  41729. {
  41730. for (int i = listeners.size(); --i >= 0;)
  41731. {
  41732. listeners.getUnchecked(i)->tableColumnsChanged (this);
  41733. i = jmin (i, listeners.size() - 1);
  41734. }
  41735. }
  41736. if (sized)
  41737. {
  41738. for (int i = listeners.size(); --i >= 0;)
  41739. {
  41740. listeners.getUnchecked(i)->tableColumnsResized (this);
  41741. i = jmin (i, listeners.size() - 1);
  41742. }
  41743. }
  41744. }
  41745. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
  41746. {
  41747. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  41748. {
  41749. const int draggableDistance = 3;
  41750. int x = 0;
  41751. for (int i = 0; i < columns.size(); ++i)
  41752. {
  41753. const ColumnInfo* const ci = columns.getUnchecked(i);
  41754. if (ci->isVisible())
  41755. {
  41756. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  41757. && (ci->propertyFlags & resizable) != 0)
  41758. return ci->id;
  41759. x += ci->width;
  41760. }
  41761. }
  41762. }
  41763. return 0;
  41764. }
  41765. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  41766. {
  41767. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  41768. ? getColumnIdAtX (x) : 0;
  41769. if (newCol != columnIdUnderMouse)
  41770. {
  41771. columnIdUnderMouse = newCol;
  41772. repaint();
  41773. }
  41774. }
  41775. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  41776. {
  41777. PopupMenu m;
  41778. addMenuItems (m, columnIdClicked);
  41779. if (m.getNumItems() > 0)
  41780. {
  41781. m.setLookAndFeel (&getLookAndFeel());
  41782. const int result = m.show();
  41783. if (result != 0)
  41784. reactToMenuItem (result, columnIdClicked);
  41785. }
  41786. }
  41787. void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  41788. {
  41789. }
  41790. END_JUCE_NAMESPACE
  41791. /*** End of inlined file: juce_TableHeaderComponent.cpp ***/
  41792. /*** Start of inlined file: juce_TableListBox.cpp ***/
  41793. BEGIN_JUCE_NAMESPACE
  41794. static const char* const tableColumnPropertyTag = "_tableColumnID";
  41795. class TableListRowComp : public Component,
  41796. public TooltipClient
  41797. {
  41798. public:
  41799. TableListRowComp (TableListBox& owner_)
  41800. : owner (owner_),
  41801. row (-1),
  41802. isSelected (false)
  41803. {
  41804. }
  41805. ~TableListRowComp()
  41806. {
  41807. deleteAllChildren();
  41808. }
  41809. void paint (Graphics& g)
  41810. {
  41811. TableListBoxModel* const model = owner.getModel();
  41812. if (model != 0)
  41813. {
  41814. const TableHeaderComponent* const header = owner.getHeader();
  41815. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  41816. const int numColumns = header->getNumColumns (true);
  41817. for (int i = 0; i < numColumns; ++i)
  41818. {
  41819. if (! columnsWithComponents [i])
  41820. {
  41821. const int columnId = header->getColumnIdOfIndex (i, true);
  41822. Rectangle<int> columnRect (header->getColumnPosition (i));
  41823. columnRect.setSize (columnRect.getWidth(), getHeight());
  41824. g.saveState();
  41825. g.reduceClipRegion (columnRect);
  41826. g.setOrigin (columnRect.getX(), 0);
  41827. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  41828. g.restoreState();
  41829. }
  41830. }
  41831. }
  41832. }
  41833. void update (const int newRow, const bool isNowSelected)
  41834. {
  41835. if (newRow != row || isNowSelected != isSelected)
  41836. {
  41837. row = newRow;
  41838. isSelected = isNowSelected;
  41839. repaint();
  41840. deleteAllChildren();
  41841. }
  41842. if (row < owner.getNumRows())
  41843. {
  41844. jassert (row >= 0);
  41845. const Identifier tagPropertyName ("_tableLastUseNum");
  41846. const int newTag = Random::getSystemRandom().nextInt();
  41847. const TableHeaderComponent* const header = owner.getHeader();
  41848. const int numColumns = header->getNumColumns (true);
  41849. columnsWithComponents.clear();
  41850. if (owner.getModel() != 0)
  41851. {
  41852. for (int i = 0; i < numColumns; ++i)
  41853. {
  41854. const int columnId = header->getColumnIdOfIndex (i, true);
  41855. Component* const newComp
  41856. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  41857. findChildComponentForColumn (columnId));
  41858. if (newComp != 0)
  41859. {
  41860. addAndMakeVisible (newComp);
  41861. newComp->getProperties().set (tagPropertyName, newTag);
  41862. newComp->getProperties().set (tableColumnPropertyTag, columnId);
  41863. const Rectangle<int> columnRect (header->getColumnPosition (i));
  41864. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41865. columnsWithComponents.setBit (i);
  41866. }
  41867. }
  41868. }
  41869. for (int i = getNumChildComponents(); --i >= 0;)
  41870. {
  41871. Component* const c = getChildComponent (i);
  41872. if ((int) c->getProperties() [tagPropertyName] != newTag)
  41873. delete c;
  41874. }
  41875. }
  41876. else
  41877. {
  41878. columnsWithComponents.clear();
  41879. deleteAllChildren();
  41880. }
  41881. }
  41882. void resized()
  41883. {
  41884. for (int i = getNumChildComponents(); --i >= 0;)
  41885. {
  41886. Component* const c = getChildComponent (i);
  41887. const int columnId = c->getProperties() [tableColumnPropertyTag];
  41888. if (columnId != 0)
  41889. {
  41890. const Rectangle<int> columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  41891. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  41892. }
  41893. }
  41894. }
  41895. void mouseDown (const MouseEvent& e)
  41896. {
  41897. isDragging = false;
  41898. selectRowOnMouseUp = false;
  41899. if (isEnabled())
  41900. {
  41901. if (! isSelected)
  41902. {
  41903. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41904. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41905. if (columnId != 0 && owner.getModel() != 0)
  41906. owner.getModel()->cellClicked (row, columnId, e);
  41907. }
  41908. else
  41909. {
  41910. selectRowOnMouseUp = true;
  41911. }
  41912. }
  41913. }
  41914. void mouseDrag (const MouseEvent& e)
  41915. {
  41916. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  41917. {
  41918. const SparseSet<int> selectedRows (owner.getSelectedRows());
  41919. if (selectedRows.size() > 0)
  41920. {
  41921. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  41922. if (dragDescription.isNotEmpty())
  41923. {
  41924. isDragging = true;
  41925. owner.startDragAndDrop (e, dragDescription);
  41926. }
  41927. }
  41928. }
  41929. }
  41930. void mouseUp (const MouseEvent& e)
  41931. {
  41932. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  41933. {
  41934. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  41935. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41936. if (columnId != 0 && owner.getModel() != 0)
  41937. owner.getModel()->cellClicked (row, columnId, e);
  41938. }
  41939. }
  41940. void mouseDoubleClick (const MouseEvent& e)
  41941. {
  41942. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  41943. if (columnId != 0 && owner.getModel() != 0)
  41944. owner.getModel()->cellDoubleClicked (row, columnId, e);
  41945. }
  41946. const String getTooltip()
  41947. {
  41948. const int columnId = owner.getHeader()->getColumnIdAtX (getMouseXYRelative().getX());
  41949. if (columnId != 0 && owner.getModel() != 0)
  41950. return owner.getModel()->getCellTooltip (row, columnId);
  41951. return String::empty;
  41952. }
  41953. Component* findChildComponentForColumn (const int columnId) const
  41954. {
  41955. for (int i = getNumChildComponents(); --i >= 0;)
  41956. {
  41957. Component* const c = getChildComponent (i);
  41958. if ((int) c->getProperties() [tableColumnPropertyTag] == columnId)
  41959. return c;
  41960. }
  41961. return 0;
  41962. }
  41963. juce_UseDebuggingNewOperator
  41964. private:
  41965. TableListBox& owner;
  41966. int row;
  41967. bool isSelected, isDragging, selectRowOnMouseUp;
  41968. BigInteger columnsWithComponents;
  41969. TableListRowComp (const TableListRowComp&);
  41970. TableListRowComp& operator= (const TableListRowComp&);
  41971. };
  41972. class TableListBoxHeader : public TableHeaderComponent
  41973. {
  41974. public:
  41975. TableListBoxHeader (TableListBox& owner_)
  41976. : owner (owner_)
  41977. {
  41978. }
  41979. void addMenuItems (PopupMenu& menu, int columnIdClicked)
  41980. {
  41981. if (owner.isAutoSizeMenuOptionShown())
  41982. {
  41983. menu.addItem (autoSizeColumnId, TRANS("Auto-size this column"), columnIdClicked != 0);
  41984. menu.addItem (autoSizeAllId, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  41985. menu.addSeparator();
  41986. }
  41987. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  41988. }
  41989. void reactToMenuItem (int menuReturnId, int columnIdClicked)
  41990. {
  41991. if (menuReturnId == autoSizeColumnId)
  41992. {
  41993. owner.autoSizeColumn (columnIdClicked);
  41994. }
  41995. else if (menuReturnId == autoSizeAllId)
  41996. {
  41997. owner.autoSizeAllColumns();
  41998. }
  41999. else
  42000. {
  42001. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  42002. }
  42003. }
  42004. juce_UseDebuggingNewOperator
  42005. private:
  42006. TableListBox& owner;
  42007. enum { autoSizeColumnId = 0xf836743, autoSizeAllId = 0xf836744 };
  42008. TableListBoxHeader (const TableListBoxHeader&);
  42009. TableListBoxHeader& operator= (const TableListBoxHeader&);
  42010. };
  42011. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  42012. : ListBox (name, 0),
  42013. model (model_),
  42014. autoSizeOptionsShown (true)
  42015. {
  42016. ListBox::model = this;
  42017. header = new TableListBoxHeader (*this);
  42018. header->setSize (100, 28);
  42019. header->addListener (this);
  42020. setHeaderComponent (header);
  42021. }
  42022. TableListBox::~TableListBox()
  42023. {
  42024. header = 0;
  42025. }
  42026. void TableListBox::setModel (TableListBoxModel* const newModel)
  42027. {
  42028. if (model != newModel)
  42029. {
  42030. model = newModel;
  42031. updateContent();
  42032. }
  42033. }
  42034. int TableListBox::getHeaderHeight() const
  42035. {
  42036. return header->getHeight();
  42037. }
  42038. void TableListBox::setHeaderHeight (const int newHeight)
  42039. {
  42040. header->setSize (header->getWidth(), newHeight);
  42041. resized();
  42042. }
  42043. void TableListBox::autoSizeColumn (const int columnId)
  42044. {
  42045. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  42046. if (width > 0)
  42047. header->setColumnWidth (columnId, width);
  42048. }
  42049. void TableListBox::autoSizeAllColumns()
  42050. {
  42051. for (int i = 0; i < header->getNumColumns (true); ++i)
  42052. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  42053. }
  42054. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  42055. {
  42056. autoSizeOptionsShown = shouldBeShown;
  42057. }
  42058. bool TableListBox::isAutoSizeMenuOptionShown() const
  42059. {
  42060. return autoSizeOptionsShown;
  42061. }
  42062. const Rectangle<int> TableListBox::getCellPosition (const int columnId,
  42063. const int rowNumber,
  42064. const bool relativeToComponentTopLeft) const
  42065. {
  42066. Rectangle<int> headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42067. if (relativeToComponentTopLeft)
  42068. headerCell.translate (header->getX(), 0);
  42069. const Rectangle<int> row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  42070. return Rectangle<int> (headerCell.getX(), row.getY(),
  42071. headerCell.getWidth(), row.getHeight());
  42072. }
  42073. Component* TableListBox::getCellComponent (int columnId, int rowNumber) const
  42074. {
  42075. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (rowNumber));
  42076. return rowComp != 0 ? rowComp->findChildComponentForColumn (columnId) : 0;
  42077. }
  42078. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  42079. {
  42080. ScrollBar* const scrollbar = getHorizontalScrollBar();
  42081. if (scrollbar != 0)
  42082. {
  42083. const Rectangle<int> pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  42084. double x = scrollbar->getCurrentRangeStart();
  42085. const double w = scrollbar->getCurrentRangeSize();
  42086. if (pos.getX() < x)
  42087. x = pos.getX();
  42088. else if (pos.getRight() > x + w)
  42089. x += jmax (0.0, pos.getRight() - (x + w));
  42090. scrollbar->setCurrentRangeStart (x);
  42091. }
  42092. }
  42093. int TableListBox::getNumRows()
  42094. {
  42095. return model != 0 ? model->getNumRows() : 0;
  42096. }
  42097. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  42098. {
  42099. }
  42100. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected_, Component* existingComponentToUpdate)
  42101. {
  42102. if (existingComponentToUpdate == 0)
  42103. existingComponentToUpdate = new TableListRowComp (*this);
  42104. static_cast <TableListRowComp*> (existingComponentToUpdate)->update (rowNumber, isRowSelected_);
  42105. return existingComponentToUpdate;
  42106. }
  42107. void TableListBox::selectedRowsChanged (int row)
  42108. {
  42109. if (model != 0)
  42110. model->selectedRowsChanged (row);
  42111. }
  42112. void TableListBox::deleteKeyPressed (int row)
  42113. {
  42114. if (model != 0)
  42115. model->deleteKeyPressed (row);
  42116. }
  42117. void TableListBox::returnKeyPressed (int row)
  42118. {
  42119. if (model != 0)
  42120. model->returnKeyPressed (row);
  42121. }
  42122. void TableListBox::backgroundClicked()
  42123. {
  42124. if (model != 0)
  42125. model->backgroundClicked();
  42126. }
  42127. void TableListBox::listWasScrolled()
  42128. {
  42129. if (model != 0)
  42130. model->listWasScrolled();
  42131. }
  42132. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  42133. {
  42134. setMinimumContentWidth (header->getTotalWidth());
  42135. repaint();
  42136. updateColumnComponents();
  42137. }
  42138. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  42139. {
  42140. setMinimumContentWidth (header->getTotalWidth());
  42141. repaint();
  42142. updateColumnComponents();
  42143. }
  42144. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  42145. {
  42146. if (model != 0)
  42147. model->sortOrderChanged (header->getSortColumnId(),
  42148. header->isSortedForwards());
  42149. }
  42150. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  42151. {
  42152. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  42153. repaint();
  42154. }
  42155. void TableListBox::resized()
  42156. {
  42157. ListBox::resized();
  42158. header->resizeAllColumnsToFit (getVisibleContentWidth());
  42159. setMinimumContentWidth (header->getTotalWidth());
  42160. }
  42161. void TableListBox::updateColumnComponents() const
  42162. {
  42163. const int firstRow = getRowContainingPosition (0, 0);
  42164. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  42165. {
  42166. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  42167. if (rowComp != 0)
  42168. rowComp->resized();
  42169. }
  42170. }
  42171. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  42172. {
  42173. }
  42174. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  42175. {
  42176. }
  42177. void TableListBoxModel::backgroundClicked()
  42178. {
  42179. }
  42180. void TableListBoxModel::sortOrderChanged (int, const bool)
  42181. {
  42182. }
  42183. int TableListBoxModel::getColumnAutoSizeWidth (int)
  42184. {
  42185. return 0;
  42186. }
  42187. void TableListBoxModel::selectedRowsChanged (int)
  42188. {
  42189. }
  42190. void TableListBoxModel::deleteKeyPressed (int)
  42191. {
  42192. }
  42193. void TableListBoxModel::returnKeyPressed (int)
  42194. {
  42195. }
  42196. void TableListBoxModel::listWasScrolled()
  42197. {
  42198. }
  42199. const String TableListBoxModel::getCellTooltip (int /*rowNumber*/, int /*columnId*/)
  42200. {
  42201. return String::empty;
  42202. }
  42203. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  42204. {
  42205. return String::empty;
  42206. }
  42207. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  42208. {
  42209. (void) existingComponentToUpdate;
  42210. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  42211. return 0;
  42212. }
  42213. END_JUCE_NAMESPACE
  42214. /*** End of inlined file: juce_TableListBox.cpp ***/
  42215. /*** Start of inlined file: juce_TextEditor.cpp ***/
  42216. BEGIN_JUCE_NAMESPACE
  42217. // a word or space that can't be broken down any further
  42218. struct TextAtom
  42219. {
  42220. String atomText;
  42221. float width;
  42222. int numChars;
  42223. bool isWhitespace() const { return CharacterFunctions::isWhitespace (atomText[0]); }
  42224. bool isNewLine() const { return atomText[0] == '\r' || atomText[0] == '\n'; }
  42225. const String getText (const juce_wchar passwordCharacter) const
  42226. {
  42227. if (passwordCharacter == 0)
  42228. return atomText;
  42229. else
  42230. return String::repeatedString (String::charToString (passwordCharacter),
  42231. atomText.length());
  42232. }
  42233. const String getTrimmedText (const juce_wchar passwordCharacter) const
  42234. {
  42235. if (passwordCharacter == 0)
  42236. return atomText.substring (0, numChars);
  42237. else if (isNewLine())
  42238. return String::empty;
  42239. else
  42240. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  42241. }
  42242. };
  42243. // a run of text with a single font and colour
  42244. class TextEditor::UniformTextSection
  42245. {
  42246. public:
  42247. UniformTextSection (const String& text,
  42248. const Font& font_,
  42249. const Colour& colour_,
  42250. const juce_wchar passwordCharacter)
  42251. : font (font_),
  42252. colour (colour_)
  42253. {
  42254. initialiseAtoms (text, passwordCharacter);
  42255. }
  42256. UniformTextSection (const UniformTextSection& other)
  42257. : font (other.font),
  42258. colour (other.colour)
  42259. {
  42260. atoms.ensureStorageAllocated (other.atoms.size());
  42261. for (int i = 0; i < other.atoms.size(); ++i)
  42262. atoms.add (new TextAtom (*other.atoms.getUnchecked(i)));
  42263. }
  42264. ~UniformTextSection()
  42265. {
  42266. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  42267. }
  42268. void clear()
  42269. {
  42270. for (int i = atoms.size(); --i >= 0;)
  42271. delete getAtom(i);
  42272. atoms.clear();
  42273. }
  42274. int getNumAtoms() const
  42275. {
  42276. return atoms.size();
  42277. }
  42278. TextAtom* getAtom (const int index) const throw()
  42279. {
  42280. return atoms.getUnchecked (index);
  42281. }
  42282. void append (const UniformTextSection& other, const juce_wchar passwordCharacter)
  42283. {
  42284. if (other.atoms.size() > 0)
  42285. {
  42286. TextAtom* const lastAtom = atoms.getLast();
  42287. int i = 0;
  42288. if (lastAtom != 0)
  42289. {
  42290. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  42291. {
  42292. TextAtom* const first = other.getAtom(0);
  42293. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  42294. {
  42295. lastAtom->atomText += first->atomText;
  42296. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  42297. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  42298. delete first;
  42299. ++i;
  42300. }
  42301. }
  42302. }
  42303. atoms.ensureStorageAllocated (atoms.size() + other.atoms.size() - i);
  42304. while (i < other.atoms.size())
  42305. {
  42306. atoms.add (other.getAtom(i));
  42307. ++i;
  42308. }
  42309. }
  42310. }
  42311. UniformTextSection* split (const int indexToBreakAt,
  42312. const juce_wchar passwordCharacter)
  42313. {
  42314. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  42315. font, colour,
  42316. passwordCharacter);
  42317. int index = 0;
  42318. for (int i = 0; i < atoms.size(); ++i)
  42319. {
  42320. TextAtom* const atom = getAtom(i);
  42321. const int nextIndex = index + atom->numChars;
  42322. if (index == indexToBreakAt)
  42323. {
  42324. int j;
  42325. for (j = i; j < atoms.size(); ++j)
  42326. section2->atoms.add (getAtom (j));
  42327. for (j = atoms.size(); --j >= i;)
  42328. atoms.remove (j);
  42329. break;
  42330. }
  42331. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  42332. {
  42333. TextAtom* const secondAtom = new TextAtom();
  42334. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  42335. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  42336. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  42337. section2->atoms.add (secondAtom);
  42338. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  42339. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42340. atom->numChars = (uint16) (indexToBreakAt - index);
  42341. int j;
  42342. for (j = i + 1; j < atoms.size(); ++j)
  42343. section2->atoms.add (getAtom (j));
  42344. for (j = atoms.size(); --j > i;)
  42345. atoms.remove (j);
  42346. break;
  42347. }
  42348. index = nextIndex;
  42349. }
  42350. return section2;
  42351. }
  42352. void appendAllText (String::Concatenator& concatenator) const
  42353. {
  42354. for (int i = 0; i < atoms.size(); ++i)
  42355. concatenator.append (getAtom(i)->atomText);
  42356. }
  42357. void appendSubstring (String::Concatenator& concatenator,
  42358. const Range<int>& range) const
  42359. {
  42360. int index = 0;
  42361. for (int i = 0; i < atoms.size(); ++i)
  42362. {
  42363. const TextAtom* const atom = getAtom (i);
  42364. const int nextIndex = index + atom->numChars;
  42365. if (range.getStart() < nextIndex)
  42366. {
  42367. if (range.getEnd() <= index)
  42368. break;
  42369. const Range<int> r ((range - index).getIntersectionWith (Range<int> (0, (int) atom->numChars)));
  42370. if (! r.isEmpty())
  42371. concatenator.append (atom->atomText.substring (r.getStart(), r.getEnd()));
  42372. }
  42373. index = nextIndex;
  42374. }
  42375. }
  42376. int getTotalLength() const
  42377. {
  42378. int total = 0;
  42379. for (int i = atoms.size(); --i >= 0;)
  42380. total += getAtom(i)->numChars;
  42381. return total;
  42382. }
  42383. void setFont (const Font& newFont,
  42384. const juce_wchar passwordCharacter)
  42385. {
  42386. if (font != newFont)
  42387. {
  42388. font = newFont;
  42389. for (int i = atoms.size(); --i >= 0;)
  42390. {
  42391. TextAtom* const atom = atoms.getUnchecked(i);
  42392. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  42393. }
  42394. }
  42395. }
  42396. juce_UseDebuggingNewOperator
  42397. Font font;
  42398. Colour colour;
  42399. private:
  42400. Array <TextAtom*> atoms;
  42401. void initialiseAtoms (const String& textToParse,
  42402. const juce_wchar passwordCharacter)
  42403. {
  42404. int i = 0;
  42405. const int len = textToParse.length();
  42406. const juce_wchar* const text = textToParse;
  42407. while (i < len)
  42408. {
  42409. int start = i;
  42410. // create a whitespace atom unless it starts with non-ws
  42411. if (CharacterFunctions::isWhitespace (text[i])
  42412. && text[i] != '\r'
  42413. && text[i] != '\n')
  42414. {
  42415. while (i < len
  42416. && CharacterFunctions::isWhitespace (text[i])
  42417. && text[i] != '\r'
  42418. && text[i] != '\n')
  42419. {
  42420. ++i;
  42421. }
  42422. }
  42423. else
  42424. {
  42425. if (text[i] == '\r')
  42426. {
  42427. ++i;
  42428. if ((i < len) && (text[i] == '\n'))
  42429. {
  42430. ++start;
  42431. ++i;
  42432. }
  42433. }
  42434. else if (text[i] == '\n')
  42435. {
  42436. ++i;
  42437. }
  42438. else
  42439. {
  42440. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  42441. ++i;
  42442. }
  42443. }
  42444. TextAtom* const atom = new TextAtom();
  42445. atom->atomText = String (text + start, i - start);
  42446. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  42447. atom->numChars = (uint16) (i - start);
  42448. atoms.add (atom);
  42449. }
  42450. }
  42451. UniformTextSection& operator= (const UniformTextSection& other);
  42452. };
  42453. class TextEditor::Iterator
  42454. {
  42455. public:
  42456. Iterator (const Array <UniformTextSection*>& sections_,
  42457. const float wordWrapWidth_,
  42458. const juce_wchar passwordCharacter_)
  42459. : indexInText (0),
  42460. lineY (0),
  42461. lineHeight (0),
  42462. maxDescent (0),
  42463. atomX (0),
  42464. atomRight (0),
  42465. atom (0),
  42466. currentSection (0),
  42467. sections (sections_),
  42468. sectionIndex (0),
  42469. atomIndex (0),
  42470. wordWrapWidth (wordWrapWidth_),
  42471. passwordCharacter (passwordCharacter_)
  42472. {
  42473. jassert (wordWrapWidth_ > 0);
  42474. if (sections.size() > 0)
  42475. {
  42476. currentSection = sections.getUnchecked (sectionIndex);
  42477. if (currentSection != 0)
  42478. beginNewLine();
  42479. }
  42480. }
  42481. Iterator (const Iterator& other)
  42482. : indexInText (other.indexInText),
  42483. lineY (other.lineY),
  42484. lineHeight (other.lineHeight),
  42485. maxDescent (other.maxDescent),
  42486. atomX (other.atomX),
  42487. atomRight (other.atomRight),
  42488. atom (other.atom),
  42489. currentSection (other.currentSection),
  42490. sections (other.sections),
  42491. sectionIndex (other.sectionIndex),
  42492. atomIndex (other.atomIndex),
  42493. wordWrapWidth (other.wordWrapWidth),
  42494. passwordCharacter (other.passwordCharacter),
  42495. tempAtom (other.tempAtom)
  42496. {
  42497. }
  42498. ~Iterator()
  42499. {
  42500. }
  42501. bool next()
  42502. {
  42503. if (atom == &tempAtom)
  42504. {
  42505. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  42506. if (numRemaining > 0)
  42507. {
  42508. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  42509. atomX = 0;
  42510. if (tempAtom.numChars > 0)
  42511. lineY += lineHeight;
  42512. indexInText += tempAtom.numChars;
  42513. GlyphArrangement g;
  42514. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  42515. int split;
  42516. for (split = 0; split < g.getNumGlyphs(); ++split)
  42517. if (shouldWrap (g.getGlyph (split).getRight()))
  42518. break;
  42519. if (split > 0 && split <= numRemaining)
  42520. {
  42521. tempAtom.numChars = (uint16) split;
  42522. tempAtom.width = g.getGlyph (split - 1).getRight();
  42523. atomRight = atomX + tempAtom.width;
  42524. return true;
  42525. }
  42526. }
  42527. }
  42528. bool forceNewLine = false;
  42529. if (sectionIndex >= sections.size())
  42530. {
  42531. moveToEndOfLastAtom();
  42532. return false;
  42533. }
  42534. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  42535. {
  42536. if (atomIndex >= currentSection->getNumAtoms())
  42537. {
  42538. if (++sectionIndex >= sections.size())
  42539. {
  42540. moveToEndOfLastAtom();
  42541. return false;
  42542. }
  42543. atomIndex = 0;
  42544. currentSection = sections.getUnchecked (sectionIndex);
  42545. }
  42546. else
  42547. {
  42548. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  42549. if (! lastAtom->isWhitespace())
  42550. {
  42551. // handle the case where the last atom in a section is actually part of the same
  42552. // word as the first atom of the next section...
  42553. float right = atomRight + lastAtom->width;
  42554. float lineHeight2 = lineHeight;
  42555. float maxDescent2 = maxDescent;
  42556. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  42557. {
  42558. const UniformTextSection* const s = sections.getUnchecked (section);
  42559. if (s->getNumAtoms() == 0)
  42560. break;
  42561. const TextAtom* const nextAtom = s->getAtom (0);
  42562. if (nextAtom->isWhitespace())
  42563. break;
  42564. right += nextAtom->width;
  42565. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  42566. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  42567. if (shouldWrap (right))
  42568. {
  42569. lineHeight = lineHeight2;
  42570. maxDescent = maxDescent2;
  42571. forceNewLine = true;
  42572. break;
  42573. }
  42574. if (s->getNumAtoms() > 1)
  42575. break;
  42576. }
  42577. }
  42578. }
  42579. }
  42580. if (atom != 0)
  42581. {
  42582. atomX = atomRight;
  42583. indexInText += atom->numChars;
  42584. if (atom->isNewLine())
  42585. beginNewLine();
  42586. }
  42587. atom = currentSection->getAtom (atomIndex);
  42588. atomRight = atomX + atom->width;
  42589. ++atomIndex;
  42590. if (shouldWrap (atomRight) || forceNewLine)
  42591. {
  42592. if (atom->isWhitespace())
  42593. {
  42594. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  42595. atomRight = jmin (atomRight, wordWrapWidth);
  42596. }
  42597. else
  42598. {
  42599. atomRight = atom->width;
  42600. if (shouldWrap (atomRight)) // atom too big to fit on a line, so break it up..
  42601. {
  42602. tempAtom = *atom;
  42603. tempAtom.width = 0;
  42604. tempAtom.numChars = 0;
  42605. atom = &tempAtom;
  42606. if (atomX > 0)
  42607. beginNewLine();
  42608. return next();
  42609. }
  42610. beginNewLine();
  42611. return true;
  42612. }
  42613. }
  42614. return true;
  42615. }
  42616. void beginNewLine()
  42617. {
  42618. atomX = 0;
  42619. lineY += lineHeight;
  42620. int tempSectionIndex = sectionIndex;
  42621. int tempAtomIndex = atomIndex;
  42622. const UniformTextSection* section = sections.getUnchecked (tempSectionIndex);
  42623. lineHeight = section->font.getHeight();
  42624. maxDescent = section->font.getDescent();
  42625. float x = (atom != 0) ? atom->width : 0;
  42626. while (! shouldWrap (x))
  42627. {
  42628. if (tempSectionIndex >= sections.size())
  42629. break;
  42630. bool checkSize = false;
  42631. if (tempAtomIndex >= section->getNumAtoms())
  42632. {
  42633. if (++tempSectionIndex >= sections.size())
  42634. break;
  42635. tempAtomIndex = 0;
  42636. section = sections.getUnchecked (tempSectionIndex);
  42637. checkSize = true;
  42638. }
  42639. const TextAtom* const nextAtom = section->getAtom (tempAtomIndex);
  42640. if (nextAtom == 0)
  42641. break;
  42642. x += nextAtom->width;
  42643. if (shouldWrap (x) || nextAtom->isNewLine())
  42644. break;
  42645. if (checkSize)
  42646. {
  42647. lineHeight = jmax (lineHeight, section->font.getHeight());
  42648. maxDescent = jmax (maxDescent, section->font.getDescent());
  42649. }
  42650. ++tempAtomIndex;
  42651. }
  42652. }
  42653. void draw (Graphics& g, const UniformTextSection*& lastSection) const
  42654. {
  42655. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42656. {
  42657. if (lastSection != currentSection)
  42658. {
  42659. lastSection = currentSection;
  42660. g.setColour (currentSection->colour);
  42661. g.setFont (currentSection->font);
  42662. }
  42663. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  42664. GlyphArrangement ga;
  42665. ga.addLineOfText (currentSection->font,
  42666. atom->getTrimmedText (passwordCharacter),
  42667. atomX,
  42668. (float) roundToInt (lineY + lineHeight - maxDescent));
  42669. ga.draw (g);
  42670. }
  42671. }
  42672. void drawSelection (Graphics& g,
  42673. const Range<int>& selection) const
  42674. {
  42675. const int startX = roundToInt (indexToX (selection.getStart()));
  42676. const int endX = roundToInt (indexToX (selection.getEnd()));
  42677. const int y = roundToInt (lineY);
  42678. const int nextY = roundToInt (lineY + lineHeight);
  42679. g.fillRect (startX, y, endX - startX, nextY - y);
  42680. }
  42681. void drawSelectedText (Graphics& g,
  42682. const Range<int>& selection,
  42683. const Colour& selectedTextColour) const
  42684. {
  42685. if (passwordCharacter != 0 || ! atom->isWhitespace())
  42686. {
  42687. GlyphArrangement ga;
  42688. ga.addLineOfText (currentSection->font,
  42689. atom->getTrimmedText (passwordCharacter),
  42690. atomX,
  42691. (float) roundToInt (lineY + lineHeight - maxDescent));
  42692. if (selection.getEnd() < indexInText + atom->numChars)
  42693. {
  42694. GlyphArrangement ga2 (ga);
  42695. ga2.removeRangeOfGlyphs (0, selection.getEnd() - indexInText);
  42696. ga.removeRangeOfGlyphs (selection.getEnd() - indexInText, -1);
  42697. g.setColour (currentSection->colour);
  42698. ga2.draw (g);
  42699. }
  42700. if (selection.getStart() > indexInText)
  42701. {
  42702. GlyphArrangement ga2 (ga);
  42703. ga2.removeRangeOfGlyphs (selection.getStart() - indexInText, -1);
  42704. ga.removeRangeOfGlyphs (0, selection.getStart() - indexInText);
  42705. g.setColour (currentSection->colour);
  42706. ga2.draw (g);
  42707. }
  42708. g.setColour (selectedTextColour);
  42709. ga.draw (g);
  42710. }
  42711. }
  42712. float indexToX (const int indexToFind) const
  42713. {
  42714. if (indexToFind <= indexInText)
  42715. return atomX;
  42716. if (indexToFind >= indexInText + atom->numChars)
  42717. return atomRight;
  42718. GlyphArrangement g;
  42719. g.addLineOfText (currentSection->font,
  42720. atom->getText (passwordCharacter),
  42721. atomX, 0.0f);
  42722. if (indexToFind - indexInText >= g.getNumGlyphs())
  42723. return atomRight;
  42724. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  42725. }
  42726. int xToIndex (const float xToFind) const
  42727. {
  42728. if (xToFind <= atomX || atom->isNewLine())
  42729. return indexInText;
  42730. if (xToFind >= atomRight)
  42731. return indexInText + atom->numChars;
  42732. GlyphArrangement g;
  42733. g.addLineOfText (currentSection->font,
  42734. atom->getText (passwordCharacter),
  42735. atomX, 0.0f);
  42736. int j;
  42737. for (j = 0; j < g.getNumGlyphs(); ++j)
  42738. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  42739. break;
  42740. return indexInText + j;
  42741. }
  42742. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_)
  42743. {
  42744. while (next())
  42745. {
  42746. if (indexInText + atom->numChars > index)
  42747. {
  42748. cx = indexToX (index);
  42749. cy = lineY;
  42750. lineHeight_ = lineHeight;
  42751. return true;
  42752. }
  42753. }
  42754. cx = atomX;
  42755. cy = lineY;
  42756. lineHeight_ = lineHeight;
  42757. return false;
  42758. }
  42759. juce_UseDebuggingNewOperator
  42760. int indexInText;
  42761. float lineY, lineHeight, maxDescent;
  42762. float atomX, atomRight;
  42763. const TextAtom* atom;
  42764. const UniformTextSection* currentSection;
  42765. private:
  42766. const Array <UniformTextSection*>& sections;
  42767. int sectionIndex, atomIndex;
  42768. const float wordWrapWidth;
  42769. const juce_wchar passwordCharacter;
  42770. TextAtom tempAtom;
  42771. Iterator& operator= (const Iterator&);
  42772. void moveToEndOfLastAtom()
  42773. {
  42774. if (atom != 0)
  42775. {
  42776. atomX = atomRight;
  42777. if (atom->isNewLine())
  42778. {
  42779. atomX = 0.0f;
  42780. lineY += lineHeight;
  42781. }
  42782. }
  42783. }
  42784. bool shouldWrap (const float x) const
  42785. {
  42786. return (x - 0.0001f) >= wordWrapWidth;
  42787. }
  42788. };
  42789. class TextEditor::InsertAction : public UndoableAction
  42790. {
  42791. TextEditor& owner;
  42792. const String text;
  42793. const int insertIndex, oldCaretPos, newCaretPos;
  42794. const Font font;
  42795. const Colour colour;
  42796. InsertAction (const InsertAction&);
  42797. InsertAction& operator= (const InsertAction&);
  42798. public:
  42799. InsertAction (TextEditor& owner_,
  42800. const String& text_,
  42801. const int insertIndex_,
  42802. const Font& font_,
  42803. const Colour& colour_,
  42804. const int oldCaretPos_,
  42805. const int newCaretPos_)
  42806. : owner (owner_),
  42807. text (text_),
  42808. insertIndex (insertIndex_),
  42809. oldCaretPos (oldCaretPos_),
  42810. newCaretPos (newCaretPos_),
  42811. font (font_),
  42812. colour (colour_)
  42813. {
  42814. }
  42815. ~InsertAction()
  42816. {
  42817. }
  42818. bool perform()
  42819. {
  42820. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  42821. return true;
  42822. }
  42823. bool undo()
  42824. {
  42825. owner.remove (Range<int> (insertIndex, insertIndex + text.length()), 0, oldCaretPos);
  42826. return true;
  42827. }
  42828. int getSizeInUnits()
  42829. {
  42830. return text.length() + 16;
  42831. }
  42832. };
  42833. class TextEditor::RemoveAction : public UndoableAction
  42834. {
  42835. TextEditor& owner;
  42836. const Range<int> range;
  42837. const int oldCaretPos, newCaretPos;
  42838. Array <UniformTextSection*> removedSections;
  42839. RemoveAction (const RemoveAction&);
  42840. RemoveAction& operator= (const RemoveAction&);
  42841. public:
  42842. RemoveAction (TextEditor& owner_,
  42843. const Range<int> range_,
  42844. const int oldCaretPos_,
  42845. const int newCaretPos_,
  42846. const Array <UniformTextSection*>& removedSections_)
  42847. : owner (owner_),
  42848. range (range_),
  42849. oldCaretPos (oldCaretPos_),
  42850. newCaretPos (newCaretPos_),
  42851. removedSections (removedSections_)
  42852. {
  42853. }
  42854. ~RemoveAction()
  42855. {
  42856. for (int i = removedSections.size(); --i >= 0;)
  42857. {
  42858. UniformTextSection* const section = removedSections.getUnchecked (i);
  42859. section->clear();
  42860. delete section;
  42861. }
  42862. }
  42863. bool perform()
  42864. {
  42865. owner.remove (range, 0, newCaretPos);
  42866. return true;
  42867. }
  42868. bool undo()
  42869. {
  42870. owner.reinsert (range.getStart(), removedSections);
  42871. owner.moveCursorTo (oldCaretPos, false);
  42872. return true;
  42873. }
  42874. int getSizeInUnits()
  42875. {
  42876. int n = 0;
  42877. for (int i = removedSections.size(); --i >= 0;)
  42878. n += removedSections.getUnchecked (i)->getTotalLength();
  42879. return n + 16;
  42880. }
  42881. };
  42882. class TextEditor::TextHolderComponent : public Component,
  42883. public Timer,
  42884. public Value::Listener
  42885. {
  42886. public:
  42887. TextHolderComponent (TextEditor& owner_)
  42888. : owner (owner_)
  42889. {
  42890. setWantsKeyboardFocus (false);
  42891. setInterceptsMouseClicks (false, true);
  42892. owner.getTextValue().addListener (this);
  42893. }
  42894. ~TextHolderComponent()
  42895. {
  42896. owner.getTextValue().removeListener (this);
  42897. }
  42898. void paint (Graphics& g)
  42899. {
  42900. owner.drawContent (g);
  42901. }
  42902. void timerCallback()
  42903. {
  42904. owner.timerCallbackInt();
  42905. }
  42906. const MouseCursor getMouseCursor()
  42907. {
  42908. return owner.getMouseCursor();
  42909. }
  42910. void valueChanged (Value&)
  42911. {
  42912. owner.textWasChangedByValue();
  42913. }
  42914. private:
  42915. TextEditor& owner;
  42916. TextHolderComponent (const TextHolderComponent&);
  42917. TextHolderComponent& operator= (const TextHolderComponent&);
  42918. };
  42919. class TextEditorViewport : public Viewport
  42920. {
  42921. public:
  42922. TextEditorViewport (TextEditor* const owner_)
  42923. : owner (owner_), lastWordWrapWidth (0), rentrant (false)
  42924. {
  42925. }
  42926. ~TextEditorViewport()
  42927. {
  42928. }
  42929. void visibleAreaChanged (int, int, int, int)
  42930. {
  42931. if (! rentrant) // it's rare, but possible to get into a feedback loop as the viewport's scrollbars
  42932. // appear and disappear, causing the wrap width to change.
  42933. {
  42934. const float wordWrapWidth = owner->getWordWrapWidth();
  42935. if (wordWrapWidth != lastWordWrapWidth)
  42936. {
  42937. lastWordWrapWidth = wordWrapWidth;
  42938. rentrant = true;
  42939. owner->updateTextHolderSize();
  42940. rentrant = false;
  42941. }
  42942. }
  42943. }
  42944. private:
  42945. TextEditor* const owner;
  42946. float lastWordWrapWidth;
  42947. bool rentrant;
  42948. TextEditorViewport (const TextEditorViewport&);
  42949. TextEditorViewport& operator= (const TextEditorViewport&);
  42950. };
  42951. namespace TextEditorDefs
  42952. {
  42953. const int flashSpeedIntervalMs = 380;
  42954. const int textChangeMessageId = 0x10003001;
  42955. const int returnKeyMessageId = 0x10003002;
  42956. const int escapeKeyMessageId = 0x10003003;
  42957. const int focusLossMessageId = 0x10003004;
  42958. const int maxActionsPerTransaction = 100;
  42959. static int getCharacterCategory (const juce_wchar character)
  42960. {
  42961. return CharacterFunctions::isLetterOrDigit (character)
  42962. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  42963. }
  42964. }
  42965. TextEditor::TextEditor (const String& name,
  42966. const juce_wchar passwordCharacter_)
  42967. : Component (name),
  42968. borderSize (1, 1, 1, 3),
  42969. readOnly (false),
  42970. multiline (false),
  42971. wordWrap (false),
  42972. returnKeyStartsNewLine (false),
  42973. caretVisible (true),
  42974. popupMenuEnabled (true),
  42975. selectAllTextWhenFocused (false),
  42976. scrollbarVisible (true),
  42977. wasFocused (false),
  42978. caretFlashState (true),
  42979. keepCursorOnScreen (true),
  42980. tabKeyUsed (false),
  42981. menuActive (false),
  42982. valueTextNeedsUpdating (false),
  42983. cursorX (0),
  42984. cursorY (0),
  42985. cursorHeight (0),
  42986. maxTextLength (0),
  42987. leftIndent (4),
  42988. topIndent (4),
  42989. lastTransactionTime (0),
  42990. currentFont (14.0f),
  42991. totalNumChars (0),
  42992. caretPosition (0),
  42993. passwordCharacter (passwordCharacter_),
  42994. dragType (notDragging)
  42995. {
  42996. setOpaque (true);
  42997. addAndMakeVisible (viewport = new TextEditorViewport (this));
  42998. viewport->setViewedComponent (textHolder = new TextHolderComponent (*this));
  42999. viewport->setWantsKeyboardFocus (false);
  43000. viewport->setScrollBarsShown (false, false);
  43001. setMouseCursor (MouseCursor::IBeamCursor);
  43002. setWantsKeyboardFocus (true);
  43003. }
  43004. TextEditor::~TextEditor()
  43005. {
  43006. textValue.referTo (Value());
  43007. clearInternal (0);
  43008. viewport = 0;
  43009. textHolder = 0;
  43010. }
  43011. void TextEditor::newTransaction()
  43012. {
  43013. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43014. undoManager.beginNewTransaction();
  43015. }
  43016. void TextEditor::doUndoRedo (const bool isRedo)
  43017. {
  43018. if (! isReadOnly())
  43019. {
  43020. if (isRedo ? undoManager.redo()
  43021. : undoManager.undo())
  43022. {
  43023. scrollToMakeSureCursorIsVisible();
  43024. repaint();
  43025. textChanged();
  43026. }
  43027. }
  43028. }
  43029. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  43030. const bool shouldWordWrap)
  43031. {
  43032. if (multiline != shouldBeMultiLine
  43033. || wordWrap != (shouldWordWrap && shouldBeMultiLine))
  43034. {
  43035. multiline = shouldBeMultiLine;
  43036. wordWrap = shouldWordWrap && shouldBeMultiLine;
  43037. viewport->setScrollBarsShown (scrollbarVisible && multiline,
  43038. scrollbarVisible && multiline);
  43039. viewport->setViewPosition (0, 0);
  43040. resized();
  43041. scrollToMakeSureCursorIsVisible();
  43042. }
  43043. }
  43044. bool TextEditor::isMultiLine() const
  43045. {
  43046. return multiline;
  43047. }
  43048. void TextEditor::setScrollbarsShown (bool shown)
  43049. {
  43050. if (scrollbarVisible != shown)
  43051. {
  43052. scrollbarVisible = shown;
  43053. shown = shown && isMultiLine();
  43054. viewport->setScrollBarsShown (shown, shown);
  43055. }
  43056. }
  43057. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  43058. {
  43059. if (readOnly != shouldBeReadOnly)
  43060. {
  43061. readOnly = shouldBeReadOnly;
  43062. enablementChanged();
  43063. }
  43064. }
  43065. bool TextEditor::isReadOnly() const
  43066. {
  43067. return readOnly || ! isEnabled();
  43068. }
  43069. bool TextEditor::isTextInputActive() const
  43070. {
  43071. return ! isReadOnly();
  43072. }
  43073. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  43074. {
  43075. returnKeyStartsNewLine = shouldStartNewLine;
  43076. }
  43077. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed)
  43078. {
  43079. tabKeyUsed = shouldTabKeyBeUsed;
  43080. }
  43081. void TextEditor::setPopupMenuEnabled (const bool b)
  43082. {
  43083. popupMenuEnabled = b;
  43084. }
  43085. void TextEditor::setSelectAllWhenFocused (const bool b)
  43086. {
  43087. selectAllTextWhenFocused = b;
  43088. }
  43089. const Font TextEditor::getFont() const
  43090. {
  43091. return currentFont;
  43092. }
  43093. void TextEditor::setFont (const Font& newFont)
  43094. {
  43095. currentFont = newFont;
  43096. scrollToMakeSureCursorIsVisible();
  43097. }
  43098. void TextEditor::applyFontToAllText (const Font& newFont)
  43099. {
  43100. currentFont = newFont;
  43101. const Colour overallColour (findColour (textColourId));
  43102. for (int i = sections.size(); --i >= 0;)
  43103. {
  43104. UniformTextSection* const uts = sections.getUnchecked (i);
  43105. uts->setFont (newFont, passwordCharacter);
  43106. uts->colour = overallColour;
  43107. }
  43108. coalesceSimilarSections();
  43109. updateTextHolderSize();
  43110. scrollToMakeSureCursorIsVisible();
  43111. repaint();
  43112. }
  43113. void TextEditor::colourChanged()
  43114. {
  43115. setOpaque (findColour (backgroundColourId).isOpaque());
  43116. repaint();
  43117. }
  43118. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible)
  43119. {
  43120. caretVisible = shouldCaretBeVisible;
  43121. if (shouldCaretBeVisible)
  43122. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43123. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  43124. : MouseCursor::NormalCursor);
  43125. }
  43126. void TextEditor::setInputRestrictions (const int maxLen,
  43127. const String& chars)
  43128. {
  43129. maxTextLength = jmax (0, maxLen);
  43130. allowedCharacters = chars;
  43131. }
  43132. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse)
  43133. {
  43134. textToShowWhenEmpty = text;
  43135. colourForTextWhenEmpty = colourToUse;
  43136. }
  43137. void TextEditor::setPasswordCharacter (const juce_wchar newPasswordCharacter)
  43138. {
  43139. if (passwordCharacter != newPasswordCharacter)
  43140. {
  43141. passwordCharacter = newPasswordCharacter;
  43142. resized();
  43143. repaint();
  43144. }
  43145. }
  43146. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  43147. {
  43148. viewport->setScrollBarThickness (newThicknessPixels);
  43149. }
  43150. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  43151. {
  43152. viewport->setScrollBarButtonVisibility (buttonsVisible);
  43153. }
  43154. void TextEditor::clear()
  43155. {
  43156. clearInternal (0);
  43157. updateTextHolderSize();
  43158. undoManager.clearUndoHistory();
  43159. }
  43160. void TextEditor::setText (const String& newText,
  43161. const bool sendTextChangeMessage)
  43162. {
  43163. const int newLength = newText.length();
  43164. if (newLength != getTotalNumChars() || getText() != newText)
  43165. {
  43166. const int oldCursorPos = caretPosition;
  43167. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  43168. clearInternal (0);
  43169. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  43170. // if you're adding text with line-feeds to a single-line text editor, it
  43171. // ain't gonna look right!
  43172. jassert (multiline || ! newText.containsAnyOf ("\r\n"));
  43173. if (cursorWasAtEnd && ! isMultiLine())
  43174. moveCursorTo (getTotalNumChars(), false);
  43175. else
  43176. moveCursorTo (oldCursorPos, false);
  43177. if (sendTextChangeMessage)
  43178. textChanged();
  43179. updateTextHolderSize();
  43180. scrollToMakeSureCursorIsVisible();
  43181. undoManager.clearUndoHistory();
  43182. repaint();
  43183. }
  43184. }
  43185. Value& TextEditor::getTextValue()
  43186. {
  43187. if (valueTextNeedsUpdating)
  43188. {
  43189. valueTextNeedsUpdating = false;
  43190. textValue = getText();
  43191. }
  43192. return textValue;
  43193. }
  43194. void TextEditor::textWasChangedByValue()
  43195. {
  43196. if (textValue.getValueSource().getReferenceCount() > 1)
  43197. setText (textValue.getValue());
  43198. }
  43199. void TextEditor::textChanged()
  43200. {
  43201. updateTextHolderSize();
  43202. postCommandMessage (TextEditorDefs::textChangeMessageId);
  43203. if (textValue.getValueSource().getReferenceCount() > 1)
  43204. {
  43205. valueTextNeedsUpdating = false;
  43206. textValue = getText();
  43207. }
  43208. }
  43209. void TextEditor::returnPressed()
  43210. {
  43211. postCommandMessage (TextEditorDefs::returnKeyMessageId);
  43212. }
  43213. void TextEditor::escapePressed()
  43214. {
  43215. postCommandMessage (TextEditorDefs::escapeKeyMessageId);
  43216. }
  43217. void TextEditor::addListener (Listener* const newListener)
  43218. {
  43219. listeners.add (newListener);
  43220. }
  43221. void TextEditor::removeListener (Listener* const listenerToRemove)
  43222. {
  43223. listeners.remove (listenerToRemove);
  43224. }
  43225. void TextEditor::timerCallbackInt()
  43226. {
  43227. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  43228. if (caretFlashState != newState)
  43229. {
  43230. caretFlashState = newState;
  43231. if (caretFlashState)
  43232. wasFocused = true;
  43233. if (caretVisible
  43234. && hasKeyboardFocus (false)
  43235. && ! isReadOnly())
  43236. {
  43237. repaintCaret();
  43238. }
  43239. }
  43240. const unsigned int now = Time::getApproximateMillisecondCounter();
  43241. if (now > lastTransactionTime + 200)
  43242. newTransaction();
  43243. }
  43244. void TextEditor::repaintCaret()
  43245. {
  43246. if (! findColour (caretColourId).isTransparent())
  43247. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundToInt (cursorX) - 1,
  43248. borderSize.getTop() + textHolder->getY() + topIndent + roundToInt (cursorY) - 1,
  43249. 4,
  43250. roundToInt (cursorHeight) + 2);
  43251. }
  43252. void TextEditor::repaintText (const Range<int>& range)
  43253. {
  43254. if (! range.isEmpty())
  43255. {
  43256. float x = 0, y = 0, lh = currentFont.getHeight();
  43257. const float wordWrapWidth = getWordWrapWidth();
  43258. if (wordWrapWidth > 0)
  43259. {
  43260. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43261. i.getCharPosition (range.getStart(), x, y, lh);
  43262. const int y1 = (int) y;
  43263. int y2;
  43264. if (range.getEnd() >= getTotalNumChars())
  43265. {
  43266. y2 = textHolder->getHeight();
  43267. }
  43268. else
  43269. {
  43270. i.getCharPosition (range.getEnd(), x, y, lh);
  43271. y2 = (int) (y + lh * 2.0f);
  43272. }
  43273. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  43274. }
  43275. }
  43276. }
  43277. void TextEditor::moveCaret (int newCaretPos)
  43278. {
  43279. if (newCaretPos < 0)
  43280. newCaretPos = 0;
  43281. else if (newCaretPos > getTotalNumChars())
  43282. newCaretPos = getTotalNumChars();
  43283. if (newCaretPos != getCaretPosition())
  43284. {
  43285. repaintCaret();
  43286. caretFlashState = true;
  43287. caretPosition = newCaretPos;
  43288. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43289. scrollToMakeSureCursorIsVisible();
  43290. repaintCaret();
  43291. }
  43292. }
  43293. void TextEditor::setCaretPosition (const int newIndex)
  43294. {
  43295. moveCursorTo (newIndex, false);
  43296. }
  43297. int TextEditor::getCaretPosition() const
  43298. {
  43299. return caretPosition;
  43300. }
  43301. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  43302. const int desiredCaretY)
  43303. {
  43304. updateCaretPosition();
  43305. int vx = roundToInt (cursorX) - desiredCaretX;
  43306. int vy = roundToInt (cursorY) - desiredCaretY;
  43307. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  43308. {
  43309. vx += desiredCaretX - proportionOfWidth (0.2f);
  43310. }
  43311. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43312. {
  43313. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43314. }
  43315. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  43316. if (! isMultiLine())
  43317. {
  43318. vy = viewport->getViewPositionY();
  43319. }
  43320. else
  43321. {
  43322. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  43323. const int curH = roundToInt (cursorHeight);
  43324. if (desiredCaretY < 0)
  43325. {
  43326. vy = jmax (0, desiredCaretY + vy);
  43327. }
  43328. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43329. {
  43330. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43331. }
  43332. }
  43333. viewport->setViewPosition (vx, vy);
  43334. }
  43335. const Rectangle<int> TextEditor::getCaretRectangle()
  43336. {
  43337. updateCaretPosition();
  43338. return Rectangle<int> (roundToInt (cursorX) - viewport->getX(),
  43339. roundToInt (cursorY) - viewport->getY(),
  43340. 1, roundToInt (cursorHeight));
  43341. }
  43342. float TextEditor::getWordWrapWidth() const
  43343. {
  43344. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  43345. : 1.0e10f;
  43346. }
  43347. void TextEditor::updateTextHolderSize()
  43348. {
  43349. const float wordWrapWidth = getWordWrapWidth();
  43350. if (wordWrapWidth > 0)
  43351. {
  43352. float maxWidth = 0.0f;
  43353. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43354. while (i.next())
  43355. maxWidth = jmax (maxWidth, i.atomRight);
  43356. const int w = leftIndent + roundToInt (maxWidth);
  43357. const int h = topIndent + roundToInt (jmax (i.lineY + i.lineHeight,
  43358. currentFont.getHeight()));
  43359. textHolder->setSize (w + 1, h + 1);
  43360. }
  43361. }
  43362. int TextEditor::getTextWidth() const
  43363. {
  43364. return textHolder->getWidth();
  43365. }
  43366. int TextEditor::getTextHeight() const
  43367. {
  43368. return textHolder->getHeight();
  43369. }
  43370. void TextEditor::setIndents (const int newLeftIndent,
  43371. const int newTopIndent)
  43372. {
  43373. leftIndent = newLeftIndent;
  43374. topIndent = newTopIndent;
  43375. }
  43376. void TextEditor::setBorder (const BorderSize& border)
  43377. {
  43378. borderSize = border;
  43379. resized();
  43380. }
  43381. const BorderSize TextEditor::getBorder() const
  43382. {
  43383. return borderSize;
  43384. }
  43385. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor)
  43386. {
  43387. keepCursorOnScreen = shouldScrollToShowCursor;
  43388. }
  43389. void TextEditor::updateCaretPosition()
  43390. {
  43391. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  43392. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  43393. }
  43394. void TextEditor::scrollToMakeSureCursorIsVisible()
  43395. {
  43396. updateCaretPosition();
  43397. if (keepCursorOnScreen)
  43398. {
  43399. int x = viewport->getViewPositionX();
  43400. int y = viewport->getViewPositionY();
  43401. const int relativeCursorX = roundToInt (cursorX) - x;
  43402. const int relativeCursorY = roundToInt (cursorY) - y;
  43403. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  43404. {
  43405. x += relativeCursorX - proportionOfWidth (0.2f);
  43406. }
  43407. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  43408. {
  43409. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  43410. }
  43411. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  43412. if (! isMultiLine())
  43413. {
  43414. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  43415. }
  43416. else
  43417. {
  43418. const int curH = roundToInt (cursorHeight);
  43419. if (relativeCursorY < 0)
  43420. {
  43421. y = jmax (0, relativeCursorY + y);
  43422. }
  43423. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  43424. {
  43425. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  43426. }
  43427. }
  43428. viewport->setViewPosition (x, y);
  43429. }
  43430. }
  43431. void TextEditor::moveCursorTo (const int newPosition,
  43432. const bool isSelecting)
  43433. {
  43434. if (isSelecting)
  43435. {
  43436. moveCaret (newPosition);
  43437. const Range<int> oldSelection (selection);
  43438. if (dragType == notDragging)
  43439. {
  43440. if (abs (getCaretPosition() - selection.getStart()) < abs (getCaretPosition() - selection.getEnd()))
  43441. dragType = draggingSelectionStart;
  43442. else
  43443. dragType = draggingSelectionEnd;
  43444. }
  43445. if (dragType == draggingSelectionStart)
  43446. {
  43447. if (getCaretPosition() >= selection.getEnd())
  43448. dragType = draggingSelectionEnd;
  43449. selection = Range<int>::between (getCaretPosition(), selection.getEnd());
  43450. }
  43451. else
  43452. {
  43453. if (getCaretPosition() < selection.getStart())
  43454. dragType = draggingSelectionStart;
  43455. selection = Range<int>::between (getCaretPosition(), selection.getStart());
  43456. }
  43457. repaintText (selection.getUnionWith (oldSelection));
  43458. }
  43459. else
  43460. {
  43461. dragType = notDragging;
  43462. repaintText (selection);
  43463. moveCaret (newPosition);
  43464. selection = Range<int>::emptyRange (getCaretPosition());
  43465. }
  43466. }
  43467. int TextEditor::getTextIndexAt (const int x,
  43468. const int y)
  43469. {
  43470. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  43471. (float) (y + viewport->getViewPositionY() - topIndent));
  43472. }
  43473. void TextEditor::insertTextAtCaret (const String& newText_)
  43474. {
  43475. String newText (newText_);
  43476. if (allowedCharacters.isNotEmpty())
  43477. newText = newText.retainCharacters (allowedCharacters);
  43478. if ((! returnKeyStartsNewLine) && newText == "\n")
  43479. {
  43480. returnPressed();
  43481. return;
  43482. }
  43483. if (! isMultiLine())
  43484. newText = newText.replaceCharacters ("\r\n", " ");
  43485. else
  43486. newText = newText.replace ("\r\n", "\n");
  43487. const int newCaretPos = selection.getStart() + newText.length();
  43488. const int insertIndex = selection.getStart();
  43489. remove (selection, getUndoManager(),
  43490. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  43491. if (maxTextLength > 0)
  43492. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  43493. if (newText.isNotEmpty())
  43494. insert (newText,
  43495. insertIndex,
  43496. currentFont,
  43497. findColour (textColourId),
  43498. getUndoManager(),
  43499. newCaretPos);
  43500. textChanged();
  43501. }
  43502. void TextEditor::setHighlightedRegion (const Range<int>& newSelection)
  43503. {
  43504. moveCursorTo (newSelection.getStart(), false);
  43505. moveCursorTo (newSelection.getEnd(), true);
  43506. }
  43507. void TextEditor::copy()
  43508. {
  43509. if (passwordCharacter == 0)
  43510. {
  43511. const String selectedText (getHighlightedText());
  43512. if (selectedText.isNotEmpty())
  43513. SystemClipboard::copyTextToClipboard (selectedText);
  43514. }
  43515. }
  43516. void TextEditor::paste()
  43517. {
  43518. if (! isReadOnly())
  43519. {
  43520. const String clip (SystemClipboard::getTextFromClipboard());
  43521. if (clip.isNotEmpty())
  43522. insertTextAtCaret (clip);
  43523. }
  43524. }
  43525. void TextEditor::cut()
  43526. {
  43527. if (! isReadOnly())
  43528. {
  43529. moveCaret (selection.getEnd());
  43530. insertTextAtCaret (String::empty);
  43531. }
  43532. }
  43533. void TextEditor::drawContent (Graphics& g)
  43534. {
  43535. const float wordWrapWidth = getWordWrapWidth();
  43536. if (wordWrapWidth > 0)
  43537. {
  43538. g.setOrigin (leftIndent, topIndent);
  43539. const Rectangle<int> clip (g.getClipBounds());
  43540. Colour selectedTextColour;
  43541. Iterator i (sections, wordWrapWidth, passwordCharacter);
  43542. while (i.lineY + 200.0 < clip.getY() && i.next())
  43543. {}
  43544. if (! selection.isEmpty())
  43545. {
  43546. g.setColour (findColour (highlightColourId)
  43547. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  43548. selectedTextColour = findColour (highlightedTextColourId);
  43549. Iterator i2 (i);
  43550. while (i2.next() && i2.lineY < clip.getBottom())
  43551. {
  43552. if (i2.lineY + i2.lineHeight >= clip.getY()
  43553. && selection.intersects (Range<int> (i2.indexInText, i2.indexInText + i2.atom->numChars)))
  43554. {
  43555. i2.drawSelection (g, selection);
  43556. }
  43557. }
  43558. }
  43559. const UniformTextSection* lastSection = 0;
  43560. while (i.next() && i.lineY < clip.getBottom())
  43561. {
  43562. if (i.lineY + i.lineHeight >= clip.getY())
  43563. {
  43564. if (selection.intersects (Range<int> (i.indexInText, i.indexInText + i.atom->numChars)))
  43565. {
  43566. i.drawSelectedText (g, selection, selectedTextColour);
  43567. lastSection = 0;
  43568. }
  43569. else
  43570. {
  43571. i.draw (g, lastSection);
  43572. }
  43573. }
  43574. }
  43575. }
  43576. }
  43577. void TextEditor::paint (Graphics& g)
  43578. {
  43579. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  43580. }
  43581. void TextEditor::paintOverChildren (Graphics& g)
  43582. {
  43583. if (caretFlashState
  43584. && hasKeyboardFocus (false)
  43585. && caretVisible
  43586. && ! isReadOnly())
  43587. {
  43588. g.setColour (findColour (caretColourId));
  43589. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  43590. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  43591. 2.0f, cursorHeight);
  43592. }
  43593. if (textToShowWhenEmpty.isNotEmpty()
  43594. && (! hasKeyboardFocus (false))
  43595. && getTotalNumChars() == 0)
  43596. {
  43597. g.setColour (colourForTextWhenEmpty);
  43598. g.setFont (getFont());
  43599. if (isMultiLine())
  43600. {
  43601. g.drawText (textToShowWhenEmpty,
  43602. 0, 0, getWidth(), getHeight(),
  43603. Justification::centred, true);
  43604. }
  43605. else
  43606. {
  43607. g.drawText (textToShowWhenEmpty,
  43608. leftIndent, topIndent,
  43609. viewport->getWidth() - leftIndent,
  43610. viewport->getHeight() - topIndent,
  43611. Justification::centredLeft, true);
  43612. }
  43613. }
  43614. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  43615. }
  43616. class TextEditorMenuPerformer : public ModalComponentManager::Callback
  43617. {
  43618. public:
  43619. TextEditorMenuPerformer (TextEditor* const editor_)
  43620. : editor (editor_)
  43621. {
  43622. }
  43623. void modalStateFinished (int returnValue)
  43624. {
  43625. if (editor != 0 && returnValue != 0)
  43626. editor->performPopupMenuAction (returnValue);
  43627. }
  43628. private:
  43629. Component::SafePointer<TextEditor> editor;
  43630. TextEditorMenuPerformer (const TextEditorMenuPerformer&);
  43631. TextEditorMenuPerformer& operator= (const TextEditorMenuPerformer&);
  43632. };
  43633. void TextEditor::mouseDown (const MouseEvent& e)
  43634. {
  43635. beginDragAutoRepeat (100);
  43636. newTransaction();
  43637. if (wasFocused || ! selectAllTextWhenFocused)
  43638. {
  43639. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43640. {
  43641. moveCursorTo (getTextIndexAt (e.x, e.y),
  43642. e.mods.isShiftDown());
  43643. }
  43644. else
  43645. {
  43646. PopupMenu m;
  43647. m.setLookAndFeel (&getLookAndFeel());
  43648. addPopupMenuItems (m, &e);
  43649. m.show (0, 0, 0, 0, new TextEditorMenuPerformer (this));
  43650. }
  43651. }
  43652. }
  43653. void TextEditor::mouseDrag (const MouseEvent& e)
  43654. {
  43655. if (wasFocused || ! selectAllTextWhenFocused)
  43656. {
  43657. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  43658. {
  43659. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  43660. }
  43661. }
  43662. }
  43663. void TextEditor::mouseUp (const MouseEvent& e)
  43664. {
  43665. newTransaction();
  43666. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43667. if (wasFocused || ! selectAllTextWhenFocused)
  43668. {
  43669. if (e.mouseWasClicked() && ! (popupMenuEnabled && e.mods.isPopupMenu()))
  43670. {
  43671. moveCaret (getTextIndexAt (e.x, e.y));
  43672. }
  43673. }
  43674. wasFocused = true;
  43675. }
  43676. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  43677. {
  43678. int tokenEnd = getTextIndexAt (e.x, e.y);
  43679. int tokenStart = tokenEnd;
  43680. if (e.getNumberOfClicks() > 3)
  43681. {
  43682. tokenStart = 0;
  43683. tokenEnd = getTotalNumChars();
  43684. }
  43685. else
  43686. {
  43687. const String t (getText());
  43688. const int totalLength = getTotalNumChars();
  43689. while (tokenEnd < totalLength)
  43690. {
  43691. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43692. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]) || t [tokenEnd] > 128)
  43693. ++tokenEnd;
  43694. else
  43695. break;
  43696. }
  43697. tokenStart = tokenEnd;
  43698. while (tokenStart > 0)
  43699. {
  43700. // (note the slight bodge here - it's because iswalnum only checks for alphabetic chars in the current locale)
  43701. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]) || t [tokenStart - 1] > 128)
  43702. --tokenStart;
  43703. else
  43704. break;
  43705. }
  43706. if (e.getNumberOfClicks() > 2)
  43707. {
  43708. while (tokenEnd < totalLength)
  43709. {
  43710. if (t [tokenEnd] != '\r' && t [tokenEnd] != '\n')
  43711. ++tokenEnd;
  43712. else
  43713. break;
  43714. }
  43715. while (tokenStart > 0)
  43716. {
  43717. if (t [tokenStart - 1] != '\r' && t [tokenStart - 1] != '\n')
  43718. --tokenStart;
  43719. else
  43720. break;
  43721. }
  43722. }
  43723. }
  43724. moveCursorTo (tokenEnd, false);
  43725. moveCursorTo (tokenStart, true);
  43726. }
  43727. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  43728. {
  43729. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  43730. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  43731. }
  43732. bool TextEditor::keyPressed (const KeyPress& key)
  43733. {
  43734. if (isReadOnly() && key != KeyPress ('c', ModifierKeys::commandModifier, 0))
  43735. return false;
  43736. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  43737. if (key.isKeyCode (KeyPress::leftKey)
  43738. || key.isKeyCode (KeyPress::upKey))
  43739. {
  43740. newTransaction();
  43741. int newPos;
  43742. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  43743. newPos = indexAtPosition (cursorX, cursorY - 1);
  43744. else if (moveInWholeWordSteps)
  43745. newPos = findWordBreakBefore (getCaretPosition());
  43746. else
  43747. newPos = getCaretPosition() - 1;
  43748. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43749. }
  43750. else if (key.isKeyCode (KeyPress::rightKey)
  43751. || key.isKeyCode (KeyPress::downKey))
  43752. {
  43753. newTransaction();
  43754. int newPos;
  43755. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  43756. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  43757. else if (moveInWholeWordSteps)
  43758. newPos = findWordBreakAfter (getCaretPosition());
  43759. else
  43760. newPos = getCaretPosition() + 1;
  43761. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  43762. }
  43763. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  43764. {
  43765. newTransaction();
  43766. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  43767. key.getModifiers().isShiftDown());
  43768. }
  43769. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  43770. {
  43771. newTransaction();
  43772. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  43773. key.getModifiers().isShiftDown());
  43774. }
  43775. else if (key.isKeyCode (KeyPress::homeKey))
  43776. {
  43777. newTransaction();
  43778. if (isMultiLine() && ! moveInWholeWordSteps)
  43779. moveCursorTo (indexAtPosition (0.0f, cursorY),
  43780. key.getModifiers().isShiftDown());
  43781. else
  43782. moveCursorTo (0, key.getModifiers().isShiftDown());
  43783. }
  43784. else if (key.isKeyCode (KeyPress::endKey))
  43785. {
  43786. newTransaction();
  43787. if (isMultiLine() && ! moveInWholeWordSteps)
  43788. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  43789. key.getModifiers().isShiftDown());
  43790. else
  43791. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  43792. }
  43793. else if (key.isKeyCode (KeyPress::backspaceKey))
  43794. {
  43795. if (moveInWholeWordSteps)
  43796. {
  43797. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  43798. }
  43799. else
  43800. {
  43801. if (selection.isEmpty() && selection.getStart() > 0)
  43802. selection.setStart (selection.getEnd() - 1);
  43803. }
  43804. cut();
  43805. }
  43806. else if (key.isKeyCode (KeyPress::deleteKey))
  43807. {
  43808. if (key.getModifiers().isShiftDown())
  43809. copy();
  43810. if (selection.isEmpty() && selection.getStart() < getTotalNumChars())
  43811. selection.setEnd (selection.getStart() + 1);
  43812. cut();
  43813. }
  43814. else if (key == KeyPress ('c', ModifierKeys::commandModifier, 0)
  43815. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  43816. {
  43817. newTransaction();
  43818. copy();
  43819. }
  43820. else if (key == KeyPress ('x', ModifierKeys::commandModifier, 0))
  43821. {
  43822. newTransaction();
  43823. copy();
  43824. cut();
  43825. }
  43826. else if (key == KeyPress ('v', ModifierKeys::commandModifier, 0)
  43827. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  43828. {
  43829. newTransaction();
  43830. paste();
  43831. }
  43832. else if (key == KeyPress ('z', ModifierKeys::commandModifier, 0))
  43833. {
  43834. newTransaction();
  43835. doUndoRedo (false);
  43836. }
  43837. else if (key == KeyPress ('y', ModifierKeys::commandModifier, 0))
  43838. {
  43839. newTransaction();
  43840. doUndoRedo (true);
  43841. }
  43842. else if (key == KeyPress ('a', ModifierKeys::commandModifier, 0))
  43843. {
  43844. newTransaction();
  43845. moveCursorTo (getTotalNumChars(), false);
  43846. moveCursorTo (0, true);
  43847. }
  43848. else if (key == KeyPress::returnKey)
  43849. {
  43850. newTransaction();
  43851. insertTextAtCaret ("\n");
  43852. }
  43853. else if (key.isKeyCode (KeyPress::escapeKey))
  43854. {
  43855. newTransaction();
  43856. moveCursorTo (getCaretPosition(), false);
  43857. escapePressed();
  43858. }
  43859. else if (key.getTextCharacter() >= ' '
  43860. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  43861. {
  43862. insertTextAtCaret (String::charToString (key.getTextCharacter()));
  43863. lastTransactionTime = Time::getApproximateMillisecondCounter();
  43864. }
  43865. else
  43866. {
  43867. return false;
  43868. }
  43869. return true;
  43870. }
  43871. bool TextEditor::keyStateChanged (const bool isKeyDown)
  43872. {
  43873. if (! isKeyDown)
  43874. return false;
  43875. #if JUCE_WINDOWS
  43876. if (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0).isCurrentlyDown())
  43877. return false; // We need to explicitly allow alt-F4 to pass through on Windows
  43878. #endif
  43879. // (overridden to avoid forwarding key events to the parent)
  43880. return ! ModifierKeys::getCurrentModifiers().isCommandDown();
  43881. }
  43882. const int baseMenuItemID = 0x7fff0000;
  43883. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  43884. {
  43885. const bool writable = ! isReadOnly();
  43886. if (passwordCharacter == 0)
  43887. {
  43888. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  43889. m.addItem (baseMenuItemID + 2, TRANS("copy"), ! selection.isEmpty());
  43890. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  43891. }
  43892. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  43893. m.addSeparator();
  43894. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  43895. m.addSeparator();
  43896. if (getUndoManager() != 0)
  43897. {
  43898. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  43899. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  43900. }
  43901. }
  43902. void TextEditor::performPopupMenuAction (const int menuItemID)
  43903. {
  43904. switch (menuItemID)
  43905. {
  43906. case baseMenuItemID + 1:
  43907. copy();
  43908. cut();
  43909. break;
  43910. case baseMenuItemID + 2:
  43911. copy();
  43912. break;
  43913. case baseMenuItemID + 3:
  43914. paste();
  43915. break;
  43916. case baseMenuItemID + 4:
  43917. cut();
  43918. break;
  43919. case baseMenuItemID + 5:
  43920. moveCursorTo (getTotalNumChars(), false);
  43921. moveCursorTo (0, true);
  43922. break;
  43923. case baseMenuItemID + 6:
  43924. doUndoRedo (false);
  43925. break;
  43926. case baseMenuItemID + 7:
  43927. doUndoRedo (true);
  43928. break;
  43929. default:
  43930. break;
  43931. }
  43932. }
  43933. void TextEditor::focusGained (FocusChangeType)
  43934. {
  43935. newTransaction();
  43936. caretFlashState = true;
  43937. if (selectAllTextWhenFocused)
  43938. {
  43939. moveCursorTo (0, false);
  43940. moveCursorTo (getTotalNumChars(), true);
  43941. }
  43942. repaint();
  43943. if (caretVisible)
  43944. textHolder->startTimer (TextEditorDefs::flashSpeedIntervalMs);
  43945. ComponentPeer* const peer = getPeer();
  43946. if (peer != 0 && ! isReadOnly())
  43947. peer->textInputRequired (getScreenPosition() - peer->getScreenPosition());
  43948. }
  43949. void TextEditor::focusLost (FocusChangeType)
  43950. {
  43951. newTransaction();
  43952. wasFocused = false;
  43953. textHolder->stopTimer();
  43954. caretFlashState = false;
  43955. postCommandMessage (TextEditorDefs::focusLossMessageId);
  43956. repaint();
  43957. }
  43958. void TextEditor::resized()
  43959. {
  43960. viewport->setBoundsInset (borderSize);
  43961. viewport->setSingleStepSizes (16, roundToInt (currentFont.getHeight()));
  43962. updateTextHolderSize();
  43963. if (! isMultiLine())
  43964. {
  43965. scrollToMakeSureCursorIsVisible();
  43966. }
  43967. else
  43968. {
  43969. updateCaretPosition();
  43970. }
  43971. }
  43972. void TextEditor::handleCommandMessage (const int commandId)
  43973. {
  43974. Component::BailOutChecker checker (this);
  43975. switch (commandId)
  43976. {
  43977. case TextEditorDefs::textChangeMessageId:
  43978. listeners.callChecked (checker, &TextEditor::Listener::textEditorTextChanged, (TextEditor&) *this);
  43979. break;
  43980. case TextEditorDefs::returnKeyMessageId:
  43981. listeners.callChecked (checker, &TextEditor::Listener::textEditorReturnKeyPressed, (TextEditor&) *this);
  43982. break;
  43983. case TextEditorDefs::escapeKeyMessageId:
  43984. listeners.callChecked (checker, &TextEditor::Listener::textEditorEscapeKeyPressed, (TextEditor&) *this);
  43985. break;
  43986. case TextEditorDefs::focusLossMessageId:
  43987. listeners.callChecked (checker, &TextEditor::Listener::textEditorFocusLost, (TextEditor&) *this);
  43988. break;
  43989. default:
  43990. jassertfalse;
  43991. break;
  43992. }
  43993. }
  43994. void TextEditor::enablementChanged()
  43995. {
  43996. setMouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  43997. : MouseCursor::IBeamCursor);
  43998. repaint();
  43999. }
  44000. UndoManager* TextEditor::getUndoManager() throw()
  44001. {
  44002. return isReadOnly() ? 0 : &undoManager;
  44003. }
  44004. void TextEditor::clearInternal (UndoManager* const um)
  44005. {
  44006. remove (Range<int> (0, getTotalNumChars()), um, caretPosition);
  44007. }
  44008. void TextEditor::insert (const String& text,
  44009. const int insertIndex,
  44010. const Font& font,
  44011. const Colour& colour,
  44012. UndoManager* const um,
  44013. const int caretPositionToMoveTo)
  44014. {
  44015. if (text.isNotEmpty())
  44016. {
  44017. if (um != 0)
  44018. {
  44019. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44020. newTransaction();
  44021. um->perform (new InsertAction (*this, text, insertIndex, font, colour,
  44022. caretPosition, caretPositionToMoveTo));
  44023. }
  44024. else
  44025. {
  44026. repaintText (Range<int> (insertIndex, getTotalNumChars())); // must do this before and after changing the data, in case
  44027. // a line gets moved due to word wrap
  44028. int index = 0;
  44029. int nextIndex = 0;
  44030. for (int i = 0; i < sections.size(); ++i)
  44031. {
  44032. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44033. if (insertIndex == index)
  44034. {
  44035. sections.insert (i, new UniformTextSection (text,
  44036. font, colour,
  44037. passwordCharacter));
  44038. break;
  44039. }
  44040. else if (insertIndex > index && insertIndex < nextIndex)
  44041. {
  44042. splitSection (i, insertIndex - index);
  44043. sections.insert (i + 1, new UniformTextSection (text,
  44044. font, colour,
  44045. passwordCharacter));
  44046. break;
  44047. }
  44048. index = nextIndex;
  44049. }
  44050. if (nextIndex == insertIndex)
  44051. sections.add (new UniformTextSection (text,
  44052. font, colour,
  44053. passwordCharacter));
  44054. coalesceSimilarSections();
  44055. totalNumChars = -1;
  44056. valueTextNeedsUpdating = true;
  44057. moveCursorTo (caretPositionToMoveTo, false);
  44058. repaintText (Range<int> (insertIndex, getTotalNumChars()));
  44059. }
  44060. }
  44061. }
  44062. void TextEditor::reinsert (const int insertIndex,
  44063. const Array <UniformTextSection*>& sectionsToInsert)
  44064. {
  44065. int index = 0;
  44066. int nextIndex = 0;
  44067. for (int i = 0; i < sections.size(); ++i)
  44068. {
  44069. nextIndex = index + sections.getUnchecked (i)->getTotalLength();
  44070. if (insertIndex == index)
  44071. {
  44072. for (int j = sectionsToInsert.size(); --j >= 0;)
  44073. sections.insert (i, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44074. break;
  44075. }
  44076. else if (insertIndex > index && insertIndex < nextIndex)
  44077. {
  44078. splitSection (i, insertIndex - index);
  44079. for (int j = sectionsToInsert.size(); --j >= 0;)
  44080. sections.insert (i + 1, new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44081. break;
  44082. }
  44083. index = nextIndex;
  44084. }
  44085. if (nextIndex == insertIndex)
  44086. {
  44087. for (int j = 0; j < sectionsToInsert.size(); ++j)
  44088. sections.add (new UniformTextSection (*sectionsToInsert.getUnchecked(j)));
  44089. }
  44090. coalesceSimilarSections();
  44091. totalNumChars = -1;
  44092. valueTextNeedsUpdating = true;
  44093. }
  44094. void TextEditor::remove (const Range<int>& range,
  44095. UndoManager* const um,
  44096. const int caretPositionToMoveTo)
  44097. {
  44098. if (! range.isEmpty())
  44099. {
  44100. int index = 0;
  44101. for (int i = 0; i < sections.size(); ++i)
  44102. {
  44103. const int nextIndex = index + sections.getUnchecked(i)->getTotalLength();
  44104. if (range.getStart() > index && range.getStart() < nextIndex)
  44105. {
  44106. splitSection (i, range.getStart() - index);
  44107. --i;
  44108. }
  44109. else if (range.getEnd() > index && range.getEnd() < nextIndex)
  44110. {
  44111. splitSection (i, range.getEnd() - index);
  44112. --i;
  44113. }
  44114. else
  44115. {
  44116. index = nextIndex;
  44117. if (index > range.getEnd())
  44118. break;
  44119. }
  44120. }
  44121. index = 0;
  44122. if (um != 0)
  44123. {
  44124. Array <UniformTextSection*> removedSections;
  44125. for (int i = 0; i < sections.size(); ++i)
  44126. {
  44127. if (range.getEnd() <= range.getStart())
  44128. break;
  44129. UniformTextSection* const section = sections.getUnchecked (i);
  44130. const int nextIndex = index + section->getTotalLength();
  44131. if (range.getStart() <= index && range.getEnd() >= nextIndex)
  44132. removedSections.add (new UniformTextSection (*section));
  44133. index = nextIndex;
  44134. }
  44135. if (um->getNumActionsInCurrentTransaction() > TextEditorDefs::maxActionsPerTransaction)
  44136. newTransaction();
  44137. um->perform (new RemoveAction (*this, range, caretPosition,
  44138. caretPositionToMoveTo, removedSections));
  44139. }
  44140. else
  44141. {
  44142. Range<int> remainingRange (range);
  44143. for (int i = 0; i < sections.size(); ++i)
  44144. {
  44145. UniformTextSection* const section = sections.getUnchecked (i);
  44146. const int nextIndex = index + section->getTotalLength();
  44147. if (remainingRange.getStart() <= index && remainingRange.getEnd() >= nextIndex)
  44148. {
  44149. sections.remove(i);
  44150. section->clear();
  44151. delete section;
  44152. remainingRange.setEnd (remainingRange.getEnd() - (nextIndex - index));
  44153. if (remainingRange.isEmpty())
  44154. break;
  44155. --i;
  44156. }
  44157. else
  44158. {
  44159. index = nextIndex;
  44160. }
  44161. }
  44162. coalesceSimilarSections();
  44163. totalNumChars = -1;
  44164. valueTextNeedsUpdating = true;
  44165. moveCursorTo (caretPositionToMoveTo, false);
  44166. repaintText (Range<int> (range.getStart(), getTotalNumChars()));
  44167. }
  44168. }
  44169. }
  44170. const String TextEditor::getText() const
  44171. {
  44172. String t;
  44173. t.preallocateStorage (getTotalNumChars());
  44174. String::Concatenator concatenator (t);
  44175. for (int i = 0; i < sections.size(); ++i)
  44176. sections.getUnchecked (i)->appendAllText (concatenator);
  44177. return t;
  44178. }
  44179. const String TextEditor::getTextInRange (const Range<int>& range) const
  44180. {
  44181. String t;
  44182. if (! range.isEmpty())
  44183. {
  44184. t.preallocateStorage (jmin (getTotalNumChars(), range.getLength()));
  44185. String::Concatenator concatenator (t);
  44186. int index = 0;
  44187. for (int i = 0; i < sections.size(); ++i)
  44188. {
  44189. const UniformTextSection* const s = sections.getUnchecked (i);
  44190. const int nextIndex = index + s->getTotalLength();
  44191. if (range.getStart() < nextIndex)
  44192. {
  44193. if (range.getEnd() <= index)
  44194. break;
  44195. s->appendSubstring (concatenator, range - index);
  44196. }
  44197. index = nextIndex;
  44198. }
  44199. }
  44200. return t;
  44201. }
  44202. const String TextEditor::getHighlightedText() const
  44203. {
  44204. return getTextInRange (selection);
  44205. }
  44206. int TextEditor::getTotalNumChars() const
  44207. {
  44208. if (totalNumChars < 0)
  44209. {
  44210. totalNumChars = 0;
  44211. for (int i = sections.size(); --i >= 0;)
  44212. totalNumChars += sections.getUnchecked (i)->getTotalLength();
  44213. }
  44214. return totalNumChars;
  44215. }
  44216. bool TextEditor::isEmpty() const
  44217. {
  44218. return getTotalNumChars() == 0;
  44219. }
  44220. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const
  44221. {
  44222. const float wordWrapWidth = getWordWrapWidth();
  44223. if (wordWrapWidth > 0 && sections.size() > 0)
  44224. {
  44225. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44226. i.getCharPosition (index, cx, cy, lineHeight);
  44227. }
  44228. else
  44229. {
  44230. cx = cy = 0;
  44231. lineHeight = currentFont.getHeight();
  44232. }
  44233. }
  44234. int TextEditor::indexAtPosition (const float x, const float y)
  44235. {
  44236. const float wordWrapWidth = getWordWrapWidth();
  44237. if (wordWrapWidth > 0)
  44238. {
  44239. Iterator i (sections, wordWrapWidth, passwordCharacter);
  44240. while (i.next())
  44241. {
  44242. if (i.lineY + i.lineHeight > y)
  44243. {
  44244. if (i.lineY > y)
  44245. return jmax (0, i.indexInText - 1);
  44246. if (i.atomX >= x)
  44247. return i.indexInText;
  44248. if (x < i.atomRight)
  44249. return i.xToIndex (x);
  44250. }
  44251. }
  44252. }
  44253. return getTotalNumChars();
  44254. }
  44255. int TextEditor::findWordBreakAfter (const int position) const
  44256. {
  44257. const String t (getTextInRange (Range<int> (position, position + 512)));
  44258. const int totalLength = t.length();
  44259. int i = 0;
  44260. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44261. ++i;
  44262. const int type = TextEditorDefs::getCharacterCategory (t[i]);
  44263. while (i < totalLength && type == TextEditorDefs::getCharacterCategory (t[i]))
  44264. ++i;
  44265. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  44266. ++i;
  44267. return position + i;
  44268. }
  44269. int TextEditor::findWordBreakBefore (const int position) const
  44270. {
  44271. if (position <= 0)
  44272. return 0;
  44273. const int startOfBuffer = jmax (0, position - 512);
  44274. const String t (getTextInRange (Range<int> (startOfBuffer, position)));
  44275. int i = position - startOfBuffer;
  44276. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  44277. --i;
  44278. if (i > 0)
  44279. {
  44280. const int type = TextEditorDefs::getCharacterCategory (t [i - 1]);
  44281. while (i > 0 && type == TextEditorDefs::getCharacterCategory (t [i - 1]))
  44282. --i;
  44283. }
  44284. jassert (startOfBuffer + i >= 0);
  44285. return startOfBuffer + i;
  44286. }
  44287. void TextEditor::splitSection (const int sectionIndex,
  44288. const int charToSplitAt)
  44289. {
  44290. jassert (sections[sectionIndex] != 0);
  44291. sections.insert (sectionIndex + 1,
  44292. sections.getUnchecked (sectionIndex)->split (charToSplitAt, passwordCharacter));
  44293. }
  44294. void TextEditor::coalesceSimilarSections()
  44295. {
  44296. for (int i = 0; i < sections.size() - 1; ++i)
  44297. {
  44298. UniformTextSection* const s1 = sections.getUnchecked (i);
  44299. UniformTextSection* const s2 = sections.getUnchecked (i + 1);
  44300. if (s1->font == s2->font
  44301. && s1->colour == s2->colour)
  44302. {
  44303. s1->append (*s2, passwordCharacter);
  44304. sections.remove (i + 1);
  44305. delete s2;
  44306. --i;
  44307. }
  44308. }
  44309. }
  44310. END_JUCE_NAMESPACE
  44311. /*** End of inlined file: juce_TextEditor.cpp ***/
  44312. /*** Start of inlined file: juce_Toolbar.cpp ***/
  44313. BEGIN_JUCE_NAMESPACE
  44314. const char* const Toolbar::toolbarDragDescriptor = "_toolbarItem_";
  44315. class ToolbarSpacerComp : public ToolbarItemComponent
  44316. {
  44317. public:
  44318. ToolbarSpacerComp (const int itemId_, const float fixedSize_, const bool drawBar_)
  44319. : ToolbarItemComponent (itemId_, String::empty, false),
  44320. fixedSize (fixedSize_),
  44321. drawBar (drawBar_)
  44322. {
  44323. }
  44324. ~ToolbarSpacerComp()
  44325. {
  44326. }
  44327. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  44328. int& preferredSize, int& minSize, int& maxSize)
  44329. {
  44330. if (fixedSize <= 0)
  44331. {
  44332. preferredSize = toolbarThickness * 2;
  44333. minSize = 4;
  44334. maxSize = 32768;
  44335. }
  44336. else
  44337. {
  44338. maxSize = roundToInt (toolbarThickness * fixedSize);
  44339. minSize = drawBar ? maxSize : jmin (4, maxSize);
  44340. preferredSize = maxSize;
  44341. if (getEditingMode() == editableOnPalette)
  44342. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  44343. }
  44344. return true;
  44345. }
  44346. void paintButtonArea (Graphics&, int, int, bool, bool)
  44347. {
  44348. }
  44349. void contentAreaChanged (const Rectangle<int>&)
  44350. {
  44351. }
  44352. int getResizeOrder() const throw()
  44353. {
  44354. return fixedSize <= 0 ? 0 : 1;
  44355. }
  44356. void paint (Graphics& g)
  44357. {
  44358. const int w = getWidth();
  44359. const int h = getHeight();
  44360. if (drawBar)
  44361. {
  44362. g.setColour (findColour (Toolbar::separatorColourId, true));
  44363. const float thickness = 0.2f;
  44364. if (isToolbarVertical())
  44365. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  44366. else
  44367. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  44368. }
  44369. if (getEditingMode() != normalMode && ! drawBar)
  44370. {
  44371. g.setColour (findColour (Toolbar::separatorColourId, true));
  44372. const int indentX = jmin (2, (w - 3) / 2);
  44373. const int indentY = jmin (2, (h - 3) / 2);
  44374. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  44375. if (fixedSize <= 0)
  44376. {
  44377. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  44378. if (isToolbarVertical())
  44379. {
  44380. x1 = w * 0.5f;
  44381. y1 = h * 0.4f;
  44382. x2 = x1;
  44383. y2 = indentX * 2.0f;
  44384. x3 = x1;
  44385. y3 = h * 0.6f;
  44386. x4 = x1;
  44387. y4 = h - y2;
  44388. hw = w * 0.15f;
  44389. hl = w * 0.2f;
  44390. }
  44391. else
  44392. {
  44393. x1 = w * 0.4f;
  44394. y1 = h * 0.5f;
  44395. x2 = indentX * 2.0f;
  44396. y2 = y1;
  44397. x3 = w * 0.6f;
  44398. y3 = y1;
  44399. x4 = w - x2;
  44400. y4 = y1;
  44401. hw = h * 0.15f;
  44402. hl = h * 0.2f;
  44403. }
  44404. Path p;
  44405. p.addArrow (Line<float> (x1, y1, x2, y2), 1.5f, hw, hl);
  44406. p.addArrow (Line<float> (x3, y3, x4, y4), 1.5f, hw, hl);
  44407. g.fillPath (p);
  44408. }
  44409. }
  44410. }
  44411. juce_UseDebuggingNewOperator
  44412. private:
  44413. const float fixedSize;
  44414. const bool drawBar;
  44415. ToolbarSpacerComp (const ToolbarSpacerComp&);
  44416. ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  44417. };
  44418. class Toolbar::MissingItemsComponent : public PopupMenuCustomComponent
  44419. {
  44420. public:
  44421. MissingItemsComponent (Toolbar& owner_, const int height_)
  44422. : PopupMenuCustomComponent (true),
  44423. owner (owner_),
  44424. height (height_)
  44425. {
  44426. for (int i = owner_.items.size(); --i >= 0;)
  44427. {
  44428. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  44429. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  44430. {
  44431. oldIndexes.insert (0, i);
  44432. addAndMakeVisible (tc, 0);
  44433. }
  44434. }
  44435. layout (400);
  44436. }
  44437. ~MissingItemsComponent()
  44438. {
  44439. // deleting the toolbar while its menu it open??
  44440. jassert (owner.isValidComponent());
  44441. for (int i = 0; i < getNumChildComponents(); ++i)
  44442. {
  44443. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44444. if (tc != 0)
  44445. {
  44446. tc->setVisible (false);
  44447. const int index = oldIndexes.remove (i);
  44448. owner.addChildComponent (tc, index);
  44449. --i;
  44450. }
  44451. }
  44452. owner.resized();
  44453. }
  44454. void layout (const int preferredWidth)
  44455. {
  44456. const int indent = 8;
  44457. int x = indent;
  44458. int y = indent;
  44459. int maxX = 0;
  44460. for (int i = 0; i < getNumChildComponents(); ++i)
  44461. {
  44462. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  44463. if (tc != 0)
  44464. {
  44465. int preferredSize = 1, minSize = 1, maxSize = 1;
  44466. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  44467. {
  44468. if (x + preferredSize > preferredWidth && x > indent)
  44469. {
  44470. x = indent;
  44471. y += height;
  44472. }
  44473. tc->setBounds (x, y, preferredSize, height);
  44474. x += preferredSize;
  44475. maxX = jmax (maxX, x);
  44476. }
  44477. }
  44478. }
  44479. setSize (maxX + 8, y + height + 8);
  44480. }
  44481. void getIdealSize (int& idealWidth, int& idealHeight)
  44482. {
  44483. idealWidth = getWidth();
  44484. idealHeight = getHeight();
  44485. }
  44486. juce_UseDebuggingNewOperator
  44487. private:
  44488. Toolbar& owner;
  44489. const int height;
  44490. Array <int> oldIndexes;
  44491. MissingItemsComponent (const MissingItemsComponent&);
  44492. MissingItemsComponent& operator= (const MissingItemsComponent&);
  44493. };
  44494. Toolbar::Toolbar()
  44495. : vertical (false),
  44496. isEditingActive (false),
  44497. toolbarStyle (Toolbar::iconsOnly)
  44498. {
  44499. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  44500. missingItemsButton->setAlwaysOnTop (true);
  44501. missingItemsButton->addButtonListener (this);
  44502. }
  44503. Toolbar::~Toolbar()
  44504. {
  44505. deleteAllChildren();
  44506. }
  44507. void Toolbar::setVertical (const bool shouldBeVertical)
  44508. {
  44509. if (vertical != shouldBeVertical)
  44510. {
  44511. vertical = shouldBeVertical;
  44512. resized();
  44513. }
  44514. }
  44515. void Toolbar::clear()
  44516. {
  44517. for (int i = items.size(); --i >= 0;)
  44518. {
  44519. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44520. items.remove (i);
  44521. delete tc;
  44522. }
  44523. resized();
  44524. }
  44525. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  44526. {
  44527. if (itemId == ToolbarItemFactory::separatorBarId)
  44528. return new ToolbarSpacerComp (itemId, 0.1f, true);
  44529. else if (itemId == ToolbarItemFactory::spacerId)
  44530. return new ToolbarSpacerComp (itemId, 0.5f, false);
  44531. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  44532. return new ToolbarSpacerComp (itemId, 0, false);
  44533. return factory.createItem (itemId);
  44534. }
  44535. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  44536. const int itemId,
  44537. const int insertIndex)
  44538. {
  44539. // An ID can't be zero - this might indicate a mistake somewhere?
  44540. jassert (itemId != 0);
  44541. ToolbarItemComponent* const tc = createItem (factory, itemId);
  44542. if (tc != 0)
  44543. {
  44544. #if JUCE_DEBUG
  44545. Array <int> allowedIds;
  44546. factory.getAllToolbarItemIds (allowedIds);
  44547. // If your factory can create an item for a given ID, it must also return
  44548. // that ID from its getAllToolbarItemIds() method!
  44549. jassert (allowedIds.contains (itemId));
  44550. #endif
  44551. items.insert (insertIndex, tc);
  44552. addAndMakeVisible (tc, insertIndex);
  44553. }
  44554. }
  44555. void Toolbar::addItem (ToolbarItemFactory& factory,
  44556. const int itemId,
  44557. const int insertIndex)
  44558. {
  44559. addItemInternal (factory, itemId, insertIndex);
  44560. resized();
  44561. }
  44562. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  44563. {
  44564. Array <int> ids;
  44565. factoryToUse.getDefaultItemSet (ids);
  44566. clear();
  44567. for (int i = 0; i < ids.size(); ++i)
  44568. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  44569. resized();
  44570. }
  44571. void Toolbar::removeToolbarItem (const int itemIndex)
  44572. {
  44573. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44574. if (tc != 0)
  44575. {
  44576. items.removeValue (tc);
  44577. delete tc;
  44578. resized();
  44579. }
  44580. }
  44581. int Toolbar::getNumItems() const throw()
  44582. {
  44583. return items.size();
  44584. }
  44585. int Toolbar::getItemId (const int itemIndex) const throw()
  44586. {
  44587. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  44588. return tc != 0 ? tc->getItemId() : 0;
  44589. }
  44590. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  44591. {
  44592. return items [itemIndex];
  44593. }
  44594. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  44595. {
  44596. for (;;)
  44597. {
  44598. index += delta;
  44599. ToolbarItemComponent* const tc = getItemComponent (index);
  44600. if (tc == 0)
  44601. break;
  44602. if (tc->isActive)
  44603. return tc;
  44604. }
  44605. return 0;
  44606. }
  44607. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  44608. {
  44609. if (toolbarStyle != newStyle)
  44610. {
  44611. toolbarStyle = newStyle;
  44612. updateAllItemPositions (false);
  44613. }
  44614. }
  44615. const String Toolbar::toString() const
  44616. {
  44617. String s ("TB:");
  44618. for (int i = 0; i < getNumItems(); ++i)
  44619. s << getItemId(i) << ' ';
  44620. return s.trimEnd();
  44621. }
  44622. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  44623. const String& savedVersion)
  44624. {
  44625. if (! savedVersion.startsWith ("TB:"))
  44626. return false;
  44627. StringArray tokens;
  44628. tokens.addTokens (savedVersion.substring (3), false);
  44629. clear();
  44630. for (int i = 0; i < tokens.size(); ++i)
  44631. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  44632. resized();
  44633. return true;
  44634. }
  44635. void Toolbar::paint (Graphics& g)
  44636. {
  44637. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  44638. }
  44639. int Toolbar::getThickness() const throw()
  44640. {
  44641. return vertical ? getWidth() : getHeight();
  44642. }
  44643. int Toolbar::getLength() const throw()
  44644. {
  44645. return vertical ? getHeight() : getWidth();
  44646. }
  44647. void Toolbar::setEditingActive (const bool active)
  44648. {
  44649. if (isEditingActive != active)
  44650. {
  44651. isEditingActive = active;
  44652. updateAllItemPositions (false);
  44653. }
  44654. }
  44655. void Toolbar::resized()
  44656. {
  44657. updateAllItemPositions (false);
  44658. }
  44659. void Toolbar::updateAllItemPositions (const bool animate)
  44660. {
  44661. if (getWidth() > 0 && getHeight() > 0)
  44662. {
  44663. StretchableObjectResizer resizer;
  44664. int i;
  44665. for (i = 0; i < items.size(); ++i)
  44666. {
  44667. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44668. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  44669. : ToolbarItemComponent::normalMode);
  44670. tc->setStyle (toolbarStyle);
  44671. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  44672. int preferredSize = 1, minSize = 1, maxSize = 1;
  44673. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  44674. preferredSize, minSize, maxSize))
  44675. {
  44676. tc->isActive = true;
  44677. resizer.addItem (preferredSize, minSize, maxSize,
  44678. spacer != 0 ? spacer->getResizeOrder() : 2);
  44679. }
  44680. else
  44681. {
  44682. tc->isActive = false;
  44683. tc->setVisible (false);
  44684. }
  44685. }
  44686. resizer.resizeToFit (getLength());
  44687. int totalLength = 0;
  44688. for (i = 0; i < resizer.getNumItems(); ++i)
  44689. totalLength += (int) resizer.getItemSize (i);
  44690. const bool itemsOffTheEnd = totalLength > getLength();
  44691. const int extrasButtonSize = getThickness() / 2;
  44692. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  44693. missingItemsButton->setVisible (itemsOffTheEnd);
  44694. missingItemsButton->setEnabled (! isEditingActive);
  44695. if (vertical)
  44696. missingItemsButton->setCentrePosition (getWidth() / 2,
  44697. getHeight() - 4 - extrasButtonSize / 2);
  44698. else
  44699. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  44700. getHeight() / 2);
  44701. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  44702. : missingItemsButton->getX()) - 4
  44703. : getLength();
  44704. int pos = 0, activeIndex = 0;
  44705. for (i = 0; i < items.size(); ++i)
  44706. {
  44707. ToolbarItemComponent* const tc = items.getUnchecked(i);
  44708. if (tc->isActive)
  44709. {
  44710. const int size = (int) resizer.getItemSize (activeIndex++);
  44711. Rectangle<int> newBounds;
  44712. if (vertical)
  44713. newBounds.setBounds (0, pos, getWidth(), size);
  44714. else
  44715. newBounds.setBounds (pos, 0, size, getHeight());
  44716. if (animate)
  44717. {
  44718. Desktop::getInstance().getAnimator().animateComponent (tc, newBounds, 1.0f, 200, false, 3.0, 0.0);
  44719. }
  44720. else
  44721. {
  44722. Desktop::getInstance().getAnimator().cancelAnimation (tc, false);
  44723. tc->setBounds (newBounds);
  44724. }
  44725. pos += size;
  44726. tc->setVisible (pos <= maxLength
  44727. && ((! tc->isBeingDragged)
  44728. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  44729. }
  44730. }
  44731. }
  44732. }
  44733. void Toolbar::buttonClicked (Button*)
  44734. {
  44735. jassert (missingItemsButton->isShowing());
  44736. if (missingItemsButton->isShowing())
  44737. {
  44738. PopupMenu m;
  44739. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  44740. m.showAt (missingItemsButton);
  44741. }
  44742. }
  44743. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  44744. Component* /*sourceComponent*/)
  44745. {
  44746. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  44747. }
  44748. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  44749. {
  44750. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44751. if (tc != 0)
  44752. {
  44753. if (getNumItems() == 0)
  44754. {
  44755. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44756. {
  44757. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44758. if (palette != 0)
  44759. palette->replaceComponent (tc);
  44760. }
  44761. else
  44762. {
  44763. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44764. }
  44765. items.add (tc);
  44766. addChildComponent (tc);
  44767. updateAllItemPositions (false);
  44768. }
  44769. else
  44770. {
  44771. for (int i = getNumItems(); --i >= 0;)
  44772. {
  44773. int currentIndex = getIndexOfChildComponent (tc);
  44774. if (currentIndex < 0)
  44775. {
  44776. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  44777. {
  44778. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  44779. if (palette != 0)
  44780. palette->replaceComponent (tc);
  44781. }
  44782. else
  44783. {
  44784. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  44785. }
  44786. items.add (tc);
  44787. addChildComponent (tc);
  44788. currentIndex = getIndexOfChildComponent (tc);
  44789. updateAllItemPositions (true);
  44790. }
  44791. int newIndex = currentIndex;
  44792. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  44793. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  44794. const Rectangle<int> current (Desktop::getInstance().getAnimator()
  44795. .getComponentDestination (getChildComponent (newIndex)));
  44796. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  44797. if (prev != 0)
  44798. {
  44799. const Rectangle<int> previousPos (Desktop::getInstance().getAnimator().getComponentDestination (prev));
  44800. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  44801. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  44802. {
  44803. newIndex = getIndexOfChildComponent (prev);
  44804. }
  44805. }
  44806. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  44807. if (next != 0)
  44808. {
  44809. const Rectangle<int> nextPos (Desktop::getInstance().getAnimator().getComponentDestination (next));
  44810. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  44811. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  44812. {
  44813. newIndex = getIndexOfChildComponent (next) + 1;
  44814. }
  44815. }
  44816. if (newIndex != currentIndex)
  44817. {
  44818. items.removeValue (tc);
  44819. removeChildComponent (tc);
  44820. addChildComponent (tc, newIndex);
  44821. items.insert (newIndex, tc);
  44822. updateAllItemPositions (true);
  44823. }
  44824. else
  44825. {
  44826. break;
  44827. }
  44828. }
  44829. }
  44830. }
  44831. }
  44832. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  44833. {
  44834. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  44835. if (tc != 0)
  44836. {
  44837. if (isParentOf (tc))
  44838. {
  44839. items.removeValue (tc);
  44840. removeChildComponent (tc);
  44841. updateAllItemPositions (true);
  44842. }
  44843. }
  44844. }
  44845. void Toolbar::itemDropped (const String&, Component*, int, int)
  44846. {
  44847. }
  44848. void Toolbar::mouseDown (const MouseEvent& e)
  44849. {
  44850. if (e.mods.isPopupMenu())
  44851. {
  44852. }
  44853. }
  44854. class ToolbarCustomisationDialog : public DialogWindow
  44855. {
  44856. public:
  44857. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  44858. Toolbar* const toolbar_,
  44859. const int optionFlags)
  44860. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  44861. toolbar (toolbar_)
  44862. {
  44863. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  44864. setResizable (true, true);
  44865. setResizeLimits (400, 300, 1500, 1000);
  44866. positionNearBar();
  44867. }
  44868. ~ToolbarCustomisationDialog()
  44869. {
  44870. setContentComponent (0, true);
  44871. }
  44872. void closeButtonPressed()
  44873. {
  44874. setVisible (false);
  44875. }
  44876. bool canModalEventBeSentToComponent (const Component* comp)
  44877. {
  44878. return toolbar->isParentOf (comp);
  44879. }
  44880. void positionNearBar()
  44881. {
  44882. const Rectangle<int> screenSize (toolbar->getParentMonitorArea());
  44883. const int tbx = toolbar->getScreenX();
  44884. const int tby = toolbar->getScreenY();
  44885. const int gap = 8;
  44886. int x, y;
  44887. if (toolbar->isVertical())
  44888. {
  44889. y = tby;
  44890. if (tbx > screenSize.getCentreX())
  44891. x = tbx - getWidth() - gap;
  44892. else
  44893. x = tbx + toolbar->getWidth() + gap;
  44894. }
  44895. else
  44896. {
  44897. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  44898. if (tby > screenSize.getCentreY())
  44899. y = tby - getHeight() - gap;
  44900. else
  44901. y = tby + toolbar->getHeight() + gap;
  44902. }
  44903. setTopLeftPosition (x, y);
  44904. }
  44905. private:
  44906. Toolbar* const toolbar;
  44907. class CustomiserPanel : public Component,
  44908. private ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  44909. private ButtonListener
  44910. {
  44911. public:
  44912. CustomiserPanel (ToolbarItemFactory& factory_,
  44913. Toolbar* const toolbar_,
  44914. const int optionFlags)
  44915. : factory (factory_),
  44916. toolbar (toolbar_),
  44917. palette (factory_, toolbar_),
  44918. instructions (String::empty, TRANS ("You can drag the items above and drop them onto a toolbar to add them.\n\n"
  44919. "Items on the toolbar can also be dragged around to change their order, or dragged off the edge to delete them.")),
  44920. defaultButton (TRANS ("Restore to default set of items"))
  44921. {
  44922. addAndMakeVisible (&palette);
  44923. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  44924. | Toolbar::allowIconsWithTextChoice
  44925. | Toolbar::allowTextOnlyChoice)) != 0)
  44926. {
  44927. addAndMakeVisible (&styleBox);
  44928. styleBox.setEditableText (false);
  44929. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0) styleBox.addItem (TRANS("Show icons only"), 1);
  44930. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0) styleBox.addItem (TRANS("Show icons and descriptions"), 2);
  44931. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0) styleBox.addItem (TRANS("Show descriptions only"), 3);
  44932. int selectedStyle = 0;
  44933. switch (toolbar_->getStyle())
  44934. {
  44935. case Toolbar::iconsOnly: selectedStyle = 1; break;
  44936. case Toolbar::iconsWithText: selectedStyle = 2; break;
  44937. case Toolbar::textOnly: selectedStyle = 3; break;
  44938. }
  44939. styleBox.setSelectedId (selectedStyle);
  44940. styleBox.addListener (this);
  44941. }
  44942. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  44943. {
  44944. addAndMakeVisible (&defaultButton);
  44945. defaultButton.addButtonListener (this);
  44946. }
  44947. addAndMakeVisible (&instructions);
  44948. instructions.setFont (Font (13.0f));
  44949. setSize (500, 300);
  44950. }
  44951. void comboBoxChanged (ComboBox*)
  44952. {
  44953. switch (styleBox.getSelectedId())
  44954. {
  44955. case 1: toolbar->setStyle (Toolbar::iconsOnly); break;
  44956. case 2: toolbar->setStyle (Toolbar::iconsWithText); break;
  44957. case 3: toolbar->setStyle (Toolbar::textOnly); break;
  44958. }
  44959. palette.resized(); // to make it update the styles
  44960. }
  44961. void buttonClicked (Button*)
  44962. {
  44963. toolbar->addDefaultItems (factory);
  44964. }
  44965. void paint (Graphics& g)
  44966. {
  44967. Colour background;
  44968. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  44969. if (dw != 0)
  44970. background = dw->getBackgroundColour();
  44971. g.setColour (background.contrasting().withAlpha (0.3f));
  44972. g.fillRect (palette.getX(), palette.getBottom() - 1, palette.getWidth(), 1);
  44973. }
  44974. void resized()
  44975. {
  44976. palette.setBounds (0, 0, getWidth(), getHeight() - 120);
  44977. styleBox.setBounds (10, getHeight() - 110, 200, 22);
  44978. defaultButton.changeWidthToFitText (22);
  44979. defaultButton.setTopLeftPosition (240, getHeight() - 110);
  44980. instructions.setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  44981. }
  44982. private:
  44983. ToolbarItemFactory& factory;
  44984. Toolbar* const toolbar;
  44985. ToolbarItemPalette palette;
  44986. Label instructions;
  44987. ComboBox styleBox;
  44988. TextButton defaultButton;
  44989. };
  44990. };
  44991. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  44992. {
  44993. setEditingActive (true);
  44994. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  44995. dw.runModalLoop();
  44996. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  44997. setEditingActive (false);
  44998. }
  44999. END_JUCE_NAMESPACE
  45000. /*** End of inlined file: juce_Toolbar.cpp ***/
  45001. /*** Start of inlined file: juce_ToolbarItemComponent.cpp ***/
  45002. BEGIN_JUCE_NAMESPACE
  45003. ToolbarItemFactory::ToolbarItemFactory()
  45004. {
  45005. }
  45006. ToolbarItemFactory::~ToolbarItemFactory()
  45007. {
  45008. }
  45009. class ItemDragAndDropOverlayComponent : public Component
  45010. {
  45011. public:
  45012. ItemDragAndDropOverlayComponent()
  45013. : isDragging (false)
  45014. {
  45015. setAlwaysOnTop (true);
  45016. setRepaintsOnMouseActivity (true);
  45017. setMouseCursor (MouseCursor::DraggingHandCursor);
  45018. }
  45019. ~ItemDragAndDropOverlayComponent()
  45020. {
  45021. }
  45022. void paint (Graphics& g)
  45023. {
  45024. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45025. if (isMouseOverOrDragging()
  45026. && tc != 0
  45027. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45028. {
  45029. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  45030. g.drawRect (0, 0, getWidth(), getHeight(),
  45031. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  45032. }
  45033. }
  45034. void mouseDown (const MouseEvent& e)
  45035. {
  45036. isDragging = false;
  45037. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45038. if (tc != 0)
  45039. {
  45040. tc->dragOffsetX = e.x;
  45041. tc->dragOffsetY = e.y;
  45042. }
  45043. }
  45044. void mouseDrag (const MouseEvent& e)
  45045. {
  45046. if (! (isDragging || e.mouseWasClicked()))
  45047. {
  45048. isDragging = true;
  45049. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  45050. if (dnd != 0)
  45051. {
  45052. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), Image::null, true);
  45053. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45054. if (tc != 0)
  45055. {
  45056. tc->isBeingDragged = true;
  45057. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45058. tc->setVisible (false);
  45059. }
  45060. }
  45061. }
  45062. }
  45063. void mouseUp (const MouseEvent&)
  45064. {
  45065. isDragging = false;
  45066. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  45067. if (tc != 0)
  45068. {
  45069. tc->isBeingDragged = false;
  45070. Toolbar* const tb = tc->getToolbar();
  45071. if (tb != 0)
  45072. tb->updateAllItemPositions (true);
  45073. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  45074. delete tc;
  45075. }
  45076. }
  45077. void parentSizeChanged()
  45078. {
  45079. setBounds (0, 0, getParentWidth(), getParentHeight());
  45080. }
  45081. juce_UseDebuggingNewOperator
  45082. private:
  45083. bool isDragging;
  45084. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  45085. ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  45086. };
  45087. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  45088. const String& labelText,
  45089. const bool isBeingUsedAsAButton_)
  45090. : Button (labelText),
  45091. itemId (itemId_),
  45092. mode (normalMode),
  45093. toolbarStyle (Toolbar::iconsOnly),
  45094. dragOffsetX (0),
  45095. dragOffsetY (0),
  45096. isActive (true),
  45097. isBeingDragged (false),
  45098. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  45099. {
  45100. // Your item ID can't be 0!
  45101. jassert (itemId_ != 0);
  45102. }
  45103. ToolbarItemComponent::~ToolbarItemComponent()
  45104. {
  45105. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45106. overlayComp = 0;
  45107. }
  45108. Toolbar* ToolbarItemComponent::getToolbar() const
  45109. {
  45110. return dynamic_cast <Toolbar*> (getParentComponent());
  45111. }
  45112. bool ToolbarItemComponent::isToolbarVertical() const
  45113. {
  45114. const Toolbar* const t = getToolbar();
  45115. return t != 0 && t->isVertical();
  45116. }
  45117. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  45118. {
  45119. if (toolbarStyle != newStyle)
  45120. {
  45121. toolbarStyle = newStyle;
  45122. repaint();
  45123. resized();
  45124. }
  45125. }
  45126. void ToolbarItemComponent::paintButton (Graphics& g, const bool over, const bool down)
  45127. {
  45128. if (isBeingUsedAsAButton)
  45129. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  45130. over, down, *this);
  45131. if (toolbarStyle != Toolbar::iconsOnly)
  45132. {
  45133. const int indent = contentArea.getX();
  45134. int y = indent;
  45135. int h = getHeight() - indent * 2;
  45136. if (toolbarStyle == Toolbar::iconsWithText)
  45137. {
  45138. y = contentArea.getBottom() + indent / 2;
  45139. h -= contentArea.getHeight();
  45140. }
  45141. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  45142. getButtonText(), *this);
  45143. }
  45144. if (! contentArea.isEmpty())
  45145. {
  45146. g.saveState();
  45147. g.reduceClipRegion (contentArea);
  45148. g.setOrigin (contentArea.getX(), contentArea.getY());
  45149. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), over, down);
  45150. g.restoreState();
  45151. }
  45152. }
  45153. void ToolbarItemComponent::resized()
  45154. {
  45155. if (toolbarStyle != Toolbar::textOnly)
  45156. {
  45157. const int indent = jmin (proportionOfWidth (0.08f),
  45158. proportionOfHeight (0.08f));
  45159. contentArea = Rectangle<int> (indent, indent,
  45160. getWidth() - indent * 2,
  45161. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  45162. : (getHeight() - indent * 2));
  45163. }
  45164. else
  45165. {
  45166. contentArea = Rectangle<int>();
  45167. }
  45168. contentAreaChanged (contentArea);
  45169. }
  45170. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  45171. {
  45172. if (mode != newMode)
  45173. {
  45174. mode = newMode;
  45175. repaint();
  45176. if (mode == normalMode)
  45177. {
  45178. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  45179. overlayComp = 0;
  45180. }
  45181. else if (overlayComp == 0)
  45182. {
  45183. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  45184. overlayComp->parentSizeChanged();
  45185. }
  45186. resized();
  45187. }
  45188. }
  45189. END_JUCE_NAMESPACE
  45190. /*** End of inlined file: juce_ToolbarItemComponent.cpp ***/
  45191. /*** Start of inlined file: juce_ToolbarItemPalette.cpp ***/
  45192. BEGIN_JUCE_NAMESPACE
  45193. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  45194. Toolbar* const toolbar_)
  45195. : factory (factory_),
  45196. toolbar (toolbar_)
  45197. {
  45198. Component* const itemHolder = new Component();
  45199. viewport.setViewedComponent (itemHolder);
  45200. Array <int> allIds;
  45201. factory_.getAllToolbarItemIds (allIds);
  45202. for (int i = 0; i < allIds.size(); ++i)
  45203. {
  45204. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  45205. jassert (tc != 0);
  45206. if (tc != 0)
  45207. {
  45208. itemHolder->addAndMakeVisible (tc);
  45209. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  45210. }
  45211. }
  45212. addAndMakeVisible (&viewport);
  45213. }
  45214. ToolbarItemPalette::~ToolbarItemPalette()
  45215. {
  45216. viewport.getViewedComponent()->deleteAllChildren();
  45217. }
  45218. void ToolbarItemPalette::resized()
  45219. {
  45220. viewport.setBoundsInset (BorderSize (1));
  45221. Component* const itemHolder = viewport.getViewedComponent();
  45222. const int indent = 8;
  45223. const int preferredWidth = viewport.getWidth() - viewport.getScrollBarThickness() - indent;
  45224. const int height = toolbar->getThickness();
  45225. int x = indent;
  45226. int y = indent;
  45227. int maxX = 0;
  45228. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  45229. {
  45230. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  45231. if (tc != 0)
  45232. {
  45233. tc->setStyle (toolbar->getStyle());
  45234. int preferredSize = 1, minSize = 1, maxSize = 1;
  45235. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  45236. {
  45237. if (x + preferredSize > preferredWidth && x > indent)
  45238. {
  45239. x = indent;
  45240. y += height;
  45241. }
  45242. tc->setBounds (x, y, preferredSize, height);
  45243. x += preferredSize + 8;
  45244. maxX = jmax (maxX, x);
  45245. }
  45246. }
  45247. }
  45248. itemHolder->setSize (maxX, y + height + 8);
  45249. }
  45250. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  45251. {
  45252. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  45253. jassert (tc != 0);
  45254. if (tc != 0)
  45255. {
  45256. tc->setBounds (comp->getBounds());
  45257. tc->setStyle (toolbar->getStyle());
  45258. tc->setEditingMode (comp->getEditingMode());
  45259. viewport.getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  45260. }
  45261. }
  45262. END_JUCE_NAMESPACE
  45263. /*** End of inlined file: juce_ToolbarItemPalette.cpp ***/
  45264. /*** Start of inlined file: juce_TreeView.cpp ***/
  45265. BEGIN_JUCE_NAMESPACE
  45266. class TreeViewContentComponent : public Component,
  45267. public TooltipClient
  45268. {
  45269. public:
  45270. TreeViewContentComponent (TreeView& owner_)
  45271. : owner (owner_),
  45272. buttonUnderMouse (0),
  45273. isDragging (false)
  45274. {
  45275. }
  45276. ~TreeViewContentComponent()
  45277. {
  45278. }
  45279. void mouseDown (const MouseEvent& e)
  45280. {
  45281. updateButtonUnderMouse (e);
  45282. isDragging = false;
  45283. needSelectionOnMouseUp = false;
  45284. Rectangle<int> pos;
  45285. TreeViewItem* const item = findItemAt (e.y, pos);
  45286. if (item == 0)
  45287. return;
  45288. // (if the open/close buttons are hidden, we'll treat clicks to the left of the item
  45289. // as selection clicks)
  45290. if (e.x < pos.getX() && owner.openCloseButtonsVisible)
  45291. {
  45292. if (e.x >= pos.getX() - owner.getIndentSize())
  45293. item->setOpen (! item->isOpen());
  45294. // (clicks to the left of an open/close button are ignored)
  45295. }
  45296. else
  45297. {
  45298. // mouse-down inside the body of the item..
  45299. if (! owner.isMultiSelectEnabled())
  45300. item->setSelected (true, true);
  45301. else if (item->isSelected())
  45302. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  45303. else
  45304. selectBasedOnModifiers (item, e.mods);
  45305. if (e.x >= pos.getX())
  45306. item->itemClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45307. }
  45308. }
  45309. void mouseUp (const MouseEvent& e)
  45310. {
  45311. updateButtonUnderMouse (e);
  45312. if (needSelectionOnMouseUp && e.mouseWasClicked())
  45313. {
  45314. Rectangle<int> pos;
  45315. TreeViewItem* const item = findItemAt (e.y, pos);
  45316. if (item != 0)
  45317. selectBasedOnModifiers (item, e.mods);
  45318. }
  45319. }
  45320. void mouseDoubleClick (const MouseEvent& e)
  45321. {
  45322. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  45323. {
  45324. Rectangle<int> pos;
  45325. TreeViewItem* const item = findItemAt (e.y, pos);
  45326. if (item != 0 && (e.x >= pos.getX() || ! owner.openCloseButtonsVisible))
  45327. item->itemDoubleClicked (e.withNewPosition (e.getPosition() - pos.getPosition()));
  45328. }
  45329. }
  45330. void mouseDrag (const MouseEvent& e)
  45331. {
  45332. if (isEnabled()
  45333. && ! (isDragging || e.mouseWasClicked()
  45334. || e.getDistanceFromDragStart() < 5
  45335. || e.mods.isPopupMenu()))
  45336. {
  45337. isDragging = true;
  45338. Rectangle<int> pos;
  45339. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  45340. if (item != 0 && e.getMouseDownX() >= pos.getX())
  45341. {
  45342. const String dragDescription (item->getDragSourceDescription());
  45343. if (dragDescription.isNotEmpty())
  45344. {
  45345. DragAndDropContainer* const dragContainer
  45346. = DragAndDropContainer::findParentDragContainerFor (this);
  45347. if (dragContainer != 0)
  45348. {
  45349. pos.setSize (pos.getWidth(), item->itemHeight);
  45350. Image dragImage (Component::createComponentSnapshot (pos, true));
  45351. dragImage.multiplyAllAlphas (0.6f);
  45352. Point<int> imageOffset (pos.getPosition() - e.getPosition());
  45353. dragContainer->startDragging (dragDescription, &owner, dragImage, true, &imageOffset);
  45354. }
  45355. else
  45356. {
  45357. // to be able to do a drag-and-drop operation, the treeview needs to
  45358. // be inside a component which is also a DragAndDropContainer.
  45359. jassertfalse;
  45360. }
  45361. }
  45362. }
  45363. }
  45364. }
  45365. void mouseMove (const MouseEvent& e)
  45366. {
  45367. updateButtonUnderMouse (e);
  45368. }
  45369. void mouseExit (const MouseEvent& e)
  45370. {
  45371. updateButtonUnderMouse (e);
  45372. }
  45373. void paint (Graphics& g)
  45374. {
  45375. if (owner.rootItem != 0)
  45376. {
  45377. owner.handleAsyncUpdate();
  45378. if (! owner.rootItemVisible)
  45379. g.setOrigin (0, -owner.rootItem->itemHeight);
  45380. owner.rootItem->paintRecursively (g, getWidth());
  45381. }
  45382. }
  45383. TreeViewItem* findItemAt (int y, Rectangle<int>& itemPosition) const
  45384. {
  45385. if (owner.rootItem != 0)
  45386. {
  45387. owner.handleAsyncUpdate();
  45388. if (! owner.rootItemVisible)
  45389. y += owner.rootItem->itemHeight;
  45390. TreeViewItem* const ti = owner.rootItem->findItemRecursively (y);
  45391. if (ti != 0)
  45392. itemPosition = ti->getItemPosition (false);
  45393. return ti;
  45394. }
  45395. return 0;
  45396. }
  45397. void updateComponents()
  45398. {
  45399. const int visibleTop = -getY();
  45400. const int visibleBottom = visibleTop + getParentHeight();
  45401. {
  45402. for (int i = items.size(); --i >= 0;)
  45403. items.getUnchecked(i)->shouldKeep = false;
  45404. }
  45405. {
  45406. TreeViewItem* item = owner.rootItem;
  45407. int y = (item != 0 && ! owner.rootItemVisible) ? -item->itemHeight : 0;
  45408. while (item != 0 && y < visibleBottom)
  45409. {
  45410. y += item->itemHeight;
  45411. if (y >= visibleTop)
  45412. {
  45413. RowItem* const ri = findItem (item->uid);
  45414. if (ri != 0)
  45415. {
  45416. ri->shouldKeep = true;
  45417. }
  45418. else
  45419. {
  45420. Component* const comp = item->createItemComponent();
  45421. if (comp != 0)
  45422. {
  45423. items.add (new RowItem (item, comp, item->uid));
  45424. addAndMakeVisible (comp);
  45425. }
  45426. }
  45427. }
  45428. item = item->getNextVisibleItem (true);
  45429. }
  45430. }
  45431. for (int i = items.size(); --i >= 0;)
  45432. {
  45433. RowItem* const ri = items.getUnchecked(i);
  45434. bool keep = false;
  45435. if (isParentOf (ri->component))
  45436. {
  45437. if (ri->shouldKeep)
  45438. {
  45439. Rectangle<int> pos (ri->item->getItemPosition (false));
  45440. pos.setSize (pos.getWidth(), ri->item->itemHeight);
  45441. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  45442. {
  45443. keep = true;
  45444. ri->component->setBounds (pos);
  45445. }
  45446. }
  45447. if ((! keep) && isMouseDraggingInChildCompOf (ri->component))
  45448. {
  45449. keep = true;
  45450. ri->component->setSize (0, 0);
  45451. }
  45452. }
  45453. if (! keep)
  45454. items.remove (i);
  45455. }
  45456. }
  45457. void updateButtonUnderMouse (const MouseEvent& e)
  45458. {
  45459. TreeViewItem* newItem = 0;
  45460. if (owner.openCloseButtonsVisible)
  45461. {
  45462. Rectangle<int> pos;
  45463. TreeViewItem* item = findItemAt (e.y, pos);
  45464. if (item != 0 && e.x < pos.getX() && e.x >= pos.getX() - owner.getIndentSize())
  45465. {
  45466. newItem = item;
  45467. if (! newItem->mightContainSubItems())
  45468. newItem = 0;
  45469. }
  45470. }
  45471. if (buttonUnderMouse != newItem)
  45472. {
  45473. if (buttonUnderMouse != 0 && containsItem (buttonUnderMouse))
  45474. {
  45475. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45476. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45477. }
  45478. buttonUnderMouse = newItem;
  45479. if (buttonUnderMouse != 0)
  45480. {
  45481. const Rectangle<int> r (buttonUnderMouse->getItemPosition (false));
  45482. repaint (0, r.getY(), r.getX(), buttonUnderMouse->getItemHeight());
  45483. }
  45484. }
  45485. }
  45486. bool isMouseOverButton (TreeViewItem* const item) const throw()
  45487. {
  45488. return item == buttonUnderMouse;
  45489. }
  45490. void resized()
  45491. {
  45492. owner.itemsChanged();
  45493. }
  45494. const String getTooltip()
  45495. {
  45496. Rectangle<int> pos;
  45497. TreeViewItem* const item = findItemAt (getMouseXYRelative().getY(), pos);
  45498. if (item != 0)
  45499. return item->getTooltip();
  45500. return owner.getTooltip();
  45501. }
  45502. juce_UseDebuggingNewOperator
  45503. private:
  45504. TreeView& owner;
  45505. struct RowItem
  45506. {
  45507. RowItem (TreeViewItem* const item_, Component* const component_, const int itemUID)
  45508. : component (component_), item (item_), uid (itemUID), shouldKeep (true)
  45509. {
  45510. }
  45511. ~RowItem()
  45512. {
  45513. component.deleteAndZero();
  45514. }
  45515. Component::SafePointer<Component> component;
  45516. TreeViewItem* item;
  45517. int uid;
  45518. bool shouldKeep;
  45519. };
  45520. OwnedArray <RowItem> items;
  45521. TreeViewItem* buttonUnderMouse;
  45522. bool isDragging, needSelectionOnMouseUp;
  45523. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  45524. {
  45525. TreeViewItem* firstSelected = 0;
  45526. if (modifiers.isShiftDown() && ((firstSelected = owner.getSelectedItem (0)) != 0))
  45527. {
  45528. TreeViewItem* const lastSelected = owner.getSelectedItem (owner.getNumSelectedItems() - 1);
  45529. jassert (lastSelected != 0);
  45530. int rowStart = firstSelected->getRowNumberInTree();
  45531. int rowEnd = lastSelected->getRowNumberInTree();
  45532. if (rowStart > rowEnd)
  45533. swapVariables (rowStart, rowEnd);
  45534. int ourRow = item->getRowNumberInTree();
  45535. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  45536. if (ourRow > otherEnd)
  45537. swapVariables (ourRow, otherEnd);
  45538. for (int i = ourRow; i <= otherEnd; ++i)
  45539. owner.getItemOnRow (i)->setSelected (true, false);
  45540. }
  45541. else
  45542. {
  45543. const bool cmd = modifiers.isCommandDown();
  45544. item->setSelected ((! cmd) || ! item->isSelected(), ! cmd);
  45545. }
  45546. }
  45547. bool containsItem (TreeViewItem* const item) const throw()
  45548. {
  45549. for (int i = items.size(); --i >= 0;)
  45550. if (items.getUnchecked(i)->item == item)
  45551. return true;
  45552. return false;
  45553. }
  45554. RowItem* findItem (const int uid) const throw()
  45555. {
  45556. for (int i = items.size(); --i >= 0;)
  45557. {
  45558. RowItem* const ri = items.getUnchecked(i);
  45559. if (ri->uid == uid)
  45560. return ri;
  45561. }
  45562. return 0;
  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. void setTargetPosition (TreeViewItem* const item, int insertIndex, const int x, const int y, const int width) throw()
  45946. {
  45947. lastItem = item;
  45948. lastIndex = insertIndex;
  45949. const int offset = getHeight() / 2;
  45950. setBounds (x - offset, y - offset, width - (x - offset), getHeight());
  45951. }
  45952. void paint (Graphics& g)
  45953. {
  45954. Path p;
  45955. const float h = (float) getHeight();
  45956. p.addEllipse (2.0f, 2.0f, h - 4.0f, h - 4.0f);
  45957. p.startNewSubPath (h - 2.0f, h / 2.0f);
  45958. p.lineTo ((float) getWidth(), h / 2.0f);
  45959. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45960. g.strokePath (p, PathStrokeType (2.0f));
  45961. }
  45962. TreeViewItem* lastItem;
  45963. int lastIndex;
  45964. private:
  45965. InsertPointHighlight (const InsertPointHighlight&);
  45966. InsertPointHighlight& operator= (const InsertPointHighlight&);
  45967. };
  45968. class TreeView::TargetGroupHighlight : public Component
  45969. {
  45970. public:
  45971. TargetGroupHighlight()
  45972. {
  45973. setAlwaysOnTop (true);
  45974. setInterceptsMouseClicks (false, false);
  45975. }
  45976. void setTargetPosition (TreeViewItem* const item) throw()
  45977. {
  45978. Rectangle<int> r (item->getItemPosition (true));
  45979. r.setHeight (item->getItemHeight());
  45980. setBounds (r);
  45981. }
  45982. void paint (Graphics& g)
  45983. {
  45984. g.setColour (findColour (TreeView::dragAndDropIndicatorColourId, true));
  45985. g.drawRoundedRectangle (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 3.0f, 2.0f);
  45986. }
  45987. private:
  45988. TargetGroupHighlight (const TargetGroupHighlight&);
  45989. TargetGroupHighlight& operator= (const TargetGroupHighlight&);
  45990. };
  45991. void TreeView::showDragHighlight (TreeViewItem* item, int insertIndex, int x, int y) throw()
  45992. {
  45993. beginDragAutoRepeat (100);
  45994. if (dragInsertPointHighlight == 0)
  45995. {
  45996. addAndMakeVisible (dragInsertPointHighlight = new InsertPointHighlight());
  45997. addAndMakeVisible (dragTargetGroupHighlight = new TargetGroupHighlight());
  45998. }
  45999. dragInsertPointHighlight->setTargetPosition (item, insertIndex, x, y, viewport->getViewWidth());
  46000. dragTargetGroupHighlight->setTargetPosition (item);
  46001. }
  46002. void TreeView::hideDragHighlight() throw()
  46003. {
  46004. dragInsertPointHighlight = 0;
  46005. dragTargetGroupHighlight = 0;
  46006. }
  46007. TreeViewItem* TreeView::getInsertPosition (int& x, int& y, int& insertIndex,
  46008. const StringArray& files, const String& sourceDescription,
  46009. Component* sourceComponent) const throw()
  46010. {
  46011. insertIndex = 0;
  46012. TreeViewItem* item = getItemAt (y);
  46013. if (item == 0)
  46014. return 0;
  46015. Rectangle<int> itemPos (item->getItemPosition (true));
  46016. insertIndex = item->getIndexInParent();
  46017. const int oldY = y;
  46018. y = itemPos.getY();
  46019. if (item->getNumSubItems() == 0 || ! item->isOpen())
  46020. {
  46021. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46022. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46023. {
  46024. // Check if we're trying to drag into an empty group item..
  46025. if (oldY > itemPos.getY() + itemPos.getHeight() / 4
  46026. && oldY < itemPos.getBottom() - itemPos.getHeight() / 4)
  46027. {
  46028. insertIndex = 0;
  46029. x = itemPos.getX() + getIndentSize();
  46030. y = itemPos.getBottom();
  46031. return item;
  46032. }
  46033. }
  46034. }
  46035. if (oldY > itemPos.getCentreY())
  46036. {
  46037. y += item->getItemHeight();
  46038. while (item->isLastOfSiblings() && item->parentItem != 0
  46039. && item->parentItem->parentItem != 0)
  46040. {
  46041. if (x > itemPos.getX())
  46042. break;
  46043. item = item->parentItem;
  46044. itemPos = item->getItemPosition (true);
  46045. insertIndex = item->getIndexInParent();
  46046. }
  46047. ++insertIndex;
  46048. }
  46049. x = itemPos.getX();
  46050. return item->parentItem;
  46051. }
  46052. void TreeView::handleDrag (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46053. {
  46054. const bool scrolled = viewport->autoScroll (x, y, 20, 10);
  46055. int insertIndex;
  46056. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46057. if (item != 0)
  46058. {
  46059. if (scrolled || dragInsertPointHighlight == 0
  46060. || dragInsertPointHighlight->lastItem != item
  46061. || dragInsertPointHighlight->lastIndex != insertIndex)
  46062. {
  46063. if (files.size() > 0 ? item->isInterestedInFileDrag (files)
  46064. : item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46065. showDragHighlight (item, insertIndex, x, y);
  46066. else
  46067. hideDragHighlight();
  46068. }
  46069. }
  46070. else
  46071. {
  46072. hideDragHighlight();
  46073. }
  46074. }
  46075. void TreeView::handleDrop (const StringArray& files, const String& sourceDescription, Component* sourceComponent, int x, int y)
  46076. {
  46077. hideDragHighlight();
  46078. int insertIndex;
  46079. TreeViewItem* const item = getInsertPosition (x, y, insertIndex, files, sourceDescription, sourceComponent);
  46080. if (item != 0)
  46081. {
  46082. if (files.size() > 0)
  46083. {
  46084. if (item->isInterestedInFileDrag (files))
  46085. item->filesDropped (files, insertIndex);
  46086. }
  46087. else
  46088. {
  46089. if (item->isInterestedInDragSource (sourceDescription, sourceComponent))
  46090. item->itemDropped (sourceDescription, sourceComponent, insertIndex);
  46091. }
  46092. }
  46093. }
  46094. bool TreeView::isInterestedInFileDrag (const StringArray&)
  46095. {
  46096. return true;
  46097. }
  46098. void TreeView::fileDragEnter (const StringArray& files, int x, int y)
  46099. {
  46100. fileDragMove (files, x, y);
  46101. }
  46102. void TreeView::fileDragMove (const StringArray& files, int x, int y)
  46103. {
  46104. handleDrag (files, String::empty, 0, x, y);
  46105. }
  46106. void TreeView::fileDragExit (const StringArray&)
  46107. {
  46108. hideDragHighlight();
  46109. }
  46110. void TreeView::filesDropped (const StringArray& files, int x, int y)
  46111. {
  46112. handleDrop (files, String::empty, 0, x, y);
  46113. }
  46114. bool TreeView::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46115. {
  46116. return true;
  46117. }
  46118. void TreeView::itemDragEnter (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46119. {
  46120. itemDragMove (sourceDescription, sourceComponent, x, y);
  46121. }
  46122. void TreeView::itemDragMove (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46123. {
  46124. handleDrag (StringArray(), sourceDescription, sourceComponent, x, y);
  46125. }
  46126. void TreeView::itemDragExit (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46127. {
  46128. hideDragHighlight();
  46129. }
  46130. void TreeView::itemDropped (const String& sourceDescription, Component* sourceComponent, int x, int y)
  46131. {
  46132. handleDrop (StringArray(), sourceDescription, sourceComponent, x, y);
  46133. }
  46134. enum TreeViewOpenness
  46135. {
  46136. opennessDefault = 0,
  46137. opennessClosed = 1,
  46138. opennessOpen = 2
  46139. };
  46140. TreeViewItem::TreeViewItem()
  46141. : ownerView (0),
  46142. parentItem (0),
  46143. y (0),
  46144. itemHeight (0),
  46145. totalHeight (0),
  46146. selected (false),
  46147. redrawNeeded (true),
  46148. drawLinesInside (true),
  46149. drawsInLeftMargin (false),
  46150. openness (opennessDefault)
  46151. {
  46152. static int nextUID = 0;
  46153. uid = nextUID++;
  46154. }
  46155. TreeViewItem::~TreeViewItem()
  46156. {
  46157. }
  46158. const String TreeViewItem::getUniqueName() const
  46159. {
  46160. return String::empty;
  46161. }
  46162. void TreeViewItem::itemOpennessChanged (bool)
  46163. {
  46164. }
  46165. int TreeViewItem::getNumSubItems() const throw()
  46166. {
  46167. return subItems.size();
  46168. }
  46169. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  46170. {
  46171. return subItems [index];
  46172. }
  46173. void TreeViewItem::clearSubItems()
  46174. {
  46175. if (subItems.size() > 0)
  46176. {
  46177. if (ownerView != 0)
  46178. {
  46179. const ScopedLock sl (ownerView->nodeAlterationLock);
  46180. subItems.clear();
  46181. treeHasChanged();
  46182. }
  46183. else
  46184. {
  46185. subItems.clear();
  46186. }
  46187. }
  46188. }
  46189. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  46190. {
  46191. if (newItem != 0)
  46192. {
  46193. newItem->parentItem = this;
  46194. newItem->setOwnerView (ownerView);
  46195. newItem->y = 0;
  46196. newItem->itemHeight = newItem->getItemHeight();
  46197. newItem->totalHeight = 0;
  46198. newItem->itemWidth = newItem->getItemWidth();
  46199. newItem->totalWidth = 0;
  46200. if (ownerView != 0)
  46201. {
  46202. const ScopedLock sl (ownerView->nodeAlterationLock);
  46203. subItems.insert (insertPosition, newItem);
  46204. treeHasChanged();
  46205. if (newItem->isOpen())
  46206. newItem->itemOpennessChanged (true);
  46207. }
  46208. else
  46209. {
  46210. subItems.insert (insertPosition, newItem);
  46211. if (newItem->isOpen())
  46212. newItem->itemOpennessChanged (true);
  46213. }
  46214. }
  46215. }
  46216. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  46217. {
  46218. if (ownerView != 0)
  46219. {
  46220. const ScopedLock sl (ownerView->nodeAlterationLock);
  46221. if (((unsigned int) index) < (unsigned int) subItems.size())
  46222. {
  46223. subItems.remove (index, deleteItem);
  46224. treeHasChanged();
  46225. }
  46226. }
  46227. else
  46228. {
  46229. subItems.remove (index, deleteItem);
  46230. }
  46231. }
  46232. bool TreeViewItem::isOpen() const throw()
  46233. {
  46234. if (openness == opennessDefault)
  46235. return ownerView != 0 && ownerView->defaultOpenness;
  46236. else
  46237. return openness == opennessOpen;
  46238. }
  46239. void TreeViewItem::setOpen (const bool shouldBeOpen)
  46240. {
  46241. if (isOpen() != shouldBeOpen)
  46242. {
  46243. openness = shouldBeOpen ? opennessOpen
  46244. : opennessClosed;
  46245. treeHasChanged();
  46246. itemOpennessChanged (isOpen());
  46247. }
  46248. }
  46249. bool TreeViewItem::isSelected() const throw()
  46250. {
  46251. return selected;
  46252. }
  46253. void TreeViewItem::deselectAllRecursively()
  46254. {
  46255. setSelected (false, false);
  46256. for (int i = 0; i < subItems.size(); ++i)
  46257. subItems.getUnchecked(i)->deselectAllRecursively();
  46258. }
  46259. void TreeViewItem::setSelected (const bool shouldBeSelected,
  46260. const bool deselectOtherItemsFirst)
  46261. {
  46262. if (shouldBeSelected && ! canBeSelected())
  46263. return;
  46264. if (deselectOtherItemsFirst)
  46265. getTopLevelItem()->deselectAllRecursively();
  46266. if (shouldBeSelected != selected)
  46267. {
  46268. selected = shouldBeSelected;
  46269. if (ownerView != 0)
  46270. ownerView->repaint();
  46271. itemSelectionChanged (shouldBeSelected);
  46272. }
  46273. }
  46274. void TreeViewItem::paintItem (Graphics&, int, int)
  46275. {
  46276. }
  46277. void TreeViewItem::paintOpenCloseButton (Graphics& g, int width, int height, bool isMouseOver)
  46278. {
  46279. ownerView->getLookAndFeel()
  46280. .drawTreeviewPlusMinusBox (g, 0, 0, width, height, ! isOpen(), isMouseOver);
  46281. }
  46282. void TreeViewItem::itemClicked (const MouseEvent&)
  46283. {
  46284. }
  46285. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  46286. {
  46287. if (mightContainSubItems())
  46288. setOpen (! isOpen());
  46289. }
  46290. void TreeViewItem::itemSelectionChanged (bool)
  46291. {
  46292. }
  46293. const String TreeViewItem::getTooltip()
  46294. {
  46295. return String::empty;
  46296. }
  46297. const String TreeViewItem::getDragSourceDescription()
  46298. {
  46299. return String::empty;
  46300. }
  46301. bool TreeViewItem::isInterestedInFileDrag (const StringArray&)
  46302. {
  46303. return false;
  46304. }
  46305. void TreeViewItem::filesDropped (const StringArray& /*files*/, int /*insertIndex*/)
  46306. {
  46307. }
  46308. bool TreeViewItem::isInterestedInDragSource (const String& /*sourceDescription*/, Component* /*sourceComponent*/)
  46309. {
  46310. return false;
  46311. }
  46312. void TreeViewItem::itemDropped (const String& /*sourceDescription*/, Component* /*sourceComponent*/, int /*insertIndex*/)
  46313. {
  46314. }
  46315. const Rectangle<int> TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  46316. {
  46317. const int indentX = getIndentX();
  46318. int width = itemWidth;
  46319. if (ownerView != 0 && width < 0)
  46320. width = ownerView->viewport->getViewWidth() - indentX;
  46321. Rectangle<int> r (indentX, y, jmax (0, width), totalHeight);
  46322. if (relativeToTreeViewTopLeft)
  46323. r -= ownerView->viewport->getViewPosition();
  46324. return r;
  46325. }
  46326. void TreeViewItem::treeHasChanged() const throw()
  46327. {
  46328. if (ownerView != 0)
  46329. ownerView->itemsChanged();
  46330. }
  46331. void TreeViewItem::repaintItem() const
  46332. {
  46333. if (ownerView != 0 && areAllParentsOpen())
  46334. {
  46335. Rectangle<int> r (getItemPosition (true));
  46336. r.setLeft (0);
  46337. ownerView->viewport->repaint (r);
  46338. }
  46339. }
  46340. bool TreeViewItem::areAllParentsOpen() const throw()
  46341. {
  46342. return parentItem == 0
  46343. || (parentItem->isOpen() && parentItem->areAllParentsOpen());
  46344. }
  46345. void TreeViewItem::updatePositions (int newY)
  46346. {
  46347. y = newY;
  46348. itemHeight = getItemHeight();
  46349. totalHeight = itemHeight;
  46350. itemWidth = getItemWidth();
  46351. totalWidth = jmax (itemWidth, 0) + getIndentX();
  46352. if (isOpen())
  46353. {
  46354. newY += totalHeight;
  46355. for (int i = 0; i < subItems.size(); ++i)
  46356. {
  46357. TreeViewItem* const ti = subItems.getUnchecked(i);
  46358. ti->updatePositions (newY);
  46359. newY += ti->totalHeight;
  46360. totalHeight += ti->totalHeight;
  46361. totalWidth = jmax (totalWidth, ti->totalWidth);
  46362. }
  46363. }
  46364. }
  46365. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  46366. {
  46367. TreeViewItem* result = this;
  46368. TreeViewItem* item = this;
  46369. while (item->parentItem != 0)
  46370. {
  46371. item = item->parentItem;
  46372. if (! item->isOpen())
  46373. result = item;
  46374. }
  46375. return result;
  46376. }
  46377. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  46378. {
  46379. ownerView = newOwner;
  46380. for (int i = subItems.size(); --i >= 0;)
  46381. subItems.getUnchecked(i)->setOwnerView (newOwner);
  46382. }
  46383. int TreeViewItem::getIndentX() const throw()
  46384. {
  46385. const int indentWidth = ownerView->getIndentSize();
  46386. int x = ownerView->rootItemVisible ? indentWidth : 0;
  46387. if (! ownerView->openCloseButtonsVisible)
  46388. x -= indentWidth;
  46389. TreeViewItem* p = parentItem;
  46390. while (p != 0)
  46391. {
  46392. x += indentWidth;
  46393. p = p->parentItem;
  46394. }
  46395. return x;
  46396. }
  46397. void TreeViewItem::setDrawsInLeftMargin (bool canDrawInLeftMargin) throw()
  46398. {
  46399. drawsInLeftMargin = canDrawInLeftMargin;
  46400. }
  46401. void TreeViewItem::paintRecursively (Graphics& g, int width)
  46402. {
  46403. jassert (ownerView != 0);
  46404. if (ownerView == 0)
  46405. return;
  46406. const int indent = getIndentX();
  46407. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  46408. {
  46409. g.saveState();
  46410. g.setOrigin (indent, 0);
  46411. if (g.reduceClipRegion (drawsInLeftMargin ? -indent : 0, 0,
  46412. drawsInLeftMargin ? itemW + indent : itemW, itemHeight))
  46413. paintItem (g, itemW, itemHeight);
  46414. g.restoreState();
  46415. }
  46416. g.setColour (ownerView->findColour (TreeView::linesColourId));
  46417. const float halfH = itemHeight * 0.5f;
  46418. int depth = 0;
  46419. TreeViewItem* p = parentItem;
  46420. while (p != 0)
  46421. {
  46422. ++depth;
  46423. p = p->parentItem;
  46424. }
  46425. if (! ownerView->rootItemVisible)
  46426. --depth;
  46427. const int indentWidth = ownerView->getIndentSize();
  46428. if (depth >= 0 && ownerView->openCloseButtonsVisible)
  46429. {
  46430. float x = (depth + 0.5f) * indentWidth;
  46431. if (depth >= 0)
  46432. {
  46433. if (parentItem != 0 && parentItem->drawLinesInside)
  46434. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  46435. if ((parentItem != 0 && parentItem->drawLinesInside)
  46436. || (parentItem == 0 && drawLinesInside))
  46437. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  46438. }
  46439. p = parentItem;
  46440. int d = depth;
  46441. while (p != 0 && --d >= 0)
  46442. {
  46443. x -= (float) indentWidth;
  46444. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  46445. && ! p->isLastOfSiblings())
  46446. {
  46447. g.drawLine (x, 0, x, (float) itemHeight);
  46448. }
  46449. p = p->parentItem;
  46450. }
  46451. if (mightContainSubItems())
  46452. {
  46453. g.saveState();
  46454. g.setOrigin (depth * indentWidth, 0);
  46455. g.reduceClipRegion (0, 0, indentWidth, itemHeight);
  46456. paintOpenCloseButton (g, indentWidth, itemHeight,
  46457. static_cast <TreeViewContentComponent*> (ownerView->viewport->getViewedComponent())
  46458. ->isMouseOverButton (this));
  46459. g.restoreState();
  46460. }
  46461. }
  46462. if (isOpen())
  46463. {
  46464. const Rectangle<int> clip (g.getClipBounds());
  46465. for (int i = 0; i < subItems.size(); ++i)
  46466. {
  46467. TreeViewItem* const ti = subItems.getUnchecked(i);
  46468. const int relY = ti->y - y;
  46469. if (relY >= clip.getBottom())
  46470. break;
  46471. if (relY + ti->totalHeight >= clip.getY())
  46472. {
  46473. g.saveState();
  46474. g.setOrigin (0, relY);
  46475. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  46476. ti->paintRecursively (g, width);
  46477. g.restoreState();
  46478. }
  46479. }
  46480. }
  46481. }
  46482. bool TreeViewItem::isLastOfSiblings() const throw()
  46483. {
  46484. return parentItem == 0
  46485. || parentItem->subItems.getLast() == this;
  46486. }
  46487. int TreeViewItem::getIndexInParent() const throw()
  46488. {
  46489. return parentItem == 0 ? 0
  46490. : parentItem->subItems.indexOf (this);
  46491. }
  46492. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  46493. {
  46494. return parentItem == 0 ? this
  46495. : parentItem->getTopLevelItem();
  46496. }
  46497. int TreeViewItem::getNumRows() const throw()
  46498. {
  46499. int num = 1;
  46500. if (isOpen())
  46501. {
  46502. for (int i = subItems.size(); --i >= 0;)
  46503. num += subItems.getUnchecked(i)->getNumRows();
  46504. }
  46505. return num;
  46506. }
  46507. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  46508. {
  46509. if (index == 0)
  46510. return this;
  46511. if (index > 0 && isOpen())
  46512. {
  46513. --index;
  46514. for (int i = 0; i < subItems.size(); ++i)
  46515. {
  46516. TreeViewItem* const item = subItems.getUnchecked(i);
  46517. if (index == 0)
  46518. return item;
  46519. const int numRows = item->getNumRows();
  46520. if (numRows > index)
  46521. return item->getItemOnRow (index);
  46522. index -= numRows;
  46523. }
  46524. }
  46525. return 0;
  46526. }
  46527. TreeViewItem* TreeViewItem::findItemRecursively (int targetY) throw()
  46528. {
  46529. if (((unsigned int) targetY) < (unsigned int) totalHeight)
  46530. {
  46531. const int h = itemHeight;
  46532. if (targetY < h)
  46533. return this;
  46534. if (isOpen())
  46535. {
  46536. targetY -= h;
  46537. for (int i = 0; i < subItems.size(); ++i)
  46538. {
  46539. TreeViewItem* const ti = subItems.getUnchecked(i);
  46540. if (targetY < ti->totalHeight)
  46541. return ti->findItemRecursively (targetY);
  46542. targetY -= ti->totalHeight;
  46543. }
  46544. }
  46545. }
  46546. return 0;
  46547. }
  46548. int TreeViewItem::countSelectedItemsRecursively() const throw()
  46549. {
  46550. int total = isSelected() ? 1 : 0;
  46551. for (int i = subItems.size(); --i >= 0;)
  46552. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  46553. return total;
  46554. }
  46555. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  46556. {
  46557. if (isSelected())
  46558. {
  46559. if (index == 0)
  46560. return this;
  46561. --index;
  46562. }
  46563. if (index >= 0)
  46564. {
  46565. for (int i = 0; i < subItems.size(); ++i)
  46566. {
  46567. TreeViewItem* const item = subItems.getUnchecked(i);
  46568. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  46569. if (found != 0)
  46570. return found;
  46571. index -= item->countSelectedItemsRecursively();
  46572. }
  46573. }
  46574. return 0;
  46575. }
  46576. int TreeViewItem::getRowNumberInTree() const throw()
  46577. {
  46578. if (parentItem != 0 && ownerView != 0)
  46579. {
  46580. int n = 1 + parentItem->getRowNumberInTree();
  46581. int ourIndex = parentItem->subItems.indexOf (this);
  46582. jassert (ourIndex >= 0);
  46583. while (--ourIndex >= 0)
  46584. n += parentItem->subItems [ourIndex]->getNumRows();
  46585. if (parentItem->parentItem == 0
  46586. && ! ownerView->rootItemVisible)
  46587. --n;
  46588. return n;
  46589. }
  46590. else
  46591. {
  46592. return 0;
  46593. }
  46594. }
  46595. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  46596. {
  46597. drawLinesInside = drawLines;
  46598. }
  46599. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  46600. {
  46601. if (recurse && isOpen() && subItems.size() > 0)
  46602. return subItems [0];
  46603. if (parentItem != 0)
  46604. {
  46605. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  46606. if (nextIndex >= parentItem->subItems.size())
  46607. return parentItem->getNextVisibleItem (false);
  46608. return parentItem->subItems [nextIndex];
  46609. }
  46610. return 0;
  46611. }
  46612. const String TreeViewItem::getItemIdentifierString() const
  46613. {
  46614. String s;
  46615. if (parentItem != 0)
  46616. s = parentItem->getItemIdentifierString();
  46617. return s + "/" + getUniqueName().replaceCharacter ('/', '\\');
  46618. }
  46619. TreeViewItem* TreeViewItem::findItemFromIdentifierString (const String& identifierString)
  46620. {
  46621. const String thisId (getUniqueName());
  46622. if (thisId == identifierString)
  46623. return this;
  46624. if (identifierString.startsWith (thisId + "/"))
  46625. {
  46626. const String remainingPath (identifierString.substring (thisId.length() + 1));
  46627. bool wasOpen = isOpen();
  46628. setOpen (true);
  46629. for (int i = subItems.size(); --i >= 0;)
  46630. {
  46631. TreeViewItem* item = subItems.getUnchecked(i)->findItemFromIdentifierString (remainingPath);
  46632. if (item != 0)
  46633. return item;
  46634. }
  46635. setOpen (wasOpen);
  46636. }
  46637. return 0;
  46638. }
  46639. void TreeViewItem::restoreOpennessState (const XmlElement& e) throw()
  46640. {
  46641. if (e.hasTagName ("CLOSED"))
  46642. {
  46643. setOpen (false);
  46644. }
  46645. else if (e.hasTagName ("OPEN"))
  46646. {
  46647. setOpen (true);
  46648. forEachXmlChildElement (e, n)
  46649. {
  46650. const String id (n->getStringAttribute ("id"));
  46651. for (int i = 0; i < subItems.size(); ++i)
  46652. {
  46653. TreeViewItem* const ti = subItems.getUnchecked(i);
  46654. if (ti->getUniqueName() == id)
  46655. {
  46656. ti->restoreOpennessState (*n);
  46657. break;
  46658. }
  46659. }
  46660. }
  46661. }
  46662. }
  46663. XmlElement* TreeViewItem::getOpennessState() const throw()
  46664. {
  46665. const String name (getUniqueName());
  46666. if (name.isNotEmpty())
  46667. {
  46668. XmlElement* e;
  46669. if (isOpen())
  46670. {
  46671. e = new XmlElement ("OPEN");
  46672. for (int i = 0; i < subItems.size(); ++i)
  46673. e->addChildElement (subItems.getUnchecked(i)->getOpennessState());
  46674. }
  46675. else
  46676. {
  46677. e = new XmlElement ("CLOSED");
  46678. }
  46679. e->setAttribute ("id", name);
  46680. return e;
  46681. }
  46682. else
  46683. {
  46684. // trying to save the openness for an element that has no name - this won't
  46685. // work because it needs the names to identify what to open.
  46686. jassertfalse;
  46687. }
  46688. return 0;
  46689. }
  46690. END_JUCE_NAMESPACE
  46691. /*** End of inlined file: juce_TreeView.cpp ***/
  46692. /*** Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46693. BEGIN_JUCE_NAMESPACE
  46694. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  46695. : fileList (listToShow)
  46696. {
  46697. }
  46698. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  46699. {
  46700. }
  46701. FileBrowserListener::~FileBrowserListener()
  46702. {
  46703. }
  46704. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener)
  46705. {
  46706. listeners.add (listener);
  46707. }
  46708. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener)
  46709. {
  46710. listeners.remove (listener);
  46711. }
  46712. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  46713. {
  46714. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46715. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  46716. }
  46717. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  46718. {
  46719. if (fileList.getDirectory().exists())
  46720. {
  46721. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46722. listeners.callChecked (checker, &FileBrowserListener::fileClicked, file, e);
  46723. }
  46724. }
  46725. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  46726. {
  46727. if (fileList.getDirectory().exists())
  46728. {
  46729. Component::BailOutChecker checker (dynamic_cast <Component*> (this));
  46730. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, file);
  46731. }
  46732. }
  46733. END_JUCE_NAMESPACE
  46734. /*** End of inlined file: juce_DirectoryContentsDisplayComponent.cpp ***/
  46735. /*** Start of inlined file: juce_DirectoryContentsList.cpp ***/
  46736. BEGIN_JUCE_NAMESPACE
  46737. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  46738. TimeSliceThread& thread_)
  46739. : fileFilter (fileFilter_),
  46740. thread (thread_),
  46741. fileTypeFlags (File::ignoreHiddenFiles | File::findFiles),
  46742. fileFindHandle (0),
  46743. shouldStop (true)
  46744. {
  46745. }
  46746. DirectoryContentsList::~DirectoryContentsList()
  46747. {
  46748. clear();
  46749. }
  46750. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  46751. {
  46752. setTypeFlags (shouldIgnoreHiddenFiles ? (fileTypeFlags | File::ignoreHiddenFiles)
  46753. : (fileTypeFlags & ~File::ignoreHiddenFiles));
  46754. }
  46755. bool DirectoryContentsList::ignoresHiddenFiles() const
  46756. {
  46757. return (fileTypeFlags & File::ignoreHiddenFiles) != 0;
  46758. }
  46759. const File& DirectoryContentsList::getDirectory() const
  46760. {
  46761. return root;
  46762. }
  46763. void DirectoryContentsList::setDirectory (const File& directory,
  46764. const bool includeDirectories,
  46765. const bool includeFiles)
  46766. {
  46767. jassert (includeDirectories || includeFiles); // you have to speciify at least one of these!
  46768. if (directory != root)
  46769. {
  46770. clear();
  46771. root = directory;
  46772. // (this forces a refresh when setTypeFlags() is called, rather than triggering two refreshes)
  46773. fileTypeFlags &= ~(File::findDirectories | File::findFiles);
  46774. }
  46775. int newFlags = fileTypeFlags;
  46776. if (includeDirectories) newFlags |= File::findDirectories; else newFlags &= ~File::findDirectories;
  46777. if (includeFiles) newFlags |= File::findFiles; else newFlags &= ~File::findFiles;
  46778. setTypeFlags (newFlags);
  46779. }
  46780. void DirectoryContentsList::setTypeFlags (const int newFlags)
  46781. {
  46782. if (fileTypeFlags != newFlags)
  46783. {
  46784. fileTypeFlags = newFlags;
  46785. refresh();
  46786. }
  46787. }
  46788. void DirectoryContentsList::clear()
  46789. {
  46790. shouldStop = true;
  46791. thread.removeTimeSliceClient (this);
  46792. fileFindHandle = 0;
  46793. if (files.size() > 0)
  46794. {
  46795. files.clear();
  46796. changed();
  46797. }
  46798. }
  46799. void DirectoryContentsList::refresh()
  46800. {
  46801. clear();
  46802. if (root.isDirectory())
  46803. {
  46804. fileFindHandle = new DirectoryIterator (root, false, "*", fileTypeFlags);
  46805. shouldStop = false;
  46806. thread.addTimeSliceClient (this);
  46807. }
  46808. }
  46809. int DirectoryContentsList::getNumFiles() const
  46810. {
  46811. return files.size();
  46812. }
  46813. bool DirectoryContentsList::getFileInfo (const int index,
  46814. FileInfo& result) const
  46815. {
  46816. const ScopedLock sl (fileListLock);
  46817. const FileInfo* const info = files [index];
  46818. if (info != 0)
  46819. {
  46820. result = *info;
  46821. return true;
  46822. }
  46823. return false;
  46824. }
  46825. const File DirectoryContentsList::getFile (const int index) const
  46826. {
  46827. const ScopedLock sl (fileListLock);
  46828. const FileInfo* const info = files [index];
  46829. if (info != 0)
  46830. return root.getChildFile (info->filename);
  46831. return File::nonexistent;
  46832. }
  46833. bool DirectoryContentsList::isStillLoading() const
  46834. {
  46835. return fileFindHandle != 0;
  46836. }
  46837. void DirectoryContentsList::changed()
  46838. {
  46839. sendChangeMessage (this);
  46840. }
  46841. bool DirectoryContentsList::useTimeSlice()
  46842. {
  46843. const uint32 startTime = Time::getApproximateMillisecondCounter();
  46844. bool hasChanged = false;
  46845. for (int i = 100; --i >= 0;)
  46846. {
  46847. if (! checkNextFile (hasChanged))
  46848. {
  46849. if (hasChanged)
  46850. changed();
  46851. return false;
  46852. }
  46853. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  46854. break;
  46855. }
  46856. if (hasChanged)
  46857. changed();
  46858. return true;
  46859. }
  46860. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  46861. {
  46862. if (fileFindHandle != 0)
  46863. {
  46864. bool fileFoundIsDir, isHidden, isReadOnly;
  46865. int64 fileSize;
  46866. Time modTime, creationTime;
  46867. if (fileFindHandle->next (&fileFoundIsDir, &isHidden, &fileSize,
  46868. &modTime, &creationTime, &isReadOnly))
  46869. {
  46870. if (addFile (fileFindHandle->getFile(), fileFoundIsDir,
  46871. fileSize, modTime, creationTime, isReadOnly))
  46872. {
  46873. hasChanged = true;
  46874. }
  46875. return true;
  46876. }
  46877. else
  46878. {
  46879. fileFindHandle = 0;
  46880. }
  46881. }
  46882. return false;
  46883. }
  46884. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  46885. const DirectoryContentsList::FileInfo* const second)
  46886. {
  46887. #if JUCE_WINDOWS
  46888. if (first->isDirectory != second->isDirectory)
  46889. return first->isDirectory ? -1 : 1;
  46890. #endif
  46891. return first->filename.compareIgnoreCase (second->filename);
  46892. }
  46893. bool DirectoryContentsList::addFile (const File& file,
  46894. const bool isDir,
  46895. const int64 fileSize,
  46896. const Time& modTime,
  46897. const Time& creationTime,
  46898. const bool isReadOnly)
  46899. {
  46900. if (fileFilter == 0
  46901. || ((! isDir) && fileFilter->isFileSuitable (file))
  46902. || (isDir && fileFilter->isDirectorySuitable (file)))
  46903. {
  46904. ScopedPointer <FileInfo> info (new FileInfo());
  46905. info->filename = file.getFileName();
  46906. info->fileSize = fileSize;
  46907. info->modificationTime = modTime;
  46908. info->creationTime = creationTime;
  46909. info->isDirectory = isDir;
  46910. info->isReadOnly = isReadOnly;
  46911. const ScopedLock sl (fileListLock);
  46912. for (int i = files.size(); --i >= 0;)
  46913. if (files.getUnchecked(i)->filename == info->filename)
  46914. return false;
  46915. files.addSorted (*this, info.release());
  46916. return true;
  46917. }
  46918. return false;
  46919. }
  46920. END_JUCE_NAMESPACE
  46921. /*** End of inlined file: juce_DirectoryContentsList.cpp ***/
  46922. /*** Start of inlined file: juce_FileBrowserComponent.cpp ***/
  46923. BEGIN_JUCE_NAMESPACE
  46924. FileBrowserComponent::FileBrowserComponent (int flags_,
  46925. const File& initialFileOrDirectory,
  46926. const FileFilter* fileFilter_,
  46927. FilePreviewComponent* previewComp_)
  46928. : FileFilter (String::empty),
  46929. fileFilter (fileFilter_),
  46930. flags (flags_),
  46931. previewComp (previewComp_),
  46932. currentPathBox ("path"),
  46933. fileLabel ("f", TRANS ("file:")),
  46934. thread ("Juce FileBrowser")
  46935. {
  46936. // You need to specify one or other of the open/save flags..
  46937. jassert ((flags & (saveMode | openMode)) != 0);
  46938. jassert ((flags & (saveMode | openMode)) != (saveMode | openMode));
  46939. // You need to specify at least one of these flags..
  46940. jassert ((flags & (canSelectFiles | canSelectDirectories)) != 0);
  46941. String filename;
  46942. if (initialFileOrDirectory == File::nonexistent)
  46943. {
  46944. currentRoot = File::getCurrentWorkingDirectory();
  46945. }
  46946. else if (initialFileOrDirectory.isDirectory())
  46947. {
  46948. currentRoot = initialFileOrDirectory;
  46949. }
  46950. else
  46951. {
  46952. chosenFiles.add (initialFileOrDirectory);
  46953. currentRoot = initialFileOrDirectory.getParentDirectory();
  46954. filename = initialFileOrDirectory.getFileName();
  46955. }
  46956. fileList = new DirectoryContentsList (this, thread);
  46957. if ((flags & useTreeView) != 0)
  46958. {
  46959. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  46960. fileListComponent = tree;
  46961. if ((flags & canSelectMultipleItems) != 0)
  46962. tree->setMultiSelectEnabled (true);
  46963. addAndMakeVisible (tree);
  46964. }
  46965. else
  46966. {
  46967. FileListComponent* const list = new FileListComponent (*fileList);
  46968. fileListComponent = list;
  46969. list->setOutlineThickness (1);
  46970. if ((flags & canSelectMultipleItems) != 0)
  46971. list->setMultipleSelectionEnabled (true);
  46972. addAndMakeVisible (list);
  46973. }
  46974. fileListComponent->addListener (this);
  46975. addAndMakeVisible (&currentPathBox);
  46976. currentPathBox.setEditableText (true);
  46977. StringArray rootNames, rootPaths;
  46978. const BigInteger separators (getRoots (rootNames, rootPaths));
  46979. for (int i = 0; i < rootNames.size(); ++i)
  46980. {
  46981. if (separators [i])
  46982. currentPathBox.addSeparator();
  46983. currentPathBox.addItem (rootNames[i], i + 1);
  46984. }
  46985. currentPathBox.addSeparator();
  46986. currentPathBox.addListener (this);
  46987. addAndMakeVisible (&filenameBox);
  46988. filenameBox.setMultiLine (false);
  46989. filenameBox.setSelectAllWhenFocused (true);
  46990. filenameBox.setText (filename, false);
  46991. filenameBox.addListener (this);
  46992. filenameBox.setReadOnly ((flags & (filenameBoxIsReadOnly | canSelectMultipleItems)) != 0);
  46993. addAndMakeVisible (&fileLabel);
  46994. fileLabel.attachToComponent (&filenameBox, true);
  46995. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  46996. goUpButton->addButtonListener (this);
  46997. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  46998. if (previewComp != 0)
  46999. addAndMakeVisible (previewComp);
  47000. setRoot (currentRoot);
  47001. thread.startThread (4);
  47002. }
  47003. FileBrowserComponent::~FileBrowserComponent()
  47004. {
  47005. fileListComponent = 0;
  47006. fileList = 0;
  47007. thread.stopThread (10000);
  47008. }
  47009. void FileBrowserComponent::addListener (FileBrowserListener* const newListener)
  47010. {
  47011. listeners.add (newListener);
  47012. }
  47013. void FileBrowserComponent::removeListener (FileBrowserListener* const listener)
  47014. {
  47015. listeners.remove (listener);
  47016. }
  47017. bool FileBrowserComponent::isSaveMode() const throw()
  47018. {
  47019. return (flags & saveMode) != 0;
  47020. }
  47021. int FileBrowserComponent::getNumSelectedFiles() const throw()
  47022. {
  47023. if (chosenFiles.size() == 0 && currentFileIsValid())
  47024. return 1;
  47025. return chosenFiles.size();
  47026. }
  47027. const File FileBrowserComponent::getSelectedFile (int index) const throw()
  47028. {
  47029. if ((flags & canSelectDirectories) != 0 && filenameBox.getText().isEmpty())
  47030. return currentRoot;
  47031. if (! filenameBox.isReadOnly())
  47032. return currentRoot.getChildFile (filenameBox.getText());
  47033. return chosenFiles[index];
  47034. }
  47035. bool FileBrowserComponent::currentFileIsValid() const
  47036. {
  47037. if (isSaveMode())
  47038. return ! getSelectedFile (0).isDirectory();
  47039. else
  47040. return getSelectedFile (0).exists();
  47041. }
  47042. const File FileBrowserComponent::getHighlightedFile() const throw()
  47043. {
  47044. return fileListComponent->getSelectedFile (0);
  47045. }
  47046. void FileBrowserComponent::deselectAllFiles()
  47047. {
  47048. fileListComponent->deselectAllFiles();
  47049. }
  47050. bool FileBrowserComponent::isFileSuitable (const File& file) const
  47051. {
  47052. return (flags & canSelectFiles) != 0 && (fileFilter == 0 || fileFilter->isFileSuitable (file));
  47053. }
  47054. bool FileBrowserComponent::isDirectorySuitable (const File&) const
  47055. {
  47056. return true;
  47057. }
  47058. bool FileBrowserComponent::isFileOrDirSuitable (const File& f) const
  47059. {
  47060. if (f.isDirectory())
  47061. return (flags & canSelectDirectories) != 0 && (fileFilter == 0 || fileFilter->isDirectorySuitable (f));
  47062. return (flags & canSelectFiles) != 0 && f.exists()
  47063. && (fileFilter == 0 || fileFilter->isFileSuitable (f));
  47064. }
  47065. const File FileBrowserComponent::getRoot() const
  47066. {
  47067. return currentRoot;
  47068. }
  47069. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  47070. {
  47071. if (currentRoot != newRootDirectory)
  47072. {
  47073. fileListComponent->scrollToTop();
  47074. String path (newRootDirectory.getFullPathName());
  47075. if (path.isEmpty())
  47076. path = File::separatorString;
  47077. StringArray rootNames, rootPaths;
  47078. getRoots (rootNames, rootPaths);
  47079. if (! rootPaths.contains (path, true))
  47080. {
  47081. bool alreadyListed = false;
  47082. for (int i = currentPathBox.getNumItems(); --i >= 0;)
  47083. {
  47084. if (currentPathBox.getItemText (i).equalsIgnoreCase (path))
  47085. {
  47086. alreadyListed = true;
  47087. break;
  47088. }
  47089. }
  47090. if (! alreadyListed)
  47091. currentPathBox.addItem (path, currentPathBox.getNumItems() + 2);
  47092. }
  47093. }
  47094. currentRoot = newRootDirectory;
  47095. fileList->setDirectory (currentRoot, true, true);
  47096. String currentRootName (currentRoot.getFullPathName());
  47097. if (currentRootName.isEmpty())
  47098. currentRootName = File::separatorString;
  47099. currentPathBox.setText (currentRootName, true);
  47100. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  47101. && currentRoot.getParentDirectory() != currentRoot);
  47102. }
  47103. void FileBrowserComponent::goUp()
  47104. {
  47105. setRoot (getRoot().getParentDirectory());
  47106. }
  47107. void FileBrowserComponent::refresh()
  47108. {
  47109. fileList->refresh();
  47110. }
  47111. const String FileBrowserComponent::getActionVerb() const
  47112. {
  47113. return isSaveMode() ? TRANS("Save") : TRANS("Open");
  47114. }
  47115. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  47116. {
  47117. return previewComp;
  47118. }
  47119. void FileBrowserComponent::resized()
  47120. {
  47121. getLookAndFeel()
  47122. .layoutFileBrowserComponent (*this, fileListComponent, previewComp,
  47123. &currentPathBox, &filenameBox, goUpButton);
  47124. }
  47125. void FileBrowserComponent::sendListenerChangeMessage()
  47126. {
  47127. Component::BailOutChecker checker (this);
  47128. if (previewComp != 0)
  47129. previewComp->selectedFileChanged (getSelectedFile (0));
  47130. // You shouldn't delete the browser when the file gets changed!
  47131. jassert (! checker.shouldBailOut());
  47132. listeners.callChecked (checker, &FileBrowserListener::selectionChanged);
  47133. }
  47134. void FileBrowserComponent::selectionChanged()
  47135. {
  47136. StringArray newFilenames;
  47137. bool resetChosenFiles = true;
  47138. for (int i = 0; i < fileListComponent->getNumSelectedFiles(); ++i)
  47139. {
  47140. const File f (fileListComponent->getSelectedFile (i));
  47141. if (isFileOrDirSuitable (f))
  47142. {
  47143. if (resetChosenFiles)
  47144. {
  47145. chosenFiles.clear();
  47146. resetChosenFiles = false;
  47147. }
  47148. chosenFiles.add (f);
  47149. newFilenames.add (f.getRelativePathFrom (getRoot()));
  47150. }
  47151. }
  47152. if (newFilenames.size() > 0)
  47153. filenameBox.setText (newFilenames.joinIntoString (", "), false);
  47154. sendListenerChangeMessage();
  47155. }
  47156. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  47157. {
  47158. Component::BailOutChecker checker (this);
  47159. listeners.callChecked (checker, &FileBrowserListener::fileClicked, f, e);
  47160. }
  47161. void FileBrowserComponent::fileDoubleClicked (const File& f)
  47162. {
  47163. if (f.isDirectory())
  47164. {
  47165. setRoot (f);
  47166. if ((flags & canSelectDirectories) != 0)
  47167. filenameBox.setText (String::empty);
  47168. }
  47169. else
  47170. {
  47171. Component::BailOutChecker checker (this);
  47172. listeners.callChecked (checker, &FileBrowserListener::fileDoubleClicked, f);
  47173. }
  47174. }
  47175. bool FileBrowserComponent::keyPressed (const KeyPress& key)
  47176. {
  47177. (void) key;
  47178. #if JUCE_LINUX || JUCE_WINDOWS
  47179. if (key.getModifiers().isCommandDown()
  47180. && (key.getKeyCode() == 'H' || key.getKeyCode() == 'h'))
  47181. {
  47182. fileList->setIgnoresHiddenFiles (! fileList->ignoresHiddenFiles());
  47183. fileList->refresh();
  47184. return true;
  47185. }
  47186. #endif
  47187. return false;
  47188. }
  47189. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  47190. {
  47191. sendListenerChangeMessage();
  47192. }
  47193. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  47194. {
  47195. if (filenameBox.getText().containsChar (File::separator))
  47196. {
  47197. const File f (currentRoot.getChildFile (filenameBox.getText()));
  47198. if (f.isDirectory())
  47199. {
  47200. setRoot (f);
  47201. chosenFiles.clear();
  47202. filenameBox.setText (String::empty);
  47203. }
  47204. else
  47205. {
  47206. setRoot (f.getParentDirectory());
  47207. chosenFiles.clear();
  47208. chosenFiles.add (f);
  47209. filenameBox.setText (f.getFileName());
  47210. }
  47211. }
  47212. else
  47213. {
  47214. fileDoubleClicked (getSelectedFile (0));
  47215. }
  47216. }
  47217. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  47218. {
  47219. }
  47220. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  47221. {
  47222. if (! isSaveMode())
  47223. selectionChanged();
  47224. }
  47225. void FileBrowserComponent::buttonClicked (Button*)
  47226. {
  47227. goUp();
  47228. }
  47229. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  47230. {
  47231. const String newText (currentPathBox.getText().trim().unquoted());
  47232. if (newText.isNotEmpty())
  47233. {
  47234. const int index = currentPathBox.getSelectedId() - 1;
  47235. StringArray rootNames, rootPaths;
  47236. getRoots (rootNames, rootPaths);
  47237. if (rootPaths [index].isNotEmpty())
  47238. {
  47239. setRoot (File (rootPaths [index]));
  47240. }
  47241. else
  47242. {
  47243. File f (newText);
  47244. for (;;)
  47245. {
  47246. if (f.isDirectory())
  47247. {
  47248. setRoot (f);
  47249. break;
  47250. }
  47251. if (f.getParentDirectory() == f)
  47252. break;
  47253. f = f.getParentDirectory();
  47254. }
  47255. }
  47256. }
  47257. }
  47258. const BigInteger FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  47259. {
  47260. BigInteger separators;
  47261. #if JUCE_WINDOWS
  47262. Array<File> roots;
  47263. File::findFileSystemRoots (roots);
  47264. rootPaths.clear();
  47265. for (int i = 0; i < roots.size(); ++i)
  47266. {
  47267. const File& drive = roots.getReference(i);
  47268. String name (drive.getFullPathName());
  47269. rootPaths.add (name);
  47270. if (drive.isOnHardDisk())
  47271. {
  47272. String volume (drive.getVolumeLabel());
  47273. if (volume.isEmpty())
  47274. volume = TRANS("Hard Drive");
  47275. name << " [" << volume << ']';
  47276. }
  47277. else if (drive.isOnCDRomDrive())
  47278. {
  47279. name << TRANS(" [CD/DVD drive]");
  47280. }
  47281. rootNames.add (name);
  47282. }
  47283. separators.setBit (rootPaths.size());
  47284. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  47285. rootNames.add ("Documents");
  47286. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47287. rootNames.add ("Desktop");
  47288. #endif
  47289. #if JUCE_MAC
  47290. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47291. rootNames.add ("Home folder");
  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. separators.setBit (rootPaths.size());
  47297. Array <File> volumes;
  47298. File vol ("/Volumes");
  47299. vol.findChildFiles (volumes, File::findDirectories, false);
  47300. for (int i = 0; i < volumes.size(); ++i)
  47301. {
  47302. const File& volume = volumes.getReference(i);
  47303. if (volume.isDirectory() && ! volume.getFileName().startsWithChar ('.'))
  47304. {
  47305. rootPaths.add (volume.getFullPathName());
  47306. rootNames.add (volume.getFileName());
  47307. }
  47308. }
  47309. #endif
  47310. #if JUCE_LINUX
  47311. rootPaths.add ("/");
  47312. rootNames.add ("/");
  47313. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  47314. rootNames.add ("Home folder");
  47315. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  47316. rootNames.add ("Desktop");
  47317. #endif
  47318. return separators;
  47319. }
  47320. END_JUCE_NAMESPACE
  47321. /*** End of inlined file: juce_FileBrowserComponent.cpp ***/
  47322. /*** Start of inlined file: juce_FileChooser.cpp ***/
  47323. BEGIN_JUCE_NAMESPACE
  47324. FileChooser::FileChooser (const String& chooserBoxTitle,
  47325. const File& currentFileOrDirectory,
  47326. const String& fileFilters,
  47327. const bool useNativeDialogBox_)
  47328. : title (chooserBoxTitle),
  47329. filters (fileFilters),
  47330. startingFile (currentFileOrDirectory),
  47331. useNativeDialogBox (useNativeDialogBox_)
  47332. {
  47333. #if JUCE_LINUX
  47334. useNativeDialogBox = false;
  47335. #endif
  47336. if (! fileFilters.containsNonWhitespaceChars())
  47337. filters = "*";
  47338. }
  47339. FileChooser::~FileChooser()
  47340. {
  47341. }
  47342. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  47343. {
  47344. return showDialog (false, true, false, false, false, previewComponent);
  47345. }
  47346. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  47347. {
  47348. return showDialog (false, true, false, false, true, previewComponent);
  47349. }
  47350. bool FileChooser::browseForMultipleFilesOrDirectories (FilePreviewComponent* previewComponent)
  47351. {
  47352. return showDialog (true, true, false, false, true, previewComponent);
  47353. }
  47354. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  47355. {
  47356. return showDialog (false, true, true, warnAboutOverwritingExistingFiles, false, 0);
  47357. }
  47358. bool FileChooser::browseForDirectory()
  47359. {
  47360. return showDialog (true, false, false, false, false, 0);
  47361. }
  47362. const File FileChooser::getResult() const
  47363. {
  47364. // if you've used a multiple-file select, you should use the getResults() method
  47365. // to retrieve all the files that were chosen.
  47366. jassert (results.size() <= 1);
  47367. return results.getFirst();
  47368. }
  47369. const Array<File>& FileChooser::getResults() const
  47370. {
  47371. return results;
  47372. }
  47373. bool FileChooser::showDialog (const bool selectsDirectories,
  47374. const bool selectsFiles,
  47375. const bool isSave,
  47376. const bool warnAboutOverwritingExistingFiles,
  47377. const bool selectMultipleFiles,
  47378. FilePreviewComponent* const previewComponent)
  47379. {
  47380. Component::SafePointer<Component> previouslyFocused (Component::getCurrentlyFocusedComponent());
  47381. results.clear();
  47382. // the preview component needs to be the right size before you pass it in here..
  47383. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  47384. && previewComponent->getHeight() > 10));
  47385. #if JUCE_WINDOWS
  47386. if (useNativeDialogBox && ! (selectsFiles && selectsDirectories))
  47387. #elif JUCE_MAC
  47388. if (useNativeDialogBox && (previewComponent == 0))
  47389. #else
  47390. if (false)
  47391. #endif
  47392. {
  47393. showPlatformDialog (results, title, startingFile, filters,
  47394. selectsDirectories, selectsFiles, isSave,
  47395. warnAboutOverwritingExistingFiles,
  47396. selectMultipleFiles,
  47397. previewComponent);
  47398. }
  47399. else
  47400. {
  47401. WildcardFileFilter wildcard (selectsFiles ? filters : String::empty,
  47402. selectsDirectories ? "*" : String::empty,
  47403. String::empty);
  47404. int flags = isSave ? FileBrowserComponent::saveMode
  47405. : FileBrowserComponent::openMode;
  47406. if (selectsFiles)
  47407. flags |= FileBrowserComponent::canSelectFiles;
  47408. if (selectsDirectories)
  47409. {
  47410. flags |= FileBrowserComponent::canSelectDirectories;
  47411. if (! isSave)
  47412. flags |= FileBrowserComponent::filenameBoxIsReadOnly;
  47413. }
  47414. if (selectMultipleFiles)
  47415. flags |= FileBrowserComponent::canSelectMultipleItems;
  47416. FileBrowserComponent browserComponent (flags, startingFile, &wildcard, previewComponent);
  47417. FileChooserDialogBox box (title, String::empty,
  47418. browserComponent,
  47419. warnAboutOverwritingExistingFiles,
  47420. browserComponent.findColour (AlertWindow::backgroundColourId));
  47421. if (box.show())
  47422. {
  47423. for (int i = 0; i < browserComponent.getNumSelectedFiles(); ++i)
  47424. results.add (browserComponent.getSelectedFile (i));
  47425. }
  47426. }
  47427. if (previouslyFocused != 0)
  47428. previouslyFocused->grabKeyboardFocus();
  47429. return results.size() > 0;
  47430. }
  47431. FilePreviewComponent::FilePreviewComponent()
  47432. {
  47433. }
  47434. FilePreviewComponent::~FilePreviewComponent()
  47435. {
  47436. }
  47437. END_JUCE_NAMESPACE
  47438. /*** End of inlined file: juce_FileChooser.cpp ***/
  47439. /*** Start of inlined file: juce_FileChooserDialogBox.cpp ***/
  47440. BEGIN_JUCE_NAMESPACE
  47441. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  47442. const String& instructions,
  47443. FileBrowserComponent& chooserComponent,
  47444. const bool warnAboutOverwritingExistingFiles_,
  47445. const Colour& backgroundColour)
  47446. : ResizableWindow (name, backgroundColour, true),
  47447. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  47448. {
  47449. setContentComponent (content = new ContentComponent (name, instructions, chooserComponent));
  47450. setResizable (true, true);
  47451. setResizeLimits (300, 300, 1200, 1000);
  47452. content->okButton.addButtonListener (this);
  47453. content->cancelButton.addButtonListener (this);
  47454. content->chooserComponent.addListener (this);
  47455. }
  47456. FileChooserDialogBox::~FileChooserDialogBox()
  47457. {
  47458. content->chooserComponent.removeListener (this);
  47459. }
  47460. bool FileChooserDialogBox::show (int w, int h)
  47461. {
  47462. return showAt (-1, -1, w, h);
  47463. }
  47464. bool FileChooserDialogBox::showAt (int x, int y, int w, int h)
  47465. {
  47466. if (w <= 0)
  47467. {
  47468. Component* const previewComp = content->chooserComponent.getPreviewComponent();
  47469. if (previewComp != 0)
  47470. w = 400 + previewComp->getWidth();
  47471. else
  47472. w = 600;
  47473. }
  47474. if (h <= 0)
  47475. h = 500;
  47476. if (x < 0 || y < 0)
  47477. centreWithSize (w, h);
  47478. else
  47479. setBounds (x, y, w, h);
  47480. const bool ok = (runModalLoop() != 0);
  47481. setVisible (false);
  47482. return ok;
  47483. }
  47484. void FileChooserDialogBox::buttonClicked (Button* button)
  47485. {
  47486. if (button == &(content->okButton))
  47487. {
  47488. if (warnAboutOverwritingExistingFiles
  47489. && content->chooserComponent.isSaveMode()
  47490. && content->chooserComponent.getSelectedFile(0).exists())
  47491. {
  47492. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  47493. TRANS("File already exists"),
  47494. TRANS("There's already a file called:")
  47495. + "\n\n" + content->chooserComponent.getSelectedFile(0).getFullPathName()
  47496. + "\n\n" + TRANS("Are you sure you want to overwrite it?"),
  47497. TRANS("overwrite"),
  47498. TRANS("cancel")))
  47499. {
  47500. return;
  47501. }
  47502. }
  47503. exitModalState (1);
  47504. }
  47505. else if (button == &(content->cancelButton))
  47506. {
  47507. closeButtonPressed();
  47508. }
  47509. }
  47510. void FileChooserDialogBox::closeButtonPressed()
  47511. {
  47512. setVisible (false);
  47513. }
  47514. void FileChooserDialogBox::selectionChanged()
  47515. {
  47516. content->okButton.setEnabled (content->chooserComponent.currentFileIsValid());
  47517. }
  47518. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  47519. {
  47520. }
  47521. void FileChooserDialogBox::fileDoubleClicked (const File&)
  47522. {
  47523. selectionChanged();
  47524. content->okButton.triggerClick();
  47525. }
  47526. FileChooserDialogBox::ContentComponent::ContentComponent (const String& name, const String& instructions_, FileBrowserComponent& chooserComponent_)
  47527. : Component (name), instructions (instructions_),
  47528. chooserComponent (chooserComponent_),
  47529. okButton (chooserComponent_.getActionVerb()),
  47530. cancelButton (TRANS ("Cancel"))
  47531. {
  47532. addAndMakeVisible (&chooserComponent);
  47533. addAndMakeVisible (&okButton);
  47534. okButton.setEnabled (chooserComponent.currentFileIsValid());
  47535. okButton.addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  47536. addAndMakeVisible (&cancelButton);
  47537. cancelButton.addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  47538. setInterceptsMouseClicks (false, true);
  47539. }
  47540. FileChooserDialogBox::ContentComponent::~ContentComponent()
  47541. {
  47542. }
  47543. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  47544. {
  47545. g.setColour (getLookAndFeel().findColour (FileChooserDialogBox::titleTextColourId));
  47546. text.draw (g);
  47547. }
  47548. void FileChooserDialogBox::ContentComponent::resized()
  47549. {
  47550. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  47551. const Rectangle<float> bb (text.getBoundingBox (0, text.getNumGlyphs(), false));
  47552. const int y = roundToInt (bb.getBottom()) + 10;
  47553. const int buttonHeight = 26;
  47554. const int buttonY = getHeight() - buttonHeight - 8;
  47555. chooserComponent.setBounds (0, y, getWidth(), buttonY - y - 20);
  47556. okButton.setBounds (proportionOfWidth (0.25f), buttonY,
  47557. proportionOfWidth (0.2f), buttonHeight);
  47558. cancelButton.setBounds (proportionOfWidth (0.55f), buttonY,
  47559. proportionOfWidth (0.2f), buttonHeight);
  47560. }
  47561. END_JUCE_NAMESPACE
  47562. /*** End of inlined file: juce_FileChooserDialogBox.cpp ***/
  47563. /*** Start of inlined file: juce_FileFilter.cpp ***/
  47564. BEGIN_JUCE_NAMESPACE
  47565. FileFilter::FileFilter (const String& filterDescription)
  47566. : description (filterDescription)
  47567. {
  47568. }
  47569. FileFilter::~FileFilter()
  47570. {
  47571. }
  47572. const String& FileFilter::getDescription() const throw()
  47573. {
  47574. return description;
  47575. }
  47576. END_JUCE_NAMESPACE
  47577. /*** End of inlined file: juce_FileFilter.cpp ***/
  47578. /*** Start of inlined file: juce_FileListComponent.cpp ***/
  47579. BEGIN_JUCE_NAMESPACE
  47580. const Image juce_createIconForFile (const File& file);
  47581. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  47582. : ListBox (String::empty, 0),
  47583. DirectoryContentsDisplayComponent (listToShow)
  47584. {
  47585. setModel (this);
  47586. fileList.addChangeListener (this);
  47587. }
  47588. FileListComponent::~FileListComponent()
  47589. {
  47590. fileList.removeChangeListener (this);
  47591. }
  47592. int FileListComponent::getNumSelectedFiles() const
  47593. {
  47594. return getNumSelectedRows();
  47595. }
  47596. const File FileListComponent::getSelectedFile (int index) const
  47597. {
  47598. return fileList.getFile (getSelectedRow (index));
  47599. }
  47600. void FileListComponent::deselectAllFiles()
  47601. {
  47602. deselectAllRows();
  47603. }
  47604. void FileListComponent::scrollToTop()
  47605. {
  47606. getVerticalScrollBar()->setCurrentRangeStart (0);
  47607. }
  47608. void FileListComponent::changeListenerCallback (void*)
  47609. {
  47610. updateContent();
  47611. if (lastDirectory != fileList.getDirectory())
  47612. {
  47613. lastDirectory = fileList.getDirectory();
  47614. deselectAllRows();
  47615. }
  47616. }
  47617. class FileListItemComponent : public Component,
  47618. public TimeSliceClient,
  47619. public AsyncUpdater
  47620. {
  47621. public:
  47622. FileListItemComponent (FileListComponent& owner_, TimeSliceThread& thread_)
  47623. : owner (owner_), thread (thread_),
  47624. highlighted (false), index (0), icon (0)
  47625. {
  47626. }
  47627. ~FileListItemComponent()
  47628. {
  47629. thread.removeTimeSliceClient (this);
  47630. clearIcon();
  47631. }
  47632. void paint (Graphics& g)
  47633. {
  47634. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  47635. file.getFileName(),
  47636. &icon,
  47637. fileSize, modTime,
  47638. isDirectory, highlighted,
  47639. index, owner);
  47640. }
  47641. void mouseDown (const MouseEvent& e)
  47642. {
  47643. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  47644. owner.sendMouseClickMessage (file, e);
  47645. }
  47646. void mouseDoubleClick (const MouseEvent&)
  47647. {
  47648. owner.sendDoubleClickMessage (file);
  47649. }
  47650. void update (const File& root,
  47651. const DirectoryContentsList::FileInfo* const fileInfo,
  47652. const int index_,
  47653. const bool highlighted_)
  47654. {
  47655. thread.removeTimeSliceClient (this);
  47656. if (highlighted_ != highlighted
  47657. || index_ != index)
  47658. {
  47659. index = index_;
  47660. highlighted = highlighted_;
  47661. repaint();
  47662. }
  47663. File newFile;
  47664. String newFileSize;
  47665. String newModTime;
  47666. if (fileInfo != 0)
  47667. {
  47668. newFile = root.getChildFile (fileInfo->filename);
  47669. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  47670. newModTime = fileInfo->modificationTime.formatted ("%d %b '%y %H:%M");
  47671. }
  47672. if (newFile != file
  47673. || fileSize != newFileSize
  47674. || modTime != newModTime)
  47675. {
  47676. file = newFile;
  47677. fileSize = newFileSize;
  47678. modTime = newModTime;
  47679. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  47680. repaint();
  47681. clearIcon();
  47682. }
  47683. if (file != File::nonexistent && icon.isNull() && ! isDirectory)
  47684. {
  47685. updateIcon (true);
  47686. if (! icon.isValid())
  47687. thread.addTimeSliceClient (this);
  47688. }
  47689. }
  47690. bool useTimeSlice()
  47691. {
  47692. updateIcon (false);
  47693. return false;
  47694. }
  47695. void handleAsyncUpdate()
  47696. {
  47697. repaint();
  47698. }
  47699. juce_UseDebuggingNewOperator
  47700. private:
  47701. FileListComponent& owner;
  47702. TimeSliceThread& thread;
  47703. bool highlighted;
  47704. int index;
  47705. File file;
  47706. String fileSize;
  47707. String modTime;
  47708. Image icon;
  47709. bool isDirectory;
  47710. void clearIcon()
  47711. {
  47712. icon = Image::null;
  47713. }
  47714. void updateIcon (const bool onlyUpdateIfCached)
  47715. {
  47716. if (icon.isNull())
  47717. {
  47718. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  47719. Image im (ImageCache::getFromHashCode (hashCode));
  47720. if (im.isNull() && ! onlyUpdateIfCached)
  47721. {
  47722. im = juce_createIconForFile (file);
  47723. if (im.isValid())
  47724. ImageCache::addImageToCache (im, hashCode);
  47725. }
  47726. if (im.isValid())
  47727. {
  47728. icon = im;
  47729. triggerAsyncUpdate();
  47730. }
  47731. }
  47732. }
  47733. };
  47734. int FileListComponent::getNumRows()
  47735. {
  47736. return fileList.getNumFiles();
  47737. }
  47738. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  47739. {
  47740. }
  47741. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  47742. {
  47743. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  47744. if (comp == 0)
  47745. {
  47746. delete existingComponentToUpdate;
  47747. comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  47748. }
  47749. DirectoryContentsList::FileInfo fileInfo;
  47750. if (fileList.getFileInfo (row, fileInfo))
  47751. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  47752. else
  47753. comp->update (fileList.getDirectory(), 0, row, isSelected);
  47754. return comp;
  47755. }
  47756. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  47757. {
  47758. sendSelectionChangeMessage();
  47759. }
  47760. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  47761. {
  47762. }
  47763. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  47764. {
  47765. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  47766. }
  47767. END_JUCE_NAMESPACE
  47768. /*** End of inlined file: juce_FileListComponent.cpp ***/
  47769. /*** Start of inlined file: juce_FilenameComponent.cpp ***/
  47770. BEGIN_JUCE_NAMESPACE
  47771. FilenameComponent::FilenameComponent (const String& name,
  47772. const File& currentFile,
  47773. const bool canEditFilename,
  47774. const bool isDirectory,
  47775. const bool isForSaving,
  47776. const String& fileBrowserWildcard,
  47777. const String& enforcedSuffix_,
  47778. const String& textWhenNothingSelected)
  47779. : Component (name),
  47780. maxRecentFiles (30),
  47781. isDir (isDirectory),
  47782. isSaving (isForSaving),
  47783. isFileDragOver (false),
  47784. wildcard (fileBrowserWildcard),
  47785. enforcedSuffix (enforcedSuffix_)
  47786. {
  47787. addAndMakeVisible (&filenameBox);
  47788. filenameBox.setEditableText (canEditFilename);
  47789. filenameBox.addListener (this);
  47790. filenameBox.setTextWhenNothingSelected (textWhenNothingSelected);
  47791. filenameBox.setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  47792. setBrowseButtonText ("...");
  47793. setCurrentFile (currentFile, true);
  47794. }
  47795. FilenameComponent::~FilenameComponent()
  47796. {
  47797. }
  47798. void FilenameComponent::paintOverChildren (Graphics& g)
  47799. {
  47800. if (isFileDragOver)
  47801. {
  47802. g.setColour (Colours::red.withAlpha (0.2f));
  47803. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  47804. }
  47805. }
  47806. void FilenameComponent::resized()
  47807. {
  47808. getLookAndFeel().layoutFilenameComponent (*this, &filenameBox, browseButton);
  47809. }
  47810. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  47811. {
  47812. browseButtonText = newBrowseButtonText;
  47813. lookAndFeelChanged();
  47814. }
  47815. void FilenameComponent::lookAndFeelChanged()
  47816. {
  47817. browseButton = 0;
  47818. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  47819. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  47820. resized();
  47821. browseButton->addButtonListener (this);
  47822. }
  47823. void FilenameComponent::setTooltip (const String& newTooltip)
  47824. {
  47825. SettableTooltipClient::setTooltip (newTooltip);
  47826. filenameBox.setTooltip (newTooltip);
  47827. }
  47828. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  47829. {
  47830. defaultBrowseFile = newDefaultDirectory;
  47831. }
  47832. void FilenameComponent::buttonClicked (Button*)
  47833. {
  47834. FileChooser fc (TRANS("Choose a new file"),
  47835. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  47836. : getCurrentFile(),
  47837. wildcard);
  47838. if (isDir ? fc.browseForDirectory()
  47839. : (isSaving ? fc.browseForFileToSave (false)
  47840. : fc.browseForFileToOpen()))
  47841. {
  47842. setCurrentFile (fc.getResult(), true);
  47843. }
  47844. }
  47845. void FilenameComponent::comboBoxChanged (ComboBox*)
  47846. {
  47847. setCurrentFile (getCurrentFile(), true);
  47848. }
  47849. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  47850. {
  47851. return true;
  47852. }
  47853. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  47854. {
  47855. isFileDragOver = false;
  47856. repaint();
  47857. const File f (filenames[0]);
  47858. if (f.exists() && (f.isDirectory() == isDir))
  47859. setCurrentFile (f, true);
  47860. }
  47861. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  47862. {
  47863. isFileDragOver = true;
  47864. repaint();
  47865. }
  47866. void FilenameComponent::fileDragExit (const StringArray&)
  47867. {
  47868. isFileDragOver = false;
  47869. repaint();
  47870. }
  47871. const File FilenameComponent::getCurrentFile() const
  47872. {
  47873. File f (filenameBox.getText());
  47874. if (enforcedSuffix.isNotEmpty())
  47875. f = f.withFileExtension (enforcedSuffix);
  47876. return f;
  47877. }
  47878. void FilenameComponent::setCurrentFile (File newFile,
  47879. const bool addToRecentlyUsedList,
  47880. const bool sendChangeNotification)
  47881. {
  47882. if (enforcedSuffix.isNotEmpty())
  47883. newFile = newFile.withFileExtension (enforcedSuffix);
  47884. if (newFile.getFullPathName() != lastFilename)
  47885. {
  47886. lastFilename = newFile.getFullPathName();
  47887. if (addToRecentlyUsedList)
  47888. addRecentlyUsedFile (newFile);
  47889. filenameBox.setText (lastFilename, true);
  47890. if (sendChangeNotification)
  47891. triggerAsyncUpdate();
  47892. }
  47893. }
  47894. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  47895. {
  47896. filenameBox.setEditableText (shouldBeEditable);
  47897. }
  47898. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  47899. {
  47900. StringArray names;
  47901. for (int i = 0; i < filenameBox.getNumItems(); ++i)
  47902. names.add (filenameBox.getItemText (i));
  47903. return names;
  47904. }
  47905. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  47906. {
  47907. if (filenames != getRecentlyUsedFilenames())
  47908. {
  47909. filenameBox.clear();
  47910. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  47911. filenameBox.addItem (filenames[i], i + 1);
  47912. }
  47913. }
  47914. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  47915. {
  47916. maxRecentFiles = jmax (1, newMaximum);
  47917. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  47918. }
  47919. void FilenameComponent::addRecentlyUsedFile (const File& file)
  47920. {
  47921. StringArray files (getRecentlyUsedFilenames());
  47922. if (file.getFullPathName().isNotEmpty())
  47923. {
  47924. files.removeString (file.getFullPathName(), true);
  47925. files.insert (0, file.getFullPathName());
  47926. setRecentlyUsedFilenames (files);
  47927. }
  47928. }
  47929. void FilenameComponent::addListener (FilenameComponentListener* const listener)
  47930. {
  47931. listeners.add (listener);
  47932. }
  47933. void FilenameComponent::removeListener (FilenameComponentListener* const listener)
  47934. {
  47935. listeners.remove (listener);
  47936. }
  47937. void FilenameComponent::handleAsyncUpdate()
  47938. {
  47939. Component::BailOutChecker checker (this);
  47940. listeners.callChecked (checker, &FilenameComponentListener::filenameComponentChanged, this);
  47941. }
  47942. END_JUCE_NAMESPACE
  47943. /*** End of inlined file: juce_FilenameComponent.cpp ***/
  47944. /*** Start of inlined file: juce_FileSearchPathListComponent.cpp ***/
  47945. BEGIN_JUCE_NAMESPACE
  47946. FileSearchPathListComponent::FileSearchPathListComponent()
  47947. : addButton ("+"),
  47948. removeButton ("-"),
  47949. changeButton (TRANS ("change...")),
  47950. upButton (String::empty, DrawableButton::ImageOnButtonBackground),
  47951. downButton (String::empty, DrawableButton::ImageOnButtonBackground)
  47952. {
  47953. listBox.setModel (this);
  47954. addAndMakeVisible (&listBox);
  47955. listBox.setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  47956. listBox.setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  47957. listBox.setOutlineThickness (1);
  47958. addAndMakeVisible (&addButton);
  47959. addButton.addButtonListener (this);
  47960. addButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47961. addAndMakeVisible (&removeButton);
  47962. removeButton.addButtonListener (this);
  47963. removeButton.setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  47964. addAndMakeVisible (&changeButton);
  47965. changeButton.addButtonListener (this);
  47966. addAndMakeVisible (&upButton);
  47967. upButton.addButtonListener (this);
  47968. {
  47969. Path arrowPath;
  47970. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  47971. DrawablePath arrowImage;
  47972. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47973. arrowImage.setPath (arrowPath);
  47974. upButton.setImages (&arrowImage);
  47975. }
  47976. addAndMakeVisible (&downButton);
  47977. downButton.addButtonListener (this);
  47978. {
  47979. Path arrowPath;
  47980. arrowPath.addArrow (Line<float> (50.0f, 0.0f, 50.0f, 100.0f), 40.0f, 100.0f, 50.0f);
  47981. DrawablePath arrowImage;
  47982. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  47983. arrowImage.setPath (arrowPath);
  47984. downButton.setImages (&arrowImage);
  47985. }
  47986. updateButtons();
  47987. }
  47988. FileSearchPathListComponent::~FileSearchPathListComponent()
  47989. {
  47990. }
  47991. void FileSearchPathListComponent::updateButtons()
  47992. {
  47993. const bool anythingSelected = listBox.getNumSelectedRows() > 0;
  47994. removeButton.setEnabled (anythingSelected);
  47995. changeButton.setEnabled (anythingSelected);
  47996. upButton.setEnabled (anythingSelected);
  47997. downButton.setEnabled (anythingSelected);
  47998. }
  47999. void FileSearchPathListComponent::changed()
  48000. {
  48001. listBox.updateContent();
  48002. listBox.repaint();
  48003. updateButtons();
  48004. }
  48005. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  48006. {
  48007. if (newPath.toString() != path.toString())
  48008. {
  48009. path = newPath;
  48010. changed();
  48011. }
  48012. }
  48013. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory)
  48014. {
  48015. defaultBrowseTarget = newDefaultDirectory;
  48016. }
  48017. int FileSearchPathListComponent::getNumRows()
  48018. {
  48019. return path.getNumPaths();
  48020. }
  48021. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  48022. {
  48023. if (rowIsSelected)
  48024. g.fillAll (findColour (TextEditor::highlightColourId));
  48025. g.setColour (findColour (ListBox::textColourId));
  48026. Font f (height * 0.7f);
  48027. f.setHorizontalScale (0.9f);
  48028. g.setFont (f);
  48029. g.drawText (path [rowNumber].getFullPathName(),
  48030. 4, 0, width - 6, height,
  48031. Justification::centredLeft, true);
  48032. }
  48033. void FileSearchPathListComponent::deleteKeyPressed (int row)
  48034. {
  48035. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  48036. {
  48037. path.remove (row);
  48038. changed();
  48039. }
  48040. }
  48041. void FileSearchPathListComponent::returnKeyPressed (int row)
  48042. {
  48043. FileChooser chooser (TRANS("Change folder..."), path [row], "*");
  48044. if (chooser.browseForDirectory())
  48045. {
  48046. path.remove (row);
  48047. path.add (chooser.getResult(), row);
  48048. changed();
  48049. }
  48050. }
  48051. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  48052. {
  48053. returnKeyPressed (row);
  48054. }
  48055. void FileSearchPathListComponent::selectedRowsChanged (int)
  48056. {
  48057. updateButtons();
  48058. }
  48059. void FileSearchPathListComponent::paint (Graphics& g)
  48060. {
  48061. g.fillAll (findColour (backgroundColourId));
  48062. }
  48063. void FileSearchPathListComponent::resized()
  48064. {
  48065. const int buttonH = 22;
  48066. const int buttonY = getHeight() - buttonH - 4;
  48067. listBox.setBounds (2, 2, getWidth() - 4, buttonY - 5);
  48068. addButton.setBounds (2, buttonY, buttonH, buttonH);
  48069. removeButton.setBounds (addButton.getRight(), buttonY, buttonH, buttonH);
  48070. changeButton.changeWidthToFitText (buttonH);
  48071. downButton.setSize (buttonH * 2, buttonH);
  48072. upButton.setSize (buttonH * 2, buttonH);
  48073. downButton.setTopRightPosition (getWidth() - 2, buttonY);
  48074. upButton.setTopRightPosition (downButton.getX() - 4, buttonY);
  48075. changeButton.setTopRightPosition (upButton.getX() - 8, buttonY);
  48076. }
  48077. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  48078. {
  48079. return true;
  48080. }
  48081. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  48082. {
  48083. for (int i = filenames.size(); --i >= 0;)
  48084. {
  48085. const File f (filenames[i]);
  48086. if (f.isDirectory())
  48087. {
  48088. const int row = listBox.getRowContainingPosition (0, mouseY - listBox.getY());
  48089. path.add (f, row);
  48090. changed();
  48091. }
  48092. }
  48093. }
  48094. void FileSearchPathListComponent::buttonClicked (Button* button)
  48095. {
  48096. const int currentRow = listBox.getSelectedRow();
  48097. if (button == &removeButton)
  48098. {
  48099. deleteKeyPressed (currentRow);
  48100. }
  48101. else if (button == &addButton)
  48102. {
  48103. File start (defaultBrowseTarget);
  48104. if (start == File::nonexistent)
  48105. start = path [0];
  48106. if (start == File::nonexistent)
  48107. start = File::getCurrentWorkingDirectory();
  48108. FileChooser chooser (TRANS("Add a folder..."), start, "*");
  48109. if (chooser.browseForDirectory())
  48110. {
  48111. path.add (chooser.getResult(), currentRow);
  48112. }
  48113. }
  48114. else if (button == &changeButton)
  48115. {
  48116. returnKeyPressed (currentRow);
  48117. }
  48118. else if (button == &upButton)
  48119. {
  48120. if (currentRow > 0 && currentRow < path.getNumPaths())
  48121. {
  48122. const File f (path[currentRow]);
  48123. path.remove (currentRow);
  48124. path.add (f, currentRow - 1);
  48125. listBox.selectRow (currentRow - 1);
  48126. }
  48127. }
  48128. else if (button == &downButton)
  48129. {
  48130. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  48131. {
  48132. const File f (path[currentRow]);
  48133. path.remove (currentRow);
  48134. path.add (f, currentRow + 1);
  48135. listBox.selectRow (currentRow + 1);
  48136. }
  48137. }
  48138. changed();
  48139. }
  48140. END_JUCE_NAMESPACE
  48141. /*** End of inlined file: juce_FileSearchPathListComponent.cpp ***/
  48142. /*** Start of inlined file: juce_FileTreeComponent.cpp ***/
  48143. BEGIN_JUCE_NAMESPACE
  48144. const Image juce_createIconForFile (const File& file);
  48145. class FileListTreeItem : public TreeViewItem,
  48146. public TimeSliceClient,
  48147. public AsyncUpdater,
  48148. public ChangeListener
  48149. {
  48150. public:
  48151. FileListTreeItem (FileTreeComponent& owner_,
  48152. DirectoryContentsList* const parentContentsList_,
  48153. const int indexInContentsList_,
  48154. const File& file_,
  48155. TimeSliceThread& thread_)
  48156. : file (file_),
  48157. owner (owner_),
  48158. parentContentsList (parentContentsList_),
  48159. indexInContentsList (indexInContentsList_),
  48160. subContentsList (0),
  48161. canDeleteSubContentsList (false),
  48162. thread (thread_),
  48163. icon (0)
  48164. {
  48165. DirectoryContentsList::FileInfo fileInfo;
  48166. if (parentContentsList_ != 0
  48167. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  48168. {
  48169. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  48170. modTime = fileInfo.modificationTime.formatted ("%d %b '%y %H:%M");
  48171. isDirectory = fileInfo.isDirectory;
  48172. }
  48173. else
  48174. {
  48175. isDirectory = true;
  48176. }
  48177. }
  48178. ~FileListTreeItem()
  48179. {
  48180. thread.removeTimeSliceClient (this);
  48181. clearSubItems();
  48182. if (canDeleteSubContentsList)
  48183. delete subContentsList;
  48184. }
  48185. bool mightContainSubItems() { return isDirectory; }
  48186. const String getUniqueName() const { return file.getFullPathName(); }
  48187. int getItemHeight() const { return 22; }
  48188. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  48189. void itemOpennessChanged (bool isNowOpen)
  48190. {
  48191. if (isNowOpen)
  48192. {
  48193. clearSubItems();
  48194. isDirectory = file.isDirectory();
  48195. if (isDirectory)
  48196. {
  48197. if (subContentsList == 0)
  48198. {
  48199. jassert (parentContentsList != 0);
  48200. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  48201. l->setDirectory (file, true, true);
  48202. setSubContentsList (l);
  48203. canDeleteSubContentsList = true;
  48204. }
  48205. changeListenerCallback (0);
  48206. }
  48207. }
  48208. }
  48209. void setSubContentsList (DirectoryContentsList* newList)
  48210. {
  48211. jassert (subContentsList == 0);
  48212. subContentsList = newList;
  48213. newList->addChangeListener (this);
  48214. }
  48215. void changeListenerCallback (void*)
  48216. {
  48217. clearSubItems();
  48218. if (isOpen() && subContentsList != 0)
  48219. {
  48220. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  48221. {
  48222. FileListTreeItem* const item
  48223. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  48224. addSubItem (item);
  48225. }
  48226. }
  48227. }
  48228. void paintItem (Graphics& g, int width, int height)
  48229. {
  48230. if (file != File::nonexistent)
  48231. {
  48232. updateIcon (true);
  48233. if (icon.isNull())
  48234. thread.addTimeSliceClient (this);
  48235. }
  48236. owner.getLookAndFeel()
  48237. .drawFileBrowserRow (g, width, height,
  48238. file.getFileName(),
  48239. &icon, fileSize, modTime,
  48240. isDirectory, isSelected(),
  48241. indexInContentsList, owner);
  48242. }
  48243. void itemClicked (const MouseEvent& e)
  48244. {
  48245. owner.sendMouseClickMessage (file, e);
  48246. }
  48247. void itemDoubleClicked (const MouseEvent& e)
  48248. {
  48249. TreeViewItem::itemDoubleClicked (e);
  48250. owner.sendDoubleClickMessage (file);
  48251. }
  48252. void itemSelectionChanged (bool)
  48253. {
  48254. owner.sendSelectionChangeMessage();
  48255. }
  48256. bool useTimeSlice()
  48257. {
  48258. updateIcon (false);
  48259. thread.removeTimeSliceClient (this);
  48260. return false;
  48261. }
  48262. void handleAsyncUpdate()
  48263. {
  48264. owner.repaint();
  48265. }
  48266. const File file;
  48267. juce_UseDebuggingNewOperator
  48268. private:
  48269. FileTreeComponent& owner;
  48270. DirectoryContentsList* parentContentsList;
  48271. int indexInContentsList;
  48272. DirectoryContentsList* subContentsList;
  48273. bool isDirectory, canDeleteSubContentsList;
  48274. TimeSliceThread& thread;
  48275. Image icon;
  48276. String fileSize;
  48277. String modTime;
  48278. void updateIcon (const bool onlyUpdateIfCached)
  48279. {
  48280. if (icon.isNull())
  48281. {
  48282. const int hashCode = (file.getFullPathName() + "_iconCacheSalt").hashCode();
  48283. Image im (ImageCache::getFromHashCode (hashCode));
  48284. if (im.isNull() && ! onlyUpdateIfCached)
  48285. {
  48286. im = juce_createIconForFile (file);
  48287. if (im.isValid())
  48288. ImageCache::addImageToCache (im, hashCode);
  48289. }
  48290. if (im.isValid())
  48291. {
  48292. icon = im;
  48293. triggerAsyncUpdate();
  48294. }
  48295. }
  48296. }
  48297. };
  48298. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  48299. : DirectoryContentsDisplayComponent (listToShow)
  48300. {
  48301. FileListTreeItem* const root
  48302. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  48303. listToShow.getTimeSliceThread());
  48304. root->setSubContentsList (&listToShow);
  48305. setRootItemVisible (false);
  48306. setRootItem (root);
  48307. }
  48308. FileTreeComponent::~FileTreeComponent()
  48309. {
  48310. deleteRootItem();
  48311. }
  48312. const File FileTreeComponent::getSelectedFile (const int index) const
  48313. {
  48314. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  48315. return item != 0 ? item->file
  48316. : File::nonexistent;
  48317. }
  48318. void FileTreeComponent::deselectAllFiles()
  48319. {
  48320. clearSelectedItems();
  48321. }
  48322. void FileTreeComponent::scrollToTop()
  48323. {
  48324. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  48325. }
  48326. void FileTreeComponent::setDragAndDropDescription (const String& description)
  48327. {
  48328. dragAndDropDescription = description;
  48329. }
  48330. END_JUCE_NAMESPACE
  48331. /*** End of inlined file: juce_FileTreeComponent.cpp ***/
  48332. /*** Start of inlined file: juce_ImagePreviewComponent.cpp ***/
  48333. BEGIN_JUCE_NAMESPACE
  48334. ImagePreviewComponent::ImagePreviewComponent()
  48335. {
  48336. }
  48337. ImagePreviewComponent::~ImagePreviewComponent()
  48338. {
  48339. }
  48340. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  48341. {
  48342. const int availableW = proportionOfWidth (0.97f);
  48343. const int availableH = getHeight() - 13 * 4;
  48344. const double scale = jmin (1.0,
  48345. availableW / (double) w,
  48346. availableH / (double) h);
  48347. w = roundToInt (scale * w);
  48348. h = roundToInt (scale * h);
  48349. }
  48350. void ImagePreviewComponent::selectedFileChanged (const File& file)
  48351. {
  48352. if (fileToLoad != file)
  48353. {
  48354. fileToLoad = file;
  48355. startTimer (100);
  48356. }
  48357. }
  48358. void ImagePreviewComponent::timerCallback()
  48359. {
  48360. stopTimer();
  48361. currentThumbnail = Image::null;
  48362. currentDetails = String::empty;
  48363. repaint();
  48364. ScopedPointer <FileInputStream> in (fileToLoad.createInputStream());
  48365. if (in != 0)
  48366. {
  48367. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  48368. if (format != 0)
  48369. {
  48370. currentThumbnail = format->decodeImage (*in);
  48371. if (currentThumbnail.isValid())
  48372. {
  48373. int w = currentThumbnail.getWidth();
  48374. int h = currentThumbnail.getHeight();
  48375. currentDetails
  48376. << fileToLoad.getFileName() << "\n"
  48377. << format->getFormatName() << "\n"
  48378. << w << " x " << h << " pixels\n"
  48379. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  48380. getThumbSize (w, h);
  48381. currentThumbnail = currentThumbnail.rescaled (w, h);
  48382. }
  48383. }
  48384. }
  48385. }
  48386. void ImagePreviewComponent::paint (Graphics& g)
  48387. {
  48388. if (currentThumbnail.isValid())
  48389. {
  48390. g.setFont (13.0f);
  48391. int w = currentThumbnail.getWidth();
  48392. int h = currentThumbnail.getHeight();
  48393. getThumbSize (w, h);
  48394. const int numLines = 4;
  48395. const int totalH = 13 * numLines + h + 4;
  48396. const int y = (getHeight() - totalH) / 2;
  48397. g.drawImageWithin (currentThumbnail,
  48398. (getWidth() - w) / 2, y, w, h,
  48399. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  48400. false);
  48401. g.drawFittedText (currentDetails,
  48402. 0, y + h + 4, getWidth(), 100,
  48403. Justification::centredTop, numLines);
  48404. }
  48405. }
  48406. END_JUCE_NAMESPACE
  48407. /*** End of inlined file: juce_ImagePreviewComponent.cpp ***/
  48408. /*** Start of inlined file: juce_WildcardFileFilter.cpp ***/
  48409. BEGIN_JUCE_NAMESPACE
  48410. WildcardFileFilter::WildcardFileFilter (const String& fileWildcardPatterns,
  48411. const String& directoryWildcardPatterns,
  48412. const String& description_)
  48413. : FileFilter (description_.isEmpty() ? fileWildcardPatterns
  48414. : (description_ + " (" + fileWildcardPatterns + ")"))
  48415. {
  48416. parse (fileWildcardPatterns, fileWildcards);
  48417. parse (directoryWildcardPatterns, directoryWildcards);
  48418. }
  48419. WildcardFileFilter::~WildcardFileFilter()
  48420. {
  48421. }
  48422. bool WildcardFileFilter::isFileSuitable (const File& file) const
  48423. {
  48424. return match (file, fileWildcards);
  48425. }
  48426. bool WildcardFileFilter::isDirectorySuitable (const File& file) const
  48427. {
  48428. return match (file, directoryWildcards);
  48429. }
  48430. void WildcardFileFilter::parse (const String& pattern, StringArray& result)
  48431. {
  48432. result.addTokens (pattern.toLowerCase(), ";,", "\"'");
  48433. result.trim();
  48434. result.removeEmptyStrings();
  48435. // special case for *.*, because people use it to mean "any file", but it
  48436. // would actually ignore files with no extension.
  48437. for (int i = result.size(); --i >= 0;)
  48438. if (result[i] == "*.*")
  48439. result.set (i, "*");
  48440. }
  48441. bool WildcardFileFilter::match (const File& file, const StringArray& wildcards)
  48442. {
  48443. const String filename (file.getFileName());
  48444. for (int i = wildcards.size(); --i >= 0;)
  48445. if (filename.matchesWildcard (wildcards[i], true))
  48446. return true;
  48447. return false;
  48448. }
  48449. END_JUCE_NAMESPACE
  48450. /*** End of inlined file: juce_WildcardFileFilter.cpp ***/
  48451. /*** Start of inlined file: juce_KeyboardFocusTraverser.cpp ***/
  48452. BEGIN_JUCE_NAMESPACE
  48453. KeyboardFocusTraverser::KeyboardFocusTraverser()
  48454. {
  48455. }
  48456. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  48457. {
  48458. }
  48459. namespace KeyboardFocusHelpers
  48460. {
  48461. // This will sort a set of components, so that they are ordered in terms of
  48462. // left-to-right and then top-to-bottom.
  48463. class ScreenPositionComparator
  48464. {
  48465. public:
  48466. ScreenPositionComparator() {}
  48467. static int compareElements (const Component* const first, const Component* const second)
  48468. {
  48469. int explicitOrder1 = first->getExplicitFocusOrder();
  48470. if (explicitOrder1 <= 0)
  48471. explicitOrder1 = std::numeric_limits<int>::max() / 2;
  48472. int explicitOrder2 = second->getExplicitFocusOrder();
  48473. if (explicitOrder2 <= 0)
  48474. explicitOrder2 = std::numeric_limits<int>::max() / 2;
  48475. if (explicitOrder1 != explicitOrder2)
  48476. return explicitOrder1 - explicitOrder2;
  48477. const int diff = first->getY() - second->getY();
  48478. return (diff == 0) ? first->getX() - second->getX()
  48479. : diff;
  48480. }
  48481. };
  48482. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  48483. {
  48484. if (parent->getNumChildComponents() > 0)
  48485. {
  48486. Array <Component*> localComps;
  48487. ScreenPositionComparator comparator;
  48488. int i;
  48489. for (i = parent->getNumChildComponents(); --i >= 0;)
  48490. {
  48491. Component* const c = parent->getChildComponent (i);
  48492. if (c->isVisible() && c->isEnabled())
  48493. localComps.addSorted (comparator, c);
  48494. }
  48495. for (i = 0; i < localComps.size(); ++i)
  48496. {
  48497. Component* const c = localComps.getUnchecked (i);
  48498. if (c->getWantsKeyboardFocus())
  48499. comps.add (c);
  48500. if (! c->isFocusContainer())
  48501. findAllFocusableComponents (c, comps);
  48502. }
  48503. }
  48504. }
  48505. }
  48506. namespace KeyboardFocusHelpers
  48507. {
  48508. Component* getIncrementedComponent (Component* const current, const int delta)
  48509. {
  48510. Component* focusContainer = current->getParentComponent();
  48511. if (focusContainer != 0)
  48512. {
  48513. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  48514. focusContainer = focusContainer->getParentComponent();
  48515. if (focusContainer != 0)
  48516. {
  48517. Array <Component*> comps;
  48518. KeyboardFocusHelpers::findAllFocusableComponents (focusContainer, comps);
  48519. if (comps.size() > 0)
  48520. {
  48521. const int index = comps.indexOf (current);
  48522. return comps [(index + comps.size() + delta) % comps.size()];
  48523. }
  48524. }
  48525. }
  48526. return 0;
  48527. }
  48528. }
  48529. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  48530. {
  48531. return KeyboardFocusHelpers::getIncrementedComponent (current, 1);
  48532. }
  48533. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  48534. {
  48535. return KeyboardFocusHelpers::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. class KeyMappingChangeButton : public Button
  48559. {
  48560. public:
  48561. KeyMappingChangeButton (KeyMappingEditorComponent& owner_,
  48562. const CommandID commandID_,
  48563. const String& keyName,
  48564. const int keyNum_)
  48565. : Button (keyName),
  48566. owner (owner_),
  48567. commandID (commandID_),
  48568. keyNum (keyNum_)
  48569. {
  48570. setWantsKeyboardFocus (false);
  48571. setTriggeredOnMouseDown (keyNum >= 0);
  48572. setTooltip (keyNum_ < 0 ? TRANS("adds a new key-mapping")
  48573. : TRANS("click to change this key-mapping"));
  48574. }
  48575. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/)
  48576. {
  48577. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  48578. keyNum >= 0 ? getName() : String::empty);
  48579. }
  48580. void clicked()
  48581. {
  48582. if (keyNum >= 0)
  48583. {
  48584. // existing key clicked..
  48585. PopupMenu m;
  48586. m.addItem (1, TRANS("change this key-mapping"));
  48587. m.addSeparator();
  48588. m.addItem (2, TRANS("remove this key-mapping"));
  48589. const int res = m.show();
  48590. if (res == 1)
  48591. {
  48592. owner.assignNewKey (commandID, keyNum);
  48593. }
  48594. else if (res == 2)
  48595. {
  48596. owner.getMappings()->removeKeyPress (commandID, keyNum);
  48597. }
  48598. }
  48599. else
  48600. {
  48601. // + button pressed..
  48602. owner.assignNewKey (commandID, -1);
  48603. }
  48604. }
  48605. void fitToContent (const int h) throw()
  48606. {
  48607. if (keyNum < 0)
  48608. {
  48609. setSize (h, h);
  48610. }
  48611. else
  48612. {
  48613. Font f (h * 0.6f);
  48614. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  48615. }
  48616. }
  48617. juce_UseDebuggingNewOperator
  48618. private:
  48619. KeyMappingEditorComponent& owner;
  48620. const CommandID commandID;
  48621. const int keyNum;
  48622. KeyMappingChangeButton (const KeyMappingChangeButton&);
  48623. KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  48624. };
  48625. class KeyMappingItemComponent : public Component
  48626. {
  48627. public:
  48628. KeyMappingItemComponent (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48629. : owner (owner_), commandID (commandID_)
  48630. {
  48631. setInterceptsMouseClicks (false, true);
  48632. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  48633. const Array <KeyPress> keyPresses (owner.getMappings()->getKeyPressesAssignedToCommand (commandID));
  48634. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  48635. {
  48636. KeyMappingChangeButton* const kb
  48637. = new KeyMappingChangeButton (owner, commandID,
  48638. owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  48639. kb->setEnabled (! isReadOnly);
  48640. addAndMakeVisible (kb);
  48641. }
  48642. KeyMappingChangeButton* const kb
  48643. = new KeyMappingChangeButton (owner, commandID, String::empty, -1);
  48644. addChildComponent (kb);
  48645. kb->setVisible (keyPresses.size() < (int) maxNumAssignments && ! isReadOnly);
  48646. }
  48647. ~KeyMappingItemComponent()
  48648. {
  48649. deleteAllChildren();
  48650. }
  48651. void paint (Graphics& g)
  48652. {
  48653. g.setFont (getHeight() * 0.7f);
  48654. g.setColour (findColour (KeyMappingEditorComponent::textColourId));
  48655. g.drawFittedText (owner.getMappings()->getCommandManager()->getNameOfCommand (commandID),
  48656. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  48657. Justification::centredLeft, true);
  48658. }
  48659. void resized()
  48660. {
  48661. int x = getWidth() - 4;
  48662. for (int i = getNumChildComponents(); --i >= 0;)
  48663. {
  48664. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  48665. kb->fitToContent (getHeight() - 2);
  48666. kb->setTopRightPosition (x, 1);
  48667. x -= kb->getWidth() + 5;
  48668. }
  48669. }
  48670. enum { maxNumAssignments = 3 };
  48671. juce_UseDebuggingNewOperator
  48672. private:
  48673. KeyMappingEditorComponent& owner;
  48674. const CommandID commandID;
  48675. KeyMappingItemComponent (const KeyMappingItemComponent&);
  48676. KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  48677. };
  48678. class KeyMappingTreeViewItem : public TreeViewItem
  48679. {
  48680. public:
  48681. KeyMappingTreeViewItem (KeyMappingEditorComponent& owner_, const CommandID commandID_)
  48682. : owner (owner_), commandID (commandID_)
  48683. {
  48684. }
  48685. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  48686. bool mightContainSubItems() { return false; }
  48687. int getItemHeight() const { return 20; }
  48688. Component* createItemComponent()
  48689. {
  48690. return new KeyMappingItemComponent (owner, commandID);
  48691. }
  48692. juce_UseDebuggingNewOperator
  48693. private:
  48694. KeyMappingEditorComponent& owner;
  48695. const CommandID commandID;
  48696. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  48697. KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  48698. };
  48699. class KeyCategoryTreeViewItem : public TreeViewItem
  48700. {
  48701. public:
  48702. KeyCategoryTreeViewItem (KeyMappingEditorComponent& owner_, const String& name)
  48703. : owner (owner_), categoryName (name)
  48704. {
  48705. }
  48706. const String getUniqueName() const { return categoryName + "_cat"; }
  48707. bool mightContainSubItems() { return true; }
  48708. int getItemHeight() const { return 28; }
  48709. void paintItem (Graphics& g, int width, int height)
  48710. {
  48711. g.setFont (height * 0.6f, Font::bold);
  48712. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  48713. g.drawText (categoryName,
  48714. 2, 0, width - 2, height,
  48715. Justification::centredLeft, true);
  48716. }
  48717. void itemOpennessChanged (bool isNowOpen)
  48718. {
  48719. if (isNowOpen)
  48720. {
  48721. if (getNumSubItems() == 0)
  48722. {
  48723. Array <CommandID> commands (owner.getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  48724. for (int i = 0; i < commands.size(); ++i)
  48725. {
  48726. if (owner.shouldCommandBeIncluded (commands[i]))
  48727. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  48728. }
  48729. }
  48730. }
  48731. else
  48732. {
  48733. clearSubItems();
  48734. }
  48735. }
  48736. juce_UseDebuggingNewOperator
  48737. private:
  48738. KeyMappingEditorComponent& owner;
  48739. String categoryName;
  48740. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  48741. KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  48742. };
  48743. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  48744. const bool showResetToDefaultButton)
  48745. : mappings (mappingManager),
  48746. resetButton (TRANS ("reset to defaults"))
  48747. {
  48748. jassert (mappingManager != 0); // can't be null!
  48749. mappingManager->addChangeListener (this);
  48750. setLinesDrawnForSubItems (false);
  48751. if (showResetToDefaultButton)
  48752. {
  48753. addAndMakeVisible (&resetButton);
  48754. resetButton.addButtonListener (this);
  48755. }
  48756. addAndMakeVisible (&tree);
  48757. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  48758. tree.setRootItemVisible (false);
  48759. tree.setDefaultOpenness (true);
  48760. tree.setRootItem (this);
  48761. }
  48762. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  48763. {
  48764. mappings->removeChangeListener (this);
  48765. }
  48766. bool KeyMappingEditorComponent::mightContainSubItems()
  48767. {
  48768. return true;
  48769. }
  48770. const String KeyMappingEditorComponent::getUniqueName() const
  48771. {
  48772. return "keys";
  48773. }
  48774. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  48775. const Colour& textColour)
  48776. {
  48777. setColour (backgroundColourId, mainBackground);
  48778. setColour (textColourId, textColour);
  48779. tree.setColour (TreeView::backgroundColourId, mainBackground);
  48780. }
  48781. void KeyMappingEditorComponent::parentHierarchyChanged()
  48782. {
  48783. changeListenerCallback (0);
  48784. }
  48785. void KeyMappingEditorComponent::resized()
  48786. {
  48787. int h = getHeight();
  48788. if (resetButton.isVisible())
  48789. {
  48790. const int buttonHeight = 20;
  48791. h -= buttonHeight + 8;
  48792. int x = getWidth() - 8;
  48793. resetButton.changeWidthToFitText (buttonHeight);
  48794. resetButton.setTopRightPosition (x, h + 6);
  48795. }
  48796. tree.setBounds (0, 0, getWidth(), h);
  48797. }
  48798. void KeyMappingEditorComponent::buttonClicked (Button* button)
  48799. {
  48800. if (button == &resetButton)
  48801. {
  48802. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  48803. TRANS("Reset to defaults"),
  48804. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  48805. TRANS("Reset")))
  48806. {
  48807. mappings->resetToDefaultMappings();
  48808. }
  48809. }
  48810. }
  48811. void KeyMappingEditorComponent::changeListenerCallback (void*)
  48812. {
  48813. ScopedPointer <XmlElement> oldOpenness (tree.getOpennessState (true));
  48814. clearSubItems();
  48815. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  48816. for (int i = 0; i < categories.size(); ++i)
  48817. {
  48818. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  48819. int count = 0;
  48820. for (int j = 0; j < commands.size(); ++j)
  48821. if (shouldCommandBeIncluded (commands[j]))
  48822. ++count;
  48823. if (count > 0)
  48824. addSubItem (new KeyCategoryTreeViewItem (*this, categories[i]));
  48825. }
  48826. if (oldOpenness != 0)
  48827. tree.restoreOpennessState (*oldOpenness);
  48828. }
  48829. class KeyEntryWindow : public AlertWindow
  48830. {
  48831. public:
  48832. KeyEntryWindow (KeyMappingEditorComponent& owner_)
  48833. : AlertWindow (TRANS("New key-mapping"),
  48834. TRANS("Please press a key combination now..."),
  48835. AlertWindow::NoIcon),
  48836. owner (owner_)
  48837. {
  48838. addButton (TRANS("ok"), 1);
  48839. addButton (TRANS("cancel"), 0);
  48840. // (avoid return + escape keys getting processed by the buttons..)
  48841. for (int i = getNumChildComponents(); --i >= 0;)
  48842. getChildComponent (i)->setWantsKeyboardFocus (false);
  48843. setWantsKeyboardFocus (true);
  48844. grabKeyboardFocus();
  48845. }
  48846. ~KeyEntryWindow()
  48847. {
  48848. }
  48849. bool keyPressed (const KeyPress& key)
  48850. {
  48851. lastPress = key;
  48852. String message (TRANS("Key: ") + owner.getDescriptionForKeyPress (key));
  48853. const CommandID previousCommand = owner.getMappings()->findCommandForKeyPress (key);
  48854. if (previousCommand != 0)
  48855. {
  48856. message << "\n\n"
  48857. << TRANS("(Currently assigned to \"")
  48858. << owner.getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  48859. << "\")";
  48860. }
  48861. setMessage (message);
  48862. return true;
  48863. }
  48864. bool keyStateChanged (bool)
  48865. {
  48866. return true;
  48867. }
  48868. KeyPress lastPress;
  48869. juce_UseDebuggingNewOperator
  48870. private:
  48871. KeyMappingEditorComponent& owner;
  48872. KeyEntryWindow (const KeyEntryWindow&);
  48873. KeyEntryWindow& operator= (const KeyEntryWindow&);
  48874. };
  48875. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  48876. {
  48877. KeyEntryWindow entryWindow (*this);
  48878. if (entryWindow.runModalLoop() != 0)
  48879. {
  48880. entryWindow.setVisible (false);
  48881. if (entryWindow.lastPress.isValid())
  48882. {
  48883. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  48884. if (previousCommand != 0)
  48885. {
  48886. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  48887. TRANS("Change key-mapping"),
  48888. TRANS("This key is already assigned to the command \"")
  48889. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  48890. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  48891. TRANS("re-assign"),
  48892. TRANS("cancel")))
  48893. {
  48894. return;
  48895. }
  48896. }
  48897. mappings->removeKeyPress (entryWindow.lastPress);
  48898. if (index >= 0)
  48899. mappings->removeKeyPress (commandID, index);
  48900. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  48901. }
  48902. }
  48903. }
  48904. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  48905. {
  48906. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48907. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  48908. }
  48909. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  48910. {
  48911. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  48912. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  48913. }
  48914. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  48915. {
  48916. return key.getTextDescription();
  48917. }
  48918. END_JUCE_NAMESPACE
  48919. /*** End of inlined file: juce_KeyMappingEditorComponent.cpp ***/
  48920. /*** Start of inlined file: juce_KeyPress.cpp ***/
  48921. BEGIN_JUCE_NAMESPACE
  48922. KeyPress::KeyPress() throw()
  48923. : keyCode (0),
  48924. mods (0),
  48925. textCharacter (0)
  48926. {
  48927. }
  48928. KeyPress::KeyPress (const int keyCode_,
  48929. const ModifierKeys& mods_,
  48930. const juce_wchar textCharacter_) throw()
  48931. : keyCode (keyCode_),
  48932. mods (mods_),
  48933. textCharacter (textCharacter_)
  48934. {
  48935. }
  48936. KeyPress::KeyPress (const int keyCode_) throw()
  48937. : keyCode (keyCode_),
  48938. textCharacter (0)
  48939. {
  48940. }
  48941. KeyPress::KeyPress (const KeyPress& other) throw()
  48942. : keyCode (other.keyCode),
  48943. mods (other.mods),
  48944. textCharacter (other.textCharacter)
  48945. {
  48946. }
  48947. KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  48948. {
  48949. keyCode = other.keyCode;
  48950. mods = other.mods;
  48951. textCharacter = other.textCharacter;
  48952. return *this;
  48953. }
  48954. bool KeyPress::operator== (const KeyPress& other) const throw()
  48955. {
  48956. return mods.getRawFlags() == other.mods.getRawFlags()
  48957. && (textCharacter == other.textCharacter
  48958. || textCharacter == 0
  48959. || other.textCharacter == 0)
  48960. && (keyCode == other.keyCode
  48961. || (keyCode < 256
  48962. && other.keyCode < 256
  48963. && CharacterFunctions::toLowerCase ((juce_wchar) keyCode)
  48964. == CharacterFunctions::toLowerCase ((juce_wchar) other.keyCode)));
  48965. }
  48966. bool KeyPress::operator!= (const KeyPress& other) const throw()
  48967. {
  48968. return ! operator== (other);
  48969. }
  48970. bool KeyPress::isCurrentlyDown() const
  48971. {
  48972. return isKeyCurrentlyDown (keyCode)
  48973. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  48974. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  48975. }
  48976. namespace KeyPressHelpers
  48977. {
  48978. struct KeyNameAndCode
  48979. {
  48980. const char* name;
  48981. int code;
  48982. };
  48983. static const KeyNameAndCode translations[] =
  48984. {
  48985. { "spacebar", KeyPress::spaceKey },
  48986. { "return", KeyPress::returnKey },
  48987. { "escape", KeyPress::escapeKey },
  48988. { "backspace", KeyPress::backspaceKey },
  48989. { "cursor left", KeyPress::leftKey },
  48990. { "cursor right", KeyPress::rightKey },
  48991. { "cursor up", KeyPress::upKey },
  48992. { "cursor down", KeyPress::downKey },
  48993. { "page up", KeyPress::pageUpKey },
  48994. { "page down", KeyPress::pageDownKey },
  48995. { "home", KeyPress::homeKey },
  48996. { "end", KeyPress::endKey },
  48997. { "delete", KeyPress::deleteKey },
  48998. { "insert", KeyPress::insertKey },
  48999. { "tab", KeyPress::tabKey },
  49000. { "play", KeyPress::playKey },
  49001. { "stop", KeyPress::stopKey },
  49002. { "fast forward", KeyPress::fastForwardKey },
  49003. { "rewind", KeyPress::rewindKey }
  49004. };
  49005. static const String numberPadPrefix() { return "numpad "; }
  49006. }
  49007. const KeyPress KeyPress::createFromDescription (const String& desc)
  49008. {
  49009. int modifiers = 0;
  49010. if (desc.containsWholeWordIgnoreCase ("ctrl")
  49011. || desc.containsWholeWordIgnoreCase ("control")
  49012. || desc.containsWholeWordIgnoreCase ("ctl"))
  49013. modifiers |= ModifierKeys::ctrlModifier;
  49014. if (desc.containsWholeWordIgnoreCase ("shift")
  49015. || desc.containsWholeWordIgnoreCase ("shft"))
  49016. modifiers |= ModifierKeys::shiftModifier;
  49017. if (desc.containsWholeWordIgnoreCase ("alt")
  49018. || desc.containsWholeWordIgnoreCase ("option"))
  49019. modifiers |= ModifierKeys::altModifier;
  49020. if (desc.containsWholeWordIgnoreCase ("command")
  49021. || desc.containsWholeWordIgnoreCase ("cmd"))
  49022. modifiers |= ModifierKeys::commandModifier;
  49023. int key = 0;
  49024. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49025. {
  49026. if (desc.containsWholeWordIgnoreCase (String (KeyPressHelpers::translations[i].name)))
  49027. {
  49028. key = KeyPressHelpers::translations[i].code;
  49029. break;
  49030. }
  49031. }
  49032. if (key == 0)
  49033. {
  49034. // see if it's a numpad key..
  49035. if (desc.containsIgnoreCase (KeyPressHelpers::numberPadPrefix()))
  49036. {
  49037. const juce_wchar lastChar = desc.trimEnd().getLastCharacter();
  49038. if (lastChar >= '0' && lastChar <= '9')
  49039. key = numberPad0 + lastChar - '0';
  49040. else if (lastChar == '+')
  49041. key = numberPadAdd;
  49042. else if (lastChar == '-')
  49043. key = numberPadSubtract;
  49044. else if (lastChar == '*')
  49045. key = numberPadMultiply;
  49046. else if (lastChar == '/')
  49047. key = numberPadDivide;
  49048. else if (lastChar == '.')
  49049. key = numberPadDecimalPoint;
  49050. else if (lastChar == '=')
  49051. key = numberPadEquals;
  49052. else if (desc.endsWith ("separator"))
  49053. key = numberPadSeparator;
  49054. else if (desc.endsWith ("delete"))
  49055. key = numberPadDelete;
  49056. }
  49057. if (key == 0)
  49058. {
  49059. // see if it's a function key..
  49060. if (! desc.containsChar ('#')) // avoid mistaking hex-codes like "#f1"
  49061. for (int i = 1; i <= 12; ++i)
  49062. if (desc.containsWholeWordIgnoreCase ("f" + String (i)))
  49063. key = F1Key + i - 1;
  49064. if (key == 0)
  49065. {
  49066. // give up and use the hex code..
  49067. const int hexCode = desc.fromFirstOccurrenceOf ("#", false, false)
  49068. .toLowerCase()
  49069. .retainCharacters ("0123456789abcdef")
  49070. .getHexValue32();
  49071. if (hexCode > 0)
  49072. key = hexCode;
  49073. else
  49074. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  49075. }
  49076. }
  49077. }
  49078. return KeyPress (key, ModifierKeys (modifiers), 0);
  49079. }
  49080. const String KeyPress::getTextDescription() const
  49081. {
  49082. String desc;
  49083. if (keyCode > 0)
  49084. {
  49085. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  49086. // want to store it as being a slash, not shift+whatever.
  49087. if (textCharacter == '/')
  49088. return "/";
  49089. if (mods.isCtrlDown())
  49090. desc << "ctrl + ";
  49091. if (mods.isShiftDown())
  49092. desc << "shift + ";
  49093. #if JUCE_MAC
  49094. // only do this on the mac, because on Windows ctrl and command are the same,
  49095. // and this would get confusing
  49096. if (mods.isCommandDown())
  49097. desc << "command + ";
  49098. if (mods.isAltDown())
  49099. desc << "option + ";
  49100. #else
  49101. if (mods.isAltDown())
  49102. desc << "alt + ";
  49103. #endif
  49104. for (int i = 0; i < numElementsInArray (KeyPressHelpers::translations); ++i)
  49105. if (keyCode == KeyPressHelpers::translations[i].code)
  49106. return desc + KeyPressHelpers::translations[i].name;
  49107. if (keyCode >= F1Key && keyCode <= F16Key)
  49108. desc << 'F' << (1 + keyCode - F1Key);
  49109. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  49110. desc << KeyPressHelpers::numberPadPrefix() << (keyCode - numberPad0);
  49111. else if (keyCode >= 33 && keyCode < 176)
  49112. desc += CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  49113. else if (keyCode == numberPadAdd)
  49114. desc << KeyPressHelpers::numberPadPrefix() << '+';
  49115. else if (keyCode == numberPadSubtract)
  49116. desc << KeyPressHelpers::numberPadPrefix() << '-';
  49117. else if (keyCode == numberPadMultiply)
  49118. desc << KeyPressHelpers::numberPadPrefix() << '*';
  49119. else if (keyCode == numberPadDivide)
  49120. desc << KeyPressHelpers::numberPadPrefix() << '/';
  49121. else if (keyCode == numberPadSeparator)
  49122. desc << KeyPressHelpers::numberPadPrefix() << "separator";
  49123. else if (keyCode == numberPadDecimalPoint)
  49124. desc << KeyPressHelpers::numberPadPrefix() << '.';
  49125. else if (keyCode == numberPadDelete)
  49126. desc << KeyPressHelpers::numberPadPrefix() << "delete";
  49127. else
  49128. desc << '#' << String::toHexString (keyCode);
  49129. }
  49130. return desc;
  49131. }
  49132. END_JUCE_NAMESPACE
  49133. /*** End of inlined file: juce_KeyPress.cpp ***/
  49134. /*** Start of inlined file: juce_KeyPressMappingSet.cpp ***/
  49135. BEGIN_JUCE_NAMESPACE
  49136. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_)
  49137. : commandManager (commandManager_)
  49138. {
  49139. // A manager is needed to get the descriptions of commands, and will be called when
  49140. // a command is invoked. So you can't leave this null..
  49141. jassert (commandManager_ != 0);
  49142. Desktop::getInstance().addFocusChangeListener (this);
  49143. }
  49144. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other)
  49145. : commandManager (other.commandManager)
  49146. {
  49147. Desktop::getInstance().addFocusChangeListener (this);
  49148. }
  49149. KeyPressMappingSet::~KeyPressMappingSet()
  49150. {
  49151. Desktop::getInstance().removeFocusChangeListener (this);
  49152. }
  49153. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const
  49154. {
  49155. for (int i = 0; i < mappings.size(); ++i)
  49156. if (mappings.getUnchecked(i)->commandID == commandID)
  49157. return mappings.getUnchecked (i)->keypresses;
  49158. return Array <KeyPress> ();
  49159. }
  49160. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  49161. const KeyPress& newKeyPress,
  49162. int insertIndex)
  49163. {
  49164. // If you specify an upper-case letter but no shift key, how is the user supposed to press it!?
  49165. // Stick to lower-case letters when defining a keypress, to avoid ambiguity.
  49166. jassert (! (CharacterFunctions::isUpperCase (newKeyPress.getTextCharacter())
  49167. && ! newKeyPress.getModifiers().isShiftDown()));
  49168. if (findCommandForKeyPress (newKeyPress) != commandID)
  49169. {
  49170. removeKeyPress (newKeyPress);
  49171. if (newKeyPress.isValid())
  49172. {
  49173. for (int i = mappings.size(); --i >= 0;)
  49174. {
  49175. if (mappings.getUnchecked(i)->commandID == commandID)
  49176. {
  49177. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  49178. sendChangeMessage (this);
  49179. return;
  49180. }
  49181. }
  49182. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49183. if (ci != 0)
  49184. {
  49185. CommandMapping* const cm = new CommandMapping();
  49186. cm->commandID = commandID;
  49187. cm->keypresses.add (newKeyPress);
  49188. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  49189. mappings.add (cm);
  49190. sendChangeMessage (this);
  49191. }
  49192. }
  49193. }
  49194. }
  49195. void KeyPressMappingSet::resetToDefaultMappings()
  49196. {
  49197. mappings.clear();
  49198. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  49199. {
  49200. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  49201. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49202. {
  49203. addKeyPress (ci->commandID,
  49204. ci->defaultKeypresses.getReference (j));
  49205. }
  49206. }
  49207. sendChangeMessage (this);
  49208. }
  49209. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID)
  49210. {
  49211. clearAllKeyPresses (commandID);
  49212. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49213. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  49214. {
  49215. addKeyPress (ci->commandID,
  49216. ci->defaultKeypresses.getReference (j));
  49217. }
  49218. }
  49219. void KeyPressMappingSet::clearAllKeyPresses()
  49220. {
  49221. if (mappings.size() > 0)
  49222. {
  49223. sendChangeMessage (this);
  49224. mappings.clear();
  49225. }
  49226. }
  49227. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID)
  49228. {
  49229. for (int i = mappings.size(); --i >= 0;)
  49230. {
  49231. if (mappings.getUnchecked(i)->commandID == commandID)
  49232. {
  49233. mappings.remove (i);
  49234. sendChangeMessage (this);
  49235. }
  49236. }
  49237. }
  49238. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress)
  49239. {
  49240. if (keypress.isValid())
  49241. {
  49242. for (int i = mappings.size(); --i >= 0;)
  49243. {
  49244. CommandMapping* const cm = mappings.getUnchecked(i);
  49245. for (int j = cm->keypresses.size(); --j >= 0;)
  49246. {
  49247. if (keypress == cm->keypresses [j])
  49248. {
  49249. cm->keypresses.remove (j);
  49250. sendChangeMessage (this);
  49251. }
  49252. }
  49253. }
  49254. }
  49255. }
  49256. void KeyPressMappingSet::removeKeyPress (const CommandID commandID, const int keyPressIndex)
  49257. {
  49258. for (int i = mappings.size(); --i >= 0;)
  49259. {
  49260. if (mappings.getUnchecked(i)->commandID == commandID)
  49261. {
  49262. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  49263. sendChangeMessage (this);
  49264. break;
  49265. }
  49266. }
  49267. }
  49268. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  49269. {
  49270. for (int i = 0; i < mappings.size(); ++i)
  49271. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  49272. return mappings.getUnchecked(i)->commandID;
  49273. return 0;
  49274. }
  49275. bool KeyPressMappingSet::containsMapping (const CommandID commandID, const KeyPress& keyPress) const throw()
  49276. {
  49277. for (int i = mappings.size(); --i >= 0;)
  49278. if (mappings.getUnchecked(i)->commandID == commandID)
  49279. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  49280. return false;
  49281. }
  49282. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  49283. const KeyPress& key,
  49284. const bool isKeyDown,
  49285. const int millisecsSinceKeyPressed,
  49286. Component* const originatingComponent) const
  49287. {
  49288. ApplicationCommandTarget::InvocationInfo info (commandID);
  49289. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  49290. info.isKeyDown = isKeyDown;
  49291. info.keyPress = key;
  49292. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  49293. info.originatingComponent = originatingComponent;
  49294. commandManager->invoke (info, false);
  49295. }
  49296. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  49297. {
  49298. if (xmlVersion.hasTagName ("KEYMAPPINGS"))
  49299. {
  49300. if (xmlVersion.getBoolAttribute ("basedOnDefaults", true))
  49301. {
  49302. // if the XML was created as a set of differences from the default mappings,
  49303. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  49304. resetToDefaultMappings();
  49305. }
  49306. else
  49307. {
  49308. // if the XML was created calling createXml (false), then we need to clear all
  49309. // the keys and treat the xml as describing the entire set of mappings.
  49310. clearAllKeyPresses();
  49311. }
  49312. forEachXmlChildElement (xmlVersion, map)
  49313. {
  49314. const CommandID commandId = map->getStringAttribute ("commandId").getHexValue32();
  49315. if (commandId != 0)
  49316. {
  49317. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute ("key")));
  49318. if (map->hasTagName ("MAPPING"))
  49319. {
  49320. addKeyPress (commandId, key);
  49321. }
  49322. else if (map->hasTagName ("UNMAPPING"))
  49323. {
  49324. if (containsMapping (commandId, key))
  49325. removeKeyPress (key);
  49326. }
  49327. }
  49328. }
  49329. return true;
  49330. }
  49331. return false;
  49332. }
  49333. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  49334. {
  49335. ScopedPointer <KeyPressMappingSet> defaultSet;
  49336. if (saveDifferencesFromDefaultSet)
  49337. {
  49338. defaultSet = new KeyPressMappingSet (commandManager);
  49339. defaultSet->resetToDefaultMappings();
  49340. }
  49341. XmlElement* const doc = new XmlElement ("KEYMAPPINGS");
  49342. doc->setAttribute ("basedOnDefaults", saveDifferencesFromDefaultSet);
  49343. int i;
  49344. for (i = 0; i < mappings.size(); ++i)
  49345. {
  49346. const CommandMapping* const cm = mappings.getUnchecked(i);
  49347. for (int j = 0; j < cm->keypresses.size(); ++j)
  49348. {
  49349. if (defaultSet == 0
  49350. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49351. {
  49352. XmlElement* const map = doc->createNewChildElement ("MAPPING");
  49353. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49354. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49355. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49356. }
  49357. }
  49358. }
  49359. if (defaultSet != 0)
  49360. {
  49361. for (i = 0; i < defaultSet->mappings.size(); ++i)
  49362. {
  49363. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  49364. for (int j = 0; j < cm->keypresses.size(); ++j)
  49365. {
  49366. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  49367. {
  49368. XmlElement* const map = doc->createNewChildElement ("UNMAPPING");
  49369. map->setAttribute ("commandId", String::toHexString ((int) cm->commandID));
  49370. map->setAttribute ("description", commandManager->getDescriptionOfCommand (cm->commandID));
  49371. map->setAttribute ("key", cm->keypresses.getReference (j).getTextDescription());
  49372. }
  49373. }
  49374. }
  49375. }
  49376. return doc;
  49377. }
  49378. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  49379. Component* originatingComponent)
  49380. {
  49381. bool used = false;
  49382. const CommandID commandID = findCommandForKeyPress (key);
  49383. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  49384. if (ci != 0
  49385. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  49386. {
  49387. ApplicationCommandInfo info (0);
  49388. if (commandManager->getTargetForCommand (commandID, info) != 0
  49389. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  49390. {
  49391. invokeCommand (commandID, key, true, 0, originatingComponent);
  49392. used = true;
  49393. }
  49394. else
  49395. {
  49396. if (originatingComponent != 0)
  49397. originatingComponent->getLookAndFeel().playAlertSound();
  49398. }
  49399. }
  49400. return used;
  49401. }
  49402. bool KeyPressMappingSet::keyStateChanged (const bool /*isKeyDown*/, Component* originatingComponent)
  49403. {
  49404. bool used = false;
  49405. const uint32 now = Time::getMillisecondCounter();
  49406. for (int i = mappings.size(); --i >= 0;)
  49407. {
  49408. CommandMapping* const cm = mappings.getUnchecked(i);
  49409. if (cm->wantsKeyUpDownCallbacks)
  49410. {
  49411. for (int j = cm->keypresses.size(); --j >= 0;)
  49412. {
  49413. const KeyPress key (cm->keypresses.getReference (j));
  49414. const bool isDown = key.isCurrentlyDown();
  49415. int keyPressEntryIndex = 0;
  49416. bool wasDown = false;
  49417. for (int k = keysDown.size(); --k >= 0;)
  49418. {
  49419. if (key == keysDown.getUnchecked(k)->key)
  49420. {
  49421. keyPressEntryIndex = k;
  49422. wasDown = true;
  49423. used = true;
  49424. break;
  49425. }
  49426. }
  49427. if (isDown != wasDown)
  49428. {
  49429. int millisecs = 0;
  49430. if (isDown)
  49431. {
  49432. KeyPressTime* const k = new KeyPressTime();
  49433. k->key = key;
  49434. k->timeWhenPressed = now;
  49435. keysDown.add (k);
  49436. }
  49437. else
  49438. {
  49439. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  49440. if (now > pressTime)
  49441. millisecs = now - pressTime;
  49442. keysDown.remove (keyPressEntryIndex);
  49443. }
  49444. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  49445. used = true;
  49446. }
  49447. }
  49448. }
  49449. }
  49450. return used;
  49451. }
  49452. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  49453. {
  49454. if (focusedComponent != 0)
  49455. focusedComponent->keyStateChanged (false);
  49456. }
  49457. END_JUCE_NAMESPACE
  49458. /*** End of inlined file: juce_KeyPressMappingSet.cpp ***/
  49459. /*** Start of inlined file: juce_ModifierKeys.cpp ***/
  49460. BEGIN_JUCE_NAMESPACE
  49461. ModifierKeys::ModifierKeys (const int flags_) throw()
  49462. : flags (flags_)
  49463. {
  49464. }
  49465. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  49466. : flags (other.flags)
  49467. {
  49468. }
  49469. ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  49470. {
  49471. flags = other.flags;
  49472. return *this;
  49473. }
  49474. ModifierKeys ModifierKeys::currentModifiers;
  49475. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  49476. {
  49477. return currentModifiers;
  49478. }
  49479. int ModifierKeys::getNumMouseButtonsDown() const throw()
  49480. {
  49481. int num = 0;
  49482. if (isLeftButtonDown()) ++num;
  49483. if (isRightButtonDown()) ++num;
  49484. if (isMiddleButtonDown()) ++num;
  49485. return num;
  49486. }
  49487. END_JUCE_NAMESPACE
  49488. /*** End of inlined file: juce_ModifierKeys.cpp ***/
  49489. /*** Start of inlined file: juce_ComponentAnimator.cpp ***/
  49490. BEGIN_JUCE_NAMESPACE
  49491. class ComponentAnimator::AnimationTask
  49492. {
  49493. public:
  49494. AnimationTask (Component* const comp)
  49495. : component (comp)
  49496. {
  49497. }
  49498. void reset (const Rectangle<int>& finalBounds,
  49499. float finalAlpha,
  49500. int millisecondsToSpendMoving,
  49501. bool useProxyComponent,
  49502. double startSpeed_, double endSpeed_)
  49503. {
  49504. msElapsed = 0;
  49505. msTotal = jmax (1, millisecondsToSpendMoving);
  49506. lastProgress = 0;
  49507. destination = finalBounds;
  49508. destAlpha = finalAlpha;
  49509. isMoving = (finalBounds != component->getBounds());
  49510. isChangingAlpha = (finalAlpha != component->getAlpha());
  49511. left = component->getX();
  49512. top = component->getY();
  49513. right = component->getRight();
  49514. bottom = component->getBottom();
  49515. alpha = component->getAlpha();
  49516. const double invTotalDistance = 4.0 / (startSpeed_ + endSpeed_ + 2.0);
  49517. startSpeed = jmax (0.0, startSpeed_ * invTotalDistance);
  49518. midSpeed = invTotalDistance;
  49519. endSpeed = jmax (0.0, endSpeed_ * invTotalDistance);
  49520. if (useProxyComponent)
  49521. proxy = new ProxyComponent (*component);
  49522. else
  49523. proxy = 0;
  49524. component->setVisible (! useProxyComponent);
  49525. }
  49526. bool useTimeslice (const int elapsed)
  49527. {
  49528. Component* const c = proxy != 0 ? static_cast <Component*> (proxy)
  49529. : static_cast <Component*> (component);
  49530. if (c != 0)
  49531. {
  49532. msElapsed += elapsed;
  49533. double newProgress = msElapsed / (double) msTotal;
  49534. if (newProgress >= 0 && newProgress < 1.0)
  49535. {
  49536. newProgress = timeToDistance (newProgress);
  49537. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  49538. jassert (newProgress >= lastProgress);
  49539. lastProgress = newProgress;
  49540. if (delta < 1.0)
  49541. {
  49542. bool stillBusy = false;
  49543. if (isMoving)
  49544. {
  49545. left += (destination.getX() - left) * delta;
  49546. top += (destination.getY() - top) * delta;
  49547. right += (destination.getRight() - right) * delta;
  49548. bottom += (destination.getBottom() - bottom) * delta;
  49549. const Rectangle<int> newBounds (roundToInt (left),
  49550. roundToInt (top),
  49551. roundToInt (right - left),
  49552. roundToInt (bottom - top));
  49553. if (newBounds != destination)
  49554. {
  49555. c->setBounds (newBounds);
  49556. stillBusy = true;
  49557. }
  49558. }
  49559. if (isChangingAlpha)
  49560. {
  49561. alpha += (destAlpha - alpha) * delta;
  49562. c->setAlpha ((float) alpha);
  49563. stillBusy = true;
  49564. }
  49565. if (stillBusy)
  49566. return true;
  49567. }
  49568. }
  49569. }
  49570. moveToFinalDestination();
  49571. return false;
  49572. }
  49573. void moveToFinalDestination()
  49574. {
  49575. if (component != 0)
  49576. {
  49577. component->setAlpha ((float) destAlpha);
  49578. component->setBounds (destination);
  49579. }
  49580. }
  49581. class ProxyComponent : public Component
  49582. {
  49583. public:
  49584. ProxyComponent (Component& component)
  49585. : image (component.createComponentSnapshot (component.getLocalBounds()))
  49586. {
  49587. setBounds (component.getBounds());
  49588. setAlpha (component.getAlpha());
  49589. setInterceptsMouseClicks (false, false);
  49590. Component* const parent = component.getParentComponent();
  49591. if (parent != 0)
  49592. parent->addAndMakeVisible (this);
  49593. else if (component.isOnDesktop() && component.getPeer() != 0)
  49594. addToDesktop (component.getPeer()->getStyleFlags());
  49595. else
  49596. jassertfalse; // seem to be trying to animate a component that's not visible..
  49597. setVisible (true);
  49598. toBehind (&component);
  49599. }
  49600. void paint (Graphics& g)
  49601. {
  49602. g.setOpacity (1.0f);
  49603. g.drawImage (image, 0, 0, getWidth(), getHeight(),
  49604. 0, 0, image.getWidth(), image.getHeight());
  49605. }
  49606. juce_UseDebuggingNewOperator
  49607. private:
  49608. Image image;
  49609. ProxyComponent (const ProxyComponent&);
  49610. ProxyComponent& operator= (const ProxyComponent&);
  49611. };
  49612. Component::SafePointer<Component> component;
  49613. ScopedPointer<Component> proxy;
  49614. Rectangle<int> destination;
  49615. double destAlpha;
  49616. int msElapsed, msTotal;
  49617. double startSpeed, midSpeed, endSpeed, lastProgress;
  49618. double left, top, right, bottom, alpha;
  49619. bool isMoving, isChangingAlpha;
  49620. private:
  49621. double timeToDistance (const double time) const throw()
  49622. {
  49623. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  49624. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  49625. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  49626. }
  49627. };
  49628. ComponentAnimator::ComponentAnimator()
  49629. : lastTime (0)
  49630. {
  49631. }
  49632. ComponentAnimator::~ComponentAnimator()
  49633. {
  49634. }
  49635. ComponentAnimator::AnimationTask* ComponentAnimator::findTaskFor (Component* const component) const
  49636. {
  49637. for (int i = tasks.size(); --i >= 0;)
  49638. if (component == tasks.getUnchecked(i)->component.getComponent())
  49639. return tasks.getUnchecked(i);
  49640. return 0;
  49641. }
  49642. void ComponentAnimator::animateComponent (Component* const component,
  49643. const Rectangle<int>& finalBounds,
  49644. const float finalAlpha,
  49645. const int millisecondsToSpendMoving,
  49646. const bool useProxyComponent,
  49647. const double startSpeed,
  49648. const double endSpeed)
  49649. {
  49650. // the speeds must be 0 or greater!
  49651. jassert (startSpeed >= 0 && endSpeed >= 0)
  49652. if (component != 0)
  49653. {
  49654. AnimationTask* at = findTaskFor (component);
  49655. if (at == 0)
  49656. {
  49657. at = new AnimationTask (component);
  49658. tasks.add (at);
  49659. sendChangeMessage (this);
  49660. }
  49661. at->reset (finalBounds, finalAlpha, millisecondsToSpendMoving,
  49662. useProxyComponent, startSpeed, endSpeed);
  49663. if (! isTimerRunning())
  49664. {
  49665. lastTime = Time::getMillisecondCounter();
  49666. startTimer (1000 / 50);
  49667. }
  49668. }
  49669. }
  49670. void ComponentAnimator::fadeOut (Component* component, int millisecondsToTake)
  49671. {
  49672. if (component != 0)
  49673. {
  49674. if (component->isShowing() && millisecondsToTake > 0)
  49675. animateComponent (component, component->getBounds(), 0.0f, millisecondsToTake, true, 1.0, 1.0);
  49676. component->setVisible (false);
  49677. }
  49678. }
  49679. void ComponentAnimator::fadeIn (Component* component, int millisecondsToTake)
  49680. {
  49681. if (component != 0 && ! (component->isVisible() && component->getAlpha() == 1.0f))
  49682. {
  49683. component->setAlpha (0.0f);
  49684. component->setVisible (true);
  49685. animateComponent (component, component->getBounds(), 1.0f, millisecondsToTake, false, 1.0, 1.0);
  49686. }
  49687. }
  49688. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  49689. {
  49690. if (tasks.size() > 0)
  49691. {
  49692. if (moveComponentsToTheirFinalPositions)
  49693. for (int i = tasks.size(); --i >= 0;)
  49694. tasks.getUnchecked(i)->moveToFinalDestination();
  49695. tasks.clear();
  49696. sendChangeMessage (this);
  49697. }
  49698. }
  49699. void ComponentAnimator::cancelAnimation (Component* const component,
  49700. const bool moveComponentToItsFinalPosition)
  49701. {
  49702. AnimationTask* const at = findTaskFor (component);
  49703. if (at != 0)
  49704. {
  49705. if (moveComponentToItsFinalPosition)
  49706. at->moveToFinalDestination();
  49707. tasks.removeObject (at);
  49708. sendChangeMessage (this);
  49709. }
  49710. }
  49711. const Rectangle<int> ComponentAnimator::getComponentDestination (Component* const component)
  49712. {
  49713. jassert (component != 0);
  49714. AnimationTask* const at = findTaskFor (component);
  49715. if (at != 0)
  49716. return at->destination;
  49717. return component->getBounds();
  49718. }
  49719. bool ComponentAnimator::isAnimating (Component* component) const
  49720. {
  49721. return findTaskFor (component) != 0;
  49722. }
  49723. void ComponentAnimator::timerCallback()
  49724. {
  49725. const uint32 timeNow = Time::getMillisecondCounter();
  49726. if (lastTime == 0 || lastTime == timeNow)
  49727. lastTime = timeNow;
  49728. const int elapsed = timeNow - lastTime;
  49729. for (int i = tasks.size(); --i >= 0;)
  49730. {
  49731. if (! tasks.getUnchecked(i)->useTimeslice (elapsed))
  49732. {
  49733. tasks.remove (i);
  49734. sendChangeMessage (this);
  49735. }
  49736. }
  49737. lastTime = timeNow;
  49738. if (tasks.size() == 0)
  49739. stopTimer();
  49740. }
  49741. END_JUCE_NAMESPACE
  49742. /*** End of inlined file: juce_ComponentAnimator.cpp ***/
  49743. /*** Start of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  49744. BEGIN_JUCE_NAMESPACE
  49745. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  49746. : minW (0),
  49747. maxW (0x3fffffff),
  49748. minH (0),
  49749. maxH (0x3fffffff),
  49750. minOffTop (0),
  49751. minOffLeft (0),
  49752. minOffBottom (0),
  49753. minOffRight (0),
  49754. aspectRatio (0.0)
  49755. {
  49756. }
  49757. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  49758. {
  49759. }
  49760. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  49761. {
  49762. minW = minimumWidth;
  49763. }
  49764. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  49765. {
  49766. maxW = maximumWidth;
  49767. }
  49768. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  49769. {
  49770. minH = minimumHeight;
  49771. }
  49772. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  49773. {
  49774. maxH = maximumHeight;
  49775. }
  49776. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  49777. {
  49778. jassert (maxW >= minimumWidth);
  49779. jassert (maxH >= minimumHeight);
  49780. jassert (minimumWidth > 0 && minimumHeight > 0);
  49781. minW = minimumWidth;
  49782. minH = minimumHeight;
  49783. if (minW > maxW)
  49784. maxW = minW;
  49785. if (minH > maxH)
  49786. maxH = minH;
  49787. }
  49788. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  49789. {
  49790. jassert (maximumWidth >= minW);
  49791. jassert (maximumHeight >= minH);
  49792. jassert (maximumWidth > 0 && maximumHeight > 0);
  49793. maxW = jmax (minW, maximumWidth);
  49794. maxH = jmax (minH, maximumHeight);
  49795. }
  49796. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  49797. const int minimumHeight,
  49798. const int maximumWidth,
  49799. const int maximumHeight) throw()
  49800. {
  49801. jassert (maximumWidth >= minimumWidth);
  49802. jassert (maximumHeight >= minimumHeight);
  49803. jassert (maximumWidth > 0 && maximumHeight > 0);
  49804. jassert (minimumWidth > 0 && minimumHeight > 0);
  49805. minW = jmax (0, minimumWidth);
  49806. minH = jmax (0, minimumHeight);
  49807. maxW = jmax (minW, maximumWidth);
  49808. maxH = jmax (minH, maximumHeight);
  49809. }
  49810. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  49811. const int minimumWhenOffTheLeft,
  49812. const int minimumWhenOffTheBottom,
  49813. const int minimumWhenOffTheRight) throw()
  49814. {
  49815. minOffTop = minimumWhenOffTheTop;
  49816. minOffLeft = minimumWhenOffTheLeft;
  49817. minOffBottom = minimumWhenOffTheBottom;
  49818. minOffRight = minimumWhenOffTheRight;
  49819. }
  49820. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  49821. {
  49822. aspectRatio = jmax (0.0, widthOverHeight);
  49823. }
  49824. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  49825. {
  49826. return aspectRatio;
  49827. }
  49828. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  49829. const Rectangle<int>& targetBounds,
  49830. const bool isStretchingTop,
  49831. const bool isStretchingLeft,
  49832. const bool isStretchingBottom,
  49833. const bool isStretchingRight)
  49834. {
  49835. jassert (component != 0);
  49836. Rectangle<int> limits, bounds (targetBounds);
  49837. BorderSize border;
  49838. Component* const parent = component->getParentComponent();
  49839. if (parent == 0)
  49840. {
  49841. ComponentPeer* peer = component->getPeer();
  49842. if (peer != 0)
  49843. border = peer->getFrameSize();
  49844. limits = Desktop::getInstance().getMonitorAreaContaining (bounds.getCentre());
  49845. }
  49846. else
  49847. {
  49848. limits.setSize (parent->getWidth(), parent->getHeight());
  49849. }
  49850. border.addTo (bounds);
  49851. checkBounds (bounds,
  49852. border.addedTo (component->getBounds()), limits,
  49853. isStretchingTop, isStretchingLeft,
  49854. isStretchingBottom, isStretchingRight);
  49855. border.subtractFrom (bounds);
  49856. applyBoundsToComponent (component, bounds);
  49857. }
  49858. void ComponentBoundsConstrainer::checkComponentBounds (Component* component)
  49859. {
  49860. setBoundsForComponent (component, component->getBounds(),
  49861. false, false, false, false);
  49862. }
  49863. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  49864. const Rectangle<int>& bounds)
  49865. {
  49866. component->setBounds (bounds);
  49867. }
  49868. void ComponentBoundsConstrainer::resizeStart()
  49869. {
  49870. }
  49871. void ComponentBoundsConstrainer::resizeEnd()
  49872. {
  49873. }
  49874. void ComponentBoundsConstrainer::checkBounds (Rectangle<int>& bounds,
  49875. const Rectangle<int>& old,
  49876. const Rectangle<int>& limits,
  49877. const bool isStretchingTop,
  49878. const bool isStretchingLeft,
  49879. const bool isStretchingBottom,
  49880. const bool isStretchingRight)
  49881. {
  49882. int x = bounds.getX();
  49883. int y = bounds.getY();
  49884. int w = bounds.getWidth();
  49885. int h = bounds.getHeight();
  49886. // constrain the size if it's being stretched..
  49887. if (isStretchingLeft)
  49888. {
  49889. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  49890. w = old.getRight() - x;
  49891. }
  49892. if (isStretchingRight)
  49893. {
  49894. w = jlimit (minW, maxW, w);
  49895. }
  49896. if (isStretchingTop)
  49897. {
  49898. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  49899. h = old.getBottom() - y;
  49900. }
  49901. if (isStretchingBottom)
  49902. {
  49903. h = jlimit (minH, maxH, h);
  49904. }
  49905. // constrain the aspect ratio if one has been specified..
  49906. if (aspectRatio > 0.0 && w > 0 && h > 0)
  49907. {
  49908. bool adjustWidth;
  49909. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49910. {
  49911. adjustWidth = true;
  49912. }
  49913. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49914. {
  49915. adjustWidth = false;
  49916. }
  49917. else
  49918. {
  49919. const double oldRatio = (old.getHeight() > 0) ? std::abs (old.getWidth() / (double) old.getHeight()) : 0.0;
  49920. const double newRatio = std::abs (w / (double) h);
  49921. adjustWidth = (oldRatio > newRatio);
  49922. }
  49923. if (adjustWidth)
  49924. {
  49925. w = roundToInt (h * aspectRatio);
  49926. if (w > maxW || w < minW)
  49927. {
  49928. w = jlimit (minW, maxW, w);
  49929. h = roundToInt (w / aspectRatio);
  49930. }
  49931. }
  49932. else
  49933. {
  49934. h = roundToInt (w / aspectRatio);
  49935. if (h > maxH || h < minH)
  49936. {
  49937. h = jlimit (minH, maxH, h);
  49938. w = roundToInt (h * aspectRatio);
  49939. }
  49940. }
  49941. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  49942. {
  49943. x = old.getX() + (old.getWidth() - w) / 2;
  49944. }
  49945. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  49946. {
  49947. y = old.getY() + (old.getHeight() - h) / 2;
  49948. }
  49949. else
  49950. {
  49951. if (isStretchingLeft)
  49952. x = old.getRight() - w;
  49953. if (isStretchingTop)
  49954. y = old.getBottom() - h;
  49955. }
  49956. }
  49957. // ...and constrain the position if limits have been set for that.
  49958. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  49959. {
  49960. if (minOffTop > 0)
  49961. {
  49962. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  49963. if (y < limit)
  49964. {
  49965. if (isStretchingTop)
  49966. h -= (limit - y);
  49967. y = limit;
  49968. }
  49969. }
  49970. if (minOffLeft > 0)
  49971. {
  49972. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  49973. if (x < limit)
  49974. {
  49975. if (isStretchingLeft)
  49976. w -= (limit - x);
  49977. x = limit;
  49978. }
  49979. }
  49980. if (minOffBottom > 0)
  49981. {
  49982. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  49983. if (y > limit)
  49984. {
  49985. if (isStretchingBottom)
  49986. h += (limit - y);
  49987. else
  49988. y = limit;
  49989. }
  49990. }
  49991. if (minOffRight > 0)
  49992. {
  49993. const int limit = limits.getRight() - jmin (minOffRight, w);
  49994. if (x > limit)
  49995. {
  49996. if (isStretchingRight)
  49997. w += (limit - x);
  49998. else
  49999. x = limit;
  50000. }
  50001. }
  50002. }
  50003. jassert (w >= 0 && h >= 0);
  50004. bounds = Rectangle<int> (x, y, w, h);
  50005. }
  50006. END_JUCE_NAMESPACE
  50007. /*** End of inlined file: juce_ComponentBoundsConstrainer.cpp ***/
  50008. /*** Start of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50009. BEGIN_JUCE_NAMESPACE
  50010. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  50011. : component (component_),
  50012. lastPeer (0),
  50013. reentrant (false)
  50014. {
  50015. jassert (component != 0); // can't use this with a null pointer..
  50016. component->addComponentListener (this);
  50017. registerWithParentComps();
  50018. }
  50019. ComponentMovementWatcher::~ComponentMovementWatcher()
  50020. {
  50021. component->removeComponentListener (this);
  50022. unregister();
  50023. }
  50024. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  50025. {
  50026. // agh! don't delete the target component without deleting this object first!
  50027. jassert (component != 0);
  50028. if (! reentrant)
  50029. {
  50030. reentrant = true;
  50031. ComponentPeer* const peer = component->getPeer();
  50032. if (peer != lastPeer)
  50033. {
  50034. componentPeerChanged();
  50035. if (component == 0)
  50036. return;
  50037. lastPeer = peer;
  50038. }
  50039. unregister();
  50040. registerWithParentComps();
  50041. reentrant = false;
  50042. componentMovedOrResized (*component, true, true);
  50043. }
  50044. }
  50045. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  50046. {
  50047. // agh! don't delete the target component without deleting this object first!
  50048. jassert (component != 0);
  50049. if (wasMoved)
  50050. {
  50051. const Point<int> pos (component->relativePositionToOtherComponent (component->getTopLevelComponent(), Point<int>()));
  50052. wasMoved = lastBounds.getPosition() != pos;
  50053. lastBounds.setPosition (pos);
  50054. }
  50055. wasResized = (lastBounds.getWidth() != component->getWidth() || lastBounds.getHeight() != component->getHeight());
  50056. lastBounds.setSize (component->getWidth(), component->getHeight());
  50057. if (wasMoved || wasResized)
  50058. componentMovedOrResized (wasMoved, wasResized);
  50059. }
  50060. void ComponentMovementWatcher::registerWithParentComps()
  50061. {
  50062. Component* p = component->getParentComponent();
  50063. while (p != 0)
  50064. {
  50065. p->addComponentListener (this);
  50066. registeredParentComps.add (p);
  50067. p = p->getParentComponent();
  50068. }
  50069. }
  50070. void ComponentMovementWatcher::unregister()
  50071. {
  50072. for (int i = registeredParentComps.size(); --i >= 0;)
  50073. registeredParentComps.getUnchecked(i)->removeComponentListener (this);
  50074. registeredParentComps.clear();
  50075. }
  50076. END_JUCE_NAMESPACE
  50077. /*** End of inlined file: juce_ComponentMovementWatcher.cpp ***/
  50078. /*** Start of inlined file: juce_GroupComponent.cpp ***/
  50079. BEGIN_JUCE_NAMESPACE
  50080. GroupComponent::GroupComponent (const String& componentName,
  50081. const String& labelText)
  50082. : Component (componentName),
  50083. text (labelText),
  50084. justification (Justification::left)
  50085. {
  50086. setInterceptsMouseClicks (false, true);
  50087. }
  50088. GroupComponent::~GroupComponent()
  50089. {
  50090. }
  50091. void GroupComponent::setText (const String& newText)
  50092. {
  50093. if (text != newText)
  50094. {
  50095. text = newText;
  50096. repaint();
  50097. }
  50098. }
  50099. const String GroupComponent::getText() const
  50100. {
  50101. return text;
  50102. }
  50103. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  50104. {
  50105. if (justification != newJustification)
  50106. {
  50107. justification = newJustification;
  50108. repaint();
  50109. }
  50110. }
  50111. void GroupComponent::paint (Graphics& g)
  50112. {
  50113. getLookAndFeel()
  50114. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  50115. text, justification,
  50116. *this);
  50117. }
  50118. void GroupComponent::enablementChanged()
  50119. {
  50120. repaint();
  50121. }
  50122. void GroupComponent::colourChanged()
  50123. {
  50124. repaint();
  50125. }
  50126. END_JUCE_NAMESPACE
  50127. /*** End of inlined file: juce_GroupComponent.cpp ***/
  50128. /*** Start of inlined file: juce_MultiDocumentPanel.cpp ***/
  50129. BEGIN_JUCE_NAMESPACE
  50130. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  50131. : DocumentWindow (String::empty, backgroundColour,
  50132. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  50133. {
  50134. }
  50135. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  50136. {
  50137. }
  50138. void MultiDocumentPanelWindow::maximiseButtonPressed()
  50139. {
  50140. MultiDocumentPanel* const owner = getOwner();
  50141. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50142. if (owner != 0)
  50143. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  50144. }
  50145. void MultiDocumentPanelWindow::closeButtonPressed()
  50146. {
  50147. MultiDocumentPanel* const owner = getOwner();
  50148. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  50149. if (owner != 0)
  50150. owner->closeDocument (getContentComponent(), true);
  50151. }
  50152. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  50153. {
  50154. DocumentWindow::activeWindowStatusChanged();
  50155. updateOrder();
  50156. }
  50157. void MultiDocumentPanelWindow::broughtToFront()
  50158. {
  50159. DocumentWindow::broughtToFront();
  50160. updateOrder();
  50161. }
  50162. void MultiDocumentPanelWindow::updateOrder()
  50163. {
  50164. MultiDocumentPanel* const owner = getOwner();
  50165. if (owner != 0)
  50166. owner->updateOrder();
  50167. }
  50168. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  50169. {
  50170. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50171. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50172. }
  50173. class MDITabbedComponentInternal : public TabbedComponent
  50174. {
  50175. public:
  50176. MDITabbedComponentInternal()
  50177. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  50178. {
  50179. }
  50180. ~MDITabbedComponentInternal()
  50181. {
  50182. }
  50183. void currentTabChanged (int, const String&)
  50184. {
  50185. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  50186. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  50187. if (owner != 0)
  50188. owner->updateOrder();
  50189. }
  50190. };
  50191. MultiDocumentPanel::MultiDocumentPanel()
  50192. : mode (MaximisedWindowsWithTabs),
  50193. backgroundColour (Colours::lightblue),
  50194. maximumNumDocuments (0),
  50195. numDocsBeforeTabsUsed (0)
  50196. {
  50197. setOpaque (true);
  50198. }
  50199. MultiDocumentPanel::~MultiDocumentPanel()
  50200. {
  50201. closeAllDocuments (false);
  50202. }
  50203. namespace MultiDocHelpers
  50204. {
  50205. bool shouldDeleteComp (Component* const c)
  50206. {
  50207. return c->getProperties() ["mdiDocumentDelete_"];
  50208. }
  50209. }
  50210. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  50211. {
  50212. while (components.size() > 0)
  50213. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  50214. return false;
  50215. return true;
  50216. }
  50217. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  50218. {
  50219. return new MultiDocumentPanelWindow (backgroundColour);
  50220. }
  50221. void MultiDocumentPanel::addWindow (Component* component)
  50222. {
  50223. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  50224. dw->setResizable (true, false);
  50225. dw->setContentComponent (component, false, true);
  50226. dw->setName (component->getName());
  50227. const var bkg (component->getProperties() ["mdiDocumentBkg_"]);
  50228. dw->setBackgroundColour (bkg.isVoid() ? backgroundColour : Colour ((int) bkg));
  50229. int x = 4;
  50230. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  50231. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  50232. x += 16;
  50233. dw->setTopLeftPosition (x, x);
  50234. const var pos (component->getProperties() ["mdiDocumentPos_"]);
  50235. if (pos.toString().isNotEmpty())
  50236. dw->restoreWindowStateFromString (pos.toString());
  50237. addAndMakeVisible (dw);
  50238. dw->toFront (true);
  50239. }
  50240. bool MultiDocumentPanel::addDocument (Component* const component,
  50241. const Colour& docColour,
  50242. const bool deleteWhenRemoved)
  50243. {
  50244. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  50245. // with a frame-within-a-frame! Just pass in the bare content component.
  50246. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  50247. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  50248. return false;
  50249. components.add (component);
  50250. component->getProperties().set ("mdiDocumentDelete_", deleteWhenRemoved);
  50251. component->getProperties().set ("mdiDocumentBkg_", (int) docColour.getARGB());
  50252. component->addComponentListener (this);
  50253. if (mode == FloatingWindows)
  50254. {
  50255. if (isFullscreenWhenOneDocument())
  50256. {
  50257. if (components.size() == 1)
  50258. {
  50259. addAndMakeVisible (component);
  50260. }
  50261. else
  50262. {
  50263. if (components.size() == 2)
  50264. addWindow (components.getFirst());
  50265. addWindow (component);
  50266. }
  50267. }
  50268. else
  50269. {
  50270. addWindow (component);
  50271. }
  50272. }
  50273. else
  50274. {
  50275. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  50276. {
  50277. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  50278. Array <Component*> temp (components);
  50279. for (int i = 0; i < temp.size(); ++i)
  50280. tabComponent->addTab (temp[i]->getName(), docColour, temp[i], false);
  50281. resized();
  50282. }
  50283. else
  50284. {
  50285. if (tabComponent != 0)
  50286. tabComponent->addTab (component->getName(), docColour, component, false);
  50287. else
  50288. addAndMakeVisible (component);
  50289. }
  50290. setActiveDocument (component);
  50291. }
  50292. resized();
  50293. activeDocumentChanged();
  50294. return true;
  50295. }
  50296. bool MultiDocumentPanel::closeDocument (Component* component,
  50297. const bool checkItsOkToCloseFirst)
  50298. {
  50299. if (components.contains (component))
  50300. {
  50301. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  50302. return false;
  50303. component->removeComponentListener (this);
  50304. const bool shouldDelete = MultiDocHelpers::shouldDeleteComp (component);
  50305. component->getProperties().remove ("mdiDocumentDelete_");
  50306. component->getProperties().remove ("mdiDocumentBkg_");
  50307. if (mode == FloatingWindows)
  50308. {
  50309. for (int i = getNumChildComponents(); --i >= 0;)
  50310. {
  50311. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50312. if (dw != 0 && dw->getContentComponent() == component)
  50313. {
  50314. dw->setContentComponent (0, false);
  50315. delete dw;
  50316. break;
  50317. }
  50318. }
  50319. if (shouldDelete)
  50320. delete component;
  50321. components.removeValue (component);
  50322. if (isFullscreenWhenOneDocument() && components.size() == 1)
  50323. {
  50324. for (int i = getNumChildComponents(); --i >= 0;)
  50325. {
  50326. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50327. if (dw != 0)
  50328. {
  50329. dw->setContentComponent (0, false);
  50330. delete dw;
  50331. }
  50332. }
  50333. addAndMakeVisible (components.getFirst());
  50334. }
  50335. }
  50336. else
  50337. {
  50338. jassert (components.indexOf (component) >= 0);
  50339. if (tabComponent != 0)
  50340. {
  50341. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50342. if (tabComponent->getTabContentComponent (i) == component)
  50343. tabComponent->removeTab (i);
  50344. }
  50345. else
  50346. {
  50347. removeChildComponent (component);
  50348. }
  50349. if (shouldDelete)
  50350. delete component;
  50351. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  50352. tabComponent = 0;
  50353. components.removeValue (component);
  50354. if (components.size() > 0 && tabComponent == 0)
  50355. addAndMakeVisible (components.getFirst());
  50356. }
  50357. resized();
  50358. activeDocumentChanged();
  50359. }
  50360. else
  50361. {
  50362. jassertfalse;
  50363. }
  50364. return true;
  50365. }
  50366. int MultiDocumentPanel::getNumDocuments() const throw()
  50367. {
  50368. return components.size();
  50369. }
  50370. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  50371. {
  50372. return components [index];
  50373. }
  50374. Component* MultiDocumentPanel::getActiveDocument() const throw()
  50375. {
  50376. if (mode == FloatingWindows)
  50377. {
  50378. for (int i = getNumChildComponents(); --i >= 0;)
  50379. {
  50380. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50381. if (dw != 0 && dw->isActiveWindow())
  50382. return dw->getContentComponent();
  50383. }
  50384. }
  50385. return components.getLast();
  50386. }
  50387. void MultiDocumentPanel::setActiveDocument (Component* component)
  50388. {
  50389. if (mode == FloatingWindows)
  50390. {
  50391. component = getContainerComp (component);
  50392. if (component != 0)
  50393. component->toFront (true);
  50394. }
  50395. else if (tabComponent != 0)
  50396. {
  50397. jassert (components.indexOf (component) >= 0);
  50398. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50399. {
  50400. if (tabComponent->getTabContentComponent (i) == component)
  50401. {
  50402. tabComponent->setCurrentTabIndex (i);
  50403. break;
  50404. }
  50405. }
  50406. }
  50407. else
  50408. {
  50409. component->grabKeyboardFocus();
  50410. }
  50411. }
  50412. void MultiDocumentPanel::activeDocumentChanged()
  50413. {
  50414. }
  50415. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  50416. {
  50417. maximumNumDocuments = newNumber;
  50418. }
  50419. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  50420. {
  50421. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  50422. }
  50423. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  50424. {
  50425. return numDocsBeforeTabsUsed != 0;
  50426. }
  50427. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  50428. {
  50429. if (mode != newLayoutMode)
  50430. {
  50431. mode = newLayoutMode;
  50432. if (mode == FloatingWindows)
  50433. {
  50434. tabComponent = 0;
  50435. }
  50436. else
  50437. {
  50438. for (int i = getNumChildComponents(); --i >= 0;)
  50439. {
  50440. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50441. if (dw != 0)
  50442. {
  50443. dw->getContentComponent()->getProperties().set ("mdiDocumentPos_", dw->getWindowStateAsString());
  50444. dw->setContentComponent (0, false);
  50445. delete dw;
  50446. }
  50447. }
  50448. }
  50449. resized();
  50450. const Array <Component*> tempComps (components);
  50451. components.clear();
  50452. for (int i = 0; i < tempComps.size(); ++i)
  50453. {
  50454. Component* const c = tempComps.getUnchecked(i);
  50455. addDocument (c,
  50456. Colour ((int) c->getProperties().getWithDefault ("mdiDocumentBkg_", (int) Colours::white.getARGB())),
  50457. MultiDocHelpers::shouldDeleteComp (c));
  50458. }
  50459. }
  50460. }
  50461. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  50462. {
  50463. if (backgroundColour != newBackgroundColour)
  50464. {
  50465. backgroundColour = newBackgroundColour;
  50466. setOpaque (newBackgroundColour.isOpaque());
  50467. repaint();
  50468. }
  50469. }
  50470. void MultiDocumentPanel::paint (Graphics& g)
  50471. {
  50472. g.fillAll (backgroundColour);
  50473. }
  50474. void MultiDocumentPanel::resized()
  50475. {
  50476. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  50477. {
  50478. for (int i = getNumChildComponents(); --i >= 0;)
  50479. getChildComponent (i)->setBounds (getLocalBounds());
  50480. }
  50481. setWantsKeyboardFocus (components.size() == 0);
  50482. }
  50483. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  50484. {
  50485. if (mode == FloatingWindows)
  50486. {
  50487. for (int i = 0; i < getNumChildComponents(); ++i)
  50488. {
  50489. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50490. if (dw != 0 && dw->getContentComponent() == c)
  50491. {
  50492. c = dw;
  50493. break;
  50494. }
  50495. }
  50496. }
  50497. return c;
  50498. }
  50499. void MultiDocumentPanel::componentNameChanged (Component&)
  50500. {
  50501. if (mode == FloatingWindows)
  50502. {
  50503. for (int i = 0; i < getNumChildComponents(); ++i)
  50504. {
  50505. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50506. if (dw != 0)
  50507. dw->setName (dw->getContentComponent()->getName());
  50508. }
  50509. }
  50510. else if (tabComponent != 0)
  50511. {
  50512. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  50513. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  50514. }
  50515. }
  50516. void MultiDocumentPanel::updateOrder()
  50517. {
  50518. const Array <Component*> oldList (components);
  50519. if (mode == FloatingWindows)
  50520. {
  50521. components.clear();
  50522. for (int i = 0; i < getNumChildComponents(); ++i)
  50523. {
  50524. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  50525. if (dw != 0)
  50526. components.add (dw->getContentComponent());
  50527. }
  50528. }
  50529. else
  50530. {
  50531. if (tabComponent != 0)
  50532. {
  50533. Component* const current = tabComponent->getCurrentContentComponent();
  50534. if (current != 0)
  50535. {
  50536. components.removeValue (current);
  50537. components.add (current);
  50538. }
  50539. }
  50540. }
  50541. if (components != oldList)
  50542. activeDocumentChanged();
  50543. }
  50544. END_JUCE_NAMESPACE
  50545. /*** End of inlined file: juce_MultiDocumentPanel.cpp ***/
  50546. /*** Start of inlined file: juce_ResizableBorderComponent.cpp ***/
  50547. BEGIN_JUCE_NAMESPACE
  50548. ResizableBorderComponent::Zone::Zone (int zoneFlags) throw()
  50549. : zone (zoneFlags)
  50550. {
  50551. }
  50552. ResizableBorderComponent::Zone::Zone (const ResizableBorderComponent::Zone& other) throw() : zone (other.zone) {}
  50553. ResizableBorderComponent::Zone& ResizableBorderComponent::Zone::operator= (const ResizableBorderComponent::Zone& other) throw() { zone = other.zone; return *this; }
  50554. bool ResizableBorderComponent::Zone::operator== (const ResizableBorderComponent::Zone& other) const throw() { return zone == other.zone; }
  50555. bool ResizableBorderComponent::Zone::operator!= (const ResizableBorderComponent::Zone& other) const throw() { return zone != other.zone; }
  50556. const ResizableBorderComponent::Zone ResizableBorderComponent::Zone::fromPositionOnBorder (const Rectangle<int>& totalSize,
  50557. const BorderSize& border,
  50558. const Point<int>& position)
  50559. {
  50560. int z = 0;
  50561. if (totalSize.contains (position)
  50562. && ! border.subtractedFrom (totalSize).contains (position))
  50563. {
  50564. const int minW = jmax (totalSize.getWidth() / 10, jmin (10, totalSize.getWidth() / 3));
  50565. if (position.getX() < jmax (border.getLeft(), minW))
  50566. z |= left;
  50567. else if (position.getX() >= totalSize.getWidth() - jmax (border.getRight(), minW))
  50568. z |= right;
  50569. const int minH = jmax (totalSize.getHeight() / 10, jmin (10, totalSize.getHeight() / 3));
  50570. if (position.getY() < jmax (border.getTop(), minH))
  50571. z |= top;
  50572. else if (position.getY() >= totalSize.getHeight() - jmax (border.getBottom(), minH))
  50573. z |= bottom;
  50574. }
  50575. return Zone (z);
  50576. }
  50577. const MouseCursor ResizableBorderComponent::Zone::getMouseCursor() const throw()
  50578. {
  50579. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  50580. switch (zone)
  50581. {
  50582. case (left | top): mc = MouseCursor::TopLeftCornerResizeCursor; break;
  50583. case top: mc = MouseCursor::TopEdgeResizeCursor; break;
  50584. case (right | top): mc = MouseCursor::TopRightCornerResizeCursor; break;
  50585. case left: mc = MouseCursor::LeftEdgeResizeCursor; break;
  50586. case right: mc = MouseCursor::RightEdgeResizeCursor; break;
  50587. case (left | bottom): mc = MouseCursor::BottomLeftCornerResizeCursor; break;
  50588. case bottom: mc = MouseCursor::BottomEdgeResizeCursor; break;
  50589. case (right | bottom): mc = MouseCursor::BottomRightCornerResizeCursor; break;
  50590. default: break;
  50591. }
  50592. return mc;
  50593. }
  50594. const Rectangle<int> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<int> b, const Point<int>& offset) const throw()
  50595. {
  50596. if (isDraggingWholeObject())
  50597. return b + offset;
  50598. if (isDraggingLeftEdge())
  50599. b.setLeft (b.getX() + offset.getX());
  50600. if (isDraggingRightEdge())
  50601. b.setWidth (jmax (0, b.getWidth() + offset.getX()));
  50602. if (isDraggingTopEdge())
  50603. b.setTop (b.getY() + offset.getY());
  50604. if (isDraggingBottomEdge())
  50605. b.setHeight (jmax (0, b.getHeight() + offset.getY()));
  50606. return b;
  50607. }
  50608. const Rectangle<float> ResizableBorderComponent::Zone::resizeRectangleBy (Rectangle<float> b, const Point<float>& offset) const throw()
  50609. {
  50610. if (isDraggingWholeObject())
  50611. return b + offset;
  50612. if (isDraggingLeftEdge())
  50613. b.setLeft (b.getX() + offset.getX());
  50614. if (isDraggingRightEdge())
  50615. b.setWidth (jmax (0.0f, b.getWidth() + offset.getX()));
  50616. if (isDraggingTopEdge())
  50617. b.setTop (b.getY() + offset.getY());
  50618. if (isDraggingBottomEdge())
  50619. b.setHeight (jmax (0.0f, b.getHeight() + offset.getY()));
  50620. return b;
  50621. }
  50622. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  50623. ComponentBoundsConstrainer* const constrainer_)
  50624. : component (componentToResize),
  50625. constrainer (constrainer_),
  50626. borderSize (5),
  50627. mouseZone (0)
  50628. {
  50629. }
  50630. ResizableBorderComponent::~ResizableBorderComponent()
  50631. {
  50632. }
  50633. void ResizableBorderComponent::paint (Graphics& g)
  50634. {
  50635. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  50636. }
  50637. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  50638. {
  50639. updateMouseZone (e);
  50640. }
  50641. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  50642. {
  50643. updateMouseZone (e);
  50644. }
  50645. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  50646. {
  50647. if (component == 0)
  50648. {
  50649. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50650. return;
  50651. }
  50652. updateMouseZone (e);
  50653. originalBounds = component->getBounds();
  50654. if (constrainer != 0)
  50655. constrainer->resizeStart();
  50656. }
  50657. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  50658. {
  50659. if (component == 0)
  50660. {
  50661. jassertfalse; // You've deleted the component that this resizer was supposed to be using!
  50662. return;
  50663. }
  50664. const Rectangle<int> bounds (mouseZone.resizeRectangleBy (originalBounds, e.getOffsetFromDragStart()));
  50665. if (constrainer != 0)
  50666. constrainer->setBoundsForComponent (component, bounds,
  50667. mouseZone.isDraggingTopEdge(),
  50668. mouseZone.isDraggingLeftEdge(),
  50669. mouseZone.isDraggingBottomEdge(),
  50670. mouseZone.isDraggingRightEdge());
  50671. else
  50672. component->setBounds (bounds);
  50673. }
  50674. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  50675. {
  50676. if (constrainer != 0)
  50677. constrainer->resizeEnd();
  50678. }
  50679. bool ResizableBorderComponent::hitTest (int x, int y)
  50680. {
  50681. return x < borderSize.getLeft()
  50682. || x >= getWidth() - borderSize.getRight()
  50683. || y < borderSize.getTop()
  50684. || y >= getHeight() - borderSize.getBottom();
  50685. }
  50686. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize)
  50687. {
  50688. if (borderSize != newBorderSize)
  50689. {
  50690. borderSize = newBorderSize;
  50691. repaint();
  50692. }
  50693. }
  50694. const BorderSize ResizableBorderComponent::getBorderThickness() const
  50695. {
  50696. return borderSize;
  50697. }
  50698. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e)
  50699. {
  50700. Zone newZone (Zone::fromPositionOnBorder (getLocalBounds(), borderSize, e.getPosition()));
  50701. if (mouseZone != newZone)
  50702. {
  50703. mouseZone = newZone;
  50704. setMouseCursor (newZone.getMouseCursor());
  50705. }
  50706. }
  50707. END_JUCE_NAMESPACE
  50708. /*** End of inlined file: juce_ResizableBorderComponent.cpp ***/
  50709. /*** Start of inlined file: juce_ResizableCornerComponent.cpp ***/
  50710. BEGIN_JUCE_NAMESPACE
  50711. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  50712. ComponentBoundsConstrainer* const constrainer_)
  50713. : component (componentToResize),
  50714. constrainer (constrainer_)
  50715. {
  50716. setRepaintsOnMouseActivity (true);
  50717. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  50718. }
  50719. ResizableCornerComponent::~ResizableCornerComponent()
  50720. {
  50721. }
  50722. void ResizableCornerComponent::paint (Graphics& g)
  50723. {
  50724. getLookAndFeel()
  50725. .drawCornerResizer (g, getWidth(), getHeight(),
  50726. isMouseOverOrDragging(),
  50727. isMouseButtonDown());
  50728. }
  50729. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  50730. {
  50731. if (component == 0)
  50732. {
  50733. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50734. return;
  50735. }
  50736. originalBounds = component->getBounds();
  50737. if (constrainer != 0)
  50738. constrainer->resizeStart();
  50739. }
  50740. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  50741. {
  50742. if (component == 0)
  50743. {
  50744. jassertfalse; // You've deleted the component that this resizer is supposed to be controlling!
  50745. return;
  50746. }
  50747. Rectangle<int> r (originalBounds.withSize (originalBounds.getWidth() + e.getDistanceFromDragStartX(),
  50748. originalBounds.getHeight() + e.getDistanceFromDragStartY()));
  50749. if (constrainer != 0)
  50750. constrainer->setBoundsForComponent (component, r, false, false, true, true);
  50751. else
  50752. component->setBounds (r);
  50753. }
  50754. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  50755. {
  50756. if (constrainer != 0)
  50757. constrainer->resizeStart();
  50758. }
  50759. bool ResizableCornerComponent::hitTest (int x, int y)
  50760. {
  50761. if (getWidth() <= 0)
  50762. return false;
  50763. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  50764. return y >= yAtX - getHeight() / 4;
  50765. }
  50766. END_JUCE_NAMESPACE
  50767. /*** End of inlined file: juce_ResizableCornerComponent.cpp ***/
  50768. /*** Start of inlined file: juce_ScrollBar.cpp ***/
  50769. BEGIN_JUCE_NAMESPACE
  50770. class ScrollBar::ScrollbarButton : public Button
  50771. {
  50772. public:
  50773. int direction;
  50774. ScrollbarButton (const int direction_, ScrollBar& owner_)
  50775. : Button (String::empty),
  50776. direction (direction_),
  50777. owner (owner_)
  50778. {
  50779. setWantsKeyboardFocus (false);
  50780. }
  50781. ~ScrollbarButton()
  50782. {
  50783. }
  50784. void paintButton (Graphics& g, bool over, bool down)
  50785. {
  50786. getLookAndFeel()
  50787. .drawScrollbarButton (g, owner,
  50788. getWidth(), getHeight(),
  50789. direction,
  50790. owner.isVertical(),
  50791. over, down);
  50792. }
  50793. void clicked()
  50794. {
  50795. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  50796. }
  50797. juce_UseDebuggingNewOperator
  50798. private:
  50799. ScrollBar& owner;
  50800. ScrollbarButton (const ScrollbarButton&);
  50801. ScrollbarButton& operator= (const ScrollbarButton&);
  50802. };
  50803. ScrollBar::ScrollBar (const bool vertical_,
  50804. const bool buttonsAreVisible)
  50805. : totalRange (0.0, 1.0),
  50806. visibleRange (0.0, 0.1),
  50807. singleStepSize (0.1),
  50808. thumbAreaStart (0),
  50809. thumbAreaSize (0),
  50810. thumbStart (0),
  50811. thumbSize (0),
  50812. initialDelayInMillisecs (100),
  50813. repeatDelayInMillisecs (50),
  50814. minimumDelayInMillisecs (10),
  50815. vertical (vertical_),
  50816. isDraggingThumb (false),
  50817. autohides (true)
  50818. {
  50819. setButtonVisibility (buttonsAreVisible);
  50820. setRepaintsOnMouseActivity (true);
  50821. setFocusContainer (true);
  50822. }
  50823. ScrollBar::~ScrollBar()
  50824. {
  50825. upButton = 0;
  50826. downButton = 0;
  50827. }
  50828. void ScrollBar::setRangeLimits (const Range<double>& newRangeLimit)
  50829. {
  50830. if (totalRange != newRangeLimit)
  50831. {
  50832. totalRange = newRangeLimit;
  50833. setCurrentRange (visibleRange);
  50834. updateThumbPosition();
  50835. }
  50836. }
  50837. void ScrollBar::setRangeLimits (const double newMinimum, const double newMaximum)
  50838. {
  50839. jassert (newMaximum >= newMinimum); // these can't be the wrong way round!
  50840. setRangeLimits (Range<double> (newMinimum, newMaximum));
  50841. }
  50842. void ScrollBar::setCurrentRange (const Range<double>& newRange)
  50843. {
  50844. const Range<double> constrainedRange (totalRange.constrainRange (newRange));
  50845. if (visibleRange != constrainedRange)
  50846. {
  50847. visibleRange = constrainedRange;
  50848. updateThumbPosition();
  50849. triggerAsyncUpdate();
  50850. }
  50851. }
  50852. void ScrollBar::setCurrentRange (const double newStart, const double newSize)
  50853. {
  50854. setCurrentRange (Range<double> (newStart, newStart + newSize));
  50855. }
  50856. void ScrollBar::setCurrentRangeStart (const double newStart)
  50857. {
  50858. setCurrentRange (visibleRange.movedToStartAt (newStart));
  50859. }
  50860. void ScrollBar::setSingleStepSize (const double newSingleStepSize)
  50861. {
  50862. singleStepSize = newSingleStepSize;
  50863. }
  50864. void ScrollBar::moveScrollbarInSteps (const int howManySteps)
  50865. {
  50866. setCurrentRange (visibleRange + howManySteps * singleStepSize);
  50867. }
  50868. void ScrollBar::moveScrollbarInPages (const int howManyPages)
  50869. {
  50870. setCurrentRange (visibleRange + howManyPages * visibleRange.getLength());
  50871. }
  50872. void ScrollBar::scrollToTop()
  50873. {
  50874. setCurrentRange (visibleRange.movedToStartAt (getMinimumRangeLimit()));
  50875. }
  50876. void ScrollBar::scrollToBottom()
  50877. {
  50878. setCurrentRange (visibleRange.movedToEndAt (getMaximumRangeLimit()));
  50879. }
  50880. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  50881. const int repeatDelayInMillisecs_,
  50882. const int minimumDelayInMillisecs_)
  50883. {
  50884. initialDelayInMillisecs = initialDelayInMillisecs_;
  50885. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  50886. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  50887. if (upButton != 0)
  50888. {
  50889. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50890. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50891. }
  50892. }
  50893. void ScrollBar::addListener (Listener* const listener)
  50894. {
  50895. listeners.add (listener);
  50896. }
  50897. void ScrollBar::removeListener (Listener* const listener)
  50898. {
  50899. listeners.remove (listener);
  50900. }
  50901. void ScrollBar::handleAsyncUpdate()
  50902. {
  50903. double start = visibleRange.getStart(); // (need to use a temp variable for VC7 compatibility)
  50904. listeners.call (&ScrollBar::Listener::scrollBarMoved, this, start);
  50905. }
  50906. void ScrollBar::updateThumbPosition()
  50907. {
  50908. int newThumbSize = roundToInt (totalRange.getLength() > 0 ? (visibleRange.getLength() * thumbAreaSize) / totalRange.getLength()
  50909. : thumbAreaSize);
  50910. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  50911. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  50912. if (newThumbSize > thumbAreaSize)
  50913. newThumbSize = thumbAreaSize;
  50914. int newThumbStart = thumbAreaStart;
  50915. if (totalRange.getLength() > visibleRange.getLength())
  50916. newThumbStart += roundToInt (((visibleRange.getStart() - totalRange.getStart()) * (thumbAreaSize - newThumbSize))
  50917. / (totalRange.getLength() - visibleRange.getLength()));
  50918. setVisible ((! autohides) || (totalRange.getLength() > visibleRange.getLength() && visibleRange.getLength() > 0.0));
  50919. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  50920. {
  50921. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  50922. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  50923. if (vertical)
  50924. repaint (0, repaintStart, getWidth(), repaintSize);
  50925. else
  50926. repaint (repaintStart, 0, repaintSize, getHeight());
  50927. thumbStart = newThumbStart;
  50928. thumbSize = newThumbSize;
  50929. }
  50930. }
  50931. void ScrollBar::setOrientation (const bool shouldBeVertical)
  50932. {
  50933. if (vertical != shouldBeVertical)
  50934. {
  50935. vertical = shouldBeVertical;
  50936. if (upButton != 0)
  50937. {
  50938. upButton->direction = vertical ? 0 : 3;
  50939. downButton->direction = vertical ? 2 : 1;
  50940. }
  50941. updateThumbPosition();
  50942. }
  50943. }
  50944. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  50945. {
  50946. upButton = 0;
  50947. downButton = 0;
  50948. if (buttonsAreVisible)
  50949. {
  50950. addAndMakeVisible (upButton = new ScrollbarButton (vertical ? 0 : 3, *this));
  50951. addAndMakeVisible (downButton = new ScrollbarButton (vertical ? 2 : 1, *this));
  50952. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  50953. }
  50954. updateThumbPosition();
  50955. }
  50956. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  50957. {
  50958. autohides = shouldHideWhenFullRange;
  50959. updateThumbPosition();
  50960. }
  50961. bool ScrollBar::autoHides() const throw()
  50962. {
  50963. return autohides;
  50964. }
  50965. void ScrollBar::paint (Graphics& g)
  50966. {
  50967. if (thumbAreaSize > 0)
  50968. {
  50969. LookAndFeel& lf = getLookAndFeel();
  50970. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  50971. ? thumbSize : 0;
  50972. if (vertical)
  50973. {
  50974. lf.drawScrollbar (g, *this,
  50975. 0, thumbAreaStart,
  50976. getWidth(), thumbAreaSize,
  50977. vertical,
  50978. thumbStart, thumb,
  50979. isMouseOver(), isMouseButtonDown());
  50980. }
  50981. else
  50982. {
  50983. lf.drawScrollbar (g, *this,
  50984. thumbAreaStart, 0,
  50985. thumbAreaSize, getHeight(),
  50986. vertical,
  50987. thumbStart, thumb,
  50988. isMouseOver(), isMouseButtonDown());
  50989. }
  50990. }
  50991. }
  50992. void ScrollBar::lookAndFeelChanged()
  50993. {
  50994. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  50995. }
  50996. void ScrollBar::resized()
  50997. {
  50998. const int length = ((vertical) ? getHeight() : getWidth());
  50999. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  51000. : 0;
  51001. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51002. {
  51003. thumbAreaStart = length >> 1;
  51004. thumbAreaSize = 0;
  51005. }
  51006. else
  51007. {
  51008. thumbAreaStart = buttonSize;
  51009. thumbAreaSize = length - (buttonSize << 1);
  51010. }
  51011. if (upButton != 0)
  51012. {
  51013. if (vertical)
  51014. {
  51015. upButton->setBounds (0, 0, getWidth(), buttonSize);
  51016. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  51017. }
  51018. else
  51019. {
  51020. upButton->setBounds (0, 0, buttonSize, getHeight());
  51021. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  51022. }
  51023. }
  51024. updateThumbPosition();
  51025. }
  51026. void ScrollBar::mouseDown (const MouseEvent& e)
  51027. {
  51028. isDraggingThumb = false;
  51029. lastMousePos = vertical ? e.y : e.x;
  51030. dragStartMousePos = lastMousePos;
  51031. dragStartRange = visibleRange.getStart();
  51032. if (dragStartMousePos < thumbStart)
  51033. {
  51034. moveScrollbarInPages (-1);
  51035. startTimer (400);
  51036. }
  51037. else if (dragStartMousePos >= thumbStart + thumbSize)
  51038. {
  51039. moveScrollbarInPages (1);
  51040. startTimer (400);
  51041. }
  51042. else
  51043. {
  51044. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  51045. && (thumbAreaSize > thumbSize);
  51046. }
  51047. }
  51048. void ScrollBar::mouseDrag (const MouseEvent& e)
  51049. {
  51050. if (isDraggingThumb)
  51051. {
  51052. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  51053. setCurrentRangeStart (dragStartRange
  51054. + deltaPixels * (totalRange.getLength() - visibleRange.getLength())
  51055. / (thumbAreaSize - thumbSize));
  51056. }
  51057. else
  51058. {
  51059. lastMousePos = (vertical) ? e.y : e.x;
  51060. }
  51061. }
  51062. void ScrollBar::mouseUp (const MouseEvent&)
  51063. {
  51064. isDraggingThumb = false;
  51065. stopTimer();
  51066. repaint();
  51067. }
  51068. void ScrollBar::mouseWheelMove (const MouseEvent&,
  51069. float wheelIncrementX,
  51070. float wheelIncrementY)
  51071. {
  51072. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  51073. if (increment < 0)
  51074. increment = jmin (increment * 10.0f, -1.0f);
  51075. else if (increment > 0)
  51076. increment = jmax (increment * 10.0f, 1.0f);
  51077. setCurrentRange (visibleRange - singleStepSize * increment);
  51078. }
  51079. void ScrollBar::timerCallback()
  51080. {
  51081. if (isMouseButtonDown())
  51082. {
  51083. startTimer (40);
  51084. if (lastMousePos < thumbStart)
  51085. setCurrentRange (visibleRange - visibleRange.getLength());
  51086. else if (lastMousePos > thumbStart + thumbSize)
  51087. setCurrentRangeStart (visibleRange.getEnd());
  51088. }
  51089. else
  51090. {
  51091. stopTimer();
  51092. }
  51093. }
  51094. bool ScrollBar::keyPressed (const KeyPress& key)
  51095. {
  51096. if (! isVisible())
  51097. return false;
  51098. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  51099. moveScrollbarInSteps (-1);
  51100. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  51101. moveScrollbarInSteps (1);
  51102. else if (key.isKeyCode (KeyPress::pageUpKey))
  51103. moveScrollbarInPages (-1);
  51104. else if (key.isKeyCode (KeyPress::pageDownKey))
  51105. moveScrollbarInPages (1);
  51106. else if (key.isKeyCode (KeyPress::homeKey))
  51107. scrollToTop();
  51108. else if (key.isKeyCode (KeyPress::endKey))
  51109. scrollToBottom();
  51110. else
  51111. return false;
  51112. return true;
  51113. }
  51114. END_JUCE_NAMESPACE
  51115. /*** End of inlined file: juce_ScrollBar.cpp ***/
  51116. /*** Start of inlined file: juce_StretchableLayoutManager.cpp ***/
  51117. BEGIN_JUCE_NAMESPACE
  51118. StretchableLayoutManager::StretchableLayoutManager()
  51119. : totalSize (0)
  51120. {
  51121. }
  51122. StretchableLayoutManager::~StretchableLayoutManager()
  51123. {
  51124. }
  51125. void StretchableLayoutManager::clearAllItems()
  51126. {
  51127. items.clear();
  51128. totalSize = 0;
  51129. }
  51130. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  51131. const double minimumSize,
  51132. const double maximumSize,
  51133. const double preferredSize)
  51134. {
  51135. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  51136. if (layout == 0)
  51137. {
  51138. layout = new ItemLayoutProperties();
  51139. layout->itemIndex = itemIndex;
  51140. int i;
  51141. for (i = 0; i < items.size(); ++i)
  51142. if (items.getUnchecked (i)->itemIndex > itemIndex)
  51143. break;
  51144. items.insert (i, layout);
  51145. }
  51146. layout->minSize = minimumSize;
  51147. layout->maxSize = maximumSize;
  51148. layout->preferredSize = preferredSize;
  51149. layout->currentSize = 0;
  51150. }
  51151. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  51152. double& minimumSize,
  51153. double& maximumSize,
  51154. double& preferredSize) const
  51155. {
  51156. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51157. if (layout != 0)
  51158. {
  51159. minimumSize = layout->minSize;
  51160. maximumSize = layout->maxSize;
  51161. preferredSize = layout->preferredSize;
  51162. return true;
  51163. }
  51164. return false;
  51165. }
  51166. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  51167. {
  51168. totalSize = newTotalSize;
  51169. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  51170. }
  51171. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  51172. {
  51173. int pos = 0;
  51174. for (int i = 0; i < itemIndex; ++i)
  51175. {
  51176. const ItemLayoutProperties* const layout = getInfoFor (i);
  51177. if (layout != 0)
  51178. pos += layout->currentSize;
  51179. }
  51180. return pos;
  51181. }
  51182. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  51183. {
  51184. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51185. if (layout != 0)
  51186. return layout->currentSize;
  51187. return 0;
  51188. }
  51189. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  51190. {
  51191. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  51192. if (layout != 0)
  51193. return -layout->currentSize / (double) totalSize;
  51194. return 0;
  51195. }
  51196. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  51197. int newPosition)
  51198. {
  51199. for (int i = items.size(); --i >= 0;)
  51200. {
  51201. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  51202. if (layout->itemIndex == itemIndex)
  51203. {
  51204. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  51205. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  51206. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  51207. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  51208. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  51209. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  51210. endPos += layout->currentSize;
  51211. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  51212. updatePrefSizesToMatchCurrentPositions();
  51213. break;
  51214. }
  51215. }
  51216. }
  51217. void StretchableLayoutManager::layOutComponents (Component** const components,
  51218. int numComponents,
  51219. int x, int y, int w, int h,
  51220. const bool vertically,
  51221. const bool resizeOtherDimension)
  51222. {
  51223. setTotalSize (vertically ? h : w);
  51224. int pos = vertically ? y : x;
  51225. for (int i = 0; i < numComponents; ++i)
  51226. {
  51227. const ItemLayoutProperties* const layout = getInfoFor (i);
  51228. if (layout != 0)
  51229. {
  51230. Component* const c = components[i];
  51231. if (c != 0)
  51232. {
  51233. if (i == numComponents - 1)
  51234. {
  51235. // if it's the last item, crop it to exactly fit the available space..
  51236. if (resizeOtherDimension)
  51237. {
  51238. if (vertically)
  51239. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  51240. else
  51241. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  51242. }
  51243. else
  51244. {
  51245. if (vertically)
  51246. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  51247. else
  51248. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  51249. }
  51250. }
  51251. else
  51252. {
  51253. if (resizeOtherDimension)
  51254. {
  51255. if (vertically)
  51256. c->setBounds (x, pos, w, layout->currentSize);
  51257. else
  51258. c->setBounds (pos, y, layout->currentSize, h);
  51259. }
  51260. else
  51261. {
  51262. if (vertically)
  51263. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  51264. else
  51265. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  51266. }
  51267. }
  51268. }
  51269. pos += layout->currentSize;
  51270. }
  51271. }
  51272. }
  51273. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  51274. {
  51275. for (int i = items.size(); --i >= 0;)
  51276. if (items.getUnchecked(i)->itemIndex == itemIndex)
  51277. return items.getUnchecked(i);
  51278. return 0;
  51279. }
  51280. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  51281. const int endIndex,
  51282. const int availableSpace,
  51283. int startPos)
  51284. {
  51285. // calculate the total sizes
  51286. int i;
  51287. double totalIdealSize = 0.0;
  51288. int totalMinimums = 0;
  51289. for (i = startIndex; i < endIndex; ++i)
  51290. {
  51291. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51292. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  51293. totalMinimums += layout->currentSize;
  51294. totalIdealSize += sizeToRealSize (layout->preferredSize, totalSize);
  51295. }
  51296. if (totalIdealSize <= 0)
  51297. totalIdealSize = 1.0;
  51298. // now calc the best sizes..
  51299. int extraSpace = availableSpace - totalMinimums;
  51300. while (extraSpace > 0)
  51301. {
  51302. int numWantingMoreSpace = 0;
  51303. int numHavingTakenExtraSpace = 0;
  51304. // first figure out how many comps want a slice of the extra space..
  51305. for (i = startIndex; i < endIndex; ++i)
  51306. {
  51307. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51308. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51309. const int bestSize = jlimit (layout->currentSize,
  51310. jmax (layout->currentSize,
  51311. sizeToRealSize (layout->maxSize, totalSize)),
  51312. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51313. if (bestSize > layout->currentSize)
  51314. ++numWantingMoreSpace;
  51315. }
  51316. // ..share out the extra space..
  51317. for (i = startIndex; i < endIndex; ++i)
  51318. {
  51319. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51320. double sizeWanted = sizeToRealSize (layout->preferredSize, totalSize);
  51321. int bestSize = jlimit (layout->currentSize,
  51322. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  51323. roundToInt (sizeWanted * availableSpace / totalIdealSize));
  51324. const int extraWanted = bestSize - layout->currentSize;
  51325. if (extraWanted > 0)
  51326. {
  51327. const int extraAllowed = jmin (extraWanted,
  51328. extraSpace / jmax (1, numWantingMoreSpace));
  51329. if (extraAllowed > 0)
  51330. {
  51331. ++numHavingTakenExtraSpace;
  51332. --numWantingMoreSpace;
  51333. layout->currentSize += extraAllowed;
  51334. extraSpace -= extraAllowed;
  51335. }
  51336. }
  51337. }
  51338. if (numHavingTakenExtraSpace <= 0)
  51339. break;
  51340. }
  51341. // ..and calculate the end position
  51342. for (i = startIndex; i < endIndex; ++i)
  51343. {
  51344. ItemLayoutProperties* const layout = items.getUnchecked(i);
  51345. startPos += layout->currentSize;
  51346. }
  51347. return startPos;
  51348. }
  51349. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  51350. const int endIndex) const
  51351. {
  51352. int totalMinimums = 0;
  51353. for (int i = startIndex; i < endIndex; ++i)
  51354. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  51355. return totalMinimums;
  51356. }
  51357. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  51358. {
  51359. int totalMaximums = 0;
  51360. for (int i = startIndex; i < endIndex; ++i)
  51361. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  51362. return totalMaximums;
  51363. }
  51364. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  51365. {
  51366. for (int i = 0; i < items.size(); ++i)
  51367. {
  51368. ItemLayoutProperties* const layout = items.getUnchecked (i);
  51369. layout->preferredSize
  51370. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  51371. : getItemCurrentAbsoluteSize (i);
  51372. }
  51373. }
  51374. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  51375. {
  51376. if (size < 0)
  51377. size *= -totalSpace;
  51378. return roundToInt (size);
  51379. }
  51380. END_JUCE_NAMESPACE
  51381. /*** End of inlined file: juce_StretchableLayoutManager.cpp ***/
  51382. /*** Start of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51383. BEGIN_JUCE_NAMESPACE
  51384. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  51385. const int itemIndex_,
  51386. const bool isVertical_)
  51387. : layout (layout_),
  51388. itemIndex (itemIndex_),
  51389. isVertical (isVertical_)
  51390. {
  51391. setRepaintsOnMouseActivity (true);
  51392. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  51393. : MouseCursor::UpDownResizeCursor));
  51394. }
  51395. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  51396. {
  51397. }
  51398. void StretchableLayoutResizerBar::paint (Graphics& g)
  51399. {
  51400. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  51401. getWidth(), getHeight(),
  51402. isVertical,
  51403. isMouseOver(),
  51404. isMouseButtonDown());
  51405. }
  51406. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  51407. {
  51408. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  51409. }
  51410. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  51411. {
  51412. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  51413. : e.getDistanceFromDragStartY());
  51414. layout->setItemPosition (itemIndex, desiredPos);
  51415. hasBeenMoved();
  51416. }
  51417. void StretchableLayoutResizerBar::hasBeenMoved()
  51418. {
  51419. if (getParentComponent() != 0)
  51420. getParentComponent()->resized();
  51421. }
  51422. END_JUCE_NAMESPACE
  51423. /*** End of inlined file: juce_StretchableLayoutResizerBar.cpp ***/
  51424. /*** Start of inlined file: juce_StretchableObjectResizer.cpp ***/
  51425. BEGIN_JUCE_NAMESPACE
  51426. StretchableObjectResizer::StretchableObjectResizer()
  51427. {
  51428. }
  51429. StretchableObjectResizer::~StretchableObjectResizer()
  51430. {
  51431. }
  51432. void StretchableObjectResizer::addItem (const double size,
  51433. const double minSize, const double maxSize,
  51434. const int order)
  51435. {
  51436. // the order must be >= 0 but less than the maximum integer value.
  51437. jassert (order >= 0 && order < std::numeric_limits<int>::max());
  51438. Item* const item = new Item();
  51439. item->size = size;
  51440. item->minSize = minSize;
  51441. item->maxSize = maxSize;
  51442. item->order = order;
  51443. items.add (item);
  51444. }
  51445. double StretchableObjectResizer::getItemSize (const int index) const throw()
  51446. {
  51447. const Item* const it = items [index];
  51448. return it != 0 ? it->size : 0;
  51449. }
  51450. void StretchableObjectResizer::resizeToFit (const double targetSize)
  51451. {
  51452. int order = 0;
  51453. for (;;)
  51454. {
  51455. double currentSize = 0;
  51456. double minSize = 0;
  51457. double maxSize = 0;
  51458. int nextHighestOrder = std::numeric_limits<int>::max();
  51459. for (int i = 0; i < items.size(); ++i)
  51460. {
  51461. const Item* const it = items.getUnchecked(i);
  51462. currentSize += it->size;
  51463. if (it->order <= order)
  51464. {
  51465. minSize += it->minSize;
  51466. maxSize += it->maxSize;
  51467. }
  51468. else
  51469. {
  51470. minSize += it->size;
  51471. maxSize += it->size;
  51472. nextHighestOrder = jmin (nextHighestOrder, it->order);
  51473. }
  51474. }
  51475. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  51476. if (thisIterationTarget >= currentSize)
  51477. {
  51478. const double availableExtraSpace = maxSize - currentSize;
  51479. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  51480. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  51481. for (int i = 0; i < items.size(); ++i)
  51482. {
  51483. Item* const it = items.getUnchecked(i);
  51484. if (it->order <= order)
  51485. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  51486. }
  51487. }
  51488. else
  51489. {
  51490. const double amountOfSlack = currentSize - minSize;
  51491. const double targetAmountOfSlack = thisIterationTarget - minSize;
  51492. const double scale = targetAmountOfSlack / amountOfSlack;
  51493. for (int i = 0; i < items.size(); ++i)
  51494. {
  51495. Item* const it = items.getUnchecked(i);
  51496. if (it->order <= order)
  51497. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  51498. }
  51499. }
  51500. if (nextHighestOrder < std::numeric_limits<int>::max())
  51501. order = nextHighestOrder;
  51502. else
  51503. break;
  51504. }
  51505. }
  51506. END_JUCE_NAMESPACE
  51507. /*** End of inlined file: juce_StretchableObjectResizer.cpp ***/
  51508. /*** Start of inlined file: juce_TabbedButtonBar.cpp ***/
  51509. BEGIN_JUCE_NAMESPACE
  51510. TabBarButton::TabBarButton (const String& name,
  51511. TabbedButtonBar* const owner_,
  51512. const int index)
  51513. : Button (name),
  51514. owner (owner_),
  51515. tabIndex (index),
  51516. overlapPixels (0)
  51517. {
  51518. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  51519. setComponentEffect (&shadow);
  51520. setWantsKeyboardFocus (false);
  51521. }
  51522. TabBarButton::~TabBarButton()
  51523. {
  51524. }
  51525. void TabBarButton::paintButton (Graphics& g,
  51526. bool isMouseOverButton,
  51527. bool isButtonDown)
  51528. {
  51529. int x, y, w, h;
  51530. getActiveArea (x, y, w, h);
  51531. g.setOrigin (x, y);
  51532. getLookAndFeel()
  51533. .drawTabButton (g, w, h,
  51534. owner->getTabBackgroundColour (tabIndex),
  51535. tabIndex, getButtonText(), *this,
  51536. owner->getOrientation(),
  51537. isMouseOverButton, isButtonDown,
  51538. getToggleState());
  51539. }
  51540. void TabBarButton::clicked (const ModifierKeys& mods)
  51541. {
  51542. if (mods.isPopupMenu())
  51543. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  51544. else
  51545. owner->setCurrentTabIndex (tabIndex);
  51546. }
  51547. bool TabBarButton::hitTest (int mx, int my)
  51548. {
  51549. int x, y, w, h;
  51550. getActiveArea (x, y, w, h);
  51551. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  51552. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  51553. {
  51554. if (((unsigned int) mx) < (unsigned int) getWidth()
  51555. && my >= y + overlapPixels
  51556. && my < y + h - overlapPixels)
  51557. return true;
  51558. }
  51559. else
  51560. {
  51561. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  51562. && ((unsigned int) my) < (unsigned int) getHeight())
  51563. return true;
  51564. }
  51565. Path p;
  51566. getLookAndFeel()
  51567. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  51568. owner->getOrientation(),
  51569. false, false, getToggleState());
  51570. return p.contains ((float) (mx - x),
  51571. (float) (my - y));
  51572. }
  51573. int TabBarButton::getBestTabLength (const int depth)
  51574. {
  51575. return jlimit (depth * 2,
  51576. depth * 7,
  51577. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  51578. }
  51579. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  51580. {
  51581. x = 0;
  51582. y = 0;
  51583. int r = getWidth();
  51584. int b = getHeight();
  51585. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  51586. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  51587. r -= spaceAroundImage;
  51588. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  51589. x += spaceAroundImage;
  51590. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  51591. y += spaceAroundImage;
  51592. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  51593. b -= spaceAroundImage;
  51594. w = r - x;
  51595. h = b - y;
  51596. }
  51597. class TabAreaBehindFrontButtonComponent : public Component
  51598. {
  51599. public:
  51600. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  51601. : owner (owner_)
  51602. {
  51603. setInterceptsMouseClicks (false, false);
  51604. }
  51605. ~TabAreaBehindFrontButtonComponent()
  51606. {
  51607. }
  51608. void paint (Graphics& g)
  51609. {
  51610. getLookAndFeel()
  51611. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  51612. *owner, owner->getOrientation());
  51613. }
  51614. void enablementChanged()
  51615. {
  51616. repaint();
  51617. }
  51618. private:
  51619. TabbedButtonBar* const owner;
  51620. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  51621. TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  51622. };
  51623. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  51624. : orientation (orientation_),
  51625. currentTabIndex (-1)
  51626. {
  51627. setInterceptsMouseClicks (false, true);
  51628. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  51629. setFocusContainer (true);
  51630. }
  51631. TabbedButtonBar::~TabbedButtonBar()
  51632. {
  51633. extraTabsButton = 0;
  51634. deleteAllChildren();
  51635. }
  51636. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  51637. {
  51638. orientation = newOrientation;
  51639. for (int i = getNumChildComponents(); --i >= 0;)
  51640. getChildComponent (i)->resized();
  51641. resized();
  51642. }
  51643. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  51644. {
  51645. return new TabBarButton (name, this, index);
  51646. }
  51647. void TabbedButtonBar::clearTabs()
  51648. {
  51649. tabs.clear();
  51650. tabColours.clear();
  51651. currentTabIndex = -1;
  51652. extraTabsButton = 0;
  51653. removeChildComponent (behindFrontTab);
  51654. deleteAllChildren();
  51655. addChildComponent (behindFrontTab);
  51656. setCurrentTabIndex (-1);
  51657. }
  51658. void TabbedButtonBar::addTab (const String& tabName,
  51659. const Colour& tabBackgroundColour,
  51660. int insertIndex)
  51661. {
  51662. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  51663. if (tabName.isNotEmpty())
  51664. {
  51665. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  51666. insertIndex = tabs.size();
  51667. for (int i = tabs.size(); --i >= insertIndex;)
  51668. {
  51669. TabBarButton* const tb = getTabButton (i);
  51670. if (tb != 0)
  51671. tb->tabIndex++;
  51672. }
  51673. tabs.insert (insertIndex, tabName);
  51674. tabColours.insert (insertIndex, tabBackgroundColour);
  51675. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  51676. jassert (tb != 0); // your createTabButton() mustn't return zero!
  51677. addAndMakeVisible (tb, insertIndex);
  51678. resized();
  51679. if (currentTabIndex < 0)
  51680. setCurrentTabIndex (0);
  51681. }
  51682. }
  51683. void TabbedButtonBar::setTabName (const int tabIndex,
  51684. const String& newName)
  51685. {
  51686. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  51687. && tabs[tabIndex] != newName)
  51688. {
  51689. tabs.set (tabIndex, newName);
  51690. TabBarButton* const tb = getTabButton (tabIndex);
  51691. if (tb != 0)
  51692. tb->setButtonText (newName);
  51693. resized();
  51694. }
  51695. }
  51696. void TabbedButtonBar::removeTab (const int tabIndex)
  51697. {
  51698. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  51699. {
  51700. const int oldTabIndex = currentTabIndex;
  51701. if (currentTabIndex == tabIndex)
  51702. currentTabIndex = -1;
  51703. tabs.remove (tabIndex);
  51704. tabColours.remove (tabIndex);
  51705. delete getTabButton (tabIndex);
  51706. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  51707. {
  51708. TabBarButton* const tb = getTabButton (i);
  51709. if (tb != 0)
  51710. tb->tabIndex--;
  51711. }
  51712. resized();
  51713. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  51714. }
  51715. }
  51716. void TabbedButtonBar::moveTab (const int currentIndex,
  51717. const int newIndex)
  51718. {
  51719. tabs.move (currentIndex, newIndex);
  51720. tabColours.move (currentIndex, newIndex);
  51721. resized();
  51722. }
  51723. int TabbedButtonBar::getNumTabs() const
  51724. {
  51725. return tabs.size();
  51726. }
  51727. const StringArray TabbedButtonBar::getTabNames() const
  51728. {
  51729. return tabs;
  51730. }
  51731. void TabbedButtonBar::setCurrentTabIndex (int newIndex, const bool sendChangeMessage_)
  51732. {
  51733. if (currentTabIndex != newIndex)
  51734. {
  51735. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  51736. newIndex = -1;
  51737. currentTabIndex = newIndex;
  51738. for (int i = 0; i < getNumChildComponents(); ++i)
  51739. {
  51740. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51741. if (tb != 0)
  51742. tb->setToggleState (tb->tabIndex == newIndex, false);
  51743. }
  51744. resized();
  51745. if (sendChangeMessage_)
  51746. sendChangeMessage (this);
  51747. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  51748. }
  51749. }
  51750. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  51751. {
  51752. for (int i = getNumChildComponents(); --i >= 0;)
  51753. {
  51754. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51755. if (tb != 0 && tb->tabIndex == index)
  51756. return tb;
  51757. }
  51758. return 0;
  51759. }
  51760. void TabbedButtonBar::lookAndFeelChanged()
  51761. {
  51762. extraTabsButton = 0;
  51763. resized();
  51764. }
  51765. void TabbedButtonBar::resized()
  51766. {
  51767. const double minimumScale = 0.7;
  51768. int depth = getWidth();
  51769. int length = getHeight();
  51770. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51771. swapVariables (depth, length);
  51772. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  51773. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  51774. int i, totalLength = overlap;
  51775. int numVisibleButtons = tabs.size();
  51776. for (i = 0; i < getNumChildComponents(); ++i)
  51777. {
  51778. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  51779. if (tb != 0)
  51780. {
  51781. totalLength += tb->getBestTabLength (depth) - overlap;
  51782. tb->overlapPixels = overlap / 2;
  51783. }
  51784. }
  51785. double scale = 1.0;
  51786. if (totalLength > length)
  51787. scale = jmax (minimumScale, length / (double) totalLength);
  51788. const bool isTooBig = totalLength * scale > length;
  51789. int tabsButtonPos = 0;
  51790. if (isTooBig)
  51791. {
  51792. if (extraTabsButton == 0)
  51793. {
  51794. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  51795. extraTabsButton->addButtonListener (this);
  51796. extraTabsButton->setAlwaysOnTop (true);
  51797. extraTabsButton->setTriggeredOnMouseDown (true);
  51798. }
  51799. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  51800. extraTabsButton->setSize (buttonSize, buttonSize);
  51801. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51802. {
  51803. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  51804. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  51805. }
  51806. else
  51807. {
  51808. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  51809. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  51810. }
  51811. totalLength = 0;
  51812. for (i = 0; i < tabs.size(); ++i)
  51813. {
  51814. TabBarButton* const tb = getTabButton (i);
  51815. if (tb != 0)
  51816. {
  51817. const int newLength = totalLength + tb->getBestTabLength (depth);
  51818. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  51819. {
  51820. totalLength += overlap;
  51821. break;
  51822. }
  51823. numVisibleButtons = i + 1;
  51824. totalLength = newLength - overlap;
  51825. }
  51826. }
  51827. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  51828. }
  51829. else
  51830. {
  51831. extraTabsButton = 0;
  51832. }
  51833. int pos = 0;
  51834. TabBarButton* frontTab = 0;
  51835. for (i = 0; i < tabs.size(); ++i)
  51836. {
  51837. TabBarButton* const tb = getTabButton (i);
  51838. if (tb != 0)
  51839. {
  51840. const int bestLength = roundToInt (scale * tb->getBestTabLength (depth));
  51841. if (i < numVisibleButtons)
  51842. {
  51843. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  51844. tb->setBounds (pos, 0, bestLength, getHeight());
  51845. else
  51846. tb->setBounds (0, pos, getWidth(), bestLength);
  51847. tb->toBack();
  51848. if (tb->tabIndex == currentTabIndex)
  51849. frontTab = tb;
  51850. tb->setVisible (true);
  51851. }
  51852. else
  51853. {
  51854. tb->setVisible (false);
  51855. }
  51856. pos += bestLength - overlap;
  51857. }
  51858. }
  51859. behindFrontTab->setBounds (getLocalBounds());
  51860. if (frontTab != 0)
  51861. {
  51862. frontTab->toFront (false);
  51863. behindFrontTab->toBehind (frontTab);
  51864. }
  51865. }
  51866. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  51867. {
  51868. return tabColours [tabIndex];
  51869. }
  51870. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  51871. {
  51872. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  51873. && tabColours [tabIndex] != newColour)
  51874. {
  51875. tabColours.set (tabIndex, newColour);
  51876. repaint();
  51877. }
  51878. }
  51879. void TabbedButtonBar::buttonClicked (Button* button)
  51880. {
  51881. if (button == extraTabsButton)
  51882. {
  51883. PopupMenu m;
  51884. for (int i = 0; i < tabs.size(); ++i)
  51885. {
  51886. TabBarButton* const tb = getTabButton (i);
  51887. if (tb != 0 && ! tb->isVisible())
  51888. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  51889. }
  51890. const int res = m.showAt (extraTabsButton);
  51891. if (res != 0)
  51892. setCurrentTabIndex (res - 1);
  51893. }
  51894. }
  51895. void TabbedButtonBar::currentTabChanged (const int, const String&)
  51896. {
  51897. }
  51898. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  51899. {
  51900. }
  51901. END_JUCE_NAMESPACE
  51902. /*** End of inlined file: juce_TabbedButtonBar.cpp ***/
  51903. /*** Start of inlined file: juce_TabbedComponent.cpp ***/
  51904. BEGIN_JUCE_NAMESPACE
  51905. class TabCompButtonBar : public TabbedButtonBar
  51906. {
  51907. public:
  51908. TabCompButtonBar (TabbedComponent* const owner_,
  51909. const TabbedButtonBar::Orientation orientation_)
  51910. : TabbedButtonBar (orientation_),
  51911. owner (owner_)
  51912. {
  51913. }
  51914. ~TabCompButtonBar()
  51915. {
  51916. }
  51917. void currentTabChanged (int newCurrentTabIndex, const String& newTabName)
  51918. {
  51919. owner->changeCallback (newCurrentTabIndex, newTabName);
  51920. }
  51921. void popupMenuClickOnTab (int tabIndex, const String& tabName)
  51922. {
  51923. owner->popupMenuClickOnTab (tabIndex, tabName);
  51924. }
  51925. const Colour getTabBackgroundColour (const int tabIndex)
  51926. {
  51927. return owner->tabs->getTabBackgroundColour (tabIndex);
  51928. }
  51929. TabBarButton* createTabButton (const String& tabName, int tabIndex)
  51930. {
  51931. return owner->createTabButton (tabName, tabIndex);
  51932. }
  51933. juce_UseDebuggingNewOperator
  51934. private:
  51935. TabbedComponent* const owner;
  51936. TabCompButtonBar (const TabCompButtonBar&);
  51937. TabCompButtonBar& operator= (const TabCompButtonBar&);
  51938. };
  51939. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  51940. : panelComponent (0),
  51941. tabDepth (30),
  51942. outlineThickness (1),
  51943. edgeIndent (0)
  51944. {
  51945. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  51946. }
  51947. TabbedComponent::~TabbedComponent()
  51948. {
  51949. clearTabs();
  51950. delete tabs;
  51951. }
  51952. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  51953. {
  51954. tabs->setOrientation (orientation);
  51955. resized();
  51956. }
  51957. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  51958. {
  51959. return tabs->getOrientation();
  51960. }
  51961. void TabbedComponent::setTabBarDepth (const int newDepth)
  51962. {
  51963. if (tabDepth != newDepth)
  51964. {
  51965. tabDepth = newDepth;
  51966. resized();
  51967. }
  51968. }
  51969. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  51970. {
  51971. return new TabBarButton (tabName, tabs, tabIndex);
  51972. }
  51973. const Identifier TabbedComponent::deleteComponentId ("deleteByTabComp_");
  51974. void TabbedComponent::clearTabs()
  51975. {
  51976. if (panelComponent != 0)
  51977. {
  51978. panelComponent->setVisible (false);
  51979. removeChildComponent (panelComponent);
  51980. panelComponent = 0;
  51981. }
  51982. tabs->clearTabs();
  51983. for (int i = contentComponents.size(); --i >= 0;)
  51984. {
  51985. Component* const c = contentComponents.getUnchecked(i);
  51986. // be careful not to delete these components until they've been removed from the tab component
  51987. jassert (c == 0 || c->isValidComponent());
  51988. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  51989. delete c;
  51990. }
  51991. contentComponents.clear();
  51992. }
  51993. void TabbedComponent::addTab (const String& tabName,
  51994. const Colour& tabBackgroundColour,
  51995. Component* const contentComponent,
  51996. const bool deleteComponentWhenNotNeeded,
  51997. const int insertIndex)
  51998. {
  51999. contentComponents.insert (insertIndex, contentComponent);
  52000. if (contentComponent != 0)
  52001. contentComponent->getProperties().set (deleteComponentId, deleteComponentWhenNotNeeded);
  52002. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  52003. }
  52004. void TabbedComponent::setTabName (const int tabIndex, const String& newName)
  52005. {
  52006. tabs->setTabName (tabIndex, newName);
  52007. }
  52008. void TabbedComponent::removeTab (const int tabIndex)
  52009. {
  52010. Component* const c = contentComponents [tabIndex];
  52011. if (c != 0 && (bool) c->getProperties() [deleteComponentId])
  52012. {
  52013. if (c == panelComponent)
  52014. panelComponent = 0;
  52015. delete c;
  52016. }
  52017. contentComponents.remove (tabIndex);
  52018. tabs->removeTab (tabIndex);
  52019. }
  52020. int TabbedComponent::getNumTabs() const
  52021. {
  52022. return tabs->getNumTabs();
  52023. }
  52024. const StringArray TabbedComponent::getTabNames() const
  52025. {
  52026. return tabs->getTabNames();
  52027. }
  52028. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  52029. {
  52030. return contentComponents [tabIndex];
  52031. }
  52032. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  52033. {
  52034. return tabs->getTabBackgroundColour (tabIndex);
  52035. }
  52036. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  52037. {
  52038. tabs->setTabBackgroundColour (tabIndex, newColour);
  52039. if (getCurrentTabIndex() == tabIndex)
  52040. repaint();
  52041. }
  52042. void TabbedComponent::setCurrentTabIndex (const int newTabIndex, const bool sendChangeMessage)
  52043. {
  52044. tabs->setCurrentTabIndex (newTabIndex, sendChangeMessage);
  52045. }
  52046. int TabbedComponent::getCurrentTabIndex() const
  52047. {
  52048. return tabs->getCurrentTabIndex();
  52049. }
  52050. const String& TabbedComponent::getCurrentTabName() const
  52051. {
  52052. return tabs->getCurrentTabName();
  52053. }
  52054. void TabbedComponent::setOutline (int thickness)
  52055. {
  52056. outlineThickness = thickness;
  52057. repaint();
  52058. }
  52059. void TabbedComponent::setIndent (const int indentThickness)
  52060. {
  52061. edgeIndent = indentThickness;
  52062. }
  52063. void TabbedComponent::paint (Graphics& g)
  52064. {
  52065. g.fillAll (findColour (backgroundColourId));
  52066. const TabbedButtonBar::Orientation o = getOrientation();
  52067. int x = 0;
  52068. int y = 0;
  52069. int r = getWidth();
  52070. int b = getHeight();
  52071. if (o == TabbedButtonBar::TabsAtTop)
  52072. y += tabDepth;
  52073. else if (o == TabbedButtonBar::TabsAtBottom)
  52074. b -= tabDepth;
  52075. else if (o == TabbedButtonBar::TabsAtLeft)
  52076. x += tabDepth;
  52077. else if (o == TabbedButtonBar::TabsAtRight)
  52078. r -= tabDepth;
  52079. g.reduceClipRegion (x, y, r - x, b - y);
  52080. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  52081. if (outlineThickness > 0)
  52082. {
  52083. if (o == TabbedButtonBar::TabsAtTop)
  52084. --y;
  52085. else if (o == TabbedButtonBar::TabsAtBottom)
  52086. ++b;
  52087. else if (o == TabbedButtonBar::TabsAtLeft)
  52088. --x;
  52089. else if (o == TabbedButtonBar::TabsAtRight)
  52090. ++r;
  52091. g.setColour (findColour (outlineColourId));
  52092. g.drawRect (x, y, r - x, b - y, outlineThickness);
  52093. }
  52094. }
  52095. void TabbedComponent::resized()
  52096. {
  52097. const TabbedButtonBar::Orientation o = getOrientation();
  52098. const int indent = edgeIndent + outlineThickness;
  52099. BorderSize indents (indent);
  52100. if (o == TabbedButtonBar::TabsAtTop)
  52101. {
  52102. tabs->setBounds (0, 0, getWidth(), tabDepth);
  52103. indents.setTop (tabDepth + edgeIndent);
  52104. }
  52105. else if (o == TabbedButtonBar::TabsAtBottom)
  52106. {
  52107. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  52108. indents.setBottom (tabDepth + edgeIndent);
  52109. }
  52110. else if (o == TabbedButtonBar::TabsAtLeft)
  52111. {
  52112. tabs->setBounds (0, 0, tabDepth, getHeight());
  52113. indents.setLeft (tabDepth + edgeIndent);
  52114. }
  52115. else if (o == TabbedButtonBar::TabsAtRight)
  52116. {
  52117. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  52118. indents.setRight (tabDepth + edgeIndent);
  52119. }
  52120. const Rectangle<int> bounds (indents.subtractedFrom (getLocalBounds()));
  52121. for (int i = contentComponents.size(); --i >= 0;)
  52122. if (contentComponents.getUnchecked (i) != 0)
  52123. contentComponents.getUnchecked (i)->setBounds (bounds);
  52124. }
  52125. void TabbedComponent::lookAndFeelChanged()
  52126. {
  52127. for (int i = contentComponents.size(); --i >= 0;)
  52128. if (contentComponents.getUnchecked (i) != 0)
  52129. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  52130. }
  52131. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  52132. const String& newTabName)
  52133. {
  52134. if (panelComponent != 0)
  52135. {
  52136. panelComponent->setVisible (false);
  52137. removeChildComponent (panelComponent);
  52138. panelComponent = 0;
  52139. }
  52140. if (getCurrentTabIndex() >= 0)
  52141. {
  52142. panelComponent = contentComponents [getCurrentTabIndex()];
  52143. if (panelComponent != 0)
  52144. {
  52145. // do these ops as two stages instead of addAndMakeVisible() so that the
  52146. // component has always got a parent when it gets the visibilityChanged() callback
  52147. addChildComponent (panelComponent);
  52148. panelComponent->setVisible (true);
  52149. panelComponent->toFront (true);
  52150. }
  52151. repaint();
  52152. }
  52153. resized();
  52154. currentTabChanged (newCurrentTabIndex, newTabName);
  52155. }
  52156. void TabbedComponent::currentTabChanged (const int, const String&)
  52157. {
  52158. }
  52159. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  52160. {
  52161. }
  52162. END_JUCE_NAMESPACE
  52163. /*** End of inlined file: juce_TabbedComponent.cpp ***/
  52164. /*** Start of inlined file: juce_Viewport.cpp ***/
  52165. BEGIN_JUCE_NAMESPACE
  52166. Viewport::Viewport (const String& componentName)
  52167. : Component (componentName),
  52168. scrollBarThickness (0),
  52169. singleStepX (16),
  52170. singleStepY (16),
  52171. showHScrollbar (true),
  52172. showVScrollbar (true),
  52173. verticalScrollBar (true),
  52174. horizontalScrollBar (false)
  52175. {
  52176. // content holder is used to clip the contents so they don't overlap the scrollbars
  52177. addAndMakeVisible (&contentHolder);
  52178. contentHolder.setInterceptsMouseClicks (false, true);
  52179. addChildComponent (&verticalScrollBar);
  52180. addChildComponent (&horizontalScrollBar);
  52181. verticalScrollBar.addListener (this);
  52182. horizontalScrollBar.addListener (this);
  52183. setInterceptsMouseClicks (false, true);
  52184. setWantsKeyboardFocus (true);
  52185. }
  52186. Viewport::~Viewport()
  52187. {
  52188. contentHolder.deleteAllChildren();
  52189. }
  52190. void Viewport::visibleAreaChanged (int, int, int, int)
  52191. {
  52192. }
  52193. void Viewport::setViewedComponent (Component* const newViewedComponent)
  52194. {
  52195. if (contentComp.getComponent() != newViewedComponent)
  52196. {
  52197. {
  52198. ScopedPointer<Component> oldCompDeleter (contentComp);
  52199. contentComp = 0;
  52200. }
  52201. contentComp = newViewedComponent;
  52202. if (contentComp != 0)
  52203. {
  52204. contentComp->setTopLeftPosition (0, 0);
  52205. contentHolder.addAndMakeVisible (contentComp);
  52206. contentComp->addComponentListener (this);
  52207. }
  52208. updateVisibleArea();
  52209. }
  52210. }
  52211. int Viewport::getMaximumVisibleWidth() const
  52212. {
  52213. return contentHolder.getWidth();
  52214. }
  52215. int Viewport::getMaximumVisibleHeight() const
  52216. {
  52217. return contentHolder.getHeight();
  52218. }
  52219. void Viewport::setViewPosition (const int xPixelsOffset, const int yPixelsOffset)
  52220. {
  52221. if (contentComp != 0)
  52222. contentComp->setTopLeftPosition (jmax (jmin (0, contentHolder.getWidth() - contentComp->getWidth()), jmin (0, -xPixelsOffset)),
  52223. jmax (jmin (0, contentHolder.getHeight() - contentComp->getHeight()), jmin (0, -yPixelsOffset)));
  52224. }
  52225. void Viewport::setViewPosition (const Point<int>& newPosition)
  52226. {
  52227. setViewPosition (newPosition.getX(), newPosition.getY());
  52228. }
  52229. void Viewport::setViewPositionProportionately (const double x, const double y)
  52230. {
  52231. if (contentComp != 0)
  52232. setViewPosition (jmax (0, roundToInt (x * (contentComp->getWidth() - getWidth()))),
  52233. jmax (0, roundToInt (y * (contentComp->getHeight() - getHeight()))));
  52234. }
  52235. bool Viewport::autoScroll (const int mouseX, const int mouseY, const int activeBorderThickness, const int maximumSpeed)
  52236. {
  52237. if (contentComp != 0)
  52238. {
  52239. int dx = 0, dy = 0;
  52240. if (horizontalScrollBar.isVisible() || contentComp->getX() < 0 || contentComp->getRight() > getWidth())
  52241. {
  52242. if (mouseX < activeBorderThickness)
  52243. dx = activeBorderThickness - mouseX;
  52244. else if (mouseX >= contentHolder.getWidth() - activeBorderThickness)
  52245. dx = (contentHolder.getWidth() - activeBorderThickness) - mouseX;
  52246. if (dx < 0)
  52247. dx = jmax (dx, -maximumSpeed, contentHolder.getWidth() - contentComp->getRight());
  52248. else
  52249. dx = jmin (dx, maximumSpeed, -contentComp->getX());
  52250. }
  52251. if (verticalScrollBar.isVisible() || contentComp->getY() < 0 || contentComp->getBottom() > getHeight())
  52252. {
  52253. if (mouseY < activeBorderThickness)
  52254. dy = activeBorderThickness - mouseY;
  52255. else if (mouseY >= contentHolder.getHeight() - activeBorderThickness)
  52256. dy = (contentHolder.getHeight() - activeBorderThickness) - mouseY;
  52257. if (dy < 0)
  52258. dy = jmax (dy, -maximumSpeed, contentHolder.getHeight() - contentComp->getBottom());
  52259. else
  52260. dy = jmin (dy, maximumSpeed, -contentComp->getY());
  52261. }
  52262. if (dx != 0 || dy != 0)
  52263. {
  52264. contentComp->setTopLeftPosition (contentComp->getX() + dx,
  52265. contentComp->getY() + dy);
  52266. return true;
  52267. }
  52268. }
  52269. return false;
  52270. }
  52271. void Viewport::componentMovedOrResized (Component&, bool, bool)
  52272. {
  52273. updateVisibleArea();
  52274. }
  52275. void Viewport::resized()
  52276. {
  52277. updateVisibleArea();
  52278. }
  52279. void Viewport::updateVisibleArea()
  52280. {
  52281. const int scrollbarWidth = getScrollBarThickness();
  52282. const bool canShowAnyBars = getWidth() > scrollbarWidth && getHeight() > scrollbarWidth;
  52283. const bool canShowHBar = showHScrollbar && canShowAnyBars;
  52284. const bool canShowVBar = showVScrollbar && canShowAnyBars;
  52285. bool hBarVisible = canShowHBar && ! horizontalScrollBar.autoHides();
  52286. bool vBarVisible = canShowVBar && ! verticalScrollBar.autoHides();
  52287. Rectangle<int> contentArea (getLocalBounds());
  52288. if (contentComp != 0 && ! contentArea.contains (contentComp->getBounds()))
  52289. {
  52290. hBarVisible = canShowHBar && (hBarVisible || contentComp->getX() < 0 || contentComp->getRight() > contentArea.getWidth());
  52291. vBarVisible = canShowVBar && (vBarVisible || contentComp->getY() < 0 || contentComp->getBottom() > contentArea.getHeight());
  52292. if (vBarVisible)
  52293. contentArea.setWidth (getWidth() - scrollbarWidth);
  52294. if (hBarVisible)
  52295. contentArea.setHeight (getHeight() - scrollbarWidth);
  52296. if (! contentArea.contains (contentComp->getBounds()))
  52297. {
  52298. hBarVisible = canShowHBar && (hBarVisible || contentComp->getRight() > contentArea.getWidth());
  52299. vBarVisible = canShowVBar && (vBarVisible || contentComp->getBottom() > contentArea.getHeight());
  52300. }
  52301. }
  52302. if (vBarVisible)
  52303. contentArea.setWidth (getWidth() - scrollbarWidth);
  52304. if (hBarVisible)
  52305. contentArea.setHeight (getHeight() - scrollbarWidth);
  52306. contentHolder.setBounds (contentArea);
  52307. Rectangle<int> contentBounds;
  52308. if (contentComp != 0)
  52309. contentBounds = contentComp->getBounds();
  52310. const Point<int> visibleOrigin (-contentBounds.getPosition());
  52311. if (hBarVisible)
  52312. {
  52313. horizontalScrollBar.setBounds (0, contentArea.getHeight(), contentArea.getWidth(), scrollbarWidth);
  52314. horizontalScrollBar.setRangeLimits (0.0, contentBounds.getWidth());
  52315. horizontalScrollBar.setCurrentRange (visibleOrigin.getX(), contentArea.getWidth());
  52316. horizontalScrollBar.setSingleStepSize (singleStepX);
  52317. horizontalScrollBar.cancelPendingUpdate();
  52318. }
  52319. if (vBarVisible)
  52320. {
  52321. verticalScrollBar.setBounds (contentArea.getWidth(), 0, scrollbarWidth, contentArea.getHeight());
  52322. verticalScrollBar.setRangeLimits (0.0, contentBounds.getHeight());
  52323. verticalScrollBar.setCurrentRange (visibleOrigin.getY(), contentArea.getHeight());
  52324. verticalScrollBar.setSingleStepSize (singleStepY);
  52325. verticalScrollBar.cancelPendingUpdate();
  52326. }
  52327. // Force the visibility *after* setting the ranges to avoid flicker caused by edge conditions in the numbers.
  52328. horizontalScrollBar.setVisible (hBarVisible);
  52329. verticalScrollBar.setVisible (vBarVisible);
  52330. const Rectangle<int> visibleArea (visibleOrigin.getX(), visibleOrigin.getY(),
  52331. jmin (contentBounds.getWidth() - visibleOrigin.getX(), contentArea.getWidth()),
  52332. jmin (contentBounds.getHeight() - visibleOrigin.getY(), contentArea.getHeight()));
  52333. if (lastVisibleArea != visibleArea)
  52334. {
  52335. lastVisibleArea = visibleArea;
  52336. visibleAreaChanged (visibleArea.getX(), visibleArea.getY(), visibleArea.getWidth(), visibleArea.getHeight());
  52337. }
  52338. horizontalScrollBar.handleUpdateNowIfNeeded();
  52339. verticalScrollBar.handleUpdateNowIfNeeded();
  52340. }
  52341. void Viewport::setSingleStepSizes (const int stepX, const int stepY)
  52342. {
  52343. if (singleStepX != stepX || singleStepY != stepY)
  52344. {
  52345. singleStepX = stepX;
  52346. singleStepY = stepY;
  52347. updateVisibleArea();
  52348. }
  52349. }
  52350. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  52351. const bool showHorizontalScrollbarIfNeeded)
  52352. {
  52353. if (showVScrollbar != showVerticalScrollbarIfNeeded
  52354. || showHScrollbar != showHorizontalScrollbarIfNeeded)
  52355. {
  52356. showVScrollbar = showVerticalScrollbarIfNeeded;
  52357. showHScrollbar = showHorizontalScrollbarIfNeeded;
  52358. updateVisibleArea();
  52359. }
  52360. }
  52361. void Viewport::setScrollBarThickness (const int thickness)
  52362. {
  52363. if (scrollBarThickness != thickness)
  52364. {
  52365. scrollBarThickness = thickness;
  52366. updateVisibleArea();
  52367. }
  52368. }
  52369. int Viewport::getScrollBarThickness() const
  52370. {
  52371. return scrollBarThickness > 0 ? scrollBarThickness
  52372. : getLookAndFeel().getDefaultScrollbarWidth();
  52373. }
  52374. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  52375. {
  52376. verticalScrollBar.setButtonVisibility (buttonsVisible);
  52377. horizontalScrollBar.setButtonVisibility (buttonsVisible);
  52378. }
  52379. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, double newRangeStart)
  52380. {
  52381. const int newRangeStartInt = roundToInt (newRangeStart);
  52382. if (scrollBarThatHasMoved == &horizontalScrollBar)
  52383. {
  52384. setViewPosition (newRangeStartInt, getViewPositionY());
  52385. }
  52386. else if (scrollBarThatHasMoved == &verticalScrollBar)
  52387. {
  52388. setViewPosition (getViewPositionX(), newRangeStartInt);
  52389. }
  52390. }
  52391. void Viewport::mouseWheelMove (const MouseEvent& e, const float wheelIncrementX, const float wheelIncrementY)
  52392. {
  52393. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  52394. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  52395. }
  52396. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  52397. {
  52398. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  52399. {
  52400. const bool hasVertBar = verticalScrollBar.isVisible();
  52401. const bool hasHorzBar = horizontalScrollBar.isVisible();
  52402. if (hasHorzBar || hasVertBar)
  52403. {
  52404. if (wheelIncrementX != 0)
  52405. {
  52406. wheelIncrementX *= 14.0f * singleStepX;
  52407. wheelIncrementX = (wheelIncrementX < 0) ? jmin (wheelIncrementX, -1.0f)
  52408. : jmax (wheelIncrementX, 1.0f);
  52409. }
  52410. if (wheelIncrementY != 0)
  52411. {
  52412. wheelIncrementY *= 14.0f * singleStepY;
  52413. wheelIncrementY = (wheelIncrementY < 0) ? jmin (wheelIncrementY, -1.0f)
  52414. : jmax (wheelIncrementY, 1.0f);
  52415. }
  52416. Point<int> pos (getViewPosition());
  52417. if (wheelIncrementX != 0 && wheelIncrementY != 0 && hasHorzBar && hasVertBar)
  52418. {
  52419. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52420. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52421. }
  52422. else if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  52423. {
  52424. if (wheelIncrementX == 0 && ! hasVertBar)
  52425. wheelIncrementX = wheelIncrementY;
  52426. pos.setX (pos.getX() - roundToInt (wheelIncrementX));
  52427. }
  52428. else if (hasVertBar && wheelIncrementY != 0)
  52429. {
  52430. pos.setY (pos.getY() - roundToInt (wheelIncrementY));
  52431. }
  52432. if (pos != getViewPosition())
  52433. {
  52434. setViewPosition (pos);
  52435. return true;
  52436. }
  52437. }
  52438. }
  52439. return false;
  52440. }
  52441. bool Viewport::keyPressed (const KeyPress& key)
  52442. {
  52443. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  52444. || key.isKeyCode (KeyPress::downKey)
  52445. || key.isKeyCode (KeyPress::pageUpKey)
  52446. || key.isKeyCode (KeyPress::pageDownKey)
  52447. || key.isKeyCode (KeyPress::homeKey)
  52448. || key.isKeyCode (KeyPress::endKey);
  52449. if (verticalScrollBar.isVisible() && isUpDownKey)
  52450. return verticalScrollBar.keyPressed (key);
  52451. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  52452. || key.isKeyCode (KeyPress::rightKey);
  52453. if (horizontalScrollBar.isVisible() && (isUpDownKey || isLeftRightKey))
  52454. return horizontalScrollBar.keyPressed (key);
  52455. return false;
  52456. }
  52457. END_JUCE_NAMESPACE
  52458. /*** End of inlined file: juce_Viewport.cpp ***/
  52459. /*** Start of inlined file: juce_LookAndFeel.cpp ***/
  52460. BEGIN_JUCE_NAMESPACE
  52461. namespace LookAndFeelHelpers
  52462. {
  52463. void createRoundedPath (Path& p,
  52464. const float x, const float y,
  52465. const float w, const float h,
  52466. const float cs,
  52467. const bool curveTopLeft, const bool curveTopRight,
  52468. const bool curveBottomLeft, const bool curveBottomRight) throw()
  52469. {
  52470. const float cs2 = 2.0f * cs;
  52471. if (curveTopLeft)
  52472. {
  52473. p.startNewSubPath (x, y + cs);
  52474. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  52475. }
  52476. else
  52477. {
  52478. p.startNewSubPath (x, y);
  52479. }
  52480. if (curveTopRight)
  52481. {
  52482. p.lineTo (x + w - cs, y);
  52483. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  52484. }
  52485. else
  52486. {
  52487. p.lineTo (x + w, y);
  52488. }
  52489. if (curveBottomRight)
  52490. {
  52491. p.lineTo (x + w, y + h - cs);
  52492. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  52493. }
  52494. else
  52495. {
  52496. p.lineTo (x + w, y + h);
  52497. }
  52498. if (curveBottomLeft)
  52499. {
  52500. p.lineTo (x + cs, y + h);
  52501. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  52502. }
  52503. else
  52504. {
  52505. p.lineTo (x, y + h);
  52506. }
  52507. p.closeSubPath();
  52508. }
  52509. const Colour createBaseColour (const Colour& buttonColour,
  52510. const bool hasKeyboardFocus,
  52511. const bool isMouseOverButton,
  52512. const bool isButtonDown) throw()
  52513. {
  52514. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  52515. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  52516. if (isButtonDown)
  52517. return baseColour.contrasting (0.2f);
  52518. else if (isMouseOverButton)
  52519. return baseColour.contrasting (0.1f);
  52520. return baseColour;
  52521. }
  52522. const TextLayout layoutTooltipText (const String& text) throw()
  52523. {
  52524. const float tooltipFontSize = 12.0f;
  52525. const int maxToolTipWidth = 400;
  52526. const Font f (tooltipFontSize, Font::bold);
  52527. TextLayout tl (text, f);
  52528. tl.layout (maxToolTipWidth, Justification::left, true);
  52529. return tl;
  52530. }
  52531. }
  52532. LookAndFeel::LookAndFeel()
  52533. {
  52534. /* if this fails it means you're trying to create a LookAndFeel object before
  52535. the static Colours have been initialised. That ain't gonna work. It probably
  52536. means that you're using a static LookAndFeel object and that your compiler has
  52537. decided to intialise it before the Colours class.
  52538. */
  52539. jassert (Colours::white == Colour (0xffffffff));
  52540. // set up the standard set of colours..
  52541. const int textButtonColour = 0xffbbbbff;
  52542. const int textHighlightColour = 0x401111ee;
  52543. const int standardOutlineColour = 0xb2808080;
  52544. static const int standardColours[] =
  52545. {
  52546. TextButton::buttonColourId, textButtonColour,
  52547. TextButton::buttonOnColourId, 0xff4444ff,
  52548. TextButton::textColourOnId, 0xff000000,
  52549. TextButton::textColourOffId, 0xff000000,
  52550. ComboBox::buttonColourId, 0xffbbbbff,
  52551. ComboBox::outlineColourId, standardOutlineColour,
  52552. ToggleButton::textColourId, 0xff000000,
  52553. TextEditor::backgroundColourId, 0xffffffff,
  52554. TextEditor::textColourId, 0xff000000,
  52555. TextEditor::highlightColourId, textHighlightColour,
  52556. TextEditor::highlightedTextColourId, 0xff000000,
  52557. TextEditor::caretColourId, 0xff000000,
  52558. TextEditor::outlineColourId, 0x00000000,
  52559. TextEditor::focusedOutlineColourId, textButtonColour,
  52560. TextEditor::shadowColourId, 0x38000000,
  52561. Label::backgroundColourId, 0x00000000,
  52562. Label::textColourId, 0xff000000,
  52563. Label::outlineColourId, 0x00000000,
  52564. ScrollBar::backgroundColourId, 0x00000000,
  52565. ScrollBar::thumbColourId, 0xffffffff,
  52566. ScrollBar::trackColourId, 0xffffffff,
  52567. TreeView::linesColourId, 0x4c000000,
  52568. TreeView::backgroundColourId, 0x00000000,
  52569. TreeView::dragAndDropIndicatorColourId, 0x80ff0000,
  52570. PopupMenu::backgroundColourId, 0xffffffff,
  52571. PopupMenu::textColourId, 0xff000000,
  52572. PopupMenu::headerTextColourId, 0xff000000,
  52573. PopupMenu::highlightedTextColourId, 0xffffffff,
  52574. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  52575. ComboBox::textColourId, 0xff000000,
  52576. ComboBox::backgroundColourId, 0xffffffff,
  52577. ComboBox::arrowColourId, 0x99000000,
  52578. ListBox::backgroundColourId, 0xffffffff,
  52579. ListBox::outlineColourId, standardOutlineColour,
  52580. ListBox::textColourId, 0xff000000,
  52581. Slider::backgroundColourId, 0x00000000,
  52582. Slider::thumbColourId, textButtonColour,
  52583. Slider::trackColourId, 0x7fffffff,
  52584. Slider::rotarySliderFillColourId, 0x7f0000ff,
  52585. Slider::rotarySliderOutlineColourId, 0x66000000,
  52586. Slider::textBoxTextColourId, 0xff000000,
  52587. Slider::textBoxBackgroundColourId, 0xffffffff,
  52588. Slider::textBoxHighlightColourId, textHighlightColour,
  52589. Slider::textBoxOutlineColourId, standardOutlineColour,
  52590. ResizableWindow::backgroundColourId, 0xff777777,
  52591. //DocumentWindow::textColourId, 0xff000000, // (this is deliberately not set)
  52592. AlertWindow::backgroundColourId, 0xffededed,
  52593. AlertWindow::textColourId, 0xff000000,
  52594. AlertWindow::outlineColourId, 0xff666666,
  52595. ProgressBar::backgroundColourId, 0xffeeeeee,
  52596. ProgressBar::foregroundColourId, 0xffaaaaee,
  52597. TooltipWindow::backgroundColourId, 0xffeeeebb,
  52598. TooltipWindow::textColourId, 0xff000000,
  52599. TooltipWindow::outlineColourId, 0x4c000000,
  52600. TabbedComponent::backgroundColourId, 0x00000000,
  52601. TabbedComponent::outlineColourId, 0xff777777,
  52602. TabbedButtonBar::tabOutlineColourId, 0x80000000,
  52603. TabbedButtonBar::frontOutlineColourId, 0x90000000,
  52604. Toolbar::backgroundColourId, 0xfff6f8f9,
  52605. Toolbar::separatorColourId, 0x4c000000,
  52606. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  52607. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  52608. Toolbar::labelTextColourId, 0xff000000,
  52609. Toolbar::editingModeOutlineColourId, 0xffff0000,
  52610. HyperlinkButton::textColourId, 0xcc1111ee,
  52611. GroupComponent::outlineColourId, 0x66000000,
  52612. GroupComponent::textColourId, 0xff000000,
  52613. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  52614. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  52615. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  52616. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  52617. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  52618. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  52619. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  52620. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  52621. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  52622. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  52623. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  52624. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  52625. CodeEditorComponent::backgroundColourId, 0xffffffff,
  52626. CodeEditorComponent::caretColourId, 0xff000000,
  52627. CodeEditorComponent::highlightColourId, textHighlightColour,
  52628. CodeEditorComponent::defaultTextColourId, 0xff000000,
  52629. ColourSelector::backgroundColourId, 0xffe5e5e5,
  52630. ColourSelector::labelTextColourId, 0xff000000,
  52631. KeyMappingEditorComponent::backgroundColourId, 0x00000000,
  52632. KeyMappingEditorComponent::textColourId, 0xff000000,
  52633. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  52634. FileChooserDialogBox::titleTextColourId, 0xff000000,
  52635. DrawableButton::textColourId, 0xff000000,
  52636. };
  52637. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  52638. setColour (standardColours [i], Colour (standardColours [i + 1]));
  52639. static String defaultSansName, defaultSerifName, defaultFixedName;
  52640. if (defaultSansName.isEmpty())
  52641. Font::getPlatformDefaultFontNames (defaultSansName, defaultSerifName, defaultFixedName);
  52642. defaultSans = defaultSansName;
  52643. defaultSerif = defaultSerifName;
  52644. defaultFixed = defaultFixedName;
  52645. }
  52646. LookAndFeel::~LookAndFeel()
  52647. {
  52648. }
  52649. const Colour LookAndFeel::findColour (const int colourId) const throw()
  52650. {
  52651. const int index = colourIds.indexOf (colourId);
  52652. if (index >= 0)
  52653. return colours [index];
  52654. jassertfalse;
  52655. return Colours::black;
  52656. }
  52657. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  52658. {
  52659. const int index = colourIds.indexOf (colourId);
  52660. if (index >= 0)
  52661. {
  52662. colours.set (index, colour);
  52663. }
  52664. else
  52665. {
  52666. colourIds.add (colourId);
  52667. colours.add (colour);
  52668. }
  52669. }
  52670. bool LookAndFeel::isColourSpecified (const int colourId) const throw()
  52671. {
  52672. return colourIds.contains (colourId);
  52673. }
  52674. static LookAndFeel* defaultLF = 0;
  52675. static LookAndFeel* currentDefaultLF = 0;
  52676. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  52677. {
  52678. // if this happens, your app hasn't initialised itself properly.. if you're
  52679. // trying to hack your own main() function, have a look at
  52680. // JUCEApplication::initialiseForGUI()
  52681. jassert (currentDefaultLF != 0);
  52682. return *currentDefaultLF;
  52683. }
  52684. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  52685. {
  52686. if (newDefaultLookAndFeel == 0)
  52687. {
  52688. if (defaultLF == 0)
  52689. defaultLF = new LookAndFeel();
  52690. newDefaultLookAndFeel = defaultLF;
  52691. }
  52692. currentDefaultLF = newDefaultLookAndFeel;
  52693. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  52694. {
  52695. Component* const c = Desktop::getInstance().getComponent (i);
  52696. if (c != 0)
  52697. c->sendLookAndFeelChange();
  52698. }
  52699. }
  52700. void LookAndFeel::clearDefaultLookAndFeel() throw()
  52701. {
  52702. if (currentDefaultLF == defaultLF)
  52703. currentDefaultLF = 0;
  52704. deleteAndZero (defaultLF);
  52705. }
  52706. const Typeface::Ptr LookAndFeel::getTypefaceForFont (const Font& font)
  52707. {
  52708. String faceName (font.getTypefaceName());
  52709. if (faceName == Font::getDefaultSansSerifFontName())
  52710. faceName = defaultSans;
  52711. else if (faceName == Font::getDefaultSerifFontName())
  52712. faceName = defaultSerif;
  52713. else if (faceName == Font::getDefaultMonospacedFontName())
  52714. faceName = defaultFixed;
  52715. Font f (font);
  52716. f.setTypefaceName (faceName);
  52717. return Typeface::createSystemTypefaceFor (f);
  52718. }
  52719. void LookAndFeel::setDefaultSansSerifTypefaceName (const String& newName)
  52720. {
  52721. defaultSans = newName;
  52722. }
  52723. const MouseCursor LookAndFeel::getMouseCursorFor (Component& component)
  52724. {
  52725. return component.getMouseCursor();
  52726. }
  52727. void LookAndFeel::drawButtonBackground (Graphics& g,
  52728. Button& button,
  52729. const Colour& backgroundColour,
  52730. bool isMouseOverButton,
  52731. bool isButtonDown)
  52732. {
  52733. const int width = button.getWidth();
  52734. const int height = button.getHeight();
  52735. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  52736. const float halfThickness = outlineThickness * 0.5f;
  52737. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  52738. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  52739. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  52740. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  52741. const Colour baseColour (LookAndFeelHelpers::createBaseColour (backgroundColour,
  52742. button.hasKeyboardFocus (true),
  52743. isMouseOverButton, isButtonDown)
  52744. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52745. drawGlassLozenge (g,
  52746. indentL,
  52747. indentT,
  52748. width - indentL - indentR,
  52749. height - indentT - indentB,
  52750. baseColour, outlineThickness, -1.0f,
  52751. button.isConnectedOnLeft(),
  52752. button.isConnectedOnRight(),
  52753. button.isConnectedOnTop(),
  52754. button.isConnectedOnBottom());
  52755. }
  52756. const Font LookAndFeel::getFontForTextButton (TextButton& button)
  52757. {
  52758. return button.getFont();
  52759. }
  52760. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  52761. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  52762. {
  52763. Font font (getFontForTextButton (button));
  52764. g.setFont (font);
  52765. g.setColour (button.findColour (button.getToggleState() ? TextButton::textColourOnId
  52766. : TextButton::textColourOffId)
  52767. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  52768. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  52769. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  52770. const int fontHeight = roundToInt (font.getHeight() * 0.6f);
  52771. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  52772. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  52773. g.drawFittedText (button.getButtonText(),
  52774. leftIndent,
  52775. yIndent,
  52776. button.getWidth() - leftIndent - rightIndent,
  52777. button.getHeight() - yIndent * 2,
  52778. Justification::centred, 2);
  52779. }
  52780. void LookAndFeel::drawTickBox (Graphics& g,
  52781. Component& component,
  52782. float x, float y, float w, float h,
  52783. const bool ticked,
  52784. const bool isEnabled,
  52785. const bool isMouseOverButton,
  52786. const bool isButtonDown)
  52787. {
  52788. const float boxSize = w * 0.7f;
  52789. drawGlassSphere (g, x, y + (h - boxSize) * 0.5f, boxSize,
  52790. LookAndFeelHelpers::createBaseColour (component.findColour (TextButton::buttonColourId)
  52791. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  52792. true, isMouseOverButton, isButtonDown),
  52793. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  52794. if (ticked)
  52795. {
  52796. Path tick;
  52797. tick.startNewSubPath (1.5f, 3.0f);
  52798. tick.lineTo (3.0f, 6.0f);
  52799. tick.lineTo (6.0f, 0.0f);
  52800. g.setColour (isEnabled ? Colours::black : Colours::grey);
  52801. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  52802. .translated (x, y));
  52803. g.strokePath (tick, PathStrokeType (2.5f), trans);
  52804. }
  52805. }
  52806. void LookAndFeel::drawToggleButton (Graphics& g,
  52807. ToggleButton& button,
  52808. bool isMouseOverButton,
  52809. bool isButtonDown)
  52810. {
  52811. if (button.hasKeyboardFocus (true))
  52812. {
  52813. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  52814. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  52815. }
  52816. float fontSize = jmin (15.0f, button.getHeight() * 0.75f);
  52817. const float tickWidth = fontSize * 1.1f;
  52818. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  52819. tickWidth, tickWidth,
  52820. button.getToggleState(),
  52821. button.isEnabled(),
  52822. isMouseOverButton,
  52823. isButtonDown);
  52824. g.setColour (button.findColour (ToggleButton::textColourId));
  52825. g.setFont (fontSize);
  52826. if (! button.isEnabled())
  52827. g.setOpacity (0.5f);
  52828. const int textX = (int) tickWidth + 5;
  52829. g.drawFittedText (button.getButtonText(),
  52830. textX, 0,
  52831. button.getWidth() - textX - 2, button.getHeight(),
  52832. Justification::centredLeft, 10);
  52833. }
  52834. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  52835. {
  52836. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  52837. const int tickWidth = jmin (24, button.getHeight());
  52838. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  52839. button.getHeight());
  52840. }
  52841. AlertWindow* LookAndFeel::createAlertWindow (const String& title,
  52842. const String& message,
  52843. const String& button1,
  52844. const String& button2,
  52845. const String& button3,
  52846. AlertWindow::AlertIconType iconType,
  52847. int numButtons,
  52848. Component* associatedComponent)
  52849. {
  52850. AlertWindow* aw = new AlertWindow (title, message, iconType, associatedComponent);
  52851. if (numButtons == 1)
  52852. {
  52853. aw->addButton (button1, 0,
  52854. KeyPress (KeyPress::escapeKey, 0, 0),
  52855. KeyPress (KeyPress::returnKey, 0, 0));
  52856. }
  52857. else
  52858. {
  52859. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  52860. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  52861. if (button1ShortCut == button2ShortCut)
  52862. button2ShortCut = KeyPress();
  52863. if (numButtons == 2)
  52864. {
  52865. aw->addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  52866. aw->addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  52867. }
  52868. else if (numButtons == 3)
  52869. {
  52870. aw->addButton (button1, 1, button1ShortCut);
  52871. aw->addButton (button2, 2, button2ShortCut);
  52872. aw->addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  52873. }
  52874. }
  52875. return aw;
  52876. }
  52877. void LookAndFeel::drawAlertBox (Graphics& g,
  52878. AlertWindow& alert,
  52879. const Rectangle<int>& textArea,
  52880. TextLayout& textLayout)
  52881. {
  52882. g.fillAll (alert.findColour (AlertWindow::backgroundColourId));
  52883. int iconSpaceUsed = 0;
  52884. Justification alignment (Justification::horizontallyCentred);
  52885. const int iconWidth = 80;
  52886. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  52887. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  52888. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  52889. const Rectangle<int> iconRect (iconSize / -10, iconSize / -10,
  52890. iconSize, iconSize);
  52891. if (alert.getAlertType() != AlertWindow::NoIcon)
  52892. {
  52893. Path icon;
  52894. uint32 colour;
  52895. char character;
  52896. if (alert.getAlertType() == AlertWindow::WarningIcon)
  52897. {
  52898. colour = 0x55ff5555;
  52899. character = '!';
  52900. icon.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f, (float) iconRect.getY(),
  52901. (float) iconRect.getRight(), (float) iconRect.getBottom(),
  52902. (float) iconRect.getX(), (float) iconRect.getBottom());
  52903. icon = icon.createPathWithRoundedCorners (5.0f);
  52904. }
  52905. else
  52906. {
  52907. colour = alert.getAlertType() == AlertWindow::InfoIcon ? 0x605555ff : 0x40b69900;
  52908. character = alert.getAlertType() == AlertWindow::InfoIcon ? 'i' : '?';
  52909. icon.addEllipse ((float) iconRect.getX(), (float) iconRect.getY(),
  52910. (float) iconRect.getWidth(), (float) iconRect.getHeight());
  52911. }
  52912. GlyphArrangement ga;
  52913. ga.addFittedText (Font (iconRect.getHeight() * 0.9f, Font::bold),
  52914. String::charToString (character),
  52915. (float) iconRect.getX(), (float) iconRect.getY(),
  52916. (float) iconRect.getWidth(), (float) iconRect.getHeight(),
  52917. Justification::centred, false);
  52918. ga.createPath (icon);
  52919. icon.setUsingNonZeroWinding (false);
  52920. g.setColour (Colour (colour));
  52921. g.fillPath (icon);
  52922. iconSpaceUsed = iconWidth;
  52923. alignment = Justification::left;
  52924. }
  52925. g.setColour (alert.findColour (AlertWindow::textColourId));
  52926. textLayout.drawWithin (g,
  52927. textArea.getX() + iconSpaceUsed, textArea.getY(),
  52928. textArea.getWidth() - iconSpaceUsed, textArea.getHeight(),
  52929. alignment.getFlags() | Justification::top);
  52930. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  52931. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  52932. }
  52933. int LookAndFeel::getAlertBoxWindowFlags()
  52934. {
  52935. return ComponentPeer::windowAppearsOnTaskbar
  52936. | ComponentPeer::windowHasDropShadow;
  52937. }
  52938. int LookAndFeel::getAlertWindowButtonHeight()
  52939. {
  52940. return 28;
  52941. }
  52942. const Font LookAndFeel::getAlertWindowFont()
  52943. {
  52944. return Font (12.0f);
  52945. }
  52946. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  52947. int width, int height,
  52948. double progress, const String& textToShow)
  52949. {
  52950. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  52951. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  52952. g.fillAll (background);
  52953. if (progress >= 0.0f && progress < 1.0f)
  52954. {
  52955. drawGlassLozenge (g, 1.0f, 1.0f,
  52956. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  52957. (float) (height - 2),
  52958. foreground,
  52959. 0.5f, 0.0f,
  52960. true, true, true, true);
  52961. }
  52962. else
  52963. {
  52964. // spinning bar..
  52965. g.setColour (foreground);
  52966. const int stripeWidth = height * 2;
  52967. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  52968. Path p;
  52969. for (float x = (float) (- position); x < width + stripeWidth; x += stripeWidth)
  52970. p.addQuadrilateral (x, 0.0f,
  52971. x + stripeWidth * 0.5f, 0.0f,
  52972. x, (float) height,
  52973. x - stripeWidth * 0.5f, (float) height);
  52974. Image im (Image::ARGB, width, height, true);
  52975. {
  52976. Graphics g2 (im);
  52977. drawGlassLozenge (g2, 1.0f, 1.0f,
  52978. (float) (width - 2),
  52979. (float) (height - 2),
  52980. foreground,
  52981. 0.5f, 0.0f,
  52982. true, true, true, true);
  52983. }
  52984. g.setTiledImageFill (im, 0, 0, 0.85f);
  52985. g.fillPath (p);
  52986. }
  52987. if (textToShow.isNotEmpty())
  52988. {
  52989. g.setColour (Colour::contrasting (background, foreground));
  52990. g.setFont (height * 0.6f);
  52991. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  52992. }
  52993. }
  52994. void LookAndFeel::drawSpinningWaitAnimation (Graphics& g, const Colour& colour, int x, int y, int w, int h)
  52995. {
  52996. const float radius = jmin (w, h) * 0.4f;
  52997. const float thickness = radius * 0.15f;
  52998. Path p;
  52999. p.addRoundedRectangle (radius * 0.4f, thickness * -0.5f,
  53000. radius * 0.6f, thickness,
  53001. thickness * 0.5f);
  53002. const float cx = x + w * 0.5f;
  53003. const float cy = y + h * 0.5f;
  53004. const uint32 animationIndex = (Time::getMillisecondCounter() / (1000 / 10)) % 12;
  53005. for (int i = 0; i < 12; ++i)
  53006. {
  53007. const int n = (i + 12 - animationIndex) % 12;
  53008. g.setColour (colour.withMultipliedAlpha ((n + 1) / 12.0f));
  53009. g.fillPath (p, AffineTransform::rotation (i * (float_Pi / 6.0f))
  53010. .translated (cx, cy));
  53011. }
  53012. }
  53013. void LookAndFeel::drawScrollbarButton (Graphics& g,
  53014. ScrollBar& scrollbar,
  53015. int width, int height,
  53016. int buttonDirection,
  53017. bool /*isScrollbarVertical*/,
  53018. bool /*isMouseOverButton*/,
  53019. bool isButtonDown)
  53020. {
  53021. Path p;
  53022. if (buttonDirection == 0)
  53023. p.addTriangle (width * 0.5f, height * 0.2f,
  53024. width * 0.1f, height * 0.7f,
  53025. width * 0.9f, height * 0.7f);
  53026. else if (buttonDirection == 1)
  53027. p.addTriangle (width * 0.8f, height * 0.5f,
  53028. width * 0.3f, height * 0.1f,
  53029. width * 0.3f, height * 0.9f);
  53030. else if (buttonDirection == 2)
  53031. p.addTriangle (width * 0.5f, height * 0.8f,
  53032. width * 0.1f, height * 0.3f,
  53033. width * 0.9f, height * 0.3f);
  53034. else if (buttonDirection == 3)
  53035. p.addTriangle (width * 0.2f, height * 0.5f,
  53036. width * 0.7f, height * 0.1f,
  53037. width * 0.7f, height * 0.9f);
  53038. if (isButtonDown)
  53039. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  53040. else
  53041. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53042. g.fillPath (p);
  53043. g.setColour (Colour (0x80000000));
  53044. g.strokePath (p, PathStrokeType (0.5f));
  53045. }
  53046. void LookAndFeel::drawScrollbar (Graphics& g,
  53047. ScrollBar& scrollbar,
  53048. int x, int y,
  53049. int width, int height,
  53050. bool isScrollbarVertical,
  53051. int thumbStartPosition,
  53052. int thumbSize,
  53053. bool /*isMouseOver*/,
  53054. bool /*isMouseDown*/)
  53055. {
  53056. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  53057. Path slotPath, thumbPath;
  53058. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  53059. const float slotIndentx2 = slotIndent * 2.0f;
  53060. const float thumbIndent = slotIndent + 1.0f;
  53061. const float thumbIndentx2 = thumbIndent * 2.0f;
  53062. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  53063. if (isScrollbarVertical)
  53064. {
  53065. slotPath.addRoundedRectangle (x + slotIndent,
  53066. y + slotIndent,
  53067. width - slotIndentx2,
  53068. height - slotIndentx2,
  53069. (width - slotIndentx2) * 0.5f);
  53070. if (thumbSize > 0)
  53071. thumbPath.addRoundedRectangle (x + thumbIndent,
  53072. thumbStartPosition + thumbIndent,
  53073. width - thumbIndentx2,
  53074. thumbSize - thumbIndentx2,
  53075. (width - thumbIndentx2) * 0.5f);
  53076. gx1 = (float) x;
  53077. gx2 = x + width * 0.7f;
  53078. }
  53079. else
  53080. {
  53081. slotPath.addRoundedRectangle (x + slotIndent,
  53082. y + slotIndent,
  53083. width - slotIndentx2,
  53084. height - slotIndentx2,
  53085. (height - slotIndentx2) * 0.5f);
  53086. if (thumbSize > 0)
  53087. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  53088. y + thumbIndent,
  53089. thumbSize - thumbIndentx2,
  53090. height - thumbIndentx2,
  53091. (height - thumbIndentx2) * 0.5f);
  53092. gy1 = (float) y;
  53093. gy2 = y + height * 0.7f;
  53094. }
  53095. const Colour thumbColour (scrollbar.findColour (ScrollBar::thumbColourId));
  53096. g.setGradientFill (ColourGradient (thumbColour.overlaidWith (Colour (0x44000000)), gx1, gy1,
  53097. thumbColour.overlaidWith (Colour (0x19000000)), gx2, gy2, false));
  53098. g.fillPath (slotPath);
  53099. if (isScrollbarVertical)
  53100. {
  53101. gx1 = x + width * 0.6f;
  53102. gx2 = (float) x + width;
  53103. }
  53104. else
  53105. {
  53106. gy1 = y + height * 0.6f;
  53107. gy2 = (float) y + height;
  53108. }
  53109. g.setGradientFill (ColourGradient (Colours::transparentBlack,gx1, gy1,
  53110. Colour (0x19000000), gx2, gy2, false));
  53111. g.fillPath (slotPath);
  53112. g.setColour (thumbColour);
  53113. g.fillPath (thumbPath);
  53114. g.setGradientFill (ColourGradient (Colour (0x10000000), gx1, gy1,
  53115. Colours::transparentBlack, gx2, gy2, false));
  53116. g.saveState();
  53117. if (isScrollbarVertical)
  53118. g.reduceClipRegion (x + width / 2, y, width, height);
  53119. else
  53120. g.reduceClipRegion (x, y + height / 2, width, height);
  53121. g.fillPath (thumbPath);
  53122. g.restoreState();
  53123. g.setColour (Colour (0x4c000000));
  53124. g.strokePath (thumbPath, PathStrokeType (0.4f));
  53125. }
  53126. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  53127. {
  53128. return 0;
  53129. }
  53130. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  53131. {
  53132. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  53133. }
  53134. int LookAndFeel::getDefaultScrollbarWidth()
  53135. {
  53136. return 18;
  53137. }
  53138. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  53139. {
  53140. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  53141. : scrollbar.getHeight());
  53142. }
  53143. const Path LookAndFeel::getTickShape (const float height)
  53144. {
  53145. static const unsigned char tickShapeData[] =
  53146. {
  53147. 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,
  53148. 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,
  53149. 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,
  53150. 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,
  53151. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  53152. };
  53153. Path p;
  53154. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  53155. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53156. return p;
  53157. }
  53158. const Path LookAndFeel::getCrossShape (const float height)
  53159. {
  53160. static const unsigned char crossShapeData[] =
  53161. {
  53162. 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,
  53163. 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,
  53164. 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,
  53165. 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,
  53166. 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,
  53167. 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,
  53168. 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
  53169. };
  53170. Path p;
  53171. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  53172. p.scaleToFit (0, 0, height * 2.0f, height, true);
  53173. return p;
  53174. }
  53175. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus, bool /*isMouseOver*/)
  53176. {
  53177. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  53178. x += (w - boxSize) >> 1;
  53179. y += (h - boxSize) >> 1;
  53180. w = boxSize;
  53181. h = boxSize;
  53182. g.setColour (Colour (0xe5ffffff));
  53183. g.fillRect (x, y, w, h);
  53184. g.setColour (Colour (0x80000000));
  53185. g.drawRect (x, y, w, h);
  53186. const float size = boxSize / 2 + 1.0f;
  53187. const float centre = (float) (boxSize / 2);
  53188. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  53189. if (isPlus)
  53190. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  53191. }
  53192. void LookAndFeel::drawBubble (Graphics& g,
  53193. float tipX, float tipY,
  53194. float boxX, float boxY,
  53195. float boxW, float boxH)
  53196. {
  53197. int side = 0;
  53198. if (tipX < boxX)
  53199. side = 1;
  53200. else if (tipX > boxX + boxW)
  53201. side = 3;
  53202. else if (tipY > boxY + boxH)
  53203. side = 2;
  53204. const float indent = 2.0f;
  53205. Path p;
  53206. p.addBubble (boxX + indent,
  53207. boxY + indent,
  53208. boxW - indent * 2.0f,
  53209. boxH - indent * 2.0f,
  53210. 5.0f,
  53211. tipX, tipY,
  53212. side,
  53213. 0.5f,
  53214. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  53215. //xxx need to take comp as param for colour
  53216. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  53217. g.fillPath (p);
  53218. //xxx as above
  53219. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  53220. g.strokePath (p, PathStrokeType (1.33f));
  53221. }
  53222. const Font LookAndFeel::getPopupMenuFont()
  53223. {
  53224. return Font (17.0f);
  53225. }
  53226. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  53227. const bool isSeparator,
  53228. int standardMenuItemHeight,
  53229. int& idealWidth,
  53230. int& idealHeight)
  53231. {
  53232. if (isSeparator)
  53233. {
  53234. idealWidth = 50;
  53235. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  53236. }
  53237. else
  53238. {
  53239. Font font (getPopupMenuFont());
  53240. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  53241. font.setHeight (standardMenuItemHeight / 1.3f);
  53242. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundToInt (font.getHeight() * 1.3f);
  53243. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  53244. }
  53245. }
  53246. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  53247. {
  53248. const Colour background (findColour (PopupMenu::backgroundColourId));
  53249. g.fillAll (background);
  53250. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  53251. for (int i = 0; i < height; i += 3)
  53252. g.fillRect (0, i, width, 1);
  53253. #if ! JUCE_MAC
  53254. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  53255. g.drawRect (0, 0, width, height);
  53256. #endif
  53257. }
  53258. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  53259. int width, int height,
  53260. bool isScrollUpArrow)
  53261. {
  53262. const Colour background (findColour (PopupMenu::backgroundColourId));
  53263. g.setGradientFill (ColourGradient (background, 0.0f, height * 0.5f,
  53264. background.withAlpha (0.0f),
  53265. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  53266. false));
  53267. g.fillRect (1, 1, width - 2, height - 2);
  53268. const float hw = width * 0.5f;
  53269. const float arrowW = height * 0.3f;
  53270. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  53271. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  53272. Path p;
  53273. p.addTriangle (hw - arrowW, y1,
  53274. hw + arrowW, y1,
  53275. hw, y2);
  53276. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  53277. g.fillPath (p);
  53278. }
  53279. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  53280. int width, int height,
  53281. const bool isSeparator,
  53282. const bool isActive,
  53283. const bool isHighlighted,
  53284. const bool isTicked,
  53285. const bool hasSubMenu,
  53286. const String& text,
  53287. const String& shortcutKeyText,
  53288. Image* image,
  53289. const Colour* const textColourToUse)
  53290. {
  53291. const float halfH = height * 0.5f;
  53292. if (isSeparator)
  53293. {
  53294. const float separatorIndent = 5.5f;
  53295. g.setColour (Colour (0x33000000));
  53296. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  53297. g.setColour (Colour (0x66ffffff));
  53298. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  53299. }
  53300. else
  53301. {
  53302. Colour textColour (findColour (PopupMenu::textColourId));
  53303. if (textColourToUse != 0)
  53304. textColour = *textColourToUse;
  53305. if (isHighlighted)
  53306. {
  53307. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  53308. g.fillRect (1, 1, width - 2, height - 2);
  53309. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  53310. }
  53311. else
  53312. {
  53313. g.setColour (textColour);
  53314. }
  53315. if (! isActive)
  53316. g.setOpacity (0.3f);
  53317. Font font (getPopupMenuFont());
  53318. if (font.getHeight() > height / 1.3f)
  53319. font.setHeight (height / 1.3f);
  53320. g.setFont (font);
  53321. const int leftBorder = (height * 5) / 4;
  53322. const int rightBorder = 4;
  53323. if (image != 0)
  53324. {
  53325. g.drawImageWithin (*image,
  53326. 2, 1, leftBorder - 4, height - 2,
  53327. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  53328. }
  53329. else if (isTicked)
  53330. {
  53331. const Path tick (getTickShape (1.0f));
  53332. const float th = font.getAscent();
  53333. const float ty = halfH - th * 0.5f;
  53334. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  53335. th, true));
  53336. }
  53337. g.drawFittedText (text,
  53338. leftBorder, 0,
  53339. width - (leftBorder + rightBorder), height,
  53340. Justification::centredLeft, 1);
  53341. if (shortcutKeyText.isNotEmpty())
  53342. {
  53343. Font f2 (font);
  53344. f2.setHeight (f2.getHeight() * 0.75f);
  53345. f2.setHorizontalScale (0.95f);
  53346. g.setFont (f2);
  53347. g.drawText (shortcutKeyText,
  53348. leftBorder,
  53349. 0,
  53350. width - (leftBorder + rightBorder + 4),
  53351. height,
  53352. Justification::centredRight,
  53353. true);
  53354. }
  53355. if (hasSubMenu)
  53356. {
  53357. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  53358. const float x = width - height * 0.6f;
  53359. Path p;
  53360. p.addTriangle (x, halfH - arrowH * 0.5f,
  53361. x, halfH + arrowH * 0.5f,
  53362. x + arrowH * 0.6f, halfH);
  53363. g.fillPath (p);
  53364. }
  53365. }
  53366. }
  53367. int LookAndFeel::getMenuWindowFlags()
  53368. {
  53369. return ComponentPeer::windowHasDropShadow;
  53370. }
  53371. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  53372. bool, MenuBarComponent& menuBar)
  53373. {
  53374. const Colour baseColour (LookAndFeelHelpers::createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  53375. if (menuBar.isEnabled())
  53376. {
  53377. drawShinyButtonShape (g,
  53378. -4.0f, 0.0f,
  53379. width + 8.0f, (float) height,
  53380. 0.0f,
  53381. baseColour,
  53382. 0.4f,
  53383. true, true, true, true);
  53384. }
  53385. else
  53386. {
  53387. g.fillAll (baseColour);
  53388. }
  53389. }
  53390. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  53391. {
  53392. return Font (menuBar.getHeight() * 0.7f);
  53393. }
  53394. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  53395. {
  53396. return getMenuBarFont (menuBar, itemIndex, itemText)
  53397. .getStringWidth (itemText) + menuBar.getHeight();
  53398. }
  53399. void LookAndFeel::drawMenuBarItem (Graphics& g,
  53400. int width, int height,
  53401. int itemIndex,
  53402. const String& itemText,
  53403. bool isMouseOverItem,
  53404. bool isMenuOpen,
  53405. bool /*isMouseOverBar*/,
  53406. MenuBarComponent& menuBar)
  53407. {
  53408. if (! menuBar.isEnabled())
  53409. {
  53410. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  53411. .withMultipliedAlpha (0.5f));
  53412. }
  53413. else if (isMenuOpen || isMouseOverItem)
  53414. {
  53415. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  53416. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  53417. }
  53418. else
  53419. {
  53420. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  53421. }
  53422. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  53423. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  53424. }
  53425. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  53426. TextEditor& textEditor)
  53427. {
  53428. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  53429. }
  53430. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  53431. {
  53432. if (textEditor.isEnabled())
  53433. {
  53434. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  53435. {
  53436. const int border = 2;
  53437. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  53438. g.drawRect (0, 0, width, height, border);
  53439. g.setOpacity (1.0f);
  53440. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  53441. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  53442. }
  53443. else
  53444. {
  53445. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  53446. g.drawRect (0, 0, width, height);
  53447. g.setOpacity (1.0f);
  53448. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  53449. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  53450. }
  53451. }
  53452. }
  53453. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  53454. const bool isButtonDown,
  53455. int buttonX, int buttonY,
  53456. int buttonW, int buttonH,
  53457. ComboBox& box)
  53458. {
  53459. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  53460. if (box.isEnabled() && box.hasKeyboardFocus (false))
  53461. {
  53462. g.setColour (box.findColour (TextButton::buttonColourId));
  53463. g.drawRect (0, 0, width, height, 2);
  53464. }
  53465. else
  53466. {
  53467. g.setColour (box.findColour (ComboBox::outlineColourId));
  53468. g.drawRect (0, 0, width, height);
  53469. }
  53470. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  53471. const Colour baseColour (LookAndFeelHelpers::createBaseColour (box.findColour (ComboBox::buttonColourId),
  53472. box.hasKeyboardFocus (true),
  53473. false, isButtonDown)
  53474. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  53475. drawGlassLozenge (g,
  53476. buttonX + outlineThickness, buttonY + outlineThickness,
  53477. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  53478. baseColour, outlineThickness, -1.0f,
  53479. true, true, true, true);
  53480. if (box.isEnabled())
  53481. {
  53482. const float arrowX = 0.3f;
  53483. const float arrowH = 0.2f;
  53484. Path p;
  53485. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  53486. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  53487. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  53488. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  53489. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  53490. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  53491. g.setColour (box.findColour (ComboBox::arrowColourId));
  53492. g.fillPath (p);
  53493. }
  53494. }
  53495. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  53496. {
  53497. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  53498. }
  53499. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  53500. {
  53501. return new Label (String::empty, String::empty);
  53502. }
  53503. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  53504. {
  53505. label.setBounds (1, 1,
  53506. box.getWidth() + 3 - box.getHeight(),
  53507. box.getHeight() - 2);
  53508. label.setFont (getComboBoxFont (box));
  53509. }
  53510. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  53511. {
  53512. g.fillAll (label.findColour (Label::backgroundColourId));
  53513. if (! label.isBeingEdited())
  53514. {
  53515. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  53516. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  53517. g.setFont (label.getFont());
  53518. g.drawFittedText (label.getText(),
  53519. label.getHorizontalBorderSize(),
  53520. label.getVerticalBorderSize(),
  53521. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  53522. label.getHeight() - 2 * label.getVerticalBorderSize(),
  53523. label.getJustificationType(),
  53524. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  53525. label.getMinimumHorizontalScale());
  53526. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  53527. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53528. }
  53529. else if (label.isEnabled())
  53530. {
  53531. g.setColour (label.findColour (Label::outlineColourId));
  53532. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  53533. }
  53534. }
  53535. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  53536. int x, int y,
  53537. int width, int height,
  53538. float /*sliderPos*/,
  53539. float /*minSliderPos*/,
  53540. float /*maxSliderPos*/,
  53541. const Slider::SliderStyle /*style*/,
  53542. Slider& slider)
  53543. {
  53544. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53545. const Colour trackColour (slider.findColour (Slider::trackColourId));
  53546. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  53547. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  53548. Path indent;
  53549. if (slider.isHorizontal())
  53550. {
  53551. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  53552. const float ih = sliderRadius;
  53553. g.setGradientFill (ColourGradient (gradCol1, 0.0f, iy,
  53554. gradCol2, 0.0f, iy + ih, false));
  53555. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  53556. width + sliderRadius, ih,
  53557. 5.0f);
  53558. g.fillPath (indent);
  53559. }
  53560. else
  53561. {
  53562. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  53563. const float iw = sliderRadius;
  53564. g.setGradientFill (ColourGradient (gradCol1, ix, 0.0f,
  53565. gradCol2, ix + iw, 0.0f, false));
  53566. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  53567. iw, height + sliderRadius,
  53568. 5.0f);
  53569. g.fillPath (indent);
  53570. }
  53571. g.setColour (Colour (0x4c000000));
  53572. g.strokePath (indent, PathStrokeType (0.5f));
  53573. }
  53574. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  53575. int x, int y,
  53576. int width, int height,
  53577. float sliderPos,
  53578. float minSliderPos,
  53579. float maxSliderPos,
  53580. const Slider::SliderStyle style,
  53581. Slider& slider)
  53582. {
  53583. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  53584. Colour knobColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId),
  53585. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  53586. slider.isMouseOverOrDragging() && slider.isEnabled(),
  53587. slider.isMouseButtonDown() && slider.isEnabled()));
  53588. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  53589. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  53590. {
  53591. float kx, ky;
  53592. if (style == Slider::LinearVertical)
  53593. {
  53594. kx = x + width * 0.5f;
  53595. ky = sliderPos;
  53596. }
  53597. else
  53598. {
  53599. kx = sliderPos;
  53600. ky = y + height * 0.5f;
  53601. }
  53602. drawGlassSphere (g,
  53603. kx - sliderRadius,
  53604. ky - sliderRadius,
  53605. sliderRadius * 2.0f,
  53606. knobColour, outlineThickness);
  53607. }
  53608. else
  53609. {
  53610. if (style == Slider::ThreeValueVertical)
  53611. {
  53612. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  53613. sliderPos - sliderRadius,
  53614. sliderRadius * 2.0f,
  53615. knobColour, outlineThickness);
  53616. }
  53617. else if (style == Slider::ThreeValueHorizontal)
  53618. {
  53619. drawGlassSphere (g,sliderPos - sliderRadius,
  53620. y + height * 0.5f - sliderRadius,
  53621. sliderRadius * 2.0f,
  53622. knobColour, outlineThickness);
  53623. }
  53624. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  53625. {
  53626. const float sr = jmin (sliderRadius, width * 0.4f);
  53627. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  53628. minSliderPos - sliderRadius,
  53629. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  53630. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  53631. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  53632. }
  53633. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  53634. {
  53635. const float sr = jmin (sliderRadius, height * 0.4f);
  53636. drawGlassPointer (g, minSliderPos - sr,
  53637. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  53638. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  53639. drawGlassPointer (g, maxSliderPos - sliderRadius,
  53640. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  53641. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  53642. }
  53643. }
  53644. }
  53645. void LookAndFeel::drawLinearSlider (Graphics& g,
  53646. int x, int y,
  53647. int width, int height,
  53648. float sliderPos,
  53649. float minSliderPos,
  53650. float maxSliderPos,
  53651. const Slider::SliderStyle style,
  53652. Slider& slider)
  53653. {
  53654. g.fillAll (slider.findColour (Slider::backgroundColourId));
  53655. if (style == Slider::LinearBar)
  53656. {
  53657. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53658. Colour baseColour (LookAndFeelHelpers::createBaseColour (slider.findColour (Slider::thumbColourId)
  53659. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  53660. false, isMouseOver,
  53661. isMouseOver || slider.isMouseButtonDown()));
  53662. drawShinyButtonShape (g,
  53663. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  53664. baseColour,
  53665. slider.isEnabled() ? 0.9f : 0.3f,
  53666. true, true, true, true);
  53667. }
  53668. else
  53669. {
  53670. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53671. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  53672. }
  53673. }
  53674. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  53675. {
  53676. return jmin (7,
  53677. slider.getHeight() / 2,
  53678. slider.getWidth() / 2) + 2;
  53679. }
  53680. void LookAndFeel::drawRotarySlider (Graphics& g,
  53681. int x, int y,
  53682. int width, int height,
  53683. float sliderPos,
  53684. const float rotaryStartAngle,
  53685. const float rotaryEndAngle,
  53686. Slider& slider)
  53687. {
  53688. const float radius = jmin (width / 2, height / 2) - 2.0f;
  53689. const float centreX = x + width * 0.5f;
  53690. const float centreY = y + height * 0.5f;
  53691. const float rx = centreX - radius;
  53692. const float ry = centreY - radius;
  53693. const float rw = radius * 2.0f;
  53694. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  53695. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  53696. if (radius > 12.0f)
  53697. {
  53698. if (slider.isEnabled())
  53699. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53700. else
  53701. g.setColour (Colour (0x80808080));
  53702. const float thickness = 0.7f;
  53703. {
  53704. Path filledArc;
  53705. filledArc.addPieSegment (rx, ry, rw, rw,
  53706. rotaryStartAngle,
  53707. angle,
  53708. thickness);
  53709. g.fillPath (filledArc);
  53710. }
  53711. if (thickness > 0)
  53712. {
  53713. const float innerRadius = radius * 0.2f;
  53714. Path p;
  53715. p.addTriangle (-innerRadius, 0.0f,
  53716. 0.0f, -radius * thickness * 1.1f,
  53717. innerRadius, 0.0f);
  53718. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  53719. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53720. }
  53721. if (slider.isEnabled())
  53722. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  53723. else
  53724. g.setColour (Colour (0x80808080));
  53725. Path outlineArc;
  53726. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  53727. outlineArc.closeSubPath();
  53728. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  53729. }
  53730. else
  53731. {
  53732. if (slider.isEnabled())
  53733. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  53734. else
  53735. g.setColour (Colour (0x80808080));
  53736. Path p;
  53737. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  53738. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  53739. p.addLineSegment (Line<float> (0.0f, 0.0f, 0.0f, -radius), rw * 0.2f);
  53740. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  53741. }
  53742. }
  53743. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  53744. {
  53745. return new TextButton (isIncrement ? "+" : "-", String::empty);
  53746. }
  53747. class SliderLabelComp : public Label
  53748. {
  53749. public:
  53750. SliderLabelComp() : Label (String::empty, String::empty) {}
  53751. ~SliderLabelComp() {}
  53752. void mouseWheelMove (const MouseEvent&, float, float) {}
  53753. };
  53754. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  53755. {
  53756. Label* const l = new SliderLabelComp();
  53757. l->setJustificationType (Justification::centred);
  53758. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53759. l->setColour (Label::backgroundColourId,
  53760. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  53761. : slider.findColour (Slider::textBoxBackgroundColourId));
  53762. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53763. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  53764. l->setColour (TextEditor::backgroundColourId,
  53765. slider.findColour (Slider::textBoxBackgroundColourId)
  53766. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  53767. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  53768. return l;
  53769. }
  53770. ImageEffectFilter* LookAndFeel::getSliderEffect()
  53771. {
  53772. return 0;
  53773. }
  53774. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  53775. {
  53776. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (tipText));
  53777. width = tl.getWidth() + 14;
  53778. height = tl.getHeight() + 6;
  53779. }
  53780. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  53781. {
  53782. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  53783. const Colour textCol (findColour (TooltipWindow::textColourId));
  53784. #if ! JUCE_MAC // The mac windows already have a non-optional 1 pix outline, so don't double it here..
  53785. g.setColour (findColour (TooltipWindow::outlineColourId));
  53786. g.drawRect (0, 0, width, height, 1);
  53787. #endif
  53788. const TextLayout tl (LookAndFeelHelpers::layoutTooltipText (text));
  53789. g.setColour (findColour (TooltipWindow::textColourId));
  53790. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  53791. }
  53792. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  53793. {
  53794. return new TextButton (text, TRANS("click to browse for a different file"));
  53795. }
  53796. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  53797. ComboBox* filenameBox,
  53798. Button* browseButton)
  53799. {
  53800. browseButton->setSize (80, filenameComp.getHeight());
  53801. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  53802. if (tb != 0)
  53803. tb->changeWidthToFitText();
  53804. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  53805. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  53806. }
  53807. void LookAndFeel::drawImageButton (Graphics& g, Image* image,
  53808. int imageX, int imageY, int imageW, int imageH,
  53809. const Colour& overlayColour,
  53810. float imageOpacity,
  53811. ImageButton& button)
  53812. {
  53813. if (! button.isEnabled())
  53814. imageOpacity *= 0.3f;
  53815. if (! overlayColour.isOpaque())
  53816. {
  53817. g.setOpacity (imageOpacity);
  53818. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53819. 0, 0, image->getWidth(), image->getHeight(), false);
  53820. }
  53821. if (! overlayColour.isTransparent())
  53822. {
  53823. g.setColour (overlayColour);
  53824. g.drawImage (*image, imageX, imageY, imageW, imageH,
  53825. 0, 0, image->getWidth(), image->getHeight(), true);
  53826. }
  53827. }
  53828. void LookAndFeel::drawCornerResizer (Graphics& g,
  53829. int w, int h,
  53830. bool /*isMouseOver*/,
  53831. bool /*isMouseDragging*/)
  53832. {
  53833. const float lineThickness = jmin (w, h) * 0.075f;
  53834. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  53835. {
  53836. g.setColour (Colours::lightgrey);
  53837. g.drawLine (w * i,
  53838. h + 1.0f,
  53839. w + 1.0f,
  53840. h * i,
  53841. lineThickness);
  53842. g.setColour (Colours::darkgrey);
  53843. g.drawLine (w * i + lineThickness,
  53844. h + 1.0f,
  53845. w + 1.0f,
  53846. h * i + lineThickness,
  53847. lineThickness);
  53848. }
  53849. }
  53850. void LookAndFeel::drawResizableFrame (Graphics& g, int w, int h, const BorderSize& border)
  53851. {
  53852. if (! border.isEmpty())
  53853. {
  53854. const Rectangle<int> fullSize (0, 0, w, h);
  53855. const Rectangle<int> centreArea (border.subtractedFrom (fullSize));
  53856. g.saveState();
  53857. g.excludeClipRegion (centreArea);
  53858. g.setColour (Colour (0x50000000));
  53859. g.drawRect (fullSize);
  53860. g.setColour (Colour (0x19000000));
  53861. g.drawRect (centreArea.expanded (1, 1));
  53862. g.restoreState();
  53863. }
  53864. }
  53865. void LookAndFeel::fillResizableWindowBackground (Graphics& g, int /*w*/, int /*h*/,
  53866. const BorderSize& /*border*/, ResizableWindow& window)
  53867. {
  53868. g.fillAll (window.getBackgroundColour());
  53869. }
  53870. void LookAndFeel::drawResizableWindowBorder (Graphics&, int /*w*/, int /*h*/,
  53871. const BorderSize& /*border*/, ResizableWindow&)
  53872. {
  53873. }
  53874. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  53875. Graphics& g, int w, int h,
  53876. int titleSpaceX, int titleSpaceW,
  53877. const Image* icon,
  53878. bool drawTitleTextOnLeft)
  53879. {
  53880. const bool isActive = window.isActiveWindow();
  53881. g.setGradientFill (ColourGradient (window.getBackgroundColour(),
  53882. 0.0f, 0.0f,
  53883. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  53884. 0.0f, (float) h, false));
  53885. g.fillAll();
  53886. Font font (h * 0.65f, Font::bold);
  53887. g.setFont (font);
  53888. int textW = font.getStringWidth (window.getName());
  53889. int iconW = 0;
  53890. int iconH = 0;
  53891. if (icon != 0)
  53892. {
  53893. iconH = (int) font.getHeight();
  53894. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  53895. }
  53896. textW = jmin (titleSpaceW, textW + iconW);
  53897. int textX = drawTitleTextOnLeft ? titleSpaceX
  53898. : jmax (titleSpaceX, (w - textW) / 2);
  53899. if (textX + textW > titleSpaceX + titleSpaceW)
  53900. textX = titleSpaceX + titleSpaceW - textW;
  53901. if (icon != 0)
  53902. {
  53903. g.setOpacity (isActive ? 1.0f : 0.6f);
  53904. g.drawImageWithin (*icon, textX, (h - iconH) / 2, iconW, iconH,
  53905. RectanglePlacement::centred, false);
  53906. textX += iconW;
  53907. textW -= iconW;
  53908. }
  53909. if (window.isColourSpecified (DocumentWindow::textColourId) || isColourSpecified (DocumentWindow::textColourId))
  53910. g.setColour (findColour (DocumentWindow::textColourId));
  53911. else
  53912. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  53913. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  53914. }
  53915. class GlassWindowButton : public Button
  53916. {
  53917. public:
  53918. GlassWindowButton (const String& name, const Colour& col,
  53919. const Path& normalShape_,
  53920. const Path& toggledShape_) throw()
  53921. : Button (name),
  53922. colour (col),
  53923. normalShape (normalShape_),
  53924. toggledShape (toggledShape_)
  53925. {
  53926. }
  53927. ~GlassWindowButton()
  53928. {
  53929. }
  53930. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  53931. {
  53932. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  53933. if (! isEnabled())
  53934. alpha *= 0.5f;
  53935. float x = 0, y = 0, diam;
  53936. if (getWidth() < getHeight())
  53937. {
  53938. diam = (float) getWidth();
  53939. y = (getHeight() - getWidth()) * 0.5f;
  53940. }
  53941. else
  53942. {
  53943. diam = (float) getHeight();
  53944. y = (getWidth() - getHeight()) * 0.5f;
  53945. }
  53946. x += diam * 0.05f;
  53947. y += diam * 0.05f;
  53948. diam *= 0.9f;
  53949. g.setGradientFill (ColourGradient (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  53950. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false));
  53951. g.fillEllipse (x, y, diam, diam);
  53952. x += 2.0f;
  53953. y += 2.0f;
  53954. diam -= 4.0f;
  53955. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  53956. Path& p = getToggleState() ? toggledShape : normalShape;
  53957. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  53958. diam * 0.4f, diam * 0.4f, true));
  53959. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  53960. g.fillPath (p, t);
  53961. }
  53962. juce_UseDebuggingNewOperator
  53963. private:
  53964. Colour colour;
  53965. Path normalShape, toggledShape;
  53966. GlassWindowButton (const GlassWindowButton&);
  53967. GlassWindowButton& operator= (const GlassWindowButton&);
  53968. };
  53969. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  53970. {
  53971. Path shape;
  53972. const float crossThickness = 0.25f;
  53973. if (buttonType == DocumentWindow::closeButton)
  53974. {
  53975. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), crossThickness * 1.4f);
  53976. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), crossThickness * 1.4f);
  53977. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  53978. }
  53979. else if (buttonType == DocumentWindow::minimiseButton)
  53980. {
  53981. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53982. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  53983. }
  53984. else if (buttonType == DocumentWindow::maximiseButton)
  53985. {
  53986. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), crossThickness);
  53987. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), crossThickness);
  53988. Path fullscreenShape;
  53989. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  53990. fullscreenShape.lineTo (0.0f, 100.0f);
  53991. fullscreenShape.lineTo (0.0f, 0.0f);
  53992. fullscreenShape.lineTo (100.0f, 0.0f);
  53993. fullscreenShape.lineTo (100.0f, 45.0f);
  53994. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  53995. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  53996. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  53997. }
  53998. jassertfalse;
  53999. return 0;
  54000. }
  54001. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  54002. int titleBarX,
  54003. int titleBarY,
  54004. int titleBarW,
  54005. int titleBarH,
  54006. Button* minimiseButton,
  54007. Button* maximiseButton,
  54008. Button* closeButton,
  54009. bool positionTitleBarButtonsOnLeft)
  54010. {
  54011. const int buttonW = titleBarH - titleBarH / 8;
  54012. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  54013. : titleBarX + titleBarW - buttonW - buttonW / 4;
  54014. if (closeButton != 0)
  54015. {
  54016. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54017. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  54018. }
  54019. if (positionTitleBarButtonsOnLeft)
  54020. swapVariables (minimiseButton, maximiseButton);
  54021. if (maximiseButton != 0)
  54022. {
  54023. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54024. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  54025. }
  54026. if (minimiseButton != 0)
  54027. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  54028. }
  54029. int LookAndFeel::getDefaultMenuBarHeight()
  54030. {
  54031. return 24;
  54032. }
  54033. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  54034. {
  54035. return new DropShadower (0.4f, 1, 5, 10);
  54036. }
  54037. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  54038. int w, int h,
  54039. bool /*isVerticalBar*/,
  54040. bool isMouseOver,
  54041. bool isMouseDragging)
  54042. {
  54043. float alpha = 0.5f;
  54044. if (isMouseOver || isMouseDragging)
  54045. {
  54046. g.fillAll (Colour (0x190000ff));
  54047. alpha = 1.0f;
  54048. }
  54049. const float cx = w * 0.5f;
  54050. const float cy = h * 0.5f;
  54051. const float cr = jmin (w, h) * 0.4f;
  54052. g.setGradientFill (ColourGradient (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  54053. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  54054. true));
  54055. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  54056. }
  54057. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  54058. const String& text,
  54059. const Justification& position,
  54060. GroupComponent& group)
  54061. {
  54062. const float textH = 15.0f;
  54063. const float indent = 3.0f;
  54064. const float textEdgeGap = 4.0f;
  54065. float cs = 5.0f;
  54066. Font f (textH);
  54067. Path p;
  54068. float x = indent;
  54069. float y = f.getAscent() - 3.0f;
  54070. float w = jmax (0.0f, width - x * 2.0f);
  54071. float h = jmax (0.0f, height - y - indent);
  54072. cs = jmin (cs, w * 0.5f, h * 0.5f);
  54073. const float cs2 = 2.0f * cs;
  54074. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  54075. float textX = cs + textEdgeGap;
  54076. if (position.testFlags (Justification::horizontallyCentred))
  54077. textX = cs + (w - cs2 - textW) * 0.5f;
  54078. else if (position.testFlags (Justification::right))
  54079. textX = w - cs - textW - textEdgeGap;
  54080. p.startNewSubPath (x + textX + textW, y);
  54081. p.lineTo (x + w - cs, y);
  54082. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  54083. p.lineTo (x + w, y + h - cs);
  54084. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  54085. p.lineTo (x + cs, y + h);
  54086. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  54087. p.lineTo (x, y + cs);
  54088. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  54089. p.lineTo (x + textX, y);
  54090. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  54091. g.setColour (group.findColour (GroupComponent::outlineColourId)
  54092. .withMultipliedAlpha (alpha));
  54093. g.strokePath (p, PathStrokeType (2.0f));
  54094. g.setColour (group.findColour (GroupComponent::textColourId)
  54095. .withMultipliedAlpha (alpha));
  54096. g.setFont (f);
  54097. g.drawText (text,
  54098. roundToInt (x + textX), 0,
  54099. roundToInt (textW),
  54100. roundToInt (textH),
  54101. Justification::centred, true);
  54102. }
  54103. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  54104. {
  54105. return 1 + tabDepth / 3;
  54106. }
  54107. int LookAndFeel::getTabButtonSpaceAroundImage()
  54108. {
  54109. return 4;
  54110. }
  54111. void LookAndFeel::createTabButtonShape (Path& p,
  54112. int width, int height,
  54113. int /*tabIndex*/,
  54114. const String& /*text*/,
  54115. Button& /*button*/,
  54116. TabbedButtonBar::Orientation orientation,
  54117. const bool /*isMouseOver*/,
  54118. const bool /*isMouseDown*/,
  54119. const bool /*isFrontTab*/)
  54120. {
  54121. const float w = (float) width;
  54122. const float h = (float) height;
  54123. float length = w;
  54124. float depth = h;
  54125. if (orientation == TabbedButtonBar::TabsAtLeft
  54126. || orientation == TabbedButtonBar::TabsAtRight)
  54127. {
  54128. swapVariables (length, depth);
  54129. }
  54130. const float indent = (float) getTabButtonOverlap ((int) depth);
  54131. const float overhang = 4.0f;
  54132. if (orientation == TabbedButtonBar::TabsAtLeft)
  54133. {
  54134. p.startNewSubPath (w, 0.0f);
  54135. p.lineTo (0.0f, indent);
  54136. p.lineTo (0.0f, h - indent);
  54137. p.lineTo (w, h);
  54138. p.lineTo (w + overhang, h + overhang);
  54139. p.lineTo (w + overhang, -overhang);
  54140. }
  54141. else if (orientation == TabbedButtonBar::TabsAtRight)
  54142. {
  54143. p.startNewSubPath (0.0f, 0.0f);
  54144. p.lineTo (w, indent);
  54145. p.lineTo (w, h - indent);
  54146. p.lineTo (0.0f, h);
  54147. p.lineTo (-overhang, h + overhang);
  54148. p.lineTo (-overhang, -overhang);
  54149. }
  54150. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54151. {
  54152. p.startNewSubPath (0.0f, 0.0f);
  54153. p.lineTo (indent, h);
  54154. p.lineTo (w - indent, h);
  54155. p.lineTo (w, 0.0f);
  54156. p.lineTo (w + overhang, -overhang);
  54157. p.lineTo (-overhang, -overhang);
  54158. }
  54159. else
  54160. {
  54161. p.startNewSubPath (0.0f, h);
  54162. p.lineTo (indent, 0.0f);
  54163. p.lineTo (w - indent, 0.0f);
  54164. p.lineTo (w, h);
  54165. p.lineTo (w + overhang, h + overhang);
  54166. p.lineTo (-overhang, h + overhang);
  54167. }
  54168. p.closeSubPath();
  54169. p = p.createPathWithRoundedCorners (3.0f);
  54170. }
  54171. void LookAndFeel::fillTabButtonShape (Graphics& g,
  54172. const Path& path,
  54173. const Colour& preferredColour,
  54174. int /*tabIndex*/,
  54175. const String& /*text*/,
  54176. Button& button,
  54177. TabbedButtonBar::Orientation /*orientation*/,
  54178. const bool /*isMouseOver*/,
  54179. const bool /*isMouseDown*/,
  54180. const bool isFrontTab)
  54181. {
  54182. g.setColour (isFrontTab ? preferredColour
  54183. : preferredColour.withMultipliedAlpha (0.9f));
  54184. g.fillPath (path);
  54185. g.setColour (button.findColour (isFrontTab ? TabbedButtonBar::frontOutlineColourId
  54186. : TabbedButtonBar::tabOutlineColourId, false)
  54187. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  54188. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  54189. }
  54190. void LookAndFeel::drawTabButtonText (Graphics& g,
  54191. int x, int y, int w, int h,
  54192. const Colour& preferredBackgroundColour,
  54193. int /*tabIndex*/,
  54194. const String& text,
  54195. Button& button,
  54196. TabbedButtonBar::Orientation orientation,
  54197. const bool isMouseOver,
  54198. const bool isMouseDown,
  54199. const bool isFrontTab)
  54200. {
  54201. int length = w;
  54202. int depth = h;
  54203. if (orientation == TabbedButtonBar::TabsAtLeft
  54204. || orientation == TabbedButtonBar::TabsAtRight)
  54205. {
  54206. swapVariables (length, depth);
  54207. }
  54208. Font font (depth * 0.6f);
  54209. font.setUnderline (button.hasKeyboardFocus (false));
  54210. GlyphArrangement textLayout;
  54211. textLayout.addFittedText (font, text.trim(),
  54212. 0.0f, 0.0f, (float) length, (float) depth,
  54213. Justification::centred,
  54214. jmax (1, depth / 12));
  54215. AffineTransform transform;
  54216. if (orientation == TabbedButtonBar::TabsAtLeft)
  54217. {
  54218. transform = transform.rotated (float_Pi * -0.5f)
  54219. .translated ((float) x, (float) (y + h));
  54220. }
  54221. else if (orientation == TabbedButtonBar::TabsAtRight)
  54222. {
  54223. transform = transform.rotated (float_Pi * 0.5f)
  54224. .translated ((float) (x + w), (float) y);
  54225. }
  54226. else
  54227. {
  54228. transform = transform.translated ((float) x, (float) y);
  54229. }
  54230. if (isFrontTab && (button.isColourSpecified (TabbedButtonBar::frontTextColourId) || isColourSpecified (TabbedButtonBar::frontTextColourId)))
  54231. g.setColour (findColour (TabbedButtonBar::frontTextColourId));
  54232. else if (button.isColourSpecified (TabbedButtonBar::tabTextColourId) || isColourSpecified (TabbedButtonBar::tabTextColourId))
  54233. g.setColour (findColour (TabbedButtonBar::tabTextColourId));
  54234. else
  54235. g.setColour (preferredBackgroundColour.contrasting());
  54236. if (! (isMouseOver || isMouseDown))
  54237. g.setOpacity (0.8f);
  54238. if (! button.isEnabled())
  54239. g.setOpacity (0.3f);
  54240. textLayout.draw (g, transform);
  54241. }
  54242. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  54243. const String& text,
  54244. int tabDepth,
  54245. Button&)
  54246. {
  54247. Font f (tabDepth * 0.6f);
  54248. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  54249. }
  54250. void LookAndFeel::drawTabButton (Graphics& g,
  54251. int w, int h,
  54252. const Colour& preferredColour,
  54253. int tabIndex,
  54254. const String& text,
  54255. Button& button,
  54256. TabbedButtonBar::Orientation orientation,
  54257. const bool isMouseOver,
  54258. const bool isMouseDown,
  54259. const bool isFrontTab)
  54260. {
  54261. int length = w;
  54262. int depth = h;
  54263. if (orientation == TabbedButtonBar::TabsAtLeft
  54264. || orientation == TabbedButtonBar::TabsAtRight)
  54265. {
  54266. swapVariables (length, depth);
  54267. }
  54268. Path tabShape;
  54269. createTabButtonShape (tabShape, w, h,
  54270. tabIndex, text, button, orientation,
  54271. isMouseOver, isMouseDown, isFrontTab);
  54272. fillTabButtonShape (g, tabShape, preferredColour,
  54273. tabIndex, text, button, orientation,
  54274. isMouseOver, isMouseDown, isFrontTab);
  54275. const int indent = getTabButtonOverlap (depth);
  54276. int x = 0, y = 0;
  54277. if (orientation == TabbedButtonBar::TabsAtLeft
  54278. || orientation == TabbedButtonBar::TabsAtRight)
  54279. {
  54280. y += indent;
  54281. h -= indent * 2;
  54282. }
  54283. else
  54284. {
  54285. x += indent;
  54286. w -= indent * 2;
  54287. }
  54288. drawTabButtonText (g, x, y, w, h, preferredColour,
  54289. tabIndex, text, button, orientation,
  54290. isMouseOver, isMouseDown, isFrontTab);
  54291. }
  54292. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  54293. int w, int h,
  54294. TabbedButtonBar& tabBar,
  54295. TabbedButtonBar::Orientation orientation)
  54296. {
  54297. const float shadowSize = 0.2f;
  54298. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  54299. Rectangle<int> shadowRect;
  54300. if (orientation == TabbedButtonBar::TabsAtLeft)
  54301. {
  54302. x1 = (float) w;
  54303. x2 = w * (1.0f - shadowSize);
  54304. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  54305. }
  54306. else if (orientation == TabbedButtonBar::TabsAtRight)
  54307. {
  54308. x2 = w * shadowSize;
  54309. shadowRect.setBounds (0, 0, (int) x2, h);
  54310. }
  54311. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54312. {
  54313. y2 = h * shadowSize;
  54314. shadowRect.setBounds (0, 0, w, (int) y2);
  54315. }
  54316. else
  54317. {
  54318. y1 = (float) h;
  54319. y2 = h * (1.0f - shadowSize);
  54320. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  54321. }
  54322. g.setGradientFill (ColourGradient (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  54323. Colours::transparentBlack, x2, y2, false));
  54324. shadowRect.expand (2, 2);
  54325. g.fillRect (shadowRect);
  54326. g.setColour (Colour (0x80000000));
  54327. if (orientation == TabbedButtonBar::TabsAtLeft)
  54328. {
  54329. g.fillRect (w - 1, 0, 1, h);
  54330. }
  54331. else if (orientation == TabbedButtonBar::TabsAtRight)
  54332. {
  54333. g.fillRect (0, 0, 1, h);
  54334. }
  54335. else if (orientation == TabbedButtonBar::TabsAtBottom)
  54336. {
  54337. g.fillRect (0, 0, w, 1);
  54338. }
  54339. else
  54340. {
  54341. g.fillRect (0, h - 1, w, 1);
  54342. }
  54343. }
  54344. Button* LookAndFeel::createTabBarExtrasButton()
  54345. {
  54346. const float thickness = 7.0f;
  54347. const float indent = 22.0f;
  54348. Path p;
  54349. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  54350. DrawablePath ellipse;
  54351. ellipse.setPath (p);
  54352. ellipse.setFill (Colour (0x99ffffff));
  54353. p.clear();
  54354. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54355. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54356. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54357. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54358. p.setUsingNonZeroWinding (false);
  54359. DrawablePath dp;
  54360. dp.setPath (p);
  54361. dp.setFill (Colour (0x59000000));
  54362. DrawableComposite normalImage;
  54363. normalImage.insertDrawable (ellipse);
  54364. normalImage.insertDrawable (dp);
  54365. dp.setFill (Colour (0xcc000000));
  54366. DrawableComposite overImage;
  54367. overImage.insertDrawable (ellipse);
  54368. overImage.insertDrawable (dp);
  54369. DrawableButton* db = new DrawableButton ("tabs", DrawableButton::ImageFitted);
  54370. db->setImages (&normalImage, &overImage, 0);
  54371. return db;
  54372. }
  54373. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  54374. {
  54375. g.fillAll (Colours::white);
  54376. const int w = header.getWidth();
  54377. const int h = header.getHeight();
  54378. g.setGradientFill (ColourGradient (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  54379. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  54380. false));
  54381. g.fillRect (0, h / 2, w, h);
  54382. g.setColour (Colour (0x33000000));
  54383. g.fillRect (0, h - 1, w, 1);
  54384. for (int i = header.getNumColumns (true); --i >= 0;)
  54385. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  54386. }
  54387. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  54388. int width, int height,
  54389. bool isMouseOver, bool isMouseDown,
  54390. int columnFlags)
  54391. {
  54392. if (isMouseDown)
  54393. g.fillAll (Colour (0x8899aadd));
  54394. else if (isMouseOver)
  54395. g.fillAll (Colour (0x5599aadd));
  54396. int rightOfText = width - 4;
  54397. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  54398. {
  54399. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  54400. const float bottom = height - top;
  54401. const float w = height * 0.5f;
  54402. const float x = rightOfText - (w * 1.25f);
  54403. rightOfText = (int) x;
  54404. Path sortArrow;
  54405. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  54406. g.setColour (Colour (0x99000000));
  54407. g.fillPath (sortArrow);
  54408. }
  54409. g.setColour (Colours::black);
  54410. g.setFont (height * 0.5f, Font::bold);
  54411. const int textX = 4;
  54412. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  54413. }
  54414. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  54415. {
  54416. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  54417. g.setGradientFill (ColourGradient (background, 0.0f, 0.0f,
  54418. background.darker (0.1f),
  54419. toolbar.isVertical() ? w - 1.0f : 0.0f,
  54420. toolbar.isVertical() ? 0.0f : h - 1.0f,
  54421. false));
  54422. g.fillAll();
  54423. }
  54424. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  54425. {
  54426. return createTabBarExtrasButton();
  54427. }
  54428. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  54429. bool isMouseOver, bool isMouseDown,
  54430. ToolbarItemComponent& component)
  54431. {
  54432. if (isMouseDown)
  54433. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  54434. else if (isMouseOver)
  54435. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  54436. }
  54437. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  54438. const String& text, ToolbarItemComponent& component)
  54439. {
  54440. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  54441. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  54442. const float fontHeight = jmin (14.0f, height * 0.85f);
  54443. g.setFont (fontHeight);
  54444. g.drawFittedText (text,
  54445. x, y, width, height,
  54446. Justification::centred,
  54447. jmax (1, height / (int) fontHeight));
  54448. }
  54449. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  54450. bool isOpen, int width, int height)
  54451. {
  54452. const int buttonSize = (height * 3) / 4;
  54453. const int buttonIndent = (height - buttonSize) / 2;
  54454. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen, false);
  54455. const int textX = buttonIndent * 2 + buttonSize + 2;
  54456. g.setColour (Colours::black);
  54457. g.setFont (height * 0.7f, Font::bold);
  54458. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  54459. }
  54460. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  54461. PropertyComponent&)
  54462. {
  54463. g.setColour (Colour (0x66ffffff));
  54464. g.fillRect (0, 0, width, height - 1);
  54465. }
  54466. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  54467. PropertyComponent& component)
  54468. {
  54469. g.setColour (Colours::black);
  54470. if (! component.isEnabled())
  54471. g.setOpacity (0.6f);
  54472. g.setFont (jmin (height, 24) * 0.65f);
  54473. const Rectangle<int> r (getPropertyComponentContentPosition (component));
  54474. g.drawFittedText (component.getName(),
  54475. 3, r.getY(), r.getX() - 5, r.getHeight(),
  54476. Justification::centredLeft, 2);
  54477. }
  54478. const Rectangle<int> LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  54479. {
  54480. return Rectangle<int> (component.getWidth() / 3, 1,
  54481. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  54482. }
  54483. void LookAndFeel::drawCallOutBoxBackground (CallOutBox& box, Graphics& g, const Path& path)
  54484. {
  54485. Image content (Image::ARGB, box.getWidth(), box.getHeight(), true);
  54486. {
  54487. Graphics g2 (content);
  54488. g2.setColour (Colour::greyLevel (0.23f).withAlpha (0.9f));
  54489. g2.fillPath (path);
  54490. g2.setColour (Colours::white.withAlpha (0.8f));
  54491. g2.strokePath (path, PathStrokeType (2.0f));
  54492. }
  54493. DropShadowEffect shadow;
  54494. shadow.setShadowProperties (5.0f, 0.4f, 0, 2);
  54495. shadow.applyEffect (content, g, 1.0f);
  54496. }
  54497. void LookAndFeel::createFileChooserHeaderText (const String& title,
  54498. const String& instructions,
  54499. GlyphArrangement& text,
  54500. int width)
  54501. {
  54502. text.clear();
  54503. text.addJustifiedText (Font (17.0f, Font::bold), title,
  54504. 8.0f, 22.0f, width - 16.0f,
  54505. Justification::centred);
  54506. text.addJustifiedText (Font (14.0f), instructions,
  54507. 8.0f, 24.0f + 16.0f, width - 16.0f,
  54508. Justification::centred);
  54509. }
  54510. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  54511. const String& filename, Image* icon,
  54512. const String& fileSizeDescription,
  54513. const String& fileTimeDescription,
  54514. const bool isDirectory,
  54515. const bool isItemSelected,
  54516. const int /*itemIndex*/,
  54517. DirectoryContentsDisplayComponent&)
  54518. {
  54519. if (isItemSelected)
  54520. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  54521. const int x = 32;
  54522. g.setColour (Colours::black);
  54523. if (icon != 0 && icon->isValid())
  54524. {
  54525. g.drawImageWithin (*icon, 2, 2, x - 4, height - 4,
  54526. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  54527. false);
  54528. }
  54529. else
  54530. {
  54531. const Drawable* d = isDirectory ? getDefaultFolderImage()
  54532. : getDefaultDocumentFileImage();
  54533. if (d != 0)
  54534. d->drawWithin (g, Rectangle<float> (2.0f, 2.0f, x - 4.0f, height - 4.0f),
  54535. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, 1.0f);
  54536. }
  54537. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  54538. g.setFont (height * 0.7f);
  54539. if (width > 450 && ! isDirectory)
  54540. {
  54541. const int sizeX = roundToInt (width * 0.7f);
  54542. const int dateX = roundToInt (width * 0.8f);
  54543. g.drawFittedText (filename,
  54544. x, 0, sizeX - x, height,
  54545. Justification::centredLeft, 1);
  54546. g.setFont (height * 0.5f);
  54547. g.setColour (Colours::darkgrey);
  54548. if (! isDirectory)
  54549. {
  54550. g.drawFittedText (fileSizeDescription,
  54551. sizeX, 0, dateX - sizeX - 8, height,
  54552. Justification::centredRight, 1);
  54553. g.drawFittedText (fileTimeDescription,
  54554. dateX, 0, width - 8 - dateX, height,
  54555. Justification::centredRight, 1);
  54556. }
  54557. }
  54558. else
  54559. {
  54560. g.drawFittedText (filename,
  54561. x, 0, width - x, height,
  54562. Justification::centredLeft, 1);
  54563. }
  54564. }
  54565. Button* LookAndFeel::createFileBrowserGoUpButton()
  54566. {
  54567. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  54568. Path arrowPath;
  54569. arrowPath.addArrow (Line<float> (50.0f, 100.0f, 50.0f, 0.0f), 40.0f, 100.0f, 50.0f);
  54570. DrawablePath arrowImage;
  54571. arrowImage.setFill (Colours::black.withAlpha (0.4f));
  54572. arrowImage.setPath (arrowPath);
  54573. goUpButton->setImages (&arrowImage);
  54574. return goUpButton;
  54575. }
  54576. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  54577. DirectoryContentsDisplayComponent* fileListComponent,
  54578. FilePreviewComponent* previewComp,
  54579. ComboBox* currentPathBox,
  54580. TextEditor* filenameBox,
  54581. Button* goUpButton)
  54582. {
  54583. const int x = 8;
  54584. int w = browserComp.getWidth() - x - x;
  54585. if (previewComp != 0)
  54586. {
  54587. const int previewWidth = w / 3;
  54588. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  54589. w -= previewWidth + 4;
  54590. }
  54591. int y = 4;
  54592. const int controlsHeight = 22;
  54593. const int bottomSectionHeight = controlsHeight + 8;
  54594. const int upButtonWidth = 50;
  54595. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  54596. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  54597. y += controlsHeight + 4;
  54598. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  54599. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  54600. y = listAsComp->getBottom() + 4;
  54601. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  54602. }
  54603. // Pulls a drawable out of compressed valuetree data..
  54604. Drawable* LookAndFeel::loadDrawableFromData (const void* data, size_t numBytes)
  54605. {
  54606. MemoryInputStream m (data, numBytes, false);
  54607. GZIPDecompressorInputStream gz (m);
  54608. ValueTree drawable (ValueTree::readFromStream (gz));
  54609. return Drawable::createFromValueTree (drawable.getChild (0), 0);
  54610. }
  54611. const Drawable* LookAndFeel::getDefaultFolderImage()
  54612. {
  54613. if (folderImage == 0)
  54614. {
  54615. static const unsigned char drawableData[] =
  54616. { 120,218,197,86,77,111,27,55,16,229,182,161,237,6,61,39,233,77,63,192,38,56,195,225,215,209,105,210,2,141,13,20,201,193,109,111,178,181,178,183,145,181,130,180,110,145,127,159,199,93,73,137,87,53,218,91,109,192,160,151,179,156,55,111,222,188,229,155,247,
  54617. 231,87,231,175,47,222,170,234,155,229,244,190,86,213,115,253,102,61,253,123,122,189,168,85,51,83,213,119,250,238,221,47,231,151,175,223,169,170,250,121,221,62,172,84,245,172,60,63,209,243,118,49,171,215,170,107,87,23,245,188,83,213,145,182,167,19,91,
  54618. 254,127,223,220,222,117,37,68,82,40,143,174,219,174,107,239,135,168,147,18,37,108,85,245,237,46,207,70,33,249,175,211,238,78,85,186,28,253,76,175,73,109,186,117,251,177,190,106,102,229,241,247,58,24,103,203,15,101,245,103,219,44,187,15,221,39,0,172,142,
  54619. 245,125,211,1,196,205,116,181,125,114,164,175,31,186,78,45,219,229,31,245,186,189,106,150,179,102,121,139,100,154,240,231,167,102,177,64,72,247,105,213,23,122,187,158,206,154,122,217,169,85,57,18,1,47,53,101,107,18,135,204,167,147,192,201,216,20,114,
  54620. 244,195,62,171,234,7,125,198,100,136,216,145,149,211,9,57,103,40,249,72,219,8,167,170,87,250,140,162,199,123,226,3,34,82,202,134,131,13,172,74,170,233,162,0,177,234,166,93,180,15,235,141,170,206,180,157,204,231,150,156,159,207,39,195,50,214,88,18,150,
  54621. 245,205,124,250,104,169,212,135,158,19,144,53,20,112,172,55,237,2,132,13,199,149,130,230,115,145,112,147,147,82,61,157,32,238,178,253,11,145,213,138,10,52,138,38,103,111,99,164,211,137,139,198,35,177,35,167,212,143,15,215,205,13,160,109,163,172,225,152,
  54622. 16,232,17,149,140,103,144,158,146,90,113,217,12,6,197,167,236,3,54,5,181,101,73,54,138,90,245,165,227,120,18,252,150,77,15,242,188,228,204,81,169,139,102,249,5,68,192,145,14,244,112,1,145,29,94,137,96,235,49,136,151,58,246,32,88,192,161,88,176,76,226,
  54623. 36,247,24,176,7,232,62,16,83,42,155,201,160,30,222,65,72,98,82,76,33,198,254,197,96,124,10,150,243,8,130,48,228,36,94,124,6,4,43,38,0,142,205,99,30,4,221,13,33,230,220,71,177,65,49,142,243,150,7,1,51,20,2,5,96,96,84,225,56,217,188,3,33,46,24,228,112,
  54624. 69,69,12,68,228,108,242,99,16,165,118,208,28,51,200,98,87,42,74,62,209,24,4,206,48,22,153,125,132,220,196,56,15,234,99,216,130,0,141,38,74,162,130,48,35,163,141,94,196,245,32,94,104,7,154,132,209,40,108,162,165,232,153,165,17,4,138,201,176,135,58,49,
  54625. 165,130,122,108,114,54,28,240,64,17,89,188,79,177,116,149,10,4,246,91,30,94,104,112,96,226,144,131,144,142,98,78,177,7,128,81,242,224,140,36,249,80,208,145,196,12,202,15,16,60,161,200,69,187,169,213,86,198,123,87,224,255,199,21,94,105,134,72,40,177,245,
  54626. 14,182,32,232,54,196,231,100,111,11,189,168,201,39,177,84,102,38,139,177,168,74,210,87,174,64,20,138,160,67,111,10,4,98,196,97,60,158,118,133,25,111,173,224,171,37,97,185,119,133,221,242,63,184,194,140,71,174,240,252,145,43,72,32,147,146,147,4,104,104,
  54627. 117,134,10,18,12,107,212,40,72,148,57,6,71,69,135,222,248,16,160,168,3,169,144,55,201,69,41,147,137,134,99,50,97,8,178,85,43,217,140,201,151,192,152,10,242,190,24,11,59,183,29,25,42,115,236,98,14,229,252,32,80,66,0,162,17,136,72,6,67,5,45,242,224,10,
  54628. 193,102,71,50,6,17,129,212,18,115,105,150,80,169,45,123,222,141,76,178,70,32,55,24,90,217,132,71,73,200,57,238,204,3,136,49,144,185,55,183,190,20,137,52,246,47,113,232,158,69,35,49,145,208,129,193,56,178,77,135,230,145,113,22,140,69,74,20,146,2,120,218,
  54629. 155,135,48,32,10,89,30,156,165,204,254,222,193,160,12,19,49,6,210,59,11,70,62,4,31,15,64,196,2,157,98,33,58,1,104,32,152,50,31,128,64,148,183,197,108,209,89,107,240,41,75,36,123,16,208,108,180,44,236,250,182,227,27,20,137,118,76,60,165,137,221,92,94,
  54630. 78,215,31,235,245,230,183,242,229,30,214,251,251,195,145,94,148,15,253,170,221,52,93,211,46,7,109,171,81,208,177,94,247,119,132,47,81,186,92,22,246,7,255,254,15,7,107,141,171,197,191,156,123,162,135,187,198,227,131,113,219,80,159,1,4,239,223,231,0,0 };
  54631. folderImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54632. }
  54633. return folderImage;
  54634. }
  54635. const Drawable* LookAndFeel::getDefaultDocumentFileImage()
  54636. {
  54637. if (documentImage == 0)
  54638. {
  54639. static const unsigned char drawableData[] =
  54640. { 120,218,213,88,77,115,219,54,16,37,147,208,246,228,214,75,155,246,164,123,29,12,176,216,197,199,49,105,218,94,156,153,78,114,72,219,155,108,75,137,26,89,212,200,116,59,233,175,239,3,105,201,164,68,50,158,166,233,76,196,11,69,60,173,128,197,123,139,183,
  54641. 124,241,234,217,155,103,207,207,126,204,242,7,171,233,213,44,203,31,23,47,54,211,191,166,231,203,89,182,184,204,242,147,226,195,165,219,252,125,150,229,249,207,155,242,102,157,229,143,210,227,199,197,101,121,113,115,53,91,85,89,85,174,207,102,243,42,
  54642. 203,143,10,125,58,209,233,251,171,197,219,119,85,250,173,97,151,30,157,151,85,85,94,53,168,147,132,50,226,179,252,225,246,143,174,179,44,63,254,101,90,189,203,242,34,5,127,84,172,77,118,93,109,202,247,179,55,139,203,244,248,97,161,179,63,202,197,170,
  54643. 122,93,125,192,196,242,227,226,106,81,205,54,217,197,116,125,251,228,168,56,191,169,170,108,85,174,126,159,109,202,55,139,213,229,98,245,182,249,97,254,240,167,197,114,137,5,86,31,214,245,111,175,203,37,254,230,162,92,150,55,155,180,148,249,237,39,203,
  54644. 94,215,127,58,10,213,245,39,203,234,249,102,249,87,47,203,63,129,204,49,227,252,73,225,149,145,104,131,245,254,116,34,202,82,164,16,153,179,236,108,177,234,7,49,41,237,130,144,167,17,144,15,42,104,239,93,12,35,32,99,68,9,187,24,125,7,244,77,23,36,164,
  54645. 40,56,226,61,12,107,229,130,215,100,105,24,227,89,17,246,211,105,55,140,49,218,43,207,100,245,72,28,195,70,17,230,201,118,8,243,164,139,233,95,88,23,52,152,162,54,104,48,217,237,105,15,111,91,107,253,131,160,118,34,239,69,128,54,232,135,101,121,61,203,
  54646. 110,169,181,147,2,253,159,82,48,180,229,247,167,74,193,41,141,188,35,93,241,116,18,148,113,214,120,207,113,47,19,109,16,51,182,153,193,5,59,2,10,90,69,114,218,135,48,2,50,198,43,171,189,152,81,144,88,108,85,136,78,246,64,54,42,163,35,69,30,3,121,82,38,
  54647. 98,81,98,70,64,70,139,34,111,163,167,49,144,13,202,138,179,58,220,23,52,180,186,54,104,48,79,109,208,96,198,219,19,31,220,187,118,10,6,65,237,100,222,139,5,109,80,191,30,236,151,162,135,147,142,30,68,105,182,58,6,22,84,43,229,124,148,116,97,145,55,231,
  54648. 139,11,76,228,16,37,14,48,205,145,77,134,34,176,55,152,182,200,57,99,93,204,144,145,253,65,97,229,132,72,104,63,62,71,21,140,54,186,41,226,59,84,19,63,130,15,222,235,224,185,59,104,27,226,68,101,153,241,227,177,248,29,20,136,26,8,252,178,183,241,219,
  54649. 131,137,160,209,107,109,92,79,124,16,211,184,104,93,77,130,110,124,2,65,172,67,201,60,157,88,163,2,91,99,92,216,198,55,78,69,75,190,150,119,84,98,200,71,150,109,124,36,204,227,52,8,33,229,223,68,167,173,167,131,248,137,212,226,141,19,233,160,154,248,
  54650. 144,142,195,140,137,185,59,104,15,247,119,40,126,23,69,81,200,242,110,254,123,20,49,94,112,110,245,199,111,241,167,87,36,252,101,138,132,149,22,22,38,65,134,29,182,139,24,230,192,31,144,184,133,130,72,44,131,210,142,111,147,216,30,76,123,30,113,206,242,
  54651. 150,196,157,65,129,130,76,180,194,61,34,225,160,5,228,233,160,118,34,137,26,202,115,212,29,108,72,134,243,223,90,114,226,199,226,119,80,6,245,152,197,122,217,146,184,53,24,140,210,30,21,59,80,79,124,182,202,71,207,218,112,159,72,80,53,140,109,68,2,191,
  54652. 227,217,210,78,36,94,137,88,231,82,157,8,176,61,0,122,191,19,137,3,255,13,39,183,228,20,193,151,144,119,166,79,36,40,253,156,138,72,11,181,19,137,14,46,176,217,27,180,135,251,219,31,255,235,61,148,165,96,72,122,118,23,229,81,52,135,24,250,163,183,216,
  54653. 211,43,17,217,151,136,253,116,137,28,53,188,127,92,188,221,76,47,23,169,59,90,167,144,141,239,197,86,104,141,189,60,157,80,84,142,140,4,31,154,241,122,105,132,41,107,13,201,39,86,120,24,82,114,206,198,6,96,27,227,172,36,232,168,201,36,219,24,113,62,163,
  54654. 154,101,233,143,166,203,102,26,141,206,174,179,252,89,161,39,243,249,197,121,186,38,233,246,146,211,53,1,123,56,194,231,122,143,103,179,217,60,204,167,19,147,110,41,93,173,219,123,72,89,248,35,173,16,220,50,179,111,60,181,24,88,103,156,235,7,78,248,14,
  54655. 4,119,78,162,93,60,112,35,109,16,124,126,12,17,71,67,24,1,165,142,1,181,215,248,56,6,66,235,193,137,167,61,22,30,5,3,27,101,71,64,169,25,112,216,2,63,22,169,110,43,18,200,140,129,208,160,88,44,220,208,125,65,67,171,107,131,6,243,212,6,13,102,188,61,241,
  54656. 225,189,107,165,96,16,212,78,230,189,88,208,6,245,235,214,237,235,150,62,167,110,155,106,170,53,133,192,117,193,20,84,78,74,174,98,39,92,156,8,112,21,46,80,106,12,209,207,225,228,16,113,59,225,126,87,60,133,25,209,34,36,2,99,242,52,197,48,30,75,244,247,
  54657. 212,238,246,182,173,221,185,78,215,127,167,221,162,163,221,250,152,217,146,196,222,145,100,223,235,105,108,28,250,149,212,74,224,86,2,213,118,110,119,204,224,144,208,38,214,131,200,14,214,223,120,189,230,53,1,193,70,133,154,131,56,223,16,229,48,188,14,
  54658. 201,205,213,121,71,233,68,89,15,124,103,37,53,26,11,118,176,127,169,88,166,158,219,178,117,173,83,108,75,95,55,68,186,193,53,246,146,206,127,6,63,53,78,58,228,204,155,224,113,74,91,232,221,195,240,105,215,34,29,138,64,128,183,8,130,233,71,173,56,54,101,
  54659. 99,75,186,111,65,58,28,229,145,82,19,152,12,99,180,81,130,131,75,234,229,220,247,53,231,154,79,205,185,185,155,199,249,172,38,85,253,204,76,68,95,92,204,207,255,221,75,178,227,14,187,224,224,97,202,172,173,219,12,167,130,133,9,54,135,245,92,176,29,134,
  54660. 165,110,139,141,18,16,223,29,188,183,65,207,144,106,144,151,143,128,224,176,168,110,140,32,62,56,110,219,195,54,235,20,68,209,216,34,232,21,6,41,234,157,39,211,201,107,160,230,66,225,56,153,9,101,21,37,237,150,204,14,115,208,22,221,54,216,230,33,116,
  54661. 14,65,14,44,19,8,236,73,71,246,182,110,125,224,75,132,195,214,247,163,36,51,252,84,76,124,37,212,100,88,62,183,179,76,67,217,218,242,244,229,116,243,126,182,185,254,21,105,126,208,220,239,94,229,30,21,203,244,202,117,93,94,47,170,69,185,106,246,60,219,
  54662. 3,29,23,155,250,109,237,29,170,72,175,109,119,129,127,235,9,92,20,85,185,254,72,220,147,162,121,235,219,13,44,144,225,63,241,244,165,51,0,0 };
  54663. documentImage = loadDrawableFromData (drawableData, sizeof (drawableData));
  54664. }
  54665. return documentImage;
  54666. }
  54667. void LookAndFeel::playAlertSound()
  54668. {
  54669. PlatformUtilities::beep();
  54670. }
  54671. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  54672. {
  54673. g.setColour (Colours::white.withAlpha (0.7f));
  54674. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  54675. g.setColour (Colours::black.withAlpha (0.2f));
  54676. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  54677. const int totalBlocks = 7;
  54678. const int numBlocks = roundToInt (totalBlocks * level);
  54679. const float w = (width - 6.0f) / (float) totalBlocks;
  54680. for (int i = 0; i < totalBlocks; ++i)
  54681. {
  54682. if (i >= numBlocks)
  54683. g.setColour (Colours::lightblue.withAlpha (0.6f));
  54684. else
  54685. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  54686. : Colours::red);
  54687. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  54688. }
  54689. }
  54690. void LookAndFeel::drawKeymapChangeButton (Graphics& g, int width, int height, Button& button, const String& keyDescription)
  54691. {
  54692. const Colour textColour (button.findColour (KeyMappingEditorComponent::textColourId, true));
  54693. if (keyDescription.isNotEmpty())
  54694. {
  54695. if (button.isEnabled())
  54696. {
  54697. const float alpha = button.isDown() ? 0.3f : (button.isOver() ? 0.15f : 0.08f);
  54698. g.fillAll (textColour.withAlpha (alpha));
  54699. g.setOpacity (0.3f);
  54700. g.drawBevel (0, 0, width, height, 2);
  54701. }
  54702. g.setColour (textColour);
  54703. g.setFont (height * 0.6f);
  54704. g.drawFittedText (keyDescription,
  54705. 3, 0, width - 6, height,
  54706. Justification::centred, 1);
  54707. }
  54708. else
  54709. {
  54710. const float thickness = 7.0f;
  54711. const float indent = 22.0f;
  54712. Path p;
  54713. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  54714. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  54715. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  54716. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  54717. p.setUsingNonZeroWinding (false);
  54718. g.setColour (textColour.withAlpha (button.isDown() ? 0.7f : (button.isOver() ? 0.5f : 0.3f)));
  54719. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, width - 4.0f, height - 4.0f, true));
  54720. }
  54721. if (button.hasKeyboardFocus (false))
  54722. {
  54723. g.setColour (textColour.withAlpha (0.4f));
  54724. g.drawRect (0, 0, width, height);
  54725. }
  54726. }
  54727. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  54728. float x, float y, float w, float h,
  54729. float maxCornerSize,
  54730. const Colour& baseColour,
  54731. const float strokeWidth,
  54732. const bool flatOnLeft,
  54733. const bool flatOnRight,
  54734. const bool flatOnTop,
  54735. const bool flatOnBottom) throw()
  54736. {
  54737. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  54738. return;
  54739. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  54740. Path outline;
  54741. LookAndFeelHelpers::createRoundedPath (outline, x, y, w, h, cs,
  54742. ! (flatOnLeft || flatOnTop),
  54743. ! (flatOnRight || flatOnTop),
  54744. ! (flatOnLeft || flatOnBottom),
  54745. ! (flatOnRight || flatOnBottom));
  54746. ColourGradient cg (baseColour, 0.0f, y,
  54747. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  54748. false);
  54749. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  54750. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  54751. g.setGradientFill (cg);
  54752. g.fillPath (outline);
  54753. g.setColour (Colour (0x80000000));
  54754. g.strokePath (outline, PathStrokeType (strokeWidth));
  54755. }
  54756. void LookAndFeel::drawGlassSphere (Graphics& g,
  54757. const float x, const float y,
  54758. const float diameter,
  54759. const Colour& colour,
  54760. const float outlineThickness) throw()
  54761. {
  54762. if (diameter <= outlineThickness)
  54763. return;
  54764. Path p;
  54765. p.addEllipse (x, y, diameter, diameter);
  54766. {
  54767. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54768. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54769. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54770. g.setGradientFill (cg);
  54771. g.fillPath (p);
  54772. }
  54773. g.setGradientFill (ColourGradient (Colours::white, 0, y + diameter * 0.06f,
  54774. Colours::transparentWhite, 0, y + diameter * 0.3f, false));
  54775. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  54776. ColourGradient cg (Colours::transparentBlack,
  54777. x + diameter * 0.5f, y + diameter * 0.5f,
  54778. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54779. x, y + diameter * 0.5f, true);
  54780. cg.addColour (0.7, Colours::transparentBlack);
  54781. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  54782. g.setGradientFill (cg);
  54783. g.fillPath (p);
  54784. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54785. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  54786. }
  54787. void LookAndFeel::drawGlassPointer (Graphics& g,
  54788. const float x, const float y,
  54789. const float diameter,
  54790. const Colour& colour, const float outlineThickness,
  54791. const int direction) throw()
  54792. {
  54793. if (diameter <= outlineThickness)
  54794. return;
  54795. Path p;
  54796. p.startNewSubPath (x + diameter * 0.5f, y);
  54797. p.lineTo (x + diameter, y + diameter * 0.6f);
  54798. p.lineTo (x + diameter, y + diameter);
  54799. p.lineTo (x, y + diameter);
  54800. p.lineTo (x, y + diameter * 0.6f);
  54801. p.closeSubPath();
  54802. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  54803. {
  54804. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  54805. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  54806. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  54807. g.setGradientFill (cg);
  54808. g.fillPath (p);
  54809. }
  54810. ColourGradient cg (Colours::transparentBlack,
  54811. x + diameter * 0.5f, y + diameter * 0.5f,
  54812. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  54813. x - diameter * 0.2f, y + diameter * 0.5f, true);
  54814. cg.addColour (0.5, Colours::transparentBlack);
  54815. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  54816. g.setGradientFill (cg);
  54817. g.fillPath (p);
  54818. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  54819. g.strokePath (p, PathStrokeType (outlineThickness));
  54820. }
  54821. void LookAndFeel::drawGlassLozenge (Graphics& g,
  54822. const float x, const float y,
  54823. const float width, const float height,
  54824. const Colour& colour,
  54825. const float outlineThickness,
  54826. const float cornerSize,
  54827. const bool flatOnLeft,
  54828. const bool flatOnRight,
  54829. const bool flatOnTop,
  54830. const bool flatOnBottom) throw()
  54831. {
  54832. if (width <= outlineThickness || height <= outlineThickness)
  54833. return;
  54834. const int intX = (int) x;
  54835. const int intY = (int) y;
  54836. const int intW = (int) width;
  54837. const int intH = (int) height;
  54838. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  54839. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  54840. const int intEdge = (int) edgeBlurRadius;
  54841. Path outline;
  54842. LookAndFeelHelpers::createRoundedPath (outline, x, y, width, height, cs,
  54843. ! (flatOnLeft || flatOnTop),
  54844. ! (flatOnRight || flatOnTop),
  54845. ! (flatOnLeft || flatOnBottom),
  54846. ! (flatOnRight || flatOnBottom));
  54847. {
  54848. ColourGradient cg (colour.darker (0.2f), 0, y,
  54849. colour.darker (0.2f), 0, y + height, false);
  54850. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  54851. cg.addColour (0.4, colour);
  54852. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  54853. g.setGradientFill (cg);
  54854. g.fillPath (outline);
  54855. }
  54856. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  54857. colour.darker (0.2f), x, y + height * 0.5f, true);
  54858. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  54859. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  54860. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  54861. {
  54862. g.saveState();
  54863. g.setGradientFill (cg);
  54864. g.reduceClipRegion (intX, intY, intEdge, intH);
  54865. g.fillPath (outline);
  54866. g.restoreState();
  54867. }
  54868. if (! (flatOnRight || flatOnTop || flatOnBottom))
  54869. {
  54870. cg.point1.setX (x + width - edgeBlurRadius);
  54871. cg.point2.setX (x + width);
  54872. g.saveState();
  54873. g.setGradientFill (cg);
  54874. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  54875. g.fillPath (outline);
  54876. g.restoreState();
  54877. }
  54878. {
  54879. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  54880. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  54881. Path highlight;
  54882. LookAndFeelHelpers::createRoundedPath (highlight,
  54883. x + leftIndent,
  54884. y + cs * 0.1f,
  54885. width - (leftIndent + rightIndent),
  54886. height * 0.4f, cs * 0.4f,
  54887. ! (flatOnLeft || flatOnTop),
  54888. ! (flatOnRight || flatOnTop),
  54889. ! (flatOnLeft || flatOnBottom),
  54890. ! (flatOnRight || flatOnBottom));
  54891. g.setGradientFill (ColourGradient (colour.brighter (10.0f), 0, y + height * 0.06f,
  54892. Colours::transparentWhite, 0, y + height * 0.4f, false));
  54893. g.fillPath (highlight);
  54894. }
  54895. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  54896. g.strokePath (outline, PathStrokeType (outlineThickness));
  54897. }
  54898. END_JUCE_NAMESPACE
  54899. /*** End of inlined file: juce_LookAndFeel.cpp ***/
  54900. /*** Start of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  54901. BEGIN_JUCE_NAMESPACE
  54902. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  54903. {
  54904. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  54905. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  54906. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  54907. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  54908. setColour (Slider::thumbColourId, Colours::white);
  54909. setColour (Slider::trackColourId, Colour (0x7f000000));
  54910. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  54911. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  54912. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  54913. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  54914. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  54915. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  54916. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  54917. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  54918. }
  54919. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  54920. {
  54921. }
  54922. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  54923. Button& button,
  54924. const Colour& backgroundColour,
  54925. bool isMouseOverButton,
  54926. bool isButtonDown)
  54927. {
  54928. const int width = button.getWidth();
  54929. const int height = button.getHeight();
  54930. const float indent = 2.0f;
  54931. const int cornerSize = jmin (roundToInt (width * 0.4f),
  54932. roundToInt (height * 0.4f));
  54933. Path p;
  54934. p.addRoundedRectangle (indent, indent,
  54935. width - indent * 2.0f,
  54936. height - indent * 2.0f,
  54937. (float) cornerSize);
  54938. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  54939. if (isMouseOverButton)
  54940. {
  54941. if (isButtonDown)
  54942. bc = bc.brighter();
  54943. else if (bc.getBrightness() > 0.5f)
  54944. bc = bc.darker (0.1f);
  54945. else
  54946. bc = bc.brighter (0.1f);
  54947. }
  54948. g.setColour (bc);
  54949. g.fillPath (p);
  54950. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  54951. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  54952. }
  54953. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  54954. Component& /*component*/,
  54955. float x, float y, float w, float h,
  54956. const bool ticked,
  54957. const bool isEnabled,
  54958. const bool /*isMouseOverButton*/,
  54959. const bool isButtonDown)
  54960. {
  54961. Path box;
  54962. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  54963. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  54964. : Colours::lightgrey.withAlpha (0.1f));
  54965. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f).translated (x, y));
  54966. g.fillPath (box, trans);
  54967. g.setColour (Colours::black.withAlpha (0.6f));
  54968. g.strokePath (box, PathStrokeType (0.9f), trans);
  54969. if (ticked)
  54970. {
  54971. Path tick;
  54972. tick.startNewSubPath (1.5f, 3.0f);
  54973. tick.lineTo (3.0f, 6.0f);
  54974. tick.lineTo (6.0f, 0.0f);
  54975. g.setColour (isEnabled ? Colours::black : Colours::grey);
  54976. g.strokePath (tick, PathStrokeType (2.5f), trans);
  54977. }
  54978. }
  54979. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  54980. ToggleButton& button,
  54981. bool isMouseOverButton,
  54982. bool isButtonDown)
  54983. {
  54984. if (button.hasKeyboardFocus (true))
  54985. {
  54986. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  54987. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  54988. }
  54989. const int tickWidth = jmin (20, button.getHeight() - 4);
  54990. drawTickBox (g, button, 4.0f, (button.getHeight() - tickWidth) * 0.5f,
  54991. (float) tickWidth, (float) tickWidth,
  54992. button.getToggleState(),
  54993. button.isEnabled(),
  54994. isMouseOverButton,
  54995. isButtonDown);
  54996. g.setColour (button.findColour (ToggleButton::textColourId));
  54997. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  54998. if (! button.isEnabled())
  54999. g.setOpacity (0.5f);
  55000. const int textX = tickWidth + 5;
  55001. g.drawFittedText (button.getButtonText(),
  55002. textX, 4,
  55003. button.getWidth() - textX - 2, button.getHeight() - 8,
  55004. Justification::centredLeft, 10);
  55005. }
  55006. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  55007. int width, int height,
  55008. double progress, const String& textToShow)
  55009. {
  55010. if (progress < 0 || progress >= 1.0)
  55011. {
  55012. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  55013. }
  55014. else
  55015. {
  55016. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  55017. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  55018. g.fillAll (background);
  55019. g.setColour (foreground);
  55020. g.fillRect (1, 1,
  55021. jlimit (0, width - 2, roundToInt (progress * (width - 2))),
  55022. height - 2);
  55023. if (textToShow.isNotEmpty())
  55024. {
  55025. g.setColour (Colour::contrasting (background, foreground));
  55026. g.setFont (height * 0.6f);
  55027. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  55028. }
  55029. }
  55030. }
  55031. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  55032. ScrollBar& bar,
  55033. int width, int height,
  55034. int buttonDirection,
  55035. bool isScrollbarVertical,
  55036. bool isMouseOverButton,
  55037. bool isButtonDown)
  55038. {
  55039. if (isScrollbarVertical)
  55040. width -= 2;
  55041. else
  55042. height -= 2;
  55043. Path p;
  55044. if (buttonDirection == 0)
  55045. p.addTriangle (width * 0.5f, height * 0.2f,
  55046. width * 0.1f, height * 0.7f,
  55047. width * 0.9f, height * 0.7f);
  55048. else if (buttonDirection == 1)
  55049. p.addTriangle (width * 0.8f, height * 0.5f,
  55050. width * 0.3f, height * 0.1f,
  55051. width * 0.3f, height * 0.9f);
  55052. else if (buttonDirection == 2)
  55053. p.addTriangle (width * 0.5f, height * 0.8f,
  55054. width * 0.1f, height * 0.3f,
  55055. width * 0.9f, height * 0.3f);
  55056. else if (buttonDirection == 3)
  55057. p.addTriangle (width * 0.2f, height * 0.5f,
  55058. width * 0.7f, height * 0.1f,
  55059. width * 0.7f, height * 0.9f);
  55060. if (isButtonDown)
  55061. g.setColour (Colours::white);
  55062. else if (isMouseOverButton)
  55063. g.setColour (Colours::white.withAlpha (0.7f));
  55064. else
  55065. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  55066. g.fillPath (p);
  55067. g.setColour (Colours::black.withAlpha (0.5f));
  55068. g.strokePath (p, PathStrokeType (0.5f));
  55069. }
  55070. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  55071. ScrollBar& bar,
  55072. int x, int y,
  55073. int width, int height,
  55074. bool isScrollbarVertical,
  55075. int thumbStartPosition,
  55076. int thumbSize,
  55077. bool isMouseOver,
  55078. bool isMouseDown)
  55079. {
  55080. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  55081. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55082. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  55083. if (thumbSize > 0.0f)
  55084. {
  55085. Rectangle<int> thumb;
  55086. if (isScrollbarVertical)
  55087. {
  55088. width -= 2;
  55089. g.fillRect (x + roundToInt (width * 0.35f), y,
  55090. roundToInt (width * 0.3f), height);
  55091. thumb.setBounds (x + 1, thumbStartPosition,
  55092. width - 2, thumbSize);
  55093. }
  55094. else
  55095. {
  55096. height -= 2;
  55097. g.fillRect (x, y + roundToInt (height * 0.35f),
  55098. width, roundToInt (height * 0.3f));
  55099. thumb.setBounds (thumbStartPosition, y + 1,
  55100. thumbSize, height - 2);
  55101. }
  55102. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  55103. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  55104. g.fillRect (thumb);
  55105. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  55106. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  55107. if (thumbSize > 16)
  55108. {
  55109. for (int i = 3; --i >= 0;)
  55110. {
  55111. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  55112. g.setColour (Colours::black.withAlpha (0.15f));
  55113. if (isScrollbarVertical)
  55114. {
  55115. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  55116. g.setColour (Colours::white.withAlpha (0.15f));
  55117. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  55118. }
  55119. else
  55120. {
  55121. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  55122. g.setColour (Colours::white.withAlpha (0.15f));
  55123. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  55124. }
  55125. }
  55126. }
  55127. }
  55128. }
  55129. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  55130. {
  55131. return &scrollbarShadow;
  55132. }
  55133. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  55134. {
  55135. g.fillAll (findColour (PopupMenu::backgroundColourId));
  55136. g.setColour (Colours::black.withAlpha (0.6f));
  55137. g.drawRect (0, 0, width, height);
  55138. }
  55139. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  55140. bool, MenuBarComponent& menuBar)
  55141. {
  55142. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  55143. }
  55144. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  55145. {
  55146. if (textEditor.isEnabled())
  55147. {
  55148. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  55149. g.drawRect (0, 0, width, height);
  55150. }
  55151. }
  55152. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  55153. const bool isButtonDown,
  55154. int buttonX, int buttonY,
  55155. int buttonW, int buttonH,
  55156. ComboBox& box)
  55157. {
  55158. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  55159. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  55160. : ComboBox::backgroundColourId));
  55161. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  55162. g.setColour (box.findColour (ComboBox::outlineColourId));
  55163. g.drawRect (0, 0, width, height);
  55164. const float arrowX = 0.2f;
  55165. const float arrowH = 0.3f;
  55166. if (box.isEnabled())
  55167. {
  55168. Path p;
  55169. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  55170. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  55171. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  55172. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  55173. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  55174. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  55175. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  55176. : ComboBox::buttonColourId));
  55177. g.fillPath (p);
  55178. }
  55179. }
  55180. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  55181. {
  55182. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  55183. f.setHorizontalScale (0.9f);
  55184. return f;
  55185. }
  55186. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  55187. {
  55188. Path p;
  55189. p.addTriangle (x1, y1, x2, y2, x3, y3);
  55190. g.setColour (fill);
  55191. g.fillPath (p);
  55192. g.setColour (outline);
  55193. g.strokePath (p, PathStrokeType (0.3f));
  55194. }
  55195. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  55196. int x, int y,
  55197. int w, int h,
  55198. float sliderPos,
  55199. float minSliderPos,
  55200. float maxSliderPos,
  55201. const Slider::SliderStyle style,
  55202. Slider& slider)
  55203. {
  55204. g.fillAll (slider.findColour (Slider::backgroundColourId));
  55205. if (style == Slider::LinearBar)
  55206. {
  55207. g.setColour (slider.findColour (Slider::thumbColourId));
  55208. g.fillRect (x, y, (int) sliderPos - x, h);
  55209. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  55210. g.drawRect (x, y, (int) sliderPos - x, h);
  55211. }
  55212. else
  55213. {
  55214. g.setColour (slider.findColour (Slider::trackColourId)
  55215. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  55216. if (slider.isHorizontal())
  55217. {
  55218. g.fillRect (x, y + roundToInt (h * 0.6f),
  55219. w, roundToInt (h * 0.2f));
  55220. }
  55221. else
  55222. {
  55223. g.fillRect (x + roundToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  55224. jmin (4, roundToInt (w * 0.2f)), h);
  55225. }
  55226. float alpha = 0.35f;
  55227. if (slider.isEnabled())
  55228. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  55229. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  55230. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  55231. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  55232. {
  55233. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  55234. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  55235. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  55236. fill, outline);
  55237. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  55238. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  55239. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  55240. fill, outline);
  55241. }
  55242. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  55243. {
  55244. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55245. minSliderPos - 7.0f, y + h * 0.9f ,
  55246. minSliderPos, y + h * 0.9f,
  55247. fill, outline);
  55248. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  55249. maxSliderPos, y + h * 0.9f,
  55250. maxSliderPos + 7.0f, y + h * 0.9f,
  55251. fill, outline);
  55252. }
  55253. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  55254. {
  55255. drawTriangle (g, sliderPos, y + h * 0.9f,
  55256. sliderPos - 7.0f, y + h * 0.2f,
  55257. sliderPos + 7.0f, y + h * 0.2f,
  55258. fill, outline);
  55259. }
  55260. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  55261. {
  55262. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  55263. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  55264. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  55265. fill, outline);
  55266. }
  55267. }
  55268. }
  55269. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  55270. {
  55271. if (isIncrement)
  55272. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  55273. else
  55274. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  55275. }
  55276. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  55277. {
  55278. return &scrollbarShadow;
  55279. }
  55280. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  55281. {
  55282. return 8;
  55283. }
  55284. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  55285. int w, int h,
  55286. bool isMouseOver,
  55287. bool isMouseDragging)
  55288. {
  55289. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  55290. : Colours::darkgrey);
  55291. const float lineThickness = jmin (w, h) * 0.1f;
  55292. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  55293. {
  55294. g.drawLine (w * i,
  55295. h + 1.0f,
  55296. w + 1.0f,
  55297. h * i,
  55298. lineThickness);
  55299. }
  55300. }
  55301. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  55302. {
  55303. Path shape;
  55304. if (buttonType == DocumentWindow::closeButton)
  55305. {
  55306. shape.addLineSegment (Line<float> (0.0f, 0.0f, 1.0f, 1.0f), 0.35f);
  55307. shape.addLineSegment (Line<float> (1.0f, 0.0f, 0.0f, 1.0f), 0.35f);
  55308. ShapeButton* const b = new ShapeButton ("close",
  55309. Colour (0x7fff3333),
  55310. Colour (0xd7ff3333),
  55311. Colour (0xf7ff3333));
  55312. b->setShape (shape, true, true, true);
  55313. return b;
  55314. }
  55315. else if (buttonType == DocumentWindow::minimiseButton)
  55316. {
  55317. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55318. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  55319. DrawablePath dp;
  55320. dp.setPath (shape);
  55321. dp.setFill (Colours::black.withAlpha (0.3f));
  55322. b->setImages (&dp);
  55323. return b;
  55324. }
  55325. else if (buttonType == DocumentWindow::maximiseButton)
  55326. {
  55327. shape.addLineSegment (Line<float> (0.5f, 0.0f, 0.5f, 1.0f), 0.25f);
  55328. shape.addLineSegment (Line<float> (0.0f, 0.5f, 1.0f, 0.5f), 0.25f);
  55329. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  55330. DrawablePath dp;
  55331. dp.setPath (shape);
  55332. dp.setFill (Colours::black.withAlpha (0.3f));
  55333. b->setImages (&dp);
  55334. return b;
  55335. }
  55336. jassertfalse;
  55337. return 0;
  55338. }
  55339. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  55340. int titleBarX,
  55341. int titleBarY,
  55342. int titleBarW,
  55343. int titleBarH,
  55344. Button* minimiseButton,
  55345. Button* maximiseButton,
  55346. Button* closeButton,
  55347. bool positionTitleBarButtonsOnLeft)
  55348. {
  55349. titleBarY += titleBarH / 8;
  55350. titleBarH -= titleBarH / 4;
  55351. const int buttonW = titleBarH;
  55352. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  55353. : titleBarX + titleBarW - buttonW - 4;
  55354. if (closeButton != 0)
  55355. {
  55356. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  55357. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  55358. : -(buttonW + buttonW / 5);
  55359. }
  55360. if (positionTitleBarButtonsOnLeft)
  55361. swapVariables (minimiseButton, maximiseButton);
  55362. if (maximiseButton != 0)
  55363. {
  55364. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55365. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  55366. }
  55367. if (minimiseButton != 0)
  55368. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  55369. }
  55370. END_JUCE_NAMESPACE
  55371. /*** End of inlined file: juce_OldSchoolLookAndFeel.cpp ***/
  55372. /*** Start of inlined file: juce_MenuBarComponent.cpp ***/
  55373. BEGIN_JUCE_NAMESPACE
  55374. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  55375. : model (0),
  55376. itemUnderMouse (-1),
  55377. currentPopupIndex (-1),
  55378. topLevelIndexClicked (0),
  55379. lastMouseX (0),
  55380. lastMouseY (0)
  55381. {
  55382. setRepaintsOnMouseActivity (true);
  55383. setWantsKeyboardFocus (false);
  55384. setMouseClickGrabsKeyboardFocus (false);
  55385. setModel (model_);
  55386. }
  55387. MenuBarComponent::~MenuBarComponent()
  55388. {
  55389. setModel (0);
  55390. Desktop::getInstance().removeGlobalMouseListener (this);
  55391. }
  55392. MenuBarModel* MenuBarComponent::getModel() const throw()
  55393. {
  55394. return model;
  55395. }
  55396. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  55397. {
  55398. if (model != newModel)
  55399. {
  55400. if (model != 0)
  55401. model->removeListener (this);
  55402. model = newModel;
  55403. if (model != 0)
  55404. model->addListener (this);
  55405. repaint();
  55406. menuBarItemsChanged (0);
  55407. }
  55408. }
  55409. void MenuBarComponent::paint (Graphics& g)
  55410. {
  55411. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  55412. getLookAndFeel().drawMenuBarBackground (g,
  55413. getWidth(),
  55414. getHeight(),
  55415. isMouseOverBar,
  55416. *this);
  55417. if (model != 0)
  55418. {
  55419. for (int i = 0; i < menuNames.size(); ++i)
  55420. {
  55421. g.saveState();
  55422. g.setOrigin (xPositions [i], 0);
  55423. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  55424. getLookAndFeel().drawMenuBarItem (g,
  55425. xPositions[i + 1] - xPositions[i],
  55426. getHeight(),
  55427. i,
  55428. menuNames[i],
  55429. i == itemUnderMouse,
  55430. i == currentPopupIndex,
  55431. isMouseOverBar,
  55432. *this);
  55433. g.restoreState();
  55434. }
  55435. }
  55436. }
  55437. void MenuBarComponent::resized()
  55438. {
  55439. xPositions.clear();
  55440. int x = 0;
  55441. xPositions.add (x);
  55442. for (int i = 0; i < menuNames.size(); ++i)
  55443. {
  55444. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  55445. xPositions.add (x);
  55446. }
  55447. }
  55448. int MenuBarComponent::getItemAt (const int x, const int y)
  55449. {
  55450. for (int i = 0; i < xPositions.size(); ++i)
  55451. if (x >= xPositions[i] && x < xPositions[i + 1])
  55452. return reallyContains (x, y, true) ? i : -1;
  55453. return -1;
  55454. }
  55455. void MenuBarComponent::repaintMenuItem (int index)
  55456. {
  55457. if (((unsigned int) index) < (unsigned int) xPositions.size())
  55458. {
  55459. const int x1 = xPositions [index];
  55460. const int x2 = xPositions [index + 1];
  55461. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  55462. }
  55463. }
  55464. void MenuBarComponent::setItemUnderMouse (const int index)
  55465. {
  55466. if (itemUnderMouse != index)
  55467. {
  55468. repaintMenuItem (itemUnderMouse);
  55469. itemUnderMouse = index;
  55470. repaintMenuItem (itemUnderMouse);
  55471. }
  55472. }
  55473. void MenuBarComponent::setOpenItem (int index)
  55474. {
  55475. if (currentPopupIndex != index)
  55476. {
  55477. repaintMenuItem (currentPopupIndex);
  55478. currentPopupIndex = index;
  55479. repaintMenuItem (currentPopupIndex);
  55480. if (index >= 0)
  55481. Desktop::getInstance().addGlobalMouseListener (this);
  55482. else
  55483. Desktop::getInstance().removeGlobalMouseListener (this);
  55484. }
  55485. }
  55486. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  55487. {
  55488. setItemUnderMouse (getItemAt (x, y));
  55489. }
  55490. class MenuBarComponent::AsyncCallback : public ModalComponentManager::Callback
  55491. {
  55492. public:
  55493. AsyncCallback (MenuBarComponent* const bar_, const int topLevelIndex_)
  55494. : bar (bar_), topLevelIndex (topLevelIndex_)
  55495. {
  55496. }
  55497. ~AsyncCallback() {}
  55498. void modalStateFinished (int returnValue)
  55499. {
  55500. if (bar != 0)
  55501. bar->menuDismissed (topLevelIndex, returnValue);
  55502. }
  55503. private:
  55504. Component::SafePointer<MenuBarComponent> bar;
  55505. const int topLevelIndex;
  55506. AsyncCallback (const AsyncCallback&);
  55507. AsyncCallback& operator= (const AsyncCallback&);
  55508. };
  55509. void MenuBarComponent::showMenu (int index)
  55510. {
  55511. if (index != currentPopupIndex)
  55512. {
  55513. PopupMenu::dismissAllActiveMenus();
  55514. menuBarItemsChanged (0);
  55515. setOpenItem (index);
  55516. setItemUnderMouse (index);
  55517. if (index >= 0)
  55518. {
  55519. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  55520. menuNames [itemUnderMouse]));
  55521. if (m.lookAndFeel == 0)
  55522. m.setLookAndFeel (&getLookAndFeel());
  55523. const Rectangle<int> itemPos (xPositions [index], 0, xPositions [index + 1] - xPositions [index], getHeight());
  55524. m.showMenu (itemPos + getScreenPosition(),
  55525. 0, itemPos.getWidth(), 0, 0, true, this,
  55526. new AsyncCallback (this, index));
  55527. }
  55528. }
  55529. }
  55530. void MenuBarComponent::menuDismissed (int topLevelIndex, int itemId)
  55531. {
  55532. topLevelIndexClicked = topLevelIndex;
  55533. postCommandMessage (itemId);
  55534. }
  55535. void MenuBarComponent::handleCommandMessage (int commandId)
  55536. {
  55537. const Point<int> mousePos (getMouseXYRelative());
  55538. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55539. if (currentPopupIndex == topLevelIndexClicked)
  55540. setOpenItem (-1);
  55541. if (commandId != 0 && model != 0)
  55542. model->menuItemSelected (commandId, topLevelIndexClicked);
  55543. }
  55544. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  55545. {
  55546. if (e.eventComponent == this)
  55547. updateItemUnderMouse (e.x, e.y);
  55548. }
  55549. void MenuBarComponent::mouseExit (const MouseEvent& e)
  55550. {
  55551. if (e.eventComponent == this)
  55552. updateItemUnderMouse (e.x, e.y);
  55553. }
  55554. void MenuBarComponent::mouseDown (const MouseEvent& e)
  55555. {
  55556. if (currentPopupIndex < 0)
  55557. {
  55558. const MouseEvent e2 (e.getEventRelativeTo (this));
  55559. updateItemUnderMouse (e2.x, e2.y);
  55560. currentPopupIndex = -2;
  55561. showMenu (itemUnderMouse);
  55562. }
  55563. }
  55564. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  55565. {
  55566. const MouseEvent e2 (e.getEventRelativeTo (this));
  55567. const int item = getItemAt (e2.x, e2.y);
  55568. if (item >= 0)
  55569. showMenu (item);
  55570. }
  55571. void MenuBarComponent::mouseUp (const MouseEvent& e)
  55572. {
  55573. const MouseEvent e2 (e.getEventRelativeTo (this));
  55574. updateItemUnderMouse (e2.x, e2.y);
  55575. if (itemUnderMouse < 0 && getLocalBounds().contains (e2.x, e2.y))
  55576. {
  55577. setOpenItem (-1);
  55578. PopupMenu::dismissAllActiveMenus();
  55579. }
  55580. }
  55581. void MenuBarComponent::mouseMove (const MouseEvent& e)
  55582. {
  55583. const MouseEvent e2 (e.getEventRelativeTo (this));
  55584. if (lastMouseX != e2.x || lastMouseY != e2.y)
  55585. {
  55586. if (currentPopupIndex >= 0)
  55587. {
  55588. const int item = getItemAt (e2.x, e2.y);
  55589. if (item >= 0)
  55590. showMenu (item);
  55591. }
  55592. else
  55593. {
  55594. updateItemUnderMouse (e2.x, e2.y);
  55595. }
  55596. lastMouseX = e2.x;
  55597. lastMouseY = e2.y;
  55598. }
  55599. }
  55600. bool MenuBarComponent::keyPressed (const KeyPress& key)
  55601. {
  55602. bool used = false;
  55603. const int numMenus = menuNames.size();
  55604. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  55605. if (key.isKeyCode (KeyPress::leftKey))
  55606. {
  55607. showMenu ((currentIndex + numMenus - 1) % numMenus);
  55608. used = true;
  55609. }
  55610. else if (key.isKeyCode (KeyPress::rightKey))
  55611. {
  55612. showMenu ((currentIndex + 1) % numMenus);
  55613. used = true;
  55614. }
  55615. return used;
  55616. }
  55617. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  55618. {
  55619. StringArray newNames;
  55620. if (model != 0)
  55621. newNames = model->getMenuBarNames();
  55622. if (newNames != menuNames)
  55623. {
  55624. menuNames = newNames;
  55625. repaint();
  55626. resized();
  55627. }
  55628. }
  55629. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  55630. const ApplicationCommandTarget::InvocationInfo& info)
  55631. {
  55632. if (model == 0 || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  55633. return;
  55634. for (int i = 0; i < menuNames.size(); ++i)
  55635. {
  55636. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  55637. if (menu.containsCommandItem (info.commandID))
  55638. {
  55639. setItemUnderMouse (i);
  55640. startTimer (200);
  55641. break;
  55642. }
  55643. }
  55644. }
  55645. void MenuBarComponent::timerCallback()
  55646. {
  55647. stopTimer();
  55648. const Point<int> mousePos (getMouseXYRelative());
  55649. updateItemUnderMouse (mousePos.getX(), mousePos.getY());
  55650. }
  55651. END_JUCE_NAMESPACE
  55652. /*** End of inlined file: juce_MenuBarComponent.cpp ***/
  55653. /*** Start of inlined file: juce_MenuBarModel.cpp ***/
  55654. BEGIN_JUCE_NAMESPACE
  55655. MenuBarModel::MenuBarModel() throw()
  55656. : manager (0)
  55657. {
  55658. }
  55659. MenuBarModel::~MenuBarModel()
  55660. {
  55661. setApplicationCommandManagerToWatch (0);
  55662. }
  55663. void MenuBarModel::menuItemsChanged()
  55664. {
  55665. triggerAsyncUpdate();
  55666. }
  55667. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  55668. {
  55669. if (manager != newManager)
  55670. {
  55671. if (manager != 0)
  55672. manager->removeListener (this);
  55673. manager = newManager;
  55674. if (manager != 0)
  55675. manager->addListener (this);
  55676. }
  55677. }
  55678. void MenuBarModel::addListener (Listener* const newListener) throw()
  55679. {
  55680. listeners.add (newListener);
  55681. }
  55682. void MenuBarModel::removeListener (Listener* const listenerToRemove) throw()
  55683. {
  55684. // Trying to remove a listener that isn't on the list!
  55685. // If this assertion happens because this object is a dangling pointer, make sure you've not
  55686. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  55687. jassert (listeners.contains (listenerToRemove));
  55688. listeners.remove (listenerToRemove);
  55689. }
  55690. void MenuBarModel::handleAsyncUpdate()
  55691. {
  55692. listeners.call (&MenuBarModel::Listener::menuBarItemsChanged, this);
  55693. }
  55694. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  55695. {
  55696. listeners.call (&MenuBarModel::Listener::menuCommandInvoked, this, info);
  55697. }
  55698. void MenuBarModel::applicationCommandListChanged()
  55699. {
  55700. menuItemsChanged();
  55701. }
  55702. END_JUCE_NAMESPACE
  55703. /*** End of inlined file: juce_MenuBarModel.cpp ***/
  55704. /*** Start of inlined file: juce_PopupMenu.cpp ***/
  55705. BEGIN_JUCE_NAMESPACE
  55706. class PopupMenu::Item
  55707. {
  55708. public:
  55709. Item()
  55710. : itemId (0), active (true), isSeparator (true), isTicked (false),
  55711. usesColour (false), customComp (0), commandManager (0)
  55712. {
  55713. }
  55714. Item (const int itemId_,
  55715. const String& text_,
  55716. const bool active_,
  55717. const bool isTicked_,
  55718. const Image& im,
  55719. const Colour& textColour_,
  55720. const bool usesColour_,
  55721. PopupMenuCustomComponent* const customComp_,
  55722. const PopupMenu* const subMenu_,
  55723. ApplicationCommandManager* const commandManager_)
  55724. : itemId (itemId_), text (text_), textColour (textColour_),
  55725. active (active_), isSeparator (false), isTicked (isTicked_),
  55726. usesColour (usesColour_), image (im), customComp (customComp_),
  55727. commandManager (commandManager_)
  55728. {
  55729. if (subMenu_ != 0)
  55730. subMenu = new PopupMenu (*subMenu_);
  55731. if (commandManager_ != 0 && itemId_ != 0)
  55732. {
  55733. String shortcutKey;
  55734. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  55735. ->getKeyPressesAssignedToCommand (itemId_));
  55736. for (int i = 0; i < keyPresses.size(); ++i)
  55737. {
  55738. const String key (keyPresses.getReference(i).getTextDescription());
  55739. if (shortcutKey.isNotEmpty())
  55740. shortcutKey << ", ";
  55741. if (key.length() == 1)
  55742. shortcutKey << "shortcut: '" << key << '\'';
  55743. else
  55744. shortcutKey << key;
  55745. }
  55746. shortcutKey = shortcutKey.trim();
  55747. if (shortcutKey.isNotEmpty())
  55748. text << "<end>" << shortcutKey;
  55749. }
  55750. }
  55751. Item (const Item& other)
  55752. : itemId (other.itemId),
  55753. text (other.text),
  55754. textColour (other.textColour),
  55755. active (other.active),
  55756. isSeparator (other.isSeparator),
  55757. isTicked (other.isTicked),
  55758. usesColour (other.usesColour),
  55759. image (other.image),
  55760. customComp (other.customComp),
  55761. commandManager (other.commandManager)
  55762. {
  55763. if (other.subMenu != 0)
  55764. subMenu = new PopupMenu (*(other.subMenu));
  55765. }
  55766. ~Item()
  55767. {
  55768. customComp = 0;
  55769. }
  55770. bool canBeTriggered() const throw()
  55771. {
  55772. return active && ! (isSeparator || (subMenu != 0));
  55773. }
  55774. bool hasActiveSubMenu() const throw()
  55775. {
  55776. return active && (subMenu != 0);
  55777. }
  55778. const int itemId;
  55779. String text;
  55780. const Colour textColour;
  55781. const bool active, isSeparator, isTicked, usesColour;
  55782. Image image;
  55783. ReferenceCountedObjectPtr <PopupMenuCustomComponent> customComp;
  55784. ScopedPointer <PopupMenu> subMenu;
  55785. ApplicationCommandManager* const commandManager;
  55786. juce_UseDebuggingNewOperator
  55787. private:
  55788. Item& operator= (const Item&);
  55789. };
  55790. class PopupMenu::ItemComponent : public Component
  55791. {
  55792. public:
  55793. ItemComponent (const PopupMenu::Item& itemInfo_)
  55794. : itemInfo (itemInfo_),
  55795. isHighlighted (false)
  55796. {
  55797. if (itemInfo.customComp != 0)
  55798. addAndMakeVisible (itemInfo.customComp);
  55799. }
  55800. ~ItemComponent()
  55801. {
  55802. if (itemInfo.customComp != 0)
  55803. removeChildComponent (itemInfo.customComp);
  55804. }
  55805. void getIdealSize (int& idealWidth,
  55806. int& idealHeight,
  55807. const int standardItemHeight)
  55808. {
  55809. if (itemInfo.customComp != 0)
  55810. {
  55811. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  55812. }
  55813. else
  55814. {
  55815. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  55816. itemInfo.isSeparator,
  55817. standardItemHeight,
  55818. idealWidth,
  55819. idealHeight);
  55820. }
  55821. }
  55822. void paint (Graphics& g)
  55823. {
  55824. if (itemInfo.customComp == 0)
  55825. {
  55826. String mainText (itemInfo.text);
  55827. String endText;
  55828. const int endIndex = mainText.indexOf ("<end>");
  55829. if (endIndex >= 0)
  55830. {
  55831. endText = mainText.substring (endIndex + 5).trim();
  55832. mainText = mainText.substring (0, endIndex);
  55833. }
  55834. getLookAndFeel()
  55835. .drawPopupMenuItem (g, getWidth(), getHeight(),
  55836. itemInfo.isSeparator,
  55837. itemInfo.active,
  55838. isHighlighted,
  55839. itemInfo.isTicked,
  55840. itemInfo.subMenu != 0,
  55841. mainText, endText,
  55842. itemInfo.image.isValid() ? &itemInfo.image : 0,
  55843. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  55844. }
  55845. }
  55846. void resized()
  55847. {
  55848. if (getNumChildComponents() > 0)
  55849. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  55850. }
  55851. void setHighlighted (bool shouldBeHighlighted)
  55852. {
  55853. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  55854. if (isHighlighted != shouldBeHighlighted)
  55855. {
  55856. isHighlighted = shouldBeHighlighted;
  55857. if (itemInfo.customComp != 0)
  55858. {
  55859. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  55860. itemInfo.customComp->repaint();
  55861. }
  55862. repaint();
  55863. }
  55864. }
  55865. PopupMenu::Item itemInfo;
  55866. juce_UseDebuggingNewOperator
  55867. private:
  55868. bool isHighlighted;
  55869. ItemComponent (const ItemComponent&);
  55870. ItemComponent& operator= (const ItemComponent&);
  55871. };
  55872. namespace PopupMenuSettings
  55873. {
  55874. static const int scrollZone = 24;
  55875. static const int borderSize = 2;
  55876. static const int timerInterval = 50;
  55877. static const int dismissCommandId = 0x6287345f;
  55878. }
  55879. class PopupMenu::Window : public Component,
  55880. private Timer
  55881. {
  55882. public:
  55883. Window()
  55884. : Component ("menu"),
  55885. owner (0),
  55886. currentChild (0),
  55887. activeSubMenu (0),
  55888. managerOfChosenCommand (0),
  55889. minimumWidth (0),
  55890. maximumNumColumns (7),
  55891. standardItemHeight (0),
  55892. isOver (false),
  55893. hasBeenOver (false),
  55894. isDown (false),
  55895. needsToScroll (false),
  55896. hideOnExit (false),
  55897. disableMouseMoves (false),
  55898. hasAnyJuceCompHadFocus (false),
  55899. numColumns (0),
  55900. contentHeight (0),
  55901. childYOffset (0),
  55902. timeEnteredCurrentChildComp (0),
  55903. scrollAcceleration (1.0)
  55904. {
  55905. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  55906. setWantsKeyboardFocus (true);
  55907. setMouseClickGrabsKeyboardFocus (false);
  55908. setAlwaysOnTop (true);
  55909. Desktop::getInstance().addGlobalMouseListener (this);
  55910. getActiveWindows().add (this);
  55911. }
  55912. ~Window()
  55913. {
  55914. getActiveWindows().removeValue (this);
  55915. Desktop::getInstance().removeGlobalMouseListener (this);
  55916. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  55917. activeSubMenu = 0;
  55918. deleteAllChildren();
  55919. }
  55920. static Window* create (const PopupMenu& menu,
  55921. const bool dismissOnMouseUp,
  55922. Window* const owner_,
  55923. const Rectangle<int>& target,
  55924. const int minimumWidth,
  55925. const int maximumNumColumns,
  55926. const int standardItemHeight,
  55927. const bool alignToRectangle,
  55928. const int itemIdThatMustBeVisible,
  55929. ApplicationCommandManager** managerOfChosenCommand,
  55930. Component* const componentAttachedTo)
  55931. {
  55932. if (menu.items.size() > 0)
  55933. {
  55934. int totalItems = 0;
  55935. ScopedPointer <Window> mw (new Window());
  55936. mw->setLookAndFeel (menu.lookAndFeel);
  55937. mw->setWantsKeyboardFocus (false);
  55938. mw->setOpaque (mw->getLookAndFeel().findColour (PopupMenu::backgroundColourId).isOpaque() || ! Desktop::canUseSemiTransparentWindows());
  55939. mw->minimumWidth = minimumWidth;
  55940. mw->maximumNumColumns = maximumNumColumns;
  55941. mw->standardItemHeight = standardItemHeight;
  55942. mw->dismissOnMouseUp = dismissOnMouseUp;
  55943. for (int i = 0; i < menu.items.size(); ++i)
  55944. {
  55945. PopupMenu::Item* const item = menu.items.getUnchecked(i);
  55946. mw->addItem (*item);
  55947. ++totalItems;
  55948. }
  55949. if (totalItems > 0)
  55950. {
  55951. mw->owner = owner_;
  55952. mw->managerOfChosenCommand = managerOfChosenCommand;
  55953. mw->componentAttachedTo = componentAttachedTo;
  55954. mw->componentAttachedToOriginal = componentAttachedTo;
  55955. mw->calculateWindowPos (target, alignToRectangle);
  55956. mw->setTopLeftPosition (mw->windowPos.getX(),
  55957. mw->windowPos.getY());
  55958. mw->updateYPositions();
  55959. if (itemIdThatMustBeVisible != 0)
  55960. {
  55961. const int y = target.getY() - mw->windowPos.getY();
  55962. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  55963. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  55964. }
  55965. mw->resizeToBestWindowPos();
  55966. mw->addToDesktop (ComponentPeer::windowIsTemporary
  55967. | mw->getLookAndFeel().getMenuWindowFlags());
  55968. return mw.release();
  55969. }
  55970. }
  55971. return 0;
  55972. }
  55973. void paint (Graphics& g)
  55974. {
  55975. if (isOpaque())
  55976. g.fillAll (Colours::white);
  55977. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  55978. }
  55979. void paintOverChildren (Graphics& g)
  55980. {
  55981. if (isScrolling())
  55982. {
  55983. LookAndFeel& lf = getLookAndFeel();
  55984. if (isScrollZoneActive (false))
  55985. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, true);
  55986. if (isScrollZoneActive (true))
  55987. {
  55988. g.setOrigin (0, getHeight() - PopupMenuSettings::scrollZone);
  55989. lf.drawPopupMenuUpDownArrow (g, getWidth(), PopupMenuSettings::scrollZone, false);
  55990. }
  55991. }
  55992. }
  55993. bool isScrollZoneActive (bool bottomOne) const
  55994. {
  55995. return isScrolling()
  55996. && (bottomOne
  55997. ? childYOffset < contentHeight - windowPos.getHeight()
  55998. : childYOffset > 0);
  55999. }
  56000. void addItem (const PopupMenu::Item& item)
  56001. {
  56002. PopupMenu::ItemComponent* const mic = new PopupMenu::ItemComponent (item);
  56003. addAndMakeVisible (mic);
  56004. int itemW = 80;
  56005. int itemH = 16;
  56006. mic->getIdealSize (itemW, itemH, standardItemHeight);
  56007. mic->setSize (itemW, jlimit (2, 600, itemH));
  56008. mic->addMouseListener (this, false);
  56009. }
  56010. // hide this and all sub-comps
  56011. void hide (const PopupMenu::Item* const item, const bool makeInvisible)
  56012. {
  56013. if (isVisible())
  56014. {
  56015. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56016. activeSubMenu = 0;
  56017. currentChild = 0;
  56018. exitModalState (item != 0 ? item->itemId : 0);
  56019. if (makeInvisible)
  56020. setVisible (false);
  56021. if (item != 0
  56022. && item->commandManager != 0
  56023. && item->itemId != 0)
  56024. {
  56025. *managerOfChosenCommand = item->commandManager;
  56026. }
  56027. }
  56028. }
  56029. void dismissMenu (const PopupMenu::Item* const item)
  56030. {
  56031. if (owner != 0)
  56032. {
  56033. owner->dismissMenu (item);
  56034. }
  56035. else
  56036. {
  56037. if (item != 0)
  56038. {
  56039. // need a copy of this on the stack as the one passed in will get deleted during this call
  56040. const PopupMenu::Item mi (*item);
  56041. hide (&mi, false);
  56042. }
  56043. else
  56044. {
  56045. hide (0, false);
  56046. }
  56047. }
  56048. }
  56049. void mouseMove (const MouseEvent&)
  56050. {
  56051. timerCallback();
  56052. }
  56053. void mouseDown (const MouseEvent&)
  56054. {
  56055. timerCallback();
  56056. }
  56057. void mouseDrag (const MouseEvent&)
  56058. {
  56059. timerCallback();
  56060. }
  56061. void mouseUp (const MouseEvent&)
  56062. {
  56063. timerCallback();
  56064. }
  56065. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  56066. {
  56067. alterChildYPos (roundToInt (-10.0f * amountY * PopupMenuSettings::scrollZone));
  56068. lastMouse = Point<int> (-1, -1);
  56069. }
  56070. bool keyPressed (const KeyPress& key)
  56071. {
  56072. if (key.isKeyCode (KeyPress::downKey))
  56073. {
  56074. selectNextItem (1);
  56075. }
  56076. else if (key.isKeyCode (KeyPress::upKey))
  56077. {
  56078. selectNextItem (-1);
  56079. }
  56080. else if (key.isKeyCode (KeyPress::leftKey))
  56081. {
  56082. if (owner != 0)
  56083. {
  56084. Component::SafePointer<Window> parentWindow (owner);
  56085. PopupMenu::ItemComponent* currentChildOfParent = parentWindow->currentChild;
  56086. hide (0, true);
  56087. if (parentWindow != 0)
  56088. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  56089. disableTimerUntilMouseMoves();
  56090. }
  56091. else if (componentAttachedTo != 0)
  56092. {
  56093. componentAttachedTo->keyPressed (key);
  56094. }
  56095. }
  56096. else if (key.isKeyCode (KeyPress::rightKey))
  56097. {
  56098. disableTimerUntilMouseMoves();
  56099. if (showSubMenuFor (currentChild))
  56100. {
  56101. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56102. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  56103. activeSubMenu->selectNextItem (1);
  56104. }
  56105. else if (componentAttachedTo != 0)
  56106. {
  56107. componentAttachedTo->keyPressed (key);
  56108. }
  56109. }
  56110. else if (key.isKeyCode (KeyPress::returnKey))
  56111. {
  56112. triggerCurrentlyHighlightedItem();
  56113. }
  56114. else if (key.isKeyCode (KeyPress::escapeKey))
  56115. {
  56116. dismissMenu (0);
  56117. }
  56118. else
  56119. {
  56120. return false;
  56121. }
  56122. return true;
  56123. }
  56124. void inputAttemptWhenModal()
  56125. {
  56126. Component::SafePointer<Component> deletionChecker (this);
  56127. timerCallback();
  56128. if (deletionChecker != 0 && ! isOverAnyMenu())
  56129. {
  56130. if (componentAttachedTo != 0)
  56131. {
  56132. // we want to dismiss the menu, but if we do it synchronously, then
  56133. // the mouse-click will be allowed to pass through. That's good, except
  56134. // when the user clicks on the button that orginally popped the menu up,
  56135. // as they'll expect the menu to go away, and in fact it'll just
  56136. // come back. So only dismiss synchronously if they're not on the original
  56137. // comp that we're attached to.
  56138. const Point<int> mousePos (componentAttachedTo->getMouseXYRelative());
  56139. if (componentAttachedTo->reallyContains (mousePos.getX(), mousePos.getY(), true))
  56140. {
  56141. postCommandMessage (PopupMenuSettings::dismissCommandId); // dismiss asynchrounously
  56142. return;
  56143. }
  56144. }
  56145. dismissMenu (0);
  56146. }
  56147. }
  56148. void handleCommandMessage (int commandId)
  56149. {
  56150. Component::handleCommandMessage (commandId);
  56151. if (commandId == PopupMenuSettings::dismissCommandId)
  56152. dismissMenu (0);
  56153. }
  56154. void timerCallback()
  56155. {
  56156. if (! isVisible())
  56157. return;
  56158. if (componentAttachedTo != componentAttachedToOriginal)
  56159. {
  56160. dismissMenu (0);
  56161. return;
  56162. }
  56163. Window* currentlyModalWindow = dynamic_cast <Window*> (Component::getCurrentlyModalComponent());
  56164. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  56165. return;
  56166. startTimer (PopupMenuSettings::timerInterval); // do this in case it was called from a mouse
  56167. // move rather than a real timer callback
  56168. const Point<int> globalMousePos (Desktop::getMousePosition());
  56169. const Point<int> localMousePos (globalPositionToRelative (globalMousePos));
  56170. const uint32 now = Time::getMillisecondCounter();
  56171. if (now > timeEnteredCurrentChildComp + 100
  56172. && reallyContains (localMousePos.getX(), localMousePos.getY(), true)
  56173. && currentChild->isValidComponent()
  56174. && (! disableMouseMoves)
  56175. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  56176. {
  56177. showSubMenuFor (currentChild);
  56178. }
  56179. if (globalMousePos != lastMouse || now > lastMouseMoveTime + 350)
  56180. {
  56181. highlightItemUnderMouse (globalMousePos, localMousePos);
  56182. }
  56183. bool overScrollArea = false;
  56184. if (isScrolling()
  56185. && (isOver || (isDown && ((unsigned int) localMousePos.getX()) < (unsigned int) getWidth()))
  56186. && ((isScrollZoneActive (false) && localMousePos.getY() < PopupMenuSettings::scrollZone)
  56187. || (isScrollZoneActive (true) && localMousePos.getY() > getHeight() - PopupMenuSettings::scrollZone)))
  56188. {
  56189. if (now > lastScroll + 20)
  56190. {
  56191. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  56192. int amount = 0;
  56193. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  56194. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  56195. alterChildYPos (localMousePos.getY() < PopupMenuSettings::scrollZone ? -amount : amount);
  56196. lastScroll = now;
  56197. }
  56198. overScrollArea = true;
  56199. lastMouse = Point<int> (-1, -1); // trigger a mouse-move
  56200. }
  56201. else
  56202. {
  56203. scrollAcceleration = 1.0;
  56204. }
  56205. const bool wasDown = isDown;
  56206. bool isOverAny = isOverAnyMenu();
  56207. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  56208. {
  56209. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56210. isOverAny = isOverAnyMenu();
  56211. }
  56212. if (hideOnExit && hasBeenOver && ! isOverAny)
  56213. {
  56214. hide (0, true);
  56215. }
  56216. else
  56217. {
  56218. isDown = hasBeenOver
  56219. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  56220. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  56221. bool anyFocused = Process::isForegroundProcess();
  56222. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  56223. {
  56224. // because no component at all may have focus, our test here will
  56225. // only be triggered when something has focus and then loses it.
  56226. anyFocused = ! hasAnyJuceCompHadFocus;
  56227. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  56228. {
  56229. if (ComponentPeer::getPeer (i)->isFocused())
  56230. {
  56231. anyFocused = true;
  56232. hasAnyJuceCompHadFocus = true;
  56233. break;
  56234. }
  56235. }
  56236. }
  56237. if (! anyFocused)
  56238. {
  56239. if (now > lastFocused + 10)
  56240. {
  56241. wasHiddenBecauseOfAppChange() = true;
  56242. dismissMenu (0);
  56243. return; // may have been deleted by the previous call..
  56244. }
  56245. }
  56246. else if (wasDown && now > menuCreationTime + 250
  56247. && ! (isDown || overScrollArea))
  56248. {
  56249. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56250. if (isOver)
  56251. {
  56252. triggerCurrentlyHighlightedItem();
  56253. }
  56254. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  56255. {
  56256. dismissMenu (0);
  56257. }
  56258. return; // may have been deleted by the previous calls..
  56259. }
  56260. else
  56261. {
  56262. lastFocused = now;
  56263. }
  56264. }
  56265. }
  56266. static Array<Window*>& getActiveWindows()
  56267. {
  56268. static Array<Window*> activeMenuWindows;
  56269. return activeMenuWindows;
  56270. }
  56271. static bool& wasHiddenBecauseOfAppChange() throw()
  56272. {
  56273. static bool b = false;
  56274. return b;
  56275. }
  56276. juce_UseDebuggingNewOperator
  56277. private:
  56278. Window* owner;
  56279. PopupMenu::ItemComponent* currentChild;
  56280. ScopedPointer <Window> activeSubMenu;
  56281. ApplicationCommandManager** managerOfChosenCommand;
  56282. Component::SafePointer<Component> componentAttachedTo;
  56283. Component* componentAttachedToOriginal;
  56284. Rectangle<int> windowPos;
  56285. Point<int> lastMouse;
  56286. int minimumWidth, maximumNumColumns, standardItemHeight;
  56287. bool isOver, hasBeenOver, isDown, needsToScroll;
  56288. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  56289. int numColumns, contentHeight, childYOffset;
  56290. Array <int> columnWidths;
  56291. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  56292. double scrollAcceleration;
  56293. bool overlaps (const Rectangle<int>& r) const
  56294. {
  56295. return r.intersects (getBounds())
  56296. || (owner != 0 && owner->overlaps (r));
  56297. }
  56298. bool isOverAnyMenu() const
  56299. {
  56300. return (owner != 0) ? owner->isOverAnyMenu()
  56301. : isOverChildren();
  56302. }
  56303. bool isOverChildren() const
  56304. {
  56305. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56306. return isVisible()
  56307. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  56308. }
  56309. void updateMouseOverStatus (const Point<int>& globalMousePos)
  56310. {
  56311. const Point<int> relPos (globalPositionToRelative (globalMousePos));
  56312. isOver = reallyContains (relPos.getX(), relPos.getY(), true);
  56313. if (activeSubMenu != 0)
  56314. activeSubMenu->updateMouseOverStatus (globalMousePos);
  56315. }
  56316. bool treeContains (const Window* const window) const throw()
  56317. {
  56318. const Window* mw = this;
  56319. while (mw->owner != 0)
  56320. mw = mw->owner;
  56321. while (mw != 0)
  56322. {
  56323. if (mw == window)
  56324. return true;
  56325. mw = mw->activeSubMenu;
  56326. }
  56327. return false;
  56328. }
  56329. void calculateWindowPos (const Rectangle<int>& target, const bool alignToRectangle)
  56330. {
  56331. const Rectangle<int> mon (Desktop::getInstance()
  56332. .getMonitorAreaContaining (target.getCentre(),
  56333. #if JUCE_MAC
  56334. true));
  56335. #else
  56336. false)); // on windows, don't stop the menu overlapping the taskbar
  56337. #endif
  56338. int x, y, widthToUse, heightToUse;
  56339. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  56340. if (alignToRectangle)
  56341. {
  56342. x = target.getX();
  56343. const int spaceUnder = mon.getHeight() - (target.getBottom() - mon.getY());
  56344. const int spaceOver = target.getY() - mon.getY();
  56345. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  56346. y = target.getBottom();
  56347. else
  56348. y = target.getY() - heightToUse;
  56349. }
  56350. else
  56351. {
  56352. bool tendTowardsRight = target.getCentreX() < mon.getCentreX();
  56353. if (owner != 0)
  56354. {
  56355. if (owner->owner != 0)
  56356. {
  56357. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  56358. > owner->owner->getX() + owner->owner->getWidth() / 2);
  56359. if (ownerGoingRight && target.getRight() + widthToUse < mon.getRight() - 4)
  56360. tendTowardsRight = true;
  56361. else if ((! ownerGoingRight) && target.getX() > widthToUse + 4)
  56362. tendTowardsRight = false;
  56363. }
  56364. else if (target.getRight() + widthToUse < mon.getRight() - 32)
  56365. {
  56366. tendTowardsRight = true;
  56367. }
  56368. }
  56369. const int biggestSpace = jmax (mon.getRight() - target.getRight(),
  56370. target.getX() - mon.getX()) - 32;
  56371. if (biggestSpace < widthToUse)
  56372. {
  56373. layoutMenuItems (biggestSpace + target.getWidth() / 3, widthToUse, heightToUse);
  56374. if (numColumns > 1)
  56375. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  56376. tendTowardsRight = (mon.getRight() - target.getRight()) >= (target.getX() - mon.getX());
  56377. }
  56378. if (tendTowardsRight)
  56379. x = jmin (mon.getRight() - widthToUse - 4, target.getRight());
  56380. else
  56381. x = jmax (mon.getX() + 4, target.getX() - widthToUse);
  56382. y = target.getY();
  56383. if (target.getCentreY() > mon.getCentreY())
  56384. y = jmax (mon.getY(), target.getBottom() - heightToUse);
  56385. }
  56386. x = jmax (mon.getX() + 1, jmin (mon.getRight() - (widthToUse + 6), x));
  56387. y = jmax (mon.getY() + 1, jmin (mon.getBottom() - (heightToUse + 6), y));
  56388. windowPos.setBounds (x, y, widthToUse, heightToUse);
  56389. // sets this flag if it's big enough to obscure any of its parent menus
  56390. hideOnExit = (owner != 0)
  56391. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  56392. }
  56393. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  56394. {
  56395. numColumns = 0;
  56396. contentHeight = 0;
  56397. const int maxMenuH = getParentHeight() - 24;
  56398. int totalW;
  56399. do
  56400. {
  56401. ++numColumns;
  56402. totalW = workOutBestSize (maxMenuW);
  56403. if (totalW > maxMenuW)
  56404. {
  56405. numColumns = jmax (1, numColumns - 1);
  56406. totalW = workOutBestSize (maxMenuW); // to update col widths
  56407. break;
  56408. }
  56409. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  56410. {
  56411. break;
  56412. }
  56413. } while (numColumns < maximumNumColumns);
  56414. const int actualH = jmin (contentHeight, maxMenuH);
  56415. needsToScroll = contentHeight > actualH;
  56416. width = updateYPositions();
  56417. height = actualH + PopupMenuSettings::borderSize * 2;
  56418. }
  56419. int workOutBestSize (const int maxMenuW)
  56420. {
  56421. int totalW = 0;
  56422. contentHeight = 0;
  56423. int childNum = 0;
  56424. for (int col = 0; col < numColumns; ++col)
  56425. {
  56426. int i, colW = 50, colH = 0;
  56427. const int numChildren = jmin (getNumChildComponents() - childNum,
  56428. (getNumChildComponents() + numColumns - 1) / numColumns);
  56429. for (i = numChildren; --i >= 0;)
  56430. {
  56431. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  56432. colH += getChildComponent (childNum + i)->getHeight();
  56433. }
  56434. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + PopupMenuSettings::borderSize * 2);
  56435. columnWidths.set (col, colW);
  56436. totalW += colW;
  56437. contentHeight = jmax (contentHeight, colH);
  56438. childNum += numChildren;
  56439. }
  56440. if (totalW < minimumWidth)
  56441. {
  56442. totalW = minimumWidth;
  56443. for (int col = 0; col < numColumns; ++col)
  56444. columnWidths.set (0, totalW / numColumns);
  56445. }
  56446. return totalW;
  56447. }
  56448. void ensureItemIsVisible (const int itemId, int wantedY)
  56449. {
  56450. jassert (itemId != 0)
  56451. for (int i = getNumChildComponents(); --i >= 0;)
  56452. {
  56453. PopupMenu::ItemComponent* const m = static_cast <PopupMenu::ItemComponent*> (getChildComponent (i));
  56454. if (m != 0
  56455. && m->itemInfo.itemId == itemId
  56456. && windowPos.getHeight() > PopupMenuSettings::scrollZone * 4)
  56457. {
  56458. const int currentY = m->getY();
  56459. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  56460. {
  56461. if (wantedY < 0)
  56462. wantedY = jlimit (PopupMenuSettings::scrollZone,
  56463. jmax (PopupMenuSettings::scrollZone,
  56464. windowPos.getHeight() - (PopupMenuSettings::scrollZone + m->getHeight())),
  56465. currentY);
  56466. const Rectangle<int> mon (Desktop::getInstance().getMonitorAreaContaining (windowPos.getPosition(), true));
  56467. int deltaY = wantedY - currentY;
  56468. windowPos.setSize (jmin (windowPos.getWidth(), mon.getWidth()),
  56469. jmin (windowPos.getHeight(), mon.getHeight()));
  56470. const int newY = jlimit (mon.getY(),
  56471. mon.getBottom() - windowPos.getHeight(),
  56472. windowPos.getY() + deltaY);
  56473. deltaY -= newY - windowPos.getY();
  56474. childYOffset -= deltaY;
  56475. windowPos.setPosition (windowPos.getX(), newY);
  56476. updateYPositions();
  56477. }
  56478. break;
  56479. }
  56480. }
  56481. }
  56482. void resizeToBestWindowPos()
  56483. {
  56484. Rectangle<int> r (windowPos);
  56485. if (childYOffset < 0)
  56486. {
  56487. r.setBounds (r.getX(), r.getY() - childYOffset,
  56488. r.getWidth(), r.getHeight() + childYOffset);
  56489. }
  56490. else if (childYOffset > 0)
  56491. {
  56492. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  56493. if (spaceAtBottom > 0)
  56494. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  56495. }
  56496. setBounds (r);
  56497. updateYPositions();
  56498. }
  56499. void alterChildYPos (const int delta)
  56500. {
  56501. if (isScrolling())
  56502. {
  56503. childYOffset += delta;
  56504. if (delta < 0)
  56505. {
  56506. childYOffset = jmax (childYOffset, 0);
  56507. }
  56508. else if (delta > 0)
  56509. {
  56510. childYOffset = jmin (childYOffset,
  56511. contentHeight - windowPos.getHeight() + PopupMenuSettings::borderSize);
  56512. }
  56513. updateYPositions();
  56514. }
  56515. else
  56516. {
  56517. childYOffset = 0;
  56518. }
  56519. resizeToBestWindowPos();
  56520. repaint();
  56521. }
  56522. int updateYPositions()
  56523. {
  56524. int x = 0;
  56525. int childNum = 0;
  56526. for (int col = 0; col < numColumns; ++col)
  56527. {
  56528. const int numChildren = jmin (getNumChildComponents() - childNum,
  56529. (getNumChildComponents() + numColumns - 1) / numColumns);
  56530. const int colW = columnWidths [col];
  56531. int y = PopupMenuSettings::borderSize - (childYOffset + (getY() - windowPos.getY()));
  56532. for (int i = 0; i < numChildren; ++i)
  56533. {
  56534. Component* const c = getChildComponent (childNum + i);
  56535. c->setBounds (x, y, colW, c->getHeight());
  56536. y += c->getHeight();
  56537. }
  56538. x += colW;
  56539. childNum += numChildren;
  56540. }
  56541. return x;
  56542. }
  56543. bool isScrolling() const throw()
  56544. {
  56545. return childYOffset != 0 || needsToScroll;
  56546. }
  56547. void setCurrentlyHighlightedChild (PopupMenu::ItemComponent* const child)
  56548. {
  56549. if (currentChild->isValidComponent())
  56550. currentChild->setHighlighted (false);
  56551. currentChild = child;
  56552. if (currentChild != 0)
  56553. {
  56554. currentChild->setHighlighted (true);
  56555. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  56556. }
  56557. }
  56558. bool showSubMenuFor (PopupMenu::ItemComponent* const childComp)
  56559. {
  56560. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  56561. activeSubMenu = 0;
  56562. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  56563. {
  56564. activeSubMenu = Window::create (*(childComp->itemInfo.subMenu),
  56565. dismissOnMouseUp,
  56566. this,
  56567. childComp->getScreenBounds(),
  56568. 0, maximumNumColumns,
  56569. standardItemHeight,
  56570. false, 0, managerOfChosenCommand,
  56571. componentAttachedTo);
  56572. if (activeSubMenu != 0)
  56573. {
  56574. activeSubMenu->setVisible (true);
  56575. activeSubMenu->enterModalState (false);
  56576. activeSubMenu->toFront (false);
  56577. return true;
  56578. }
  56579. }
  56580. return false;
  56581. }
  56582. void highlightItemUnderMouse (const Point<int>& globalMousePos, const Point<int>& localMousePos)
  56583. {
  56584. isOver = reallyContains (localMousePos.getX(), localMousePos.getY(), true);
  56585. if (isOver)
  56586. hasBeenOver = true;
  56587. if (lastMouse.getDistanceFrom (globalMousePos) > 2)
  56588. {
  56589. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  56590. if (disableMouseMoves && isOver)
  56591. disableMouseMoves = false;
  56592. }
  56593. if (disableMouseMoves || (activeSubMenu != 0 && activeSubMenu->isOverChildren()))
  56594. return;
  56595. bool isMovingTowardsMenu = false;
  56596. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  56597. if (isOver && (activeSubMenu != 0) && globalMousePos != lastMouse)
  56598. {
  56599. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  56600. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  56601. // extends from the last mouse pos to the submenu's rectangle..
  56602. float subX = (float) activeSubMenu->getScreenX();
  56603. if (activeSubMenu->getX() > getX())
  56604. {
  56605. lastMouse -= Point<int> (2, 0); // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  56606. }
  56607. else
  56608. {
  56609. lastMouse += Point<int> (2, 0);
  56610. subX += activeSubMenu->getWidth();
  56611. }
  56612. Path areaTowardsSubMenu;
  56613. areaTowardsSubMenu.addTriangle ((float) lastMouse.getX(),
  56614. (float) lastMouse.getY(),
  56615. subX,
  56616. (float) activeSubMenu->getScreenY(),
  56617. subX,
  56618. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  56619. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) globalMousePos.getX(), (float) globalMousePos.getY());
  56620. }
  56621. lastMouse = globalMousePos;
  56622. if (! isMovingTowardsMenu)
  56623. {
  56624. Component* c = getComponentAt (localMousePos.getX(), localMousePos.getY());
  56625. if (c == this)
  56626. c = 0;
  56627. PopupMenu::ItemComponent* mic = dynamic_cast <PopupMenu::ItemComponent*> (c);
  56628. if (mic == 0 && c != 0)
  56629. mic = c->findParentComponentOfClass ((PopupMenu::ItemComponent*) 0);
  56630. if (mic != currentChild
  56631. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  56632. {
  56633. if (isOver && (c != 0) && (activeSubMenu != 0))
  56634. {
  56635. activeSubMenu->hide (0, true);
  56636. }
  56637. if (! isOver)
  56638. mic = 0;
  56639. setCurrentlyHighlightedChild (mic);
  56640. }
  56641. }
  56642. }
  56643. void triggerCurrentlyHighlightedItem()
  56644. {
  56645. if (currentChild->isValidComponent()
  56646. && currentChild->itemInfo.canBeTriggered()
  56647. && (currentChild->itemInfo.customComp == 0
  56648. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  56649. {
  56650. dismissMenu (&currentChild->itemInfo);
  56651. }
  56652. }
  56653. void selectNextItem (const int delta)
  56654. {
  56655. disableTimerUntilMouseMoves();
  56656. PopupMenu::ItemComponent* mic = 0;
  56657. bool wasLastOne = (currentChild == 0);
  56658. const int numItems = getNumChildComponents();
  56659. for (int i = 0; i < numItems + 1; ++i)
  56660. {
  56661. int index = (delta > 0) ? i : (numItems - 1 - i);
  56662. index = (index + numItems) % numItems;
  56663. mic = dynamic_cast <PopupMenu::ItemComponent*> (getChildComponent (index));
  56664. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  56665. && wasLastOne)
  56666. break;
  56667. if (mic == currentChild)
  56668. wasLastOne = true;
  56669. }
  56670. setCurrentlyHighlightedChild (mic);
  56671. }
  56672. void disableTimerUntilMouseMoves()
  56673. {
  56674. disableMouseMoves = true;
  56675. if (owner != 0)
  56676. owner->disableTimerUntilMouseMoves();
  56677. }
  56678. Window (const Window&);
  56679. Window& operator= (const Window&);
  56680. };
  56681. PopupMenu::PopupMenu()
  56682. : lookAndFeel (0),
  56683. separatorPending (false)
  56684. {
  56685. }
  56686. PopupMenu::PopupMenu (const PopupMenu& other)
  56687. : lookAndFeel (other.lookAndFeel),
  56688. separatorPending (false)
  56689. {
  56690. items.addCopiesOf (other.items);
  56691. }
  56692. PopupMenu& PopupMenu::operator= (const PopupMenu& other)
  56693. {
  56694. if (this != &other)
  56695. {
  56696. lookAndFeel = other.lookAndFeel;
  56697. clear();
  56698. items.addCopiesOf (other.items);
  56699. }
  56700. return *this;
  56701. }
  56702. PopupMenu::~PopupMenu()
  56703. {
  56704. clear();
  56705. }
  56706. void PopupMenu::clear()
  56707. {
  56708. items.clear();
  56709. separatorPending = false;
  56710. }
  56711. void PopupMenu::addSeparatorIfPending()
  56712. {
  56713. if (separatorPending)
  56714. {
  56715. separatorPending = false;
  56716. if (items.size() > 0)
  56717. items.add (new Item());
  56718. }
  56719. }
  56720. void PopupMenu::addItem (const int itemResultId,
  56721. const String& itemText,
  56722. const bool isActive,
  56723. const bool isTicked,
  56724. const Image& iconToUse)
  56725. {
  56726. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56727. // didn't pick anything, so you shouldn't use it as the id
  56728. // for an item..
  56729. addSeparatorIfPending();
  56730. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56731. Colours::black, false, 0, 0, 0));
  56732. }
  56733. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  56734. const int commandID,
  56735. const String& displayName)
  56736. {
  56737. jassert (commandManager != 0 && commandID != 0);
  56738. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  56739. if (registeredInfo != 0)
  56740. {
  56741. ApplicationCommandInfo info (*registeredInfo);
  56742. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  56743. addSeparatorIfPending();
  56744. items.add (new Item (commandID,
  56745. displayName.isNotEmpty() ? displayName
  56746. : info.shortName,
  56747. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  56748. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  56749. Image::null,
  56750. Colours::black,
  56751. false,
  56752. 0, 0,
  56753. commandManager));
  56754. }
  56755. }
  56756. void PopupMenu::addColouredItem (const int itemResultId,
  56757. const String& itemText,
  56758. const Colour& itemTextColour,
  56759. const bool isActive,
  56760. const bool isTicked,
  56761. const Image& iconToUse)
  56762. {
  56763. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56764. // didn't pick anything, so you shouldn't use it as the id
  56765. // for an item..
  56766. addSeparatorIfPending();
  56767. items.add (new Item (itemResultId, itemText, isActive, isTicked, iconToUse,
  56768. itemTextColour, true, 0, 0, 0));
  56769. }
  56770. void PopupMenu::addCustomItem (const int itemResultId,
  56771. PopupMenuCustomComponent* const customComponent)
  56772. {
  56773. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  56774. // didn't pick anything, so you shouldn't use it as the id
  56775. // for an item..
  56776. addSeparatorIfPending();
  56777. items.add (new Item (itemResultId, String::empty, true, false, Image::null,
  56778. Colours::black, false, customComponent, 0, 0));
  56779. }
  56780. class NormalComponentWrapper : public PopupMenuCustomComponent
  56781. {
  56782. public:
  56783. NormalComponentWrapper (Component* const comp,
  56784. const int w, const int h,
  56785. const bool triggerMenuItemAutomaticallyWhenClicked)
  56786. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  56787. width (w),
  56788. height (h)
  56789. {
  56790. addAndMakeVisible (comp);
  56791. }
  56792. ~NormalComponentWrapper() {}
  56793. void getIdealSize (int& idealWidth, int& idealHeight)
  56794. {
  56795. idealWidth = width;
  56796. idealHeight = height;
  56797. }
  56798. void resized()
  56799. {
  56800. if (getChildComponent(0) != 0)
  56801. getChildComponent(0)->setBounds (getLocalBounds());
  56802. }
  56803. juce_UseDebuggingNewOperator
  56804. private:
  56805. const int width, height;
  56806. NormalComponentWrapper (const NormalComponentWrapper&);
  56807. NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  56808. };
  56809. void PopupMenu::addCustomItem (const int itemResultId,
  56810. Component* customComponent,
  56811. int idealWidth, int idealHeight,
  56812. const bool triggerMenuItemAutomaticallyWhenClicked)
  56813. {
  56814. addCustomItem (itemResultId,
  56815. new NormalComponentWrapper (customComponent,
  56816. idealWidth, idealHeight,
  56817. triggerMenuItemAutomaticallyWhenClicked));
  56818. }
  56819. void PopupMenu::addSubMenu (const String& subMenuName,
  56820. const PopupMenu& subMenu,
  56821. const bool isActive,
  56822. const Image& iconToUse,
  56823. const bool isTicked)
  56824. {
  56825. addSeparatorIfPending();
  56826. items.add (new Item (0, subMenuName, isActive && (subMenu.getNumItems() > 0), isTicked,
  56827. iconToUse, Colours::black, false, 0, &subMenu, 0));
  56828. }
  56829. void PopupMenu::addSeparator()
  56830. {
  56831. separatorPending = true;
  56832. }
  56833. class HeaderItemComponent : public PopupMenuCustomComponent
  56834. {
  56835. public:
  56836. HeaderItemComponent (const String& name)
  56837. : PopupMenuCustomComponent (false)
  56838. {
  56839. setName (name);
  56840. }
  56841. ~HeaderItemComponent()
  56842. {
  56843. }
  56844. void paint (Graphics& g)
  56845. {
  56846. Font f (getLookAndFeel().getPopupMenuFont());
  56847. f.setBold (true);
  56848. g.setFont (f);
  56849. g.setColour (findColour (PopupMenu::headerTextColourId));
  56850. g.drawFittedText (getName(),
  56851. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  56852. Justification::bottomLeft, 1);
  56853. }
  56854. void getIdealSize (int& idealWidth,
  56855. int& idealHeight)
  56856. {
  56857. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  56858. idealHeight += idealHeight / 2;
  56859. idealWidth += idealWidth / 4;
  56860. }
  56861. juce_UseDebuggingNewOperator
  56862. };
  56863. void PopupMenu::addSectionHeader (const String& title)
  56864. {
  56865. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  56866. }
  56867. // This invokes any command manager commands and deletes the menu window when it is dismissed
  56868. class PopupMenuCompletionCallback : public ModalComponentManager::Callback
  56869. {
  56870. public:
  56871. PopupMenuCompletionCallback()
  56872. : managerOfChosenCommand (0)
  56873. {
  56874. }
  56875. ~PopupMenuCompletionCallback() {}
  56876. void modalStateFinished (int result)
  56877. {
  56878. if (managerOfChosenCommand != 0 && result != 0)
  56879. {
  56880. ApplicationCommandTarget::InvocationInfo info (result);
  56881. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  56882. managerOfChosenCommand->invoke (info, true);
  56883. }
  56884. // (this would be the place to fade out the component, if that's what's required)
  56885. component = 0;
  56886. }
  56887. ApplicationCommandManager* managerOfChosenCommand;
  56888. ScopedPointer<Component> component;
  56889. private:
  56890. PopupMenuCompletionCallback (const PopupMenuCompletionCallback&);
  56891. PopupMenuCompletionCallback& operator= (const PopupMenuCompletionCallback&);
  56892. };
  56893. int PopupMenu::showMenu (const Rectangle<int>& target,
  56894. const int itemIdThatMustBeVisible,
  56895. const int minimumWidth,
  56896. const int maximumNumColumns,
  56897. const int standardItemHeight,
  56898. const bool alignToRectangle,
  56899. Component* const componentAttachedTo,
  56900. ModalComponentManager::Callback* userCallback)
  56901. {
  56902. ScopedPointer<ModalComponentManager::Callback> userCallbackDeleter (userCallback);
  56903. Component::SafePointer<Component> prevFocused (Component::getCurrentlyFocusedComponent());
  56904. Component::SafePointer<Component> prevTopLevel ((prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0);
  56905. Window::wasHiddenBecauseOfAppChange() = false;
  56906. PopupMenuCompletionCallback* callback = new PopupMenuCompletionCallback();
  56907. ScopedPointer<PopupMenuCompletionCallback> callbackDeleter (callback);
  56908. callback->component = Window::create (*this, ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  56909. 0, target, minimumWidth, maximumNumColumns > 0 ? maximumNumColumns : 7,
  56910. standardItemHeight, alignToRectangle, itemIdThatMustBeVisible,
  56911. &callback->managerOfChosenCommand, componentAttachedTo);
  56912. if (callback->component == 0)
  56913. return 0;
  56914. callback->component->enterModalState (false, userCallbackDeleter.release());
  56915. callback->component->toFront (false); // need to do this after making it modal, or it could
  56916. // be stuck behind other comps that are already modal..
  56917. ModalComponentManager::getInstance()->attachCallback (callback->component, callback);
  56918. callbackDeleter.release();
  56919. if (userCallback != 0)
  56920. return 0;
  56921. const int result = callback->component->runModalLoop();
  56922. if (! Window::wasHiddenBecauseOfAppChange())
  56923. {
  56924. if (prevTopLevel != 0)
  56925. prevTopLevel->toFront (true);
  56926. if (prevFocused != 0)
  56927. prevFocused->grabKeyboardFocus();
  56928. }
  56929. return result;
  56930. }
  56931. int PopupMenu::show (const int itemIdThatMustBeVisible,
  56932. const int minimumWidth,
  56933. const int maximumNumColumns,
  56934. const int standardItemHeight,
  56935. ModalComponentManager::Callback* callback)
  56936. {
  56937. const Point<int> mousePos (Desktop::getMousePosition());
  56938. return showAt (mousePos.getX(), mousePos.getY(),
  56939. itemIdThatMustBeVisible,
  56940. minimumWidth,
  56941. maximumNumColumns,
  56942. standardItemHeight,
  56943. callback);
  56944. }
  56945. int PopupMenu::showAt (const int screenX,
  56946. const int screenY,
  56947. const int itemIdThatMustBeVisible,
  56948. const int minimumWidth,
  56949. const int maximumNumColumns,
  56950. const int standardItemHeight,
  56951. ModalComponentManager::Callback* callback)
  56952. {
  56953. return showMenu (Rectangle<int> (screenX, screenY, 1, 1),
  56954. itemIdThatMustBeVisible,
  56955. minimumWidth, maximumNumColumns,
  56956. standardItemHeight,
  56957. false, 0, callback);
  56958. }
  56959. int PopupMenu::showAt (Component* componentToAttachTo,
  56960. const int itemIdThatMustBeVisible,
  56961. const int minimumWidth,
  56962. const int maximumNumColumns,
  56963. const int standardItemHeight,
  56964. ModalComponentManager::Callback* callback)
  56965. {
  56966. if (componentToAttachTo != 0)
  56967. {
  56968. return showMenu (componentToAttachTo->getScreenBounds(),
  56969. itemIdThatMustBeVisible,
  56970. minimumWidth,
  56971. maximumNumColumns,
  56972. standardItemHeight,
  56973. true, componentToAttachTo, callback);
  56974. }
  56975. else
  56976. {
  56977. return show (itemIdThatMustBeVisible,
  56978. minimumWidth,
  56979. maximumNumColumns,
  56980. standardItemHeight,
  56981. callback);
  56982. }
  56983. }
  56984. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus()
  56985. {
  56986. for (int i = Window::getActiveWindows().size(); --i >= 0;)
  56987. {
  56988. Window* const pmw = Window::getActiveWindows()[i];
  56989. if (pmw != 0)
  56990. pmw->dismissMenu (0);
  56991. }
  56992. }
  56993. int PopupMenu::getNumItems() const throw()
  56994. {
  56995. int num = 0;
  56996. for (int i = items.size(); --i >= 0;)
  56997. if (! (items.getUnchecked(i))->isSeparator)
  56998. ++num;
  56999. return num;
  57000. }
  57001. bool PopupMenu::containsCommandItem (const int commandID) const
  57002. {
  57003. for (int i = items.size(); --i >= 0;)
  57004. {
  57005. const Item* mi = items.getUnchecked (i);
  57006. if ((mi->itemId == commandID && mi->commandManager != 0)
  57007. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  57008. {
  57009. return true;
  57010. }
  57011. }
  57012. return false;
  57013. }
  57014. bool PopupMenu::containsAnyActiveItems() const throw()
  57015. {
  57016. for (int i = items.size(); --i >= 0;)
  57017. {
  57018. const Item* const mi = items.getUnchecked (i);
  57019. if (mi->subMenu != 0)
  57020. {
  57021. if (mi->subMenu->containsAnyActiveItems())
  57022. return true;
  57023. }
  57024. else if (mi->active)
  57025. {
  57026. return true;
  57027. }
  57028. }
  57029. return false;
  57030. }
  57031. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  57032. {
  57033. lookAndFeel = newLookAndFeel;
  57034. }
  57035. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  57036. : isHighlighted (false),
  57037. isTriggeredAutomatically (isTriggeredAutomatically_)
  57038. {
  57039. }
  57040. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  57041. {
  57042. }
  57043. void PopupMenuCustomComponent::triggerMenuItem()
  57044. {
  57045. PopupMenu::ItemComponent* const mic = dynamic_cast <PopupMenu::ItemComponent*> (getParentComponent());
  57046. if (mic != 0)
  57047. {
  57048. PopupMenu::Window* const pmw = dynamic_cast <PopupMenu::Window*> (mic->getParentComponent());
  57049. if (pmw != 0)
  57050. {
  57051. pmw->dismissMenu (&mic->itemInfo);
  57052. }
  57053. else
  57054. {
  57055. // something must have gone wrong with the component hierarchy if this happens..
  57056. jassertfalse;
  57057. }
  57058. }
  57059. else
  57060. {
  57061. // why isn't this component inside a menu? Not much point triggering the item if
  57062. // there's no menu.
  57063. jassertfalse;
  57064. }
  57065. }
  57066. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_)
  57067. : subMenu (0),
  57068. itemId (0),
  57069. isSeparator (false),
  57070. isTicked (false),
  57071. isEnabled (false),
  57072. isCustomComponent (false),
  57073. isSectionHeader (false),
  57074. customColour (0),
  57075. customImage (0),
  57076. menu (menu_),
  57077. index (0)
  57078. {
  57079. }
  57080. PopupMenu::MenuItemIterator::~MenuItemIterator()
  57081. {
  57082. }
  57083. bool PopupMenu::MenuItemIterator::next()
  57084. {
  57085. if (index >= menu.items.size())
  57086. return false;
  57087. const Item* const item = menu.items.getUnchecked (index);
  57088. ++index;
  57089. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  57090. subMenu = item->subMenu;
  57091. itemId = item->itemId;
  57092. isSeparator = item->isSeparator;
  57093. isTicked = item->isTicked;
  57094. isEnabled = item->active;
  57095. isSectionHeader = dynamic_cast <HeaderItemComponent*> ((PopupMenuCustomComponent*) item->customComp) != 0;
  57096. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  57097. customColour = item->usesColour ? &(item->textColour) : 0;
  57098. customImage = item->image;
  57099. commandManager = item->commandManager;
  57100. return true;
  57101. }
  57102. END_JUCE_NAMESPACE
  57103. /*** End of inlined file: juce_PopupMenu.cpp ***/
  57104. /*** Start of inlined file: juce_ComponentDragger.cpp ***/
  57105. BEGIN_JUCE_NAMESPACE
  57106. ComponentDragger::ComponentDragger()
  57107. : constrainer (0)
  57108. {
  57109. }
  57110. ComponentDragger::~ComponentDragger()
  57111. {
  57112. }
  57113. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  57114. ComponentBoundsConstrainer* const constrainer_)
  57115. {
  57116. jassert (componentToDrag->isValidComponent());
  57117. if (componentToDrag != 0)
  57118. {
  57119. constrainer = constrainer_;
  57120. originalPos = componentToDrag->relativePositionToGlobal (Point<int>());
  57121. }
  57122. }
  57123. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  57124. {
  57125. jassert (componentToDrag->isValidComponent());
  57126. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  57127. if (componentToDrag != 0)
  57128. {
  57129. Rectangle<int> bounds (componentToDrag->getBounds().withPosition (originalPos));
  57130. const Component* const parentComp = componentToDrag->getParentComponent();
  57131. if (parentComp != 0)
  57132. bounds.setPosition (parentComp->globalPositionToRelative (originalPos));
  57133. bounds.setPosition (bounds.getPosition() + e.getOffsetFromDragStart());
  57134. if (constrainer != 0)
  57135. constrainer->setBoundsForComponent (componentToDrag, bounds, false, false, false, false);
  57136. else
  57137. componentToDrag->setBounds (bounds);
  57138. }
  57139. }
  57140. END_JUCE_NAMESPACE
  57141. /*** End of inlined file: juce_ComponentDragger.cpp ***/
  57142. /*** Start of inlined file: juce_DragAndDropContainer.cpp ***/
  57143. BEGIN_JUCE_NAMESPACE
  57144. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  57145. bool juce_performDragDropText (const String& text, bool& shouldStop);
  57146. class DragImageComponent : public Component,
  57147. public Timer
  57148. {
  57149. public:
  57150. DragImageComponent (const Image& im,
  57151. const String& desc,
  57152. Component* const sourceComponent,
  57153. Component* const mouseDragSource_,
  57154. DragAndDropContainer* const o,
  57155. const Point<int>& imageOffset_)
  57156. : image (im),
  57157. source (sourceComponent),
  57158. mouseDragSource (mouseDragSource_),
  57159. owner (o),
  57160. dragDesc (desc),
  57161. imageOffset (imageOffset_),
  57162. hasCheckedForExternalDrag (false),
  57163. drawImage (true)
  57164. {
  57165. setSize (im.getWidth(), im.getHeight());
  57166. if (mouseDragSource == 0)
  57167. mouseDragSource = source;
  57168. mouseDragSource->addMouseListener (this, false);
  57169. startTimer (200);
  57170. setInterceptsMouseClicks (false, false);
  57171. setAlwaysOnTop (true);
  57172. }
  57173. ~DragImageComponent()
  57174. {
  57175. if (owner->dragImageComponent == this)
  57176. owner->dragImageComponent.release();
  57177. if (mouseDragSource != 0)
  57178. {
  57179. mouseDragSource->removeMouseListener (this);
  57180. if (getCurrentlyOver() != 0 && getCurrentlyOver()->isInterestedInDragSource (dragDesc, source))
  57181. getCurrentlyOver()->itemDragExit (dragDesc, source);
  57182. }
  57183. }
  57184. void paint (Graphics& g)
  57185. {
  57186. if (isOpaque())
  57187. g.fillAll (Colours::white);
  57188. if (drawImage)
  57189. {
  57190. g.setOpacity (1.0f);
  57191. g.drawImageAt (image, 0, 0);
  57192. }
  57193. }
  57194. DragAndDropTarget* findTarget (const Point<int>& screenPos, Point<int>& relativePos)
  57195. {
  57196. Component* hit = getParentComponent();
  57197. if (hit == 0)
  57198. {
  57199. hit = Desktop::getInstance().findComponentAt (screenPos);
  57200. }
  57201. else
  57202. {
  57203. const Point<int> relPos (hit->globalPositionToRelative (screenPos));
  57204. hit = hit->getComponentAt (relPos.getX(), relPos.getY());
  57205. }
  57206. // (note: use a local copy of the dragDesc member in case the callback runs
  57207. // a modal loop and deletes this object before the method completes)
  57208. const String dragDescLocal (dragDesc);
  57209. while (hit != 0)
  57210. {
  57211. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  57212. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57213. {
  57214. relativePos = hit->globalPositionToRelative (screenPos);
  57215. return ddt;
  57216. }
  57217. hit = hit->getParentComponent();
  57218. }
  57219. return 0;
  57220. }
  57221. void mouseUp (const MouseEvent& e)
  57222. {
  57223. if (e.originalComponent != this)
  57224. {
  57225. if (mouseDragSource != 0)
  57226. mouseDragSource->removeMouseListener (this);
  57227. bool dropAccepted = false;
  57228. DragAndDropTarget* ddt = 0;
  57229. Point<int> relPos;
  57230. if (isVisible())
  57231. {
  57232. setVisible (false);
  57233. ddt = findTarget (e.getScreenPosition(), relPos);
  57234. // fade this component and remove it - it'll be deleted later by the timer callback
  57235. dropAccepted = ddt != 0;
  57236. setVisible (true);
  57237. if (dropAccepted || source == 0)
  57238. {
  57239. Desktop::getInstance().getAnimator().fadeOut (this, 120);
  57240. }
  57241. else
  57242. {
  57243. const Point<int> target (source->relativePositionToGlobal (source->getLocalBounds().getCentre()));
  57244. const Point<int> ourCentre (relativePositionToGlobal (getLocalBounds().getCentre()));
  57245. Desktop::getInstance().getAnimator().animateComponent (this,
  57246. getBounds() + (target - ourCentre),
  57247. 0.0f, 120,
  57248. true, 1.0, 1.0);
  57249. }
  57250. }
  57251. if (getParentComponent() != 0)
  57252. getParentComponent()->removeChildComponent (this);
  57253. if (dropAccepted && ddt != 0)
  57254. {
  57255. // (note: use a local copy of the dragDesc member in case the callback runs
  57256. // a modal loop and deletes this object before the method completes)
  57257. const String dragDescLocal (dragDesc);
  57258. currentlyOverComp = 0;
  57259. ddt->itemDropped (dragDescLocal, source, relPos.getX(), relPos.getY());
  57260. }
  57261. // careful - this object could now be deleted..
  57262. }
  57263. }
  57264. void updateLocation (const bool canDoExternalDrag, const Point<int>& screenPos)
  57265. {
  57266. // (note: use a local copy of the dragDesc member in case the callback runs
  57267. // a modal loop and deletes this object before it returns)
  57268. const String dragDescLocal (dragDesc);
  57269. Point<int> newPos (screenPos + imageOffset);
  57270. if (getParentComponent() != 0)
  57271. newPos = getParentComponent()->globalPositionToRelative (newPos);
  57272. //if (newX != getX() || newY != getY())
  57273. {
  57274. setTopLeftPosition (newPos.getX(), newPos.getY());
  57275. Point<int> relPos;
  57276. DragAndDropTarget* const ddt = findTarget (screenPos, relPos);
  57277. Component* ddtComp = dynamic_cast <Component*> (ddt);
  57278. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  57279. if (ddtComp != currentlyOverComp)
  57280. {
  57281. if (currentlyOverComp != 0 && source != 0
  57282. && getCurrentlyOver()->isInterestedInDragSource (dragDescLocal, source))
  57283. {
  57284. getCurrentlyOver()->itemDragExit (dragDescLocal, source);
  57285. }
  57286. currentlyOverComp = ddtComp;
  57287. if (ddt != 0 && ddt->isInterestedInDragSource (dragDescLocal, source))
  57288. ddt->itemDragEnter (dragDescLocal, source, relPos.getX(), relPos.getY());
  57289. }
  57290. DragAndDropTarget* target = getCurrentlyOver();
  57291. if (target != 0 && target->isInterestedInDragSource (dragDescLocal, source))
  57292. target->itemDragMove (dragDescLocal, source, relPos.getX(), relPos.getY());
  57293. if (getCurrentlyOver() == 0 && canDoExternalDrag && ! hasCheckedForExternalDrag)
  57294. {
  57295. if (Desktop::getInstance().findComponentAt (screenPos) == 0)
  57296. {
  57297. hasCheckedForExternalDrag = true;
  57298. StringArray files;
  57299. bool canMoveFiles = false;
  57300. if (owner->shouldDropFilesWhenDraggedExternally (dragDescLocal, source, files, canMoveFiles)
  57301. && files.size() > 0)
  57302. {
  57303. Component::SafePointer<Component> cdw (this);
  57304. setVisible (false);
  57305. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  57306. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  57307. if (cdw != 0)
  57308. delete this;
  57309. return;
  57310. }
  57311. }
  57312. }
  57313. }
  57314. }
  57315. void mouseDrag (const MouseEvent& e)
  57316. {
  57317. if (e.originalComponent != this)
  57318. updateLocation (true, e.getScreenPosition());
  57319. }
  57320. void timerCallback()
  57321. {
  57322. if (source == 0)
  57323. {
  57324. delete this;
  57325. }
  57326. else if (! isMouseButtonDownAnywhere())
  57327. {
  57328. if (mouseDragSource != 0)
  57329. mouseDragSource->removeMouseListener (this);
  57330. delete this;
  57331. }
  57332. }
  57333. private:
  57334. Image image;
  57335. Component::SafePointer<Component> source;
  57336. Component::SafePointer<Component> mouseDragSource;
  57337. DragAndDropContainer* const owner;
  57338. Component::SafePointer<Component> currentlyOverComp;
  57339. DragAndDropTarget* getCurrentlyOver()
  57340. {
  57341. return dynamic_cast <DragAndDropTarget*> (static_cast <Component*> (currentlyOverComp));
  57342. }
  57343. String dragDesc;
  57344. const Point<int> imageOffset;
  57345. bool hasCheckedForExternalDrag, drawImage;
  57346. DragImageComponent (const DragImageComponent&);
  57347. DragImageComponent& operator= (const DragImageComponent&);
  57348. };
  57349. DragAndDropContainer::DragAndDropContainer()
  57350. {
  57351. }
  57352. DragAndDropContainer::~DragAndDropContainer()
  57353. {
  57354. dragImageComponent = 0;
  57355. }
  57356. void DragAndDropContainer::startDragging (const String& sourceDescription,
  57357. Component* sourceComponent,
  57358. const Image& dragImage_,
  57359. const bool allowDraggingToExternalWindows,
  57360. const Point<int>* imageOffsetFromMouse)
  57361. {
  57362. Image dragImage (dragImage_);
  57363. if (dragImageComponent == 0)
  57364. {
  57365. Component* const thisComp = dynamic_cast <Component*> (this);
  57366. if (thisComp == 0)
  57367. {
  57368. jassertfalse; // Your DragAndDropContainer needs to be a Component!
  57369. return;
  57370. }
  57371. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource (0);
  57372. if (draggingSource == 0 || ! draggingSource->isDragging())
  57373. {
  57374. jassertfalse; // You must call startDragging() from within a mouseDown or mouseDrag callback!
  57375. return;
  57376. }
  57377. const Point<int> lastMouseDown (Desktop::getLastMouseDownPosition());
  57378. Point<int> imageOffset;
  57379. if (dragImage.isNull())
  57380. {
  57381. dragImage = sourceComponent->createComponentSnapshot (sourceComponent->getLocalBounds())
  57382. .convertedToFormat (Image::ARGB);
  57383. dragImage.multiplyAllAlphas (0.6f);
  57384. const int lo = 150;
  57385. const int hi = 400;
  57386. Point<int> relPos (sourceComponent->globalPositionToRelative (lastMouseDown));
  57387. Point<int> clipped (dragImage.getBounds().getConstrainedPoint (relPos));
  57388. for (int y = dragImage.getHeight(); --y >= 0;)
  57389. {
  57390. const double dy = (y - clipped.getY()) * (y - clipped.getY());
  57391. for (int x = dragImage.getWidth(); --x >= 0;)
  57392. {
  57393. const int dx = x - clipped.getX();
  57394. const int distance = roundToInt (std::sqrt (dx * dx + dy));
  57395. if (distance > lo)
  57396. {
  57397. const float alpha = (distance > hi) ? 0
  57398. : (hi - distance) / (float) (hi - lo)
  57399. + Random::getSystemRandom().nextFloat() * 0.008f;
  57400. dragImage.multiplyAlphaAt (x, y, alpha);
  57401. }
  57402. }
  57403. }
  57404. imageOffset = -clipped;
  57405. }
  57406. else
  57407. {
  57408. if (imageOffsetFromMouse == 0)
  57409. imageOffset = -dragImage.getBounds().getCentre();
  57410. else
  57411. imageOffset = -(dragImage.getBounds().getConstrainedPoint (-*imageOffsetFromMouse));
  57412. }
  57413. dragImageComponent = new DragImageComponent (dragImage, sourceDescription, sourceComponent,
  57414. draggingSource->getComponentUnderMouse(), this, imageOffset);
  57415. currentDragDesc = sourceDescription;
  57416. if (allowDraggingToExternalWindows)
  57417. {
  57418. if (! Desktop::canUseSemiTransparentWindows())
  57419. dragImageComponent->setOpaque (true);
  57420. dragImageComponent->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  57421. | ComponentPeer::windowIsTemporary
  57422. | ComponentPeer::windowIgnoresKeyPresses);
  57423. }
  57424. else
  57425. thisComp->addChildComponent (dragImageComponent);
  57426. static_cast <DragImageComponent*> (static_cast <Component*> (dragImageComponent))->updateLocation (false, lastMouseDown);
  57427. dragImageComponent->setVisible (true);
  57428. }
  57429. }
  57430. bool DragAndDropContainer::isDragAndDropActive() const
  57431. {
  57432. return dragImageComponent != 0;
  57433. }
  57434. const String DragAndDropContainer::getCurrentDragDescription() const
  57435. {
  57436. return (dragImageComponent != 0) ? currentDragDesc
  57437. : String::empty;
  57438. }
  57439. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  57440. {
  57441. return c == 0 ? 0 : c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  57442. }
  57443. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  57444. {
  57445. return false;
  57446. }
  57447. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  57448. {
  57449. }
  57450. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  57451. {
  57452. }
  57453. void DragAndDropTarget::itemDragExit (const String&, Component*)
  57454. {
  57455. }
  57456. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  57457. {
  57458. return true;
  57459. }
  57460. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  57461. {
  57462. }
  57463. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  57464. {
  57465. }
  57466. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  57467. {
  57468. }
  57469. END_JUCE_NAMESPACE
  57470. /*** End of inlined file: juce_DragAndDropContainer.cpp ***/
  57471. /*** Start of inlined file: juce_MouseCursor.cpp ***/
  57472. BEGIN_JUCE_NAMESPACE
  57473. class MouseCursor::SharedCursorHandle
  57474. {
  57475. public:
  57476. explicit SharedCursorHandle (const MouseCursor::StandardCursorType type)
  57477. : handle (createStandardMouseCursor (type)),
  57478. refCount (1),
  57479. standardType (type),
  57480. isStandard (true)
  57481. {
  57482. }
  57483. SharedCursorHandle (const Image& image, const int hotSpotX, const int hotSpotY)
  57484. : handle (createMouseCursorFromImage (image, hotSpotX, hotSpotY)),
  57485. refCount (1),
  57486. standardType (MouseCursor::NormalCursor),
  57487. isStandard (false)
  57488. {
  57489. }
  57490. static SharedCursorHandle* createStandard (const MouseCursor::StandardCursorType type)
  57491. {
  57492. const ScopedLock sl (getLock());
  57493. for (int i = 0; i < getCursors().size(); ++i)
  57494. {
  57495. SharedCursorHandle* const sc = getCursors().getUnchecked(i);
  57496. if (sc->standardType == type)
  57497. return sc->retain();
  57498. }
  57499. SharedCursorHandle* const sc = new SharedCursorHandle (type);
  57500. getCursors().add (sc);
  57501. return sc;
  57502. }
  57503. SharedCursorHandle* retain() throw()
  57504. {
  57505. ++refCount;
  57506. return this;
  57507. }
  57508. void release()
  57509. {
  57510. if (--refCount == 0)
  57511. {
  57512. if (isStandard)
  57513. {
  57514. const ScopedLock sl (getLock());
  57515. getCursors().removeValue (this);
  57516. }
  57517. delete this;
  57518. }
  57519. }
  57520. void* getHandle() const throw() { return handle; }
  57521. juce_UseDebuggingNewOperator
  57522. private:
  57523. void* const handle;
  57524. Atomic <int> refCount;
  57525. const MouseCursor::StandardCursorType standardType;
  57526. const bool isStandard;
  57527. static CriticalSection& getLock()
  57528. {
  57529. static CriticalSection lock;
  57530. return lock;
  57531. }
  57532. static Array <SharedCursorHandle*>& getCursors()
  57533. {
  57534. static Array <SharedCursorHandle*> cursors;
  57535. return cursors;
  57536. }
  57537. ~SharedCursorHandle()
  57538. {
  57539. deleteMouseCursor (handle, isStandard);
  57540. }
  57541. SharedCursorHandle& operator= (const SharedCursorHandle&);
  57542. };
  57543. MouseCursor::MouseCursor()
  57544. : cursorHandle (SharedCursorHandle::createStandard (NormalCursor))
  57545. {
  57546. jassert (cursorHandle != 0);
  57547. }
  57548. MouseCursor::MouseCursor (const StandardCursorType type)
  57549. : cursorHandle (SharedCursorHandle::createStandard (type))
  57550. {
  57551. jassert (cursorHandle != 0);
  57552. }
  57553. MouseCursor::MouseCursor (const Image& image, const int hotSpotX, const int hotSpotY)
  57554. : cursorHandle (new SharedCursorHandle (image, hotSpotX, hotSpotY))
  57555. {
  57556. }
  57557. MouseCursor::MouseCursor (const MouseCursor& other)
  57558. : cursorHandle (other.cursorHandle->retain())
  57559. {
  57560. }
  57561. MouseCursor::~MouseCursor()
  57562. {
  57563. cursorHandle->release();
  57564. }
  57565. MouseCursor& MouseCursor::operator= (const MouseCursor& other)
  57566. {
  57567. other.cursorHandle->retain();
  57568. cursorHandle->release();
  57569. cursorHandle = other.cursorHandle;
  57570. return *this;
  57571. }
  57572. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  57573. {
  57574. return getHandle() == other.getHandle();
  57575. }
  57576. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  57577. {
  57578. return getHandle() != other.getHandle();
  57579. }
  57580. void* MouseCursor::getHandle() const throw()
  57581. {
  57582. return cursorHandle->getHandle();
  57583. }
  57584. void MouseCursor::showWaitCursor()
  57585. {
  57586. Desktop::getInstance().getMainMouseSource().showMouseCursor (MouseCursor::WaitCursor);
  57587. }
  57588. void MouseCursor::hideWaitCursor()
  57589. {
  57590. Desktop::getInstance().getMainMouseSource().revealCursor();
  57591. }
  57592. END_JUCE_NAMESPACE
  57593. /*** End of inlined file: juce_MouseCursor.cpp ***/
  57594. /*** Start of inlined file: juce_MouseEvent.cpp ***/
  57595. BEGIN_JUCE_NAMESPACE
  57596. MouseEvent::MouseEvent (MouseInputSource& source_,
  57597. const Point<int>& position,
  57598. const ModifierKeys& mods_,
  57599. Component* const eventComponent_,
  57600. Component* const originator,
  57601. const Time& eventTime_,
  57602. const Point<int> mouseDownPos_,
  57603. const Time& mouseDownTime_,
  57604. const int numberOfClicks_,
  57605. const bool mouseWasDragged) throw()
  57606. : x (position.getX()),
  57607. y (position.getY()),
  57608. mods (mods_),
  57609. eventComponent (eventComponent_),
  57610. originalComponent (originator),
  57611. eventTime (eventTime_),
  57612. source (source_),
  57613. mouseDownPos (mouseDownPos_),
  57614. mouseDownTime (mouseDownTime_),
  57615. numberOfClicks (numberOfClicks_),
  57616. wasMovedSinceMouseDown (mouseWasDragged)
  57617. {
  57618. }
  57619. MouseEvent::~MouseEvent() throw()
  57620. {
  57621. }
  57622. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  57623. {
  57624. if (otherComponent == 0)
  57625. {
  57626. jassertfalse;
  57627. return *this;
  57628. }
  57629. return MouseEvent (source, eventComponent->relativePositionToOtherComponent (otherComponent, getPosition()),
  57630. mods, otherComponent, originalComponent, eventTime,
  57631. eventComponent->relativePositionToOtherComponent (otherComponent, mouseDownPos),
  57632. mouseDownTime, numberOfClicks, wasMovedSinceMouseDown);
  57633. }
  57634. const MouseEvent MouseEvent::withNewPosition (const Point<int>& newPosition) const throw()
  57635. {
  57636. return MouseEvent (source, newPosition, mods, eventComponent, originalComponent,
  57637. eventTime, mouseDownPos, mouseDownTime,
  57638. numberOfClicks, wasMovedSinceMouseDown);
  57639. }
  57640. bool MouseEvent::mouseWasClicked() const throw()
  57641. {
  57642. return ! wasMovedSinceMouseDown;
  57643. }
  57644. int MouseEvent::getMouseDownX() const throw()
  57645. {
  57646. return mouseDownPos.getX();
  57647. }
  57648. int MouseEvent::getMouseDownY() const throw()
  57649. {
  57650. return mouseDownPos.getY();
  57651. }
  57652. const Point<int> MouseEvent::getMouseDownPosition() const throw()
  57653. {
  57654. return mouseDownPos;
  57655. }
  57656. int MouseEvent::getDistanceFromDragStartX() const throw()
  57657. {
  57658. return x - mouseDownPos.getX();
  57659. }
  57660. int MouseEvent::getDistanceFromDragStartY() const throw()
  57661. {
  57662. return y - mouseDownPos.getY();
  57663. }
  57664. int MouseEvent::getDistanceFromDragStart() const throw()
  57665. {
  57666. return mouseDownPos.getDistanceFrom (getPosition());
  57667. }
  57668. const Point<int> MouseEvent::getOffsetFromDragStart() const throw()
  57669. {
  57670. return getPosition() - mouseDownPos;
  57671. }
  57672. int MouseEvent::getLengthOfMousePress() const throw()
  57673. {
  57674. if (mouseDownTime.toMilliseconds() > 0)
  57675. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  57676. return 0;
  57677. }
  57678. const Point<int> MouseEvent::getPosition() const throw()
  57679. {
  57680. return Point<int> (x, y);
  57681. }
  57682. int MouseEvent::getScreenX() const
  57683. {
  57684. return getScreenPosition().getX();
  57685. }
  57686. int MouseEvent::getScreenY() const
  57687. {
  57688. return getScreenPosition().getY();
  57689. }
  57690. const Point<int> MouseEvent::getScreenPosition() const
  57691. {
  57692. return eventComponent->relativePositionToGlobal (Point<int> (x, y));
  57693. }
  57694. int MouseEvent::getMouseDownScreenX() const
  57695. {
  57696. return getMouseDownScreenPosition().getX();
  57697. }
  57698. int MouseEvent::getMouseDownScreenY() const
  57699. {
  57700. return getMouseDownScreenPosition().getY();
  57701. }
  57702. const Point<int> MouseEvent::getMouseDownScreenPosition() const
  57703. {
  57704. return eventComponent->relativePositionToGlobal (mouseDownPos);
  57705. }
  57706. int MouseEvent::doubleClickTimeOutMs = 400;
  57707. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  57708. {
  57709. doubleClickTimeOutMs = newTime;
  57710. }
  57711. int MouseEvent::getDoubleClickTimeout() throw()
  57712. {
  57713. return doubleClickTimeOutMs;
  57714. }
  57715. END_JUCE_NAMESPACE
  57716. /*** End of inlined file: juce_MouseEvent.cpp ***/
  57717. /*** Start of inlined file: juce_MouseInputSource.cpp ***/
  57718. BEGIN_JUCE_NAMESPACE
  57719. class MouseInputSourceInternal : public AsyncUpdater
  57720. {
  57721. public:
  57722. MouseInputSourceInternal (MouseInputSource& source_, const int index_, const bool isMouseDevice_)
  57723. : index (index_), isMouseDevice (isMouseDevice_), source (source_), lastPeer (0),
  57724. isUnboundedMouseModeOn (false), isCursorVisibleUntilOffscreen (false), currentCursorHandle (0),
  57725. mouseEventCounter (0), lastTime (0)
  57726. {
  57727. zerostruct (mouseDowns);
  57728. }
  57729. ~MouseInputSourceInternal()
  57730. {
  57731. }
  57732. bool isDragging() const throw()
  57733. {
  57734. return buttonState.isAnyMouseButtonDown();
  57735. }
  57736. Component* getComponentUnderMouse() const
  57737. {
  57738. return static_cast <Component*> (componentUnderMouse);
  57739. }
  57740. const ModifierKeys getCurrentModifiers() const
  57741. {
  57742. return ModifierKeys::getCurrentModifiers().withoutMouseButtons().withFlags (buttonState.getRawFlags());
  57743. }
  57744. ComponentPeer* getPeer()
  57745. {
  57746. if (! ComponentPeer::isValidPeer (lastPeer))
  57747. lastPeer = 0;
  57748. return lastPeer;
  57749. }
  57750. Component* findComponentAt (const Point<int>& screenPos)
  57751. {
  57752. ComponentPeer* const peer = getPeer();
  57753. if (peer != 0)
  57754. {
  57755. Component* const comp = peer->getComponent();
  57756. const Point<int> relativePos (comp->globalPositionToRelative (screenPos));
  57757. // (the contains() call is needed to test for overlapping desktop windows)
  57758. if (comp->contains (relativePos.getX(), relativePos.getY()))
  57759. return comp->getComponentAt (relativePos);
  57760. }
  57761. return 0;
  57762. }
  57763. const Point<int> getScreenPosition() const throw()
  57764. {
  57765. return lastScreenPos + unboundedMouseOffset;
  57766. }
  57767. void sendMouseEnter (Component* const comp, const Point<int>& screenPos, const int64 time)
  57768. {
  57769. //DBG ("Mouse " + String (source.getIndex()) + " enter: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57770. comp->internalMouseEnter (source, comp->globalPositionToRelative (screenPos), time);
  57771. }
  57772. void sendMouseExit (Component* const comp, const Point<int>& screenPos, const int64 time)
  57773. {
  57774. //DBG ("Mouse " + String (source.getIndex()) + " exit: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57775. comp->internalMouseExit (source, comp->globalPositionToRelative (screenPos), time);
  57776. }
  57777. void sendMouseMove (Component* const comp, const Point<int>& screenPos, const int64 time)
  57778. {
  57779. //DBG ("Mouse " + String (source.getIndex()) + " move: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57780. comp->internalMouseMove (source, comp->globalPositionToRelative (screenPos), time);
  57781. }
  57782. void sendMouseDown (Component* const comp, const Point<int>& screenPos, const int64 time)
  57783. {
  57784. //DBG ("Mouse " + String (source.getIndex()) + " down: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57785. comp->internalMouseDown (source, comp->globalPositionToRelative (screenPos), time);
  57786. }
  57787. void sendMouseDrag (Component* const comp, const Point<int>& screenPos, const int64 time)
  57788. {
  57789. //DBG ("Mouse " + String (source.getIndex()) + " drag: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57790. comp->internalMouseDrag (source, comp->globalPositionToRelative (screenPos), time);
  57791. }
  57792. void sendMouseUp (Component* const comp, const Point<int>& screenPos, const int64 time)
  57793. {
  57794. //DBG ("Mouse " + String (source.getIndex()) + " up: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57795. comp->internalMouseUp (source, comp->globalPositionToRelative (screenPos), time, getCurrentModifiers());
  57796. }
  57797. void sendMouseWheel (Component* const comp, const Point<int>& screenPos, const int64 time, float x, float y)
  57798. {
  57799. //DBG ("Mouse " + String (source.getIndex()) + " wheel: " + comp->globalPositionToRelative (screenPos).toString() + " - Comp: " + String::toHexString ((int) comp));
  57800. comp->internalMouseWheel (source, comp->globalPositionToRelative (screenPos), time, x, y);
  57801. }
  57802. // (returns true if the button change caused a modal event loop)
  57803. bool setButtons (const Point<int>& screenPos, const int64 time, const ModifierKeys& newButtonState)
  57804. {
  57805. if (buttonState == newButtonState)
  57806. return false;
  57807. setScreenPos (screenPos, time, false);
  57808. // (ignore secondary clicks when there's already a button down)
  57809. if (buttonState.isAnyMouseButtonDown() == newButtonState.isAnyMouseButtonDown())
  57810. {
  57811. buttonState = newButtonState;
  57812. return false;
  57813. }
  57814. const int lastCounter = mouseEventCounter;
  57815. if (buttonState.isAnyMouseButtonDown())
  57816. {
  57817. Component* const current = getComponentUnderMouse();
  57818. if (current != 0)
  57819. sendMouseUp (current, screenPos + unboundedMouseOffset, time);
  57820. enableUnboundedMouseMovement (false, false);
  57821. }
  57822. buttonState = newButtonState;
  57823. if (buttonState.isAnyMouseButtonDown())
  57824. {
  57825. Desktop::getInstance().incrementMouseClickCounter();
  57826. Component* const current = getComponentUnderMouse();
  57827. if (current != 0)
  57828. {
  57829. registerMouseDown (screenPos, time, current, buttonState);
  57830. sendMouseDown (current, screenPos, time);
  57831. }
  57832. }
  57833. return lastCounter != mouseEventCounter;
  57834. }
  57835. void setComponentUnderMouse (Component* const newComponent, const Point<int>& screenPos, const int64 time)
  57836. {
  57837. Component* current = getComponentUnderMouse();
  57838. if (newComponent != current)
  57839. {
  57840. Component::SafePointer<Component> safeNewComp (newComponent);
  57841. const ModifierKeys originalButtonState (buttonState);
  57842. if (current != 0)
  57843. {
  57844. setButtons (screenPos, time, ModifierKeys());
  57845. sendMouseExit (current, screenPos, time);
  57846. buttonState = originalButtonState;
  57847. }
  57848. componentUnderMouse = safeNewComp;
  57849. current = getComponentUnderMouse();
  57850. if (current != 0)
  57851. sendMouseEnter (current, screenPos, time);
  57852. revealCursor (false);
  57853. setButtons (screenPos, time, originalButtonState);
  57854. }
  57855. }
  57856. void setPeer (ComponentPeer* const newPeer, const Point<int>& screenPos, const int64 time)
  57857. {
  57858. ModifierKeys::updateCurrentModifiers();
  57859. if (newPeer != lastPeer)
  57860. {
  57861. setComponentUnderMouse (0, screenPos, time);
  57862. lastPeer = newPeer;
  57863. setComponentUnderMouse (findComponentAt (screenPos), screenPos, time);
  57864. }
  57865. }
  57866. void setScreenPos (const Point<int>& newScreenPos, const int64 time, const bool forceUpdate)
  57867. {
  57868. if (! isDragging())
  57869. setComponentUnderMouse (findComponentAt (newScreenPos), newScreenPos, time);
  57870. if (newScreenPos != lastScreenPos || forceUpdate)
  57871. {
  57872. cancelPendingUpdate();
  57873. lastScreenPos = newScreenPos;
  57874. Component* const current = getComponentUnderMouse();
  57875. if (current != 0)
  57876. {
  57877. if (isDragging())
  57878. {
  57879. registerMouseDrag (newScreenPos);
  57880. sendMouseDrag (current, newScreenPos + unboundedMouseOffset, time);
  57881. if (isUnboundedMouseModeOn)
  57882. handleUnboundedDrag (current);
  57883. }
  57884. else
  57885. {
  57886. sendMouseMove (current, newScreenPos, time);
  57887. }
  57888. }
  57889. revealCursor (false);
  57890. }
  57891. }
  57892. void handleEvent (ComponentPeer* const newPeer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& newMods)
  57893. {
  57894. jassert (newPeer != 0);
  57895. lastTime = time;
  57896. ++mouseEventCounter;
  57897. const Point<int> screenPos (newPeer->relativePositionToGlobal (positionWithinPeer));
  57898. if (isDragging() && newMods.isAnyMouseButtonDown())
  57899. {
  57900. setScreenPos (screenPos, time, false);
  57901. }
  57902. else
  57903. {
  57904. setPeer (newPeer, screenPos, time);
  57905. ComponentPeer* peer = getPeer();
  57906. if (peer != 0)
  57907. {
  57908. if (setButtons (screenPos, time, newMods))
  57909. return; // some modal events have been dispatched, so the current event is now out-of-date
  57910. peer = getPeer();
  57911. if (peer != 0)
  57912. setScreenPos (screenPos, time, false);
  57913. }
  57914. }
  57915. }
  57916. void handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, int64 time, float x, float y)
  57917. {
  57918. jassert (peer != 0);
  57919. lastTime = time;
  57920. ++mouseEventCounter;
  57921. const Point<int> screenPos (peer->relativePositionToGlobal (positionWithinPeer));
  57922. setPeer (peer, screenPos, time);
  57923. setScreenPos (screenPos, time, false);
  57924. triggerFakeMove();
  57925. if (! isDragging())
  57926. {
  57927. Component* current = getComponentUnderMouse();
  57928. if (current != 0)
  57929. sendMouseWheel (current, screenPos, time, x, y);
  57930. }
  57931. }
  57932. const Time getLastMouseDownTime() const throw()
  57933. {
  57934. return Time (mouseDowns[0].time);
  57935. }
  57936. const Point<int> getLastMouseDownPosition() const throw()
  57937. {
  57938. return mouseDowns[0].position;
  57939. }
  57940. int getNumberOfMultipleClicks() const throw()
  57941. {
  57942. int numClicks = 0;
  57943. if (mouseDowns[0].time != 0)
  57944. {
  57945. if (! mouseMovedSignificantlySincePressed)
  57946. ++numClicks;
  57947. for (int i = 1; i < numElementsInArray (mouseDowns); ++i)
  57948. {
  57949. if (mouseDowns[0].canBePartOfMultipleClickWith (mouseDowns[1], (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))))
  57950. ++numClicks;
  57951. else
  57952. break;
  57953. }
  57954. }
  57955. return numClicks;
  57956. }
  57957. bool hasMouseMovedSignificantlySincePressed() const throw()
  57958. {
  57959. return mouseMovedSignificantlySincePressed
  57960. || lastTime > mouseDowns[0].time + 300;
  57961. }
  57962. void triggerFakeMove()
  57963. {
  57964. triggerAsyncUpdate();
  57965. }
  57966. void handleAsyncUpdate()
  57967. {
  57968. setScreenPos (lastScreenPos, jmax (lastTime, Time::currentTimeMillis()), true);
  57969. }
  57970. void enableUnboundedMouseMovement (bool enable, bool keepCursorVisibleUntilOffscreen)
  57971. {
  57972. enable = enable && isDragging();
  57973. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  57974. if (enable != isUnboundedMouseModeOn)
  57975. {
  57976. if ((! enable) && ((! isCursorVisibleUntilOffscreen) || ! unboundedMouseOffset.isOrigin()))
  57977. {
  57978. // when released, return the mouse to within the component's bounds
  57979. Component* current = getComponentUnderMouse();
  57980. if (current != 0)
  57981. Desktop::setMousePosition (current->getScreenBounds()
  57982. .getConstrainedPoint (lastScreenPos));
  57983. }
  57984. isUnboundedMouseModeOn = enable;
  57985. unboundedMouseOffset = Point<int>();
  57986. revealCursor (true);
  57987. }
  57988. }
  57989. void handleUnboundedDrag (Component* current)
  57990. {
  57991. const Rectangle<int> screenArea (current->getParentMonitorArea().expanded (-2, -2));
  57992. if (! screenArea.contains (lastScreenPos))
  57993. {
  57994. const Point<int> componentCentre (current->getScreenBounds().getCentre());
  57995. unboundedMouseOffset += (lastScreenPos - componentCentre);
  57996. Desktop::setMousePosition (componentCentre);
  57997. }
  57998. else if (isCursorVisibleUntilOffscreen
  57999. && (! unboundedMouseOffset.isOrigin())
  58000. && screenArea.contains (lastScreenPos + unboundedMouseOffset))
  58001. {
  58002. Desktop::setMousePosition (lastScreenPos + unboundedMouseOffset);
  58003. unboundedMouseOffset = Point<int>();
  58004. }
  58005. }
  58006. void showMouseCursor (MouseCursor cursor, bool forcedUpdate)
  58007. {
  58008. if (isUnboundedMouseModeOn && ((! unboundedMouseOffset.isOrigin()) || ! isCursorVisibleUntilOffscreen))
  58009. {
  58010. cursor = MouseCursor::NoCursor;
  58011. forcedUpdate = true;
  58012. }
  58013. if (forcedUpdate || cursor.getHandle() != currentCursorHandle)
  58014. {
  58015. currentCursorHandle = cursor.getHandle();
  58016. cursor.showInWindow (getPeer());
  58017. }
  58018. }
  58019. void hideCursor()
  58020. {
  58021. showMouseCursor (MouseCursor::NoCursor, true);
  58022. }
  58023. void revealCursor (bool forcedUpdate)
  58024. {
  58025. MouseCursor mc (MouseCursor::NormalCursor);
  58026. Component* current = getComponentUnderMouse();
  58027. if (current != 0)
  58028. mc = current->getLookAndFeel().getMouseCursorFor (*current);
  58029. showMouseCursor (mc, forcedUpdate);
  58030. }
  58031. int index;
  58032. bool isMouseDevice;
  58033. Point<int> lastScreenPos;
  58034. ModifierKeys buttonState;
  58035. private:
  58036. MouseInputSource& source;
  58037. Component::SafePointer<Component> componentUnderMouse;
  58038. ComponentPeer* lastPeer;
  58039. Point<int> unboundedMouseOffset;
  58040. bool isUnboundedMouseModeOn, isCursorVisibleUntilOffscreen;
  58041. void* currentCursorHandle;
  58042. int mouseEventCounter;
  58043. struct RecentMouseDown
  58044. {
  58045. Point<int> position;
  58046. int64 time;
  58047. Component* component;
  58048. ModifierKeys buttons;
  58049. bool canBePartOfMultipleClickWith (const RecentMouseDown& other, int maxTimeBetween) const
  58050. {
  58051. return time - other.time < maxTimeBetween
  58052. && abs (position.getX() - other.position.getX()) < 8
  58053. && abs (position.getY() - other.position.getY()) < 8
  58054. && buttons == other.buttons;;
  58055. }
  58056. };
  58057. RecentMouseDown mouseDowns[4];
  58058. bool mouseMovedSignificantlySincePressed;
  58059. int64 lastTime;
  58060. void registerMouseDown (const Point<int>& screenPos, const int64 time,
  58061. Component* const component, const ModifierKeys& modifiers) throw()
  58062. {
  58063. for (int i = numElementsInArray (mouseDowns); --i > 0;)
  58064. mouseDowns[i] = mouseDowns[i - 1];
  58065. mouseDowns[0].position = screenPos;
  58066. mouseDowns[0].time = time;
  58067. mouseDowns[0].component = component;
  58068. mouseDowns[0].buttons = modifiers.withOnlyMouseButtons();
  58069. mouseMovedSignificantlySincePressed = false;
  58070. }
  58071. void registerMouseDrag (const Point<int>& screenPos) throw()
  58072. {
  58073. mouseMovedSignificantlySincePressed = mouseMovedSignificantlySincePressed
  58074. || mouseDowns[0].position.getDistanceFrom (screenPos) >= 4;
  58075. }
  58076. MouseInputSourceInternal (const MouseInputSourceInternal&);
  58077. MouseInputSourceInternal& operator= (const MouseInputSourceInternal&);
  58078. };
  58079. MouseInputSource::MouseInputSource (const int index, const bool isMouseDevice)
  58080. {
  58081. pimpl = new MouseInputSourceInternal (*this, index, isMouseDevice);
  58082. }
  58083. MouseInputSource::~MouseInputSource()
  58084. {
  58085. }
  58086. bool MouseInputSource::isMouse() const { return pimpl->isMouseDevice; }
  58087. bool MouseInputSource::isTouch() const { return ! isMouse(); }
  58088. bool MouseInputSource::canHover() const { return isMouse(); }
  58089. bool MouseInputSource::hasMouseWheel() const { return isMouse(); }
  58090. int MouseInputSource::getIndex() const { return pimpl->index; }
  58091. bool MouseInputSource::isDragging() const { return pimpl->isDragging(); }
  58092. const Point<int> MouseInputSource::getScreenPosition() const { return pimpl->getScreenPosition(); }
  58093. const ModifierKeys MouseInputSource::getCurrentModifiers() const { return pimpl->getCurrentModifiers(); }
  58094. Component* MouseInputSource::getComponentUnderMouse() const { return pimpl->getComponentUnderMouse(); }
  58095. void MouseInputSource::triggerFakeMove() const { pimpl->triggerFakeMove(); }
  58096. int MouseInputSource::getNumberOfMultipleClicks() const throw() { return pimpl->getNumberOfMultipleClicks(); }
  58097. const Time MouseInputSource::getLastMouseDownTime() const throw() { return pimpl->getLastMouseDownTime(); }
  58098. const Point<int> MouseInputSource::getLastMouseDownPosition() const throw() { return pimpl->getLastMouseDownPosition(); }
  58099. bool MouseInputSource::hasMouseMovedSignificantlySincePressed() const throw() { return pimpl->hasMouseMovedSignificantlySincePressed(); }
  58100. bool MouseInputSource::canDoUnboundedMovement() const throw() { return isMouse(); }
  58101. void MouseInputSource::enableUnboundedMouseMovement (bool isEnabled, bool keepCursorVisibleUntilOffscreen) { pimpl->enableUnboundedMouseMovement (isEnabled, keepCursorVisibleUntilOffscreen); }
  58102. bool MouseInputSource::hasMouseCursor() const throw() { return isMouse(); }
  58103. void MouseInputSource::showMouseCursor (const MouseCursor& cursor) { pimpl->showMouseCursor (cursor, false); }
  58104. void MouseInputSource::hideCursor() { pimpl->hideCursor(); }
  58105. void MouseInputSource::revealCursor() { pimpl->revealCursor (false); }
  58106. void MouseInputSource::forceMouseCursorUpdate() { pimpl->revealCursor (true); }
  58107. void MouseInputSource::handleEvent (ComponentPeer* peer, const Point<int>& positionWithinPeer, const int64 time, const ModifierKeys& mods)
  58108. {
  58109. pimpl->handleEvent (peer, positionWithinPeer, time, mods.withOnlyMouseButtons());
  58110. }
  58111. void MouseInputSource::handleWheel (ComponentPeer* const peer, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  58112. {
  58113. pimpl->handleWheel (peer, positionWithinPeer, time, x, y);
  58114. }
  58115. END_JUCE_NAMESPACE
  58116. /*** End of inlined file: juce_MouseInputSource.cpp ***/
  58117. /*** Start of inlined file: juce_MouseHoverDetector.cpp ***/
  58118. BEGIN_JUCE_NAMESPACE
  58119. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  58120. : source (0),
  58121. hoverTimeMillisecs (hoverTimeMillisecs_),
  58122. hasJustHovered (false)
  58123. {
  58124. internalTimer.owner = this;
  58125. }
  58126. MouseHoverDetector::~MouseHoverDetector()
  58127. {
  58128. setHoverComponent (0);
  58129. }
  58130. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  58131. {
  58132. hoverTimeMillisecs = newTimeInMillisecs;
  58133. }
  58134. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  58135. {
  58136. if (source != newSourceComponent)
  58137. {
  58138. internalTimer.stopTimer();
  58139. hasJustHovered = false;
  58140. if (source != 0)
  58141. {
  58142. // ! you need to delete the hover detector before deleting its component
  58143. jassert (source->isValidComponent());
  58144. source->removeMouseListener (&internalTimer);
  58145. }
  58146. source = newSourceComponent;
  58147. if (newSourceComponent != 0)
  58148. newSourceComponent->addMouseListener (&internalTimer, false);
  58149. }
  58150. }
  58151. void MouseHoverDetector::hoverTimerCallback()
  58152. {
  58153. internalTimer.stopTimer();
  58154. if (source != 0)
  58155. {
  58156. const Point<int> pos (source->getMouseXYRelative());
  58157. if (source->reallyContains (pos.getX(), pos.getY(), false))
  58158. {
  58159. hasJustHovered = true;
  58160. mouseHovered (pos.getX(), pos.getY());
  58161. }
  58162. }
  58163. }
  58164. void MouseHoverDetector::checkJustHoveredCallback()
  58165. {
  58166. if (hasJustHovered)
  58167. {
  58168. hasJustHovered = false;
  58169. mouseMovedAfterHover();
  58170. }
  58171. }
  58172. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  58173. {
  58174. owner->hoverTimerCallback();
  58175. }
  58176. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  58177. {
  58178. stopTimer();
  58179. owner->checkJustHoveredCallback();
  58180. }
  58181. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  58182. {
  58183. stopTimer();
  58184. owner->checkJustHoveredCallback();
  58185. }
  58186. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  58187. {
  58188. stopTimer();
  58189. owner->checkJustHoveredCallback();
  58190. }
  58191. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  58192. {
  58193. stopTimer();
  58194. owner->checkJustHoveredCallback();
  58195. }
  58196. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  58197. {
  58198. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  58199. {
  58200. lastX = e.x;
  58201. lastY = e.y;
  58202. if (owner->source != 0)
  58203. startTimer (owner->hoverTimeMillisecs);
  58204. owner->checkJustHoveredCallback();
  58205. }
  58206. }
  58207. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  58208. {
  58209. stopTimer();
  58210. owner->checkJustHoveredCallback();
  58211. }
  58212. END_JUCE_NAMESPACE
  58213. /*** End of inlined file: juce_MouseHoverDetector.cpp ***/
  58214. /*** Start of inlined file: juce_MouseListener.cpp ***/
  58215. BEGIN_JUCE_NAMESPACE
  58216. void MouseListener::mouseEnter (const MouseEvent&)
  58217. {
  58218. }
  58219. void MouseListener::mouseExit (const MouseEvent&)
  58220. {
  58221. }
  58222. void MouseListener::mouseDown (const MouseEvent&)
  58223. {
  58224. }
  58225. void MouseListener::mouseUp (const MouseEvent&)
  58226. {
  58227. }
  58228. void MouseListener::mouseDrag (const MouseEvent&)
  58229. {
  58230. }
  58231. void MouseListener::mouseMove (const MouseEvent&)
  58232. {
  58233. }
  58234. void MouseListener::mouseDoubleClick (const MouseEvent&)
  58235. {
  58236. }
  58237. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  58238. {
  58239. }
  58240. END_JUCE_NAMESPACE
  58241. /*** End of inlined file: juce_MouseListener.cpp ***/
  58242. /*** Start of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58243. BEGIN_JUCE_NAMESPACE
  58244. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  58245. const String& buttonTextWhenTrue,
  58246. const String& buttonTextWhenFalse)
  58247. : PropertyComponent (name),
  58248. onText (buttonTextWhenTrue),
  58249. offText (buttonTextWhenFalse)
  58250. {
  58251. addAndMakeVisible (&button);
  58252. button.setClickingTogglesState (false);
  58253. button.addButtonListener (this);
  58254. }
  58255. BooleanPropertyComponent::BooleanPropertyComponent (const Value& valueToControl,
  58256. const String& name,
  58257. const String& buttonText)
  58258. : PropertyComponent (name),
  58259. onText (buttonText),
  58260. offText (buttonText)
  58261. {
  58262. addAndMakeVisible (&button);
  58263. button.setClickingTogglesState (false);
  58264. button.setButtonText (buttonText);
  58265. button.getToggleStateValue().referTo (valueToControl);
  58266. button.setClickingTogglesState (true);
  58267. }
  58268. BooleanPropertyComponent::~BooleanPropertyComponent()
  58269. {
  58270. }
  58271. void BooleanPropertyComponent::setState (const bool newState)
  58272. {
  58273. button.setToggleState (newState, true);
  58274. }
  58275. bool BooleanPropertyComponent::getState() const
  58276. {
  58277. return button.getToggleState();
  58278. }
  58279. void BooleanPropertyComponent::paint (Graphics& g)
  58280. {
  58281. PropertyComponent::paint (g);
  58282. g.setColour (Colours::white);
  58283. g.fillRect (button.getBounds());
  58284. g.setColour (findColour (ComboBox::outlineColourId));
  58285. g.drawRect (button.getBounds());
  58286. }
  58287. void BooleanPropertyComponent::refresh()
  58288. {
  58289. button.setToggleState (getState(), false);
  58290. button.setButtonText (button.getToggleState() ? onText : offText);
  58291. }
  58292. void BooleanPropertyComponent::buttonClicked (Button*)
  58293. {
  58294. setState (! getState());
  58295. }
  58296. END_JUCE_NAMESPACE
  58297. /*** End of inlined file: juce_BooleanPropertyComponent.cpp ***/
  58298. /*** Start of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58299. BEGIN_JUCE_NAMESPACE
  58300. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  58301. const bool triggerOnMouseDown)
  58302. : PropertyComponent (name)
  58303. {
  58304. addAndMakeVisible (&button);
  58305. button.setTriggeredOnMouseDown (triggerOnMouseDown);
  58306. button.addButtonListener (this);
  58307. }
  58308. ButtonPropertyComponent::~ButtonPropertyComponent()
  58309. {
  58310. }
  58311. void ButtonPropertyComponent::refresh()
  58312. {
  58313. button.setButtonText (getButtonText());
  58314. }
  58315. void ButtonPropertyComponent::buttonClicked (Button*)
  58316. {
  58317. buttonClicked();
  58318. }
  58319. END_JUCE_NAMESPACE
  58320. /*** End of inlined file: juce_ButtonPropertyComponent.cpp ***/
  58321. /*** Start of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58322. BEGIN_JUCE_NAMESPACE
  58323. class ChoicePropertyComponent::RemapperValueSource : public Value::ValueSource,
  58324. public Value::Listener
  58325. {
  58326. public:
  58327. RemapperValueSource (const Value& sourceValue_, const Array<var>& mappings_)
  58328. : sourceValue (sourceValue_),
  58329. mappings (mappings_)
  58330. {
  58331. sourceValue.addListener (this);
  58332. }
  58333. ~RemapperValueSource() {}
  58334. const var getValue() const
  58335. {
  58336. return mappings.indexOf (sourceValue.getValue()) + 1;
  58337. }
  58338. void setValue (const var& newValue)
  58339. {
  58340. const var remappedVal (mappings [(int) newValue - 1]);
  58341. if (remappedVal != sourceValue)
  58342. sourceValue = remappedVal;
  58343. }
  58344. void valueChanged (Value&)
  58345. {
  58346. sendChangeMessage (true);
  58347. }
  58348. juce_UseDebuggingNewOperator
  58349. protected:
  58350. Value sourceValue;
  58351. Array<var> mappings;
  58352. RemapperValueSource (const RemapperValueSource&);
  58353. const RemapperValueSource& operator= (const RemapperValueSource&);
  58354. };
  58355. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  58356. : PropertyComponent (name),
  58357. isCustomClass (true)
  58358. {
  58359. }
  58360. ChoicePropertyComponent::ChoicePropertyComponent (const Value& valueToControl,
  58361. const String& name,
  58362. const StringArray& choices_,
  58363. const Array <var>& correspondingValues)
  58364. : PropertyComponent (name),
  58365. choices (choices_),
  58366. isCustomClass (false)
  58367. {
  58368. // The array of corresponding values must contain one value for each of the items in
  58369. // the choices array!
  58370. jassert (correspondingValues.size() == choices.size());
  58371. createComboBox();
  58372. comboBox.getSelectedIdAsValue().referTo (Value (new RemapperValueSource (valueToControl, correspondingValues)));
  58373. }
  58374. ChoicePropertyComponent::~ChoicePropertyComponent()
  58375. {
  58376. }
  58377. void ChoicePropertyComponent::createComboBox()
  58378. {
  58379. addAndMakeVisible (&comboBox);
  58380. for (int i = 0; i < choices.size(); ++i)
  58381. {
  58382. if (choices[i].isNotEmpty())
  58383. comboBox.addItem (choices[i], i + 1);
  58384. else
  58385. comboBox.addSeparator();
  58386. }
  58387. comboBox.setEditableText (false);
  58388. }
  58389. void ChoicePropertyComponent::setIndex (const int /*newIndex*/)
  58390. {
  58391. jassertfalse; // you need to override this method in your subclass!
  58392. }
  58393. int ChoicePropertyComponent::getIndex() const
  58394. {
  58395. jassertfalse; // you need to override this method in your subclass!
  58396. return -1;
  58397. }
  58398. const StringArray& ChoicePropertyComponent::getChoices() const
  58399. {
  58400. return choices;
  58401. }
  58402. void ChoicePropertyComponent::refresh()
  58403. {
  58404. if (isCustomClass)
  58405. {
  58406. if (! comboBox.isVisible())
  58407. {
  58408. createComboBox();
  58409. comboBox.addListener (this);
  58410. }
  58411. comboBox.setSelectedId (getIndex() + 1, true);
  58412. }
  58413. }
  58414. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  58415. {
  58416. if (isCustomClass)
  58417. {
  58418. const int newIndex = comboBox.getSelectedId() - 1;
  58419. if (newIndex != getIndex())
  58420. setIndex (newIndex);
  58421. }
  58422. }
  58423. END_JUCE_NAMESPACE
  58424. /*** End of inlined file: juce_ChoicePropertyComponent.cpp ***/
  58425. /*** Start of inlined file: juce_PropertyComponent.cpp ***/
  58426. BEGIN_JUCE_NAMESPACE
  58427. PropertyComponent::PropertyComponent (const String& name,
  58428. const int preferredHeight_)
  58429. : Component (name),
  58430. preferredHeight (preferredHeight_)
  58431. {
  58432. jassert (name.isNotEmpty());
  58433. }
  58434. PropertyComponent::~PropertyComponent()
  58435. {
  58436. }
  58437. void PropertyComponent::paint (Graphics& g)
  58438. {
  58439. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  58440. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  58441. }
  58442. void PropertyComponent::resized()
  58443. {
  58444. if (getNumChildComponents() > 0)
  58445. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  58446. }
  58447. void PropertyComponent::enablementChanged()
  58448. {
  58449. repaint();
  58450. }
  58451. END_JUCE_NAMESPACE
  58452. /*** End of inlined file: juce_PropertyComponent.cpp ***/
  58453. /*** Start of inlined file: juce_PropertyPanel.cpp ***/
  58454. BEGIN_JUCE_NAMESPACE
  58455. class PropertyPanel::PropertyHolderComponent : public Component
  58456. {
  58457. public:
  58458. PropertyHolderComponent()
  58459. {
  58460. }
  58461. ~PropertyHolderComponent()
  58462. {
  58463. deleteAllChildren();
  58464. }
  58465. void paint (Graphics&)
  58466. {
  58467. }
  58468. void updateLayout (int width);
  58469. void refreshAll() const;
  58470. private:
  58471. PropertyHolderComponent (const PropertyHolderComponent&);
  58472. PropertyHolderComponent& operator= (const PropertyHolderComponent&);
  58473. };
  58474. class PropertySectionComponent : public Component
  58475. {
  58476. public:
  58477. PropertySectionComponent (const String& sectionTitle,
  58478. const Array <PropertyComponent*>& newProperties,
  58479. const bool open)
  58480. : Component (sectionTitle),
  58481. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  58482. isOpen_ (open)
  58483. {
  58484. for (int i = newProperties.size(); --i >= 0;)
  58485. {
  58486. addAndMakeVisible (newProperties.getUnchecked(i));
  58487. newProperties.getUnchecked(i)->refresh();
  58488. }
  58489. }
  58490. ~PropertySectionComponent()
  58491. {
  58492. deleteAllChildren();
  58493. }
  58494. void paint (Graphics& g)
  58495. {
  58496. if (titleHeight > 0)
  58497. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  58498. }
  58499. void resized()
  58500. {
  58501. int y = titleHeight;
  58502. for (int i = getNumChildComponents(); --i >= 0;)
  58503. {
  58504. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58505. if (pec != 0)
  58506. {
  58507. const int prefH = pec->getPreferredHeight();
  58508. pec->setBounds (1, y, getWidth() - 2, prefH);
  58509. y += prefH;
  58510. }
  58511. }
  58512. }
  58513. int getPreferredHeight() const
  58514. {
  58515. int y = titleHeight;
  58516. if (isOpen())
  58517. {
  58518. for (int i = 0; i < getNumChildComponents(); ++i)
  58519. {
  58520. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58521. if (pec != 0)
  58522. y += pec->getPreferredHeight();
  58523. }
  58524. }
  58525. return y;
  58526. }
  58527. void setOpen (const bool open)
  58528. {
  58529. if (isOpen_ != open)
  58530. {
  58531. isOpen_ = open;
  58532. for (int i = 0; i < getNumChildComponents(); ++i)
  58533. {
  58534. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58535. if (pec != 0)
  58536. pec->setVisible (open);
  58537. }
  58538. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  58539. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  58540. if (pp != 0)
  58541. pp->resized();
  58542. }
  58543. }
  58544. bool isOpen() const
  58545. {
  58546. return isOpen_;
  58547. }
  58548. void refreshAll() const
  58549. {
  58550. for (int i = 0; i < getNumChildComponents(); ++i)
  58551. {
  58552. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  58553. if (pec != 0)
  58554. pec->refresh();
  58555. }
  58556. }
  58557. void mouseDown (const MouseEvent&)
  58558. {
  58559. }
  58560. void mouseUp (const MouseEvent& e)
  58561. {
  58562. if (e.getMouseDownX() < titleHeight
  58563. && e.x < titleHeight
  58564. && e.y < titleHeight
  58565. && e.getNumberOfClicks() != 2)
  58566. {
  58567. setOpen (! isOpen());
  58568. }
  58569. }
  58570. void mouseDoubleClick (const MouseEvent& e)
  58571. {
  58572. if (e.y < titleHeight)
  58573. setOpen (! isOpen());
  58574. }
  58575. private:
  58576. int titleHeight;
  58577. bool isOpen_;
  58578. PropertySectionComponent (const PropertySectionComponent&);
  58579. PropertySectionComponent& operator= (const PropertySectionComponent&);
  58580. };
  58581. void PropertyPanel::PropertyHolderComponent::updateLayout (const int width)
  58582. {
  58583. int y = 0;
  58584. for (int i = getNumChildComponents(); --i >= 0;)
  58585. {
  58586. PropertySectionComponent* const section
  58587. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58588. if (section != 0)
  58589. {
  58590. const int prefH = section->getPreferredHeight();
  58591. section->setBounds (0, y, width, prefH);
  58592. y += prefH;
  58593. }
  58594. }
  58595. setSize (width, y);
  58596. repaint();
  58597. }
  58598. void PropertyPanel::PropertyHolderComponent::refreshAll() const
  58599. {
  58600. for (int i = getNumChildComponents(); --i >= 0;)
  58601. {
  58602. PropertySectionComponent* const section
  58603. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  58604. if (section != 0)
  58605. section->refreshAll();
  58606. }
  58607. }
  58608. PropertyPanel::PropertyPanel()
  58609. {
  58610. messageWhenEmpty = TRANS("(nothing selected)");
  58611. addAndMakeVisible (&viewport);
  58612. viewport.setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  58613. viewport.setFocusContainer (true);
  58614. }
  58615. PropertyPanel::~PropertyPanel()
  58616. {
  58617. clear();
  58618. }
  58619. void PropertyPanel::paint (Graphics& g)
  58620. {
  58621. if (propertyHolderComponent->getNumChildComponents() == 0)
  58622. {
  58623. g.setColour (Colours::black.withAlpha (0.5f));
  58624. g.setFont (14.0f);
  58625. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  58626. Justification::centred, true);
  58627. }
  58628. }
  58629. void PropertyPanel::resized()
  58630. {
  58631. viewport.setBounds (getLocalBounds());
  58632. updatePropHolderLayout();
  58633. }
  58634. void PropertyPanel::clear()
  58635. {
  58636. if (propertyHolderComponent->getNumChildComponents() > 0)
  58637. {
  58638. propertyHolderComponent->deleteAllChildren();
  58639. repaint();
  58640. }
  58641. }
  58642. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  58643. {
  58644. if (propertyHolderComponent->getNumChildComponents() == 0)
  58645. repaint();
  58646. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  58647. newProperties,
  58648. true), 0);
  58649. updatePropHolderLayout();
  58650. }
  58651. void PropertyPanel::addSection (const String& sectionTitle,
  58652. const Array <PropertyComponent*>& newProperties,
  58653. const bool shouldBeOpen)
  58654. {
  58655. jassert (sectionTitle.isNotEmpty());
  58656. if (propertyHolderComponent->getNumChildComponents() == 0)
  58657. repaint();
  58658. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  58659. newProperties,
  58660. shouldBeOpen), 0);
  58661. updatePropHolderLayout();
  58662. }
  58663. void PropertyPanel::updatePropHolderLayout() const
  58664. {
  58665. const int maxWidth = viewport.getMaximumVisibleWidth();
  58666. propertyHolderComponent->updateLayout (maxWidth);
  58667. const int newMaxWidth = viewport.getMaximumVisibleWidth();
  58668. if (maxWidth != newMaxWidth)
  58669. {
  58670. // need to do this twice because of scrollbars changing the size, etc.
  58671. propertyHolderComponent->updateLayout (newMaxWidth);
  58672. }
  58673. }
  58674. void PropertyPanel::refreshAll() const
  58675. {
  58676. propertyHolderComponent->refreshAll();
  58677. }
  58678. const StringArray PropertyPanel::getSectionNames() const
  58679. {
  58680. StringArray s;
  58681. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58682. {
  58683. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58684. if (section != 0 && section->getName().isNotEmpty())
  58685. s.add (section->getName());
  58686. }
  58687. return s;
  58688. }
  58689. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  58690. {
  58691. int index = 0;
  58692. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58693. {
  58694. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58695. if (section != 0 && section->getName().isNotEmpty())
  58696. {
  58697. if (index == sectionIndex)
  58698. return section->isOpen();
  58699. ++index;
  58700. }
  58701. }
  58702. return false;
  58703. }
  58704. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  58705. {
  58706. int index = 0;
  58707. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58708. {
  58709. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58710. if (section != 0 && section->getName().isNotEmpty())
  58711. {
  58712. if (index == sectionIndex)
  58713. {
  58714. section->setOpen (shouldBeOpen);
  58715. break;
  58716. }
  58717. ++index;
  58718. }
  58719. }
  58720. }
  58721. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  58722. {
  58723. int index = 0;
  58724. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  58725. {
  58726. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  58727. if (section != 0 && section->getName().isNotEmpty())
  58728. {
  58729. if (index == sectionIndex)
  58730. {
  58731. section->setEnabled (shouldBeEnabled);
  58732. break;
  58733. }
  58734. ++index;
  58735. }
  58736. }
  58737. }
  58738. XmlElement* PropertyPanel::getOpennessState() const
  58739. {
  58740. XmlElement* const xml = new XmlElement ("PROPERTYPANELSTATE");
  58741. xml->setAttribute ("scrollPos", viewport.getViewPositionY());
  58742. const StringArray sections (getSectionNames());
  58743. for (int i = 0; i < sections.size(); ++i)
  58744. {
  58745. if (sections[i].isNotEmpty())
  58746. {
  58747. XmlElement* const e = xml->createNewChildElement ("SECTION");
  58748. e->setAttribute ("name", sections[i]);
  58749. e->setAttribute ("open", isSectionOpen (i) ? 1 : 0);
  58750. }
  58751. }
  58752. return xml;
  58753. }
  58754. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  58755. {
  58756. if (xml.hasTagName ("PROPERTYPANELSTATE"))
  58757. {
  58758. const StringArray sections (getSectionNames());
  58759. forEachXmlChildElementWithTagName (xml, e, "SECTION")
  58760. {
  58761. setSectionOpen (sections.indexOf (e->getStringAttribute ("name")),
  58762. e->getBoolAttribute ("open"));
  58763. }
  58764. viewport.setViewPosition (viewport.getViewPositionX(),
  58765. xml.getIntAttribute ("scrollPos", viewport.getViewPositionY()));
  58766. }
  58767. }
  58768. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  58769. {
  58770. if (messageWhenEmpty != newMessage)
  58771. {
  58772. messageWhenEmpty = newMessage;
  58773. repaint();
  58774. }
  58775. }
  58776. const String& PropertyPanel::getMessageWhenEmpty() const
  58777. {
  58778. return messageWhenEmpty;
  58779. }
  58780. END_JUCE_NAMESPACE
  58781. /*** End of inlined file: juce_PropertyPanel.cpp ***/
  58782. /*** Start of inlined file: juce_SliderPropertyComponent.cpp ***/
  58783. BEGIN_JUCE_NAMESPACE
  58784. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  58785. const double rangeMin,
  58786. const double rangeMax,
  58787. const double interval,
  58788. const double skewFactor)
  58789. : PropertyComponent (name)
  58790. {
  58791. addAndMakeVisible (&slider);
  58792. slider.setRange (rangeMin, rangeMax, interval);
  58793. slider.setSkewFactor (skewFactor);
  58794. slider.setSliderStyle (Slider::LinearBar);
  58795. slider.addListener (this);
  58796. }
  58797. SliderPropertyComponent::SliderPropertyComponent (const Value& valueToControl,
  58798. const String& name,
  58799. const double rangeMin,
  58800. const double rangeMax,
  58801. const double interval,
  58802. const double skewFactor)
  58803. : PropertyComponent (name)
  58804. {
  58805. addAndMakeVisible (&slider);
  58806. slider.setRange (rangeMin, rangeMax, interval);
  58807. slider.setSkewFactor (skewFactor);
  58808. slider.setSliderStyle (Slider::LinearBar);
  58809. slider.getValueObject().referTo (valueToControl);
  58810. }
  58811. SliderPropertyComponent::~SliderPropertyComponent()
  58812. {
  58813. }
  58814. void SliderPropertyComponent::setValue (const double /*newValue*/)
  58815. {
  58816. }
  58817. double SliderPropertyComponent::getValue() const
  58818. {
  58819. return slider.getValue();
  58820. }
  58821. void SliderPropertyComponent::refresh()
  58822. {
  58823. slider.setValue (getValue(), false);
  58824. }
  58825. void SliderPropertyComponent::sliderValueChanged (Slider*)
  58826. {
  58827. if (getValue() != slider.getValue())
  58828. setValue (slider.getValue());
  58829. }
  58830. END_JUCE_NAMESPACE
  58831. /*** End of inlined file: juce_SliderPropertyComponent.cpp ***/
  58832. /*** Start of inlined file: juce_TextPropertyComponent.cpp ***/
  58833. BEGIN_JUCE_NAMESPACE
  58834. class TextPropLabel : public Label
  58835. {
  58836. public:
  58837. TextPropLabel (TextPropertyComponent& owner_,
  58838. const int maxChars_, const bool isMultiline_)
  58839. : Label (String::empty, String::empty),
  58840. owner (owner_),
  58841. maxChars (maxChars_),
  58842. isMultiline (isMultiline_)
  58843. {
  58844. setEditable (true, true, false);
  58845. setColour (backgroundColourId, Colours::white);
  58846. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  58847. }
  58848. TextEditor* createEditorComponent()
  58849. {
  58850. TextEditor* const textEditor = Label::createEditorComponent();
  58851. textEditor->setInputRestrictions (maxChars);
  58852. if (isMultiline)
  58853. {
  58854. textEditor->setMultiLine (true, true);
  58855. textEditor->setReturnKeyStartsNewLine (true);
  58856. }
  58857. return textEditor;
  58858. }
  58859. void textWasEdited()
  58860. {
  58861. owner.textWasEdited();
  58862. }
  58863. private:
  58864. TextPropertyComponent& owner;
  58865. int maxChars;
  58866. bool isMultiline;
  58867. };
  58868. TextPropertyComponent::TextPropertyComponent (const String& name,
  58869. const int maxNumChars,
  58870. const bool isMultiLine)
  58871. : PropertyComponent (name)
  58872. {
  58873. createEditor (maxNumChars, isMultiLine);
  58874. }
  58875. TextPropertyComponent::TextPropertyComponent (const Value& valueToControl,
  58876. const String& name,
  58877. const int maxNumChars,
  58878. const bool isMultiLine)
  58879. : PropertyComponent (name)
  58880. {
  58881. createEditor (maxNumChars, isMultiLine);
  58882. textEditor->getTextValue().referTo (valueToControl);
  58883. }
  58884. TextPropertyComponent::~TextPropertyComponent()
  58885. {
  58886. }
  58887. void TextPropertyComponent::setText (const String& newText)
  58888. {
  58889. textEditor->setText (newText, true);
  58890. }
  58891. const String TextPropertyComponent::getText() const
  58892. {
  58893. return textEditor->getText();
  58894. }
  58895. void TextPropertyComponent::createEditor (const int maxNumChars, const bool isMultiLine)
  58896. {
  58897. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  58898. if (isMultiLine)
  58899. {
  58900. textEditor->setJustificationType (Justification::topLeft);
  58901. preferredHeight = 120;
  58902. }
  58903. }
  58904. void TextPropertyComponent::refresh()
  58905. {
  58906. textEditor->setText (getText(), false);
  58907. }
  58908. void TextPropertyComponent::textWasEdited()
  58909. {
  58910. const String newText (textEditor->getText());
  58911. if (getText() != newText)
  58912. setText (newText);
  58913. }
  58914. END_JUCE_NAMESPACE
  58915. /*** End of inlined file: juce_TextPropertyComponent.cpp ***/
  58916. /*** Start of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  58917. BEGIN_JUCE_NAMESPACE
  58918. class SimpleDeviceManagerInputLevelMeter : public Component,
  58919. public Timer
  58920. {
  58921. public:
  58922. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  58923. : manager (manager_),
  58924. level (0)
  58925. {
  58926. startTimer (50);
  58927. manager->enableInputLevelMeasurement (true);
  58928. }
  58929. ~SimpleDeviceManagerInputLevelMeter()
  58930. {
  58931. manager->enableInputLevelMeasurement (false);
  58932. }
  58933. void timerCallback()
  58934. {
  58935. const float newLevel = (float) manager->getCurrentInputLevel();
  58936. if (std::abs (level - newLevel) > 0.005f)
  58937. {
  58938. level = newLevel;
  58939. repaint();
  58940. }
  58941. }
  58942. void paint (Graphics& g)
  58943. {
  58944. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  58945. (float) exp (log (level) / 3.0)); // (add a bit of a skew to make the level more obvious)
  58946. }
  58947. private:
  58948. AudioDeviceManager* const manager;
  58949. float level;
  58950. SimpleDeviceManagerInputLevelMeter (const SimpleDeviceManagerInputLevelMeter&);
  58951. SimpleDeviceManagerInputLevelMeter& operator= (const SimpleDeviceManagerInputLevelMeter&);
  58952. };
  58953. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  58954. public ListBoxModel
  58955. {
  58956. public:
  58957. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  58958. const String& noItemsMessage_,
  58959. const int minNumber_,
  58960. const int maxNumber_)
  58961. : ListBox (String::empty, 0),
  58962. deviceManager (deviceManager_),
  58963. noItemsMessage (noItemsMessage_),
  58964. minNumber (minNumber_),
  58965. maxNumber (maxNumber_)
  58966. {
  58967. items = MidiInput::getDevices();
  58968. setModel (this);
  58969. setOutlineThickness (1);
  58970. }
  58971. ~MidiInputSelectorComponentListBox()
  58972. {
  58973. }
  58974. int getNumRows()
  58975. {
  58976. return items.size();
  58977. }
  58978. void paintListBoxItem (int row,
  58979. Graphics& g,
  58980. int width, int height,
  58981. bool rowIsSelected)
  58982. {
  58983. if (((unsigned int) row) < (unsigned int) items.size())
  58984. {
  58985. if (rowIsSelected)
  58986. g.fillAll (findColour (TextEditor::highlightColourId)
  58987. .withMultipliedAlpha (0.3f));
  58988. const String item (items [row]);
  58989. bool enabled = deviceManager.isMidiInputEnabled (item);
  58990. const int x = getTickX();
  58991. const float tickW = height * 0.75f;
  58992. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  58993. enabled, true, true, false);
  58994. g.setFont (height * 0.6f);
  58995. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  58996. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  58997. }
  58998. }
  58999. void listBoxItemClicked (int row, const MouseEvent& e)
  59000. {
  59001. selectRow (row);
  59002. if (e.x < getTickX())
  59003. flipEnablement (row);
  59004. }
  59005. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59006. {
  59007. flipEnablement (row);
  59008. }
  59009. void returnKeyPressed (int row)
  59010. {
  59011. flipEnablement (row);
  59012. }
  59013. void paint (Graphics& g)
  59014. {
  59015. ListBox::paint (g);
  59016. if (items.size() == 0)
  59017. {
  59018. g.setColour (Colours::grey);
  59019. g.setFont (13.0f);
  59020. g.drawText (noItemsMessage,
  59021. 0, 0, getWidth(), getHeight() / 2,
  59022. Justification::centred, true);
  59023. }
  59024. }
  59025. int getBestHeight (const int preferredHeight)
  59026. {
  59027. const int extra = getOutlineThickness() * 2;
  59028. return jmax (getRowHeight() * 2 + extra,
  59029. jmin (getRowHeight() * getNumRows() + extra,
  59030. preferredHeight));
  59031. }
  59032. juce_UseDebuggingNewOperator
  59033. private:
  59034. AudioDeviceManager& deviceManager;
  59035. const String noItemsMessage;
  59036. StringArray items;
  59037. int minNumber, maxNumber;
  59038. void flipEnablement (const int row)
  59039. {
  59040. if (((unsigned int) row) < (unsigned int) items.size())
  59041. {
  59042. const String item (items [row]);
  59043. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  59044. }
  59045. }
  59046. int getTickX() const
  59047. {
  59048. return getRowHeight() + 5;
  59049. }
  59050. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  59051. MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  59052. };
  59053. class AudioDeviceSettingsPanel : public Component,
  59054. public ChangeListener,
  59055. public ComboBoxListener, // (can't use ComboBox::Listener due to idiotic VC2005 bug)
  59056. public ButtonListener
  59057. {
  59058. public:
  59059. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  59060. AudioIODeviceType::DeviceSetupDetails& setup_,
  59061. const bool hideAdvancedOptionsWithButton)
  59062. : type (type_),
  59063. setup (setup_)
  59064. {
  59065. if (hideAdvancedOptionsWithButton)
  59066. {
  59067. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  59068. showAdvancedSettingsButton->addButtonListener (this);
  59069. }
  59070. type->scanForDevices();
  59071. setup.manager->addChangeListener (this);
  59072. changeListenerCallback (0);
  59073. }
  59074. ~AudioDeviceSettingsPanel()
  59075. {
  59076. setup.manager->removeChangeListener (this);
  59077. }
  59078. void resized()
  59079. {
  59080. const int lx = proportionOfWidth (0.35f);
  59081. const int w = proportionOfWidth (0.4f);
  59082. const int h = 24;
  59083. const int space = 6;
  59084. const int dh = h + space;
  59085. int y = 0;
  59086. if (outputDeviceDropDown != 0)
  59087. {
  59088. outputDeviceDropDown->setBounds (lx, y, w, h);
  59089. if (testButton != 0)
  59090. testButton->setBounds (proportionOfWidth (0.77f),
  59091. outputDeviceDropDown->getY(),
  59092. proportionOfWidth (0.18f),
  59093. h);
  59094. y += dh;
  59095. }
  59096. if (inputDeviceDropDown != 0)
  59097. {
  59098. inputDeviceDropDown->setBounds (lx, y, w, h);
  59099. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  59100. inputDeviceDropDown->getY(),
  59101. proportionOfWidth (0.18f),
  59102. h);
  59103. y += dh;
  59104. }
  59105. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  59106. if (outputChanList != 0)
  59107. {
  59108. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  59109. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59110. y += bh + space;
  59111. }
  59112. if (inputChanList != 0)
  59113. {
  59114. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  59115. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  59116. y += bh + space;
  59117. }
  59118. y += space * 2;
  59119. if (showAdvancedSettingsButton != 0)
  59120. {
  59121. showAdvancedSettingsButton->changeWidthToFitText (h);
  59122. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  59123. }
  59124. if (sampleRateDropDown != 0)
  59125. {
  59126. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  59127. || ! showAdvancedSettingsButton->isVisible());
  59128. sampleRateDropDown->setBounds (lx, y, w, h);
  59129. y += dh;
  59130. }
  59131. if (bufferSizeDropDown != 0)
  59132. {
  59133. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  59134. || ! showAdvancedSettingsButton->isVisible());
  59135. bufferSizeDropDown->setBounds (lx, y, w, h);
  59136. y += dh;
  59137. }
  59138. if (showUIButton != 0)
  59139. {
  59140. showUIButton->setVisible (showAdvancedSettingsButton == 0
  59141. || ! showAdvancedSettingsButton->isVisible());
  59142. showUIButton->changeWidthToFitText (h);
  59143. showUIButton->setTopLeftPosition (lx, y);
  59144. }
  59145. }
  59146. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59147. {
  59148. if (comboBoxThatHasChanged == 0)
  59149. return;
  59150. AudioDeviceManager::AudioDeviceSetup config;
  59151. setup.manager->getAudioDeviceSetup (config);
  59152. String error;
  59153. if (comboBoxThatHasChanged == outputDeviceDropDown
  59154. || comboBoxThatHasChanged == inputDeviceDropDown)
  59155. {
  59156. if (outputDeviceDropDown != 0)
  59157. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59158. : outputDeviceDropDown->getText();
  59159. if (inputDeviceDropDown != 0)
  59160. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  59161. : inputDeviceDropDown->getText();
  59162. if (! type->hasSeparateInputsAndOutputs())
  59163. config.inputDeviceName = config.outputDeviceName;
  59164. if (comboBoxThatHasChanged == inputDeviceDropDown)
  59165. config.useDefaultInputChannels = true;
  59166. else
  59167. config.useDefaultOutputChannels = true;
  59168. error = setup.manager->setAudioDeviceSetup (config, true);
  59169. showCorrectDeviceName (inputDeviceDropDown, true);
  59170. showCorrectDeviceName (outputDeviceDropDown, false);
  59171. updateControlPanelButton();
  59172. resized();
  59173. }
  59174. else if (comboBoxThatHasChanged == sampleRateDropDown)
  59175. {
  59176. if (sampleRateDropDown->getSelectedId() > 0)
  59177. {
  59178. config.sampleRate = sampleRateDropDown->getSelectedId();
  59179. error = setup.manager->setAudioDeviceSetup (config, true);
  59180. }
  59181. }
  59182. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  59183. {
  59184. if (bufferSizeDropDown->getSelectedId() > 0)
  59185. {
  59186. config.bufferSize = bufferSizeDropDown->getSelectedId();
  59187. error = setup.manager->setAudioDeviceSetup (config, true);
  59188. }
  59189. }
  59190. if (error.isNotEmpty())
  59191. {
  59192. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  59193. "Error when trying to open audio device!",
  59194. error);
  59195. }
  59196. }
  59197. void buttonClicked (Button* button)
  59198. {
  59199. if (button == showAdvancedSettingsButton)
  59200. {
  59201. showAdvancedSettingsButton->setVisible (false);
  59202. resized();
  59203. }
  59204. else if (button == showUIButton)
  59205. {
  59206. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  59207. if (device != 0 && device->showControlPanel())
  59208. {
  59209. setup.manager->closeAudioDevice();
  59210. setup.manager->restartLastAudioDevice();
  59211. getTopLevelComponent()->toFront (true);
  59212. }
  59213. }
  59214. else if (button == testButton && testButton != 0)
  59215. {
  59216. setup.manager->playTestSound();
  59217. }
  59218. }
  59219. void updateControlPanelButton()
  59220. {
  59221. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59222. showUIButton = 0;
  59223. if (currentDevice != 0 && currentDevice->hasControlPanel())
  59224. {
  59225. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  59226. TRANS ("opens the device's own control panel")));
  59227. showUIButton->addButtonListener (this);
  59228. }
  59229. resized();
  59230. }
  59231. void changeListenerCallback (void*)
  59232. {
  59233. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59234. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  59235. {
  59236. if (outputDeviceDropDown == 0)
  59237. {
  59238. outputDeviceDropDown = new ComboBox (String::empty);
  59239. outputDeviceDropDown->addListener (this);
  59240. addAndMakeVisible (outputDeviceDropDown);
  59241. outputDeviceLabel = new Label (String::empty,
  59242. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  59243. : TRANS ("device:"));
  59244. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  59245. if (setup.maxNumOutputChannels > 0)
  59246. {
  59247. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  59248. testButton->addButtonListener (this);
  59249. }
  59250. }
  59251. addNamesToDeviceBox (*outputDeviceDropDown, false);
  59252. }
  59253. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  59254. {
  59255. if (inputDeviceDropDown == 0)
  59256. {
  59257. inputDeviceDropDown = new ComboBox (String::empty);
  59258. inputDeviceDropDown->addListener (this);
  59259. addAndMakeVisible (inputDeviceDropDown);
  59260. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  59261. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  59262. addAndMakeVisible (inputLevelMeter
  59263. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  59264. }
  59265. addNamesToDeviceBox (*inputDeviceDropDown, true);
  59266. }
  59267. updateControlPanelButton();
  59268. showCorrectDeviceName (inputDeviceDropDown, true);
  59269. showCorrectDeviceName (outputDeviceDropDown, false);
  59270. if (currentDevice != 0)
  59271. {
  59272. if (setup.maxNumOutputChannels > 0
  59273. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  59274. {
  59275. if (outputChanList == 0)
  59276. {
  59277. addAndMakeVisible (outputChanList
  59278. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  59279. TRANS ("(no audio output channels found)")));
  59280. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  59281. outputChanLabel->attachToComponent (outputChanList, true);
  59282. }
  59283. outputChanList->refresh();
  59284. }
  59285. else
  59286. {
  59287. outputChanLabel = 0;
  59288. outputChanList = 0;
  59289. }
  59290. if (setup.maxNumInputChannels > 0
  59291. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  59292. {
  59293. if (inputChanList == 0)
  59294. {
  59295. addAndMakeVisible (inputChanList
  59296. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  59297. TRANS ("(no audio input channels found)")));
  59298. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  59299. inputChanLabel->attachToComponent (inputChanList, true);
  59300. }
  59301. inputChanList->refresh();
  59302. }
  59303. else
  59304. {
  59305. inputChanLabel = 0;
  59306. inputChanList = 0;
  59307. }
  59308. // sample rate..
  59309. {
  59310. if (sampleRateDropDown == 0)
  59311. {
  59312. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  59313. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  59314. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  59315. }
  59316. else
  59317. {
  59318. sampleRateDropDown->clear();
  59319. sampleRateDropDown->removeListener (this);
  59320. }
  59321. const int numRates = currentDevice->getNumSampleRates();
  59322. for (int i = 0; i < numRates; ++i)
  59323. {
  59324. const int rate = roundToInt (currentDevice->getSampleRate (i));
  59325. sampleRateDropDown->addItem (String (rate) + " Hz", rate);
  59326. }
  59327. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), true);
  59328. sampleRateDropDown->addListener (this);
  59329. }
  59330. // buffer size
  59331. {
  59332. if (bufferSizeDropDown == 0)
  59333. {
  59334. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  59335. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  59336. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  59337. }
  59338. else
  59339. {
  59340. bufferSizeDropDown->clear();
  59341. bufferSizeDropDown->removeListener (this);
  59342. }
  59343. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  59344. double currentRate = currentDevice->getCurrentSampleRate();
  59345. if (currentRate == 0)
  59346. currentRate = 48000.0;
  59347. for (int i = 0; i < numBufferSizes; ++i)
  59348. {
  59349. const int bs = currentDevice->getBufferSizeSamples (i);
  59350. bufferSizeDropDown->addItem (String (bs)
  59351. + " samples ("
  59352. + String (bs * 1000.0 / currentRate, 1)
  59353. + " ms)",
  59354. bs);
  59355. }
  59356. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  59357. bufferSizeDropDown->addListener (this);
  59358. }
  59359. }
  59360. else
  59361. {
  59362. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  59363. sampleRateLabel = 0;
  59364. bufferSizeLabel = 0;
  59365. sampleRateDropDown = 0;
  59366. bufferSizeDropDown = 0;
  59367. if (outputDeviceDropDown != 0)
  59368. outputDeviceDropDown->setSelectedId (-1, true);
  59369. if (inputDeviceDropDown != 0)
  59370. inputDeviceDropDown->setSelectedId (-1, true);
  59371. }
  59372. resized();
  59373. setSize (getWidth(), getLowestY() + 4);
  59374. }
  59375. private:
  59376. AudioIODeviceType* const type;
  59377. const AudioIODeviceType::DeviceSetupDetails setup;
  59378. ScopedPointer<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  59379. ScopedPointer<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  59380. ScopedPointer<TextButton> testButton;
  59381. ScopedPointer<Component> inputLevelMeter;
  59382. ScopedPointer<TextButton> showUIButton, showAdvancedSettingsButton;
  59383. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  59384. {
  59385. if (box != 0)
  59386. {
  59387. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  59388. const int index = type->getIndexOfDevice (currentDevice, isInput);
  59389. box->setSelectedId (index + 1, true);
  59390. if (testButton != 0 && ! isInput)
  59391. testButton->setEnabled (index >= 0);
  59392. }
  59393. }
  59394. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  59395. {
  59396. const StringArray devs (type->getDeviceNames (isInputs));
  59397. combo.clear (true);
  59398. for (int i = 0; i < devs.size(); ++i)
  59399. combo.addItem (devs[i], i + 1);
  59400. combo.addItem (TRANS("<< none >>"), -1);
  59401. combo.setSelectedId (-1, true);
  59402. }
  59403. int getLowestY() const
  59404. {
  59405. int y = 0;
  59406. for (int i = getNumChildComponents(); --i >= 0;)
  59407. y = jmax (y, getChildComponent (i)->getBottom());
  59408. return y;
  59409. }
  59410. public:
  59411. class ChannelSelectorListBox : public ListBox,
  59412. public ListBoxModel
  59413. {
  59414. public:
  59415. enum BoxType
  59416. {
  59417. audioInputType,
  59418. audioOutputType
  59419. };
  59420. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  59421. const BoxType type_,
  59422. const String& noItemsMessage_)
  59423. : ListBox (String::empty, 0),
  59424. setup (setup_),
  59425. type (type_),
  59426. noItemsMessage (noItemsMessage_)
  59427. {
  59428. refresh();
  59429. setModel (this);
  59430. setOutlineThickness (1);
  59431. }
  59432. ~ChannelSelectorListBox()
  59433. {
  59434. }
  59435. void refresh()
  59436. {
  59437. items.clear();
  59438. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  59439. if (currentDevice != 0)
  59440. {
  59441. if (type == audioInputType)
  59442. items = currentDevice->getInputChannelNames();
  59443. else if (type == audioOutputType)
  59444. items = currentDevice->getOutputChannelNames();
  59445. if (setup.useStereoPairs)
  59446. {
  59447. StringArray pairs;
  59448. for (int i = 0; i < items.size(); i += 2)
  59449. {
  59450. const String name (items[i]);
  59451. const String name2 (items[i + 1]);
  59452. String commonBit;
  59453. for (int j = 0; j < name.length(); ++j)
  59454. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  59455. commonBit = name.substring (0, j);
  59456. // Make sure we only split the name at a space, because otherwise, things
  59457. // like "input 11" + "input 12" would become "input 11 + 2"
  59458. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  59459. commonBit = commonBit.dropLastCharacters (1);
  59460. pairs.add (name.trim() + " + " + name2.substring (commonBit.length()).trim());
  59461. }
  59462. items = pairs;
  59463. }
  59464. }
  59465. updateContent();
  59466. repaint();
  59467. }
  59468. int getNumRows()
  59469. {
  59470. return items.size();
  59471. }
  59472. void paintListBoxItem (int row,
  59473. Graphics& g,
  59474. int width, int height,
  59475. bool rowIsSelected)
  59476. {
  59477. if (((unsigned int) row) < (unsigned int) items.size())
  59478. {
  59479. if (rowIsSelected)
  59480. g.fillAll (findColour (TextEditor::highlightColourId)
  59481. .withMultipliedAlpha (0.3f));
  59482. const String item (items [row]);
  59483. bool enabled = false;
  59484. AudioDeviceManager::AudioDeviceSetup config;
  59485. setup.manager->getAudioDeviceSetup (config);
  59486. if (setup.useStereoPairs)
  59487. {
  59488. if (type == audioInputType)
  59489. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  59490. else if (type == audioOutputType)
  59491. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  59492. }
  59493. else
  59494. {
  59495. if (type == audioInputType)
  59496. enabled = config.inputChannels [row];
  59497. else if (type == audioOutputType)
  59498. enabled = config.outputChannels [row];
  59499. }
  59500. const int x = getTickX();
  59501. const float tickW = height * 0.75f;
  59502. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  59503. enabled, true, true, false);
  59504. g.setFont (height * 0.6f);
  59505. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  59506. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  59507. }
  59508. }
  59509. void listBoxItemClicked (int row, const MouseEvent& e)
  59510. {
  59511. selectRow (row);
  59512. if (e.x < getTickX())
  59513. flipEnablement (row);
  59514. }
  59515. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  59516. {
  59517. flipEnablement (row);
  59518. }
  59519. void returnKeyPressed (int row)
  59520. {
  59521. flipEnablement (row);
  59522. }
  59523. void paint (Graphics& g)
  59524. {
  59525. ListBox::paint (g);
  59526. if (items.size() == 0)
  59527. {
  59528. g.setColour (Colours::grey);
  59529. g.setFont (13.0f);
  59530. g.drawText (noItemsMessage,
  59531. 0, 0, getWidth(), getHeight() / 2,
  59532. Justification::centred, true);
  59533. }
  59534. }
  59535. int getBestHeight (int maxHeight)
  59536. {
  59537. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  59538. getNumRows())
  59539. + getOutlineThickness() * 2;
  59540. }
  59541. juce_UseDebuggingNewOperator
  59542. private:
  59543. const AudioIODeviceType::DeviceSetupDetails setup;
  59544. const BoxType type;
  59545. const String noItemsMessage;
  59546. StringArray items;
  59547. void flipEnablement (const int row)
  59548. {
  59549. jassert (type == audioInputType || type == audioOutputType);
  59550. if (((unsigned int) row) < (unsigned int) items.size())
  59551. {
  59552. AudioDeviceManager::AudioDeviceSetup config;
  59553. setup.manager->getAudioDeviceSetup (config);
  59554. if (setup.useStereoPairs)
  59555. {
  59556. BigInteger bits;
  59557. BigInteger& original = (type == audioInputType ? config.inputChannels
  59558. : config.outputChannels);
  59559. int i;
  59560. for (i = 0; i < 256; i += 2)
  59561. bits.setBit (i / 2, original [i] || original [i + 1]);
  59562. if (type == audioInputType)
  59563. {
  59564. config.useDefaultInputChannels = false;
  59565. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  59566. }
  59567. else
  59568. {
  59569. config.useDefaultOutputChannels = false;
  59570. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  59571. }
  59572. for (i = 0; i < 256; ++i)
  59573. original.setBit (i, bits [i / 2]);
  59574. }
  59575. else
  59576. {
  59577. if (type == audioInputType)
  59578. {
  59579. config.useDefaultInputChannels = false;
  59580. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  59581. }
  59582. else
  59583. {
  59584. config.useDefaultOutputChannels = false;
  59585. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  59586. }
  59587. }
  59588. String error (setup.manager->setAudioDeviceSetup (config, true));
  59589. if (! error.isEmpty())
  59590. {
  59591. //xxx
  59592. }
  59593. }
  59594. }
  59595. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  59596. {
  59597. const int numActive = chans.countNumberOfSetBits();
  59598. if (chans [index])
  59599. {
  59600. if (numActive > minNumber)
  59601. chans.setBit (index, false);
  59602. }
  59603. else
  59604. {
  59605. if (numActive >= maxNumber)
  59606. {
  59607. const int firstActiveChan = chans.findNextSetBit();
  59608. chans.setBit (index > firstActiveChan
  59609. ? firstActiveChan : chans.getHighestBit(),
  59610. false);
  59611. }
  59612. chans.setBit (index, true);
  59613. }
  59614. }
  59615. int getTickX() const
  59616. {
  59617. return getRowHeight() + 5;
  59618. }
  59619. ChannelSelectorListBox (const ChannelSelectorListBox&);
  59620. ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  59621. };
  59622. private:
  59623. ScopedPointer<ChannelSelectorListBox> inputChanList, outputChanList;
  59624. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  59625. AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  59626. };
  59627. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  59628. const int minInputChannels_,
  59629. const int maxInputChannels_,
  59630. const int minOutputChannels_,
  59631. const int maxOutputChannels_,
  59632. const bool showMidiInputOptions,
  59633. const bool showMidiOutputSelector,
  59634. const bool showChannelsAsStereoPairs_,
  59635. const bool hideAdvancedOptionsWithButton_)
  59636. : deviceManager (deviceManager_),
  59637. deviceTypeDropDown (0),
  59638. deviceTypeDropDownLabel (0),
  59639. minOutputChannels (minOutputChannels_),
  59640. maxOutputChannels (maxOutputChannels_),
  59641. minInputChannels (minInputChannels_),
  59642. maxInputChannels (maxInputChannels_),
  59643. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  59644. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  59645. {
  59646. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  59647. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  59648. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  59649. {
  59650. deviceTypeDropDown = new ComboBox (String::empty);
  59651. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  59652. {
  59653. deviceTypeDropDown
  59654. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  59655. i + 1);
  59656. }
  59657. addAndMakeVisible (deviceTypeDropDown);
  59658. deviceTypeDropDown->addListener (this);
  59659. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  59660. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  59661. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  59662. }
  59663. if (showMidiInputOptions)
  59664. {
  59665. addAndMakeVisible (midiInputsList
  59666. = new MidiInputSelectorComponentListBox (deviceManager,
  59667. TRANS("(no midi inputs available)"),
  59668. 0, 0));
  59669. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  59670. midiInputsLabel->setJustificationType (Justification::topRight);
  59671. midiInputsLabel->attachToComponent (midiInputsList, true);
  59672. }
  59673. else
  59674. {
  59675. midiInputsList = 0;
  59676. midiInputsLabel = 0;
  59677. }
  59678. if (showMidiOutputSelector)
  59679. {
  59680. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  59681. midiOutputSelector->addListener (this);
  59682. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  59683. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  59684. }
  59685. else
  59686. {
  59687. midiOutputSelector = 0;
  59688. midiOutputLabel = 0;
  59689. }
  59690. deviceManager_.addChangeListener (this);
  59691. changeListenerCallback (0);
  59692. }
  59693. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  59694. {
  59695. deviceManager.removeChangeListener (this);
  59696. }
  59697. void AudioDeviceSelectorComponent::resized()
  59698. {
  59699. const int lx = proportionOfWidth (0.35f);
  59700. const int w = proportionOfWidth (0.4f);
  59701. const int h = 24;
  59702. const int space = 6;
  59703. const int dh = h + space;
  59704. int y = 15;
  59705. if (deviceTypeDropDown != 0)
  59706. {
  59707. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  59708. y += dh + space * 2;
  59709. }
  59710. if (audioDeviceSettingsComp != 0)
  59711. {
  59712. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  59713. y += audioDeviceSettingsComp->getHeight() + space;
  59714. }
  59715. if (midiInputsList != 0)
  59716. {
  59717. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  59718. midiInputsList->setBounds (lx, y, w, bh);
  59719. y += bh + space;
  59720. }
  59721. if (midiOutputSelector != 0)
  59722. midiOutputSelector->setBounds (lx, y, w, h);
  59723. }
  59724. void AudioDeviceSelectorComponent::childBoundsChanged (Component* child)
  59725. {
  59726. if (child == audioDeviceSettingsComp)
  59727. resized();
  59728. }
  59729. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  59730. {
  59731. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  59732. if (device != 0 && device->hasControlPanel())
  59733. {
  59734. if (device->showControlPanel())
  59735. deviceManager.restartLastAudioDevice();
  59736. getTopLevelComponent()->toFront (true);
  59737. }
  59738. }
  59739. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  59740. {
  59741. if (comboBoxThatHasChanged == deviceTypeDropDown)
  59742. {
  59743. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  59744. if (type != 0)
  59745. {
  59746. audioDeviceSettingsComp = 0;
  59747. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  59748. changeListenerCallback (0); // needed in case the type hasn't actally changed
  59749. }
  59750. }
  59751. else if (comboBoxThatHasChanged == midiOutputSelector)
  59752. {
  59753. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  59754. }
  59755. }
  59756. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  59757. {
  59758. if (deviceTypeDropDown != 0)
  59759. {
  59760. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  59761. }
  59762. if (audioDeviceSettingsComp == 0
  59763. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  59764. {
  59765. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  59766. audioDeviceSettingsComp = 0;
  59767. AudioIODeviceType* const type
  59768. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  59769. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  59770. if (type != 0)
  59771. {
  59772. AudioIODeviceType::DeviceSetupDetails details;
  59773. details.manager = &deviceManager;
  59774. details.minNumInputChannels = minInputChannels;
  59775. details.maxNumInputChannels = maxInputChannels;
  59776. details.minNumOutputChannels = minOutputChannels;
  59777. details.maxNumOutputChannels = maxOutputChannels;
  59778. details.useStereoPairs = showChannelsAsStereoPairs;
  59779. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  59780. if (audioDeviceSettingsComp != 0)
  59781. {
  59782. addAndMakeVisible (audioDeviceSettingsComp);
  59783. audioDeviceSettingsComp->resized();
  59784. }
  59785. }
  59786. }
  59787. if (midiInputsList != 0)
  59788. {
  59789. midiInputsList->updateContent();
  59790. midiInputsList->repaint();
  59791. }
  59792. if (midiOutputSelector != 0)
  59793. {
  59794. midiOutputSelector->clear();
  59795. const StringArray midiOuts (MidiOutput::getDevices());
  59796. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  59797. midiOutputSelector->addSeparator();
  59798. for (int i = 0; i < midiOuts.size(); ++i)
  59799. midiOutputSelector->addItem (midiOuts[i], i + 1);
  59800. int current = -1;
  59801. if (deviceManager.getDefaultMidiOutput() != 0)
  59802. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  59803. midiOutputSelector->setSelectedId (current, true);
  59804. }
  59805. resized();
  59806. }
  59807. END_JUCE_NAMESPACE
  59808. /*** End of inlined file: juce_AudioDeviceSelectorComponent.cpp ***/
  59809. /*** Start of inlined file: juce_BubbleComponent.cpp ***/
  59810. BEGIN_JUCE_NAMESPACE
  59811. BubbleComponent::BubbleComponent()
  59812. : side (0),
  59813. allowablePlacements (above | below | left | right),
  59814. arrowTipX (0.0f),
  59815. arrowTipY (0.0f)
  59816. {
  59817. setInterceptsMouseClicks (false, false);
  59818. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  59819. setComponentEffect (&shadow);
  59820. }
  59821. BubbleComponent::~BubbleComponent()
  59822. {
  59823. }
  59824. void BubbleComponent::paint (Graphics& g)
  59825. {
  59826. int x = content.getX();
  59827. int y = content.getY();
  59828. int w = content.getWidth();
  59829. int h = content.getHeight();
  59830. int cw, ch;
  59831. getContentSize (cw, ch);
  59832. if (side == 3)
  59833. x += w - cw;
  59834. else if (side != 1)
  59835. x += (w - cw) / 2;
  59836. w = cw;
  59837. if (side == 2)
  59838. y += h - ch;
  59839. else if (side != 0)
  59840. y += (h - ch) / 2;
  59841. h = ch;
  59842. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  59843. (float) x, (float) y,
  59844. (float) w, (float) h);
  59845. const int cx = x + (w - cw) / 2;
  59846. const int cy = y + (h - ch) / 2;
  59847. const int indent = 3;
  59848. g.setOrigin (cx + indent, cy + indent);
  59849. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  59850. paintContent (g, cw - indent * 2, ch - indent * 2);
  59851. }
  59852. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  59853. {
  59854. allowablePlacements = newPlacement;
  59855. }
  59856. void BubbleComponent::setPosition (Component* componentToPointTo)
  59857. {
  59858. jassert (componentToPointTo->isValidComponent());
  59859. Point<int> pos;
  59860. if (getParentComponent() != 0)
  59861. pos = componentToPointTo->relativePositionToOtherComponent (getParentComponent(), pos);
  59862. else
  59863. pos = componentToPointTo->relativePositionToGlobal (pos);
  59864. setPosition (Rectangle<int> (pos.getX(), pos.getY(), componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  59865. }
  59866. void BubbleComponent::setPosition (const int arrowTipX_,
  59867. const int arrowTipY_)
  59868. {
  59869. setPosition (Rectangle<int> (arrowTipX_, arrowTipY_, 1, 1));
  59870. }
  59871. void BubbleComponent::setPosition (const Rectangle<int>& rectangleToPointTo)
  59872. {
  59873. Rectangle<int> availableSpace (getParentComponent() != 0 ? getParentComponent()->getLocalBounds()
  59874. : getParentMonitorArea());
  59875. int x = 0;
  59876. int y = 0;
  59877. int w = 150;
  59878. int h = 30;
  59879. getContentSize (w, h);
  59880. w += 30;
  59881. h += 30;
  59882. const float edgeIndent = 2.0f;
  59883. const int arrowLength = jmin (10, h / 3, w / 3);
  59884. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  59885. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  59886. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  59887. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  59888. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  59889. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  59890. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  59891. {
  59892. spaceLeft = spaceRight = 0;
  59893. }
  59894. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  59895. && (spaceLeft > w + 20 || spaceRight > w + 20))
  59896. {
  59897. spaceAbove = spaceBelow = 0;
  59898. }
  59899. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  59900. {
  59901. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  59902. arrowTipX = w * 0.5f;
  59903. content.setSize (w, h - arrowLength);
  59904. if (spaceAbove >= spaceBelow)
  59905. {
  59906. // above
  59907. y = rectangleToPointTo.getY() - h;
  59908. content.setPosition (0, 0);
  59909. arrowTipY = h - edgeIndent;
  59910. side = 2;
  59911. }
  59912. else
  59913. {
  59914. // below
  59915. y = rectangleToPointTo.getBottom();
  59916. content.setPosition (0, arrowLength);
  59917. arrowTipY = edgeIndent;
  59918. side = 0;
  59919. }
  59920. }
  59921. else
  59922. {
  59923. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  59924. arrowTipY = h * 0.5f;
  59925. content.setSize (w - arrowLength, h);
  59926. if (spaceLeft > spaceRight)
  59927. {
  59928. // on the left
  59929. x = rectangleToPointTo.getX() - w;
  59930. content.setPosition (0, 0);
  59931. arrowTipX = w - edgeIndent;
  59932. side = 3;
  59933. }
  59934. else
  59935. {
  59936. // on the right
  59937. x = rectangleToPointTo.getRight();
  59938. content.setPosition (arrowLength, 0);
  59939. arrowTipX = edgeIndent;
  59940. side = 1;
  59941. }
  59942. }
  59943. setBounds (x, y, w, h);
  59944. }
  59945. END_JUCE_NAMESPACE
  59946. /*** End of inlined file: juce_BubbleComponent.cpp ***/
  59947. /*** Start of inlined file: juce_BubbleMessageComponent.cpp ***/
  59948. BEGIN_JUCE_NAMESPACE
  59949. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  59950. : fadeOutLength (fadeOutLengthMs),
  59951. deleteAfterUse (false)
  59952. {
  59953. }
  59954. BubbleMessageComponent::~BubbleMessageComponent()
  59955. {
  59956. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  59957. }
  59958. void BubbleMessageComponent::showAt (int x, int y,
  59959. const String& text,
  59960. const int numMillisecondsBeforeRemoving,
  59961. const bool removeWhenMouseClicked,
  59962. const bool deleteSelfAfterUse)
  59963. {
  59964. textLayout.clear();
  59965. textLayout.setText (text, Font (14.0f));
  59966. textLayout.layout (256, Justification::centredLeft, true);
  59967. setPosition (x, y);
  59968. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59969. }
  59970. void BubbleMessageComponent::showAt (Component* const component,
  59971. const String& text,
  59972. const int numMillisecondsBeforeRemoving,
  59973. const bool removeWhenMouseClicked,
  59974. const bool deleteSelfAfterUse)
  59975. {
  59976. textLayout.clear();
  59977. textLayout.setText (text, Font (14.0f));
  59978. textLayout.layout (256, Justification::centredLeft, true);
  59979. setPosition (component);
  59980. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  59981. }
  59982. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  59983. const bool removeWhenMouseClicked,
  59984. const bool deleteSelfAfterUse)
  59985. {
  59986. setVisible (true);
  59987. deleteAfterUse = deleteSelfAfterUse;
  59988. if (numMillisecondsBeforeRemoving > 0)
  59989. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  59990. else
  59991. expiryTime = 0;
  59992. startTimer (77);
  59993. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  59994. if (! (removeWhenMouseClicked && isShowing()))
  59995. mouseClickCounter += 0xfffff;
  59996. repaint();
  59997. }
  59998. void BubbleMessageComponent::getContentSize (int& w, int& h)
  59999. {
  60000. w = textLayout.getWidth() + 16;
  60001. h = textLayout.getHeight() + 16;
  60002. }
  60003. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  60004. {
  60005. g.setColour (findColour (TooltipWindow::textColourId));
  60006. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  60007. }
  60008. void BubbleMessageComponent::timerCallback()
  60009. {
  60010. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  60011. {
  60012. stopTimer();
  60013. setVisible (false);
  60014. if (deleteAfterUse)
  60015. delete this;
  60016. }
  60017. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  60018. {
  60019. stopTimer();
  60020. if (deleteAfterUse)
  60021. delete this;
  60022. else
  60023. Desktop::getInstance().getAnimator().fadeOut (this, fadeOutLength);
  60024. }
  60025. }
  60026. END_JUCE_NAMESPACE
  60027. /*** End of inlined file: juce_BubbleMessageComponent.cpp ***/
  60028. /*** Start of inlined file: juce_ColourSelector.cpp ***/
  60029. BEGIN_JUCE_NAMESPACE
  60030. class ColourComponentSlider : public Slider
  60031. {
  60032. public:
  60033. ColourComponentSlider (const String& name)
  60034. : Slider (name)
  60035. {
  60036. setRange (0.0, 255.0, 1.0);
  60037. }
  60038. const String getTextFromValue (double value)
  60039. {
  60040. return String::toHexString ((int) value).toUpperCase().paddedLeft ('0', 2);
  60041. }
  60042. double getValueFromText (const String& text)
  60043. {
  60044. return (double) text.getHexValue32();
  60045. }
  60046. private:
  60047. ColourComponentSlider (const ColourComponentSlider&);
  60048. ColourComponentSlider& operator= (const ColourComponentSlider&);
  60049. };
  60050. class ColourSpaceMarker : public Component
  60051. {
  60052. public:
  60053. ColourSpaceMarker()
  60054. {
  60055. setInterceptsMouseClicks (false, false);
  60056. }
  60057. void paint (Graphics& g)
  60058. {
  60059. g.setColour (Colour::greyLevel (0.1f));
  60060. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  60061. g.setColour (Colour::greyLevel (0.9f));
  60062. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  60063. }
  60064. private:
  60065. ColourSpaceMarker (const ColourSpaceMarker&);
  60066. ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  60067. };
  60068. class ColourSelector::ColourSpaceView : public Component
  60069. {
  60070. public:
  60071. ColourSpaceView (ColourSelector& owner_,
  60072. float& h_, float& s_, float& v_,
  60073. const int edgeSize)
  60074. : owner (owner_),
  60075. h (h_), s (s_), v (v_),
  60076. lastHue (0.0f),
  60077. edge (edgeSize)
  60078. {
  60079. addAndMakeVisible (&marker);
  60080. setMouseCursor (MouseCursor::CrosshairCursor);
  60081. }
  60082. void paint (Graphics& g)
  60083. {
  60084. if (colours.isNull())
  60085. {
  60086. const int width = getWidth() / 2;
  60087. const int height = getHeight() / 2;
  60088. colours = Image (Image::RGB, width, height, false);
  60089. Image::BitmapData pixels (colours, true);
  60090. for (int y = 0; y < height; ++y)
  60091. {
  60092. const float val = 1.0f - y / (float) height;
  60093. for (int x = 0; x < width; ++x)
  60094. {
  60095. const float sat = x / (float) width;
  60096. pixels.setPixelColour (x, y, Colour (h, sat, val, 1.0f));
  60097. }
  60098. }
  60099. }
  60100. g.setOpacity (1.0f);
  60101. g.drawImage (colours, edge, edge, getWidth() - edge * 2, getHeight() - edge * 2,
  60102. 0, 0, colours.getWidth(), colours.getHeight());
  60103. }
  60104. void mouseDown (const MouseEvent& e)
  60105. {
  60106. mouseDrag (e);
  60107. }
  60108. void mouseDrag (const MouseEvent& e)
  60109. {
  60110. const float sat = (e.x - edge) / (float) (getWidth() - edge * 2);
  60111. const float val = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  60112. owner.setSV (sat, val);
  60113. }
  60114. void updateIfNeeded()
  60115. {
  60116. if (lastHue != h)
  60117. {
  60118. lastHue = h;
  60119. colours = Image::null;
  60120. repaint();
  60121. }
  60122. updateMarker();
  60123. }
  60124. void resized()
  60125. {
  60126. colours = Image::null;
  60127. updateMarker();
  60128. }
  60129. private:
  60130. ColourSelector& owner;
  60131. float& h;
  60132. float& s;
  60133. float& v;
  60134. float lastHue;
  60135. ColourSpaceMarker marker;
  60136. const int edge;
  60137. Image colours;
  60138. void updateMarker()
  60139. {
  60140. marker.setBounds (roundToInt ((getWidth() - edge * 2) * s),
  60141. roundToInt ((getHeight() - edge * 2) * (1.0f - v)),
  60142. edge * 2, edge * 2);
  60143. }
  60144. ColourSpaceView (const ColourSpaceView&);
  60145. ColourSpaceView& operator= (const ColourSpaceView&);
  60146. };
  60147. class HueSelectorMarker : public Component
  60148. {
  60149. public:
  60150. HueSelectorMarker()
  60151. {
  60152. setInterceptsMouseClicks (false, false);
  60153. }
  60154. void paint (Graphics& g)
  60155. {
  60156. Path p;
  60157. p.addTriangle (1.0f, 1.0f,
  60158. getWidth() * 0.3f, getHeight() * 0.5f,
  60159. 1.0f, getHeight() - 1.0f);
  60160. p.addTriangle (getWidth() - 1.0f, 1.0f,
  60161. getWidth() * 0.7f, getHeight() * 0.5f,
  60162. getWidth() - 1.0f, getHeight() - 1.0f);
  60163. g.setColour (Colours::white.withAlpha (0.75f));
  60164. g.fillPath (p);
  60165. g.setColour (Colours::black.withAlpha (0.75f));
  60166. g.strokePath (p, PathStrokeType (1.2f));
  60167. }
  60168. private:
  60169. HueSelectorMarker (const HueSelectorMarker&);
  60170. HueSelectorMarker& operator= (const HueSelectorMarker&);
  60171. };
  60172. class ColourSelector::HueSelectorComp : public Component
  60173. {
  60174. public:
  60175. HueSelectorComp (ColourSelector& owner_,
  60176. float& h_, float& s_, float& v_,
  60177. const int edgeSize)
  60178. : owner (owner_),
  60179. h (h_), s (s_), v (v_),
  60180. lastHue (0.0f),
  60181. edge (edgeSize)
  60182. {
  60183. addAndMakeVisible (&marker);
  60184. }
  60185. void paint (Graphics& g)
  60186. {
  60187. const float yScale = 1.0f / (getHeight() - edge * 2);
  60188. const Rectangle<int> clip (g.getClipBounds());
  60189. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  60190. {
  60191. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  60192. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  60193. }
  60194. }
  60195. void resized()
  60196. {
  60197. marker.setBounds (0, roundToInt ((getHeight() - edge * 2) * h),
  60198. getWidth(), edge * 2);
  60199. }
  60200. void mouseDown (const MouseEvent& e)
  60201. {
  60202. mouseDrag (e);
  60203. }
  60204. void mouseDrag (const MouseEvent& e)
  60205. {
  60206. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  60207. owner.setHue (hue);
  60208. }
  60209. void updateIfNeeded()
  60210. {
  60211. resized();
  60212. }
  60213. private:
  60214. ColourSelector& owner;
  60215. float& h;
  60216. float& s;
  60217. float& v;
  60218. float lastHue;
  60219. HueSelectorMarker marker;
  60220. const int edge;
  60221. HueSelectorComp (const HueSelectorComp&);
  60222. HueSelectorComp& operator= (const HueSelectorComp&);
  60223. };
  60224. class ColourSelector::SwatchComponent : public Component
  60225. {
  60226. public:
  60227. SwatchComponent (ColourSelector& owner_, int index_)
  60228. : owner (owner_), index (index_)
  60229. {
  60230. }
  60231. void paint (Graphics& g)
  60232. {
  60233. const Colour colour (owner.getSwatchColour (index));
  60234. g.fillCheckerBoard (getLocalBounds(), 6, 6,
  60235. Colour (0xffdddddd).overlaidWith (colour),
  60236. Colour (0xffffffff).overlaidWith (colour));
  60237. }
  60238. void mouseDown (const MouseEvent&)
  60239. {
  60240. PopupMenu m;
  60241. m.addItem (1, TRANS("Use this swatch as the current colour"));
  60242. m.addSeparator();
  60243. m.addItem (2, TRANS("Set this swatch to the current colour"));
  60244. const int r = m.showAt (this);
  60245. if (r == 1)
  60246. {
  60247. owner.setCurrentColour (owner.getSwatchColour (index));
  60248. }
  60249. else if (r == 2)
  60250. {
  60251. if (owner.getSwatchColour (index) != owner.getCurrentColour())
  60252. {
  60253. owner.setSwatchColour (index, owner.getCurrentColour());
  60254. repaint();
  60255. }
  60256. }
  60257. }
  60258. private:
  60259. ColourSelector& owner;
  60260. const int index;
  60261. SwatchComponent (const SwatchComponent&);
  60262. SwatchComponent& operator= (const SwatchComponent&);
  60263. };
  60264. ColourSelector::ColourSelector (const int flags_,
  60265. const int edgeGap_,
  60266. const int gapAroundColourSpaceComponent)
  60267. : colour (Colours::white),
  60268. colourSpace (0),
  60269. hueSelector (0),
  60270. flags (flags_),
  60271. edgeGap (edgeGap_)
  60272. {
  60273. // not much point having a selector with no components in it!
  60274. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  60275. updateHSV();
  60276. if ((flags & showSliders) != 0)
  60277. {
  60278. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  60279. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  60280. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  60281. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  60282. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  60283. for (int i = 4; --i >= 0;)
  60284. sliders[i]->addListener (this);
  60285. }
  60286. else
  60287. {
  60288. zeromem (sliders, sizeof (sliders));
  60289. }
  60290. if ((flags & showColourspace) != 0)
  60291. {
  60292. addAndMakeVisible (colourSpace = new ColourSpaceView (*this, h, s, v, gapAroundColourSpaceComponent));
  60293. addAndMakeVisible (hueSelector = new HueSelectorComp (*this, h, s, v, gapAroundColourSpaceComponent));
  60294. }
  60295. update();
  60296. }
  60297. ColourSelector::~ColourSelector()
  60298. {
  60299. dispatchPendingMessages();
  60300. swatchComponents.clear();
  60301. deleteAllChildren();
  60302. }
  60303. const Colour ColourSelector::getCurrentColour() const
  60304. {
  60305. return ((flags & showAlphaChannel) != 0) ? colour
  60306. : colour.withAlpha ((uint8) 0xff);
  60307. }
  60308. void ColourSelector::setCurrentColour (const Colour& c)
  60309. {
  60310. if (c != colour)
  60311. {
  60312. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  60313. updateHSV();
  60314. update();
  60315. }
  60316. }
  60317. void ColourSelector::setHue (float newH)
  60318. {
  60319. newH = jlimit (0.0f, 1.0f, newH);
  60320. if (h != newH)
  60321. {
  60322. h = newH;
  60323. colour = Colour (h, s, v, colour.getFloatAlpha());
  60324. update();
  60325. }
  60326. }
  60327. void ColourSelector::setSV (float newS, float newV)
  60328. {
  60329. newS = jlimit (0.0f, 1.0f, newS);
  60330. newV = jlimit (0.0f, 1.0f, newV);
  60331. if (s != newS || v != newV)
  60332. {
  60333. s = newS;
  60334. v = newV;
  60335. colour = Colour (h, s, v, colour.getFloatAlpha());
  60336. update();
  60337. }
  60338. }
  60339. void ColourSelector::updateHSV()
  60340. {
  60341. colour.getHSB (h, s, v);
  60342. }
  60343. void ColourSelector::update()
  60344. {
  60345. if (sliders[0] != 0)
  60346. {
  60347. sliders[0]->setValue ((int) colour.getRed());
  60348. sliders[1]->setValue ((int) colour.getGreen());
  60349. sliders[2]->setValue ((int) colour.getBlue());
  60350. sliders[3]->setValue ((int) colour.getAlpha());
  60351. }
  60352. if (colourSpace != 0)
  60353. {
  60354. colourSpace->updateIfNeeded();
  60355. hueSelector->updateIfNeeded();
  60356. }
  60357. if ((flags & showColourAtTop) != 0)
  60358. repaint (previewArea);
  60359. sendChangeMessage (this);
  60360. }
  60361. void ColourSelector::paint (Graphics& g)
  60362. {
  60363. g.fillAll (findColour (backgroundColourId));
  60364. if ((flags & showColourAtTop) != 0)
  60365. {
  60366. const Colour currentColour (getCurrentColour());
  60367. g.fillCheckerBoard (previewArea, 10, 10,
  60368. Colour (0xffdddddd).overlaidWith (currentColour),
  60369. Colour (0xffffffff).overlaidWith (currentColour));
  60370. g.setColour (Colours::white.overlaidWith (currentColour).contrasting());
  60371. g.setFont (14.0f, true);
  60372. g.drawText (currentColour.toDisplayString ((flags & showAlphaChannel) != 0),
  60373. previewArea.getX(), previewArea.getY(), previewArea.getWidth(), previewArea.getHeight(),
  60374. Justification::centred, false);
  60375. }
  60376. if ((flags & showSliders) != 0)
  60377. {
  60378. g.setColour (findColour (labelTextColourId));
  60379. g.setFont (11.0f);
  60380. for (int i = 4; --i >= 0;)
  60381. {
  60382. if (sliders[i]->isVisible())
  60383. g.drawText (sliders[i]->getName() + ":",
  60384. 0, sliders[i]->getY(),
  60385. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  60386. Justification::centredRight, false);
  60387. }
  60388. }
  60389. }
  60390. void ColourSelector::resized()
  60391. {
  60392. const int swatchesPerRow = 8;
  60393. const int swatchHeight = 22;
  60394. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  60395. const int numSwatches = getNumSwatches();
  60396. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  60397. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  60398. const int topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  60399. previewArea.setBounds (edgeGap, edgeGap, getWidth() - edgeGap * 2, topSpace - edgeGap * 2);
  60400. int y = topSpace;
  60401. if ((flags & showColourspace) != 0)
  60402. {
  60403. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  60404. colourSpace->setBounds (edgeGap, y,
  60405. getWidth() - hueWidth - edgeGap - 4,
  60406. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  60407. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  60408. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  60409. colourSpace->getHeight());
  60410. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  60411. }
  60412. if ((flags & showSliders) != 0)
  60413. {
  60414. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  60415. for (int i = 0; i < numSliders; ++i)
  60416. {
  60417. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  60418. proportionOfWidth (0.72f), sliderHeight - 2);
  60419. y += sliderHeight;
  60420. }
  60421. }
  60422. if (numSwatches > 0)
  60423. {
  60424. const int startX = 8;
  60425. const int xGap = 4;
  60426. const int yGap = 4;
  60427. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  60428. y += edgeGap;
  60429. if (swatchComponents.size() != numSwatches)
  60430. {
  60431. swatchComponents.clear();
  60432. for (int i = 0; i < numSwatches; ++i)
  60433. {
  60434. SwatchComponent* const sc = new SwatchComponent (*this, i);
  60435. swatchComponents.add (sc);
  60436. addAndMakeVisible (sc);
  60437. }
  60438. }
  60439. int x = startX;
  60440. for (int i = 0; i < swatchComponents.size(); ++i)
  60441. {
  60442. SwatchComponent* const sc = swatchComponents.getUnchecked(i);
  60443. sc->setBounds (x + xGap / 2,
  60444. y + yGap / 2,
  60445. swatchWidth - xGap,
  60446. swatchHeight - yGap);
  60447. if (((i + 1) % swatchesPerRow) == 0)
  60448. {
  60449. x = startX;
  60450. y += swatchHeight;
  60451. }
  60452. else
  60453. {
  60454. x += swatchWidth;
  60455. }
  60456. }
  60457. }
  60458. }
  60459. void ColourSelector::sliderValueChanged (Slider*)
  60460. {
  60461. if (sliders[0] != 0)
  60462. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  60463. (uint8) sliders[1]->getValue(),
  60464. (uint8) sliders[2]->getValue(),
  60465. (uint8) sliders[3]->getValue()));
  60466. }
  60467. int ColourSelector::getNumSwatches() const
  60468. {
  60469. return 0;
  60470. }
  60471. const Colour ColourSelector::getSwatchColour (const int) const
  60472. {
  60473. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60474. return Colours::black;
  60475. }
  60476. void ColourSelector::setSwatchColour (const int, const Colour&) const
  60477. {
  60478. jassertfalse; // if you've overridden getNumSwatches(), you also need to implement this method
  60479. }
  60480. END_JUCE_NAMESPACE
  60481. /*** End of inlined file: juce_ColourSelector.cpp ***/
  60482. /*** Start of inlined file: juce_DropShadower.cpp ***/
  60483. BEGIN_JUCE_NAMESPACE
  60484. class ShadowWindow : public Component
  60485. {
  60486. Component* owner;
  60487. Image shadowImageSections [12];
  60488. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  60489. public:
  60490. ShadowWindow (Component* const owner_,
  60491. const int type_,
  60492. const Image shadowImageSections_ [12])
  60493. : owner (owner_),
  60494. type (type_)
  60495. {
  60496. for (int i = 0; i < numElementsInArray (shadowImageSections); ++i)
  60497. shadowImageSections [i] = shadowImageSections_ [i];
  60498. setInterceptsMouseClicks (false, false);
  60499. if (owner_->isOnDesktop())
  60500. {
  60501. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  60502. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  60503. | ComponentPeer::windowIsTemporary
  60504. | ComponentPeer::windowIgnoresKeyPresses);
  60505. }
  60506. else if (owner_->getParentComponent() != 0)
  60507. {
  60508. owner_->getParentComponent()->addChildComponent (this);
  60509. }
  60510. }
  60511. ~ShadowWindow()
  60512. {
  60513. }
  60514. void paint (Graphics& g)
  60515. {
  60516. const Image& topLeft = shadowImageSections [type * 3];
  60517. const Image& bottomRight = shadowImageSections [type * 3 + 1];
  60518. const Image& filler = shadowImageSections [type * 3 + 2];
  60519. g.setOpacity (1.0f);
  60520. if (type < 2)
  60521. {
  60522. int imH = jmin (topLeft.getHeight(), getHeight() / 2);
  60523. g.drawImage (topLeft,
  60524. 0, 0, topLeft.getWidth(), imH,
  60525. 0, 0, topLeft.getWidth(), imH);
  60526. imH = jmin (bottomRight.getHeight(), getHeight() - getHeight() / 2);
  60527. g.drawImage (bottomRight,
  60528. 0, getHeight() - imH, bottomRight.getWidth(), imH,
  60529. 0, bottomRight.getHeight() - imH, bottomRight.getWidth(), imH);
  60530. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60531. g.fillRect (0, topLeft.getHeight(), getWidth(), getHeight() - (topLeft.getHeight() + bottomRight.getHeight()));
  60532. }
  60533. else
  60534. {
  60535. int imW = jmin (topLeft.getWidth(), getWidth() / 2);
  60536. g.drawImage (topLeft,
  60537. 0, 0, imW, topLeft.getHeight(),
  60538. 0, 0, imW, topLeft.getHeight());
  60539. imW = jmin (bottomRight.getWidth(), getWidth() - getWidth() / 2);
  60540. g.drawImage (bottomRight,
  60541. getWidth() - imW, 0, imW, bottomRight.getHeight(),
  60542. bottomRight.getWidth() - imW, 0, imW, bottomRight.getHeight());
  60543. g.setTiledImageFill (filler, 0, 0, 1.0f);
  60544. g.fillRect (topLeft.getWidth(), 0, getWidth() - (topLeft.getWidth() + bottomRight.getWidth()), getHeight());
  60545. }
  60546. }
  60547. void resized()
  60548. {
  60549. repaint(); // (needed for correct repainting)
  60550. }
  60551. private:
  60552. ShadowWindow (const ShadowWindow&);
  60553. ShadowWindow& operator= (const ShadowWindow&);
  60554. };
  60555. DropShadower::DropShadower (const float alpha_,
  60556. const int xOffset_,
  60557. const int yOffset_,
  60558. const float blurRadius_)
  60559. : owner (0),
  60560. numShadows (0),
  60561. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  60562. xOffset (xOffset_),
  60563. yOffset (yOffset_),
  60564. alpha (alpha_),
  60565. blurRadius (blurRadius_),
  60566. inDestructor (false),
  60567. reentrant (false)
  60568. {
  60569. }
  60570. DropShadower::~DropShadower()
  60571. {
  60572. if (owner != 0)
  60573. owner->removeComponentListener (this);
  60574. inDestructor = true;
  60575. deleteShadowWindows();
  60576. }
  60577. void DropShadower::deleteShadowWindows()
  60578. {
  60579. if (numShadows > 0)
  60580. {
  60581. int i;
  60582. for (i = numShadows; --i >= 0;)
  60583. delete shadowWindows[i];
  60584. numShadows = 0;
  60585. }
  60586. }
  60587. void DropShadower::setOwner (Component* componentToFollow)
  60588. {
  60589. if (componentToFollow != owner)
  60590. {
  60591. if (owner != 0)
  60592. owner->removeComponentListener (this);
  60593. // (the component can't be null)
  60594. jassert (componentToFollow != 0);
  60595. owner = componentToFollow;
  60596. jassert (owner != 0);
  60597. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  60598. owner->addComponentListener (this);
  60599. updateShadows();
  60600. }
  60601. }
  60602. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  60603. {
  60604. updateShadows();
  60605. }
  60606. void DropShadower::componentBroughtToFront (Component&)
  60607. {
  60608. bringShadowWindowsToFront();
  60609. }
  60610. void DropShadower::componentChildrenChanged (Component&)
  60611. {
  60612. }
  60613. void DropShadower::componentParentHierarchyChanged (Component&)
  60614. {
  60615. deleteShadowWindows();
  60616. updateShadows();
  60617. }
  60618. void DropShadower::componentVisibilityChanged (Component&)
  60619. {
  60620. updateShadows();
  60621. }
  60622. void DropShadower::updateShadows()
  60623. {
  60624. if (reentrant || inDestructor || (owner == 0))
  60625. return;
  60626. reentrant = true;
  60627. ComponentPeer* const nw = owner->getPeer();
  60628. const bool isOwnerVisible = owner->isVisible()
  60629. && (nw == 0 || ! nw->isMinimised());
  60630. const bool createShadowWindows = numShadows == 0
  60631. && owner->getWidth() > 0
  60632. && owner->getHeight() > 0
  60633. && isOwnerVisible
  60634. && (Desktop::canUseSemiTransparentWindows()
  60635. || owner->getParentComponent() != 0);
  60636. if (createShadowWindows)
  60637. {
  60638. // keep a cached version of the image to save doing the gaussian too often
  60639. String imageId;
  60640. imageId << shadowEdge << ',' << xOffset << ',' << yOffset << ',' << alpha;
  60641. const int hash = imageId.hashCode();
  60642. Image bigIm (ImageCache::getFromHashCode (hash));
  60643. if (bigIm.isNull())
  60644. {
  60645. bigIm = Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true, Image::NativeImage);
  60646. Graphics bigG (bigIm);
  60647. bigG.setColour (Colours::black.withAlpha (alpha));
  60648. bigG.fillRect (shadowEdge + xOffset,
  60649. shadowEdge + yOffset,
  60650. bigIm.getWidth() - (shadowEdge * 2),
  60651. bigIm.getHeight() - (shadowEdge * 2));
  60652. ImageConvolutionKernel blurKernel (roundToInt (blurRadius * 2.0f));
  60653. blurKernel.createGaussianBlur (blurRadius);
  60654. blurKernel.applyToImage (bigIm, bigIm,
  60655. Rectangle<int> (xOffset, yOffset,
  60656. bigIm.getWidth(), bigIm.getHeight()));
  60657. ImageCache::addImageToCache (bigIm, hash);
  60658. }
  60659. const int iw = bigIm.getWidth();
  60660. const int ih = bigIm.getHeight();
  60661. const int shadowEdge2 = shadowEdge * 2;
  60662. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  60663. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  60664. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  60665. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  60666. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  60667. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  60668. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  60669. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  60670. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  60671. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  60672. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  60673. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  60674. for (int i = 0; i < 4; ++i)
  60675. {
  60676. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  60677. ++numShadows;
  60678. }
  60679. }
  60680. if (numShadows > 0)
  60681. {
  60682. for (int i = numShadows; --i >= 0;)
  60683. {
  60684. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  60685. shadowWindows[i]->setVisible (isOwnerVisible);
  60686. }
  60687. const int x = owner->getX();
  60688. const int y = owner->getY() - shadowEdge;
  60689. const int w = owner->getWidth();
  60690. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  60691. shadowWindows[0]->setBounds (x - shadowEdge,
  60692. y,
  60693. shadowEdge,
  60694. h);
  60695. shadowWindows[1]->setBounds (x + w,
  60696. y,
  60697. shadowEdge,
  60698. h);
  60699. shadowWindows[2]->setBounds (x,
  60700. y,
  60701. w,
  60702. shadowEdge);
  60703. shadowWindows[3]->setBounds (x,
  60704. owner->getBottom(),
  60705. w,
  60706. shadowEdge);
  60707. }
  60708. reentrant = false;
  60709. if (createShadowWindows)
  60710. bringShadowWindowsToFront();
  60711. }
  60712. void DropShadower::setShadowImage (const Image& src, const int num, const int w, const int h,
  60713. const int sx, const int sy)
  60714. {
  60715. shadowImageSections[num] = Image (Image::ARGB, w, h, true, Image::NativeImage);
  60716. Graphics g (shadowImageSections[num]);
  60717. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  60718. }
  60719. void DropShadower::bringShadowWindowsToFront()
  60720. {
  60721. if (! (inDestructor || reentrant))
  60722. {
  60723. updateShadows();
  60724. reentrant = true;
  60725. for (int i = numShadows; --i >= 0;)
  60726. shadowWindows[i]->toBehind (owner);
  60727. reentrant = false;
  60728. }
  60729. }
  60730. END_JUCE_NAMESPACE
  60731. /*** End of inlined file: juce_DropShadower.cpp ***/
  60732. /*** Start of inlined file: juce_MagnifierComponent.cpp ***/
  60733. BEGIN_JUCE_NAMESPACE
  60734. class MagnifyingPeer : public ComponentPeer
  60735. {
  60736. public:
  60737. MagnifyingPeer (Component* const component_,
  60738. MagnifierComponent* const magnifierComp_)
  60739. : ComponentPeer (component_, 0),
  60740. magnifierComp (magnifierComp_)
  60741. {
  60742. }
  60743. ~MagnifyingPeer()
  60744. {
  60745. }
  60746. void* getNativeHandle() const { return 0; }
  60747. void setVisible (bool) {}
  60748. void setTitle (const String&) {}
  60749. void setPosition (int, int) {}
  60750. void setSize (int, int) {}
  60751. void setBounds (int, int, int, int, bool) {}
  60752. void setMinimised (bool) {}
  60753. void setAlpha (float /*newAlpha*/) {}
  60754. bool isMinimised() const { return false; }
  60755. void setFullScreen (bool) {}
  60756. bool isFullScreen() const { return false; }
  60757. const BorderSize getFrameSize() const { return BorderSize (0); }
  60758. bool setAlwaysOnTop (bool) { return true; }
  60759. void toFront (bool) {}
  60760. void toBehind (ComponentPeer*) {}
  60761. void setIcon (const Image&) {}
  60762. bool isFocused() const
  60763. {
  60764. return magnifierComp->hasKeyboardFocus (true);
  60765. }
  60766. void grabFocus()
  60767. {
  60768. ComponentPeer* peer = magnifierComp->getPeer();
  60769. if (peer != 0)
  60770. peer->grabFocus();
  60771. }
  60772. void textInputRequired (const Point<int>& position)
  60773. {
  60774. ComponentPeer* peer = magnifierComp->getPeer();
  60775. if (peer != 0)
  60776. peer->textInputRequired (position);
  60777. }
  60778. const Rectangle<int> getBounds() const
  60779. {
  60780. return Rectangle<int> (magnifierComp->getScreenX(), magnifierComp->getScreenY(),
  60781. component->getWidth(), component->getHeight());
  60782. }
  60783. const Point<int> getScreenPosition() const
  60784. {
  60785. return magnifierComp->getScreenPosition();
  60786. }
  60787. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  60788. {
  60789. const double zoom = magnifierComp->getScaleFactor();
  60790. return magnifierComp->relativePositionToGlobal (Point<int> (roundToInt (relativePosition.getX() * zoom),
  60791. roundToInt (relativePosition.getY() * zoom)));
  60792. }
  60793. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  60794. {
  60795. const Point<int> p (magnifierComp->globalPositionToRelative (screenPosition));
  60796. const double zoom = magnifierComp->getScaleFactor();
  60797. return Point<int> (roundToInt (p.getX() / zoom),
  60798. roundToInt (p.getY() / zoom));
  60799. }
  60800. bool contains (const Point<int>& position, bool) const
  60801. {
  60802. return ((unsigned int) position.getX()) < (unsigned int) magnifierComp->getWidth()
  60803. && ((unsigned int) position.getY()) < (unsigned int) magnifierComp->getHeight();
  60804. }
  60805. void repaint (const Rectangle<int>& area)
  60806. {
  60807. const double zoom = magnifierComp->getScaleFactor();
  60808. magnifierComp->repaint ((int) (area.getX() * zoom),
  60809. (int) (area.getY() * zoom),
  60810. roundToInt (area.getWidth() * zoom) + 1,
  60811. roundToInt (area.getHeight() * zoom) + 1);
  60812. }
  60813. void performAnyPendingRepaintsNow()
  60814. {
  60815. }
  60816. juce_UseDebuggingNewOperator
  60817. private:
  60818. MagnifierComponent* const magnifierComp;
  60819. MagnifyingPeer (const MagnifyingPeer&);
  60820. MagnifyingPeer& operator= (const MagnifyingPeer&);
  60821. };
  60822. class PeerHolderComp : public Component
  60823. {
  60824. public:
  60825. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  60826. : magnifierComp (magnifierComp_)
  60827. {
  60828. setVisible (true);
  60829. }
  60830. ~PeerHolderComp()
  60831. {
  60832. }
  60833. ComponentPeer* createNewPeer (int, void*)
  60834. {
  60835. return new MagnifyingPeer (this, magnifierComp);
  60836. }
  60837. void childBoundsChanged (Component* c)
  60838. {
  60839. if (c != 0)
  60840. {
  60841. setSize (c->getWidth(), c->getHeight());
  60842. magnifierComp->childBoundsChanged (this);
  60843. }
  60844. }
  60845. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60846. {
  60847. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  60848. Component* const p = magnifierComp->getParentComponent();
  60849. if (p != 0)
  60850. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  60851. }
  60852. private:
  60853. MagnifierComponent* const magnifierComp;
  60854. PeerHolderComp (const PeerHolderComp&);
  60855. PeerHolderComp& operator= (const PeerHolderComp&);
  60856. };
  60857. MagnifierComponent::MagnifierComponent (Component* const content_,
  60858. const bool deleteContentCompWhenNoLongerNeeded)
  60859. : content (content_),
  60860. scaleFactor (0.0),
  60861. peer (0),
  60862. deleteContent (deleteContentCompWhenNoLongerNeeded),
  60863. quality (Graphics::lowResamplingQuality),
  60864. mouseSource (0, true)
  60865. {
  60866. holderComp = new PeerHolderComp (this);
  60867. setScaleFactor (1.0);
  60868. }
  60869. MagnifierComponent::~MagnifierComponent()
  60870. {
  60871. delete holderComp;
  60872. if (deleteContent)
  60873. delete content;
  60874. }
  60875. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  60876. {
  60877. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  60878. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  60879. if (scaleFactor != newScaleFactor)
  60880. {
  60881. scaleFactor = newScaleFactor;
  60882. if (scaleFactor == 1.0)
  60883. {
  60884. holderComp->removeFromDesktop();
  60885. peer = 0;
  60886. addChildComponent (content);
  60887. childBoundsChanged (content);
  60888. }
  60889. else
  60890. {
  60891. holderComp->addAndMakeVisible (content);
  60892. holderComp->childBoundsChanged (content);
  60893. childBoundsChanged (holderComp);
  60894. holderComp->addToDesktop (0);
  60895. peer = holderComp->getPeer();
  60896. }
  60897. repaint();
  60898. }
  60899. }
  60900. void MagnifierComponent::setResamplingQuality (Graphics::ResamplingQuality newQuality)
  60901. {
  60902. quality = newQuality;
  60903. }
  60904. void MagnifierComponent::paint (Graphics& g)
  60905. {
  60906. const int w = holderComp->getWidth();
  60907. const int h = holderComp->getHeight();
  60908. if (w == 0 || h == 0)
  60909. return;
  60910. const Rectangle<int> r (g.getClipBounds());
  60911. const int srcX = (int) (r.getX() / scaleFactor);
  60912. const int srcY = (int) (r.getY() / scaleFactor);
  60913. int srcW = roundToInt (r.getRight() / scaleFactor) - srcX;
  60914. int srcH = roundToInt (r.getBottom() / scaleFactor) - srcY;
  60915. if (scaleFactor >= 1.0)
  60916. {
  60917. ++srcW;
  60918. ++srcH;
  60919. }
  60920. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  60921. const Rectangle<int> area (srcX, srcY, srcW, srcH);
  60922. temp.clear (area);
  60923. {
  60924. Graphics g2 (temp);
  60925. g2.reduceClipRegion (area);
  60926. holderComp->paintEntireComponent (g2, false);
  60927. }
  60928. g.setImageResamplingQuality (quality);
  60929. g.drawImageTransformed (temp, AffineTransform::scale ((float) scaleFactor, (float) scaleFactor), false);
  60930. }
  60931. void MagnifierComponent::childBoundsChanged (Component* c)
  60932. {
  60933. if (c != 0)
  60934. setSize (roundToInt (c->getWidth() * scaleFactor),
  60935. roundToInt (c->getHeight() * scaleFactor));
  60936. }
  60937. void MagnifierComponent::passOnMouseEventToPeer (const MouseEvent& e)
  60938. {
  60939. if (peer != 0)
  60940. mouseSource.handleEvent (peer, Point<int> (scaleInt (e.x), scaleInt (e.y)),
  60941. e.eventTime.toMilliseconds(), ModifierKeys::getCurrentModifiers());
  60942. }
  60943. void MagnifierComponent::mouseDown (const MouseEvent& e)
  60944. {
  60945. passOnMouseEventToPeer (e);
  60946. }
  60947. void MagnifierComponent::mouseUp (const MouseEvent& e)
  60948. {
  60949. passOnMouseEventToPeer (e);
  60950. }
  60951. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  60952. {
  60953. passOnMouseEventToPeer (e);
  60954. }
  60955. void MagnifierComponent::mouseMove (const MouseEvent& e)
  60956. {
  60957. passOnMouseEventToPeer (e);
  60958. }
  60959. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  60960. {
  60961. passOnMouseEventToPeer (e);
  60962. }
  60963. void MagnifierComponent::mouseExit (const MouseEvent& e)
  60964. {
  60965. passOnMouseEventToPeer (e);
  60966. }
  60967. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  60968. {
  60969. if (peer != 0)
  60970. peer->handleMouseWheel (e.source.getIndex(),
  60971. Point<int> (scaleInt (e.x), scaleInt (e.y)), e.eventTime.toMilliseconds(),
  60972. ix * 256.0f, iy * 256.0f);
  60973. else
  60974. Component::mouseWheelMove (e, ix, iy);
  60975. }
  60976. int MagnifierComponent::scaleInt (const int n) const
  60977. {
  60978. return roundToInt (n / scaleFactor);
  60979. }
  60980. END_JUCE_NAMESPACE
  60981. /*** End of inlined file: juce_MagnifierComponent.cpp ***/
  60982. /*** Start of inlined file: juce_MidiKeyboardComponent.cpp ***/
  60983. BEGIN_JUCE_NAMESPACE
  60984. class MidiKeyboardUpDownButton : public Button
  60985. {
  60986. public:
  60987. MidiKeyboardUpDownButton (MidiKeyboardComponent& owner_, const int delta_)
  60988. : Button (String::empty),
  60989. owner (owner_),
  60990. delta (delta_)
  60991. {
  60992. setOpaque (true);
  60993. }
  60994. void clicked()
  60995. {
  60996. int note = owner.getLowestVisibleKey();
  60997. if (delta < 0)
  60998. note = (note - 1) / 12;
  60999. else
  61000. note = note / 12 + 1;
  61001. owner.setLowestVisibleKey (note * 12);
  61002. }
  61003. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  61004. {
  61005. owner.drawUpDownButton (g, getWidth(), getHeight(),
  61006. isMouseOverButton, isButtonDown,
  61007. delta > 0);
  61008. }
  61009. private:
  61010. MidiKeyboardComponent& owner;
  61011. const int delta;
  61012. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  61013. MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  61014. };
  61015. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  61016. const Orientation orientation_)
  61017. : state (state_),
  61018. xOffset (0),
  61019. blackNoteLength (1),
  61020. keyWidth (16.0f),
  61021. orientation (orientation_),
  61022. midiChannel (1),
  61023. midiInChannelMask (0xffff),
  61024. velocity (1.0f),
  61025. noteUnderMouse (-1),
  61026. mouseDownNote (-1),
  61027. rangeStart (0),
  61028. rangeEnd (127),
  61029. firstKey (12 * 4),
  61030. canScroll (true),
  61031. mouseDragging (false),
  61032. useMousePositionForVelocity (true),
  61033. keyMappingOctave (6),
  61034. octaveNumForMiddleC (3)
  61035. {
  61036. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (*this, -1));
  61037. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (*this, 1));
  61038. // initialise with a default set of querty key-mappings..
  61039. const char* const keymap = "awsedftgyhujkolp;";
  61040. for (int i = String (keymap).length(); --i >= 0;)
  61041. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  61042. setOpaque (true);
  61043. setWantsKeyboardFocus (true);
  61044. state.addListener (this);
  61045. }
  61046. MidiKeyboardComponent::~MidiKeyboardComponent()
  61047. {
  61048. state.removeListener (this);
  61049. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  61050. }
  61051. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  61052. {
  61053. keyWidth = widthInPixels;
  61054. resized();
  61055. }
  61056. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  61057. {
  61058. if (orientation != newOrientation)
  61059. {
  61060. orientation = newOrientation;
  61061. resized();
  61062. }
  61063. }
  61064. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  61065. const int highestNote)
  61066. {
  61067. jassert (lowestNote >= 0 && lowestNote <= 127);
  61068. jassert (highestNote >= 0 && highestNote <= 127);
  61069. jassert (lowestNote <= highestNote);
  61070. if (rangeStart != lowestNote || rangeEnd != highestNote)
  61071. {
  61072. rangeStart = jlimit (0, 127, lowestNote);
  61073. rangeEnd = jlimit (0, 127, highestNote);
  61074. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  61075. resized();
  61076. }
  61077. }
  61078. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  61079. {
  61080. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  61081. if (noteNumber != firstKey)
  61082. {
  61083. firstKey = noteNumber;
  61084. sendChangeMessage (this);
  61085. resized();
  61086. }
  61087. }
  61088. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  61089. {
  61090. if (canScroll != canScroll_)
  61091. {
  61092. canScroll = canScroll_;
  61093. resized();
  61094. }
  61095. }
  61096. void MidiKeyboardComponent::colourChanged()
  61097. {
  61098. repaint();
  61099. }
  61100. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  61101. {
  61102. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  61103. if (midiChannel != midiChannelNumber)
  61104. {
  61105. resetAnyKeysInUse();
  61106. midiChannel = jlimit (1, 16, midiChannelNumber);
  61107. }
  61108. }
  61109. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  61110. {
  61111. midiInChannelMask = midiChannelMask;
  61112. triggerAsyncUpdate();
  61113. }
  61114. void MidiKeyboardComponent::setVelocity (const float velocity_, const bool useMousePositionForVelocity_)
  61115. {
  61116. velocity = jlimit (0.0f, 1.0f, velocity_);
  61117. useMousePositionForVelocity = useMousePositionForVelocity_;
  61118. }
  61119. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth_, int& x, int& w) const
  61120. {
  61121. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  61122. static const float blackNoteWidth = 0.7f;
  61123. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  61124. 1.0f, 2 - blackNoteWidth * 0.4f,
  61125. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  61126. 4.0f, 5 - blackNoteWidth * 0.5f,
  61127. 5.0f, 6 - blackNoteWidth * 0.3f,
  61128. 6.0f };
  61129. static const float widths[] = { 1.0f, blackNoteWidth,
  61130. 1.0f, blackNoteWidth,
  61131. 1.0f, 1.0f, blackNoteWidth,
  61132. 1.0f, blackNoteWidth,
  61133. 1.0f, blackNoteWidth,
  61134. 1.0f };
  61135. const int octave = midiNoteNumber / 12;
  61136. const int note = midiNoteNumber % 12;
  61137. x = roundToInt (octave * 7.0f * keyWidth_ + notePos [note] * keyWidth_);
  61138. w = roundToInt (widths [note] * keyWidth_);
  61139. }
  61140. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  61141. {
  61142. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  61143. int rx, rw;
  61144. getKeyPosition (rangeStart, keyWidth, rx, rw);
  61145. x -= xOffset + rx;
  61146. }
  61147. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  61148. {
  61149. int x, y;
  61150. getKeyPos (midiNoteNumber, x, y);
  61151. return x;
  61152. }
  61153. const uint8 MidiKeyboardComponent::whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  61154. const uint8 MidiKeyboardComponent::blackNotes[] = { 1, 3, 6, 8, 10 };
  61155. int MidiKeyboardComponent::xyToNote (const Point<int>& pos, float& mousePositionVelocity)
  61156. {
  61157. if (! reallyContains (pos.getX(), pos.getY(), false))
  61158. return -1;
  61159. Point<int> p (pos);
  61160. if (orientation != horizontalKeyboard)
  61161. {
  61162. p = Point<int> (p.getY(), p.getX());
  61163. if (orientation == verticalKeyboardFacingLeft)
  61164. p = Point<int> (p.getX(), getWidth() - p.getY());
  61165. else
  61166. p = Point<int> (getHeight() - p.getX(), p.getY());
  61167. }
  61168. return remappedXYToNote (p + Point<int> (xOffset, 0), mousePositionVelocity);
  61169. }
  61170. int MidiKeyboardComponent::remappedXYToNote (const Point<int>& pos, float& mousePositionVelocity) const
  61171. {
  61172. if (pos.getY() < blackNoteLength)
  61173. {
  61174. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61175. {
  61176. for (int i = 0; i < 5; ++i)
  61177. {
  61178. const int note = octaveStart + blackNotes [i];
  61179. if (note >= rangeStart && note <= rangeEnd)
  61180. {
  61181. int kx, kw;
  61182. getKeyPos (note, kx, kw);
  61183. kx += xOffset;
  61184. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61185. {
  61186. mousePositionVelocity = pos.getY() / (float) blackNoteLength;
  61187. return note;
  61188. }
  61189. }
  61190. }
  61191. }
  61192. }
  61193. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  61194. {
  61195. for (int i = 0; i < 7; ++i)
  61196. {
  61197. const int note = octaveStart + whiteNotes [i];
  61198. if (note >= rangeStart && note <= rangeEnd)
  61199. {
  61200. int kx, kw;
  61201. getKeyPos (note, kx, kw);
  61202. kx += xOffset;
  61203. if (pos.getX() >= kx && pos.getX() < kx + kw)
  61204. {
  61205. const int whiteNoteLength = (orientation == horizontalKeyboard) ? getHeight() : getWidth();
  61206. mousePositionVelocity = pos.getY() / (float) whiteNoteLength;
  61207. return note;
  61208. }
  61209. }
  61210. }
  61211. }
  61212. mousePositionVelocity = 0;
  61213. return -1;
  61214. }
  61215. void MidiKeyboardComponent::repaintNote (const int noteNum)
  61216. {
  61217. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61218. {
  61219. int x, w;
  61220. getKeyPos (noteNum, x, w);
  61221. if (orientation == horizontalKeyboard)
  61222. repaint (x, 0, w, getHeight());
  61223. else if (orientation == verticalKeyboardFacingLeft)
  61224. repaint (0, x, getWidth(), w);
  61225. else if (orientation == verticalKeyboardFacingRight)
  61226. repaint (0, getHeight() - x - w, getWidth(), w);
  61227. }
  61228. }
  61229. void MidiKeyboardComponent::paint (Graphics& g)
  61230. {
  61231. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  61232. const Colour lineColour (findColour (keySeparatorLineColourId));
  61233. const Colour textColour (findColour (textLabelColourId));
  61234. int x, w, octave;
  61235. for (octave = 0; octave < 128; octave += 12)
  61236. {
  61237. for (int white = 0; white < 7; ++white)
  61238. {
  61239. const int noteNum = octave + whiteNotes [white];
  61240. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61241. {
  61242. getKeyPos (noteNum, x, w);
  61243. if (orientation == horizontalKeyboard)
  61244. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  61245. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61246. noteUnderMouse == noteNum,
  61247. lineColour, textColour);
  61248. else if (orientation == verticalKeyboardFacingLeft)
  61249. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  61250. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61251. noteUnderMouse == noteNum,
  61252. lineColour, textColour);
  61253. else if (orientation == verticalKeyboardFacingRight)
  61254. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  61255. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61256. noteUnderMouse == noteNum,
  61257. lineColour, textColour);
  61258. }
  61259. }
  61260. }
  61261. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  61262. if (orientation == verticalKeyboardFacingLeft)
  61263. {
  61264. x1 = getWidth() - 1.0f;
  61265. x2 = getWidth() - 5.0f;
  61266. }
  61267. else if (orientation == verticalKeyboardFacingRight)
  61268. x2 = 5.0f;
  61269. else
  61270. y2 = 5.0f;
  61271. g.setGradientFill (ColourGradient (Colours::black.withAlpha (0.3f), x1, y1,
  61272. Colours::transparentBlack, x2, y2, false));
  61273. getKeyPos (rangeEnd, x, w);
  61274. x += w;
  61275. if (orientation == verticalKeyboardFacingLeft)
  61276. g.fillRect (getWidth() - 5, 0, 5, x);
  61277. else if (orientation == verticalKeyboardFacingRight)
  61278. g.fillRect (0, 0, 5, x);
  61279. else
  61280. g.fillRect (0, 0, x, 5);
  61281. g.setColour (lineColour);
  61282. if (orientation == verticalKeyboardFacingLeft)
  61283. g.fillRect (0, 0, 1, x);
  61284. else if (orientation == verticalKeyboardFacingRight)
  61285. g.fillRect (getWidth() - 1, 0, 1, x);
  61286. else
  61287. g.fillRect (0, getHeight() - 1, x, 1);
  61288. const Colour blackNoteColour (findColour (blackNoteColourId));
  61289. for (octave = 0; octave < 128; octave += 12)
  61290. {
  61291. for (int black = 0; black < 5; ++black)
  61292. {
  61293. const int noteNum = octave + blackNotes [black];
  61294. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  61295. {
  61296. getKeyPos (noteNum, x, w);
  61297. if (orientation == horizontalKeyboard)
  61298. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  61299. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61300. noteUnderMouse == noteNum,
  61301. blackNoteColour);
  61302. else if (orientation == verticalKeyboardFacingLeft)
  61303. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  61304. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61305. noteUnderMouse == noteNum,
  61306. blackNoteColour);
  61307. else if (orientation == verticalKeyboardFacingRight)
  61308. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  61309. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  61310. noteUnderMouse == noteNum,
  61311. blackNoteColour);
  61312. }
  61313. }
  61314. }
  61315. }
  61316. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  61317. Graphics& g, int x, int y, int w, int h,
  61318. bool isDown, bool isOver,
  61319. const Colour& lineColour,
  61320. const Colour& textColour)
  61321. {
  61322. Colour c (Colours::transparentWhite);
  61323. if (isDown)
  61324. c = findColour (keyDownOverlayColourId);
  61325. if (isOver)
  61326. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61327. g.setColour (c);
  61328. g.fillRect (x, y, w, h);
  61329. const String text (getWhiteNoteText (midiNoteNumber));
  61330. if (! text.isEmpty())
  61331. {
  61332. g.setColour (textColour);
  61333. Font f (jmin (12.0f, keyWidth * 0.9f));
  61334. f.setHorizontalScale (0.8f);
  61335. g.setFont (f);
  61336. Justification justification (Justification::centredBottom);
  61337. if (orientation == verticalKeyboardFacingLeft)
  61338. justification = Justification::centredLeft;
  61339. else if (orientation == verticalKeyboardFacingRight)
  61340. justification = Justification::centredRight;
  61341. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  61342. }
  61343. g.setColour (lineColour);
  61344. if (orientation == horizontalKeyboard)
  61345. g.fillRect (x, y, 1, h);
  61346. else if (orientation == verticalKeyboardFacingLeft)
  61347. g.fillRect (x, y, w, 1);
  61348. else if (orientation == verticalKeyboardFacingRight)
  61349. g.fillRect (x, y + h - 1, w, 1);
  61350. if (midiNoteNumber == rangeEnd)
  61351. {
  61352. if (orientation == horizontalKeyboard)
  61353. g.fillRect (x + w, y, 1, h);
  61354. else if (orientation == verticalKeyboardFacingLeft)
  61355. g.fillRect (x, y + h, w, 1);
  61356. else if (orientation == verticalKeyboardFacingRight)
  61357. g.fillRect (x, y - 1, w, 1);
  61358. }
  61359. }
  61360. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  61361. Graphics& g, int x, int y, int w, int h,
  61362. bool isDown, bool isOver,
  61363. const Colour& noteFillColour)
  61364. {
  61365. Colour c (noteFillColour);
  61366. if (isDown)
  61367. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  61368. if (isOver)
  61369. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  61370. g.setColour (c);
  61371. g.fillRect (x, y, w, h);
  61372. if (isDown)
  61373. {
  61374. g.setColour (noteFillColour);
  61375. g.drawRect (x, y, w, h);
  61376. }
  61377. else
  61378. {
  61379. const int xIndent = jmax (1, jmin (w, h) / 8);
  61380. g.setColour (c.brighter());
  61381. if (orientation == horizontalKeyboard)
  61382. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  61383. else if (orientation == verticalKeyboardFacingLeft)
  61384. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  61385. else if (orientation == verticalKeyboardFacingRight)
  61386. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  61387. }
  61388. }
  61389. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_)
  61390. {
  61391. octaveNumForMiddleC = octaveNumForMiddleC_;
  61392. repaint();
  61393. }
  61394. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  61395. {
  61396. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  61397. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  61398. return String::empty;
  61399. }
  61400. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  61401. const bool isMouseOver_,
  61402. const bool isButtonDown,
  61403. const bool movesOctavesUp)
  61404. {
  61405. g.fillAll (findColour (upDownButtonBackgroundColourId));
  61406. float angle;
  61407. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  61408. angle = movesOctavesUp ? 0.0f : 0.5f;
  61409. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  61410. angle = movesOctavesUp ? 0.25f : 0.75f;
  61411. else
  61412. angle = movesOctavesUp ? 0.75f : 0.25f;
  61413. Path path;
  61414. path.lineTo (0.0f, 1.0f);
  61415. path.lineTo (1.0f, 0.5f);
  61416. path.closeSubPath();
  61417. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  61418. g.setColour (findColour (upDownButtonArrowColourId)
  61419. .withAlpha (isButtonDown ? 1.0f : (isMouseOver_ ? 0.6f : 0.4f)));
  61420. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  61421. w - 2.0f,
  61422. h - 2.0f,
  61423. true));
  61424. }
  61425. void MidiKeyboardComponent::resized()
  61426. {
  61427. int w = getWidth();
  61428. int h = getHeight();
  61429. if (w > 0 && h > 0)
  61430. {
  61431. if (orientation != horizontalKeyboard)
  61432. swapVariables (w, h);
  61433. blackNoteLength = roundToInt (h * 0.7f);
  61434. int kx2, kw2;
  61435. getKeyPos (rangeEnd, kx2, kw2);
  61436. kx2 += kw2;
  61437. if (firstKey != rangeStart)
  61438. {
  61439. int kx1, kw1;
  61440. getKeyPos (rangeStart, kx1, kw1);
  61441. if (kx2 - kx1 <= w)
  61442. {
  61443. firstKey = rangeStart;
  61444. sendChangeMessage (this);
  61445. repaint();
  61446. }
  61447. }
  61448. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  61449. scrollDown->setVisible (showScrollButtons);
  61450. scrollUp->setVisible (showScrollButtons);
  61451. xOffset = 0;
  61452. if (showScrollButtons)
  61453. {
  61454. const int scrollButtonW = jmin (12, w / 2);
  61455. if (orientation == horizontalKeyboard)
  61456. {
  61457. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  61458. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  61459. }
  61460. else if (orientation == verticalKeyboardFacingLeft)
  61461. {
  61462. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  61463. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61464. }
  61465. else if (orientation == verticalKeyboardFacingRight)
  61466. {
  61467. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  61468. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  61469. }
  61470. int endOfLastKey, kw;
  61471. getKeyPos (rangeEnd, endOfLastKey, kw);
  61472. endOfLastKey += kw;
  61473. float mousePositionVelocity;
  61474. const int spaceAvailable = w - scrollButtonW * 2;
  61475. const int lastStartKey = remappedXYToNote (Point<int> (endOfLastKey - spaceAvailable, 0), mousePositionVelocity) + 1;
  61476. if (lastStartKey >= 0 && firstKey > lastStartKey)
  61477. {
  61478. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  61479. sendChangeMessage (this);
  61480. }
  61481. int newOffset = 0;
  61482. getKeyPos (firstKey, newOffset, kw);
  61483. xOffset = newOffset - scrollButtonW;
  61484. }
  61485. else
  61486. {
  61487. firstKey = rangeStart;
  61488. }
  61489. timerCallback();
  61490. repaint();
  61491. }
  61492. }
  61493. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  61494. {
  61495. triggerAsyncUpdate();
  61496. }
  61497. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  61498. {
  61499. triggerAsyncUpdate();
  61500. }
  61501. void MidiKeyboardComponent::handleAsyncUpdate()
  61502. {
  61503. for (int i = rangeStart; i <= rangeEnd; ++i)
  61504. {
  61505. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  61506. {
  61507. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  61508. repaintNote (i);
  61509. }
  61510. }
  61511. }
  61512. void MidiKeyboardComponent::resetAnyKeysInUse()
  61513. {
  61514. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  61515. {
  61516. state.allNotesOff (midiChannel);
  61517. keysPressed.clear();
  61518. mouseDownNote = -1;
  61519. }
  61520. }
  61521. void MidiKeyboardComponent::updateNoteUnderMouse (const Point<int>& pos)
  61522. {
  61523. float mousePositionVelocity = 0.0f;
  61524. const int newNote = (mouseDragging || isMouseOver())
  61525. ? xyToNote (pos, mousePositionVelocity) : -1;
  61526. if (noteUnderMouse != newNote)
  61527. {
  61528. if (mouseDownNote >= 0)
  61529. {
  61530. state.noteOff (midiChannel, mouseDownNote);
  61531. mouseDownNote = -1;
  61532. }
  61533. if (mouseDragging && newNote >= 0)
  61534. {
  61535. if (! useMousePositionForVelocity)
  61536. mousePositionVelocity = 1.0f;
  61537. state.noteOn (midiChannel, newNote, mousePositionVelocity * velocity);
  61538. mouseDownNote = newNote;
  61539. }
  61540. repaintNote (noteUnderMouse);
  61541. noteUnderMouse = newNote;
  61542. repaintNote (noteUnderMouse);
  61543. }
  61544. else if (mouseDownNote >= 0 && ! mouseDragging)
  61545. {
  61546. state.noteOff (midiChannel, mouseDownNote);
  61547. mouseDownNote = -1;
  61548. }
  61549. }
  61550. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  61551. {
  61552. updateNoteUnderMouse (e.getPosition());
  61553. stopTimer();
  61554. }
  61555. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  61556. {
  61557. float mousePositionVelocity;
  61558. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61559. if (newNote >= 0)
  61560. mouseDraggedToKey (newNote, e);
  61561. updateNoteUnderMouse (e.getPosition());
  61562. }
  61563. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  61564. {
  61565. return true;
  61566. }
  61567. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  61568. {
  61569. }
  61570. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  61571. {
  61572. float mousePositionVelocity;
  61573. const int newNote = xyToNote (e.getPosition(), mousePositionVelocity);
  61574. mouseDragging = false;
  61575. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  61576. {
  61577. repaintNote (noteUnderMouse);
  61578. noteUnderMouse = -1;
  61579. mouseDragging = true;
  61580. updateNoteUnderMouse (e.getPosition());
  61581. startTimer (500);
  61582. }
  61583. }
  61584. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  61585. {
  61586. mouseDragging = false;
  61587. updateNoteUnderMouse (e.getPosition());
  61588. stopTimer();
  61589. }
  61590. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  61591. {
  61592. updateNoteUnderMouse (e.getPosition());
  61593. }
  61594. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  61595. {
  61596. updateNoteUnderMouse (e.getPosition());
  61597. }
  61598. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  61599. {
  61600. setLowestVisibleKey (getLowestVisibleKey() + roundToInt ((ix != 0 ? ix : iy) * 5.0f));
  61601. }
  61602. void MidiKeyboardComponent::timerCallback()
  61603. {
  61604. updateNoteUnderMouse (getMouseXYRelative());
  61605. }
  61606. void MidiKeyboardComponent::clearKeyMappings()
  61607. {
  61608. resetAnyKeysInUse();
  61609. keyPressNotes.clear();
  61610. keyPresses.clear();
  61611. }
  61612. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  61613. const int midiNoteOffsetFromC)
  61614. {
  61615. removeKeyPressForNote (midiNoteOffsetFromC);
  61616. keyPressNotes.add (midiNoteOffsetFromC);
  61617. keyPresses.add (key);
  61618. }
  61619. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  61620. {
  61621. for (int i = keyPressNotes.size(); --i >= 0;)
  61622. {
  61623. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  61624. {
  61625. keyPressNotes.remove (i);
  61626. keyPresses.remove (i);
  61627. }
  61628. }
  61629. }
  61630. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  61631. {
  61632. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  61633. keyMappingOctave = newOctaveNumber;
  61634. }
  61635. bool MidiKeyboardComponent::keyStateChanged (const bool /*isKeyDown*/)
  61636. {
  61637. bool keyPressUsed = false;
  61638. for (int i = keyPresses.size(); --i >= 0;)
  61639. {
  61640. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  61641. if (keyPresses.getReference(i).isCurrentlyDown())
  61642. {
  61643. if (! keysPressed [note])
  61644. {
  61645. keysPressed.setBit (note);
  61646. state.noteOn (midiChannel, note, velocity);
  61647. keyPressUsed = true;
  61648. }
  61649. }
  61650. else
  61651. {
  61652. if (keysPressed [note])
  61653. {
  61654. keysPressed.clearBit (note);
  61655. state.noteOff (midiChannel, note);
  61656. keyPressUsed = true;
  61657. }
  61658. }
  61659. }
  61660. return keyPressUsed;
  61661. }
  61662. void MidiKeyboardComponent::focusLost (FocusChangeType)
  61663. {
  61664. resetAnyKeysInUse();
  61665. }
  61666. END_JUCE_NAMESPACE
  61667. /*** End of inlined file: juce_MidiKeyboardComponent.cpp ***/
  61668. /*** Start of inlined file: juce_OpenGLComponent.cpp ***/
  61669. #if JUCE_OPENGL
  61670. BEGIN_JUCE_NAMESPACE
  61671. extern void juce_glViewport (const int w, const int h);
  61672. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  61673. const int alphaBits_,
  61674. const int depthBufferBits_,
  61675. const int stencilBufferBits_)
  61676. : redBits (bitsPerRGBComponent),
  61677. greenBits (bitsPerRGBComponent),
  61678. blueBits (bitsPerRGBComponent),
  61679. alphaBits (alphaBits_),
  61680. depthBufferBits (depthBufferBits_),
  61681. stencilBufferBits (stencilBufferBits_),
  61682. accumulationBufferRedBits (0),
  61683. accumulationBufferGreenBits (0),
  61684. accumulationBufferBlueBits (0),
  61685. accumulationBufferAlphaBits (0),
  61686. fullSceneAntiAliasingNumSamples (0)
  61687. {
  61688. }
  61689. OpenGLPixelFormat::OpenGLPixelFormat (const OpenGLPixelFormat& other)
  61690. : redBits (other.redBits),
  61691. greenBits (other.greenBits),
  61692. blueBits (other.blueBits),
  61693. alphaBits (other.alphaBits),
  61694. depthBufferBits (other.depthBufferBits),
  61695. stencilBufferBits (other.stencilBufferBits),
  61696. accumulationBufferRedBits (other.accumulationBufferRedBits),
  61697. accumulationBufferGreenBits (other.accumulationBufferGreenBits),
  61698. accumulationBufferBlueBits (other.accumulationBufferBlueBits),
  61699. accumulationBufferAlphaBits (other.accumulationBufferAlphaBits),
  61700. fullSceneAntiAliasingNumSamples (other.fullSceneAntiAliasingNumSamples)
  61701. {
  61702. }
  61703. OpenGLPixelFormat& OpenGLPixelFormat::operator= (const OpenGLPixelFormat& other)
  61704. {
  61705. redBits = other.redBits;
  61706. greenBits = other.greenBits;
  61707. blueBits = other.blueBits;
  61708. alphaBits = other.alphaBits;
  61709. depthBufferBits = other.depthBufferBits;
  61710. stencilBufferBits = other.stencilBufferBits;
  61711. accumulationBufferRedBits = other.accumulationBufferRedBits;
  61712. accumulationBufferGreenBits = other.accumulationBufferGreenBits;
  61713. accumulationBufferBlueBits = other.accumulationBufferBlueBits;
  61714. accumulationBufferAlphaBits = other.accumulationBufferAlphaBits;
  61715. fullSceneAntiAliasingNumSamples = other.fullSceneAntiAliasingNumSamples;
  61716. return *this;
  61717. }
  61718. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const
  61719. {
  61720. return redBits == other.redBits
  61721. && greenBits == other.greenBits
  61722. && blueBits == other.blueBits
  61723. && alphaBits == other.alphaBits
  61724. && depthBufferBits == other.depthBufferBits
  61725. && stencilBufferBits == other.stencilBufferBits
  61726. && accumulationBufferRedBits == other.accumulationBufferRedBits
  61727. && accumulationBufferGreenBits == other.accumulationBufferGreenBits
  61728. && accumulationBufferBlueBits == other.accumulationBufferBlueBits
  61729. && accumulationBufferAlphaBits == other.accumulationBufferAlphaBits
  61730. && fullSceneAntiAliasingNumSamples == other.fullSceneAntiAliasingNumSamples;
  61731. }
  61732. static Array<OpenGLContext*> knownContexts;
  61733. OpenGLContext::OpenGLContext() throw()
  61734. {
  61735. knownContexts.add (this);
  61736. }
  61737. OpenGLContext::~OpenGLContext()
  61738. {
  61739. knownContexts.removeValue (this);
  61740. }
  61741. OpenGLContext* OpenGLContext::getCurrentContext()
  61742. {
  61743. for (int i = knownContexts.size(); --i >= 0;)
  61744. {
  61745. OpenGLContext* const oglc = knownContexts.getUnchecked(i);
  61746. if (oglc->isActive())
  61747. return oglc;
  61748. }
  61749. return 0;
  61750. }
  61751. class OpenGLComponent::OpenGLComponentWatcher : public ComponentMovementWatcher
  61752. {
  61753. public:
  61754. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  61755. : ComponentMovementWatcher (owner_),
  61756. owner (owner_),
  61757. wasShowing (false)
  61758. {
  61759. }
  61760. ~OpenGLComponentWatcher() {}
  61761. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  61762. {
  61763. owner->updateContextPosition();
  61764. }
  61765. void componentPeerChanged()
  61766. {
  61767. const ScopedLock sl (owner->getContextLock());
  61768. owner->deleteContext();
  61769. }
  61770. void componentVisibilityChanged (Component&)
  61771. {
  61772. const bool isShowingNow = owner->isShowing();
  61773. if (wasShowing != isShowingNow)
  61774. {
  61775. wasShowing = isShowingNow;
  61776. if (! isShowingNow)
  61777. {
  61778. const ScopedLock sl (owner->getContextLock());
  61779. owner->deleteContext();
  61780. }
  61781. }
  61782. }
  61783. juce_UseDebuggingNewOperator
  61784. private:
  61785. OpenGLComponent* const owner;
  61786. bool wasShowing;
  61787. };
  61788. OpenGLComponent::OpenGLComponent (const OpenGLType type_)
  61789. : type (type_),
  61790. contextToShareListsWith (0),
  61791. needToUpdateViewport (true)
  61792. {
  61793. setOpaque (true);
  61794. componentWatcher = new OpenGLComponentWatcher (this);
  61795. }
  61796. OpenGLComponent::~OpenGLComponent()
  61797. {
  61798. deleteContext();
  61799. componentWatcher = 0;
  61800. }
  61801. void OpenGLComponent::deleteContext()
  61802. {
  61803. const ScopedLock sl (contextLock);
  61804. context = 0;
  61805. }
  61806. void OpenGLComponent::updateContextPosition()
  61807. {
  61808. needToUpdateViewport = true;
  61809. if (getWidth() > 0 && getHeight() > 0)
  61810. {
  61811. Component* const topComp = getTopLevelComponent();
  61812. if (topComp->getPeer() != 0)
  61813. {
  61814. const ScopedLock sl (contextLock);
  61815. if (context != 0)
  61816. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  61817. getScreenY() - topComp->getScreenY(),
  61818. getWidth(),
  61819. getHeight(),
  61820. topComp->getHeight());
  61821. }
  61822. }
  61823. }
  61824. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  61825. {
  61826. OpenGLPixelFormat pf;
  61827. const ScopedLock sl (contextLock);
  61828. if (context != 0)
  61829. pf = context->getPixelFormat();
  61830. return pf;
  61831. }
  61832. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  61833. {
  61834. if (! (preferredPixelFormat == formatToUse))
  61835. {
  61836. const ScopedLock sl (contextLock);
  61837. deleteContext();
  61838. preferredPixelFormat = formatToUse;
  61839. }
  61840. }
  61841. void OpenGLComponent::shareWith (OpenGLContext* c)
  61842. {
  61843. if (contextToShareListsWith != c)
  61844. {
  61845. const ScopedLock sl (contextLock);
  61846. deleteContext();
  61847. contextToShareListsWith = c;
  61848. }
  61849. }
  61850. bool OpenGLComponent::makeCurrentContextActive()
  61851. {
  61852. if (context == 0)
  61853. {
  61854. const ScopedLock sl (contextLock);
  61855. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  61856. {
  61857. context = createContext();
  61858. if (context != 0)
  61859. {
  61860. updateContextPosition();
  61861. if (context->makeActive())
  61862. newOpenGLContextCreated();
  61863. }
  61864. }
  61865. }
  61866. return context != 0 && context->makeActive();
  61867. }
  61868. void OpenGLComponent::makeCurrentContextInactive()
  61869. {
  61870. if (context != 0)
  61871. context->makeInactive();
  61872. }
  61873. bool OpenGLComponent::isActiveContext() const throw()
  61874. {
  61875. return context != 0 && context->isActive();
  61876. }
  61877. void OpenGLComponent::swapBuffers()
  61878. {
  61879. if (context != 0)
  61880. context->swapBuffers();
  61881. }
  61882. void OpenGLComponent::paint (Graphics&)
  61883. {
  61884. if (renderAndSwapBuffers())
  61885. {
  61886. ComponentPeer* const peer = getPeer();
  61887. if (peer != 0)
  61888. {
  61889. const Point<int> topLeft (getScreenPosition() - peer->getScreenPosition());
  61890. peer->addMaskedRegion (topLeft.getX(), topLeft.getY(), getWidth(), getHeight());
  61891. }
  61892. }
  61893. }
  61894. bool OpenGLComponent::renderAndSwapBuffers()
  61895. {
  61896. const ScopedLock sl (contextLock);
  61897. if (! makeCurrentContextActive())
  61898. return false;
  61899. if (needToUpdateViewport)
  61900. {
  61901. needToUpdateViewport = false;
  61902. juce_glViewport (getWidth(), getHeight());
  61903. }
  61904. renderOpenGL();
  61905. swapBuffers();
  61906. return true;
  61907. }
  61908. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  61909. {
  61910. Component::internalRepaint (x, y, w, h);
  61911. if (context != 0)
  61912. context->repaint();
  61913. }
  61914. END_JUCE_NAMESPACE
  61915. #endif
  61916. /*** End of inlined file: juce_OpenGLComponent.cpp ***/
  61917. /*** Start of inlined file: juce_PreferencesPanel.cpp ***/
  61918. BEGIN_JUCE_NAMESPACE
  61919. PreferencesPanel::PreferencesPanel()
  61920. : buttonSize (70)
  61921. {
  61922. }
  61923. PreferencesPanel::~PreferencesPanel()
  61924. {
  61925. }
  61926. void PreferencesPanel::addSettingsPage (const String& title,
  61927. const Drawable* icon,
  61928. const Drawable* overIcon,
  61929. const Drawable* downIcon)
  61930. {
  61931. DrawableButton* const button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  61932. buttons.add (button);
  61933. button->setImages (icon, overIcon, downIcon);
  61934. button->setRadioGroupId (1);
  61935. button->addButtonListener (this);
  61936. button->setClickingTogglesState (true);
  61937. button->setWantsKeyboardFocus (false);
  61938. addAndMakeVisible (button);
  61939. resized();
  61940. if (currentPage == 0)
  61941. setCurrentPage (title);
  61942. }
  61943. void PreferencesPanel::addSettingsPage (const String& title, const void* imageData, const int imageDataSize)
  61944. {
  61945. DrawableImage icon, iconOver, iconDown;
  61946. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61947. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61948. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  61949. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize));
  61950. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  61951. addSettingsPage (title, &icon, &iconOver, &iconDown);
  61952. }
  61953. void PreferencesPanel::showInDialogBox (const String& dialogTitle, int dialogWidth, int dialogHeight, const Colour& backgroundColour)
  61954. {
  61955. setSize (dialogWidth, dialogHeight);
  61956. DialogWindow::showModalDialog (dialogTitle, this, 0, backgroundColour, false);
  61957. }
  61958. void PreferencesPanel::resized()
  61959. {
  61960. for (int i = 0; i < buttons.size(); ++i)
  61961. buttons.getUnchecked(i)->setBounds (i * buttonSize, 0, buttonSize, buttonSize);
  61962. if (currentPage != 0)
  61963. currentPage->setBounds (getLocalBounds().withTop (buttonSize + 5));
  61964. }
  61965. void PreferencesPanel::paint (Graphics& g)
  61966. {
  61967. g.setColour (Colours::grey);
  61968. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  61969. }
  61970. void PreferencesPanel::setCurrentPage (const String& pageName)
  61971. {
  61972. if (currentPageName != pageName)
  61973. {
  61974. currentPageName = pageName;
  61975. currentPage = 0;
  61976. currentPage = createComponentForPage (pageName);
  61977. if (currentPage != 0)
  61978. {
  61979. addAndMakeVisible (currentPage);
  61980. currentPage->toBack();
  61981. resized();
  61982. }
  61983. for (int i = 0; i < buttons.size(); ++i)
  61984. {
  61985. if (buttons.getUnchecked(i)->getName() == pageName)
  61986. {
  61987. buttons.getUnchecked(i)->setToggleState (true, false);
  61988. break;
  61989. }
  61990. }
  61991. }
  61992. }
  61993. void PreferencesPanel::buttonClicked (Button*)
  61994. {
  61995. for (int i = 0; i < buttons.size(); ++i)
  61996. {
  61997. if (buttons.getUnchecked(i)->getToggleState())
  61998. {
  61999. setCurrentPage (buttons.getUnchecked(i)->getName());
  62000. break;
  62001. }
  62002. }
  62003. }
  62004. END_JUCE_NAMESPACE
  62005. /*** End of inlined file: juce_PreferencesPanel.cpp ***/
  62006. /*** Start of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62007. #if JUCE_WINDOWS || JUCE_LINUX
  62008. BEGIN_JUCE_NAMESPACE
  62009. SystemTrayIconComponent::SystemTrayIconComponent()
  62010. {
  62011. addToDesktop (0);
  62012. }
  62013. SystemTrayIconComponent::~SystemTrayIconComponent()
  62014. {
  62015. }
  62016. END_JUCE_NAMESPACE
  62017. #endif
  62018. /*** End of inlined file: juce_SystemTrayIconComponent.cpp ***/
  62019. /*** Start of inlined file: juce_AlertWindow.cpp ***/
  62020. BEGIN_JUCE_NAMESPACE
  62021. class AlertWindowTextEditor : public TextEditor
  62022. {
  62023. public:
  62024. AlertWindowTextEditor (const String& name, const bool isPasswordBox)
  62025. : TextEditor (name, isPasswordBox ? getDefaultPasswordChar() : 0)
  62026. {
  62027. setSelectAllWhenFocused (true);
  62028. }
  62029. ~AlertWindowTextEditor()
  62030. {
  62031. }
  62032. void returnPressed()
  62033. {
  62034. // pass these up the component hierarchy to be trigger the buttons
  62035. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, '\n'));
  62036. }
  62037. void escapePressed()
  62038. {
  62039. // pass these up the component hierarchy to be trigger the buttons
  62040. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  62041. }
  62042. private:
  62043. AlertWindowTextEditor (const AlertWindowTextEditor&);
  62044. AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  62045. static juce_wchar getDefaultPasswordChar() throw()
  62046. {
  62047. #if JUCE_LINUX
  62048. return 0x2022;
  62049. #else
  62050. return 0x25cf;
  62051. #endif
  62052. }
  62053. };
  62054. AlertWindow::AlertWindow (const String& title,
  62055. const String& message,
  62056. AlertIconType iconType,
  62057. Component* associatedComponent_)
  62058. : TopLevelWindow (title, true),
  62059. alertIconType (iconType),
  62060. associatedComponent (associatedComponent_)
  62061. {
  62062. if (message.isEmpty())
  62063. text = " "; // to force an update if the message is empty
  62064. setMessage (message);
  62065. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  62066. {
  62067. Component* const c = Desktop::getInstance().getComponent (i);
  62068. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  62069. {
  62070. setAlwaysOnTop (true);
  62071. break;
  62072. }
  62073. }
  62074. if (! JUCEApplication::isStandaloneApp())
  62075. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62076. lookAndFeelChanged();
  62077. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  62078. }
  62079. AlertWindow::~AlertWindow()
  62080. {
  62081. for (int i = customComps.size(); --i >= 0;)
  62082. removeChildComponent ((Component*) customComps[i]);
  62083. deleteAllChildren();
  62084. }
  62085. void AlertWindow::userTriedToCloseWindow()
  62086. {
  62087. exitModalState (0);
  62088. }
  62089. void AlertWindow::setMessage (const String& message)
  62090. {
  62091. const String newMessage (message.substring (0, 2048));
  62092. if (text != newMessage)
  62093. {
  62094. text = newMessage;
  62095. font.setHeight (15.0f);
  62096. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  62097. textLayout.setText (getName() + "\n\n", titleFont);
  62098. textLayout.appendText (text, font);
  62099. updateLayout (true);
  62100. repaint();
  62101. }
  62102. }
  62103. void AlertWindow::buttonClicked (Button* button)
  62104. {
  62105. for (int i = 0; i < buttons.size(); i++)
  62106. {
  62107. TextButton* const c = (TextButton*) buttons[i];
  62108. if (button->getName() == c->getName())
  62109. {
  62110. if (c->getParentComponent() != 0)
  62111. c->getParentComponent()->exitModalState (c->getCommandID());
  62112. break;
  62113. }
  62114. }
  62115. }
  62116. void AlertWindow::addButton (const String& name,
  62117. const int returnValue,
  62118. const KeyPress& shortcutKey1,
  62119. const KeyPress& shortcutKey2)
  62120. {
  62121. TextButton* const b = new TextButton (name, String::empty);
  62122. b->setWantsKeyboardFocus (true);
  62123. b->setMouseClickGrabsKeyboardFocus (false);
  62124. b->setCommandToTrigger (0, returnValue, false);
  62125. b->addShortcut (shortcutKey1);
  62126. b->addShortcut (shortcutKey2);
  62127. b->addButtonListener (this);
  62128. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  62129. addAndMakeVisible (b, 0);
  62130. buttons.add (b);
  62131. updateLayout (false);
  62132. }
  62133. int AlertWindow::getNumButtons() const
  62134. {
  62135. return buttons.size();
  62136. }
  62137. void AlertWindow::triggerButtonClick (const String& buttonName)
  62138. {
  62139. for (int i = buttons.size(); --i >= 0;)
  62140. {
  62141. TextButton* const b = (TextButton*) buttons[i];
  62142. if (buttonName == b->getName())
  62143. {
  62144. b->triggerClick();
  62145. break;
  62146. }
  62147. }
  62148. }
  62149. void AlertWindow::addTextEditor (const String& name,
  62150. const String& initialContents,
  62151. const String& onScreenLabel,
  62152. const bool isPasswordBox)
  62153. {
  62154. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  62155. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  62156. tc->setFont (font);
  62157. tc->setText (initialContents);
  62158. tc->setCaretPosition (initialContents.length());
  62159. addAndMakeVisible (tc);
  62160. textBoxes.add (tc);
  62161. allComps.add (tc);
  62162. textboxNames.add (onScreenLabel);
  62163. updateLayout (false);
  62164. }
  62165. TextEditor* AlertWindow::getTextEditor (const String& nameOfTextEditor) const
  62166. {
  62167. for (int i = textBoxes.size(); --i >= 0;)
  62168. if (static_cast <TextEditor*> (textBoxes.getUnchecked(i))->getName() == nameOfTextEditor)
  62169. return static_cast <TextEditor*> (textBoxes.getUnchecked(i));
  62170. return 0;
  62171. }
  62172. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  62173. {
  62174. TextEditor* const t = getTextEditor (nameOfTextEditor);
  62175. return t != 0 ? t->getText() : String::empty;
  62176. }
  62177. void AlertWindow::addComboBox (const String& name,
  62178. const StringArray& items,
  62179. const String& onScreenLabel)
  62180. {
  62181. ComboBox* const cb = new ComboBox (name);
  62182. for (int i = 0; i < items.size(); ++i)
  62183. cb->addItem (items[i], i + 1);
  62184. addAndMakeVisible (cb);
  62185. cb->setSelectedItemIndex (0);
  62186. comboBoxes.add (cb);
  62187. allComps.add (cb);
  62188. comboBoxNames.add (onScreenLabel);
  62189. updateLayout (false);
  62190. }
  62191. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  62192. {
  62193. for (int i = comboBoxes.size(); --i >= 0;)
  62194. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  62195. return (ComboBox*) comboBoxes[i];
  62196. return 0;
  62197. }
  62198. class AlertTextComp : public TextEditor
  62199. {
  62200. public:
  62201. AlertTextComp (const String& message,
  62202. const Font& font)
  62203. {
  62204. setReadOnly (true);
  62205. setMultiLine (true, true);
  62206. setCaretVisible (false);
  62207. setScrollbarsShown (true);
  62208. lookAndFeelChanged();
  62209. setWantsKeyboardFocus (false);
  62210. setFont (font);
  62211. setText (message, false);
  62212. bestWidth = 2 * (int) std::sqrt (font.getHeight() * font.getStringWidth (message));
  62213. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  62214. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  62215. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  62216. }
  62217. ~AlertTextComp()
  62218. {
  62219. }
  62220. int getPreferredWidth() const throw() { return bestWidth; }
  62221. void updateLayout (const int width)
  62222. {
  62223. TextLayout text;
  62224. text.appendText (getText(), getFont());
  62225. text.layout (width - 8, Justification::topLeft, true);
  62226. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  62227. }
  62228. private:
  62229. int bestWidth;
  62230. AlertTextComp (const AlertTextComp&);
  62231. AlertTextComp& operator= (const AlertTextComp&);
  62232. };
  62233. void AlertWindow::addTextBlock (const String& textBlock)
  62234. {
  62235. AlertTextComp* const c = new AlertTextComp (textBlock, font);
  62236. textBlocks.add (c);
  62237. allComps.add (c);
  62238. addAndMakeVisible (c);
  62239. updateLayout (false);
  62240. }
  62241. void AlertWindow::addProgressBarComponent (double& progressValue)
  62242. {
  62243. ProgressBar* const pb = new ProgressBar (progressValue);
  62244. progressBars.add (pb);
  62245. allComps.add (pb);
  62246. addAndMakeVisible (pb);
  62247. updateLayout (false);
  62248. }
  62249. void AlertWindow::addCustomComponent (Component* const component)
  62250. {
  62251. customComps.add (component);
  62252. allComps.add (component);
  62253. addAndMakeVisible (component);
  62254. updateLayout (false);
  62255. }
  62256. int AlertWindow::getNumCustomComponents() const
  62257. {
  62258. return customComps.size();
  62259. }
  62260. Component* AlertWindow::getCustomComponent (const int index) const
  62261. {
  62262. return (Component*) customComps [index];
  62263. }
  62264. Component* AlertWindow::removeCustomComponent (const int index)
  62265. {
  62266. Component* const c = getCustomComponent (index);
  62267. if (c != 0)
  62268. {
  62269. customComps.removeValue (c);
  62270. allComps.removeValue (c);
  62271. removeChildComponent (c);
  62272. updateLayout (false);
  62273. }
  62274. return c;
  62275. }
  62276. void AlertWindow::paint (Graphics& g)
  62277. {
  62278. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  62279. g.setColour (findColour (textColourId));
  62280. g.setFont (getLookAndFeel().getAlertWindowFont());
  62281. int i;
  62282. for (i = textBoxes.size(); --i >= 0;)
  62283. {
  62284. const TextEditor* const te = (TextEditor*) textBoxes[i];
  62285. g.drawFittedText (textboxNames[i],
  62286. te->getX(), te->getY() - 14,
  62287. te->getWidth(), 14,
  62288. Justification::centredLeft, 1);
  62289. }
  62290. for (i = comboBoxNames.size(); --i >= 0;)
  62291. {
  62292. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  62293. g.drawFittedText (comboBoxNames[i],
  62294. cb->getX(), cb->getY() - 14,
  62295. cb->getWidth(), 14,
  62296. Justification::centredLeft, 1);
  62297. }
  62298. for (i = customComps.size(); --i >= 0;)
  62299. {
  62300. const Component* const c = (Component*) customComps[i];
  62301. g.drawFittedText (c->getName(),
  62302. c->getX(), c->getY() - 14,
  62303. c->getWidth(), 14,
  62304. Justification::centredLeft, 1);
  62305. }
  62306. }
  62307. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  62308. {
  62309. const int titleH = 24;
  62310. const int iconWidth = 80;
  62311. const int wid = jmax (font.getStringWidth (text),
  62312. font.getStringWidth (getName()));
  62313. const int sw = (int) std::sqrt (font.getHeight() * wid);
  62314. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  62315. const int edgeGap = 10;
  62316. const int labelHeight = 18;
  62317. int iconSpace;
  62318. if (alertIconType == NoIcon)
  62319. {
  62320. textLayout.layout (w, Justification::horizontallyCentred, true);
  62321. iconSpace = 0;
  62322. }
  62323. else
  62324. {
  62325. textLayout.layout (w, Justification::left, true);
  62326. iconSpace = iconWidth;
  62327. }
  62328. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  62329. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62330. const int textLayoutH = textLayout.getHeight();
  62331. const int textBottom = 16 + titleH + textLayoutH;
  62332. int h = textBottom;
  62333. int buttonW = 40;
  62334. int i;
  62335. for (i = 0; i < buttons.size(); ++i)
  62336. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  62337. w = jmax (buttonW, w);
  62338. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  62339. if (buttons.size() > 0)
  62340. h += 20 + ((TextButton*) buttons[0])->getHeight();
  62341. for (i = customComps.size(); --i >= 0;)
  62342. {
  62343. Component* c = (Component*) customComps[i];
  62344. w = jmax (w, (c->getWidth() * 100) / 80);
  62345. h += 10 + c->getHeight();
  62346. if (c->getName().isNotEmpty())
  62347. h += labelHeight;
  62348. }
  62349. for (i = textBlocks.size(); --i >= 0;)
  62350. {
  62351. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62352. w = jmax (w, ac->getPreferredWidth());
  62353. }
  62354. w = jmin (w, (int) (getParentWidth() * 0.7f));
  62355. for (i = textBlocks.size(); --i >= 0;)
  62356. {
  62357. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  62358. ac->updateLayout ((int) (w * 0.8f));
  62359. h += ac->getHeight() + 10;
  62360. }
  62361. h = jmin (getParentHeight() - 50, h);
  62362. if (onlyIncreaseSize)
  62363. {
  62364. w = jmax (w, getWidth());
  62365. h = jmax (h, getHeight());
  62366. }
  62367. if (! isVisible())
  62368. {
  62369. centreAroundComponent (associatedComponent, w, h);
  62370. }
  62371. else
  62372. {
  62373. const int cx = getX() + getWidth() / 2;
  62374. const int cy = getY() + getHeight() / 2;
  62375. setBounds (cx - w / 2,
  62376. cy - h / 2,
  62377. w, h);
  62378. }
  62379. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  62380. const int spacer = 16;
  62381. int totalWidth = -spacer;
  62382. for (i = buttons.size(); --i >= 0;)
  62383. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  62384. int x = (w - totalWidth) / 2;
  62385. int y = (int) (getHeight() * 0.95f);
  62386. for (i = 0; i < buttons.size(); ++i)
  62387. {
  62388. TextButton* const c = (TextButton*) buttons[i];
  62389. int ny = proportionOfHeight (0.95f) - c->getHeight();
  62390. c->setTopLeftPosition (x, ny);
  62391. if (ny < y)
  62392. y = ny;
  62393. x += c->getWidth() + spacer;
  62394. c->toFront (false);
  62395. }
  62396. y = textBottom;
  62397. for (i = 0; i < allComps.size(); ++i)
  62398. {
  62399. Component* const c = (Component*) allComps[i];
  62400. h = 22;
  62401. const int comboIndex = comboBoxes.indexOf (c);
  62402. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  62403. y += labelHeight;
  62404. const int tbIndex = textBoxes.indexOf (c);
  62405. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  62406. y += labelHeight;
  62407. if (customComps.contains (c))
  62408. {
  62409. if (c->getName().isNotEmpty())
  62410. y += labelHeight;
  62411. c->setTopLeftPosition (proportionOfWidth (0.1f), y);
  62412. h = c->getHeight();
  62413. }
  62414. else if (textBlocks.contains (c))
  62415. {
  62416. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  62417. h = c->getHeight();
  62418. }
  62419. else
  62420. {
  62421. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  62422. }
  62423. y += h + 10;
  62424. }
  62425. setWantsKeyboardFocus (getNumChildComponents() == 0);
  62426. }
  62427. bool AlertWindow::containsAnyExtraComponents() const
  62428. {
  62429. return textBoxes.size()
  62430. + comboBoxes.size()
  62431. + progressBars.size()
  62432. + customComps.size() > 0;
  62433. }
  62434. void AlertWindow::mouseDown (const MouseEvent&)
  62435. {
  62436. dragger.startDraggingComponent (this, &constrainer);
  62437. }
  62438. void AlertWindow::mouseDrag (const MouseEvent& e)
  62439. {
  62440. dragger.dragComponent (this, e);
  62441. }
  62442. bool AlertWindow::keyPressed (const KeyPress& key)
  62443. {
  62444. for (int i = buttons.size(); --i >= 0;)
  62445. {
  62446. TextButton* const b = (TextButton*) buttons[i];
  62447. if (b->isRegisteredForShortcut (key))
  62448. {
  62449. b->triggerClick();
  62450. return true;
  62451. }
  62452. }
  62453. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  62454. {
  62455. exitModalState (0);
  62456. return true;
  62457. }
  62458. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  62459. {
  62460. ((TextButton*) buttons.getFirst())->triggerClick();
  62461. return true;
  62462. }
  62463. return false;
  62464. }
  62465. void AlertWindow::lookAndFeelChanged()
  62466. {
  62467. const int newFlags = getLookAndFeel().getAlertBoxWindowFlags();
  62468. setUsingNativeTitleBar ((newFlags & ComponentPeer::windowHasTitleBar) != 0);
  62469. setDropShadowEnabled (isOpaque() && (newFlags & ComponentPeer::windowHasDropShadow) != 0);
  62470. }
  62471. int AlertWindow::getDesktopWindowStyleFlags() const
  62472. {
  62473. return getLookAndFeel().getAlertBoxWindowFlags();
  62474. }
  62475. struct AlertWindowInfo
  62476. {
  62477. String title, message, button1, button2, button3;
  62478. AlertWindow::AlertIconType iconType;
  62479. int numButtons;
  62480. Component::SafePointer<Component> associatedComponent;
  62481. int run() const
  62482. {
  62483. return (int) (pointer_sized_int)
  62484. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  62485. }
  62486. private:
  62487. int show() const
  62488. {
  62489. LookAndFeel& lf = associatedComponent != 0 ? associatedComponent->getLookAndFeel()
  62490. : LookAndFeel::getDefaultLookAndFeel();
  62491. ScopedPointer <Component> alertBox (lf.createAlertWindow (title, message, button1, button2, button3,
  62492. iconType, numButtons, associatedComponent));
  62493. jassert (alertBox != 0); // you have to return one of these!
  62494. return alertBox->runModalLoop();
  62495. }
  62496. static void* showCallback (void* userData)
  62497. {
  62498. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  62499. }
  62500. };
  62501. void AlertWindow::showMessageBox (AlertIconType iconType,
  62502. const String& title,
  62503. const String& message,
  62504. const String& buttonText,
  62505. Component* associatedComponent)
  62506. {
  62507. AlertWindowInfo info;
  62508. info.title = title;
  62509. info.message = message;
  62510. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  62511. info.iconType = iconType;
  62512. info.numButtons = 1;
  62513. info.associatedComponent = associatedComponent;
  62514. info.run();
  62515. }
  62516. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  62517. const String& title,
  62518. const String& message,
  62519. const String& button1Text,
  62520. const String& button2Text,
  62521. Component* associatedComponent)
  62522. {
  62523. AlertWindowInfo info;
  62524. info.title = title;
  62525. info.message = message;
  62526. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  62527. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  62528. info.iconType = iconType;
  62529. info.numButtons = 2;
  62530. info.associatedComponent = associatedComponent;
  62531. return info.run() != 0;
  62532. }
  62533. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  62534. const String& title,
  62535. const String& message,
  62536. const String& button1Text,
  62537. const String& button2Text,
  62538. const String& button3Text,
  62539. Component* associatedComponent)
  62540. {
  62541. AlertWindowInfo info;
  62542. info.title = title;
  62543. info.message = message;
  62544. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  62545. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  62546. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  62547. info.iconType = iconType;
  62548. info.numButtons = 3;
  62549. info.associatedComponent = associatedComponent;
  62550. return info.run();
  62551. }
  62552. END_JUCE_NAMESPACE
  62553. /*** End of inlined file: juce_AlertWindow.cpp ***/
  62554. /*** Start of inlined file: juce_CallOutBox.cpp ***/
  62555. BEGIN_JUCE_NAMESPACE
  62556. CallOutBox::CallOutBox (Component& contentComponent,
  62557. Component& componentToPointTo,
  62558. Component* const parentComponent)
  62559. : borderSpace (20), arrowSize (16.0f), content (contentComponent)
  62560. {
  62561. addAndMakeVisible (&content);
  62562. if (parentComponent != 0)
  62563. {
  62564. parentComponent->addChildComponent (this);
  62565. updatePosition (componentToPointTo.getLocalBounds()
  62566. + componentToPointTo.relativePositionToOtherComponent (parentComponent, Point<int>()),
  62567. parentComponent->getLocalBounds());
  62568. setVisible (true);
  62569. }
  62570. else
  62571. {
  62572. if (! JUCEApplication::isStandaloneApp())
  62573. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  62574. updatePosition (componentToPointTo.getScreenBounds(),
  62575. componentToPointTo.getParentMonitorArea());
  62576. addToDesktop (ComponentPeer::windowIsTemporary);
  62577. }
  62578. }
  62579. CallOutBox::~CallOutBox()
  62580. {
  62581. }
  62582. void CallOutBox::setArrowSize (const float newSize)
  62583. {
  62584. arrowSize = newSize;
  62585. borderSpace = jmax (20, (int) arrowSize);
  62586. refreshPath();
  62587. }
  62588. void CallOutBox::paint (Graphics& g)
  62589. {
  62590. if (background.isNull())
  62591. {
  62592. background = Image (Image::ARGB, getWidth(), getHeight(), true);
  62593. Graphics g (background);
  62594. getLookAndFeel().drawCallOutBoxBackground (*this, g, outline);
  62595. }
  62596. g.setColour (Colours::black);
  62597. g.drawImageAt (background, 0, 0);
  62598. }
  62599. void CallOutBox::resized()
  62600. {
  62601. content.setTopLeftPosition (borderSpace, borderSpace);
  62602. refreshPath();
  62603. }
  62604. void CallOutBox::moved()
  62605. {
  62606. refreshPath();
  62607. }
  62608. void CallOutBox::childBoundsChanged (Component*)
  62609. {
  62610. updatePosition (targetArea, availableArea);
  62611. }
  62612. bool CallOutBox::hitTest (int x, int y)
  62613. {
  62614. return outline.contains ((float) x, (float) y);
  62615. }
  62616. enum { callOutBoxDismissCommandId = 0x4f83a04b };
  62617. void CallOutBox::inputAttemptWhenModal()
  62618. {
  62619. const Point<int> mousePos (getMouseXYRelative() + getBounds().getPosition());
  62620. if (targetArea.contains (mousePos))
  62621. {
  62622. // if you click on the area that originally popped-up the callout, you expect it
  62623. // to get rid of the box, but deleting the box here allows the click to pass through and
  62624. // probably re-trigger it, so we need to dismiss the box asynchronously to consume the click..
  62625. postCommandMessage (callOutBoxDismissCommandId);
  62626. }
  62627. else
  62628. {
  62629. exitModalState (0);
  62630. setVisible (false);
  62631. }
  62632. }
  62633. void CallOutBox::handleCommandMessage (int commandId)
  62634. {
  62635. Component::handleCommandMessage (commandId);
  62636. if (commandId == callOutBoxDismissCommandId)
  62637. {
  62638. exitModalState (0);
  62639. setVisible (false);
  62640. }
  62641. }
  62642. bool CallOutBox::keyPressed (const KeyPress& key)
  62643. {
  62644. if (key.isKeyCode (KeyPress::escapeKey))
  62645. {
  62646. inputAttemptWhenModal();
  62647. return true;
  62648. }
  62649. return false;
  62650. }
  62651. void CallOutBox::updatePosition (const Rectangle<int>& newAreaToPointTo, const Rectangle<int>& newAreaToFitIn)
  62652. {
  62653. targetArea = newAreaToPointTo;
  62654. availableArea = newAreaToFitIn;
  62655. Rectangle<int> bounds (0, 0,
  62656. content.getWidth() + borderSpace * 2,
  62657. content.getHeight() + borderSpace * 2);
  62658. const int hw = bounds.getWidth() / 2;
  62659. const int hh = bounds.getHeight() / 2;
  62660. const float hwReduced = (float) (hw - borderSpace * 3);
  62661. const float hhReduced = (float) (hh - borderSpace * 3);
  62662. const float arrowIndent = borderSpace - arrowSize;
  62663. Point<float> targets[4] = { Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getBottom()),
  62664. Point<float> ((float) targetArea.getRight(), (float) targetArea.getCentreY()),
  62665. Point<float> ((float) targetArea.getX(), (float) targetArea.getCentreY()),
  62666. Point<float> ((float) targetArea.getCentreX(), (float) targetArea.getY()) };
  62667. Line<float> lines[4] = { Line<float> (targets[0].translated (-hwReduced, hh - arrowIndent), targets[0].translated (hwReduced, hh - arrowIndent)),
  62668. Line<float> (targets[1].translated (hw - arrowIndent, -hhReduced), targets[1].translated (hw - arrowIndent, hhReduced)),
  62669. Line<float> (targets[2].translated (-(hw - arrowIndent), -hhReduced), targets[2].translated (-(hw - arrowIndent), hhReduced)),
  62670. Line<float> (targets[3].translated (-hwReduced, -(hh - arrowIndent)), targets[3].translated (hwReduced, -(hh - arrowIndent))) };
  62671. const Rectangle<float> centrePointArea (newAreaToFitIn.reduced (hw, hh).toFloat());
  62672. float nearest = 1.0e9f;
  62673. for (int i = 0; i < 4; ++i)
  62674. {
  62675. Line<float> constrainedLine (centrePointArea.getConstrainedPoint (lines[i].getStart()),
  62676. centrePointArea.getConstrainedPoint (lines[i].getEnd()));
  62677. const Point<float> centre (constrainedLine.findNearestPointTo (centrePointArea.getCentre()));
  62678. float distanceFromCentre = centre.getDistanceFrom (centrePointArea.getCentre());
  62679. if (! (centrePointArea.contains (lines[i].getStart()) || centrePointArea.contains (lines[i].getEnd())))
  62680. distanceFromCentre *= 2.0f;
  62681. if (distanceFromCentre < nearest)
  62682. {
  62683. nearest = distanceFromCentre;
  62684. targetPoint = targets[i];
  62685. bounds.setPosition ((int) (centre.getX() - hw),
  62686. (int) (centre.getY() - hh));
  62687. }
  62688. }
  62689. setBounds (bounds);
  62690. }
  62691. void CallOutBox::refreshPath()
  62692. {
  62693. repaint();
  62694. background = Image::null;
  62695. outline.clear();
  62696. const float gap = 4.5f;
  62697. const float cornerSize = 9.0f;
  62698. const float cornerSize2 = 2.0f * cornerSize;
  62699. const float arrowBaseWidth = arrowSize * 0.7f;
  62700. const float left = content.getX() - gap, top = content.getY() - gap, right = content.getRight() + gap, bottom = content.getBottom() + gap;
  62701. const float targetX = targetPoint.getX() - getX(), targetY = targetPoint.getY() - getY();
  62702. outline.startNewSubPath (left + cornerSize, top);
  62703. if (targetY <= top)
  62704. {
  62705. outline.lineTo (targetX - arrowBaseWidth, top);
  62706. outline.lineTo (targetX, targetY);
  62707. outline.lineTo (targetX + arrowBaseWidth, top);
  62708. }
  62709. outline.lineTo (right - cornerSize, top);
  62710. outline.addArc (right - cornerSize2, top, cornerSize2, cornerSize2, 0, float_Pi * 0.5f);
  62711. if (targetX >= right)
  62712. {
  62713. outline.lineTo (right, targetY - arrowBaseWidth);
  62714. outline.lineTo (targetX, targetY);
  62715. outline.lineTo (right, targetY + arrowBaseWidth);
  62716. }
  62717. outline.lineTo (right, bottom - cornerSize);
  62718. outline.addArc (right - cornerSize2, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi * 0.5f, float_Pi);
  62719. if (targetY >= bottom)
  62720. {
  62721. outline.lineTo (targetX + arrowBaseWidth, bottom);
  62722. outline.lineTo (targetX, targetY);
  62723. outline.lineTo (targetX - arrowBaseWidth, bottom);
  62724. }
  62725. outline.lineTo (left + cornerSize, bottom);
  62726. outline.addArc (left, bottom - cornerSize2, cornerSize2, cornerSize2, float_Pi, float_Pi * 1.5f);
  62727. if (targetX <= left)
  62728. {
  62729. outline.lineTo (left, targetY + arrowBaseWidth);
  62730. outline.lineTo (targetX, targetY);
  62731. outline.lineTo (left, targetY - arrowBaseWidth);
  62732. }
  62733. outline.lineTo (left, top + cornerSize);
  62734. outline.addArc (left, top, cornerSize2, cornerSize2, float_Pi * 1.5f, float_Pi * 2.0f - 0.05f);
  62735. outline.closeSubPath();
  62736. }
  62737. END_JUCE_NAMESPACE
  62738. /*** End of inlined file: juce_CallOutBox.cpp ***/
  62739. /*** Start of inlined file: juce_ComponentPeer.cpp ***/
  62740. BEGIN_JUCE_NAMESPACE
  62741. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  62742. static Array <ComponentPeer*> heavyweightPeers;
  62743. ComponentPeer::ComponentPeer (Component* const component_, const int styleFlags_)
  62744. : component (component_),
  62745. styleFlags (styleFlags_),
  62746. lastPaintTime (0),
  62747. constrainer (0),
  62748. lastDragAndDropCompUnderMouse (0),
  62749. fakeMouseMessageSent (false),
  62750. isWindowMinimised (false)
  62751. {
  62752. heavyweightPeers.add (this);
  62753. }
  62754. ComponentPeer::~ComponentPeer()
  62755. {
  62756. heavyweightPeers.removeValue (this);
  62757. Desktop::getInstance().triggerFocusCallback();
  62758. }
  62759. int ComponentPeer::getNumPeers() throw()
  62760. {
  62761. return heavyweightPeers.size();
  62762. }
  62763. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  62764. {
  62765. return heavyweightPeers [index];
  62766. }
  62767. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  62768. {
  62769. for (int i = heavyweightPeers.size(); --i >= 0;)
  62770. {
  62771. ComponentPeer* const peer = heavyweightPeers.getUnchecked(i);
  62772. if (peer->getComponent() == component)
  62773. return peer;
  62774. }
  62775. return 0;
  62776. }
  62777. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  62778. {
  62779. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  62780. }
  62781. void ComponentPeer::updateCurrentModifiers() throw()
  62782. {
  62783. ModifierKeys::updateCurrentModifiers();
  62784. }
  62785. void ComponentPeer::handleMouseEvent (const int touchIndex, const Point<int>& positionWithinPeer, const ModifierKeys& newMods, const int64 time)
  62786. {
  62787. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62788. jassert (mouse != 0); // not enough sources!
  62789. mouse->handleEvent (this, positionWithinPeer, time, newMods);
  62790. }
  62791. void ComponentPeer::handleMouseWheel (const int touchIndex, const Point<int>& positionWithinPeer, const int64 time, const float x, const float y)
  62792. {
  62793. MouseInputSource* const mouse = Desktop::getInstance().getMouseSource (touchIndex);
  62794. jassert (mouse != 0); // not enough sources!
  62795. mouse->handleWheel (this, positionWithinPeer, time, x, y);
  62796. }
  62797. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  62798. {
  62799. Graphics g (&contextToPaintTo);
  62800. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62801. g.saveState();
  62802. #endif
  62803. JUCE_TRY
  62804. {
  62805. component->paintEntireComponent (g, true);
  62806. }
  62807. JUCE_CATCH_EXCEPTION
  62808. #if JUCE_ENABLE_REPAINT_DEBUGGING
  62809. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  62810. // clearly when things are being repainted.
  62811. {
  62812. g.restoreState();
  62813. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  62814. (uint8) Random::getSystemRandom().nextInt (255),
  62815. (uint8) Random::getSystemRandom().nextInt (255),
  62816. (uint8) 0x50));
  62817. }
  62818. #endif
  62819. /** If this fails, it's probably be because your CPU floating-point precision mode has
  62820. been set to low.. This setting is sometimes changed by things like Direct3D, and can
  62821. mess up a lot of the calculations that the library needs to do.
  62822. */
  62823. jassert (roundToInt (10.1f) == 10);
  62824. }
  62825. bool ComponentPeer::handleKeyPress (const int keyCode,
  62826. const juce_wchar textCharacter)
  62827. {
  62828. updateCurrentModifiers();
  62829. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62830. ? Component::getCurrentlyFocusedComponent()
  62831. : component;
  62832. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62833. {
  62834. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62835. if (currentModalComp != 0)
  62836. target = currentModalComp;
  62837. }
  62838. const KeyPress keyInfo (keyCode,
  62839. ModifierKeys::getCurrentModifiers().getRawFlags()
  62840. & ModifierKeys::allKeyboardModifiers,
  62841. textCharacter);
  62842. bool keyWasUsed = false;
  62843. while (target != 0)
  62844. {
  62845. const Component::SafePointer<Component> deletionChecker (target);
  62846. if (target->keyListeners_ != 0)
  62847. {
  62848. for (int i = target->keyListeners_->size(); --i >= 0;)
  62849. {
  62850. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyPressed (keyInfo, target);
  62851. if (keyWasUsed || deletionChecker == 0)
  62852. return keyWasUsed;
  62853. i = jmin (i, target->keyListeners_->size());
  62854. }
  62855. }
  62856. keyWasUsed = target->keyPressed (keyInfo);
  62857. if (keyWasUsed || deletionChecker == 0)
  62858. break;
  62859. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  62860. {
  62861. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  62862. currentlyFocused->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  62863. keyWasUsed = (currentlyFocused != Component::getCurrentlyFocusedComponent());
  62864. break;
  62865. }
  62866. target = target->parentComponent_;
  62867. }
  62868. return keyWasUsed;
  62869. }
  62870. bool ComponentPeer::handleKeyUpOrDown (const bool isKeyDown)
  62871. {
  62872. updateCurrentModifiers();
  62873. Component* target = Component::getCurrentlyFocusedComponent() != 0
  62874. ? Component::getCurrentlyFocusedComponent()
  62875. : component;
  62876. if (target->isCurrentlyBlockedByAnotherModalComponent())
  62877. {
  62878. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  62879. if (currentModalComp != 0)
  62880. target = currentModalComp;
  62881. }
  62882. bool keyWasUsed = false;
  62883. while (target != 0)
  62884. {
  62885. const Component::SafePointer<Component> deletionChecker (target);
  62886. keyWasUsed = target->keyStateChanged (isKeyDown);
  62887. if (keyWasUsed || deletionChecker == 0)
  62888. break;
  62889. if (target->keyListeners_ != 0)
  62890. {
  62891. for (int i = target->keyListeners_->size(); --i >= 0;)
  62892. {
  62893. keyWasUsed = target->keyListeners_->getUnchecked(i)->keyStateChanged (isKeyDown, target);
  62894. if (keyWasUsed || deletionChecker == 0)
  62895. return keyWasUsed;
  62896. i = jmin (i, target->keyListeners_->size());
  62897. }
  62898. }
  62899. target = target->parentComponent_;
  62900. }
  62901. return keyWasUsed;
  62902. }
  62903. void ComponentPeer::handleModifierKeysChange()
  62904. {
  62905. updateCurrentModifiers();
  62906. Component* target = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  62907. if (target == 0)
  62908. target = Component::getCurrentlyFocusedComponent();
  62909. if (target == 0)
  62910. target = component;
  62911. if (target != 0)
  62912. target->internalModifierKeysChanged();
  62913. }
  62914. TextInputTarget* ComponentPeer::findCurrentTextInputTarget()
  62915. {
  62916. Component* const c = Component::getCurrentlyFocusedComponent();
  62917. if (component->isParentOf (c))
  62918. {
  62919. TextInputTarget* const ti = dynamic_cast <TextInputTarget*> (c);
  62920. if (ti != 0 && ti->isTextInputActive())
  62921. return ti;
  62922. }
  62923. return 0;
  62924. }
  62925. void ComponentPeer::handleBroughtToFront()
  62926. {
  62927. updateCurrentModifiers();
  62928. if (component != 0)
  62929. component->internalBroughtToFront();
  62930. }
  62931. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  62932. {
  62933. constrainer = newConstrainer;
  62934. }
  62935. void ComponentPeer::handleMovedOrResized()
  62936. {
  62937. jassert (component->isValidComponent());
  62938. updateCurrentModifiers();
  62939. const bool nowMinimised = isMinimised();
  62940. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  62941. {
  62942. const Component::SafePointer<Component> deletionChecker (component);
  62943. const Rectangle<int> newBounds (getBounds());
  62944. const bool wasMoved = (component->getPosition() != newBounds.getPosition());
  62945. const bool wasResized = (component->getWidth() != newBounds.getWidth() || component->getHeight() != newBounds.getHeight());
  62946. if (wasMoved || wasResized)
  62947. {
  62948. component->bounds_ = newBounds;
  62949. if (wasResized)
  62950. component->repaint();
  62951. component->sendMovedResizedMessages (wasMoved, wasResized);
  62952. if (deletionChecker == 0)
  62953. return;
  62954. }
  62955. }
  62956. if (isWindowMinimised != nowMinimised)
  62957. {
  62958. isWindowMinimised = nowMinimised;
  62959. component->minimisationStateChanged (nowMinimised);
  62960. component->sendVisibilityChangeMessage();
  62961. }
  62962. if (! isFullScreen())
  62963. lastNonFullscreenBounds = component->getBounds();
  62964. }
  62965. void ComponentPeer::handleFocusGain()
  62966. {
  62967. updateCurrentModifiers();
  62968. if (component->isParentOf (lastFocusedComponent))
  62969. {
  62970. Component::currentlyFocusedComponent = lastFocusedComponent;
  62971. Desktop::getInstance().triggerFocusCallback();
  62972. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  62973. }
  62974. else
  62975. {
  62976. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  62977. component->grabKeyboardFocus();
  62978. else
  62979. Component::bringModalComponentToFront();
  62980. }
  62981. }
  62982. void ComponentPeer::handleFocusLoss()
  62983. {
  62984. updateCurrentModifiers();
  62985. if (component->hasKeyboardFocus (true))
  62986. {
  62987. lastFocusedComponent = Component::currentlyFocusedComponent;
  62988. if (lastFocusedComponent != 0)
  62989. {
  62990. Component::currentlyFocusedComponent = 0;
  62991. Desktop::getInstance().triggerFocusCallback();
  62992. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  62993. }
  62994. }
  62995. }
  62996. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  62997. {
  62998. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  62999. ? static_cast <Component*> (lastFocusedComponent)
  63000. : component;
  63001. }
  63002. void ComponentPeer::handleScreenSizeChange()
  63003. {
  63004. updateCurrentModifiers();
  63005. component->parentSizeChanged();
  63006. handleMovedOrResized();
  63007. }
  63008. void ComponentPeer::setNonFullScreenBounds (const Rectangle<int>& newBounds) throw()
  63009. {
  63010. lastNonFullscreenBounds = newBounds;
  63011. }
  63012. const Rectangle<int>& ComponentPeer::getNonFullScreenBounds() const throw()
  63013. {
  63014. return lastNonFullscreenBounds;
  63015. }
  63016. namespace ComponentPeerHelpers
  63017. {
  63018. FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  63019. const StringArray& files,
  63020. FileDragAndDropTarget* const lastOne)
  63021. {
  63022. while (c != 0)
  63023. {
  63024. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  63025. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  63026. return t;
  63027. c = c->getParentComponent();
  63028. }
  63029. return 0;
  63030. }
  63031. }
  63032. void ComponentPeer::handleFileDragMove (const StringArray& files, const Point<int>& position)
  63033. {
  63034. updateCurrentModifiers();
  63035. FileDragAndDropTarget* lastTarget
  63036. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63037. FileDragAndDropTarget* newTarget = 0;
  63038. Component* const compUnderMouse = component->getComponentAt (position);
  63039. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  63040. {
  63041. lastDragAndDropCompUnderMouse = compUnderMouse;
  63042. newTarget = ComponentPeerHelpers::findDragAndDropTarget (compUnderMouse, files, lastTarget);
  63043. if (newTarget != lastTarget)
  63044. {
  63045. if (lastTarget != 0)
  63046. lastTarget->fileDragExit (files);
  63047. dragAndDropTargetComponent = 0;
  63048. if (newTarget != 0)
  63049. {
  63050. dragAndDropTargetComponent = dynamic_cast <Component*> (newTarget);
  63051. const Point<int> pos (component->relativePositionToOtherComponent (dragAndDropTargetComponent, position));
  63052. newTarget->fileDragEnter (files, pos.getX(), pos.getY());
  63053. }
  63054. }
  63055. }
  63056. else
  63057. {
  63058. newTarget = lastTarget;
  63059. }
  63060. if (newTarget != 0)
  63061. {
  63062. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  63063. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63064. newTarget->fileDragMove (files, pos.getX(), pos.getY());
  63065. }
  63066. }
  63067. void ComponentPeer::handleFileDragExit (const StringArray& files)
  63068. {
  63069. handleFileDragMove (files, Point<int> (-1, -1));
  63070. jassert (dragAndDropTargetComponent == 0);
  63071. lastDragAndDropCompUnderMouse = 0;
  63072. }
  63073. void ComponentPeer::handleFileDragDrop (const StringArray& files, const Point<int>& position)
  63074. {
  63075. handleFileDragMove (files, position);
  63076. if (dragAndDropTargetComponent != 0)
  63077. {
  63078. FileDragAndDropTarget* const target
  63079. = dynamic_cast<FileDragAndDropTarget*> (static_cast<Component*> (dragAndDropTargetComponent));
  63080. dragAndDropTargetComponent = 0;
  63081. lastDragAndDropCompUnderMouse = 0;
  63082. if (target != 0)
  63083. {
  63084. Component* const targetComp = dynamic_cast <Component*> (target);
  63085. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63086. {
  63087. targetComp->internalModalInputAttempt();
  63088. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  63089. return;
  63090. }
  63091. const Point<int> pos (component->relativePositionToOtherComponent (targetComp, position));
  63092. target->filesDropped (files, pos.getX(), pos.getY());
  63093. }
  63094. }
  63095. }
  63096. void ComponentPeer::handleUserClosingWindow()
  63097. {
  63098. updateCurrentModifiers();
  63099. component->userTriedToCloseWindow();
  63100. }
  63101. void ComponentPeer::bringModalComponentToFront()
  63102. {
  63103. Component::bringModalComponentToFront();
  63104. }
  63105. void ComponentPeer::clearMaskedRegion()
  63106. {
  63107. maskedRegion.clear();
  63108. }
  63109. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h)
  63110. {
  63111. maskedRegion.add (x, y, w, h);
  63112. }
  63113. const StringArray ComponentPeer::getAvailableRenderingEngines()
  63114. {
  63115. StringArray s;
  63116. s.add ("Software Renderer");
  63117. return s;
  63118. }
  63119. int ComponentPeer::getCurrentRenderingEngine() throw()
  63120. {
  63121. return 0;
  63122. }
  63123. void ComponentPeer::setCurrentRenderingEngine (int /*index*/)
  63124. {
  63125. }
  63126. END_JUCE_NAMESPACE
  63127. /*** End of inlined file: juce_ComponentPeer.cpp ***/
  63128. /*** Start of inlined file: juce_DialogWindow.cpp ***/
  63129. BEGIN_JUCE_NAMESPACE
  63130. DialogWindow::DialogWindow (const String& name,
  63131. const Colour& backgroundColour_,
  63132. const bool escapeKeyTriggersCloseButton_,
  63133. const bool addToDesktop_)
  63134. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  63135. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  63136. {
  63137. }
  63138. DialogWindow::~DialogWindow()
  63139. {
  63140. }
  63141. void DialogWindow::resized()
  63142. {
  63143. DocumentWindow::resized();
  63144. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  63145. if (escapeKeyTriggersCloseButton
  63146. && getCloseButton() != 0
  63147. && ! getCloseButton()->isRegisteredForShortcut (esc))
  63148. {
  63149. getCloseButton()->addShortcut (esc);
  63150. }
  63151. }
  63152. class TempDialogWindow : public DialogWindow
  63153. {
  63154. public:
  63155. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  63156. : DialogWindow (title, colour, escapeCloses, true)
  63157. {
  63158. if (! JUCEApplication::isStandaloneApp())
  63159. setAlwaysOnTop (true); // for a plugin, make it always-on-top because the host windows are often top-level
  63160. }
  63161. ~TempDialogWindow()
  63162. {
  63163. }
  63164. void closeButtonPressed()
  63165. {
  63166. setVisible (false);
  63167. }
  63168. private:
  63169. TempDialogWindow (const TempDialogWindow&);
  63170. TempDialogWindow& operator= (const TempDialogWindow&);
  63171. };
  63172. int DialogWindow::showModalDialog (const String& dialogTitle,
  63173. Component* contentComponent,
  63174. Component* componentToCentreAround,
  63175. const Colour& colour,
  63176. const bool escapeKeyTriggersCloseButton,
  63177. const bool shouldBeResizable,
  63178. const bool useBottomRightCornerResizer)
  63179. {
  63180. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  63181. dw.setContentComponent (contentComponent, true, true);
  63182. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  63183. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63184. const int result = dw.runModalLoop();
  63185. dw.setContentComponent (0, false);
  63186. return result;
  63187. }
  63188. END_JUCE_NAMESPACE
  63189. /*** End of inlined file: juce_DialogWindow.cpp ***/
  63190. /*** Start of inlined file: juce_DocumentWindow.cpp ***/
  63191. BEGIN_JUCE_NAMESPACE
  63192. class DocumentWindow::ButtonListenerProxy : public ButtonListener // (can't use Button::Listener due to idiotic VC2005 bug)
  63193. {
  63194. public:
  63195. ButtonListenerProxy (DocumentWindow& owner_)
  63196. : owner (owner_)
  63197. {
  63198. }
  63199. void buttonClicked (Button* button)
  63200. {
  63201. if (button == owner.getMinimiseButton())
  63202. owner.minimiseButtonPressed();
  63203. else if (button == owner.getMaximiseButton())
  63204. owner.maximiseButtonPressed();
  63205. else if (button == owner.getCloseButton())
  63206. owner.closeButtonPressed();
  63207. }
  63208. juce_UseDebuggingNewOperator
  63209. private:
  63210. DocumentWindow& owner;
  63211. ButtonListenerProxy (const ButtonListenerProxy&);
  63212. ButtonListenerProxy& operator= (const ButtonListenerProxy&);
  63213. };
  63214. DocumentWindow::DocumentWindow (const String& title,
  63215. const Colour& backgroundColour,
  63216. const int requiredButtons_,
  63217. const bool addToDesktop_)
  63218. : ResizableWindow (title, backgroundColour, addToDesktop_),
  63219. titleBarHeight (26),
  63220. menuBarHeight (24),
  63221. requiredButtons (requiredButtons_),
  63222. #if JUCE_MAC
  63223. positionTitleBarButtonsOnLeft (true),
  63224. #else
  63225. positionTitleBarButtonsOnLeft (false),
  63226. #endif
  63227. drawTitleTextCentred (true),
  63228. menuBarModel (0)
  63229. {
  63230. setResizeLimits (128, 128, 32768, 32768);
  63231. lookAndFeelChanged();
  63232. }
  63233. DocumentWindow::~DocumentWindow()
  63234. {
  63235. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63236. titleBarButtons[i] = 0;
  63237. menuBar = 0;
  63238. }
  63239. void DocumentWindow::repaintTitleBar()
  63240. {
  63241. repaint (getTitleBarArea());
  63242. }
  63243. void DocumentWindow::setName (const String& newName)
  63244. {
  63245. if (newName != getName())
  63246. {
  63247. Component::setName (newName);
  63248. repaintTitleBar();
  63249. }
  63250. }
  63251. void DocumentWindow::setIcon (const Image& imageToUse)
  63252. {
  63253. titleBarIcon = imageToUse;
  63254. repaintTitleBar();
  63255. }
  63256. void DocumentWindow::setTitleBarHeight (const int newHeight)
  63257. {
  63258. titleBarHeight = newHeight;
  63259. resized();
  63260. repaintTitleBar();
  63261. }
  63262. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  63263. const bool positionTitleBarButtonsOnLeft_)
  63264. {
  63265. requiredButtons = requiredButtons_;
  63266. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  63267. lookAndFeelChanged();
  63268. }
  63269. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  63270. {
  63271. drawTitleTextCentred = textShouldBeCentred;
  63272. repaintTitleBar();
  63273. }
  63274. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  63275. const int menuBarHeight_)
  63276. {
  63277. if (menuBarModel != menuBarModel_)
  63278. {
  63279. menuBar = 0;
  63280. menuBarModel = menuBarModel_;
  63281. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  63282. : getLookAndFeel().getDefaultMenuBarHeight();
  63283. if (menuBarModel != 0)
  63284. {
  63285. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63286. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  63287. menuBar->setEnabled (isActiveWindow());
  63288. }
  63289. resized();
  63290. }
  63291. }
  63292. void DocumentWindow::closeButtonPressed()
  63293. {
  63294. /* If you've got a close button, you have to override this method to get
  63295. rid of your window!
  63296. If the window is just a pop-up, you should override this method and make
  63297. it delete the window in whatever way is appropriate for your app. E.g. you
  63298. might just want to call "delete this".
  63299. If your app is centred around this window such that the whole app should quit when
  63300. the window is closed, then you will probably want to use this method as an opportunity
  63301. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  63302. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  63303. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  63304. or closing it via the taskbar icon on Windows).
  63305. */
  63306. jassertfalse;
  63307. }
  63308. void DocumentWindow::minimiseButtonPressed()
  63309. {
  63310. setMinimised (true);
  63311. }
  63312. void DocumentWindow::maximiseButtonPressed()
  63313. {
  63314. setFullScreen (! isFullScreen());
  63315. }
  63316. void DocumentWindow::paint (Graphics& g)
  63317. {
  63318. ResizableWindow::paint (g);
  63319. if (resizableBorder == 0)
  63320. {
  63321. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  63322. const BorderSize border (getBorderThickness());
  63323. g.fillRect (0, 0, getWidth(), border.getTop());
  63324. g.fillRect (0, border.getTop(), border.getLeft(), getHeight() - border.getTopAndBottom());
  63325. g.fillRect (getWidth() - border.getRight(), border.getTop(), border.getRight(), getHeight() - border.getTopAndBottom());
  63326. g.fillRect (0, getHeight() - border.getBottom(), getWidth(), border.getBottom());
  63327. }
  63328. const Rectangle<int> titleBarArea (getTitleBarArea());
  63329. g.reduceClipRegion (titleBarArea);
  63330. g.setOrigin (titleBarArea.getX(), titleBarArea.getY());
  63331. int titleSpaceX1 = 6;
  63332. int titleSpaceX2 = titleBarArea.getWidth() - 6;
  63333. for (int i = 0; i < 3; ++i)
  63334. {
  63335. if (titleBarButtons[i] != 0)
  63336. {
  63337. if (positionTitleBarButtonsOnLeft)
  63338. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  63339. else
  63340. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  63341. }
  63342. }
  63343. getLookAndFeel().drawDocumentWindowTitleBar (*this, g,
  63344. titleBarArea.getWidth(),
  63345. titleBarArea.getHeight(),
  63346. titleSpaceX1,
  63347. jmax (1, titleSpaceX2 - titleSpaceX1),
  63348. titleBarIcon.isValid() ? &titleBarIcon : 0,
  63349. ! drawTitleTextCentred);
  63350. }
  63351. void DocumentWindow::resized()
  63352. {
  63353. ResizableWindow::resized();
  63354. if (titleBarButtons[1] != 0)
  63355. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  63356. const Rectangle<int> titleBarArea (getTitleBarArea());
  63357. getLookAndFeel()
  63358. .positionDocumentWindowButtons (*this,
  63359. titleBarArea.getX(), titleBarArea.getY(),
  63360. titleBarArea.getWidth(), titleBarArea.getHeight(),
  63361. titleBarButtons[0],
  63362. titleBarButtons[1],
  63363. titleBarButtons[2],
  63364. positionTitleBarButtonsOnLeft);
  63365. if (menuBar != 0)
  63366. menuBar->setBounds (titleBarArea.getX(), titleBarArea.getBottom(),
  63367. titleBarArea.getWidth(), menuBarHeight);
  63368. }
  63369. const BorderSize DocumentWindow::getBorderThickness()
  63370. {
  63371. return BorderSize ((isFullScreen() || isUsingNativeTitleBar())
  63372. ? 0 : (resizableBorder != 0 ? 4 : 1));
  63373. }
  63374. const BorderSize DocumentWindow::getContentComponentBorder()
  63375. {
  63376. BorderSize border (getBorderThickness());
  63377. border.setTop (border.getTop()
  63378. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  63379. + (menuBar != 0 ? menuBarHeight : 0));
  63380. return border;
  63381. }
  63382. int DocumentWindow::getTitleBarHeight() const
  63383. {
  63384. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  63385. }
  63386. const Rectangle<int> DocumentWindow::getTitleBarArea()
  63387. {
  63388. const BorderSize border (getBorderThickness());
  63389. return Rectangle<int> (border.getLeft(), border.getTop(),
  63390. getWidth() - border.getLeftAndRight(),
  63391. getTitleBarHeight());
  63392. }
  63393. Button* DocumentWindow::getCloseButton() const throw()
  63394. {
  63395. return titleBarButtons[2];
  63396. }
  63397. Button* DocumentWindow::getMinimiseButton() const throw()
  63398. {
  63399. return titleBarButtons[0];
  63400. }
  63401. Button* DocumentWindow::getMaximiseButton() const throw()
  63402. {
  63403. return titleBarButtons[1];
  63404. }
  63405. int DocumentWindow::getDesktopWindowStyleFlags() const
  63406. {
  63407. int styleFlags = ResizableWindow::getDesktopWindowStyleFlags();
  63408. if ((requiredButtons & minimiseButton) != 0)
  63409. styleFlags |= ComponentPeer::windowHasMinimiseButton;
  63410. if ((requiredButtons & maximiseButton) != 0)
  63411. styleFlags |= ComponentPeer::windowHasMaximiseButton;
  63412. if ((requiredButtons & closeButton) != 0)
  63413. styleFlags |= ComponentPeer::windowHasCloseButton;
  63414. return styleFlags;
  63415. }
  63416. void DocumentWindow::lookAndFeelChanged()
  63417. {
  63418. int i;
  63419. for (i = numElementsInArray (titleBarButtons); --i >= 0;)
  63420. titleBarButtons[i] = 0;
  63421. if (! isUsingNativeTitleBar())
  63422. {
  63423. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  63424. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  63425. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  63426. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  63427. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  63428. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  63429. for (i = 0; i < 3; ++i)
  63430. {
  63431. if (titleBarButtons[i] != 0)
  63432. {
  63433. if (buttonListener == 0)
  63434. buttonListener = new ButtonListenerProxy (*this);
  63435. titleBarButtons[i]->addButtonListener (buttonListener);
  63436. titleBarButtons[i]->setWantsKeyboardFocus (false);
  63437. // (call the Component method directly to avoid the assertion in ResizableWindow)
  63438. Component::addAndMakeVisible (titleBarButtons[i]);
  63439. }
  63440. }
  63441. if (getCloseButton() != 0)
  63442. {
  63443. #if JUCE_MAC
  63444. getCloseButton()->addShortcut (KeyPress ('w', ModifierKeys::commandModifier, 0));
  63445. #else
  63446. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  63447. #endif
  63448. }
  63449. }
  63450. activeWindowStatusChanged();
  63451. ResizableWindow::lookAndFeelChanged();
  63452. }
  63453. void DocumentWindow::parentHierarchyChanged()
  63454. {
  63455. lookAndFeelChanged();
  63456. }
  63457. void DocumentWindow::activeWindowStatusChanged()
  63458. {
  63459. ResizableWindow::activeWindowStatusChanged();
  63460. for (int i = numElementsInArray (titleBarButtons); --i >= 0;)
  63461. if (titleBarButtons[i] != 0)
  63462. titleBarButtons[i]->setEnabled (isActiveWindow());
  63463. if (menuBar != 0)
  63464. menuBar->setEnabled (isActiveWindow());
  63465. }
  63466. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  63467. {
  63468. if (getTitleBarArea().contains (e.x, e.y)
  63469. && getMaximiseButton() != 0)
  63470. {
  63471. getMaximiseButton()->triggerClick();
  63472. }
  63473. }
  63474. void DocumentWindow::userTriedToCloseWindow()
  63475. {
  63476. closeButtonPressed();
  63477. }
  63478. END_JUCE_NAMESPACE
  63479. /*** End of inlined file: juce_DocumentWindow.cpp ***/
  63480. /*** Start of inlined file: juce_ResizableWindow.cpp ***/
  63481. BEGIN_JUCE_NAMESPACE
  63482. ResizableWindow::ResizableWindow (const String& name,
  63483. const bool addToDesktop_)
  63484. : TopLevelWindow (name, addToDesktop_),
  63485. resizeToFitContent (false),
  63486. fullscreen (false),
  63487. lastNonFullScreenPos (50, 50, 256, 256),
  63488. constrainer (0)
  63489. #if JUCE_DEBUG
  63490. , hasBeenResized (false)
  63491. #endif
  63492. {
  63493. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63494. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  63495. if (addToDesktop_)
  63496. Component::addToDesktop (getDesktopWindowStyleFlags());
  63497. }
  63498. ResizableWindow::ResizableWindow (const String& name,
  63499. const Colour& backgroundColour_,
  63500. const bool addToDesktop_)
  63501. : TopLevelWindow (name, addToDesktop_),
  63502. resizeToFitContent (false),
  63503. fullscreen (false),
  63504. lastNonFullScreenPos (50, 50, 256, 256),
  63505. constrainer (0)
  63506. #if JUCE_DEBUG
  63507. , hasBeenResized (false)
  63508. #endif
  63509. {
  63510. setBackgroundColour (backgroundColour_);
  63511. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  63512. if (addToDesktop_)
  63513. Component::addToDesktop (getDesktopWindowStyleFlags());
  63514. }
  63515. ResizableWindow::~ResizableWindow()
  63516. {
  63517. resizableCorner = 0;
  63518. resizableBorder = 0;
  63519. contentComponent.deleteAndZero();
  63520. // have you been adding your own components directly to this window..? tut tut tut.
  63521. // Read the instructions for using a ResizableWindow!
  63522. jassert (getNumChildComponents() == 0);
  63523. }
  63524. int ResizableWindow::getDesktopWindowStyleFlags() const
  63525. {
  63526. int styleFlags = TopLevelWindow::getDesktopWindowStyleFlags();
  63527. if (isResizable() && (styleFlags & ComponentPeer::windowHasTitleBar) != 0)
  63528. styleFlags |= ComponentPeer::windowIsResizable;
  63529. return styleFlags;
  63530. }
  63531. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  63532. const bool deleteOldOne,
  63533. const bool resizeToFit)
  63534. {
  63535. resizeToFitContent = resizeToFit;
  63536. if (newContentComponent != static_cast <Component*> (contentComponent))
  63537. {
  63538. if (deleteOldOne)
  63539. contentComponent.deleteAndZero(); // (avoid using a scoped pointer for this, so that it survives
  63540. // external deletion of the content comp)
  63541. else
  63542. removeChildComponent (contentComponent);
  63543. contentComponent = newContentComponent;
  63544. Component::addAndMakeVisible (contentComponent);
  63545. }
  63546. if (resizeToFit)
  63547. childBoundsChanged (contentComponent);
  63548. resized(); // must always be called to position the new content comp
  63549. }
  63550. void ResizableWindow::setContentComponentSize (int width, int height)
  63551. {
  63552. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  63553. const BorderSize border (getContentComponentBorder());
  63554. setSize (width + border.getLeftAndRight(),
  63555. height + border.getTopAndBottom());
  63556. }
  63557. const BorderSize ResizableWindow::getBorderThickness()
  63558. {
  63559. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  63560. }
  63561. const BorderSize ResizableWindow::getContentComponentBorder()
  63562. {
  63563. return getBorderThickness();
  63564. }
  63565. void ResizableWindow::moved()
  63566. {
  63567. updateLastPos();
  63568. }
  63569. void ResizableWindow::visibilityChanged()
  63570. {
  63571. TopLevelWindow::visibilityChanged();
  63572. updateLastPos();
  63573. }
  63574. void ResizableWindow::resized()
  63575. {
  63576. if (resizableBorder != 0)
  63577. {
  63578. #if JUCE_WINDOWS || JUCE_LINUX
  63579. // hide the resizable border if the OS already provides one..
  63580. resizableBorder->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63581. #else
  63582. resizableBorder->setVisible (! isFullScreen());
  63583. #endif
  63584. resizableBorder->setBorderThickness (getBorderThickness());
  63585. resizableBorder->setSize (getWidth(), getHeight());
  63586. resizableBorder->toBack();
  63587. }
  63588. if (resizableCorner != 0)
  63589. {
  63590. #if JUCE_MAC
  63591. // hide the resizable border if the OS already provides one..
  63592. resizableCorner->setVisible (! (isFullScreen() || isUsingNativeTitleBar()));
  63593. #else
  63594. resizableCorner->setVisible (! isFullScreen());
  63595. #endif
  63596. const int resizerSize = 18;
  63597. resizableCorner->setBounds (getWidth() - resizerSize,
  63598. getHeight() - resizerSize,
  63599. resizerSize, resizerSize);
  63600. }
  63601. if (contentComponent != 0)
  63602. contentComponent->setBoundsInset (getContentComponentBorder());
  63603. updateLastPos();
  63604. #if JUCE_DEBUG
  63605. hasBeenResized = true;
  63606. #endif
  63607. }
  63608. void ResizableWindow::childBoundsChanged (Component* child)
  63609. {
  63610. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  63611. {
  63612. // not going to look very good if this component has a zero size..
  63613. jassert (child->getWidth() > 0);
  63614. jassert (child->getHeight() > 0);
  63615. const BorderSize borders (getContentComponentBorder());
  63616. setSize (child->getWidth() + borders.getLeftAndRight(),
  63617. child->getHeight() + borders.getTopAndBottom());
  63618. }
  63619. }
  63620. void ResizableWindow::activeWindowStatusChanged()
  63621. {
  63622. const BorderSize border (getContentComponentBorder());
  63623. Rectangle<int> area (getLocalBounds());
  63624. repaint (area.removeFromTop (border.getTop()));
  63625. repaint (area.removeFromLeft (border.getLeft()));
  63626. repaint (area.removeFromRight (border.getRight()));
  63627. repaint (area.removeFromBottom (border.getBottom()));
  63628. }
  63629. void ResizableWindow::setResizable (const bool shouldBeResizable,
  63630. const bool useBottomRightCornerResizer)
  63631. {
  63632. if (shouldBeResizable)
  63633. {
  63634. if (useBottomRightCornerResizer)
  63635. {
  63636. resizableBorder = 0;
  63637. if (resizableCorner == 0)
  63638. {
  63639. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  63640. resizableCorner->setAlwaysOnTop (true);
  63641. }
  63642. }
  63643. else
  63644. {
  63645. resizableCorner = 0;
  63646. if (resizableBorder == 0)
  63647. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  63648. }
  63649. }
  63650. else
  63651. {
  63652. resizableCorner = 0;
  63653. resizableBorder = 0;
  63654. }
  63655. if (isUsingNativeTitleBar())
  63656. recreateDesktopWindow();
  63657. childBoundsChanged (contentComponent);
  63658. resized();
  63659. }
  63660. bool ResizableWindow::isResizable() const throw()
  63661. {
  63662. return resizableCorner != 0
  63663. || resizableBorder != 0;
  63664. }
  63665. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  63666. const int newMinimumHeight,
  63667. const int newMaximumWidth,
  63668. const int newMaximumHeight) throw()
  63669. {
  63670. // if you've set up a custom constrainer then these settings won't have any effect..
  63671. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  63672. if (constrainer == 0)
  63673. setConstrainer (&defaultConstrainer);
  63674. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  63675. newMaximumWidth, newMaximumHeight);
  63676. setBoundsConstrained (getBounds());
  63677. }
  63678. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  63679. {
  63680. if (constrainer != newConstrainer)
  63681. {
  63682. constrainer = newConstrainer;
  63683. const bool useBottomRightCornerResizer = resizableCorner != 0;
  63684. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  63685. resizableCorner = 0;
  63686. resizableBorder = 0;
  63687. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  63688. ComponentPeer* const peer = getPeer();
  63689. if (peer != 0)
  63690. peer->setConstrainer (newConstrainer);
  63691. }
  63692. }
  63693. void ResizableWindow::setBoundsConstrained (const Rectangle<int>& bounds)
  63694. {
  63695. if (constrainer != 0)
  63696. constrainer->setBoundsForComponent (this, bounds, false, false, false, false);
  63697. else
  63698. setBounds (bounds);
  63699. }
  63700. void ResizableWindow::paint (Graphics& g)
  63701. {
  63702. getLookAndFeel().fillResizableWindowBackground (g, getWidth(), getHeight(),
  63703. getBorderThickness(), *this);
  63704. if (! isFullScreen())
  63705. {
  63706. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  63707. getBorderThickness(), *this);
  63708. }
  63709. #if JUCE_DEBUG
  63710. /* If this fails, then you've probably written a subclass with a resized()
  63711. callback but forgotten to make it call its parent class's resized() method.
  63712. It's important when you override methods like resized(), moved(),
  63713. etc., that you make sure the base class methods also get called.
  63714. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  63715. because your content should all be inside the content component - and it's the
  63716. content component's resized() method that you should be using to do your
  63717. layout.
  63718. */
  63719. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  63720. #endif
  63721. }
  63722. void ResizableWindow::lookAndFeelChanged()
  63723. {
  63724. resized();
  63725. if (isOnDesktop())
  63726. {
  63727. Component::addToDesktop (getDesktopWindowStyleFlags());
  63728. ComponentPeer* const peer = getPeer();
  63729. if (peer != 0)
  63730. peer->setConstrainer (constrainer);
  63731. }
  63732. }
  63733. const Colour ResizableWindow::getBackgroundColour() const throw()
  63734. {
  63735. return findColour (backgroundColourId, false);
  63736. }
  63737. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  63738. {
  63739. Colour backgroundColour (newColour);
  63740. if (! Desktop::canUseSemiTransparentWindows())
  63741. backgroundColour = newColour.withAlpha (1.0f);
  63742. setColour (backgroundColourId, backgroundColour);
  63743. setOpaque (backgroundColour.isOpaque());
  63744. repaint();
  63745. }
  63746. bool ResizableWindow::isFullScreen() const
  63747. {
  63748. if (isOnDesktop())
  63749. {
  63750. ComponentPeer* const peer = getPeer();
  63751. return peer != 0 && peer->isFullScreen();
  63752. }
  63753. return fullscreen;
  63754. }
  63755. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  63756. {
  63757. if (shouldBeFullScreen != isFullScreen())
  63758. {
  63759. updateLastPos();
  63760. fullscreen = shouldBeFullScreen;
  63761. if (isOnDesktop())
  63762. {
  63763. ComponentPeer* const peer = getPeer();
  63764. if (peer != 0)
  63765. {
  63766. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  63767. const Rectangle<int> lastPos (lastNonFullScreenPos);
  63768. peer->setFullScreen (shouldBeFullScreen);
  63769. if ((! shouldBeFullScreen) && ! lastPos.isEmpty())
  63770. setBounds (lastPos);
  63771. }
  63772. else
  63773. {
  63774. jassertfalse;
  63775. }
  63776. }
  63777. else
  63778. {
  63779. if (shouldBeFullScreen)
  63780. setBounds (0, 0, getParentWidth(), getParentHeight());
  63781. else
  63782. setBounds (lastNonFullScreenPos);
  63783. }
  63784. resized();
  63785. }
  63786. }
  63787. bool ResizableWindow::isMinimised() const
  63788. {
  63789. ComponentPeer* const peer = getPeer();
  63790. return (peer != 0) && peer->isMinimised();
  63791. }
  63792. void ResizableWindow::setMinimised (const bool shouldMinimise)
  63793. {
  63794. if (shouldMinimise != isMinimised())
  63795. {
  63796. ComponentPeer* const peer = getPeer();
  63797. if (peer != 0)
  63798. {
  63799. updateLastPos();
  63800. peer->setMinimised (shouldMinimise);
  63801. }
  63802. else
  63803. {
  63804. jassertfalse;
  63805. }
  63806. }
  63807. }
  63808. void ResizableWindow::updateLastPos()
  63809. {
  63810. if (isShowing() && ! (isFullScreen() || isMinimised()))
  63811. {
  63812. lastNonFullScreenPos = getBounds();
  63813. }
  63814. }
  63815. void ResizableWindow::parentSizeChanged()
  63816. {
  63817. if (isFullScreen() && getParentComponent() != 0)
  63818. {
  63819. setBounds (0, 0, getParentWidth(), getParentHeight());
  63820. }
  63821. }
  63822. const String ResizableWindow::getWindowStateAsString()
  63823. {
  63824. updateLastPos();
  63825. return (isFullScreen() ? "fs " : "") + lastNonFullScreenPos.toString();
  63826. }
  63827. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  63828. {
  63829. StringArray tokens;
  63830. tokens.addTokens (s, false);
  63831. tokens.removeEmptyStrings();
  63832. tokens.trim();
  63833. const bool fs = tokens[0].startsWithIgnoreCase ("fs");
  63834. const int firstCoord = fs ? 1 : 0;
  63835. if (tokens.size() != firstCoord + 4)
  63836. return false;
  63837. Rectangle<int> newPos (tokens[firstCoord].getIntValue(),
  63838. tokens[firstCoord + 1].getIntValue(),
  63839. tokens[firstCoord + 2].getIntValue(),
  63840. tokens[firstCoord + 3].getIntValue());
  63841. if (newPos.isEmpty())
  63842. return false;
  63843. const Rectangle<int> screen (Desktop::getInstance().getMonitorAreaContaining (newPos.getCentre()));
  63844. ComponentPeer* const peer = isOnDesktop() ? getPeer() : 0;
  63845. if (peer != 0)
  63846. peer->getFrameSize().addTo (newPos);
  63847. if (! screen.contains (newPos))
  63848. {
  63849. newPos.setSize (jmin (newPos.getWidth(), screen.getWidth()),
  63850. jmin (newPos.getHeight(), screen.getHeight()));
  63851. newPos.setPosition (jlimit (screen.getX(), screen.getRight() - newPos.getWidth(), newPos.getX()),
  63852. jlimit (screen.getY(), screen.getBottom() - newPos.getHeight(), newPos.getY()));
  63853. }
  63854. if (peer != 0)
  63855. {
  63856. peer->getFrameSize().subtractFrom (newPos);
  63857. peer->setNonFullScreenBounds (newPos);
  63858. }
  63859. lastNonFullScreenPos = newPos;
  63860. setFullScreen (fs);
  63861. if (! fs)
  63862. setBoundsConstrained (newPos);
  63863. return true;
  63864. }
  63865. void ResizableWindow::mouseDown (const MouseEvent&)
  63866. {
  63867. if (! isFullScreen())
  63868. dragger.startDraggingComponent (this, constrainer);
  63869. }
  63870. void ResizableWindow::mouseDrag (const MouseEvent& e)
  63871. {
  63872. if (! isFullScreen())
  63873. dragger.dragComponent (this, e);
  63874. }
  63875. #if JUCE_DEBUG
  63876. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  63877. {
  63878. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63879. manages its child components automatically, and if you add your own it'll cause
  63880. trouble. Instead, use setContentComponent() to give it a component which
  63881. will be automatically resized and kept in the right place - then you can add
  63882. subcomponents to the content comp. See the notes for the ResizableWindow class
  63883. for more info.
  63884. If you really know what you're doing and want to avoid this assertion, just call
  63885. Component::addChildComponent directly.
  63886. */
  63887. jassertfalse;
  63888. Component::addChildComponent (child, zOrder);
  63889. }
  63890. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  63891. {
  63892. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  63893. manages its child components automatically, and if you add your own it'll cause
  63894. trouble. Instead, use setContentComponent() to give it a component which
  63895. will be automatically resized and kept in the right place - then you can add
  63896. subcomponents to the content comp. See the notes for the ResizableWindow class
  63897. for more info.
  63898. If you really know what you're doing and want to avoid this assertion, just call
  63899. Component::addAndMakeVisible directly.
  63900. */
  63901. jassertfalse;
  63902. Component::addAndMakeVisible (child, zOrder);
  63903. }
  63904. #endif
  63905. END_JUCE_NAMESPACE
  63906. /*** End of inlined file: juce_ResizableWindow.cpp ***/
  63907. /*** Start of inlined file: juce_SplashScreen.cpp ***/
  63908. BEGIN_JUCE_NAMESPACE
  63909. SplashScreen::SplashScreen()
  63910. {
  63911. setOpaque (true);
  63912. }
  63913. SplashScreen::~SplashScreen()
  63914. {
  63915. }
  63916. void SplashScreen::show (const String& title,
  63917. const Image& backgroundImage_,
  63918. const int minimumTimeToDisplayFor,
  63919. const bool useDropShadow,
  63920. const bool removeOnMouseClick)
  63921. {
  63922. backgroundImage = backgroundImage_;
  63923. jassert (backgroundImage_.isValid());
  63924. if (backgroundImage_.isValid())
  63925. {
  63926. setOpaque (! backgroundImage_.hasAlphaChannel());
  63927. show (title,
  63928. backgroundImage_.getWidth(),
  63929. backgroundImage_.getHeight(),
  63930. minimumTimeToDisplayFor,
  63931. useDropShadow,
  63932. removeOnMouseClick);
  63933. }
  63934. }
  63935. void SplashScreen::show (const String& title,
  63936. const int width,
  63937. const int height,
  63938. const int minimumTimeToDisplayFor,
  63939. const bool useDropShadow,
  63940. const bool removeOnMouseClick)
  63941. {
  63942. setName (title);
  63943. setAlwaysOnTop (true);
  63944. setVisible (true);
  63945. centreWithSize (width, height);
  63946. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  63947. toFront (false);
  63948. MessageManager::getInstance()->runDispatchLoopUntil (300);
  63949. repaint();
  63950. originalClickCounter = removeOnMouseClick
  63951. ? Desktop::getMouseButtonClickCounter()
  63952. : std::numeric_limits<int>::max();
  63953. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  63954. startTimer (50);
  63955. }
  63956. void SplashScreen::paint (Graphics& g)
  63957. {
  63958. g.setOpacity (1.0f);
  63959. g.drawImage (backgroundImage,
  63960. 0, 0, getWidth(), getHeight(),
  63961. 0, 0, backgroundImage.getWidth(), backgroundImage.getHeight());
  63962. }
  63963. void SplashScreen::timerCallback()
  63964. {
  63965. if (Time::getCurrentTime() > earliestTimeToDelete
  63966. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  63967. {
  63968. delete this;
  63969. }
  63970. }
  63971. END_JUCE_NAMESPACE
  63972. /*** End of inlined file: juce_SplashScreen.cpp ***/
  63973. /*** Start of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  63974. BEGIN_JUCE_NAMESPACE
  63975. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  63976. const bool hasProgressBar,
  63977. const bool hasCancelButton,
  63978. const int timeOutMsWhenCancelling_,
  63979. const String& cancelButtonText)
  63980. : Thread ("Juce Progress Window"),
  63981. progress (0.0),
  63982. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  63983. {
  63984. alertWindow = LookAndFeel::getDefaultLookAndFeel()
  63985. .createAlertWindow (title, String::empty, cancelButtonText,
  63986. String::empty, String::empty,
  63987. AlertWindow::NoIcon, hasCancelButton ? 1 : 0, 0);
  63988. if (hasProgressBar)
  63989. alertWindow->addProgressBarComponent (progress);
  63990. }
  63991. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  63992. {
  63993. stopThread (timeOutMsWhenCancelling);
  63994. }
  63995. bool ThreadWithProgressWindow::runThread (const int priority)
  63996. {
  63997. startThread (priority);
  63998. startTimer (100);
  63999. {
  64000. const ScopedLock sl (messageLock);
  64001. alertWindow->setMessage (message);
  64002. }
  64003. const bool finishedNaturally = alertWindow->runModalLoop() != 0;
  64004. stopThread (timeOutMsWhenCancelling);
  64005. alertWindow->setVisible (false);
  64006. return finishedNaturally;
  64007. }
  64008. void ThreadWithProgressWindow::setProgress (const double newProgress)
  64009. {
  64010. progress = newProgress;
  64011. }
  64012. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  64013. {
  64014. const ScopedLock sl (messageLock);
  64015. message = newStatusMessage;
  64016. }
  64017. void ThreadWithProgressWindow::timerCallback()
  64018. {
  64019. if (! isThreadRunning())
  64020. {
  64021. // thread has finished normally..
  64022. alertWindow->exitModalState (1);
  64023. alertWindow->setVisible (false);
  64024. }
  64025. else
  64026. {
  64027. const ScopedLock sl (messageLock);
  64028. alertWindow->setMessage (message);
  64029. }
  64030. }
  64031. END_JUCE_NAMESPACE
  64032. /*** End of inlined file: juce_ThreadWithProgressWindow.cpp ***/
  64033. /*** Start of inlined file: juce_TooltipWindow.cpp ***/
  64034. BEGIN_JUCE_NAMESPACE
  64035. TooltipWindow::TooltipWindow (Component* const parentComponent,
  64036. const int millisecondsBeforeTipAppears_)
  64037. : Component ("tooltip"),
  64038. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  64039. mouseClicks (0),
  64040. lastHideTime (0),
  64041. lastComponentUnderMouse (0),
  64042. changedCompsSinceShown (true)
  64043. {
  64044. if (Desktop::getInstance().getMainMouseSource().canHover())
  64045. startTimer (123);
  64046. setAlwaysOnTop (true);
  64047. setOpaque (true);
  64048. if (parentComponent != 0)
  64049. parentComponent->addChildComponent (this);
  64050. }
  64051. TooltipWindow::~TooltipWindow()
  64052. {
  64053. hide();
  64054. }
  64055. void TooltipWindow::setMillisecondsBeforeTipAppears (const int newTimeMs) throw()
  64056. {
  64057. millisecondsBeforeTipAppears = newTimeMs;
  64058. }
  64059. void TooltipWindow::paint (Graphics& g)
  64060. {
  64061. getLookAndFeel().drawTooltip (g, tipShowing, getWidth(), getHeight());
  64062. }
  64063. void TooltipWindow::mouseEnter (const MouseEvent&)
  64064. {
  64065. hide();
  64066. }
  64067. void TooltipWindow::showFor (const String& tip)
  64068. {
  64069. jassert (tip.isNotEmpty());
  64070. if (tipShowing != tip)
  64071. repaint();
  64072. tipShowing = tip;
  64073. Point<int> mousePos (Desktop::getMousePosition());
  64074. if (getParentComponent() != 0)
  64075. mousePos = getParentComponent()->globalPositionToRelative (mousePos);
  64076. int x, y, w, h;
  64077. getLookAndFeel().getTooltipSize (tip, w, h);
  64078. if (mousePos.getX() > getParentWidth() / 2)
  64079. x = mousePos.getX() - (w + 12);
  64080. else
  64081. x = mousePos.getX() + 24;
  64082. if (mousePos.getY() > getParentHeight() / 2)
  64083. y = mousePos.getY() - (h + 6);
  64084. else
  64085. y = mousePos.getY() + 6;
  64086. setBounds (x, y, w, h);
  64087. setVisible (true);
  64088. if (getParentComponent() == 0)
  64089. {
  64090. addToDesktop (ComponentPeer::windowHasDropShadow
  64091. | ComponentPeer::windowIsTemporary
  64092. | ComponentPeer::windowIgnoresKeyPresses);
  64093. }
  64094. toFront (false);
  64095. }
  64096. const String TooltipWindow::getTipFor (Component* const c)
  64097. {
  64098. if (c != 0
  64099. && Process::isForegroundProcess()
  64100. && ! Component::isMouseButtonDownAnywhere())
  64101. {
  64102. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  64103. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  64104. return ttc->getTooltip();
  64105. }
  64106. return String::empty;
  64107. }
  64108. void TooltipWindow::hide()
  64109. {
  64110. tipShowing = String::empty;
  64111. removeFromDesktop();
  64112. setVisible (false);
  64113. }
  64114. void TooltipWindow::timerCallback()
  64115. {
  64116. const unsigned int now = Time::getApproximateMillisecondCounter();
  64117. Component* const newComp = Desktop::getInstance().getMainMouseSource().getComponentUnderMouse();
  64118. const String newTip (getTipFor (newComp));
  64119. const bool tipChanged = (newTip != lastTipUnderMouse || newComp != lastComponentUnderMouse);
  64120. lastComponentUnderMouse = newComp;
  64121. lastTipUnderMouse = newTip;
  64122. const int clickCount = Desktop::getInstance().getMouseButtonClickCounter();
  64123. const bool mouseWasClicked = clickCount > mouseClicks;
  64124. mouseClicks = clickCount;
  64125. const Point<int> mousePos (Desktop::getMousePosition());
  64126. const bool mouseMovedQuickly = mousePos.getDistanceFrom (lastMousePos) > 12;
  64127. lastMousePos = mousePos;
  64128. if (tipChanged || mouseWasClicked || mouseMovedQuickly)
  64129. lastCompChangeTime = now;
  64130. if (isVisible() || now < lastHideTime + 500)
  64131. {
  64132. // if a tip is currently visible (or has just disappeared), update to a new one
  64133. // immediately if needed..
  64134. if (newComp == 0 || mouseWasClicked || newTip.isEmpty())
  64135. {
  64136. if (isVisible())
  64137. {
  64138. lastHideTime = now;
  64139. hide();
  64140. }
  64141. }
  64142. else if (tipChanged)
  64143. {
  64144. showFor (newTip);
  64145. }
  64146. }
  64147. else
  64148. {
  64149. // if there isn't currently a tip, but one is needed, only let it
  64150. // appear after a timeout..
  64151. if (newTip.isNotEmpty()
  64152. && newTip != tipShowing
  64153. && now > lastCompChangeTime + millisecondsBeforeTipAppears)
  64154. {
  64155. showFor (newTip);
  64156. }
  64157. }
  64158. }
  64159. END_JUCE_NAMESPACE
  64160. /*** End of inlined file: juce_TooltipWindow.cpp ***/
  64161. /*** Start of inlined file: juce_TopLevelWindow.cpp ***/
  64162. BEGIN_JUCE_NAMESPACE
  64163. /** Keeps track of the active top level window.
  64164. */
  64165. class TopLevelWindowManager : public Timer,
  64166. public DeletedAtShutdown
  64167. {
  64168. public:
  64169. TopLevelWindowManager()
  64170. : currentActive (0)
  64171. {
  64172. }
  64173. ~TopLevelWindowManager()
  64174. {
  64175. clearSingletonInstance();
  64176. }
  64177. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  64178. void timerCallback()
  64179. {
  64180. startTimer (jmin (1731, getTimerInterval() * 2));
  64181. TopLevelWindow* active = 0;
  64182. if (Process::isForegroundProcess())
  64183. {
  64184. active = currentActive;
  64185. Component* const c = Component::getCurrentlyFocusedComponent();
  64186. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  64187. if (tlw == 0 && c != 0)
  64188. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  64189. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  64190. if (tlw != 0)
  64191. active = tlw;
  64192. }
  64193. if (active != currentActive)
  64194. {
  64195. currentActive = active;
  64196. for (int i = windows.size(); --i >= 0;)
  64197. {
  64198. TopLevelWindow* const tlw = windows.getUnchecked (i);
  64199. tlw->setWindowActive (isWindowActive (tlw));
  64200. i = jmin (i, windows.size() - 1);
  64201. }
  64202. Desktop::getInstance().triggerFocusCallback();
  64203. }
  64204. }
  64205. bool addWindow (TopLevelWindow* const w)
  64206. {
  64207. windows.add (w);
  64208. startTimer (10);
  64209. return isWindowActive (w);
  64210. }
  64211. void removeWindow (TopLevelWindow* const w)
  64212. {
  64213. startTimer (10);
  64214. if (currentActive == w)
  64215. currentActive = 0;
  64216. windows.removeValue (w);
  64217. if (windows.size() == 0)
  64218. deleteInstance();
  64219. }
  64220. Array <TopLevelWindow*> windows;
  64221. private:
  64222. TopLevelWindow* currentActive;
  64223. bool isWindowActive (TopLevelWindow* const tlw) const
  64224. {
  64225. return (tlw == currentActive
  64226. || tlw->isParentOf (currentActive)
  64227. || tlw->hasKeyboardFocus (true))
  64228. && tlw->isShowing();
  64229. }
  64230. TopLevelWindowManager (const TopLevelWindowManager&);
  64231. TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  64232. };
  64233. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  64234. void juce_CheckCurrentlyFocusedTopLevelWindow()
  64235. {
  64236. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  64237. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  64238. }
  64239. TopLevelWindow::TopLevelWindow (const String& name,
  64240. const bool addToDesktop_)
  64241. : Component (name),
  64242. useDropShadow (true),
  64243. useNativeTitleBar (false),
  64244. windowIsActive_ (false)
  64245. {
  64246. setOpaque (true);
  64247. if (addToDesktop_)
  64248. Component::addToDesktop (getDesktopWindowStyleFlags());
  64249. else
  64250. setDropShadowEnabled (true);
  64251. setWantsKeyboardFocus (true);
  64252. setBroughtToFrontOnMouseClick (true);
  64253. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  64254. }
  64255. TopLevelWindow::~TopLevelWindow()
  64256. {
  64257. shadower = 0;
  64258. TopLevelWindowManager::getInstance()->removeWindow (this);
  64259. }
  64260. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  64261. {
  64262. if (hasKeyboardFocus (true))
  64263. TopLevelWindowManager::getInstance()->timerCallback();
  64264. else
  64265. TopLevelWindowManager::getInstance()->startTimer (10);
  64266. }
  64267. void TopLevelWindow::setWindowActive (const bool isNowActive)
  64268. {
  64269. if (windowIsActive_ != isNowActive)
  64270. {
  64271. windowIsActive_ = isNowActive;
  64272. activeWindowStatusChanged();
  64273. }
  64274. }
  64275. void TopLevelWindow::activeWindowStatusChanged()
  64276. {
  64277. }
  64278. void TopLevelWindow::parentHierarchyChanged()
  64279. {
  64280. setDropShadowEnabled (useDropShadow);
  64281. }
  64282. void TopLevelWindow::visibilityChanged()
  64283. {
  64284. if (isShowing())
  64285. toFront (true);
  64286. }
  64287. int TopLevelWindow::getDesktopWindowStyleFlags() const
  64288. {
  64289. int styleFlags = ComponentPeer::windowAppearsOnTaskbar;
  64290. if (useDropShadow)
  64291. styleFlags |= ComponentPeer::windowHasDropShadow;
  64292. if (useNativeTitleBar)
  64293. styleFlags |= ComponentPeer::windowHasTitleBar;
  64294. return styleFlags;
  64295. }
  64296. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  64297. {
  64298. useDropShadow = useShadow;
  64299. if (isOnDesktop())
  64300. {
  64301. shadower = 0;
  64302. Component::addToDesktop (getDesktopWindowStyleFlags());
  64303. }
  64304. else
  64305. {
  64306. if (useShadow && isOpaque())
  64307. {
  64308. if (shadower == 0)
  64309. {
  64310. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  64311. if (shadower != 0)
  64312. shadower->setOwner (this);
  64313. }
  64314. }
  64315. else
  64316. {
  64317. shadower = 0;
  64318. }
  64319. }
  64320. }
  64321. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  64322. {
  64323. if (useNativeTitleBar != useNativeTitleBar_)
  64324. {
  64325. useNativeTitleBar = useNativeTitleBar_;
  64326. recreateDesktopWindow();
  64327. sendLookAndFeelChange();
  64328. }
  64329. }
  64330. void TopLevelWindow::recreateDesktopWindow()
  64331. {
  64332. if (isOnDesktop())
  64333. {
  64334. Component::addToDesktop (getDesktopWindowStyleFlags());
  64335. toFront (true);
  64336. }
  64337. }
  64338. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  64339. {
  64340. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  64341. because this class needs to make sure its layout corresponds with settings like whether
  64342. it's got a native title bar or not.
  64343. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  64344. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  64345. method, then add or remove whatever flags are necessary from this value before returning it.
  64346. */
  64347. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  64348. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  64349. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  64350. if (windowStyleFlags != getDesktopWindowStyleFlags())
  64351. sendLookAndFeelChange();
  64352. }
  64353. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  64354. {
  64355. if (c == 0)
  64356. c = TopLevelWindow::getActiveTopLevelWindow();
  64357. if (c == 0)
  64358. {
  64359. centreWithSize (width, height);
  64360. }
  64361. else
  64362. {
  64363. Point<int> p (c->relativePositionToGlobal (Point<int> ((c->getWidth() - width) / 2,
  64364. (c->getHeight() - height) / 2)));
  64365. Rectangle<int> parentArea (c->getParentMonitorArea());
  64366. if (getParentComponent() != 0)
  64367. {
  64368. p = getParentComponent()->globalPositionToRelative (p);
  64369. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  64370. }
  64371. parentArea.reduce (12, 12);
  64372. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), p.getX()),
  64373. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), p.getY()),
  64374. width, height);
  64375. }
  64376. }
  64377. int TopLevelWindow::getNumTopLevelWindows() throw()
  64378. {
  64379. return TopLevelWindowManager::getInstance()->windows.size();
  64380. }
  64381. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  64382. {
  64383. return static_cast <TopLevelWindow*> (TopLevelWindowManager::getInstance()->windows [index]);
  64384. }
  64385. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  64386. {
  64387. TopLevelWindow* best = 0;
  64388. int bestNumTWLParents = -1;
  64389. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  64390. {
  64391. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  64392. if (tlw->isActiveWindow())
  64393. {
  64394. int numTWLParents = 0;
  64395. const Component* c = tlw->getParentComponent();
  64396. while (c != 0)
  64397. {
  64398. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  64399. ++numTWLParents;
  64400. c = c->getParentComponent();
  64401. }
  64402. if (bestNumTWLParents < numTWLParents)
  64403. {
  64404. best = tlw;
  64405. bestNumTWLParents = numTWLParents;
  64406. }
  64407. }
  64408. }
  64409. return best;
  64410. }
  64411. END_JUCE_NAMESPACE
  64412. /*** End of inlined file: juce_TopLevelWindow.cpp ***/
  64413. /*** Start of inlined file: juce_RelativeCoordinate.cpp ***/
  64414. BEGIN_JUCE_NAMESPACE
  64415. namespace RelativeCoordinateHelpers
  64416. {
  64417. static void skipComma (const juce_wchar* const s, int& i)
  64418. {
  64419. while (CharacterFunctions::isWhitespace (s[i]))
  64420. ++i;
  64421. if (s[i] == ',')
  64422. ++i;
  64423. }
  64424. }
  64425. const String RelativeCoordinate::Strings::parent ("parent");
  64426. const String RelativeCoordinate::Strings::left ("left");
  64427. const String RelativeCoordinate::Strings::right ("right");
  64428. const String RelativeCoordinate::Strings::top ("top");
  64429. const String RelativeCoordinate::Strings::bottom ("bottom");
  64430. const String RelativeCoordinate::Strings::parentLeft ("parent.left");
  64431. const String RelativeCoordinate::Strings::parentTop ("parent.top");
  64432. const String RelativeCoordinate::Strings::parentRight ("parent.right");
  64433. const String RelativeCoordinate::Strings::parentBottom ("parent.bottom");
  64434. RelativeCoordinate::RelativeCoordinate()
  64435. {
  64436. }
  64437. RelativeCoordinate::RelativeCoordinate (const Expression& term_)
  64438. : term (term_)
  64439. {
  64440. }
  64441. RelativeCoordinate::RelativeCoordinate (const RelativeCoordinate& other)
  64442. : term (other.term)
  64443. {
  64444. }
  64445. RelativeCoordinate& RelativeCoordinate::operator= (const RelativeCoordinate& other)
  64446. {
  64447. term = other.term;
  64448. return *this;
  64449. }
  64450. RelativeCoordinate::RelativeCoordinate (const double absoluteDistanceFromOrigin)
  64451. : term (absoluteDistanceFromOrigin)
  64452. {
  64453. }
  64454. RelativeCoordinate::RelativeCoordinate (const String& s)
  64455. {
  64456. try
  64457. {
  64458. term = Expression (s);
  64459. }
  64460. catch (...)
  64461. {}
  64462. }
  64463. RelativeCoordinate::~RelativeCoordinate()
  64464. {
  64465. }
  64466. bool RelativeCoordinate::operator== (const RelativeCoordinate& other) const throw()
  64467. {
  64468. return term.toString() == other.term.toString();
  64469. }
  64470. bool RelativeCoordinate::operator!= (const RelativeCoordinate& other) const throw()
  64471. {
  64472. return ! operator== (other);
  64473. }
  64474. double RelativeCoordinate::resolve (const Expression::EvaluationContext* context) const
  64475. {
  64476. try
  64477. {
  64478. if (context != 0)
  64479. return term.evaluate (*context);
  64480. else
  64481. return term.evaluate();
  64482. }
  64483. catch (...)
  64484. {}
  64485. return 0.0;
  64486. }
  64487. bool RelativeCoordinate::isRecursive (const Expression::EvaluationContext* context) const
  64488. {
  64489. try
  64490. {
  64491. if (context != 0)
  64492. term.evaluate (*context);
  64493. else
  64494. term.evaluate();
  64495. }
  64496. catch (...)
  64497. {
  64498. return true;
  64499. }
  64500. return false;
  64501. }
  64502. void RelativeCoordinate::moveToAbsolute (double newPos, const Expression::EvaluationContext* context)
  64503. {
  64504. try
  64505. {
  64506. if (context != 0)
  64507. {
  64508. term = term.adjustedToGiveNewResult (newPos, *context);
  64509. }
  64510. else
  64511. {
  64512. Expression::EvaluationContext defaultContext;
  64513. term = term.adjustedToGiveNewResult (newPos, defaultContext);
  64514. }
  64515. }
  64516. catch (...)
  64517. {}
  64518. }
  64519. bool RelativeCoordinate::references (const String& coordName, const Expression::EvaluationContext* context) const
  64520. {
  64521. try
  64522. {
  64523. return term.referencesSymbol (coordName, context);
  64524. }
  64525. catch (...)
  64526. {}
  64527. return false;
  64528. }
  64529. bool RelativeCoordinate::isDynamic() const
  64530. {
  64531. return term.usesAnySymbols();
  64532. }
  64533. const String RelativeCoordinate::toString() const
  64534. {
  64535. return term.toString();
  64536. }
  64537. void RelativeCoordinate::renameSymbolIfUsed (const String& oldName, const String& newName)
  64538. {
  64539. jassert (newName.isNotEmpty() && newName.toLowerCase().containsOnly ("abcdefghijklmnopqrstuvwxyz0123456789_"));
  64540. if (term.referencesSymbol (oldName, 0))
  64541. term = term.withRenamedSymbol (oldName, newName);
  64542. }
  64543. RelativePoint::RelativePoint()
  64544. {
  64545. }
  64546. RelativePoint::RelativePoint (const Point<float>& absolutePoint)
  64547. : x (absolutePoint.getX()), y (absolutePoint.getY())
  64548. {
  64549. }
  64550. RelativePoint::RelativePoint (const float x_, const float y_)
  64551. : x (x_), y (y_)
  64552. {
  64553. }
  64554. RelativePoint::RelativePoint (const RelativeCoordinate& x_, const RelativeCoordinate& y_)
  64555. : x (x_), y (y_)
  64556. {
  64557. }
  64558. RelativePoint::RelativePoint (const String& s)
  64559. {
  64560. int i = 0;
  64561. x = RelativeCoordinate (Expression::parse (s, i));
  64562. RelativeCoordinateHelpers::skipComma (s, i);
  64563. y = RelativeCoordinate (Expression::parse (s, i));
  64564. }
  64565. bool RelativePoint::operator== (const RelativePoint& other) const throw()
  64566. {
  64567. return x == other.x && y == other.y;
  64568. }
  64569. bool RelativePoint::operator!= (const RelativePoint& other) const throw()
  64570. {
  64571. return ! operator== (other);
  64572. }
  64573. const Point<float> RelativePoint::resolve (const Expression::EvaluationContext* context) const
  64574. {
  64575. return Point<float> ((float) x.resolve (context),
  64576. (float) y.resolve (context));
  64577. }
  64578. void RelativePoint::moveToAbsolute (const Point<float>& newPos, const Expression::EvaluationContext* context)
  64579. {
  64580. x.moveToAbsolute (newPos.getX(), context);
  64581. y.moveToAbsolute (newPos.getY(), context);
  64582. }
  64583. const String RelativePoint::toString() const
  64584. {
  64585. return x.toString() + ", " + y.toString();
  64586. }
  64587. void RelativePoint::renameSymbolIfUsed (const String& oldName, const String& newName)
  64588. {
  64589. x.renameSymbolIfUsed (oldName, newName);
  64590. y.renameSymbolIfUsed (oldName, newName);
  64591. }
  64592. bool RelativePoint::isDynamic() const
  64593. {
  64594. return x.isDynamic() || y.isDynamic();
  64595. }
  64596. RelativeRectangle::RelativeRectangle()
  64597. {
  64598. }
  64599. RelativeRectangle::RelativeRectangle (const RelativeCoordinate& left_, const RelativeCoordinate& right_,
  64600. const RelativeCoordinate& top_, const RelativeCoordinate& bottom_)
  64601. : left (left_), right (right_), top (top_), bottom (bottom_)
  64602. {
  64603. }
  64604. RelativeRectangle::RelativeRectangle (const Rectangle<float>& rect, const String& componentName)
  64605. : left (rect.getX()),
  64606. right (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::left) + Expression ((double) rect.getWidth())),
  64607. top (rect.getY()),
  64608. bottom (Expression::symbol (componentName + "." + RelativeCoordinate::Strings::top) + Expression ((double) rect.getHeight()))
  64609. {
  64610. }
  64611. RelativeRectangle::RelativeRectangle (const String& s)
  64612. {
  64613. int i = 0;
  64614. left = RelativeCoordinate (Expression::parse (s, i));
  64615. RelativeCoordinateHelpers::skipComma (s, i);
  64616. top = RelativeCoordinate (Expression::parse (s, i));
  64617. RelativeCoordinateHelpers::skipComma (s, i);
  64618. right = RelativeCoordinate (Expression::parse (s, i));
  64619. RelativeCoordinateHelpers::skipComma (s, i);
  64620. bottom = RelativeCoordinate (Expression::parse (s, i));
  64621. }
  64622. bool RelativeRectangle::operator== (const RelativeRectangle& other) const throw()
  64623. {
  64624. return left == other.left && top == other.top && right == other.right && bottom == other.bottom;
  64625. }
  64626. bool RelativeRectangle::operator!= (const RelativeRectangle& other) const throw()
  64627. {
  64628. return ! operator== (other);
  64629. }
  64630. const Rectangle<float> RelativeRectangle::resolve (const Expression::EvaluationContext* context) const
  64631. {
  64632. const double l = left.resolve (context);
  64633. const double r = right.resolve (context);
  64634. const double t = top.resolve (context);
  64635. const double b = bottom.resolve (context);
  64636. return Rectangle<float> ((float) l, (float) t, (float) (r - l), (float) (b - t));
  64637. }
  64638. void RelativeRectangle::moveToAbsolute (const Rectangle<float>& newPos, const Expression::EvaluationContext* context)
  64639. {
  64640. left.moveToAbsolute (newPos.getX(), context);
  64641. right.moveToAbsolute (newPos.getRight(), context);
  64642. top.moveToAbsolute (newPos.getY(), context);
  64643. bottom.moveToAbsolute (newPos.getBottom(), context);
  64644. }
  64645. const String RelativeRectangle::toString() const
  64646. {
  64647. return left.toString() + ", " + top.toString() + ", " + right.toString() + ", " + bottom.toString();
  64648. }
  64649. void RelativeRectangle::renameSymbolIfUsed (const String& oldName, const String& newName)
  64650. {
  64651. left.renameSymbolIfUsed (oldName, newName);
  64652. right.renameSymbolIfUsed (oldName, newName);
  64653. top.renameSymbolIfUsed (oldName, newName);
  64654. bottom.renameSymbolIfUsed (oldName, newName);
  64655. }
  64656. RelativePointPath::RelativePointPath()
  64657. : usesNonZeroWinding (true),
  64658. containsDynamicPoints (false)
  64659. {
  64660. }
  64661. RelativePointPath::RelativePointPath (const RelativePointPath& other)
  64662. : usesNonZeroWinding (true),
  64663. containsDynamicPoints (false)
  64664. {
  64665. ValueTree state (DrawablePath::valueTreeType);
  64666. other.writeTo (state, 0);
  64667. parse (state);
  64668. }
  64669. RelativePointPath::RelativePointPath (const ValueTree& drawable)
  64670. : usesNonZeroWinding (true),
  64671. containsDynamicPoints (false)
  64672. {
  64673. parse (drawable);
  64674. }
  64675. RelativePointPath::RelativePointPath (const Path& path)
  64676. {
  64677. usesNonZeroWinding = path.isUsingNonZeroWinding();
  64678. Path::Iterator i (path);
  64679. while (i.next())
  64680. {
  64681. switch (i.elementType)
  64682. {
  64683. case Path::Iterator::startNewSubPath: elements.add (new StartSubPath (RelativePoint (i.x1, i.y1))); break;
  64684. case Path::Iterator::lineTo: elements.add (new LineTo (RelativePoint (i.x1, i.y1))); break;
  64685. case Path::Iterator::quadraticTo: elements.add (new QuadraticTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2))); break;
  64686. case Path::Iterator::cubicTo: elements.add (new CubicTo (RelativePoint (i.x1, i.y1), RelativePoint (i.x2, i.y2), RelativePoint (i.x3, i.y3))); break;
  64687. case Path::Iterator::closePath: elements.add (new CloseSubPath()); break;
  64688. default: jassertfalse; break;
  64689. }
  64690. }
  64691. }
  64692. void RelativePointPath::writeTo (ValueTree state, UndoManager* undoManager) const
  64693. {
  64694. DrawablePath::ValueTreeWrapper wrapper (state);
  64695. wrapper.setUsesNonZeroWinding (usesNonZeroWinding, undoManager);
  64696. ValueTree pathTree (wrapper.getPathState());
  64697. pathTree.removeAllChildren (undoManager);
  64698. for (int i = 0; i < elements.size(); ++i)
  64699. pathTree.addChild (elements.getUnchecked(i)->createTree(), -1, undoManager);
  64700. }
  64701. void RelativePointPath::parse (const ValueTree& state)
  64702. {
  64703. DrawablePath::ValueTreeWrapper wrapper (state);
  64704. usesNonZeroWinding = wrapper.usesNonZeroWinding();
  64705. RelativePoint points[3];
  64706. const ValueTree pathTree (wrapper.getPathState());
  64707. const int num = pathTree.getNumChildren();
  64708. for (int i = 0; i < num; ++i)
  64709. {
  64710. const DrawablePath::ValueTreeWrapper::Element e (pathTree.getChild(i));
  64711. const int numCps = e.getNumControlPoints();
  64712. for (int j = 0; j < numCps; ++j)
  64713. {
  64714. points[j] = e.getControlPoint (j);
  64715. containsDynamicPoints = containsDynamicPoints || points[j].isDynamic();
  64716. }
  64717. const Identifier type (e.getType());
  64718. if (type == DrawablePath::ValueTreeWrapper::Element::startSubPathElement)
  64719. elements.add (new StartSubPath (points[0]));
  64720. else if (type == DrawablePath::ValueTreeWrapper::Element::closeSubPathElement)
  64721. elements.add (new CloseSubPath());
  64722. else if (type == DrawablePath::ValueTreeWrapper::Element::lineToElement)
  64723. elements.add (new LineTo (points[0]));
  64724. else if (type == DrawablePath::ValueTreeWrapper::Element::quadraticToElement)
  64725. elements.add (new QuadraticTo (points[0], points[1]));
  64726. else if (type == DrawablePath::ValueTreeWrapper::Element::cubicToElement)
  64727. elements.add (new CubicTo (points[0], points[1], points[2]));
  64728. else
  64729. jassertfalse;
  64730. }
  64731. }
  64732. RelativePointPath::~RelativePointPath()
  64733. {
  64734. }
  64735. void RelativePointPath::swapWith (RelativePointPath& other) throw()
  64736. {
  64737. elements.swapWithArray (other.elements);
  64738. swapVariables (usesNonZeroWinding, other.usesNonZeroWinding);
  64739. }
  64740. void RelativePointPath::createPath (Path& path, Expression::EvaluationContext* coordFinder)
  64741. {
  64742. for (int i = 0; i < elements.size(); ++i)
  64743. elements.getUnchecked(i)->addToPath (path, coordFinder);
  64744. }
  64745. bool RelativePointPath::containsAnyDynamicPoints() const
  64746. {
  64747. return containsDynamicPoints;
  64748. }
  64749. RelativePointPath::ElementBase::ElementBase (const ElementType type_) : type (type_)
  64750. {
  64751. }
  64752. RelativePointPath::StartSubPath::StartSubPath (const RelativePoint& pos)
  64753. : ElementBase (startSubPathElement), startPos (pos)
  64754. {
  64755. }
  64756. const ValueTree RelativePointPath::StartSubPath::createTree() const
  64757. {
  64758. ValueTree v (DrawablePath::ValueTreeWrapper::Element::startSubPathElement);
  64759. v.setProperty (DrawablePath::ValueTreeWrapper::point1, startPos.toString(), 0);
  64760. return v;
  64761. }
  64762. void RelativePointPath::StartSubPath::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64763. {
  64764. path.startNewSubPath (startPos.resolve (coordFinder));
  64765. }
  64766. RelativePoint* RelativePointPath::StartSubPath::getControlPoints (int& numPoints)
  64767. {
  64768. numPoints = 1;
  64769. return &startPos;
  64770. }
  64771. RelativePointPath::CloseSubPath::CloseSubPath()
  64772. : ElementBase (closeSubPathElement)
  64773. {
  64774. }
  64775. const ValueTree RelativePointPath::CloseSubPath::createTree() const
  64776. {
  64777. return ValueTree (DrawablePath::ValueTreeWrapper::Element::closeSubPathElement);
  64778. }
  64779. void RelativePointPath::CloseSubPath::addToPath (Path& path, Expression::EvaluationContext*) const
  64780. {
  64781. path.closeSubPath();
  64782. }
  64783. RelativePoint* RelativePointPath::CloseSubPath::getControlPoints (int& numPoints)
  64784. {
  64785. numPoints = 0;
  64786. return 0;
  64787. }
  64788. RelativePointPath::LineTo::LineTo (const RelativePoint& endPoint_)
  64789. : ElementBase (lineToElement), endPoint (endPoint_)
  64790. {
  64791. }
  64792. const ValueTree RelativePointPath::LineTo::createTree() const
  64793. {
  64794. ValueTree v (DrawablePath::ValueTreeWrapper::Element::lineToElement);
  64795. v.setProperty (DrawablePath::ValueTreeWrapper::point1, endPoint.toString(), 0);
  64796. return v;
  64797. }
  64798. void RelativePointPath::LineTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64799. {
  64800. path.lineTo (endPoint.resolve (coordFinder));
  64801. }
  64802. RelativePoint* RelativePointPath::LineTo::getControlPoints (int& numPoints)
  64803. {
  64804. numPoints = 1;
  64805. return &endPoint;
  64806. }
  64807. RelativePointPath::QuadraticTo::QuadraticTo (const RelativePoint& controlPoint, const RelativePoint& endPoint)
  64808. : ElementBase (quadraticToElement)
  64809. {
  64810. controlPoints[0] = controlPoint;
  64811. controlPoints[1] = endPoint;
  64812. }
  64813. const ValueTree RelativePointPath::QuadraticTo::createTree() const
  64814. {
  64815. ValueTree v (DrawablePath::ValueTreeWrapper::Element::quadraticToElement);
  64816. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64817. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64818. return v;
  64819. }
  64820. void RelativePointPath::QuadraticTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64821. {
  64822. path.quadraticTo (controlPoints[0].resolve (coordFinder),
  64823. controlPoints[1].resolve (coordFinder));
  64824. }
  64825. RelativePoint* RelativePointPath::QuadraticTo::getControlPoints (int& numPoints)
  64826. {
  64827. numPoints = 2;
  64828. return controlPoints;
  64829. }
  64830. RelativePointPath::CubicTo::CubicTo (const RelativePoint& controlPoint1, const RelativePoint& controlPoint2, const RelativePoint& endPoint)
  64831. : ElementBase (cubicToElement)
  64832. {
  64833. controlPoints[0] = controlPoint1;
  64834. controlPoints[1] = controlPoint2;
  64835. controlPoints[2] = endPoint;
  64836. }
  64837. const ValueTree RelativePointPath::CubicTo::createTree() const
  64838. {
  64839. ValueTree v (DrawablePath::ValueTreeWrapper::Element::cubicToElement);
  64840. v.setProperty (DrawablePath::ValueTreeWrapper::point1, controlPoints[0].toString(), 0);
  64841. v.setProperty (DrawablePath::ValueTreeWrapper::point2, controlPoints[1].toString(), 0);
  64842. v.setProperty (DrawablePath::ValueTreeWrapper::point3, controlPoints[2].toString(), 0);
  64843. return v;
  64844. }
  64845. void RelativePointPath::CubicTo::addToPath (Path& path, Expression::EvaluationContext* coordFinder) const
  64846. {
  64847. path.cubicTo (controlPoints[0].resolve (coordFinder),
  64848. controlPoints[1].resolve (coordFinder),
  64849. controlPoints[2].resolve (coordFinder));
  64850. }
  64851. RelativePoint* RelativePointPath::CubicTo::getControlPoints (int& numPoints)
  64852. {
  64853. numPoints = 3;
  64854. return controlPoints;
  64855. }
  64856. RelativeParallelogram::RelativeParallelogram()
  64857. {
  64858. }
  64859. RelativeParallelogram::RelativeParallelogram (const Rectangle<float>& r)
  64860. : topLeft (r.getTopLeft()), topRight (r.getTopRight()), bottomLeft (r.getBottomLeft())
  64861. {
  64862. }
  64863. RelativeParallelogram::RelativeParallelogram (const RelativePoint& topLeft_, const RelativePoint& topRight_, const RelativePoint& bottomLeft_)
  64864. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64865. {
  64866. }
  64867. RelativeParallelogram::RelativeParallelogram (const String& topLeft_, const String& topRight_, const String& bottomLeft_)
  64868. : topLeft (topLeft_), topRight (topRight_), bottomLeft (bottomLeft_)
  64869. {
  64870. }
  64871. RelativeParallelogram::~RelativeParallelogram()
  64872. {
  64873. }
  64874. void RelativeParallelogram::resolveThreePoints (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64875. {
  64876. points[0] = topLeft.resolve (coordFinder);
  64877. points[1] = topRight.resolve (coordFinder);
  64878. points[2] = bottomLeft.resolve (coordFinder);
  64879. }
  64880. void RelativeParallelogram::resolveFourCorners (Point<float>* points, Expression::EvaluationContext* const coordFinder) const
  64881. {
  64882. resolveThreePoints (points, coordFinder);
  64883. points[3] = points[1] + (points[2] - points[0]);
  64884. }
  64885. const Rectangle<float> RelativeParallelogram::getBounds (Expression::EvaluationContext* const coordFinder) const
  64886. {
  64887. Point<float> points[4];
  64888. resolveFourCorners (points, coordFinder);
  64889. return Rectangle<float>::findAreaContainingPoints (points, 4);
  64890. }
  64891. void RelativeParallelogram::getPath (Path& path, Expression::EvaluationContext* const coordFinder) const
  64892. {
  64893. Point<float> points[4];
  64894. resolveFourCorners (points, coordFinder);
  64895. path.startNewSubPath (points[0]);
  64896. path.lineTo (points[1]);
  64897. path.lineTo (points[3]);
  64898. path.lineTo (points[2]);
  64899. path.closeSubPath();
  64900. }
  64901. const AffineTransform RelativeParallelogram::resetToPerpendicular (Expression::EvaluationContext* const coordFinder)
  64902. {
  64903. Point<float> corners[3];
  64904. resolveThreePoints (corners, coordFinder);
  64905. const Line<float> top (corners[0], corners[1]);
  64906. const Line<float> left (corners[0], corners[2]);
  64907. const Point<float> newTopRight (corners[0] + Point<float> (top.getLength(), 0.0f));
  64908. const Point<float> newBottomLeft (corners[0] + Point<float> (0.0f, left.getLength()));
  64909. topRight.moveToAbsolute (newTopRight, coordFinder);
  64910. bottomLeft.moveToAbsolute (newBottomLeft, coordFinder);
  64911. return AffineTransform::fromTargetPoints (corners[0].getX(), corners[0].getY(), corners[0].getX(), corners[0].getY(),
  64912. corners[1].getX(), corners[1].getY(), newTopRight.getX(), newTopRight.getY(),
  64913. corners[2].getX(), corners[2].getY(), newBottomLeft.getX(), newBottomLeft.getY());
  64914. }
  64915. bool RelativeParallelogram::operator== (const RelativeParallelogram& other) const throw()
  64916. {
  64917. return topLeft == other.topLeft && topRight == other.topRight && bottomLeft == other.bottomLeft;
  64918. }
  64919. bool RelativeParallelogram::operator!= (const RelativeParallelogram& other) const throw()
  64920. {
  64921. return ! operator== (other);
  64922. }
  64923. const Point<float> RelativeParallelogram::getInternalCoordForPoint (const Point<float>* const corners, Point<float> target) throw()
  64924. {
  64925. const Point<float> tr (corners[1] - corners[0]);
  64926. const Point<float> bl (corners[2] - corners[0]);
  64927. target -= corners[0];
  64928. return Point<float> (Line<float> (Point<float>(), tr).getIntersection (Line<float> (target, target - bl)).getDistanceFromOrigin(),
  64929. Line<float> (Point<float>(), bl).getIntersection (Line<float> (target, target - tr)).getDistanceFromOrigin());
  64930. }
  64931. const Point<float> RelativeParallelogram::getPointForInternalCoord (const Point<float>* const corners, const Point<float>& point) throw()
  64932. {
  64933. return corners[0]
  64934. + Line<float> (Point<float>(), corners[1] - corners[0]).getPointAlongLine (point.getX())
  64935. + Line<float> (Point<float>(), corners[2] - corners[0]).getPointAlongLine (point.getY());
  64936. }
  64937. END_JUCE_NAMESPACE
  64938. /*** End of inlined file: juce_RelativeCoordinate.cpp ***/
  64939. #endif
  64940. #if JUCE_BUILD_MISC // (put these in misc to balance the file sizes and avoid problems in iphone build)
  64941. /*** Start of inlined file: juce_Colour.cpp ***/
  64942. BEGIN_JUCE_NAMESPACE
  64943. namespace ColourHelpers
  64944. {
  64945. static uint8 floatAlphaToInt (const float alpha) throw()
  64946. {
  64947. return (uint8) jlimit (0, 0xff, roundToInt (alpha * 255.0f));
  64948. }
  64949. static void convertHSBtoRGB (float h, float s, float v,
  64950. uint8& r, uint8& g, uint8& b) throw()
  64951. {
  64952. v = jlimit (0.0f, 1.0f, v);
  64953. v *= 255.0f;
  64954. const uint8 intV = (uint8) roundToInt (v);
  64955. if (s <= 0)
  64956. {
  64957. r = intV;
  64958. g = intV;
  64959. b = intV;
  64960. }
  64961. else
  64962. {
  64963. s = jmin (1.0f, s);
  64964. h = jlimit (0.0f, 1.0f, h);
  64965. h = (h - std::floor (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  64966. const float f = h - std::floor (h);
  64967. const uint8 x = (uint8) roundToInt (v * (1.0f - s));
  64968. const float y = v * (1.0f - s * f);
  64969. const float z = v * (1.0f - (s * (1.0f - f)));
  64970. if (h < 1.0f)
  64971. {
  64972. r = intV;
  64973. g = (uint8) roundToInt (z);
  64974. b = x;
  64975. }
  64976. else if (h < 2.0f)
  64977. {
  64978. r = (uint8) roundToInt (y);
  64979. g = intV;
  64980. b = x;
  64981. }
  64982. else if (h < 3.0f)
  64983. {
  64984. r = x;
  64985. g = intV;
  64986. b = (uint8) roundToInt (z);
  64987. }
  64988. else if (h < 4.0f)
  64989. {
  64990. r = x;
  64991. g = (uint8) roundToInt (y);
  64992. b = intV;
  64993. }
  64994. else if (h < 5.0f)
  64995. {
  64996. r = (uint8) roundToInt (z);
  64997. g = x;
  64998. b = intV;
  64999. }
  65000. else if (h < 6.0f)
  65001. {
  65002. r = intV;
  65003. g = x;
  65004. b = (uint8) roundToInt (y);
  65005. }
  65006. else
  65007. {
  65008. r = 0;
  65009. g = 0;
  65010. b = 0;
  65011. }
  65012. }
  65013. }
  65014. }
  65015. Colour::Colour() throw()
  65016. : argb (0)
  65017. {
  65018. }
  65019. Colour::Colour (const Colour& other) throw()
  65020. : argb (other.argb)
  65021. {
  65022. }
  65023. Colour& Colour::operator= (const Colour& other) throw()
  65024. {
  65025. argb = other.argb;
  65026. return *this;
  65027. }
  65028. bool Colour::operator== (const Colour& other) const throw()
  65029. {
  65030. return argb.getARGB() == other.argb.getARGB();
  65031. }
  65032. bool Colour::operator!= (const Colour& other) const throw()
  65033. {
  65034. return argb.getARGB() != other.argb.getARGB();
  65035. }
  65036. Colour::Colour (const uint32 argb_) throw()
  65037. : argb (argb_)
  65038. {
  65039. }
  65040. Colour::Colour (const uint8 red,
  65041. const uint8 green,
  65042. const uint8 blue) throw()
  65043. {
  65044. argb.setARGB (0xff, red, green, blue);
  65045. }
  65046. const Colour Colour::fromRGB (const uint8 red,
  65047. const uint8 green,
  65048. const uint8 blue) throw()
  65049. {
  65050. return Colour (red, green, blue);
  65051. }
  65052. Colour::Colour (const uint8 red,
  65053. const uint8 green,
  65054. const uint8 blue,
  65055. const uint8 alpha) throw()
  65056. {
  65057. argb.setARGB (alpha, red, green, blue);
  65058. }
  65059. const Colour Colour::fromRGBA (const uint8 red,
  65060. const uint8 green,
  65061. const uint8 blue,
  65062. const uint8 alpha) throw()
  65063. {
  65064. return Colour (red, green, blue, alpha);
  65065. }
  65066. Colour::Colour (const uint8 red,
  65067. const uint8 green,
  65068. const uint8 blue,
  65069. const float alpha) throw()
  65070. {
  65071. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), red, green, blue);
  65072. }
  65073. const Colour Colour::fromRGBAFloat (const uint8 red,
  65074. const uint8 green,
  65075. const uint8 blue,
  65076. const float alpha) throw()
  65077. {
  65078. return Colour (red, green, blue, alpha);
  65079. }
  65080. Colour::Colour (const float hue,
  65081. const float saturation,
  65082. const float brightness,
  65083. const float alpha) throw()
  65084. {
  65085. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65086. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65087. argb.setARGB (ColourHelpers::floatAlphaToInt (alpha), r, g, b);
  65088. }
  65089. const Colour Colour::fromHSV (const float hue,
  65090. const float saturation,
  65091. const float brightness,
  65092. const float alpha) throw()
  65093. {
  65094. return Colour (hue, saturation, brightness, alpha);
  65095. }
  65096. Colour::Colour (const float hue,
  65097. const float saturation,
  65098. const float brightness,
  65099. const uint8 alpha) throw()
  65100. {
  65101. uint8 r = getRed(), g = getGreen(), b = getBlue();
  65102. ColourHelpers::convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  65103. argb.setARGB (alpha, r, g, b);
  65104. }
  65105. Colour::~Colour() throw()
  65106. {
  65107. }
  65108. const PixelARGB Colour::getPixelARGB() const throw()
  65109. {
  65110. PixelARGB p (argb);
  65111. p.premultiply();
  65112. return p;
  65113. }
  65114. uint32 Colour::getARGB() const throw()
  65115. {
  65116. return argb.getARGB();
  65117. }
  65118. bool Colour::isTransparent() const throw()
  65119. {
  65120. return getAlpha() == 0;
  65121. }
  65122. bool Colour::isOpaque() const throw()
  65123. {
  65124. return getAlpha() == 0xff;
  65125. }
  65126. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  65127. {
  65128. PixelARGB newCol (argb);
  65129. newCol.setAlpha (newAlpha);
  65130. return Colour (newCol.getARGB());
  65131. }
  65132. const Colour Colour::withAlpha (const float newAlpha) const throw()
  65133. {
  65134. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  65135. PixelARGB newCol (argb);
  65136. newCol.setAlpha (ColourHelpers::floatAlphaToInt (newAlpha));
  65137. return Colour (newCol.getARGB());
  65138. }
  65139. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  65140. {
  65141. jassert (alphaMultiplier >= 0);
  65142. PixelARGB newCol (argb);
  65143. newCol.setAlpha ((uint8) jmin (0xff, roundToInt (alphaMultiplier * newCol.getAlpha())));
  65144. return Colour (newCol.getARGB());
  65145. }
  65146. const Colour Colour::overlaidWith (const Colour& src) const throw()
  65147. {
  65148. const int destAlpha = getAlpha();
  65149. if (destAlpha > 0)
  65150. {
  65151. const int invA = 0xff - (int) src.getAlpha();
  65152. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  65153. if (resA > 0)
  65154. {
  65155. const int da = (invA * destAlpha) / resA;
  65156. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  65157. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  65158. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  65159. (uint8) resA);
  65160. }
  65161. return *this;
  65162. }
  65163. else
  65164. {
  65165. return src;
  65166. }
  65167. }
  65168. const Colour Colour::interpolatedWith (const Colour& other, float proportionOfOther) const throw()
  65169. {
  65170. if (proportionOfOther <= 0)
  65171. return *this;
  65172. if (proportionOfOther >= 1.0f)
  65173. return other;
  65174. PixelARGB c1 (getPixelARGB());
  65175. const PixelARGB c2 (other.getPixelARGB());
  65176. c1.tween (c2, roundToInt (proportionOfOther * 255.0f));
  65177. c1.unpremultiply();
  65178. return Colour (c1.getARGB());
  65179. }
  65180. float Colour::getFloatRed() const throw()
  65181. {
  65182. return getRed() / 255.0f;
  65183. }
  65184. float Colour::getFloatGreen() const throw()
  65185. {
  65186. return getGreen() / 255.0f;
  65187. }
  65188. float Colour::getFloatBlue() const throw()
  65189. {
  65190. return getBlue() / 255.0f;
  65191. }
  65192. float Colour::getFloatAlpha() const throw()
  65193. {
  65194. return getAlpha() / 255.0f;
  65195. }
  65196. void Colour::getHSB (float& h, float& s, float& v) const throw()
  65197. {
  65198. const int r = getRed();
  65199. const int g = getGreen();
  65200. const int b = getBlue();
  65201. const int hi = jmax (r, g, b);
  65202. const int lo = jmin (r, g, b);
  65203. if (hi != 0)
  65204. {
  65205. s = (hi - lo) / (float) hi;
  65206. if (s != 0)
  65207. {
  65208. const float invDiff = 1.0f / (hi - lo);
  65209. const float red = (hi - r) * invDiff;
  65210. const float green = (hi - g) * invDiff;
  65211. const float blue = (hi - b) * invDiff;
  65212. if (r == hi)
  65213. h = blue - green;
  65214. else if (g == hi)
  65215. h = 2.0f + red - blue;
  65216. else
  65217. h = 4.0f + green - red;
  65218. h *= 1.0f / 6.0f;
  65219. if (h < 0)
  65220. ++h;
  65221. }
  65222. else
  65223. {
  65224. h = 0;
  65225. }
  65226. }
  65227. else
  65228. {
  65229. s = 0;
  65230. h = 0;
  65231. }
  65232. v = hi / 255.0f;
  65233. }
  65234. float Colour::getHue() const throw()
  65235. {
  65236. float h, s, b;
  65237. getHSB (h, s, b);
  65238. return h;
  65239. }
  65240. const Colour Colour::withHue (const float hue) const throw()
  65241. {
  65242. float h, s, b;
  65243. getHSB (h, s, b);
  65244. return Colour (hue, s, b, getAlpha());
  65245. }
  65246. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  65247. {
  65248. float h, s, b;
  65249. getHSB (h, s, b);
  65250. h += amountToRotate;
  65251. h -= std::floor (h);
  65252. return Colour (h, s, b, getAlpha());
  65253. }
  65254. float Colour::getSaturation() const throw()
  65255. {
  65256. float h, s, b;
  65257. getHSB (h, s, b);
  65258. return s;
  65259. }
  65260. const Colour Colour::withSaturation (const float saturation) const throw()
  65261. {
  65262. float h, s, b;
  65263. getHSB (h, s, b);
  65264. return Colour (h, saturation, b, getAlpha());
  65265. }
  65266. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  65267. {
  65268. float h, s, b;
  65269. getHSB (h, s, b);
  65270. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  65271. }
  65272. float Colour::getBrightness() const throw()
  65273. {
  65274. float h, s, b;
  65275. getHSB (h, s, b);
  65276. return b;
  65277. }
  65278. const Colour Colour::withBrightness (const float brightness) const throw()
  65279. {
  65280. float h, s, b;
  65281. getHSB (h, s, b);
  65282. return Colour (h, s, brightness, getAlpha());
  65283. }
  65284. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  65285. {
  65286. float h, s, b;
  65287. getHSB (h, s, b);
  65288. b *= amount;
  65289. if (b > 1.0f)
  65290. b = 1.0f;
  65291. return Colour (h, s, b, getAlpha());
  65292. }
  65293. const Colour Colour::brighter (float amount) const throw()
  65294. {
  65295. amount = 1.0f / (1.0f + amount);
  65296. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  65297. (uint8) (255 - (amount * (255 - getGreen()))),
  65298. (uint8) (255 - (amount * (255 - getBlue()))),
  65299. getAlpha());
  65300. }
  65301. const Colour Colour::darker (float amount) const throw()
  65302. {
  65303. amount = 1.0f / (1.0f + amount);
  65304. return Colour ((uint8) (amount * getRed()),
  65305. (uint8) (amount * getGreen()),
  65306. (uint8) (amount * getBlue()),
  65307. getAlpha());
  65308. }
  65309. const Colour Colour::greyLevel (const float brightness) throw()
  65310. {
  65311. const uint8 level
  65312. = (uint8) jlimit (0x00, 0xff, roundToInt (brightness * 255.0f));
  65313. return Colour (level, level, level);
  65314. }
  65315. const Colour Colour::contrasting (const float amount) const throw()
  65316. {
  65317. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  65318. ? Colours::black
  65319. : Colours::white).withAlpha (amount));
  65320. }
  65321. const Colour Colour::contrasting (const Colour& colour1,
  65322. const Colour& colour2) throw()
  65323. {
  65324. const float b1 = colour1.getBrightness();
  65325. const float b2 = colour2.getBrightness();
  65326. float best = 0.0f;
  65327. float bestDist = 0.0f;
  65328. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  65329. {
  65330. const float d1 = std::abs (i - b1);
  65331. const float d2 = std::abs (i - b2);
  65332. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  65333. if (dist > bestDist)
  65334. {
  65335. best = i;
  65336. bestDist = dist;
  65337. }
  65338. }
  65339. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  65340. .withBrightness (best);
  65341. }
  65342. const String Colour::toString() const
  65343. {
  65344. return String::toHexString ((int) argb.getARGB());
  65345. }
  65346. const Colour Colour::fromString (const String& encodedColourString)
  65347. {
  65348. return Colour ((uint32) encodedColourString.getHexValue32());
  65349. }
  65350. const String Colour::toDisplayString (const bool includeAlphaValue) const
  65351. {
  65352. return String::toHexString ((int) (argb.getARGB() & (includeAlphaValue ? 0xffffffff : 0xffffff)))
  65353. .paddedLeft ('0', includeAlphaValue ? 8 : 6)
  65354. .toUpperCase();
  65355. }
  65356. END_JUCE_NAMESPACE
  65357. /*** End of inlined file: juce_Colour.cpp ***/
  65358. /*** Start of inlined file: juce_ColourGradient.cpp ***/
  65359. BEGIN_JUCE_NAMESPACE
  65360. ColourGradient::ColourGradient() throw()
  65361. {
  65362. #if JUCE_DEBUG
  65363. point1.setX (987654.0f);
  65364. #endif
  65365. }
  65366. ColourGradient::ColourGradient (const Colour& colour1, const float x1_, const float y1_,
  65367. const Colour& colour2, const float x2_, const float y2_,
  65368. const bool isRadial_)
  65369. : point1 (x1_, y1_),
  65370. point2 (x2_, y2_),
  65371. isRadial (isRadial_)
  65372. {
  65373. colours.add (ColourPoint (0.0, colour1));
  65374. colours.add (ColourPoint (1.0, colour2));
  65375. }
  65376. ColourGradient::~ColourGradient()
  65377. {
  65378. }
  65379. bool ColourGradient::operator== (const ColourGradient& other) const throw()
  65380. {
  65381. return point1 == other.point1 && point2 == other.point2
  65382. && isRadial == other.isRadial
  65383. && colours == other.colours;
  65384. }
  65385. bool ColourGradient::operator!= (const ColourGradient& other) const throw()
  65386. {
  65387. return ! operator== (other);
  65388. }
  65389. void ColourGradient::clearColours()
  65390. {
  65391. colours.clear();
  65392. }
  65393. int ColourGradient::addColour (const double proportionAlongGradient, const Colour& colour)
  65394. {
  65395. // must be within the two end-points
  65396. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  65397. const double pos = jlimit (0.0, 1.0, proportionAlongGradient);
  65398. int i;
  65399. for (i = 0; i < colours.size(); ++i)
  65400. if (colours.getReference(i).position > pos)
  65401. break;
  65402. colours.insert (i, ColourPoint (pos, colour));
  65403. return i;
  65404. }
  65405. void ColourGradient::removeColour (int index)
  65406. {
  65407. jassert (index > 0 && index < colours.size() - 1);
  65408. colours.remove (index);
  65409. }
  65410. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  65411. {
  65412. for (int i = 0; i < colours.size(); ++i)
  65413. {
  65414. Colour& c = colours.getReference(i).colour;
  65415. c = c.withMultipliedAlpha (multiplier);
  65416. }
  65417. }
  65418. int ColourGradient::getNumColours() const throw()
  65419. {
  65420. return colours.size();
  65421. }
  65422. double ColourGradient::getColourPosition (const int index) const throw()
  65423. {
  65424. if (((unsigned int) index) < (unsigned int) colours.size())
  65425. return colours.getReference (index).position;
  65426. return 0;
  65427. }
  65428. const Colour ColourGradient::getColour (const int index) const throw()
  65429. {
  65430. if (((unsigned int) index) < (unsigned int) colours.size())
  65431. return colours.getReference (index).colour;
  65432. return Colour();
  65433. }
  65434. void ColourGradient::setColour (int index, const Colour& newColour) throw()
  65435. {
  65436. if (((unsigned int) index) < (unsigned int) colours.size())
  65437. colours.getReference (index).colour = newColour;
  65438. }
  65439. const Colour ColourGradient::getColourAtPosition (const double position) const throw()
  65440. {
  65441. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65442. if (position <= 0 || colours.size() <= 1)
  65443. return colours.getReference(0).colour;
  65444. int i = colours.size() - 1;
  65445. while (position < colours.getReference(i).position)
  65446. --i;
  65447. const ColourPoint& p1 = colours.getReference (i);
  65448. if (i >= colours.size() - 1)
  65449. return p1.colour;
  65450. const ColourPoint& p2 = colours.getReference (i + 1);
  65451. return p1.colour.interpolatedWith (p2.colour, (float) ((position - p1.position) / (p2.position - p1.position)));
  65452. }
  65453. int ColourGradient::createLookupTable (const AffineTransform& transform, HeapBlock <PixelARGB>& lookupTable) const
  65454. {
  65455. #if JUCE_DEBUG
  65456. // trying to use the object without setting its co-ordinates? Have a careful read of
  65457. // the comments for the constructors.
  65458. jassert (point1.getX() != 987654.0f);
  65459. #endif
  65460. const int numEntries = jlimit (1, jmax (1, (colours.size() - 1) << 8),
  65461. 3 * (int) point1.transformedBy (transform)
  65462. .getDistanceFrom (point2.transformedBy (transform)));
  65463. lookupTable.malloc (numEntries);
  65464. if (colours.size() >= 2)
  65465. {
  65466. jassert (colours.getReference(0).position == 0); // the first colour specified has to go at position 0
  65467. PixelARGB pix1 (colours.getReference (0).colour.getPixelARGB());
  65468. int index = 0;
  65469. for (int j = 1; j < colours.size(); ++j)
  65470. {
  65471. const ColourPoint& p = colours.getReference (j);
  65472. const int numToDo = roundToInt (p.position * (numEntries - 1)) - index;
  65473. const PixelARGB pix2 (p.colour.getPixelARGB());
  65474. for (int i = 0; i < numToDo; ++i)
  65475. {
  65476. jassert (index >= 0 && index < numEntries);
  65477. lookupTable[index] = pix1;
  65478. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  65479. ++index;
  65480. }
  65481. pix1 = pix2;
  65482. }
  65483. while (index < numEntries)
  65484. lookupTable [index++] = pix1;
  65485. }
  65486. else
  65487. {
  65488. jassertfalse; // no colours specified!
  65489. }
  65490. return numEntries;
  65491. }
  65492. bool ColourGradient::isOpaque() const throw()
  65493. {
  65494. for (int i = 0; i < colours.size(); ++i)
  65495. if (! colours.getReference(i).colour.isOpaque())
  65496. return false;
  65497. return true;
  65498. }
  65499. bool ColourGradient::isInvisible() const throw()
  65500. {
  65501. for (int i = 0; i < colours.size(); ++i)
  65502. if (! colours.getReference(i).colour.isTransparent())
  65503. return false;
  65504. return true;
  65505. }
  65506. END_JUCE_NAMESPACE
  65507. /*** End of inlined file: juce_ColourGradient.cpp ***/
  65508. /*** Start of inlined file: juce_Colours.cpp ***/
  65509. BEGIN_JUCE_NAMESPACE
  65510. const Colour Colours::transparentBlack (0);
  65511. const Colour Colours::transparentWhite (0x00ffffff);
  65512. const Colour Colours::aliceblue (0xfff0f8ff);
  65513. const Colour Colours::antiquewhite (0xfffaebd7);
  65514. const Colour Colours::aqua (0xff00ffff);
  65515. const Colour Colours::aquamarine (0xff7fffd4);
  65516. const Colour Colours::azure (0xfff0ffff);
  65517. const Colour Colours::beige (0xfff5f5dc);
  65518. const Colour Colours::bisque (0xffffe4c4);
  65519. const Colour Colours::black (0xff000000);
  65520. const Colour Colours::blanchedalmond (0xffffebcd);
  65521. const Colour Colours::blue (0xff0000ff);
  65522. const Colour Colours::blueviolet (0xff8a2be2);
  65523. const Colour Colours::brown (0xffa52a2a);
  65524. const Colour Colours::burlywood (0xffdeb887);
  65525. const Colour Colours::cadetblue (0xff5f9ea0);
  65526. const Colour Colours::chartreuse (0xff7fff00);
  65527. const Colour Colours::chocolate (0xffd2691e);
  65528. const Colour Colours::coral (0xffff7f50);
  65529. const Colour Colours::cornflowerblue (0xff6495ed);
  65530. const Colour Colours::cornsilk (0xfffff8dc);
  65531. const Colour Colours::crimson (0xffdc143c);
  65532. const Colour Colours::cyan (0xff00ffff);
  65533. const Colour Colours::darkblue (0xff00008b);
  65534. const Colour Colours::darkcyan (0xff008b8b);
  65535. const Colour Colours::darkgoldenrod (0xffb8860b);
  65536. const Colour Colours::darkgrey (0xff555555);
  65537. const Colour Colours::darkgreen (0xff006400);
  65538. const Colour Colours::darkkhaki (0xffbdb76b);
  65539. const Colour Colours::darkmagenta (0xff8b008b);
  65540. const Colour Colours::darkolivegreen (0xff556b2f);
  65541. const Colour Colours::darkorange (0xffff8c00);
  65542. const Colour Colours::darkorchid (0xff9932cc);
  65543. const Colour Colours::darkred (0xff8b0000);
  65544. const Colour Colours::darksalmon (0xffe9967a);
  65545. const Colour Colours::darkseagreen (0xff8fbc8f);
  65546. const Colour Colours::darkslateblue (0xff483d8b);
  65547. const Colour Colours::darkslategrey (0xff2f4f4f);
  65548. const Colour Colours::darkturquoise (0xff00ced1);
  65549. const Colour Colours::darkviolet (0xff9400d3);
  65550. const Colour Colours::deeppink (0xffff1493);
  65551. const Colour Colours::deepskyblue (0xff00bfff);
  65552. const Colour Colours::dimgrey (0xff696969);
  65553. const Colour Colours::dodgerblue (0xff1e90ff);
  65554. const Colour Colours::firebrick (0xffb22222);
  65555. const Colour Colours::floralwhite (0xfffffaf0);
  65556. const Colour Colours::forestgreen (0xff228b22);
  65557. const Colour Colours::fuchsia (0xffff00ff);
  65558. const Colour Colours::gainsboro (0xffdcdcdc);
  65559. const Colour Colours::gold (0xffffd700);
  65560. const Colour Colours::goldenrod (0xffdaa520);
  65561. const Colour Colours::grey (0xff808080);
  65562. const Colour Colours::green (0xff008000);
  65563. const Colour Colours::greenyellow (0xffadff2f);
  65564. const Colour Colours::honeydew (0xfff0fff0);
  65565. const Colour Colours::hotpink (0xffff69b4);
  65566. const Colour Colours::indianred (0xffcd5c5c);
  65567. const Colour Colours::indigo (0xff4b0082);
  65568. const Colour Colours::ivory (0xfffffff0);
  65569. const Colour Colours::khaki (0xfff0e68c);
  65570. const Colour Colours::lavender (0xffe6e6fa);
  65571. const Colour Colours::lavenderblush (0xfffff0f5);
  65572. const Colour Colours::lemonchiffon (0xfffffacd);
  65573. const Colour Colours::lightblue (0xffadd8e6);
  65574. const Colour Colours::lightcoral (0xfff08080);
  65575. const Colour Colours::lightcyan (0xffe0ffff);
  65576. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  65577. const Colour Colours::lightgreen (0xff90ee90);
  65578. const Colour Colours::lightgrey (0xffd3d3d3);
  65579. const Colour Colours::lightpink (0xffffb6c1);
  65580. const Colour Colours::lightsalmon (0xffffa07a);
  65581. const Colour Colours::lightseagreen (0xff20b2aa);
  65582. const Colour Colours::lightskyblue (0xff87cefa);
  65583. const Colour Colours::lightslategrey (0xff778899);
  65584. const Colour Colours::lightsteelblue (0xffb0c4de);
  65585. const Colour Colours::lightyellow (0xffffffe0);
  65586. const Colour Colours::lime (0xff00ff00);
  65587. const Colour Colours::limegreen (0xff32cd32);
  65588. const Colour Colours::linen (0xfffaf0e6);
  65589. const Colour Colours::magenta (0xffff00ff);
  65590. const Colour Colours::maroon (0xff800000);
  65591. const Colour Colours::mediumaquamarine (0xff66cdaa);
  65592. const Colour Colours::mediumblue (0xff0000cd);
  65593. const Colour Colours::mediumorchid (0xffba55d3);
  65594. const Colour Colours::mediumpurple (0xff9370db);
  65595. const Colour Colours::mediumseagreen (0xff3cb371);
  65596. const Colour Colours::mediumslateblue (0xff7b68ee);
  65597. const Colour Colours::mediumspringgreen (0xff00fa9a);
  65598. const Colour Colours::mediumturquoise (0xff48d1cc);
  65599. const Colour Colours::mediumvioletred (0xffc71585);
  65600. const Colour Colours::midnightblue (0xff191970);
  65601. const Colour Colours::mintcream (0xfff5fffa);
  65602. const Colour Colours::mistyrose (0xffffe4e1);
  65603. const Colour Colours::navajowhite (0xffffdead);
  65604. const Colour Colours::navy (0xff000080);
  65605. const Colour Colours::oldlace (0xfffdf5e6);
  65606. const Colour Colours::olive (0xff808000);
  65607. const Colour Colours::olivedrab (0xff6b8e23);
  65608. const Colour Colours::orange (0xffffa500);
  65609. const Colour Colours::orangered (0xffff4500);
  65610. const Colour Colours::orchid (0xffda70d6);
  65611. const Colour Colours::palegoldenrod (0xffeee8aa);
  65612. const Colour Colours::palegreen (0xff98fb98);
  65613. const Colour Colours::paleturquoise (0xffafeeee);
  65614. const Colour Colours::palevioletred (0xffdb7093);
  65615. const Colour Colours::papayawhip (0xffffefd5);
  65616. const Colour Colours::peachpuff (0xffffdab9);
  65617. const Colour Colours::peru (0xffcd853f);
  65618. const Colour Colours::pink (0xffffc0cb);
  65619. const Colour Colours::plum (0xffdda0dd);
  65620. const Colour Colours::powderblue (0xffb0e0e6);
  65621. const Colour Colours::purple (0xff800080);
  65622. const Colour Colours::red (0xffff0000);
  65623. const Colour Colours::rosybrown (0xffbc8f8f);
  65624. const Colour Colours::royalblue (0xff4169e1);
  65625. const Colour Colours::saddlebrown (0xff8b4513);
  65626. const Colour Colours::salmon (0xfffa8072);
  65627. const Colour Colours::sandybrown (0xfff4a460);
  65628. const Colour Colours::seagreen (0xff2e8b57);
  65629. const Colour Colours::seashell (0xfffff5ee);
  65630. const Colour Colours::sienna (0xffa0522d);
  65631. const Colour Colours::silver (0xffc0c0c0);
  65632. const Colour Colours::skyblue (0xff87ceeb);
  65633. const Colour Colours::slateblue (0xff6a5acd);
  65634. const Colour Colours::slategrey (0xff708090);
  65635. const Colour Colours::snow (0xfffffafa);
  65636. const Colour Colours::springgreen (0xff00ff7f);
  65637. const Colour Colours::steelblue (0xff4682b4);
  65638. const Colour Colours::tan (0xffd2b48c);
  65639. const Colour Colours::teal (0xff008080);
  65640. const Colour Colours::thistle (0xffd8bfd8);
  65641. const Colour Colours::tomato (0xffff6347);
  65642. const Colour Colours::turquoise (0xff40e0d0);
  65643. const Colour Colours::violet (0xffee82ee);
  65644. const Colour Colours::wheat (0xfff5deb3);
  65645. const Colour Colours::white (0xffffffff);
  65646. const Colour Colours::whitesmoke (0xfff5f5f5);
  65647. const Colour Colours::yellow (0xffffff00);
  65648. const Colour Colours::yellowgreen (0xff9acd32);
  65649. const Colour Colours::findColourForName (const String& colourName,
  65650. const Colour& defaultColour)
  65651. {
  65652. static const int presets[] =
  65653. {
  65654. // (first value is the string's hashcode, second is ARGB)
  65655. 0x05978fff, 0xff000000, /* black */
  65656. 0x06bdcc29, 0xffffffff, /* white */
  65657. 0x002e305a, 0xff0000ff, /* blue */
  65658. 0x00308adf, 0xff808080, /* grey */
  65659. 0x05e0cf03, 0xff008000, /* green */
  65660. 0x0001b891, 0xffff0000, /* red */
  65661. 0xd43c6474, 0xffffff00, /* yellow */
  65662. 0x620886da, 0xfff0f8ff, /* aliceblue */
  65663. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  65664. 0x002dcebc, 0xff00ffff, /* aqua */
  65665. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  65666. 0x0590228f, 0xfff0ffff, /* azure */
  65667. 0x05947fe4, 0xfff5f5dc, /* beige */
  65668. 0xad388e35, 0xffffe4c4, /* bisque */
  65669. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  65670. 0x39129959, 0xff8a2be2, /* blueviolet */
  65671. 0x059a8136, 0xffa52a2a, /* brown */
  65672. 0x89cea8f9, 0xffdeb887, /* burlywood */
  65673. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  65674. 0x6b748956, 0xff7fff00, /* chartreuse */
  65675. 0x2903623c, 0xffd2691e, /* chocolate */
  65676. 0x05a74431, 0xffff7f50, /* coral */
  65677. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  65678. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  65679. 0x3d8c4edf, 0xffdc143c, /* crimson */
  65680. 0x002ed323, 0xff00ffff, /* cyan */
  65681. 0x67cc74d0, 0xff00008b, /* darkblue */
  65682. 0x67cd1799, 0xff008b8b, /* darkcyan */
  65683. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  65684. 0x67cecf55, 0xff555555, /* darkgrey */
  65685. 0x920b194d, 0xff006400, /* darkgreen */
  65686. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  65687. 0x5c293873, 0xff8b008b, /* darkmagenta */
  65688. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  65689. 0xbcfd2524, 0xffff8c00, /* darkorange */
  65690. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  65691. 0x55ee0d5b, 0xff8b0000, /* darkred */
  65692. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  65693. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  65694. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  65695. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  65696. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  65697. 0xc8769375, 0xff9400d3, /* darkviolet */
  65698. 0x25832862, 0xffff1493, /* deeppink */
  65699. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  65700. 0x634c8b67, 0xff696969, /* dimgrey */
  65701. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  65702. 0xef19e3cb, 0xffb22222, /* firebrick */
  65703. 0xb852b195, 0xfffffaf0, /* floralwhite */
  65704. 0xd086fd06, 0xff228b22, /* forestgreen */
  65705. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  65706. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  65707. 0x00308060, 0xffffd700, /* gold */
  65708. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  65709. 0xbab8a537, 0xffadff2f, /* greenyellow */
  65710. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  65711. 0x41892743, 0xffff69b4, /* hotpink */
  65712. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  65713. 0xb969fed2, 0xff4b0082, /* indigo */
  65714. 0x05fef6a9, 0xfffffff0, /* ivory */
  65715. 0x06149302, 0xfff0e68c, /* khaki */
  65716. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  65717. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  65718. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  65719. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  65720. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  65721. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  65722. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  65723. 0xf40157ad, 0xff90ee90, /* lightgreen */
  65724. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  65725. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  65726. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  65727. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  65728. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  65729. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  65730. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  65731. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  65732. 0x0032afd5, 0xff00ff00, /* lime */
  65733. 0x607bbc4e, 0xff32cd32, /* limegreen */
  65734. 0x06234efa, 0xfffaf0e6, /* linen */
  65735. 0x316858a9, 0xffff00ff, /* magenta */
  65736. 0xbf8ca470, 0xff800000, /* maroon */
  65737. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  65738. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  65739. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  65740. 0x07556b71, 0xff9370db, /* mediumpurple */
  65741. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  65742. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  65743. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  65744. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  65745. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  65746. 0x168eb32a, 0xff191970, /* midnightblue */
  65747. 0x4306b960, 0xfff5fffa, /* mintcream */
  65748. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  65749. 0xe97218a6, 0xffffdead, /* navajowhite */
  65750. 0x00337bb6, 0xff000080, /* navy */
  65751. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  65752. 0x064ee1db, 0xff808000, /* olive */
  65753. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  65754. 0xc3de262e, 0xffffa500, /* orange */
  65755. 0x58bebba3, 0xffff4500, /* orangered */
  65756. 0xc3def8a3, 0xffda70d6, /* orchid */
  65757. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  65758. 0x3d9dd619, 0xff98fb98, /* palegreen */
  65759. 0x74022737, 0xffafeeee, /* paleturquoise */
  65760. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  65761. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  65762. 0x93e1b776, 0xffffdab9, /* peachpuff */
  65763. 0x003472f8, 0xffcd853f, /* peru */
  65764. 0x00348176, 0xffffc0cb, /* pink */
  65765. 0x00348d94, 0xffdda0dd, /* plum */
  65766. 0xd036be93, 0xffb0e0e6, /* powderblue */
  65767. 0xc5c507bc, 0xff800080, /* purple */
  65768. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  65769. 0xbd9413e1, 0xff4169e1, /* royalblue */
  65770. 0xf456044f, 0xff8b4513, /* saddlebrown */
  65771. 0xc9c6f66e, 0xfffa8072, /* salmon */
  65772. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  65773. 0x34636c14, 0xff2e8b57, /* seagreen */
  65774. 0x3507fb41, 0xfffff5ee, /* seashell */
  65775. 0xca348772, 0xffa0522d, /* sienna */
  65776. 0xca37d30d, 0xffc0c0c0, /* silver */
  65777. 0x80da74fb, 0xff87ceeb, /* skyblue */
  65778. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  65779. 0x44ab37f8, 0xff708090, /* slategrey */
  65780. 0x0035f183, 0xfffffafa, /* snow */
  65781. 0xd5440d16, 0xff00ff7f, /* springgreen */
  65782. 0x3e1524a5, 0xff4682b4, /* steelblue */
  65783. 0x0001bfa1, 0xffd2b48c, /* tan */
  65784. 0x0036425c, 0xff008080, /* teal */
  65785. 0xafc8858f, 0xffd8bfd8, /* thistle */
  65786. 0xcc41600a, 0xffff6347, /* tomato */
  65787. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  65788. 0xcf57947f, 0xffee82ee, /* violet */
  65789. 0x06bdbae7, 0xfff5deb3, /* wheat */
  65790. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  65791. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  65792. };
  65793. const int hash = colourName.trim().toLowerCase().hashCode();
  65794. for (int i = 0; i < numElementsInArray (presets); i += 2)
  65795. if (presets [i] == hash)
  65796. return Colour (presets [i + 1]);
  65797. return defaultColour;
  65798. }
  65799. END_JUCE_NAMESPACE
  65800. /*** End of inlined file: juce_Colours.cpp ***/
  65801. /*** Start of inlined file: juce_EdgeTable.cpp ***/
  65802. BEGIN_JUCE_NAMESPACE
  65803. const int juce_edgeTableDefaultEdgesPerLine = 32;
  65804. EdgeTable::EdgeTable (const Rectangle<int>& bounds_,
  65805. const Path& path, const AffineTransform& transform)
  65806. : bounds (bounds_),
  65807. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65808. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65809. needToCheckEmptinesss (true)
  65810. {
  65811. table.malloc ((bounds.getHeight() + 1) * lineStrideElements);
  65812. int* t = table;
  65813. for (int i = bounds.getHeight(); --i >= 0;)
  65814. {
  65815. *t = 0;
  65816. t += lineStrideElements;
  65817. }
  65818. const int topLimit = bounds.getY() << 8;
  65819. const int heightLimit = bounds.getHeight() << 8;
  65820. const int leftLimit = bounds.getX() << 8;
  65821. const int rightLimit = bounds.getRight() << 8;
  65822. PathFlatteningIterator iter (path, transform);
  65823. while (iter.next())
  65824. {
  65825. int y1 = roundToInt (iter.y1 * 256.0f);
  65826. int y2 = roundToInt (iter.y2 * 256.0f);
  65827. if (y1 != y2)
  65828. {
  65829. y1 -= topLimit;
  65830. y2 -= topLimit;
  65831. const int startY = y1;
  65832. int direction = -1;
  65833. if (y1 > y2)
  65834. {
  65835. swapVariables (y1, y2);
  65836. direction = 1;
  65837. }
  65838. if (y1 < 0)
  65839. y1 = 0;
  65840. if (y2 > heightLimit)
  65841. y2 = heightLimit;
  65842. if (y1 < y2)
  65843. {
  65844. const double startX = 256.0f * iter.x1;
  65845. const double multiplier = (iter.x2 - iter.x1) / (iter.y2 - iter.y1);
  65846. const int stepSize = jlimit (1, 256, 256 / (1 + (int) std::abs (multiplier)));
  65847. do
  65848. {
  65849. const int step = jmin (stepSize, y2 - y1, 256 - (y1 & 255));
  65850. int x = roundToInt (startX + multiplier * ((y1 + (step >> 1)) - startY));
  65851. if (x < leftLimit)
  65852. x = leftLimit;
  65853. else if (x >= rightLimit)
  65854. x = rightLimit - 1;
  65855. addEdgePoint (x, y1 >> 8, direction * step);
  65856. y1 += step;
  65857. }
  65858. while (y1 < y2);
  65859. }
  65860. }
  65861. }
  65862. sanitiseLevels (path.isUsingNonZeroWinding());
  65863. }
  65864. EdgeTable::EdgeTable (const Rectangle<int>& rectangleToAdd)
  65865. : bounds (rectangleToAdd),
  65866. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65867. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65868. needToCheckEmptinesss (true)
  65869. {
  65870. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65871. table[0] = 0;
  65872. const int x1 = rectangleToAdd.getX() << 8;
  65873. const int x2 = rectangleToAdd.getRight() << 8;
  65874. int* t = table;
  65875. for (int i = rectangleToAdd.getHeight(); --i >= 0;)
  65876. {
  65877. t[0] = 2;
  65878. t[1] = x1;
  65879. t[2] = 255;
  65880. t[3] = x2;
  65881. t[4] = 0;
  65882. t += lineStrideElements;
  65883. }
  65884. }
  65885. EdgeTable::EdgeTable (const RectangleList& rectanglesToAdd)
  65886. : bounds (rectanglesToAdd.getBounds()),
  65887. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65888. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65889. needToCheckEmptinesss (true)
  65890. {
  65891. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65892. int* t = table;
  65893. for (int i = bounds.getHeight(); --i >= 0;)
  65894. {
  65895. *t = 0;
  65896. t += lineStrideElements;
  65897. }
  65898. for (RectangleList::Iterator iter (rectanglesToAdd); iter.next();)
  65899. {
  65900. const Rectangle<int>* const r = iter.getRectangle();
  65901. const int x1 = r->getX() << 8;
  65902. const int x2 = r->getRight() << 8;
  65903. int y = r->getY() - bounds.getY();
  65904. for (int j = r->getHeight(); --j >= 0;)
  65905. {
  65906. addEdgePoint (x1, y, 255);
  65907. addEdgePoint (x2, y, -255);
  65908. ++y;
  65909. }
  65910. }
  65911. sanitiseLevels (true);
  65912. }
  65913. EdgeTable::EdgeTable (const Rectangle<float>& rectangleToAdd)
  65914. : bounds (Rectangle<int> ((int) std::floor (rectangleToAdd.getX()),
  65915. roundToInt (rectangleToAdd.getY() * 256.0f) >> 8,
  65916. 2 + (int) rectangleToAdd.getWidth(),
  65917. 2 + (int) rectangleToAdd.getHeight())),
  65918. maxEdgesPerLine (juce_edgeTableDefaultEdgesPerLine),
  65919. lineStrideElements ((juce_edgeTableDefaultEdgesPerLine << 1) + 1),
  65920. needToCheckEmptinesss (true)
  65921. {
  65922. jassert (! rectangleToAdd.isEmpty());
  65923. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65924. table[0] = 0;
  65925. const int x1 = roundToInt (rectangleToAdd.getX() * 256.0f);
  65926. const int x2 = roundToInt (rectangleToAdd.getRight() * 256.0f);
  65927. int y1 = roundToInt (rectangleToAdd.getY() * 256.0f) - (bounds.getY() << 8);
  65928. jassert (y1 < 256);
  65929. int y2 = roundToInt (rectangleToAdd.getBottom() * 256.0f) - (bounds.getY() << 8);
  65930. if (x2 <= x1 || y2 <= y1)
  65931. {
  65932. bounds.setHeight (0);
  65933. return;
  65934. }
  65935. int lineY = 0;
  65936. int* t = table;
  65937. if ((y1 >> 8) == (y2 >> 8))
  65938. {
  65939. t[0] = 2;
  65940. t[1] = x1;
  65941. t[2] = y2 - y1;
  65942. t[3] = x2;
  65943. t[4] = 0;
  65944. ++lineY;
  65945. t += lineStrideElements;
  65946. }
  65947. else
  65948. {
  65949. t[0] = 2;
  65950. t[1] = x1;
  65951. t[2] = 255 - (y1 & 255);
  65952. t[3] = x2;
  65953. t[4] = 0;
  65954. ++lineY;
  65955. t += lineStrideElements;
  65956. while (lineY < (y2 >> 8))
  65957. {
  65958. t[0] = 2;
  65959. t[1] = x1;
  65960. t[2] = 255;
  65961. t[3] = x2;
  65962. t[4] = 0;
  65963. ++lineY;
  65964. t += lineStrideElements;
  65965. }
  65966. jassert (lineY < bounds.getHeight());
  65967. t[0] = 2;
  65968. t[1] = x1;
  65969. t[2] = y2 & 255;
  65970. t[3] = x2;
  65971. t[4] = 0;
  65972. ++lineY;
  65973. t += lineStrideElements;
  65974. }
  65975. while (lineY < bounds.getHeight())
  65976. {
  65977. t[0] = 0;
  65978. t += lineStrideElements;
  65979. ++lineY;
  65980. }
  65981. }
  65982. EdgeTable::EdgeTable (const EdgeTable& other)
  65983. {
  65984. operator= (other);
  65985. }
  65986. EdgeTable& EdgeTable::operator= (const EdgeTable& other)
  65987. {
  65988. bounds = other.bounds;
  65989. maxEdgesPerLine = other.maxEdgesPerLine;
  65990. lineStrideElements = other.lineStrideElements;
  65991. needToCheckEmptinesss = other.needToCheckEmptinesss;
  65992. table.malloc (jmax (1, bounds.getHeight()) * lineStrideElements);
  65993. copyEdgeTableData (table, lineStrideElements, other.table, lineStrideElements, bounds.getHeight());
  65994. return *this;
  65995. }
  65996. EdgeTable::~EdgeTable()
  65997. {
  65998. }
  65999. void EdgeTable::copyEdgeTableData (int* dest, const int destLineStride, const int* src, const int srcLineStride, int numLines) throw()
  66000. {
  66001. while (--numLines >= 0)
  66002. {
  66003. memcpy (dest, src, (src[0] * 2 + 1) * sizeof (int));
  66004. src += srcLineStride;
  66005. dest += destLineStride;
  66006. }
  66007. }
  66008. void EdgeTable::sanitiseLevels (const bool useNonZeroWinding) throw()
  66009. {
  66010. // Convert the table from relative windings to absolute levels..
  66011. int* lineStart = table;
  66012. for (int i = bounds.getHeight(); --i >= 0;)
  66013. {
  66014. int* line = lineStart;
  66015. lineStart += lineStrideElements;
  66016. int num = *line;
  66017. if (num == 0)
  66018. continue;
  66019. int level = 0;
  66020. if (useNonZeroWinding)
  66021. {
  66022. while (--num > 0)
  66023. {
  66024. line += 2;
  66025. level += *line;
  66026. int corrected = abs (level);
  66027. if (corrected >> 8)
  66028. corrected = 255;
  66029. *line = corrected;
  66030. }
  66031. }
  66032. else
  66033. {
  66034. while (--num > 0)
  66035. {
  66036. line += 2;
  66037. level += *line;
  66038. int corrected = abs (level);
  66039. if (corrected >> 8)
  66040. {
  66041. corrected &= 511;
  66042. if (corrected >> 8)
  66043. corrected = 511 - corrected;
  66044. }
  66045. *line = corrected;
  66046. }
  66047. }
  66048. line[2] = 0; // force the last level to 0, just in case something went wrong in creating the table
  66049. }
  66050. }
  66051. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  66052. {
  66053. if (newNumEdgesPerLine != maxEdgesPerLine)
  66054. {
  66055. maxEdgesPerLine = newNumEdgesPerLine;
  66056. jassert (bounds.getHeight() > 0);
  66057. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  66058. HeapBlock <int> newTable (bounds.getHeight() * newLineStrideElements);
  66059. copyEdgeTableData (newTable, newLineStrideElements, table, lineStrideElements, bounds.getHeight());
  66060. table.swapWith (newTable);
  66061. lineStrideElements = newLineStrideElements;
  66062. }
  66063. }
  66064. void EdgeTable::optimiseTable() throw()
  66065. {
  66066. int maxLineElements = 0;
  66067. for (int i = bounds.getHeight(); --i >= 0;)
  66068. maxLineElements = jmax (maxLineElements, table [i * lineStrideElements]);
  66069. remapTableForNumEdges (maxLineElements);
  66070. }
  66071. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  66072. {
  66073. jassert (y >= 0 && y < bounds.getHeight());
  66074. int* line = table + lineStrideElements * y;
  66075. const int numPoints = line[0];
  66076. int n = numPoints << 1;
  66077. if (n > 0)
  66078. {
  66079. while (n > 0)
  66080. {
  66081. const int cx = line [n - 1];
  66082. if (cx <= x)
  66083. {
  66084. if (cx == x)
  66085. {
  66086. line [n] += winding;
  66087. return;
  66088. }
  66089. break;
  66090. }
  66091. n -= 2;
  66092. }
  66093. if (numPoints >= maxEdgesPerLine)
  66094. {
  66095. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66096. jassert (numPoints < maxEdgesPerLine);
  66097. line = table + lineStrideElements * y;
  66098. }
  66099. memmove (line + (n + 3), line + (n + 1), sizeof (int) * ((numPoints << 1) - n));
  66100. }
  66101. line [n + 1] = x;
  66102. line [n + 2] = winding;
  66103. line[0]++;
  66104. }
  66105. void EdgeTable::translate (float dx, const int dy) throw()
  66106. {
  66107. bounds.translate ((int) std::floor (dx), dy);
  66108. int* lineStart = table;
  66109. const int intDx = (int) (dx * 256.0f);
  66110. for (int i = bounds.getHeight(); --i >= 0;)
  66111. {
  66112. int* line = lineStart;
  66113. lineStart += lineStrideElements;
  66114. int num = *line++;
  66115. while (--num >= 0)
  66116. {
  66117. *line += intDx;
  66118. line += 2;
  66119. }
  66120. }
  66121. }
  66122. void EdgeTable::intersectWithEdgeTableLine (const int y, const int* otherLine) throw()
  66123. {
  66124. jassert (y >= 0 && y < bounds.getHeight());
  66125. int* dest = table + lineStrideElements * y;
  66126. if (dest[0] == 0)
  66127. return;
  66128. int otherNumPoints = *otherLine;
  66129. if (otherNumPoints == 0)
  66130. {
  66131. *dest = 0;
  66132. return;
  66133. }
  66134. const int right = bounds.getRight() << 8;
  66135. // optimise for the common case where our line lies entirely within a
  66136. // single pair of points, as happens when clipping to a simple rect.
  66137. if (otherNumPoints == 2 && otherLine[2] >= 255)
  66138. {
  66139. clipEdgeTableLineToRange (dest, otherLine[1], jmin (right, otherLine[3]));
  66140. return;
  66141. }
  66142. ++otherLine;
  66143. const size_t lineSizeBytes = (dest[0] * 2 + 1) * sizeof (int);
  66144. int* temp = static_cast<int*> (alloca (lineSizeBytes));
  66145. memcpy (temp, dest, lineSizeBytes);
  66146. const int* src1 = temp;
  66147. int srcNum1 = *src1++;
  66148. int x1 = *src1++;
  66149. const int* src2 = otherLine;
  66150. int srcNum2 = otherNumPoints;
  66151. int x2 = *src2++;
  66152. int destIndex = 0, destTotal = 0;
  66153. int level1 = 0, level2 = 0;
  66154. int lastX = std::numeric_limits<int>::min(), lastLevel = 0;
  66155. while (srcNum1 > 0 && srcNum2 > 0)
  66156. {
  66157. int nextX;
  66158. if (x1 < x2)
  66159. {
  66160. nextX = x1;
  66161. level1 = *src1++;
  66162. x1 = *src1++;
  66163. --srcNum1;
  66164. }
  66165. else if (x1 == x2)
  66166. {
  66167. nextX = x1;
  66168. level1 = *src1++;
  66169. level2 = *src2++;
  66170. x1 = *src1++;
  66171. x2 = *src2++;
  66172. --srcNum1;
  66173. --srcNum2;
  66174. }
  66175. else
  66176. {
  66177. nextX = x2;
  66178. level2 = *src2++;
  66179. x2 = *src2++;
  66180. --srcNum2;
  66181. }
  66182. if (nextX > lastX)
  66183. {
  66184. if (nextX >= right)
  66185. break;
  66186. lastX = nextX;
  66187. const int nextLevel = (level1 * (level2 + 1)) >> 8;
  66188. jassert (((unsigned int) nextLevel) < (unsigned int) 256);
  66189. if (nextLevel != lastLevel)
  66190. {
  66191. if (destTotal >= maxEdgesPerLine)
  66192. {
  66193. dest[0] = destTotal;
  66194. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66195. dest = table + lineStrideElements * y;
  66196. }
  66197. ++destTotal;
  66198. lastLevel = nextLevel;
  66199. dest[++destIndex] = nextX;
  66200. dest[++destIndex] = nextLevel;
  66201. }
  66202. }
  66203. }
  66204. if (lastLevel > 0)
  66205. {
  66206. if (destTotal >= maxEdgesPerLine)
  66207. {
  66208. dest[0] = destTotal;
  66209. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  66210. dest = table + lineStrideElements * y;
  66211. }
  66212. ++destTotal;
  66213. dest[++destIndex] = right;
  66214. dest[++destIndex] = 0;
  66215. }
  66216. dest[0] = destTotal;
  66217. #if JUCE_DEBUG
  66218. int last = std::numeric_limits<int>::min();
  66219. for (int i = 0; i < dest[0]; ++i)
  66220. {
  66221. jassert (dest[i * 2 + 1] > last);
  66222. last = dest[i * 2 + 1];
  66223. }
  66224. jassert (dest [dest[0] * 2] == 0);
  66225. #endif
  66226. }
  66227. void EdgeTable::clipEdgeTableLineToRange (int* dest, const int x1, const int x2) throw()
  66228. {
  66229. int* lastItem = dest + (dest[0] * 2 - 1);
  66230. if (x2 < lastItem[0])
  66231. {
  66232. if (x2 <= dest[1])
  66233. {
  66234. dest[0] = 0;
  66235. return;
  66236. }
  66237. while (x2 < lastItem[-2])
  66238. {
  66239. --(dest[0]);
  66240. lastItem -= 2;
  66241. }
  66242. lastItem[0] = x2;
  66243. lastItem[1] = 0;
  66244. }
  66245. if (x1 > dest[1])
  66246. {
  66247. while (lastItem[0] > x1)
  66248. lastItem -= 2;
  66249. const int itemsRemoved = (int) (lastItem - (dest + 1)) / 2;
  66250. if (itemsRemoved > 0)
  66251. {
  66252. dest[0] -= itemsRemoved;
  66253. memmove (dest + 1, lastItem, dest[0] * (sizeof (int) * 2));
  66254. }
  66255. dest[1] = x1;
  66256. }
  66257. }
  66258. void EdgeTable::clipToRectangle (const Rectangle<int>& r) throw()
  66259. {
  66260. const Rectangle<int> clipped (r.getIntersection (bounds));
  66261. if (clipped.isEmpty())
  66262. {
  66263. needToCheckEmptinesss = false;
  66264. bounds.setHeight (0);
  66265. }
  66266. else
  66267. {
  66268. const int top = clipped.getY() - bounds.getY();
  66269. const int bottom = clipped.getBottom() - bounds.getY();
  66270. if (bottom < bounds.getHeight())
  66271. bounds.setHeight (bottom);
  66272. if (clipped.getRight() < bounds.getRight())
  66273. bounds.setRight (clipped.getRight());
  66274. for (int i = top; --i >= 0;)
  66275. table [lineStrideElements * i] = 0;
  66276. if (clipped.getX() > bounds.getX())
  66277. {
  66278. const int x1 = clipped.getX() << 8;
  66279. const int x2 = jmin (bounds.getRight(), clipped.getRight()) << 8;
  66280. int* line = table + lineStrideElements * top;
  66281. for (int i = bottom - top; --i >= 0;)
  66282. {
  66283. if (line[0] != 0)
  66284. clipEdgeTableLineToRange (line, x1, x2);
  66285. line += lineStrideElements;
  66286. }
  66287. }
  66288. needToCheckEmptinesss = true;
  66289. }
  66290. }
  66291. void EdgeTable::excludeRectangle (const Rectangle<int>& r) throw()
  66292. {
  66293. const Rectangle<int> clipped (r.getIntersection (bounds));
  66294. if (! clipped.isEmpty())
  66295. {
  66296. const int top = clipped.getY() - bounds.getY();
  66297. const int bottom = clipped.getBottom() - bounds.getY();
  66298. //XXX optimise here by shortening the table if it fills top or bottom
  66299. const int rectLine[] = { 4, std::numeric_limits<int>::min(), 255,
  66300. clipped.getX() << 8, 0,
  66301. clipped.getRight() << 8, 255,
  66302. std::numeric_limits<int>::max(), 0 };
  66303. for (int i = top; i < bottom; ++i)
  66304. intersectWithEdgeTableLine (i, rectLine);
  66305. needToCheckEmptinesss = true;
  66306. }
  66307. }
  66308. void EdgeTable::clipToEdgeTable (const EdgeTable& other)
  66309. {
  66310. const Rectangle<int> clipped (other.bounds.getIntersection (bounds));
  66311. if (clipped.isEmpty())
  66312. {
  66313. needToCheckEmptinesss = false;
  66314. bounds.setHeight (0);
  66315. }
  66316. else
  66317. {
  66318. const int top = clipped.getY() - bounds.getY();
  66319. const int bottom = clipped.getBottom() - bounds.getY();
  66320. if (bottom < bounds.getHeight())
  66321. bounds.setHeight (bottom);
  66322. if (clipped.getRight() < bounds.getRight())
  66323. bounds.setRight (clipped.getRight());
  66324. int i = 0;
  66325. for (i = top; --i >= 0;)
  66326. table [lineStrideElements * i] = 0;
  66327. const int* otherLine = other.table + other.lineStrideElements * (clipped.getY() - other.bounds.getY());
  66328. for (i = top; i < bottom; ++i)
  66329. {
  66330. intersectWithEdgeTableLine (i, otherLine);
  66331. otherLine += other.lineStrideElements;
  66332. }
  66333. needToCheckEmptinesss = true;
  66334. }
  66335. }
  66336. void EdgeTable::clipLineToMask (int x, int y, const uint8* mask, int maskStride, int numPixels) throw()
  66337. {
  66338. y -= bounds.getY();
  66339. if (y < 0 || y >= bounds.getHeight())
  66340. return;
  66341. needToCheckEmptinesss = true;
  66342. if (numPixels <= 0)
  66343. {
  66344. table [lineStrideElements * y] = 0;
  66345. return;
  66346. }
  66347. int* tempLine = static_cast<int*> (alloca ((numPixels * 2 + 4) * sizeof (int)));
  66348. int destIndex = 0, lastLevel = 0;
  66349. while (--numPixels >= 0)
  66350. {
  66351. const int alpha = *mask;
  66352. mask += maskStride;
  66353. if (alpha != lastLevel)
  66354. {
  66355. tempLine[++destIndex] = (x << 8);
  66356. tempLine[++destIndex] = alpha;
  66357. lastLevel = alpha;
  66358. }
  66359. ++x;
  66360. }
  66361. if (lastLevel > 0)
  66362. {
  66363. tempLine[++destIndex] = (x << 8);
  66364. tempLine[++destIndex] = 0;
  66365. }
  66366. tempLine[0] = destIndex >> 1;
  66367. intersectWithEdgeTableLine (y, tempLine);
  66368. }
  66369. bool EdgeTable::isEmpty() throw()
  66370. {
  66371. if (needToCheckEmptinesss)
  66372. {
  66373. needToCheckEmptinesss = false;
  66374. int* t = table;
  66375. for (int i = bounds.getHeight(); --i >= 0;)
  66376. {
  66377. if (t[0] > 1)
  66378. return false;
  66379. t += lineStrideElements;
  66380. }
  66381. bounds.setHeight (0);
  66382. }
  66383. return bounds.getHeight() == 0;
  66384. }
  66385. END_JUCE_NAMESPACE
  66386. /*** End of inlined file: juce_EdgeTable.cpp ***/
  66387. /*** Start of inlined file: juce_FillType.cpp ***/
  66388. BEGIN_JUCE_NAMESPACE
  66389. FillType::FillType() throw()
  66390. : colour (0xff000000), image (0)
  66391. {
  66392. }
  66393. FillType::FillType (const Colour& colour_) throw()
  66394. : colour (colour_), image (0)
  66395. {
  66396. }
  66397. FillType::FillType (const ColourGradient& gradient_)
  66398. : colour (0xff000000), gradient (new ColourGradient (gradient_)), image (0)
  66399. {
  66400. }
  66401. FillType::FillType (const Image& image_, const AffineTransform& transform_) throw()
  66402. : colour (0xff000000), image (image_), transform (transform_)
  66403. {
  66404. }
  66405. FillType::FillType (const FillType& other)
  66406. : colour (other.colour),
  66407. gradient (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0),
  66408. image (other.image), transform (other.transform)
  66409. {
  66410. }
  66411. FillType& FillType::operator= (const FillType& other)
  66412. {
  66413. if (this != &other)
  66414. {
  66415. colour = other.colour;
  66416. gradient = (other.gradient != 0 ? new ColourGradient (*other.gradient) : 0);
  66417. image = other.image;
  66418. transform = other.transform;
  66419. }
  66420. return *this;
  66421. }
  66422. FillType::~FillType() throw()
  66423. {
  66424. }
  66425. bool FillType::operator== (const FillType& other) const
  66426. {
  66427. return colour == other.colour && image == other.image
  66428. && transform == other.transform
  66429. && (gradient == other.gradient
  66430. || (gradient != 0 && other.gradient != 0 && *gradient == *other.gradient));
  66431. }
  66432. bool FillType::operator!= (const FillType& other) const
  66433. {
  66434. return ! operator== (other);
  66435. }
  66436. void FillType::setColour (const Colour& newColour) throw()
  66437. {
  66438. gradient = 0;
  66439. image = Image::null;
  66440. colour = newColour;
  66441. }
  66442. void FillType::setGradient (const ColourGradient& newGradient)
  66443. {
  66444. if (gradient != 0)
  66445. {
  66446. *gradient = newGradient;
  66447. }
  66448. else
  66449. {
  66450. image = Image::null;
  66451. gradient = new ColourGradient (newGradient);
  66452. colour = Colours::black;
  66453. }
  66454. }
  66455. void FillType::setTiledImage (const Image& image_, const AffineTransform& transform_) throw()
  66456. {
  66457. gradient = 0;
  66458. image = image_;
  66459. transform = transform_;
  66460. colour = Colours::black;
  66461. }
  66462. void FillType::setOpacity (const float newOpacity) throw()
  66463. {
  66464. colour = colour.withAlpha (newOpacity);
  66465. }
  66466. bool FillType::isInvisible() const throw()
  66467. {
  66468. return colour.isTransparent() || (gradient != 0 && gradient->isInvisible());
  66469. }
  66470. END_JUCE_NAMESPACE
  66471. /*** End of inlined file: juce_FillType.cpp ***/
  66472. /*** Start of inlined file: juce_Graphics.cpp ***/
  66473. BEGIN_JUCE_NAMESPACE
  66474. namespace
  66475. {
  66476. template <typename Type>
  66477. bool areCoordsSensibleNumbers (Type x, Type y, Type w, Type h)
  66478. {
  66479. const int maxVal = 0x3fffffff;
  66480. return (int) x >= -maxVal && (int) x <= maxVal
  66481. && (int) y >= -maxVal && (int) y <= maxVal
  66482. && (int) w >= -maxVal && (int) w <= maxVal
  66483. && (int) h >= -maxVal && (int) h <= maxVal;
  66484. }
  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 Rectangle<int>& area)
  66518. {
  66519. saveStateIfPending();
  66520. return context->clipToRectangle (area);
  66521. }
  66522. bool Graphics::reduceClipRegion (const int x, const int y, const int w, const int h)
  66523. {
  66524. return reduceClipRegion (Rectangle<int> (x, y, w, h));
  66525. }
  66526. bool Graphics::reduceClipRegion (const RectangleList& clipRegion)
  66527. {
  66528. saveStateIfPending();
  66529. return context->clipToRectangleList (clipRegion);
  66530. }
  66531. bool Graphics::reduceClipRegion (const Path& path, const AffineTransform& transform)
  66532. {
  66533. saveStateIfPending();
  66534. context->clipToPath (path, transform);
  66535. return ! context->isClipEmpty();
  66536. }
  66537. bool Graphics::reduceClipRegion (const Image& image, const AffineTransform& transform)
  66538. {
  66539. saveStateIfPending();
  66540. context->clipToImageAlpha (image, transform);
  66541. return ! context->isClipEmpty();
  66542. }
  66543. void Graphics::excludeClipRegion (const Rectangle<int>& rectangleToExclude)
  66544. {
  66545. saveStateIfPending();
  66546. context->excludeClipRectangle (rectangleToExclude);
  66547. }
  66548. bool Graphics::isClipEmpty() const
  66549. {
  66550. return context->isClipEmpty();
  66551. }
  66552. const Rectangle<int> Graphics::getClipBounds() const
  66553. {
  66554. return context->getClipBounds();
  66555. }
  66556. void Graphics::saveState()
  66557. {
  66558. saveStateIfPending();
  66559. saveStatePending = true;
  66560. }
  66561. void Graphics::restoreState()
  66562. {
  66563. if (saveStatePending)
  66564. saveStatePending = false;
  66565. else
  66566. context->restoreState();
  66567. }
  66568. void Graphics::saveStateIfPending()
  66569. {
  66570. if (saveStatePending)
  66571. {
  66572. saveStatePending = false;
  66573. context->saveState();
  66574. }
  66575. }
  66576. void Graphics::setOrigin (const int newOriginX, const int newOriginY)
  66577. {
  66578. saveStateIfPending();
  66579. context->setOrigin (newOriginX, newOriginY);
  66580. }
  66581. bool Graphics::clipRegionIntersects (const Rectangle<int>& area) const
  66582. {
  66583. return context->clipRegionIntersects (area);
  66584. }
  66585. void Graphics::setColour (const Colour& newColour)
  66586. {
  66587. saveStateIfPending();
  66588. context->setFill (newColour);
  66589. }
  66590. void Graphics::setOpacity (const float newOpacity)
  66591. {
  66592. saveStateIfPending();
  66593. context->setOpacity (newOpacity);
  66594. }
  66595. void Graphics::setGradientFill (const ColourGradient& gradient)
  66596. {
  66597. setFillType (gradient);
  66598. }
  66599. void Graphics::setTiledImageFill (const Image& imageToUse, const int anchorX, const int anchorY, const float opacity)
  66600. {
  66601. saveStateIfPending();
  66602. context->setFill (FillType (imageToUse, AffineTransform::translation ((float) anchorX, (float) anchorY)));
  66603. context->setOpacity (opacity);
  66604. }
  66605. void Graphics::setFillType (const FillType& newFill)
  66606. {
  66607. saveStateIfPending();
  66608. context->setFill (newFill);
  66609. }
  66610. void Graphics::setFont (const Font& newFont)
  66611. {
  66612. saveStateIfPending();
  66613. context->setFont (newFont);
  66614. }
  66615. void Graphics::setFont (const float newFontHeight, const int newFontStyleFlags)
  66616. {
  66617. saveStateIfPending();
  66618. Font f (context->getFont());
  66619. f.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0);
  66620. context->setFont (f);
  66621. }
  66622. const Font Graphics::getCurrentFont() const
  66623. {
  66624. return context->getFont();
  66625. }
  66626. void Graphics::drawSingleLineText (const String& text, const int startX, const int baselineY) const
  66627. {
  66628. if (text.isNotEmpty()
  66629. && startX < context->getClipBounds().getRight())
  66630. {
  66631. GlyphArrangement arr;
  66632. arr.addLineOfText (context->getFont(), text, (float) startX, (float) baselineY);
  66633. arr.draw (*this);
  66634. }
  66635. }
  66636. void Graphics::drawTextAsPath (const String& text, const AffineTransform& transform) const
  66637. {
  66638. if (text.isNotEmpty())
  66639. {
  66640. GlyphArrangement arr;
  66641. arr.addLineOfText (context->getFont(), text, 0.0f, 0.0f);
  66642. arr.draw (*this, transform);
  66643. }
  66644. }
  66645. void Graphics::drawMultiLineText (const String& text, const int startX, const int baselineY, const int maximumLineWidth) const
  66646. {
  66647. if (text.isNotEmpty()
  66648. && startX < context->getClipBounds().getRight())
  66649. {
  66650. GlyphArrangement arr;
  66651. arr.addJustifiedText (context->getFont(), text,
  66652. (float) startX, (float) baselineY, (float) maximumLineWidth,
  66653. Justification::left);
  66654. arr.draw (*this);
  66655. }
  66656. }
  66657. void Graphics::drawText (const String& text,
  66658. const int x, const int y, const int width, const int height,
  66659. const Justification& justificationType,
  66660. const bool useEllipsesIfTooBig) const
  66661. {
  66662. if (text.isNotEmpty() && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66663. {
  66664. GlyphArrangement arr;
  66665. arr.addCurtailedLineOfText (context->getFont(), text,
  66666. 0.0f, 0.0f, (float) width,
  66667. useEllipsesIfTooBig);
  66668. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  66669. (float) x, (float) y, (float) width, (float) height,
  66670. justificationType);
  66671. arr.draw (*this);
  66672. }
  66673. }
  66674. void Graphics::drawFittedText (const String& text,
  66675. const int x, const int y, const int width, const int height,
  66676. const Justification& justification,
  66677. const int maximumNumberOfLines,
  66678. const float minimumHorizontalScale) const
  66679. {
  66680. if (text.isNotEmpty()
  66681. && width > 0 && height > 0
  66682. && context->clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66683. {
  66684. GlyphArrangement arr;
  66685. arr.addFittedText (context->getFont(), text,
  66686. (float) x, (float) y, (float) width, (float) height,
  66687. justification,
  66688. maximumNumberOfLines,
  66689. minimumHorizontalScale);
  66690. arr.draw (*this);
  66691. }
  66692. }
  66693. void Graphics::fillRect (int x, int y, int width, int height) const
  66694. {
  66695. // passing in a silly number can cause maths problems in rendering!
  66696. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66697. context->fillRect (Rectangle<int> (x, y, width, height), false);
  66698. }
  66699. void Graphics::fillRect (const Rectangle<int>& r) const
  66700. {
  66701. context->fillRect (r, false);
  66702. }
  66703. void Graphics::fillRect (const float x, const float y, const float width, const float height) const
  66704. {
  66705. // passing in a silly number can cause maths problems in rendering!
  66706. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66707. Path p;
  66708. p.addRectangle (x, y, width, height);
  66709. fillPath (p);
  66710. }
  66711. void Graphics::setPixel (int x, int y) const
  66712. {
  66713. context->fillRect (Rectangle<int> (x, y, 1, 1), false);
  66714. }
  66715. void Graphics::fillAll() const
  66716. {
  66717. fillRect (context->getClipBounds());
  66718. }
  66719. void Graphics::fillAll (const Colour& colourToUse) const
  66720. {
  66721. if (! colourToUse.isTransparent())
  66722. {
  66723. const Rectangle<int> clip (context->getClipBounds());
  66724. context->saveState();
  66725. context->setFill (colourToUse);
  66726. context->fillRect (clip, false);
  66727. context->restoreState();
  66728. }
  66729. }
  66730. void Graphics::fillPath (const Path& path, const AffineTransform& transform) const
  66731. {
  66732. if ((! context->isClipEmpty()) && ! path.isEmpty())
  66733. context->fillPath (path, transform);
  66734. }
  66735. void Graphics::strokePath (const Path& path,
  66736. const PathStrokeType& strokeType,
  66737. const AffineTransform& transform) const
  66738. {
  66739. Path stroke;
  66740. strokeType.createStrokedPath (stroke, path, transform);
  66741. fillPath (stroke);
  66742. }
  66743. void Graphics::drawRect (const int x, const int y, const int width, const int height,
  66744. const int lineThickness) const
  66745. {
  66746. // passing in a silly number can cause maths problems in rendering!
  66747. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66748. context->fillRect (Rectangle<int> (x, y, width, lineThickness), false);
  66749. context->fillRect (Rectangle<int> (x, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66750. context->fillRect (Rectangle<int> (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2), false);
  66751. context->fillRect (Rectangle<int> (x, y + height - lineThickness, width, lineThickness), false);
  66752. }
  66753. void Graphics::drawRect (const float x, const float y, const float width, const float height, const float lineThickness) const
  66754. {
  66755. // passing in a silly number can cause maths problems in rendering!
  66756. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66757. Path p;
  66758. p.addRectangle (x, y, width, lineThickness);
  66759. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66760. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  66761. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  66762. fillPath (p);
  66763. }
  66764. void Graphics::drawRect (const Rectangle<int>& r, const int lineThickness) const
  66765. {
  66766. drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight(), lineThickness);
  66767. }
  66768. void Graphics::drawBevel (const int x, const int y, const int width, const int height,
  66769. const int bevelThickness, const Colour& topLeftColour, const Colour& bottomRightColour,
  66770. const bool useGradient, const bool sharpEdgeOnOutside) const
  66771. {
  66772. // passing in a silly number can cause maths problems in rendering!
  66773. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66774. if (clipRegionIntersects (Rectangle<int> (x, y, width, height)))
  66775. {
  66776. context->saveState();
  66777. const float oldOpacity = 1.0f;//xxx state->colour.getFloatAlpha();
  66778. const float ramp = oldOpacity / bevelThickness;
  66779. for (int i = bevelThickness; --i >= 0;)
  66780. {
  66781. const float op = useGradient ? ramp * (sharpEdgeOnOutside ? bevelThickness - i : i)
  66782. : oldOpacity;
  66783. context->setFill (topLeftColour.withMultipliedAlpha (op));
  66784. context->fillRect (Rectangle<int> (x + i, y + i, width - i * 2, 1), false);
  66785. context->setFill (topLeftColour.withMultipliedAlpha (op * 0.75f));
  66786. context->fillRect (Rectangle<int> (x + i, y + i + 1, 1, height - i * 2 - 2), false);
  66787. context->setFill (bottomRightColour.withMultipliedAlpha (op));
  66788. context->fillRect (Rectangle<int> (x + i, y + height - i - 1, width - i * 2, 1), false);
  66789. context->setFill (bottomRightColour.withMultipliedAlpha (op * 0.75f));
  66790. context->fillRect (Rectangle<int> (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2), false);
  66791. }
  66792. context->restoreState();
  66793. }
  66794. }
  66795. void Graphics::fillEllipse (const float x, const float y, const float width, const float height) const
  66796. {
  66797. // passing in a silly number can cause maths problems in rendering!
  66798. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66799. Path p;
  66800. p.addEllipse (x, y, width, height);
  66801. fillPath (p);
  66802. }
  66803. void Graphics::drawEllipse (const float x, const float y, const float width, const float height,
  66804. const float lineThickness) const
  66805. {
  66806. // passing in a silly number can cause maths problems in rendering!
  66807. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66808. Path p;
  66809. p.addEllipse (x, y, width, height);
  66810. strokePath (p, PathStrokeType (lineThickness));
  66811. }
  66812. void Graphics::fillRoundedRectangle (const float x, const float y, const float width, const float height, const float cornerSize) const
  66813. {
  66814. // passing in a silly number can cause maths problems in rendering!
  66815. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66816. Path p;
  66817. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66818. fillPath (p);
  66819. }
  66820. void Graphics::fillRoundedRectangle (const Rectangle<float>& r, const float cornerSize) const
  66821. {
  66822. fillRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize);
  66823. }
  66824. void Graphics::drawRoundedRectangle (const float x, const float y, const float width, const float height,
  66825. const float cornerSize, const float lineThickness) const
  66826. {
  66827. // passing in a silly number can cause maths problems in rendering!
  66828. jassert (areCoordsSensibleNumbers (x, y, width, height));
  66829. Path p;
  66830. p.addRoundedRectangle (x, y, width, height, cornerSize);
  66831. strokePath (p, PathStrokeType (lineThickness));
  66832. }
  66833. void Graphics::drawRoundedRectangle (const Rectangle<float>& r, const float cornerSize, const float lineThickness) const
  66834. {
  66835. drawRoundedRectangle (r.getX(), r.getY(), r.getWidth(), r.getHeight(), cornerSize, lineThickness);
  66836. }
  66837. void Graphics::drawArrow (const Line<float>& line, const float lineThickness, const float arrowheadWidth, const float arrowheadLength) const
  66838. {
  66839. Path p;
  66840. p.addArrow (line, lineThickness, arrowheadWidth, arrowheadLength);
  66841. fillPath (p);
  66842. }
  66843. void Graphics::fillCheckerBoard (const Rectangle<int>& area,
  66844. const int checkWidth, const int checkHeight,
  66845. const Colour& colour1, const Colour& colour2) const
  66846. {
  66847. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  66848. if (checkWidth > 0 && checkHeight > 0)
  66849. {
  66850. context->saveState();
  66851. if (colour1 == colour2)
  66852. {
  66853. context->setFill (colour1);
  66854. context->fillRect (area, false);
  66855. }
  66856. else
  66857. {
  66858. const Rectangle<int> clipped (context->getClipBounds().getIntersection (area));
  66859. if (! clipped.isEmpty())
  66860. {
  66861. context->clipToRectangle (clipped);
  66862. const int checkNumX = (clipped.getX() - area.getX()) / checkWidth;
  66863. const int checkNumY = (clipped.getY() - area.getY()) / checkHeight;
  66864. const int startX = area.getX() + checkNumX * checkWidth;
  66865. const int startY = area.getY() + checkNumY * checkHeight;
  66866. const int right = clipped.getRight();
  66867. const int bottom = clipped.getBottom();
  66868. for (int i = 0; i < 2; ++i)
  66869. {
  66870. context->setFill (i == ((checkNumX ^ checkNumY) & 1) ? colour1 : colour2);
  66871. int cy = i;
  66872. for (int y = startY; y < bottom; y += checkHeight)
  66873. for (int x = startX + (cy++ & 1) * checkWidth; x < right; x += checkWidth * 2)
  66874. context->fillRect (Rectangle<int> (x, y, checkWidth, checkHeight), false);
  66875. }
  66876. }
  66877. }
  66878. context->restoreState();
  66879. }
  66880. }
  66881. void Graphics::drawVerticalLine (const int x, float top, float bottom) const
  66882. {
  66883. context->drawVerticalLine (x, top, bottom);
  66884. }
  66885. void Graphics::drawHorizontalLine (const int y, float left, float right) const
  66886. {
  66887. context->drawHorizontalLine (y, left, right);
  66888. }
  66889. void Graphics::drawLine (float x1, float y1, float x2, float y2) const
  66890. {
  66891. context->drawLine (Line<float> (x1, y1, x2, y2));
  66892. }
  66893. void Graphics::drawLine (const float startX, const float startY,
  66894. const float endX, const float endY,
  66895. const float lineThickness) const
  66896. {
  66897. drawLine (Line<float> (startX, startY, endX, endY),lineThickness);
  66898. }
  66899. void Graphics::drawLine (const Line<float>& line) const
  66900. {
  66901. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  66902. }
  66903. void Graphics::drawLine (const Line<float>& line, const float lineThickness) const
  66904. {
  66905. Path p;
  66906. p.addLineSegment (line, lineThickness);
  66907. fillPath (p);
  66908. }
  66909. void Graphics::drawDashedLine (const float startX, const float startY,
  66910. const float endX, const float endY,
  66911. const float* const dashLengths,
  66912. const int numDashLengths,
  66913. const float lineThickness) const
  66914. {
  66915. const double dx = endX - startX;
  66916. const double dy = endY - startY;
  66917. const double totalLen = juce_hypot (dx, dy);
  66918. if (totalLen >= 0.5)
  66919. {
  66920. const double onePixAlpha = 1.0 / totalLen;
  66921. double alpha = 0.0;
  66922. float x = startX;
  66923. float y = startY;
  66924. int n = 0;
  66925. while (alpha < 1.0f)
  66926. {
  66927. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  66928. n = n % numDashLengths;
  66929. const float oldX = x;
  66930. const float oldY = y;
  66931. x = (float) (startX + dx * alpha);
  66932. y = (float) (startY + dy * alpha);
  66933. if ((n & 1) != 0)
  66934. {
  66935. if (lineThickness != 1.0f)
  66936. drawLine (oldX, oldY, x, y, lineThickness);
  66937. else
  66938. drawLine (oldX, oldY, x, y);
  66939. }
  66940. }
  66941. }
  66942. }
  66943. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality)
  66944. {
  66945. saveStateIfPending();
  66946. context->setInterpolationQuality (newQuality);
  66947. }
  66948. void Graphics::drawImageAt (const Image& imageToDraw,
  66949. const int topLeftX, const int topLeftY,
  66950. const bool fillAlphaChannelWithCurrentBrush) const
  66951. {
  66952. const int imageW = imageToDraw.getWidth();
  66953. const int imageH = imageToDraw.getHeight();
  66954. drawImage (imageToDraw,
  66955. topLeftX, topLeftY, imageW, imageH,
  66956. 0, 0, imageW, imageH,
  66957. fillAlphaChannelWithCurrentBrush);
  66958. }
  66959. void Graphics::drawImageWithin (const Image& imageToDraw,
  66960. const int destX, const int destY,
  66961. const int destW, const int destH,
  66962. const RectanglePlacement& placementWithinTarget,
  66963. const bool fillAlphaChannelWithCurrentBrush) const
  66964. {
  66965. // passing in a silly number can cause maths problems in rendering!
  66966. jassert (areCoordsSensibleNumbers (destX, destY, destW, destH));
  66967. if (imageToDraw.isValid())
  66968. {
  66969. const int imageW = imageToDraw.getWidth();
  66970. const int imageH = imageToDraw.getHeight();
  66971. if (imageW > 0 && imageH > 0)
  66972. {
  66973. double newX = 0.0, newY = 0.0;
  66974. double newW = imageW;
  66975. double newH = imageH;
  66976. placementWithinTarget.applyTo (newX, newY, newW, newH,
  66977. destX, destY, destW, destH);
  66978. if (newW > 0 && newH > 0)
  66979. {
  66980. drawImage (imageToDraw,
  66981. roundToInt (newX), roundToInt (newY),
  66982. roundToInt (newW), roundToInt (newH),
  66983. 0, 0, imageW, imageH,
  66984. fillAlphaChannelWithCurrentBrush);
  66985. }
  66986. }
  66987. }
  66988. }
  66989. void Graphics::drawImage (const Image& imageToDraw,
  66990. int dx, int dy, int dw, int dh,
  66991. int sx, int sy, int sw, int sh,
  66992. const bool fillAlphaChannelWithCurrentBrush) const
  66993. {
  66994. // passing in a silly number can cause maths problems in rendering!
  66995. jassert (areCoordsSensibleNumbers (dx, dy, dw, dh));
  66996. jassert (areCoordsSensibleNumbers (sx, sy, sw, sh));
  66997. if (imageToDraw.isValid() && context->clipRegionIntersects (Rectangle<int> (dx, dy, dw, dh)))
  66998. {
  66999. drawImageTransformed (imageToDraw.getClippedImage (Rectangle<int> (sx, sy, sw, sh)),
  67000. AffineTransform::scale (dw / (float) sw, dh / (float) sh)
  67001. .translated ((float) dx, (float) dy),
  67002. fillAlphaChannelWithCurrentBrush);
  67003. }
  67004. }
  67005. void Graphics::drawImageTransformed (const Image& imageToDraw,
  67006. const AffineTransform& transform,
  67007. const bool fillAlphaChannelWithCurrentBrush) const
  67008. {
  67009. if (imageToDraw.isValid() && ! context->isClipEmpty())
  67010. {
  67011. if (fillAlphaChannelWithCurrentBrush)
  67012. {
  67013. context->saveState();
  67014. context->clipToImageAlpha (imageToDraw, transform);
  67015. fillAll();
  67016. context->restoreState();
  67017. }
  67018. else
  67019. {
  67020. context->drawImage (imageToDraw, transform, false);
  67021. }
  67022. }
  67023. }
  67024. END_JUCE_NAMESPACE
  67025. /*** End of inlined file: juce_Graphics.cpp ***/
  67026. /*** Start of inlined file: juce_Justification.cpp ***/
  67027. BEGIN_JUCE_NAMESPACE
  67028. Justification::Justification (const Justification& other) throw()
  67029. : flags (other.flags)
  67030. {
  67031. }
  67032. Justification& Justification::operator= (const Justification& other) throw()
  67033. {
  67034. flags = other.flags;
  67035. return *this;
  67036. }
  67037. int Justification::getOnlyVerticalFlags() const throw()
  67038. {
  67039. return flags & (top | bottom | verticallyCentred);
  67040. }
  67041. int Justification::getOnlyHorizontalFlags() const throw()
  67042. {
  67043. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  67044. }
  67045. void Justification::applyToRectangle (int& x, int& y,
  67046. const int w, const int h,
  67047. const int spaceX, const int spaceY,
  67048. const int spaceW, const int spaceH) const throw()
  67049. {
  67050. if ((flags & horizontallyCentred) != 0)
  67051. x = spaceX + ((spaceW - w) >> 1);
  67052. else if ((flags & right) != 0)
  67053. x = spaceX + spaceW - w;
  67054. else
  67055. x = spaceX;
  67056. if ((flags & verticallyCentred) != 0)
  67057. y = spaceY + ((spaceH - h) >> 1);
  67058. else if ((flags & bottom) != 0)
  67059. y = spaceY + spaceH - h;
  67060. else
  67061. y = spaceY;
  67062. }
  67063. END_JUCE_NAMESPACE
  67064. /*** End of inlined file: juce_Justification.cpp ***/
  67065. /*** Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67066. BEGIN_JUCE_NAMESPACE
  67067. // this will throw an assertion if you try to draw something that's not
  67068. // possible in postscript
  67069. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  67070. #if JUCE_DEBUG && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  67071. #define notPossibleInPostscriptAssert jassertfalse
  67072. #else
  67073. #define notPossibleInPostscriptAssert
  67074. #endif
  67075. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  67076. const String& documentTitle,
  67077. const int totalWidth_,
  67078. const int totalHeight_)
  67079. : out (resultingPostScript),
  67080. totalWidth (totalWidth_),
  67081. totalHeight (totalHeight_),
  67082. needToClip (true)
  67083. {
  67084. stateStack.add (new SavedState());
  67085. stateStack.getLast()->clip = Rectangle<int> (totalWidth_, totalHeight_);
  67086. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  67087. out << "%!PS-Adobe-3.0 EPSF-3.0"
  67088. "\n%%BoundingBox: 0 0 600 824"
  67089. "\n%%Pages: 0"
  67090. "\n%%Creator: Raw Material Software JUCE"
  67091. "\n%%Title: " << documentTitle <<
  67092. "\n%%CreationDate: none"
  67093. "\n%%LanguageLevel: 2"
  67094. "\n%%EndComments"
  67095. "\n%%BeginProlog"
  67096. "\n%%BeginResource: JRes"
  67097. "\n/bd {bind def} bind def"
  67098. "\n/c {setrgbcolor} bd"
  67099. "\n/m {moveto} bd"
  67100. "\n/l {lineto} bd"
  67101. "\n/rl {rlineto} bd"
  67102. "\n/ct {curveto} bd"
  67103. "\n/cp {closepath} bd"
  67104. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  67105. "\n/doclip {initclip newpath} bd"
  67106. "\n/endclip {clip newpath} bd"
  67107. "\n%%EndResource"
  67108. "\n%%EndProlog"
  67109. "\n%%BeginSetup"
  67110. "\n%%EndSetup"
  67111. "\n%%Page: 1 1"
  67112. "\n%%BeginPageSetup"
  67113. "\n%%EndPageSetup\n\n"
  67114. << "40 800 translate\n"
  67115. << scale << ' ' << scale << " scale\n\n";
  67116. }
  67117. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  67118. {
  67119. }
  67120. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  67121. {
  67122. return true;
  67123. }
  67124. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  67125. {
  67126. if (x != 0 || y != 0)
  67127. {
  67128. stateStack.getLast()->xOffset += x;
  67129. stateStack.getLast()->yOffset += y;
  67130. needToClip = true;
  67131. }
  67132. }
  67133. bool LowLevelGraphicsPostScriptRenderer::clipToRectangle (const Rectangle<int>& r)
  67134. {
  67135. needToClip = true;
  67136. return stateStack.getLast()->clip.clipTo (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67137. }
  67138. bool LowLevelGraphicsPostScriptRenderer::clipToRectangleList (const RectangleList& clipRegion)
  67139. {
  67140. needToClip = true;
  67141. return stateStack.getLast()->clip.clipTo (clipRegion);
  67142. }
  67143. void LowLevelGraphicsPostScriptRenderer::excludeClipRectangle (const Rectangle<int>& r)
  67144. {
  67145. needToClip = true;
  67146. stateStack.getLast()->clip.subtract (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67147. }
  67148. void LowLevelGraphicsPostScriptRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  67149. {
  67150. writeClip();
  67151. Path p (path);
  67152. p.applyTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67153. writePath (p);
  67154. out << "clip\n";
  67155. }
  67156. void LowLevelGraphicsPostScriptRenderer::clipToImageAlpha (const Image& /*sourceImage*/, const AffineTransform& /*transform*/)
  67157. {
  67158. needToClip = true;
  67159. jassertfalse; // xxx
  67160. }
  67161. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (const Rectangle<int>& r)
  67162. {
  67163. return stateStack.getLast()->clip.intersectsRectangle (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67164. }
  67165. const Rectangle<int> LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  67166. {
  67167. return stateStack.getLast()->clip.getBounds().translated (-stateStack.getLast()->xOffset,
  67168. -stateStack.getLast()->yOffset);
  67169. }
  67170. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  67171. {
  67172. return stateStack.getLast()->clip.isEmpty();
  67173. }
  67174. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState()
  67175. : xOffset (0),
  67176. yOffset (0)
  67177. {
  67178. }
  67179. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  67180. {
  67181. }
  67182. void LowLevelGraphicsPostScriptRenderer::saveState()
  67183. {
  67184. stateStack.add (new SavedState (*stateStack.getLast()));
  67185. }
  67186. void LowLevelGraphicsPostScriptRenderer::restoreState()
  67187. {
  67188. jassert (stateStack.size() > 0);
  67189. if (stateStack.size() > 0)
  67190. stateStack.removeLast();
  67191. }
  67192. void LowLevelGraphicsPostScriptRenderer::writeClip()
  67193. {
  67194. if (needToClip)
  67195. {
  67196. needToClip = false;
  67197. out << "doclip ";
  67198. int itemsOnLine = 0;
  67199. for (RectangleList::Iterator i (stateStack.getLast()->clip); i.next();)
  67200. {
  67201. if (++itemsOnLine == 6)
  67202. {
  67203. itemsOnLine = 0;
  67204. out << '\n';
  67205. }
  67206. const Rectangle<int>& r = *i.getRectangle();
  67207. out << r.getX() << ' ' << -r.getY() << ' '
  67208. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  67209. }
  67210. out << "endclip\n";
  67211. }
  67212. }
  67213. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  67214. {
  67215. Colour c (Colours::white.overlaidWith (colour));
  67216. if (lastColour != c)
  67217. {
  67218. lastColour = c;
  67219. out << String (c.getFloatRed(), 3) << ' '
  67220. << String (c.getFloatGreen(), 3) << ' '
  67221. << String (c.getFloatBlue(), 3) << " c\n";
  67222. }
  67223. }
  67224. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  67225. {
  67226. out << String (x, 2) << ' '
  67227. << String (-y, 2) << ' ';
  67228. }
  67229. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  67230. {
  67231. out << "newpath ";
  67232. float lastX = 0.0f;
  67233. float lastY = 0.0f;
  67234. int itemsOnLine = 0;
  67235. Path::Iterator i (path);
  67236. while (i.next())
  67237. {
  67238. if (++itemsOnLine == 4)
  67239. {
  67240. itemsOnLine = 0;
  67241. out << '\n';
  67242. }
  67243. switch (i.elementType)
  67244. {
  67245. case Path::Iterator::startNewSubPath:
  67246. writeXY (i.x1, i.y1);
  67247. lastX = i.x1;
  67248. lastY = i.y1;
  67249. out << "m ";
  67250. break;
  67251. case Path::Iterator::lineTo:
  67252. writeXY (i.x1, i.y1);
  67253. lastX = i.x1;
  67254. lastY = i.y1;
  67255. out << "l ";
  67256. break;
  67257. case Path::Iterator::quadraticTo:
  67258. {
  67259. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  67260. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  67261. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  67262. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  67263. writeXY (cp1x, cp1y);
  67264. writeXY (cp2x, cp2y);
  67265. writeXY (i.x2, i.y2);
  67266. out << "ct ";
  67267. lastX = i.x2;
  67268. lastY = i.y2;
  67269. }
  67270. break;
  67271. case Path::Iterator::cubicTo:
  67272. writeXY (i.x1, i.y1);
  67273. writeXY (i.x2, i.y2);
  67274. writeXY (i.x3, i.y3);
  67275. out << "ct ";
  67276. lastX = i.x3;
  67277. lastY = i.y3;
  67278. break;
  67279. case Path::Iterator::closePath:
  67280. out << "cp ";
  67281. break;
  67282. default:
  67283. jassertfalse;
  67284. break;
  67285. }
  67286. }
  67287. out << '\n';
  67288. }
  67289. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  67290. {
  67291. out << "[ "
  67292. << trans.mat00 << ' '
  67293. << trans.mat10 << ' '
  67294. << trans.mat01 << ' '
  67295. << trans.mat11 << ' '
  67296. << trans.mat02 << ' '
  67297. << trans.mat12 << " ] concat ";
  67298. }
  67299. void LowLevelGraphicsPostScriptRenderer::setFill (const FillType& fillType)
  67300. {
  67301. stateStack.getLast()->fillType = fillType;
  67302. }
  67303. void LowLevelGraphicsPostScriptRenderer::setOpacity (float /*opacity*/)
  67304. {
  67305. }
  67306. void LowLevelGraphicsPostScriptRenderer::setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  67307. {
  67308. }
  67309. void LowLevelGraphicsPostScriptRenderer::fillRect (const Rectangle<int>& r, const bool /*replaceExistingContents*/)
  67310. {
  67311. if (stateStack.getLast()->fillType.isColour())
  67312. {
  67313. writeClip();
  67314. writeColour (stateStack.getLast()->fillType.colour);
  67315. Rectangle<int> r2 (r.translated (stateStack.getLast()->xOffset, stateStack.getLast()->yOffset));
  67316. out << r2.getX() << ' ' << -r2.getBottom() << ' ' << r2.getWidth() << ' ' << r2.getHeight() << " rectfill\n";
  67317. }
  67318. else
  67319. {
  67320. Path p;
  67321. p.addRectangle (r);
  67322. fillPath (p, AffineTransform::identity);
  67323. }
  67324. }
  67325. void LowLevelGraphicsPostScriptRenderer::fillPath (const Path& path, const AffineTransform& t)
  67326. {
  67327. if (stateStack.getLast()->fillType.isColour())
  67328. {
  67329. writeClip();
  67330. Path p (path);
  67331. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset,
  67332. (float) stateStack.getLast()->yOffset));
  67333. writePath (p);
  67334. writeColour (stateStack.getLast()->fillType.colour);
  67335. out << "fill\n";
  67336. }
  67337. else if (stateStack.getLast()->fillType.isGradient())
  67338. {
  67339. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  67340. // postscript can't do semi-transparent ones.
  67341. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  67342. writeClip();
  67343. out << "gsave ";
  67344. {
  67345. Path p (path);
  67346. p.applyTransform (t.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset));
  67347. writePath (p);
  67348. out << "clip\n";
  67349. }
  67350. const Rectangle<int> bounds (stateStack.getLast()->clip.getBounds());
  67351. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  67352. // time-being, this just fills it with the average colour..
  67353. writeColour (stateStack.getLast()->fillType.gradient->getColourAtPosition (0.5f));
  67354. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  67355. out << "grestore\n";
  67356. }
  67357. }
  67358. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  67359. const int sx, const int sy,
  67360. const int maxW, const int maxH) const
  67361. {
  67362. out << "{<\n";
  67363. const int w = jmin (maxW, im.getWidth());
  67364. const int h = jmin (maxH, im.getHeight());
  67365. int charsOnLine = 0;
  67366. const Image::BitmapData srcData (im, 0, 0, w, h);
  67367. Colour pixel;
  67368. for (int y = h; --y >= 0;)
  67369. {
  67370. for (int x = 0; x < w; ++x)
  67371. {
  67372. const uint8* pixelData = srcData.getPixelPointer (x, y);
  67373. if (x >= sx && y >= sy)
  67374. {
  67375. if (im.isARGB())
  67376. {
  67377. PixelARGB p (*(const PixelARGB*) pixelData);
  67378. p.unpremultiply();
  67379. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  67380. }
  67381. else if (im.isRGB())
  67382. {
  67383. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  67384. }
  67385. else
  67386. {
  67387. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  67388. }
  67389. }
  67390. else
  67391. {
  67392. pixel = Colours::transparentWhite;
  67393. }
  67394. const uint8 pixelValues[3] = { pixel.getRed(), pixel.getGreen(), pixel.getBlue() };
  67395. out << String::toHexString (pixelValues, 3, 0);
  67396. charsOnLine += 3;
  67397. if (charsOnLine > 100)
  67398. {
  67399. out << '\n';
  67400. charsOnLine = 0;
  67401. }
  67402. }
  67403. }
  67404. out << "\n>}\n";
  67405. }
  67406. void LowLevelGraphicsPostScriptRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool /*fillEntireClipAsTiles*/)
  67407. {
  67408. const int w = sourceImage.getWidth();
  67409. const int h = sourceImage.getHeight();
  67410. writeClip();
  67411. out << "gsave ";
  67412. writeTransform (transform.translated ((float) stateStack.getLast()->xOffset, (float) stateStack.getLast()->yOffset)
  67413. .scaled (1.0f, -1.0f));
  67414. RectangleList imageClip;
  67415. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  67416. out << "newpath ";
  67417. int itemsOnLine = 0;
  67418. for (RectangleList::Iterator i (imageClip); i.next();)
  67419. {
  67420. if (++itemsOnLine == 6)
  67421. {
  67422. out << '\n';
  67423. itemsOnLine = 0;
  67424. }
  67425. const Rectangle<int>& r = *i.getRectangle();
  67426. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  67427. }
  67428. out << " clip newpath\n";
  67429. out << w << ' ' << h << " scale\n";
  67430. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  67431. writeImage (sourceImage, 0, 0, w, h);
  67432. out << "false 3 colorimage grestore\n";
  67433. needToClip = true;
  67434. }
  67435. void LowLevelGraphicsPostScriptRenderer::drawLine (const Line <float>& line)
  67436. {
  67437. Path p;
  67438. p.addLineSegment (line, 1.0f);
  67439. fillPath (p, AffineTransform::identity);
  67440. }
  67441. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, float top, float bottom)
  67442. {
  67443. drawLine (Line<float> ((float) x, top, (float) x, bottom));
  67444. }
  67445. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, float left, float right)
  67446. {
  67447. drawLine (Line<float> (left, (float) y, right, (float) y));
  67448. }
  67449. void LowLevelGraphicsPostScriptRenderer::setFont (const Font& newFont)
  67450. {
  67451. stateStack.getLast()->font = newFont;
  67452. }
  67453. const Font LowLevelGraphicsPostScriptRenderer::getFont()
  67454. {
  67455. return stateStack.getLast()->font;
  67456. }
  67457. void LowLevelGraphicsPostScriptRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  67458. {
  67459. Path p;
  67460. Font& font = stateStack.getLast()->font;
  67461. font.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  67462. fillPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight()).followedBy (transform));
  67463. }
  67464. END_JUCE_NAMESPACE
  67465. /*** End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp ***/
  67466. /*** Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  67467. BEGIN_JUCE_NAMESPACE
  67468. #if (JUCE_WINDOWS || JUCE_LINUX) && ! JUCE_64BIT
  67469. #define JUCE_USE_SSE_INSTRUCTIONS 1
  67470. #endif
  67471. #if JUCE_MSVC
  67472. #pragma warning (push)
  67473. #pragma warning (disable: 4127) // "expression is constant" warning
  67474. #if JUCE_DEBUG
  67475. #pragma optimize ("t", on) // optimise just this file, to avoid sluggish graphics when debugging
  67476. #pragma warning (disable: 4714) // warning about forcedinline methods not being inlined
  67477. #endif
  67478. #endif
  67479. namespace SoftwareRendererClasses
  67480. {
  67481. template <class PixelType, bool replaceExisting = false>
  67482. class SolidColourEdgeTableRenderer
  67483. {
  67484. public:
  67485. SolidColourEdgeTableRenderer (const Image::BitmapData& data_, const PixelARGB& colour)
  67486. : data (data_),
  67487. sourceColour (colour)
  67488. {
  67489. if (sizeof (PixelType) == 3)
  67490. {
  67491. areRGBComponentsEqual = sourceColour.getRed() == sourceColour.getGreen()
  67492. && sourceColour.getGreen() == sourceColour.getBlue();
  67493. filler[0].set (sourceColour);
  67494. filler[1].set (sourceColour);
  67495. filler[2].set (sourceColour);
  67496. filler[3].set (sourceColour);
  67497. }
  67498. }
  67499. forcedinline void setEdgeTableYPos (const int y) throw()
  67500. {
  67501. linePixels = (PixelType*) data.getLinePointer (y);
  67502. }
  67503. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67504. {
  67505. if (replaceExisting)
  67506. linePixels[x].set (sourceColour);
  67507. else
  67508. linePixels[x].blend (sourceColour, alphaLevel);
  67509. }
  67510. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67511. {
  67512. if (replaceExisting)
  67513. linePixels[x].set (sourceColour);
  67514. else
  67515. linePixels[x].blend (sourceColour);
  67516. }
  67517. forcedinline void handleEdgeTableLine (const int x, const int width, const int alphaLevel) const throw()
  67518. {
  67519. PixelARGB p (sourceColour);
  67520. p.multiplyAlpha (alphaLevel);
  67521. PixelType* dest = linePixels + x;
  67522. if (replaceExisting || p.getAlpha() >= 0xff)
  67523. replaceLine (dest, p, width);
  67524. else
  67525. blendLine (dest, p, width);
  67526. }
  67527. forcedinline void handleEdgeTableLineFull (const int x, const int width) const throw()
  67528. {
  67529. PixelType* dest = linePixels + x;
  67530. if (replaceExisting || sourceColour.getAlpha() >= 0xff)
  67531. replaceLine (dest, sourceColour, width);
  67532. else
  67533. blendLine (dest, sourceColour, width);
  67534. }
  67535. private:
  67536. const Image::BitmapData& data;
  67537. PixelType* linePixels;
  67538. PixelARGB sourceColour;
  67539. PixelRGB filler [4];
  67540. bool areRGBComponentsEqual;
  67541. inline void blendLine (PixelType* dest, const PixelARGB& colour, int width) const throw()
  67542. {
  67543. do
  67544. {
  67545. dest->blend (colour);
  67546. ++dest;
  67547. } while (--width > 0);
  67548. }
  67549. forcedinline void replaceLine (PixelRGB* dest, const PixelARGB& colour, int width) const throw()
  67550. {
  67551. if (areRGBComponentsEqual) // if all the component values are the same, we can cheat..
  67552. {
  67553. memset (dest, colour.getRed(), width * 3);
  67554. }
  67555. else
  67556. {
  67557. if (width >> 5)
  67558. {
  67559. const int* const intFiller = reinterpret_cast<const int*> (filler);
  67560. while (width > 8 && (((pointer_sized_int) dest) & 7) != 0)
  67561. {
  67562. dest->set (colour);
  67563. ++dest;
  67564. --width;
  67565. }
  67566. while (width > 4)
  67567. {
  67568. int* d = reinterpret_cast<int*> (dest);
  67569. *d++ = intFiller[0];
  67570. *d++ = intFiller[1];
  67571. *d++ = intFiller[2];
  67572. dest = reinterpret_cast<PixelRGB*> (d);
  67573. width -= 4;
  67574. }
  67575. }
  67576. while (--width >= 0)
  67577. {
  67578. dest->set (colour);
  67579. ++dest;
  67580. }
  67581. }
  67582. }
  67583. forcedinline void replaceLine (PixelAlpha* const dest, const PixelARGB& colour, int const width) const throw()
  67584. {
  67585. memset (dest, colour.getAlpha(), width);
  67586. }
  67587. forcedinline void replaceLine (PixelARGB* dest, const PixelARGB& colour, int width) const throw()
  67588. {
  67589. do
  67590. {
  67591. dest->set (colour);
  67592. ++dest;
  67593. } while (--width > 0);
  67594. }
  67595. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  67596. SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  67597. };
  67598. class LinearGradientPixelGenerator
  67599. {
  67600. public:
  67601. LinearGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform, const PixelARGB* const lookupTable_, const int numEntries_)
  67602. : lookupTable (lookupTable_), numEntries (numEntries_)
  67603. {
  67604. jassert (numEntries_ >= 0);
  67605. Point<float> p1 (gradient.point1);
  67606. Point<float> p2 (gradient.point2);
  67607. if (! transform.isIdentity())
  67608. {
  67609. const Line<float> l (p2, p1);
  67610. Point<float> p3 = l.getPointAlongLine (0.0f, 100.0f);
  67611. p1.applyTransform (transform);
  67612. p2.applyTransform (transform);
  67613. p3.applyTransform (transform);
  67614. p2 = Line<float> (p2, p3).findNearestPointTo (p1);
  67615. }
  67616. vertical = std::abs (p1.getX() - p2.getX()) < 0.001f;
  67617. horizontal = std::abs (p1.getY() - p2.getY()) < 0.001f;
  67618. if (vertical)
  67619. {
  67620. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getY() - p1.getY()));
  67621. start = roundToInt (p1.getY() * scale);
  67622. }
  67623. else if (horizontal)
  67624. {
  67625. scale = roundToInt ((numEntries << (int) numScaleBits) / (double) (p2.getX() - p1.getX()));
  67626. start = roundToInt (p1.getX() * scale);
  67627. }
  67628. else
  67629. {
  67630. grad = (p2.getY() - p1.getY()) / (double) (p1.getX() - p2.getX());
  67631. yTerm = p1.getY() - p1.getX() / grad;
  67632. scale = roundToInt ((numEntries << (int) numScaleBits) / (yTerm * grad - (p2.getY() * grad - p2.getX())));
  67633. grad *= scale;
  67634. }
  67635. }
  67636. forcedinline void setY (const int y) throw()
  67637. {
  67638. if (vertical)
  67639. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> (int) numScaleBits)];
  67640. else if (! horizontal)
  67641. start = roundToInt ((y - yTerm) * grad);
  67642. }
  67643. inline const PixelARGB getPixel (const int x) const throw()
  67644. {
  67645. return vertical ? linePix
  67646. : lookupTable [jlimit (0, numEntries, (x * scale - start) >> (int) numScaleBits)];
  67647. }
  67648. private:
  67649. const PixelARGB* const lookupTable;
  67650. const int numEntries;
  67651. PixelARGB linePix;
  67652. int start, scale;
  67653. double grad, yTerm;
  67654. bool vertical, horizontal;
  67655. enum { numScaleBits = 12 };
  67656. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  67657. LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  67658. };
  67659. class RadialGradientPixelGenerator
  67660. {
  67661. public:
  67662. RadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform&,
  67663. const PixelARGB* const lookupTable_, const int numEntries_)
  67664. : lookupTable (lookupTable_),
  67665. numEntries (numEntries_),
  67666. gx1 (gradient.point1.getX()),
  67667. gy1 (gradient.point1.getY())
  67668. {
  67669. jassert (numEntries_ >= 0);
  67670. const Point<float> diff (gradient.point1 - gradient.point2);
  67671. maxDist = diff.getX() * diff.getX() + diff.getY() * diff.getY();
  67672. invScale = numEntries / std::sqrt (maxDist);
  67673. jassert (roundToInt (std::sqrt (maxDist) * invScale) <= numEntries);
  67674. }
  67675. forcedinline void setY (const int y) throw()
  67676. {
  67677. dy = y - gy1;
  67678. dy *= dy;
  67679. }
  67680. inline const PixelARGB getPixel (const int px) const throw()
  67681. {
  67682. double x = px - gx1;
  67683. x *= x;
  67684. x += dy;
  67685. return lookupTable [x >= maxDist ? numEntries : roundToInt (std::sqrt (x) * invScale)];
  67686. }
  67687. protected:
  67688. const PixelARGB* const lookupTable;
  67689. const int numEntries;
  67690. const double gx1, gy1;
  67691. double maxDist, invScale, dy;
  67692. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  67693. RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  67694. };
  67695. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  67696. {
  67697. public:
  67698. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient, const AffineTransform& transform,
  67699. const PixelARGB* const lookupTable_, const int numEntries_)
  67700. : RadialGradientPixelGenerator (gradient, transform, lookupTable_, numEntries_),
  67701. inverseTransform (transform.inverted())
  67702. {
  67703. tM10 = inverseTransform.mat10;
  67704. tM00 = inverseTransform.mat00;
  67705. }
  67706. forcedinline void setY (const int y) throw()
  67707. {
  67708. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  67709. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  67710. }
  67711. inline const PixelARGB getPixel (const int px) const throw()
  67712. {
  67713. double x = px;
  67714. const double y = tM10 * x + lineYM11;
  67715. x = tM00 * x + lineYM01;
  67716. x *= x;
  67717. x += y * y;
  67718. if (x >= maxDist)
  67719. return lookupTable [numEntries];
  67720. else
  67721. return lookupTable [jmin (numEntries, roundToInt (std::sqrt (x) * invScale))];
  67722. }
  67723. private:
  67724. double tM10, tM00, lineYM01, lineYM11;
  67725. const AffineTransform inverseTransform;
  67726. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  67727. TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  67728. };
  67729. template <class PixelType, class GradientType>
  67730. class GradientEdgeTableRenderer : public GradientType
  67731. {
  67732. public:
  67733. GradientEdgeTableRenderer (const Image::BitmapData& destData_, const ColourGradient& gradient, const AffineTransform& transform,
  67734. const PixelARGB* const lookupTable_, const int numEntries_)
  67735. : GradientType (gradient, transform, lookupTable_, numEntries_ - 1),
  67736. destData (destData_)
  67737. {
  67738. }
  67739. forcedinline void setEdgeTableYPos (const int y) throw()
  67740. {
  67741. linePixels = (PixelType*) destData.getLinePointer (y);
  67742. GradientType::setY (y);
  67743. }
  67744. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  67745. {
  67746. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  67747. }
  67748. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67749. {
  67750. linePixels[x].blend (GradientType::getPixel (x));
  67751. }
  67752. void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  67753. {
  67754. PixelType* dest = linePixels + x;
  67755. if (alphaLevel < 0xff)
  67756. {
  67757. do
  67758. {
  67759. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  67760. } while (--width > 0);
  67761. }
  67762. else
  67763. {
  67764. do
  67765. {
  67766. (dest++)->blend (GradientType::getPixel (x++));
  67767. } while (--width > 0);
  67768. }
  67769. }
  67770. void handleEdgeTableLineFull (int x, int width) const throw()
  67771. {
  67772. PixelType* dest = linePixels + x;
  67773. do
  67774. {
  67775. (dest++)->blend (GradientType::getPixel (x++));
  67776. } while (--width > 0);
  67777. }
  67778. private:
  67779. const Image::BitmapData& destData;
  67780. PixelType* linePixels;
  67781. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  67782. GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  67783. };
  67784. namespace
  67785. {
  67786. forcedinline int safeModulo (int n, const int divisor) throw()
  67787. {
  67788. jassert (divisor > 0);
  67789. n %= divisor;
  67790. return (n < 0) ? (n + divisor) : n;
  67791. }
  67792. }
  67793. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67794. class ImageFillEdgeTableRenderer
  67795. {
  67796. public:
  67797. ImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67798. const Image::BitmapData& srcData_,
  67799. const int extraAlpha_,
  67800. const int x, const int y)
  67801. : destData (destData_),
  67802. srcData (srcData_),
  67803. extraAlpha (extraAlpha_ + 1),
  67804. xOffset (repeatPattern ? safeModulo (x, srcData_.width) - srcData_.width : x),
  67805. yOffset (repeatPattern ? safeModulo (y, srcData_.height) - srcData_.height : y)
  67806. {
  67807. }
  67808. forcedinline void setEdgeTableYPos (int y) throw()
  67809. {
  67810. linePixels = (DestPixelType*) destData.getLinePointer (y);
  67811. y -= yOffset;
  67812. if (repeatPattern)
  67813. {
  67814. jassert (y >= 0);
  67815. y %= srcData.height;
  67816. }
  67817. sourceLineStart = (SrcPixelType*) srcData.getLinePointer (y);
  67818. }
  67819. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  67820. {
  67821. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67822. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], alphaLevel);
  67823. }
  67824. forcedinline void handleEdgeTablePixelFull (const int x) const throw()
  67825. {
  67826. linePixels[x].blend (sourceLineStart [repeatPattern ? ((x - xOffset) % srcData.width) : (x - xOffset)], extraAlpha);
  67827. }
  67828. void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  67829. {
  67830. DestPixelType* dest = linePixels + x;
  67831. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  67832. x -= xOffset;
  67833. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67834. if (alphaLevel < 0xfe)
  67835. {
  67836. do
  67837. {
  67838. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], alphaLevel);
  67839. } while (--width > 0);
  67840. }
  67841. else
  67842. {
  67843. if (repeatPattern)
  67844. {
  67845. do
  67846. {
  67847. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67848. } while (--width > 0);
  67849. }
  67850. else
  67851. {
  67852. copyRow (dest, sourceLineStart + x, width);
  67853. }
  67854. }
  67855. }
  67856. void handleEdgeTableLineFull (int x, int width) const throw()
  67857. {
  67858. DestPixelType* dest = linePixels + x;
  67859. x -= xOffset;
  67860. jassert (repeatPattern || (x >= 0 && x + width <= srcData.width));
  67861. if (extraAlpha < 0xfe)
  67862. {
  67863. do
  67864. {
  67865. dest++ ->blend (sourceLineStart [repeatPattern ? (x++ % srcData.width) : x++], extraAlpha);
  67866. } while (--width > 0);
  67867. }
  67868. else
  67869. {
  67870. if (repeatPattern)
  67871. {
  67872. do
  67873. {
  67874. dest++ ->blend (sourceLineStart [x++ % srcData.width]);
  67875. } while (--width > 0);
  67876. }
  67877. else
  67878. {
  67879. copyRow (dest, sourceLineStart + x, width);
  67880. }
  67881. }
  67882. }
  67883. void clipEdgeTableLine (EdgeTable& et, int x, int y, int width)
  67884. {
  67885. jassert (x - xOffset >= 0 && x + width - xOffset <= srcData.width);
  67886. SrcPixelType* s = (SrcPixelType*) srcData.getLinePointer (y - yOffset);
  67887. uint8* mask = (uint8*) (s + x - xOffset);
  67888. if (sizeof (SrcPixelType) == sizeof (PixelARGB))
  67889. mask += PixelARGB::indexA;
  67890. et.clipLineToMask (x, y, mask, sizeof (SrcPixelType), width);
  67891. }
  67892. private:
  67893. const Image::BitmapData& destData;
  67894. const Image::BitmapData& srcData;
  67895. const int extraAlpha, xOffset, yOffset;
  67896. DestPixelType* linePixels;
  67897. SrcPixelType* sourceLineStart;
  67898. template <class PixelType1, class PixelType2>
  67899. forcedinline static void copyRow (PixelType1* dest, PixelType2* src, int width) throw()
  67900. {
  67901. do
  67902. {
  67903. dest++ ->blend (*src++);
  67904. } while (--width > 0);
  67905. }
  67906. forcedinline static void copyRow (PixelRGB* dest, PixelRGB* src, int width) throw()
  67907. {
  67908. memcpy (dest, src, width * sizeof (PixelRGB));
  67909. }
  67910. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  67911. ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  67912. };
  67913. template <class DestPixelType, class SrcPixelType, bool repeatPattern>
  67914. class TransformedImageFillEdgeTableRenderer
  67915. {
  67916. public:
  67917. TransformedImageFillEdgeTableRenderer (const Image::BitmapData& destData_,
  67918. const Image::BitmapData& srcData_,
  67919. const AffineTransform& transform,
  67920. const int extraAlpha_,
  67921. const bool betterQuality_)
  67922. : interpolator (transform),
  67923. destData (destData_),
  67924. srcData (srcData_),
  67925. extraAlpha (extraAlpha_ + 1),
  67926. betterQuality (betterQuality_),
  67927. pixelOffset (betterQuality_ ? 0.5f : 0.0f),
  67928. pixelOffsetInt (betterQuality_ ? -128 : 0),
  67929. maxX (srcData_.width - 1),
  67930. maxY (srcData_.height - 1),
  67931. scratchSize (2048)
  67932. {
  67933. scratchBuffer.malloc (scratchSize);
  67934. }
  67935. ~TransformedImageFillEdgeTableRenderer()
  67936. {
  67937. }
  67938. forcedinline void setEdgeTableYPos (const int newY) throw()
  67939. {
  67940. y = newY;
  67941. linePixels = (DestPixelType*) destData.getLinePointer (newY);
  67942. }
  67943. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) throw()
  67944. {
  67945. alphaLevel *= extraAlpha;
  67946. alphaLevel >>= 8;
  67947. SrcPixelType p;
  67948. generate (&p, x, 1);
  67949. linePixels[x].blend (p, alphaLevel);
  67950. }
  67951. forcedinline void handleEdgeTablePixelFull (const int x) throw()
  67952. {
  67953. SrcPixelType p;
  67954. generate (&p, x, 1);
  67955. linePixels[x].blend (p, extraAlpha);
  67956. }
  67957. void handleEdgeTableLine (const int x, int width, int alphaLevel) throw()
  67958. {
  67959. if (width > scratchSize)
  67960. {
  67961. scratchSize = width;
  67962. scratchBuffer.malloc (scratchSize);
  67963. }
  67964. SrcPixelType* span = scratchBuffer;
  67965. generate (span, x, width);
  67966. DestPixelType* dest = linePixels + x;
  67967. alphaLevel *= extraAlpha;
  67968. alphaLevel >>= 8;
  67969. if (alphaLevel < 0xfe)
  67970. {
  67971. do
  67972. {
  67973. dest++ ->blend (*span++, alphaLevel);
  67974. } while (--width > 0);
  67975. }
  67976. else
  67977. {
  67978. do
  67979. {
  67980. dest++ ->blend (*span++);
  67981. } while (--width > 0);
  67982. }
  67983. }
  67984. forcedinline void handleEdgeTableLineFull (const int x, int width) throw()
  67985. {
  67986. handleEdgeTableLine (x, width, 255);
  67987. }
  67988. void clipEdgeTableLine (EdgeTable& et, int x, int y_, int width)
  67989. {
  67990. if (width > scratchSize)
  67991. {
  67992. scratchSize = width;
  67993. scratchBuffer.malloc (scratchSize);
  67994. }
  67995. y = y_;
  67996. generate (scratchBuffer, x, width);
  67997. et.clipLineToMask (x, y_,
  67998. reinterpret_cast<uint8*> (scratchBuffer.getData()) + SrcPixelType::indexA,
  67999. sizeof (SrcPixelType), width);
  68000. }
  68001. private:
  68002. void generate (PixelARGB* dest, const int x, int numPixels) throw()
  68003. {
  68004. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68005. do
  68006. {
  68007. int hiResX, hiResY;
  68008. this->interpolator.next (hiResX, hiResY);
  68009. hiResX += pixelOffsetInt;
  68010. hiResY += pixelOffsetInt;
  68011. int loResX = hiResX >> 8;
  68012. int loResY = hiResY >> 8;
  68013. if (repeatPattern)
  68014. {
  68015. loResX = safeModulo (loResX, srcData.width);
  68016. loResY = safeModulo (loResY, srcData.height);
  68017. }
  68018. if (betterQuality
  68019. && ((unsigned int) loResX) < (unsigned int) maxX
  68020. && ((unsigned int) loResY) < (unsigned int) maxY)
  68021. {
  68022. uint32 c[4] = { 256 * 128, 256 * 128, 256 * 128, 256 * 128 };
  68023. hiResX &= 255;
  68024. hiResY &= 255;
  68025. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68026. uint32 weight = (256 - hiResX) * (256 - hiResY);
  68027. c[0] += weight * src[0];
  68028. c[1] += weight * src[1];
  68029. c[2] += weight * src[2];
  68030. c[3] += weight * src[3];
  68031. weight = hiResX * (256 - hiResY);
  68032. c[0] += weight * src[4];
  68033. c[1] += weight * src[5];
  68034. c[2] += weight * src[6];
  68035. c[3] += weight * src[7];
  68036. src += this->srcData.lineStride;
  68037. weight = (256 - hiResX) * hiResY;
  68038. c[0] += weight * src[0];
  68039. c[1] += weight * src[1];
  68040. c[2] += weight * src[2];
  68041. c[3] += weight * src[3];
  68042. weight = hiResX * hiResY;
  68043. c[0] += weight * src[4];
  68044. c[1] += weight * src[5];
  68045. c[2] += weight * src[6];
  68046. c[3] += weight * src[7];
  68047. dest->setARGB ((uint8) (c[PixelARGB::indexA] >> 16),
  68048. (uint8) (c[PixelARGB::indexR] >> 16),
  68049. (uint8) (c[PixelARGB::indexG] >> 16),
  68050. (uint8) (c[PixelARGB::indexB] >> 16));
  68051. }
  68052. else
  68053. {
  68054. if (! repeatPattern)
  68055. {
  68056. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68057. if (loResX < 0) loResX = 0;
  68058. if (loResY < 0) loResY = 0;
  68059. if (loResX > maxX) loResX = maxX;
  68060. if (loResY > maxY) loResY = maxY;
  68061. }
  68062. dest->set (*(const PixelARGB*) this->srcData.getPixelPointer (loResX, loResY));
  68063. }
  68064. ++dest;
  68065. } while (--numPixels > 0);
  68066. }
  68067. void generate (PixelRGB* dest, const int x, int numPixels) throw()
  68068. {
  68069. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68070. do
  68071. {
  68072. int hiResX, hiResY;
  68073. this->interpolator.next (hiResX, hiResY);
  68074. hiResX += pixelOffsetInt;
  68075. hiResY += pixelOffsetInt;
  68076. int loResX = hiResX >> 8;
  68077. int loResY = hiResY >> 8;
  68078. if (repeatPattern)
  68079. {
  68080. loResX = safeModulo (loResX, srcData.width);
  68081. loResY = safeModulo (loResY, srcData.height);
  68082. }
  68083. if (betterQuality
  68084. && ((unsigned int) loResX) < (unsigned int) maxX
  68085. && ((unsigned int) loResY) < (unsigned int) maxY)
  68086. {
  68087. uint32 c[3] = { 256 * 128, 256 * 128, 256 * 128 };
  68088. hiResX &= 255;
  68089. hiResY &= 255;
  68090. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68091. unsigned int weight = (256 - hiResX) * (256 - hiResY);
  68092. c[0] += weight * src[0];
  68093. c[1] += weight * src[1];
  68094. c[2] += weight * src[2];
  68095. weight = hiResX * (256 - hiResY);
  68096. c[0] += weight * src[3];
  68097. c[1] += weight * src[4];
  68098. c[2] += weight * src[5];
  68099. src += this->srcData.lineStride;
  68100. weight = (256 - hiResX) * hiResY;
  68101. c[0] += weight * src[0];
  68102. c[1] += weight * src[1];
  68103. c[2] += weight * src[2];
  68104. weight = hiResX * hiResY;
  68105. c[0] += weight * src[3];
  68106. c[1] += weight * src[4];
  68107. c[2] += weight * src[5];
  68108. dest->setARGB ((uint8) 255,
  68109. (uint8) (c[PixelRGB::indexR] >> 16),
  68110. (uint8) (c[PixelRGB::indexG] >> 16),
  68111. (uint8) (c[PixelRGB::indexB] >> 16));
  68112. }
  68113. else
  68114. {
  68115. if (! repeatPattern)
  68116. {
  68117. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68118. if (loResX < 0) loResX = 0;
  68119. if (loResY < 0) loResY = 0;
  68120. if (loResX > maxX) loResX = maxX;
  68121. if (loResY > maxY) loResY = maxY;
  68122. }
  68123. dest->set (*(const PixelRGB*) this->srcData.getPixelPointer (loResX, loResY));
  68124. }
  68125. ++dest;
  68126. } while (--numPixels > 0);
  68127. }
  68128. void generate (PixelAlpha* dest, const int x, int numPixels) throw()
  68129. {
  68130. this->interpolator.setStartOfLine (x + pixelOffset, y + pixelOffset, numPixels);
  68131. do
  68132. {
  68133. int hiResX, hiResY;
  68134. this->interpolator.next (hiResX, hiResY);
  68135. hiResX += pixelOffsetInt;
  68136. hiResY += pixelOffsetInt;
  68137. int loResX = hiResX >> 8;
  68138. int loResY = hiResY >> 8;
  68139. if (repeatPattern)
  68140. {
  68141. loResX = safeModulo (loResX, srcData.width);
  68142. loResY = safeModulo (loResY, srcData.height);
  68143. }
  68144. if (betterQuality
  68145. && ((unsigned int) loResX) < (unsigned int) maxX
  68146. && ((unsigned int) loResY) < (unsigned int) maxY)
  68147. {
  68148. hiResX &= 255;
  68149. hiResY &= 255;
  68150. const uint8* src = this->srcData.getPixelPointer (loResX, loResY);
  68151. uint32 c = 256 * 128;
  68152. c += src[0] * ((256 - hiResX) * (256 - hiResY));
  68153. c += src[1] * (hiResX * (256 - hiResY));
  68154. src += this->srcData.lineStride;
  68155. c += src[0] * ((256 - hiResX) * hiResY);
  68156. c += src[1] * (hiResX * hiResY);
  68157. *((uint8*) dest) = (uint8) c;
  68158. }
  68159. else
  68160. {
  68161. if (! repeatPattern)
  68162. {
  68163. // Beyond the edges, just repeat the edge pixels and leave the anti-aliasing to be handled by the edgetable
  68164. if (loResX < 0) loResX = 0;
  68165. if (loResY < 0) loResY = 0;
  68166. if (loResX > maxX) loResX = maxX;
  68167. if (loResY > maxY) loResY = maxY;
  68168. }
  68169. *((uint8*) dest) = *(this->srcData.getPixelPointer (loResX, loResY));
  68170. }
  68171. ++dest;
  68172. } while (--numPixels > 0);
  68173. }
  68174. class TransformedImageSpanInterpolator
  68175. {
  68176. public:
  68177. TransformedImageSpanInterpolator (const AffineTransform& transform) throw()
  68178. : inverseTransform (transform.inverted())
  68179. {}
  68180. void setStartOfLine (float x, float y, const int numPixels) throw()
  68181. {
  68182. float x1 = x, y1 = y;
  68183. x += numPixels;
  68184. inverseTransform.transformPoints (x1, y1, x, y);
  68185. xBresenham.set ((int) (x1 * 256.0f), (int) (x * 256.0f), numPixels);
  68186. yBresenham.set ((int) (y1 * 256.0f), (int) (y * 256.0f), numPixels);
  68187. }
  68188. void next (int& x, int& y) throw()
  68189. {
  68190. x = xBresenham.n;
  68191. xBresenham.stepToNext();
  68192. y = yBresenham.n;
  68193. yBresenham.stepToNext();
  68194. }
  68195. private:
  68196. class BresenhamInterpolator
  68197. {
  68198. public:
  68199. BresenhamInterpolator() throw() {}
  68200. void set (const int n1, const int n2, const int numSteps_) throw()
  68201. {
  68202. numSteps = jmax (1, numSteps_);
  68203. step = (n2 - n1) / numSteps;
  68204. remainder = modulo = (n2 - n1) % numSteps;
  68205. n = n1;
  68206. if (modulo <= 0)
  68207. {
  68208. modulo += numSteps;
  68209. remainder += numSteps;
  68210. --step;
  68211. }
  68212. modulo -= numSteps;
  68213. }
  68214. forcedinline void stepToNext() throw()
  68215. {
  68216. modulo += remainder;
  68217. n += step;
  68218. if (modulo > 0)
  68219. {
  68220. modulo -= numSteps;
  68221. ++n;
  68222. }
  68223. }
  68224. int n;
  68225. private:
  68226. int numSteps, step, modulo, remainder;
  68227. };
  68228. const AffineTransform inverseTransform;
  68229. BresenhamInterpolator xBresenham, yBresenham;
  68230. TransformedImageSpanInterpolator (const TransformedImageSpanInterpolator&);
  68231. TransformedImageSpanInterpolator& operator= (const TransformedImageSpanInterpolator&);
  68232. };
  68233. TransformedImageSpanInterpolator interpolator;
  68234. const Image::BitmapData& destData;
  68235. const Image::BitmapData& srcData;
  68236. const int extraAlpha;
  68237. const bool betterQuality;
  68238. const float pixelOffset;
  68239. const int pixelOffsetInt, maxX, maxY;
  68240. int y;
  68241. DestPixelType* linePixels;
  68242. HeapBlock <SrcPixelType> scratchBuffer;
  68243. int scratchSize;
  68244. TransformedImageFillEdgeTableRenderer (const TransformedImageFillEdgeTableRenderer&);
  68245. TransformedImageFillEdgeTableRenderer& operator= (const TransformedImageFillEdgeTableRenderer&);
  68246. };
  68247. class ClipRegionBase : public ReferenceCountedObject
  68248. {
  68249. public:
  68250. ClipRegionBase() {}
  68251. virtual ~ClipRegionBase() {}
  68252. typedef ReferenceCountedObjectPtr<ClipRegionBase> Ptr;
  68253. virtual const Ptr clone() const = 0;
  68254. virtual const Ptr applyClipTo (const Ptr& target) const = 0;
  68255. virtual const Ptr clipToRectangle (const Rectangle<int>& r) = 0;
  68256. virtual const Ptr clipToRectangleList (const RectangleList& r) = 0;
  68257. virtual const Ptr excludeClipRectangle (const Rectangle<int>& r) = 0;
  68258. virtual const Ptr clipToPath (const Path& p, const AffineTransform& transform) = 0;
  68259. virtual const Ptr clipToEdgeTable (const EdgeTable& et) = 0;
  68260. virtual const Ptr clipToImageAlpha (const Image& image, const AffineTransform& t, const bool betterQuality) = 0;
  68261. virtual bool clipRegionIntersects (const Rectangle<int>& r) const = 0;
  68262. virtual const Rectangle<int> getClipBounds() const = 0;
  68263. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const = 0;
  68264. virtual void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const = 0;
  68265. virtual void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const = 0;
  68266. virtual void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const = 0;
  68267. virtual void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& t, bool betterQuality, bool tiledFill) const = 0;
  68268. virtual void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const = 0;
  68269. protected:
  68270. template <class Iterator>
  68271. static void renderImageTransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData,
  68272. const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill)
  68273. {
  68274. switch (destData.pixelFormat)
  68275. {
  68276. case Image::ARGB:
  68277. switch (srcData.pixelFormat)
  68278. {
  68279. case Image::ARGB:
  68280. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68281. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68282. break;
  68283. case Image::RGB:
  68284. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68285. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68286. break;
  68287. default:
  68288. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68289. else { TransformedImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68290. break;
  68291. }
  68292. break;
  68293. case Image::RGB:
  68294. switch (srcData.pixelFormat)
  68295. {
  68296. case Image::ARGB:
  68297. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68298. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68299. break;
  68300. case Image::RGB:
  68301. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68302. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68303. break;
  68304. default:
  68305. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68306. else { TransformedImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68307. break;
  68308. }
  68309. break;
  68310. default:
  68311. switch (srcData.pixelFormat)
  68312. {
  68313. case Image::ARGB:
  68314. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68315. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68316. break;
  68317. case Image::RGB:
  68318. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68319. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68320. break;
  68321. default:
  68322. if (tiledFill) { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68323. else { TransformedImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, transform, alpha, betterQuality); iter.iterate (r); }
  68324. break;
  68325. }
  68326. break;
  68327. }
  68328. }
  68329. template <class Iterator>
  68330. static void renderImageUntransformedInternal (Iterator& iter, const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill)
  68331. {
  68332. switch (destData.pixelFormat)
  68333. {
  68334. case Image::ARGB:
  68335. switch (srcData.pixelFormat)
  68336. {
  68337. case Image::ARGB:
  68338. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68339. else { ImageFillEdgeTableRenderer <PixelARGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68340. break;
  68341. case Image::RGB:
  68342. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68343. else { ImageFillEdgeTableRenderer <PixelARGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68344. break;
  68345. default:
  68346. if (tiledFill) { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68347. else { ImageFillEdgeTableRenderer <PixelARGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68348. break;
  68349. }
  68350. break;
  68351. case Image::RGB:
  68352. switch (srcData.pixelFormat)
  68353. {
  68354. case Image::ARGB:
  68355. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68356. else { ImageFillEdgeTableRenderer <PixelRGB, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68357. break;
  68358. case Image::RGB:
  68359. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68360. else { ImageFillEdgeTableRenderer <PixelRGB, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68361. break;
  68362. default:
  68363. if (tiledFill) { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68364. else { ImageFillEdgeTableRenderer <PixelRGB, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68365. break;
  68366. }
  68367. break;
  68368. default:
  68369. switch (srcData.pixelFormat)
  68370. {
  68371. case Image::ARGB:
  68372. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68373. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelARGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68374. break;
  68375. case Image::RGB:
  68376. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68377. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelRGB, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68378. break;
  68379. default:
  68380. if (tiledFill) { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, true> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68381. else { ImageFillEdgeTableRenderer <PixelAlpha, PixelAlpha, false> r (destData, srcData, alpha, x, y); iter.iterate (r); }
  68382. break;
  68383. }
  68384. break;
  68385. }
  68386. }
  68387. template <class Iterator, class DestPixelType>
  68388. static void renderSolidFill (Iterator& iter, const Image::BitmapData& destData, const PixelARGB& fillColour, const bool replaceContents, DestPixelType*)
  68389. {
  68390. jassert (destData.pixelStride == sizeof (DestPixelType));
  68391. if (replaceContents)
  68392. {
  68393. SolidColourEdgeTableRenderer <DestPixelType, true> r (destData, fillColour);
  68394. iter.iterate (r);
  68395. }
  68396. else
  68397. {
  68398. SolidColourEdgeTableRenderer <DestPixelType, false> r (destData, fillColour);
  68399. iter.iterate (r);
  68400. }
  68401. }
  68402. template <class Iterator, class DestPixelType>
  68403. static void renderGradient (Iterator& iter, const Image::BitmapData& destData, const ColourGradient& g, const AffineTransform& transform,
  68404. const PixelARGB* const lookupTable, const int numLookupEntries, const bool isIdentity, DestPixelType*)
  68405. {
  68406. jassert (destData.pixelStride == sizeof (DestPixelType));
  68407. if (g.isRadial)
  68408. {
  68409. if (isIdentity)
  68410. {
  68411. GradientEdgeTableRenderer <DestPixelType, RadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68412. iter.iterate (renderer);
  68413. }
  68414. else
  68415. {
  68416. GradientEdgeTableRenderer <DestPixelType, TransformedRadialGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68417. iter.iterate (renderer);
  68418. }
  68419. }
  68420. else
  68421. {
  68422. GradientEdgeTableRenderer <DestPixelType, LinearGradientPixelGenerator> renderer (destData, g, transform, lookupTable, numLookupEntries);
  68423. iter.iterate (renderer);
  68424. }
  68425. }
  68426. };
  68427. class ClipRegion_EdgeTable : public ClipRegionBase
  68428. {
  68429. public:
  68430. ClipRegion_EdgeTable (const EdgeTable& e) : edgeTable (e) {}
  68431. ClipRegion_EdgeTable (const Rectangle<int>& r) : edgeTable (r) {}
  68432. ClipRegion_EdgeTable (const Rectangle<float>& r) : edgeTable (r) {}
  68433. ClipRegion_EdgeTable (const RectangleList& r) : edgeTable (r) {}
  68434. ClipRegion_EdgeTable (const Rectangle<int>& bounds, const Path& p, const AffineTransform& t) : edgeTable (bounds, p, t) {}
  68435. ClipRegion_EdgeTable (const ClipRegion_EdgeTable& other) : edgeTable (other.edgeTable) {}
  68436. ~ClipRegion_EdgeTable() {}
  68437. const Ptr clone() const
  68438. {
  68439. return new ClipRegion_EdgeTable (*this);
  68440. }
  68441. const Ptr applyClipTo (const Ptr& target) const
  68442. {
  68443. return target->clipToEdgeTable (edgeTable);
  68444. }
  68445. const Ptr clipToRectangle (const Rectangle<int>& r)
  68446. {
  68447. edgeTable.clipToRectangle (r);
  68448. return edgeTable.isEmpty() ? 0 : this;
  68449. }
  68450. const Ptr clipToRectangleList (const RectangleList& r)
  68451. {
  68452. RectangleList inverse (edgeTable.getMaximumBounds());
  68453. if (inverse.subtract (r))
  68454. for (RectangleList::Iterator iter (inverse); iter.next();)
  68455. edgeTable.excludeRectangle (*iter.getRectangle());
  68456. return edgeTable.isEmpty() ? 0 : this;
  68457. }
  68458. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68459. {
  68460. edgeTable.excludeRectangle (r);
  68461. return edgeTable.isEmpty() ? 0 : this;
  68462. }
  68463. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68464. {
  68465. EdgeTable et (edgeTable.getMaximumBounds(), p, transform);
  68466. edgeTable.clipToEdgeTable (et);
  68467. return edgeTable.isEmpty() ? 0 : this;
  68468. }
  68469. const Ptr clipToEdgeTable (const EdgeTable& et)
  68470. {
  68471. edgeTable.clipToEdgeTable (et);
  68472. return edgeTable.isEmpty() ? 0 : this;
  68473. }
  68474. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68475. {
  68476. const Image::BitmapData srcData (image, false);
  68477. if (transform.isOnlyTranslation())
  68478. {
  68479. // If our translation doesn't involve any distortion, just use a simple blit..
  68480. const int tx = (int) (transform.getTranslationX() * 256.0f);
  68481. const int ty = (int) (transform.getTranslationY() * 256.0f);
  68482. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  68483. {
  68484. const int imageX = ((tx + 128) >> 8);
  68485. const int imageY = ((ty + 128) >> 8);
  68486. if (image.getFormat() == Image::ARGB)
  68487. straightClipImage (srcData, imageX, imageY, (PixelARGB*) 0);
  68488. else
  68489. straightClipImage (srcData, imageX, imageY, (PixelAlpha*) 0);
  68490. return edgeTable.isEmpty() ? 0 : this;
  68491. }
  68492. }
  68493. if (transform.isSingularity())
  68494. return 0;
  68495. {
  68496. Path p;
  68497. p.addRectangle (0, 0, (float) srcData.width, (float) srcData.height);
  68498. EdgeTable et2 (edgeTable.getMaximumBounds(), p, transform);
  68499. edgeTable.clipToEdgeTable (et2);
  68500. }
  68501. if (! edgeTable.isEmpty())
  68502. {
  68503. if (image.getFormat() == Image::ARGB)
  68504. transformedClipImage (srcData, transform, betterQuality, (PixelARGB*) 0);
  68505. else
  68506. transformedClipImage (srcData, transform, betterQuality, (PixelAlpha*) 0);
  68507. }
  68508. return edgeTable.isEmpty() ? 0 : this;
  68509. }
  68510. bool clipRegionIntersects (const Rectangle<int>& r) const
  68511. {
  68512. return edgeTable.getMaximumBounds().intersects (r);
  68513. }
  68514. const Rectangle<int> getClipBounds() const
  68515. {
  68516. return edgeTable.getMaximumBounds();
  68517. }
  68518. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68519. {
  68520. const Rectangle<int> totalClip (edgeTable.getMaximumBounds());
  68521. const Rectangle<int> clipped (totalClip.getIntersection (area));
  68522. if (! clipped.isEmpty())
  68523. {
  68524. ClipRegion_EdgeTable et (clipped);
  68525. et.edgeTable.clipToEdgeTable (edgeTable);
  68526. et.fillAllWithColour (destData, colour, replaceContents);
  68527. }
  68528. }
  68529. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68530. {
  68531. const Rectangle<float> totalClip (edgeTable.getMaximumBounds().toFloat());
  68532. const Rectangle<float> clipped (totalClip.getIntersection (area));
  68533. if (! clipped.isEmpty())
  68534. {
  68535. ClipRegion_EdgeTable et (clipped);
  68536. et.edgeTable.clipToEdgeTable (edgeTable);
  68537. et.fillAllWithColour (destData, colour, false);
  68538. }
  68539. }
  68540. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68541. {
  68542. switch (destData.pixelFormat)
  68543. {
  68544. case Image::ARGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68545. case Image::RGB: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68546. default: renderSolidFill (edgeTable, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68547. }
  68548. }
  68549. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68550. {
  68551. HeapBlock <PixelARGB> lookupTable;
  68552. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68553. jassert (numLookupEntries > 0);
  68554. switch (destData.pixelFormat)
  68555. {
  68556. case Image::ARGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68557. case Image::RGB: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68558. default: renderGradient (edgeTable, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68559. }
  68560. }
  68561. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68562. {
  68563. renderImageTransformedInternal (edgeTable, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68564. }
  68565. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68566. {
  68567. renderImageUntransformedInternal (edgeTable, destData, srcData, alpha, x, y, tiledFill);
  68568. }
  68569. EdgeTable edgeTable;
  68570. private:
  68571. template <class SrcPixelType>
  68572. void transformedClipImage (const Image::BitmapData& srcData, const AffineTransform& transform, const bool betterQuality, const SrcPixelType*)
  68573. {
  68574. TransformedImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, transform, 255, betterQuality);
  68575. for (int y = 0; y < edgeTable.getMaximumBounds().getHeight(); ++y)
  68576. renderer.clipEdgeTableLine (edgeTable, edgeTable.getMaximumBounds().getX(), y + edgeTable.getMaximumBounds().getY(),
  68577. edgeTable.getMaximumBounds().getWidth());
  68578. }
  68579. template <class SrcPixelType>
  68580. void straightClipImage (const Image::BitmapData& srcData, int imageX, int imageY, const SrcPixelType*)
  68581. {
  68582. Rectangle<int> r (imageX, imageY, srcData.width, srcData.height);
  68583. edgeTable.clipToRectangle (r);
  68584. ImageFillEdgeTableRenderer <SrcPixelType, SrcPixelType, false> renderer (srcData, srcData, 255, imageX, imageY);
  68585. for (int y = 0; y < r.getHeight(); ++y)
  68586. renderer.clipEdgeTableLine (edgeTable, r.getX(), y + r.getY(), r.getWidth());
  68587. }
  68588. ClipRegion_EdgeTable& operator= (const ClipRegion_EdgeTable&);
  68589. };
  68590. class ClipRegion_RectangleList : public ClipRegionBase
  68591. {
  68592. public:
  68593. ClipRegion_RectangleList (const Rectangle<int>& r) : clip (r) {}
  68594. ClipRegion_RectangleList (const RectangleList& r) : clip (r) {}
  68595. ClipRegion_RectangleList (const ClipRegion_RectangleList& other) : clip (other.clip) {}
  68596. ~ClipRegion_RectangleList() {}
  68597. const Ptr clone() const
  68598. {
  68599. return new ClipRegion_RectangleList (*this);
  68600. }
  68601. const Ptr applyClipTo (const Ptr& target) const
  68602. {
  68603. return target->clipToRectangleList (clip);
  68604. }
  68605. const Ptr clipToRectangle (const Rectangle<int>& r)
  68606. {
  68607. clip.clipTo (r);
  68608. return clip.isEmpty() ? 0 : this;
  68609. }
  68610. const Ptr clipToRectangleList (const RectangleList& r)
  68611. {
  68612. clip.clipTo (r);
  68613. return clip.isEmpty() ? 0 : this;
  68614. }
  68615. const Ptr excludeClipRectangle (const Rectangle<int>& r)
  68616. {
  68617. clip.subtract (r);
  68618. return clip.isEmpty() ? 0 : this;
  68619. }
  68620. const Ptr clipToPath (const Path& p, const AffineTransform& transform)
  68621. {
  68622. return Ptr (new ClipRegion_EdgeTable (clip))->clipToPath (p, transform);
  68623. }
  68624. const Ptr clipToEdgeTable (const EdgeTable& et)
  68625. {
  68626. return Ptr (new ClipRegion_EdgeTable (clip))->clipToEdgeTable (et);
  68627. }
  68628. const Ptr clipToImageAlpha (const Image& image, const AffineTransform& transform, const bool betterQuality)
  68629. {
  68630. return Ptr (new ClipRegion_EdgeTable (clip))->clipToImageAlpha (image, transform, betterQuality);
  68631. }
  68632. bool clipRegionIntersects (const Rectangle<int>& r) const
  68633. {
  68634. return clip.intersects (r);
  68635. }
  68636. const Rectangle<int> getClipBounds() const
  68637. {
  68638. return clip.getBounds();
  68639. }
  68640. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<int>& area, const PixelARGB& colour, bool replaceContents) const
  68641. {
  68642. SubRectangleIterator iter (clip, area);
  68643. switch (destData.pixelFormat)
  68644. {
  68645. case Image::ARGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68646. case Image::RGB: renderSolidFill (iter, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68647. default: renderSolidFill (iter, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68648. }
  68649. }
  68650. void fillRectWithColour (Image::BitmapData& destData, const Rectangle<float>& area, const PixelARGB& colour) const
  68651. {
  68652. SubRectangleIteratorFloat iter (clip, area);
  68653. switch (destData.pixelFormat)
  68654. {
  68655. case Image::ARGB: renderSolidFill (iter, destData, colour, false, (PixelARGB*) 0); break;
  68656. case Image::RGB: renderSolidFill (iter, destData, colour, false, (PixelRGB*) 0); break;
  68657. default: renderSolidFill (iter, destData, colour, false, (PixelAlpha*) 0); break;
  68658. }
  68659. }
  68660. void fillAllWithColour (Image::BitmapData& destData, const PixelARGB& colour, bool replaceContents) const
  68661. {
  68662. switch (destData.pixelFormat)
  68663. {
  68664. case Image::ARGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelARGB*) 0); break;
  68665. case Image::RGB: renderSolidFill (*this, destData, colour, replaceContents, (PixelRGB*) 0); break;
  68666. default: renderSolidFill (*this, destData, colour, replaceContents, (PixelAlpha*) 0); break;
  68667. }
  68668. }
  68669. void fillAllWithGradient (Image::BitmapData& destData, ColourGradient& gradient, const AffineTransform& transform, bool isIdentity) const
  68670. {
  68671. HeapBlock <PixelARGB> lookupTable;
  68672. const int numLookupEntries = gradient.createLookupTable (transform, lookupTable);
  68673. jassert (numLookupEntries > 0);
  68674. switch (destData.pixelFormat)
  68675. {
  68676. case Image::ARGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelARGB*) 0); break;
  68677. case Image::RGB: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelRGB*) 0); break;
  68678. default: renderGradient (*this, destData, gradient, transform, lookupTable, numLookupEntries, isIdentity, (PixelAlpha*) 0); break;
  68679. }
  68680. }
  68681. void renderImageTransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, const AffineTransform& transform, bool betterQuality, bool tiledFill) const
  68682. {
  68683. renderImageTransformedInternal (*this, destData, srcData, alpha, transform, betterQuality, tiledFill);
  68684. }
  68685. void renderImageUntransformed (const Image::BitmapData& destData, const Image::BitmapData& srcData, const int alpha, int x, int y, bool tiledFill) const
  68686. {
  68687. renderImageUntransformedInternal (*this, destData, srcData, alpha, x, y, tiledFill);
  68688. }
  68689. RectangleList clip;
  68690. template <class Renderer>
  68691. void iterate (Renderer& r) const throw()
  68692. {
  68693. RectangleList::Iterator iter (clip);
  68694. while (iter.next())
  68695. {
  68696. const Rectangle<int> rect (*iter.getRectangle());
  68697. const int x = rect.getX();
  68698. const int w = rect.getWidth();
  68699. jassert (w > 0);
  68700. const int bottom = rect.getBottom();
  68701. for (int y = rect.getY(); y < bottom; ++y)
  68702. {
  68703. r.setEdgeTableYPos (y);
  68704. r.handleEdgeTableLineFull (x, w);
  68705. }
  68706. }
  68707. }
  68708. private:
  68709. class SubRectangleIterator
  68710. {
  68711. public:
  68712. SubRectangleIterator (const RectangleList& clip_, const Rectangle<int>& area_)
  68713. : clip (clip_), area (area_)
  68714. {
  68715. }
  68716. template <class Renderer>
  68717. void iterate (Renderer& r) const throw()
  68718. {
  68719. RectangleList::Iterator iter (clip);
  68720. while (iter.next())
  68721. {
  68722. const Rectangle<int> rect (iter.getRectangle()->getIntersection (area));
  68723. if (! rect.isEmpty())
  68724. {
  68725. const int x = rect.getX();
  68726. const int w = rect.getWidth();
  68727. const int bottom = rect.getBottom();
  68728. for (int y = rect.getY(); y < bottom; ++y)
  68729. {
  68730. r.setEdgeTableYPos (y);
  68731. r.handleEdgeTableLineFull (x, w);
  68732. }
  68733. }
  68734. }
  68735. }
  68736. private:
  68737. const RectangleList& clip;
  68738. const Rectangle<int> area;
  68739. SubRectangleIterator (const SubRectangleIterator&);
  68740. SubRectangleIterator& operator= (const SubRectangleIterator&);
  68741. };
  68742. class SubRectangleIteratorFloat
  68743. {
  68744. public:
  68745. SubRectangleIteratorFloat (const RectangleList& clip_, const Rectangle<float>& area_)
  68746. : clip (clip_), area (area_)
  68747. {
  68748. }
  68749. template <class Renderer>
  68750. void iterate (Renderer& r) const throw()
  68751. {
  68752. int left = roundToInt (area.getX() * 256.0f);
  68753. int top = roundToInt (area.getY() * 256.0f);
  68754. int right = roundToInt (area.getRight() * 256.0f);
  68755. int bottom = roundToInt (area.getBottom() * 256.0f);
  68756. int totalTop, totalLeft, totalBottom, totalRight;
  68757. int topAlpha, leftAlpha, bottomAlpha, rightAlpha;
  68758. if ((top >> 8) == (bottom >> 8))
  68759. {
  68760. topAlpha = bottom - top;
  68761. bottomAlpha = 0;
  68762. totalTop = top >> 8;
  68763. totalBottom = bottom = top = totalTop + 1;
  68764. }
  68765. else
  68766. {
  68767. if ((top & 255) == 0)
  68768. {
  68769. topAlpha = 0;
  68770. top = totalTop = (top >> 8);
  68771. }
  68772. else
  68773. {
  68774. topAlpha = 255 - (top & 255);
  68775. totalTop = (top >> 8);
  68776. top = totalTop + 1;
  68777. }
  68778. bottomAlpha = bottom & 255;
  68779. bottom >>= 8;
  68780. totalBottom = bottom + (bottomAlpha != 0 ? 1 : 0);
  68781. }
  68782. if ((left >> 8) == (right >> 8))
  68783. {
  68784. leftAlpha = right - left;
  68785. rightAlpha = 0;
  68786. totalLeft = (left >> 8);
  68787. totalRight = right = left = totalLeft + 1;
  68788. }
  68789. else
  68790. {
  68791. if ((left & 255) == 0)
  68792. {
  68793. leftAlpha = 0;
  68794. left = totalLeft = (left >> 8);
  68795. }
  68796. else
  68797. {
  68798. leftAlpha = 255 - (left & 255);
  68799. totalLeft = (left >> 8);
  68800. left = totalLeft + 1;
  68801. }
  68802. rightAlpha = right & 255;
  68803. right >>= 8;
  68804. totalRight = right + (rightAlpha != 0 ? 1 : 0);
  68805. }
  68806. RectangleList::Iterator iter (clip);
  68807. while (iter.next())
  68808. {
  68809. const int clipLeft = iter.getRectangle()->getX();
  68810. const int clipRight = iter.getRectangle()->getRight();
  68811. const int clipTop = iter.getRectangle()->getY();
  68812. const int clipBottom = iter.getRectangle()->getBottom();
  68813. if (totalBottom > clipTop && totalTop < clipBottom && totalRight > clipLeft && totalLeft < clipRight)
  68814. {
  68815. if (right - left == 1 && leftAlpha + rightAlpha == 0) // special case for 1-pix vertical lines
  68816. {
  68817. if (topAlpha != 0 && totalTop >= clipTop)
  68818. {
  68819. r.setEdgeTableYPos (totalTop);
  68820. r.handleEdgeTablePixel (left, topAlpha);
  68821. }
  68822. const int endY = jmin (bottom, clipBottom);
  68823. for (int y = jmax (clipTop, top); y < endY; ++y)
  68824. {
  68825. r.setEdgeTableYPos (y);
  68826. r.handleEdgeTablePixelFull (left);
  68827. }
  68828. if (bottomAlpha != 0 && bottom < clipBottom)
  68829. {
  68830. r.setEdgeTableYPos (bottom);
  68831. r.handleEdgeTablePixel (left, bottomAlpha);
  68832. }
  68833. }
  68834. else
  68835. {
  68836. const int clippedLeft = jmax (left, clipLeft);
  68837. const int clippedWidth = jmin (right, clipRight) - clippedLeft;
  68838. const bool doLeftAlpha = leftAlpha != 0 && totalLeft >= clipLeft;
  68839. const bool doRightAlpha = rightAlpha != 0 && right < clipRight;
  68840. if (topAlpha != 0 && totalTop >= clipTop)
  68841. {
  68842. r.setEdgeTableYPos (totalTop);
  68843. if (doLeftAlpha)
  68844. r.handleEdgeTablePixel (totalLeft, (leftAlpha * topAlpha) >> 8);
  68845. if (clippedWidth > 0)
  68846. r.handleEdgeTableLine (clippedLeft, clippedWidth, topAlpha);
  68847. if (doRightAlpha)
  68848. r.handleEdgeTablePixel (right, (rightAlpha * topAlpha) >> 8);
  68849. }
  68850. const int endY = jmin (bottom, clipBottom);
  68851. for (int y = jmax (clipTop, top); y < endY; ++y)
  68852. {
  68853. r.setEdgeTableYPos (y);
  68854. if (doLeftAlpha)
  68855. r.handleEdgeTablePixel (totalLeft, leftAlpha);
  68856. if (clippedWidth > 0)
  68857. r.handleEdgeTableLineFull (clippedLeft, clippedWidth);
  68858. if (doRightAlpha)
  68859. r.handleEdgeTablePixel (right, rightAlpha);
  68860. }
  68861. if (bottomAlpha != 0 && bottom < clipBottom)
  68862. {
  68863. r.setEdgeTableYPos (bottom);
  68864. if (doLeftAlpha)
  68865. r.handleEdgeTablePixel (totalLeft, (leftAlpha * bottomAlpha) >> 8);
  68866. if (clippedWidth > 0)
  68867. r.handleEdgeTableLine (clippedLeft, clippedWidth, bottomAlpha);
  68868. if (doRightAlpha)
  68869. r.handleEdgeTablePixel (right, (rightAlpha * bottomAlpha) >> 8);
  68870. }
  68871. }
  68872. }
  68873. }
  68874. }
  68875. private:
  68876. const RectangleList& clip;
  68877. const Rectangle<float>& area;
  68878. SubRectangleIteratorFloat (const SubRectangleIteratorFloat&);
  68879. SubRectangleIteratorFloat& operator= (const SubRectangleIteratorFloat&);
  68880. };
  68881. ClipRegion_RectangleList& operator= (const ClipRegion_RectangleList&);
  68882. };
  68883. }
  68884. class LowLevelGraphicsSoftwareRenderer::SavedState
  68885. {
  68886. public:
  68887. SavedState (const Rectangle<int>& clip_, const int xOffset_, const int yOffset_)
  68888. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68889. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68890. {
  68891. }
  68892. SavedState (const RectangleList& clip_, const int xOffset_, const int yOffset_)
  68893. : clip (new SoftwareRendererClasses::ClipRegion_RectangleList (clip_)),
  68894. xOffset (xOffset_), yOffset (yOffset_), interpolationQuality (Graphics::mediumResamplingQuality)
  68895. {
  68896. }
  68897. SavedState (const SavedState& other)
  68898. : clip (other.clip), xOffset (other.xOffset), yOffset (other.yOffset), font (other.font),
  68899. fillType (other.fillType), interpolationQuality (other.interpolationQuality)
  68900. {
  68901. }
  68902. ~SavedState()
  68903. {
  68904. }
  68905. void setOrigin (const int x, const int y) throw()
  68906. {
  68907. xOffset += x;
  68908. yOffset += y;
  68909. }
  68910. bool clipToRectangle (const Rectangle<int>& r)
  68911. {
  68912. if (clip != 0)
  68913. {
  68914. cloneClipIfMultiplyReferenced();
  68915. clip = clip->clipToRectangle (r.translated (xOffset, yOffset));
  68916. }
  68917. return clip != 0;
  68918. }
  68919. bool clipToRectangleList (const RectangleList& r)
  68920. {
  68921. if (clip != 0)
  68922. {
  68923. cloneClipIfMultiplyReferenced();
  68924. RectangleList offsetList (r);
  68925. offsetList.offsetAll (xOffset, yOffset);
  68926. clip = clip->clipToRectangleList (offsetList);
  68927. }
  68928. return clip != 0;
  68929. }
  68930. bool excludeClipRectangle (const Rectangle<int>& r)
  68931. {
  68932. if (clip != 0)
  68933. {
  68934. cloneClipIfMultiplyReferenced();
  68935. clip = clip->excludeClipRectangle (r.translated (xOffset, yOffset));
  68936. }
  68937. return clip != 0;
  68938. }
  68939. void clipToPath (const Path& p, const AffineTransform& transform)
  68940. {
  68941. if (clip != 0)
  68942. {
  68943. cloneClipIfMultiplyReferenced();
  68944. clip = clip->clipToPath (p, transform.translated ((float) xOffset, (float) yOffset));
  68945. }
  68946. }
  68947. void clipToImageAlpha (const Image& image, const AffineTransform& t)
  68948. {
  68949. if (clip != 0)
  68950. {
  68951. if (image.hasAlphaChannel())
  68952. {
  68953. cloneClipIfMultiplyReferenced();
  68954. clip = clip->clipToImageAlpha (image, t.translated ((float) xOffset, (float) yOffset),
  68955. interpolationQuality != Graphics::lowResamplingQuality);
  68956. }
  68957. else
  68958. {
  68959. Path p;
  68960. p.addRectangle (image.getBounds());
  68961. clipToPath (p, t);
  68962. }
  68963. }
  68964. }
  68965. bool clipRegionIntersects (const Rectangle<int>& r) const
  68966. {
  68967. return clip != 0 && clip->clipRegionIntersects (r.translated (xOffset, yOffset));
  68968. }
  68969. const Rectangle<int> getClipBounds() const
  68970. {
  68971. return clip == 0 ? Rectangle<int>() : clip->getClipBounds().translated (-xOffset, -yOffset);
  68972. }
  68973. void fillRect (Image& image, const Rectangle<int>& r, const bool replaceContents)
  68974. {
  68975. if (clip != 0)
  68976. {
  68977. if (fillType.isColour())
  68978. {
  68979. Image::BitmapData destData (image, true);
  68980. clip->fillRectWithColour (destData, r.translated (xOffset, yOffset), fillType.colour.getPixelARGB(), replaceContents);
  68981. }
  68982. else
  68983. {
  68984. const Rectangle<int> totalClip (clip->getClipBounds());
  68985. const Rectangle<int> clipped (totalClip.getIntersection (r.translated (xOffset, yOffset)));
  68986. if (! clipped.isEmpty())
  68987. fillShape (image, new SoftwareRendererClasses::ClipRegion_RectangleList (clipped), false);
  68988. }
  68989. }
  68990. }
  68991. void fillRect (Image& image, const Rectangle<float>& r)
  68992. {
  68993. if (clip != 0)
  68994. {
  68995. if (fillType.isColour())
  68996. {
  68997. Image::BitmapData destData (image, true);
  68998. clip->fillRectWithColour (destData, r.translated ((float) xOffset, (float) yOffset), fillType.colour.getPixelARGB());
  68999. }
  69000. else
  69001. {
  69002. const Rectangle<float> totalClip (clip->getClipBounds().toFloat());
  69003. const Rectangle<float> clipped (totalClip.getIntersection (r.translated ((float) xOffset, (float) yOffset)));
  69004. if (! clipped.isEmpty())
  69005. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clipped), false);
  69006. }
  69007. }
  69008. }
  69009. void fillPath (Image& image, const Path& path, const AffineTransform& transform)
  69010. {
  69011. if (clip != 0)
  69012. fillShape (image, new SoftwareRendererClasses::ClipRegion_EdgeTable (clip->getClipBounds(), path, transform.translated ((float) xOffset, (float) yOffset)), false);
  69013. }
  69014. void fillEdgeTable (Image& image, const EdgeTable& edgeTable, const float x, const int y)
  69015. {
  69016. if (clip != 0)
  69017. {
  69018. SoftwareRendererClasses::ClipRegion_EdgeTable* edgeTableClip = new SoftwareRendererClasses::ClipRegion_EdgeTable (edgeTable);
  69019. SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill (edgeTableClip);
  69020. edgeTableClip->edgeTable.translate (x + xOffset, y + yOffset);
  69021. fillShape (image, shapeToFill, false);
  69022. }
  69023. }
  69024. void fillShape (Image& image, SoftwareRendererClasses::ClipRegionBase::Ptr shapeToFill, const bool replaceContents)
  69025. {
  69026. jassert (clip != 0);
  69027. shapeToFill = clip->applyClipTo (shapeToFill);
  69028. if (shapeToFill != 0)
  69029. {
  69030. Image::BitmapData destData (image, true);
  69031. if (fillType.isGradient())
  69032. {
  69033. jassert (! replaceContents); // that option is just for solid colours
  69034. ColourGradient g2 (*(fillType.gradient));
  69035. g2.multiplyOpacity (fillType.getOpacity());
  69036. AffineTransform transform (fillType.transform.translated (xOffset - 0.5f, yOffset - 0.5f));
  69037. const bool isIdentity = transform.isOnlyTranslation();
  69038. if (isIdentity)
  69039. {
  69040. // If our translation doesn't involve any distortion, we can speed it up..
  69041. g2.point1.applyTransform (transform);
  69042. g2.point2.applyTransform (transform);
  69043. transform = AffineTransform::identity;
  69044. }
  69045. shapeToFill->fillAllWithGradient (destData, g2, transform, isIdentity);
  69046. }
  69047. else if (fillType.isTiledImage())
  69048. {
  69049. renderImage (image, fillType.image, fillType.transform, shapeToFill);
  69050. }
  69051. else
  69052. {
  69053. shapeToFill->fillAllWithColour (destData, fillType.colour.getPixelARGB(), replaceContents);
  69054. }
  69055. }
  69056. }
  69057. void renderImage (Image& destImage, const Image& sourceImage, const AffineTransform& t, const SoftwareRendererClasses::ClipRegionBase* const tiledFillClipRegion)
  69058. {
  69059. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  69060. const Image::BitmapData destData (destImage, true);
  69061. const Image::BitmapData srcData (sourceImage, false);
  69062. const int alpha = fillType.colour.getAlpha();
  69063. const bool betterQuality = (interpolationQuality != Graphics::lowResamplingQuality);
  69064. if (transform.isOnlyTranslation())
  69065. {
  69066. // If our translation doesn't involve any distortion, just use a simple blit..
  69067. int tx = (int) (transform.getTranslationX() * 256.0f);
  69068. int ty = (int) (transform.getTranslationY() * 256.0f);
  69069. if ((! betterQuality) || ((tx | ty) & 224) == 0)
  69070. {
  69071. tx = ((tx + 128) >> 8);
  69072. ty = ((ty + 128) >> 8);
  69073. if (tiledFillClipRegion != 0)
  69074. {
  69075. tiledFillClipRegion->renderImageUntransformed (destData, srcData, alpha, tx, ty, true);
  69076. }
  69077. else
  69078. {
  69079. SoftwareRendererClasses::ClipRegionBase::Ptr c (new SoftwareRendererClasses::ClipRegion_EdgeTable (Rectangle<int> (tx, ty, sourceImage.getWidth(), sourceImage.getHeight()).getIntersection (destImage.getBounds())));
  69080. c = clip->applyClipTo (c);
  69081. if (c != 0)
  69082. c->renderImageUntransformed (destData, srcData, alpha, tx, ty, false);
  69083. }
  69084. return;
  69085. }
  69086. }
  69087. if (transform.isSingularity())
  69088. return;
  69089. if (tiledFillClipRegion != 0)
  69090. {
  69091. tiledFillClipRegion->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, true);
  69092. }
  69093. else
  69094. {
  69095. Path p;
  69096. p.addRectangle (sourceImage.getBounds());
  69097. SoftwareRendererClasses::ClipRegionBase::Ptr c (clip->clone());
  69098. c = c->clipToPath (p, transform);
  69099. if (c != 0)
  69100. c->renderImageTransformed (destData, srcData, alpha, transform, betterQuality, false);
  69101. }
  69102. }
  69103. SoftwareRendererClasses::ClipRegionBase::Ptr clip;
  69104. int xOffset, yOffset;
  69105. Font font;
  69106. FillType fillType;
  69107. Graphics::ResamplingQuality interpolationQuality;
  69108. private:
  69109. void cloneClipIfMultiplyReferenced()
  69110. {
  69111. if (clip->getReferenceCount() > 1)
  69112. clip = clip->clone();
  69113. }
  69114. SavedState& operator= (const SavedState&);
  69115. };
  69116. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_)
  69117. : image (image_)
  69118. {
  69119. currentState = new SavedState (image_.getBounds(), 0, 0);
  69120. }
  69121. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (const Image& image_, const int xOffset, const int yOffset,
  69122. const RectangleList& initialClip)
  69123. : image (image_)
  69124. {
  69125. currentState = new SavedState (initialClip, xOffset, yOffset);
  69126. }
  69127. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  69128. {
  69129. }
  69130. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  69131. {
  69132. return false;
  69133. }
  69134. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  69135. {
  69136. currentState->setOrigin (x, y);
  69137. }
  69138. bool LowLevelGraphicsSoftwareRenderer::clipToRectangle (const Rectangle<int>& r)
  69139. {
  69140. return currentState->clipToRectangle (r);
  69141. }
  69142. bool LowLevelGraphicsSoftwareRenderer::clipToRectangleList (const RectangleList& clipRegion)
  69143. {
  69144. return currentState->clipToRectangleList (clipRegion);
  69145. }
  69146. void LowLevelGraphicsSoftwareRenderer::excludeClipRectangle (const Rectangle<int>& r)
  69147. {
  69148. currentState->excludeClipRectangle (r);
  69149. }
  69150. void LowLevelGraphicsSoftwareRenderer::clipToPath (const Path& path, const AffineTransform& transform)
  69151. {
  69152. currentState->clipToPath (path, transform);
  69153. }
  69154. void LowLevelGraphicsSoftwareRenderer::clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  69155. {
  69156. currentState->clipToImageAlpha (sourceImage, transform);
  69157. }
  69158. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (const Rectangle<int>& r)
  69159. {
  69160. return currentState->clipRegionIntersects (r);
  69161. }
  69162. const Rectangle<int> LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  69163. {
  69164. return currentState->getClipBounds();
  69165. }
  69166. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  69167. {
  69168. return currentState->clip == 0;
  69169. }
  69170. void LowLevelGraphicsSoftwareRenderer::saveState()
  69171. {
  69172. stateStack.add (new SavedState (*currentState));
  69173. }
  69174. void LowLevelGraphicsSoftwareRenderer::restoreState()
  69175. {
  69176. SavedState* const top = stateStack.getLast();
  69177. if (top != 0)
  69178. {
  69179. currentState = top;
  69180. stateStack.removeLast (1, false);
  69181. }
  69182. else
  69183. {
  69184. jassertfalse; // trying to pop with an empty stack!
  69185. }
  69186. }
  69187. void LowLevelGraphicsSoftwareRenderer::setFill (const FillType& fillType)
  69188. {
  69189. currentState->fillType = fillType;
  69190. }
  69191. void LowLevelGraphicsSoftwareRenderer::setOpacity (float newOpacity)
  69192. {
  69193. currentState->fillType.setOpacity (newOpacity);
  69194. }
  69195. void LowLevelGraphicsSoftwareRenderer::setInterpolationQuality (Graphics::ResamplingQuality quality)
  69196. {
  69197. currentState->interpolationQuality = quality;
  69198. }
  69199. void LowLevelGraphicsSoftwareRenderer::fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  69200. {
  69201. currentState->fillRect (image, r, replaceExistingContents);
  69202. }
  69203. void LowLevelGraphicsSoftwareRenderer::fillPath (const Path& path, const AffineTransform& transform)
  69204. {
  69205. currentState->fillPath (image, path, transform);
  69206. }
  69207. void LowLevelGraphicsSoftwareRenderer::drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  69208. {
  69209. currentState->renderImage (image, sourceImage, transform,
  69210. fillEntireClipAsTiles ? currentState->clip : 0);
  69211. }
  69212. void LowLevelGraphicsSoftwareRenderer::drawLine (const Line <float>& line)
  69213. {
  69214. Path p;
  69215. p.addLineSegment (line, 1.0f);
  69216. fillPath (p, AffineTransform::identity);
  69217. }
  69218. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, float top, float bottom)
  69219. {
  69220. if (bottom > top)
  69221. currentState->fillRect (image, Rectangle<float> ((float) x, top, 1.0f, bottom - top));
  69222. }
  69223. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, float left, float right)
  69224. {
  69225. if (right > left)
  69226. currentState->fillRect (image, Rectangle<float> (left, (float) y, right - left, 1.0f));
  69227. }
  69228. class LowLevelGraphicsSoftwareRenderer::CachedGlyph
  69229. {
  69230. public:
  69231. CachedGlyph() : glyph (0), lastAccessCount (0) {}
  69232. ~CachedGlyph() {}
  69233. void draw (SavedState& state, Image& image, const float x, const float y) const
  69234. {
  69235. if (edgeTable != 0)
  69236. state.fillEdgeTable (image, *edgeTable, x, roundToInt (y));
  69237. }
  69238. void generate (const Font& newFont, const int glyphNumber)
  69239. {
  69240. font = newFont;
  69241. glyph = glyphNumber;
  69242. edgeTable = 0;
  69243. Path glyphPath;
  69244. font.getTypeface()->getOutlineForGlyph (glyphNumber, glyphPath);
  69245. if (! glyphPath.isEmpty())
  69246. {
  69247. const float fontHeight = font.getHeight();
  69248. const AffineTransform transform (AffineTransform::scale (fontHeight * font.getHorizontalScale(), fontHeight)
  69249. #if JUCE_MAC || JUCE_IOS
  69250. .translated (0.0f, -0.5f)
  69251. #endif
  69252. );
  69253. edgeTable = new EdgeTable (glyphPath.getBoundsTransformed (transform).getSmallestIntegerContainer().expanded (1, 0),
  69254. glyphPath, transform);
  69255. }
  69256. }
  69257. int glyph, lastAccessCount;
  69258. Font font;
  69259. juce_UseDebuggingNewOperator
  69260. private:
  69261. ScopedPointer <EdgeTable> edgeTable;
  69262. CachedGlyph (const CachedGlyph&);
  69263. CachedGlyph& operator= (const CachedGlyph&);
  69264. };
  69265. class LowLevelGraphicsSoftwareRenderer::GlyphCache : private DeletedAtShutdown
  69266. {
  69267. public:
  69268. GlyphCache()
  69269. : accessCounter (0), hits (0), misses (0)
  69270. {
  69271. for (int i = 120; --i >= 0;)
  69272. glyphs.add (new CachedGlyph());
  69273. }
  69274. ~GlyphCache()
  69275. {
  69276. clearSingletonInstance();
  69277. }
  69278. juce_DeclareSingleton_SingleThreaded_Minimal (GlyphCache);
  69279. void drawGlyph (SavedState& state, Image& image, const Font& font, const int glyphNumber, float x, float y)
  69280. {
  69281. ++accessCounter;
  69282. int oldestCounter = std::numeric_limits<int>::max();
  69283. CachedGlyph* oldest = 0;
  69284. for (int i = glyphs.size(); --i >= 0;)
  69285. {
  69286. CachedGlyph* const glyph = glyphs.getUnchecked (i);
  69287. if (glyph->glyph == glyphNumber && glyph->font == font)
  69288. {
  69289. ++hits;
  69290. glyph->lastAccessCount = accessCounter;
  69291. glyph->draw (state, image, x, y);
  69292. return;
  69293. }
  69294. if (glyph->lastAccessCount <= oldestCounter)
  69295. {
  69296. oldestCounter = glyph->lastAccessCount;
  69297. oldest = glyph;
  69298. }
  69299. }
  69300. if (hits + ++misses > (glyphs.size() << 4))
  69301. {
  69302. if (misses * 2 > hits)
  69303. {
  69304. for (int i = 32; --i >= 0;)
  69305. glyphs.add (new CachedGlyph());
  69306. }
  69307. hits = misses = 0;
  69308. oldest = glyphs.getLast();
  69309. }
  69310. jassert (oldest != 0);
  69311. oldest->lastAccessCount = accessCounter;
  69312. oldest->generate (font, glyphNumber);
  69313. oldest->draw (state, image, x, y);
  69314. }
  69315. juce_UseDebuggingNewOperator
  69316. private:
  69317. friend class OwnedArray <CachedGlyph>;
  69318. OwnedArray <CachedGlyph> glyphs;
  69319. int accessCounter, hits, misses;
  69320. GlyphCache (const GlyphCache&);
  69321. GlyphCache& operator= (const GlyphCache&);
  69322. };
  69323. juce_ImplementSingleton_SingleThreaded (LowLevelGraphicsSoftwareRenderer::GlyphCache);
  69324. void LowLevelGraphicsSoftwareRenderer::setFont (const Font& newFont)
  69325. {
  69326. currentState->font = newFont;
  69327. }
  69328. const Font LowLevelGraphicsSoftwareRenderer::getFont()
  69329. {
  69330. return currentState->font;
  69331. }
  69332. void LowLevelGraphicsSoftwareRenderer::drawGlyph (int glyphNumber, const AffineTransform& transform)
  69333. {
  69334. Font& f = currentState->font;
  69335. if (transform.isOnlyTranslation())
  69336. {
  69337. GlyphCache::getInstance()->drawGlyph (*currentState, image, f, glyphNumber,
  69338. transform.getTranslationX(),
  69339. transform.getTranslationY());
  69340. }
  69341. else
  69342. {
  69343. Path p;
  69344. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  69345. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight()).followedBy (transform));
  69346. }
  69347. }
  69348. #if JUCE_MSVC
  69349. #pragma warning (pop)
  69350. #if JUCE_DEBUG
  69351. #pragma optimize ("", on) // resets optimisations to the project defaults
  69352. #endif
  69353. #endif
  69354. END_JUCE_NAMESPACE
  69355. /*** End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp ***/
  69356. /*** Start of inlined file: juce_RectanglePlacement.cpp ***/
  69357. BEGIN_JUCE_NAMESPACE
  69358. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  69359. : flags (other.flags)
  69360. {
  69361. }
  69362. RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  69363. {
  69364. flags = other.flags;
  69365. return *this;
  69366. }
  69367. void RectanglePlacement::applyTo (double& x, double& y,
  69368. double& w, double& h,
  69369. const double dx, const double dy,
  69370. const double dw, const double dh) const throw()
  69371. {
  69372. if (w == 0 || h == 0)
  69373. return;
  69374. if ((flags & stretchToFit) != 0)
  69375. {
  69376. x = dx;
  69377. y = dy;
  69378. w = dw;
  69379. h = dh;
  69380. }
  69381. else
  69382. {
  69383. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  69384. : jmin (dw / w, dh / h);
  69385. if ((flags & onlyReduceInSize) != 0)
  69386. scale = jmin (scale, 1.0);
  69387. if ((flags & onlyIncreaseInSize) != 0)
  69388. scale = jmax (scale, 1.0);
  69389. w *= scale;
  69390. h *= scale;
  69391. if ((flags & xLeft) != 0)
  69392. x = dx;
  69393. else if ((flags & xRight) != 0)
  69394. x = dx + dw - w;
  69395. else
  69396. x = dx + (dw - w) * 0.5;
  69397. if ((flags & yTop) != 0)
  69398. y = dy;
  69399. else if ((flags & yBottom) != 0)
  69400. y = dy + dh - h;
  69401. else
  69402. y = dy + (dh - h) * 0.5;
  69403. }
  69404. }
  69405. const AffineTransform RectanglePlacement::getTransformToFit (const Rectangle<float>& source, const Rectangle<float>& destination) const throw()
  69406. {
  69407. if (source.isEmpty())
  69408. return AffineTransform::identity;
  69409. float w = source.getWidth();
  69410. float h = source.getHeight();
  69411. const float scaleX = destination.getWidth() / w;
  69412. const float scaleY = destination.getHeight() / h;
  69413. if ((flags & stretchToFit) != 0)
  69414. return AffineTransform::translation (-source.getX(), -source.getY())
  69415. .scaled (scaleX, scaleY)
  69416. .translated (destination.getX(), destination.getY());
  69417. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  69418. : jmin (scaleX, scaleY);
  69419. if ((flags & onlyReduceInSize) != 0)
  69420. scale = jmin (scale, 1.0f);
  69421. if ((flags & onlyIncreaseInSize) != 0)
  69422. scale = jmax (scale, 1.0f);
  69423. w *= scale;
  69424. h *= scale;
  69425. float newX = destination.getX();
  69426. float newY = destination.getY();
  69427. if ((flags & xRight) != 0)
  69428. newX += destination.getWidth() - w; // right
  69429. else if ((flags & xLeft) == 0)
  69430. newX += (destination.getWidth() - w) / 2.0f; // centre
  69431. if ((flags & yBottom) != 0)
  69432. newY += destination.getHeight() - h; // bottom
  69433. else if ((flags & yTop) == 0)
  69434. newY += (destination.getHeight() - h) / 2.0f; // centre
  69435. return AffineTransform::translation (-source.getX(), -source.getY())
  69436. .scaled (scale, scale)
  69437. .translated (newX, newY);
  69438. }
  69439. END_JUCE_NAMESPACE
  69440. /*** End of inlined file: juce_RectanglePlacement.cpp ***/
  69441. /*** Start of inlined file: juce_Drawable.cpp ***/
  69442. BEGIN_JUCE_NAMESPACE
  69443. Drawable::RenderingContext::RenderingContext (Graphics& g_,
  69444. const AffineTransform& transform_,
  69445. const float opacity_) throw()
  69446. : g (g_),
  69447. transform (transform_),
  69448. opacity (opacity_)
  69449. {
  69450. }
  69451. Drawable::Drawable()
  69452. : parent (0)
  69453. {
  69454. }
  69455. Drawable::~Drawable()
  69456. {
  69457. }
  69458. void Drawable::draw (Graphics& g, const float opacity, const AffineTransform& transform) const
  69459. {
  69460. render (RenderingContext (g, transform, opacity));
  69461. }
  69462. void Drawable::drawAt (Graphics& g, const float x, const float y, const float opacity) const
  69463. {
  69464. draw (g, opacity, AffineTransform::translation (x, y));
  69465. }
  69466. void Drawable::drawWithin (Graphics& g,
  69467. const Rectangle<float>& destArea,
  69468. const RectanglePlacement& placement,
  69469. const float opacity) const
  69470. {
  69471. if (! destArea.isEmpty())
  69472. draw (g, opacity, placement.getTransformToFit (getBounds(), destArea));
  69473. }
  69474. Drawable* Drawable::createFromImageData (const void* data, const size_t numBytes)
  69475. {
  69476. Drawable* result = 0;
  69477. Image image (ImageFileFormat::loadFrom (data, (int) numBytes));
  69478. if (image.isValid())
  69479. {
  69480. DrawableImage* const di = new DrawableImage();
  69481. di->setImage (image);
  69482. result = di;
  69483. }
  69484. else
  69485. {
  69486. const String asString (String::createStringFromData (data, (int) numBytes));
  69487. XmlDocument doc (asString);
  69488. ScopedPointer <XmlElement> outer (doc.getDocumentElement (true));
  69489. if (outer != 0 && outer->hasTagName ("svg"))
  69490. {
  69491. ScopedPointer <XmlElement> svg (doc.getDocumentElement());
  69492. if (svg != 0)
  69493. result = Drawable::createFromSVG (*svg);
  69494. }
  69495. }
  69496. return result;
  69497. }
  69498. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  69499. {
  69500. MemoryOutputStream mo;
  69501. mo.writeFromInputStream (dataSource, -1);
  69502. return createFromImageData (mo.getData(), mo.getDataSize());
  69503. }
  69504. Drawable* Drawable::createFromImageFile (const File& file)
  69505. {
  69506. const ScopedPointer <FileInputStream> fin (file.createInputStream());
  69507. return fin != 0 ? createFromImageDataStream (*fin) : 0;
  69508. }
  69509. Drawable* Drawable::createFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  69510. {
  69511. return createChildFromValueTree (0, tree, imageProvider);
  69512. }
  69513. Drawable* Drawable::createChildFromValueTree (DrawableComposite* parent, const ValueTree& tree, ImageProvider* imageProvider)
  69514. {
  69515. const Identifier type (tree.getType());
  69516. Drawable* d = 0;
  69517. if (type == DrawablePath::valueTreeType)
  69518. d = new DrawablePath();
  69519. else if (type == DrawableComposite::valueTreeType)
  69520. d = new DrawableComposite();
  69521. else if (type == DrawableRectangle::valueTreeType)
  69522. d = new DrawableRectangle();
  69523. else if (type == DrawableImage::valueTreeType)
  69524. d = new DrawableImage();
  69525. else if (type == DrawableText::valueTreeType)
  69526. d = new DrawableText();
  69527. if (d != 0)
  69528. {
  69529. d->parent = parent;
  69530. d->refreshFromValueTree (tree, imageProvider);
  69531. }
  69532. return d;
  69533. }
  69534. const Identifier Drawable::ValueTreeWrapperBase::idProperty ("id");
  69535. Drawable::ValueTreeWrapperBase::ValueTreeWrapperBase (const ValueTree& state_)
  69536. : state (state_)
  69537. {
  69538. }
  69539. Drawable::ValueTreeWrapperBase::~ValueTreeWrapperBase()
  69540. {
  69541. }
  69542. const String Drawable::ValueTreeWrapperBase::getID() const
  69543. {
  69544. return state [idProperty];
  69545. }
  69546. void Drawable::ValueTreeWrapperBase::setID (const String& newID, UndoManager* const undoManager)
  69547. {
  69548. if (newID.isEmpty())
  69549. state.removeProperty (idProperty, undoManager);
  69550. else
  69551. state.setProperty (idProperty, newID, undoManager);
  69552. }
  69553. END_JUCE_NAMESPACE
  69554. /*** End of inlined file: juce_Drawable.cpp ***/
  69555. /*** Start of inlined file: juce_DrawableShape.cpp ***/
  69556. BEGIN_JUCE_NAMESPACE
  69557. DrawableShape::DrawableShape()
  69558. : strokeType (0.0f),
  69559. mainFill (Colours::black),
  69560. strokeFill (Colours::black),
  69561. pathNeedsUpdating (true),
  69562. strokeNeedsUpdating (true)
  69563. {
  69564. }
  69565. DrawableShape::DrawableShape (const DrawableShape& other)
  69566. : strokeType (other.strokeType),
  69567. mainFill (other.mainFill),
  69568. strokeFill (other.strokeFill),
  69569. pathNeedsUpdating (true),
  69570. strokeNeedsUpdating (true)
  69571. {
  69572. }
  69573. DrawableShape::~DrawableShape()
  69574. {
  69575. }
  69576. void DrawableShape::setFill (const FillType& newFill)
  69577. {
  69578. mainFill = newFill;
  69579. }
  69580. void DrawableShape::setStrokeFill (const FillType& newFill)
  69581. {
  69582. strokeFill = newFill;
  69583. }
  69584. void DrawableShape::setStrokeType (const PathStrokeType& newStrokeType)
  69585. {
  69586. strokeType = newStrokeType;
  69587. strokeNeedsUpdating = true;
  69588. }
  69589. void DrawableShape::setStrokeThickness (const float newThickness)
  69590. {
  69591. setStrokeType (PathStrokeType (newThickness, strokeType.getJointStyle(), strokeType.getEndStyle()));
  69592. }
  69593. bool DrawableShape::isStrokeVisible() const throw()
  69594. {
  69595. return strokeType.getStrokeThickness() > 0.0f && ! strokeFill.isInvisible();
  69596. }
  69597. void DrawableShape::setBrush (const Drawable::RenderingContext& context, const FillType& type)
  69598. {
  69599. FillType f (type);
  69600. if (f.isGradient())
  69601. f.gradient->multiplyOpacity (context.opacity);
  69602. else
  69603. f.setOpacity (f.getOpacity() * context.opacity);
  69604. f.transform = f.transform.followedBy (context.transform);
  69605. context.g.setFillType (f);
  69606. }
  69607. bool DrawableShape::refreshFillTypes (const FillAndStrokeState& newState,
  69608. Expression::EvaluationContext* /*nameFinder*/,
  69609. ImageProvider* imageProvider)
  69610. {
  69611. bool hasChanged = false;
  69612. {
  69613. const FillType f (newState.getMainFill (parent, imageProvider));
  69614. if (mainFill != f)
  69615. {
  69616. hasChanged = true;
  69617. mainFill = f;
  69618. }
  69619. }
  69620. {
  69621. const FillType f (newState.getStrokeFill (parent, imageProvider));
  69622. if (strokeFill != f)
  69623. {
  69624. hasChanged = true;
  69625. strokeFill = f;
  69626. }
  69627. }
  69628. return hasChanged;
  69629. }
  69630. void DrawableShape::writeTo (FillAndStrokeState& state, ImageProvider* imageProvider, UndoManager* undoManager) const
  69631. {
  69632. state.setMainFill (mainFill, 0, 0, 0, imageProvider, undoManager);
  69633. state.setStrokeFill (strokeFill, 0, 0, 0, imageProvider, undoManager);
  69634. state.setStrokeType (strokeType, undoManager);
  69635. }
  69636. void DrawableShape::render (const Drawable::RenderingContext& context) const
  69637. {
  69638. setBrush (context, mainFill);
  69639. context.g.fillPath (getCachedPath(), context.transform);
  69640. if (isStrokeVisible())
  69641. {
  69642. setBrush (context, strokeFill);
  69643. context.g.fillPath (getCachedStrokePath(), context.transform);
  69644. }
  69645. }
  69646. void DrawableShape::pathChanged()
  69647. {
  69648. pathNeedsUpdating = true;
  69649. }
  69650. void DrawableShape::strokeChanged()
  69651. {
  69652. strokeNeedsUpdating = true;
  69653. }
  69654. void DrawableShape::invalidatePoints()
  69655. {
  69656. pathNeedsUpdating = true;
  69657. strokeNeedsUpdating = true;
  69658. }
  69659. const Path& DrawableShape::getCachedPath() const
  69660. {
  69661. if (pathNeedsUpdating)
  69662. {
  69663. pathNeedsUpdating = false;
  69664. if (rebuildPath (cachedPath))
  69665. strokeNeedsUpdating = true;
  69666. }
  69667. return cachedPath;
  69668. }
  69669. const Path& DrawableShape::getCachedStrokePath() const
  69670. {
  69671. if (strokeNeedsUpdating)
  69672. {
  69673. cachedStroke.clear();
  69674. strokeType.createStrokedPath (cachedStroke, getCachedPath(), AffineTransform::identity, 4.0f);
  69675. strokeNeedsUpdating = false; // (must be called after getCachedPath)
  69676. }
  69677. return cachedStroke;
  69678. }
  69679. const Rectangle<float> DrawableShape::getBounds() const
  69680. {
  69681. if (isStrokeVisible())
  69682. return getCachedStrokePath().getBounds();
  69683. else
  69684. return getCachedPath().getBounds();
  69685. }
  69686. bool DrawableShape::hitTest (float x, float y) const
  69687. {
  69688. return getCachedPath().contains (x, y)
  69689. || (isStrokeVisible() && getCachedStrokePath().contains (x, y));
  69690. }
  69691. const Identifier DrawableShape::FillAndStrokeState::type ("type");
  69692. const Identifier DrawableShape::FillAndStrokeState::colour ("colour");
  69693. const Identifier DrawableShape::FillAndStrokeState::colours ("colours");
  69694. const Identifier DrawableShape::FillAndStrokeState::fill ("Fill");
  69695. const Identifier DrawableShape::FillAndStrokeState::stroke ("Stroke");
  69696. const Identifier DrawableShape::FillAndStrokeState::path ("Path");
  69697. const Identifier DrawableShape::FillAndStrokeState::jointStyle ("jointStyle");
  69698. const Identifier DrawableShape::FillAndStrokeState::capStyle ("capStyle");
  69699. const Identifier DrawableShape::FillAndStrokeState::strokeWidth ("strokeWidth");
  69700. const Identifier DrawableShape::FillAndStrokeState::gradientPoint1 ("point1");
  69701. const Identifier DrawableShape::FillAndStrokeState::gradientPoint2 ("point2");
  69702. const Identifier DrawableShape::FillAndStrokeState::gradientPoint3 ("point3");
  69703. const Identifier DrawableShape::FillAndStrokeState::radial ("radial");
  69704. const Identifier DrawableShape::FillAndStrokeState::imageId ("imageId");
  69705. const Identifier DrawableShape::FillAndStrokeState::imageOpacity ("imageOpacity");
  69706. DrawableShape::FillAndStrokeState::FillAndStrokeState (const ValueTree& state_)
  69707. : Drawable::ValueTreeWrapperBase (state_)
  69708. {
  69709. }
  69710. const FillType DrawableShape::FillAndStrokeState::getMainFill (Expression::EvaluationContext* nameFinder,
  69711. ImageProvider* imageProvider) const
  69712. {
  69713. return readFillType (state.getChildWithName (fill), 0, 0, 0, nameFinder, imageProvider);
  69714. }
  69715. ValueTree DrawableShape::FillAndStrokeState::getMainFillState()
  69716. {
  69717. ValueTree v (state.getChildWithName (fill));
  69718. if (v.isValid())
  69719. return v;
  69720. setMainFill (Colours::black, 0, 0, 0, 0, 0);
  69721. return getMainFillState();
  69722. }
  69723. void DrawableShape::FillAndStrokeState::setMainFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69724. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69725. {
  69726. ValueTree v (state.getOrCreateChildWithName (fill, undoManager));
  69727. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69728. }
  69729. const FillType DrawableShape::FillAndStrokeState::getStrokeFill (Expression::EvaluationContext* nameFinder,
  69730. ImageProvider* imageProvider) const
  69731. {
  69732. return readFillType (state.getChildWithName (stroke), 0, 0, 0, nameFinder, imageProvider);
  69733. }
  69734. ValueTree DrawableShape::FillAndStrokeState::getStrokeFillState()
  69735. {
  69736. ValueTree v (state.getChildWithName (stroke));
  69737. if (v.isValid())
  69738. return v;
  69739. setStrokeFill (Colours::black, 0, 0, 0, 0, 0);
  69740. return getStrokeFillState();
  69741. }
  69742. void DrawableShape::FillAndStrokeState::setStrokeFill (const FillType& newFill, const RelativePoint* gp1, const RelativePoint* gp2,
  69743. const RelativePoint* gp3, ImageProvider* imageProvider, UndoManager* undoManager)
  69744. {
  69745. ValueTree v (state.getOrCreateChildWithName (stroke, undoManager));
  69746. writeFillType (v, newFill, gp1, gp2, gp3, imageProvider, undoManager);
  69747. }
  69748. const PathStrokeType DrawableShape::FillAndStrokeState::getStrokeType() const
  69749. {
  69750. const String jointStyleString (state [jointStyle].toString());
  69751. const String capStyleString (state [capStyle].toString());
  69752. return PathStrokeType (state [strokeWidth],
  69753. jointStyleString == "curved" ? PathStrokeType::curved
  69754. : (jointStyleString == "bevel" ? PathStrokeType::beveled
  69755. : PathStrokeType::mitered),
  69756. capStyleString == "square" ? PathStrokeType::square
  69757. : (capStyleString == "round" ? PathStrokeType::rounded
  69758. : PathStrokeType::butt));
  69759. }
  69760. void DrawableShape::FillAndStrokeState::setStrokeType (const PathStrokeType& newStrokeType, UndoManager* undoManager)
  69761. {
  69762. state.setProperty (strokeWidth, (double) newStrokeType.getStrokeThickness(), undoManager);
  69763. state.setProperty (jointStyle, newStrokeType.getJointStyle() == PathStrokeType::mitered
  69764. ? "miter" : (newStrokeType.getJointStyle() == PathStrokeType::curved ? "curved" : "bevel"), undoManager);
  69765. state.setProperty (capStyle, newStrokeType.getEndStyle() == PathStrokeType::butt
  69766. ? "butt" : (newStrokeType.getEndStyle() == PathStrokeType::square ? "square" : "round"), undoManager);
  69767. }
  69768. const FillType DrawableShape::FillAndStrokeState::readFillType (const ValueTree& v, RelativePoint* const gp1, RelativePoint* const gp2, RelativePoint* const gp3,
  69769. Expression::EvaluationContext* const nameFinder, ImageProvider* imageProvider)
  69770. {
  69771. const String newType (v[type].toString());
  69772. if (newType == "solid")
  69773. {
  69774. const String colourString (v [colour].toString());
  69775. return FillType (Colour (colourString.isEmpty() ? (uint32) 0xff000000
  69776. : (uint32) colourString.getHexValue32()));
  69777. }
  69778. else if (newType == "gradient")
  69779. {
  69780. RelativePoint p1 (v [gradientPoint1]), p2 (v [gradientPoint2]), p3 (v [gradientPoint3]);
  69781. ColourGradient g;
  69782. if (gp1 != 0) *gp1 = p1;
  69783. if (gp2 != 0) *gp2 = p2;
  69784. if (gp3 != 0) *gp3 = p3;
  69785. g.point1 = p1.resolve (nameFinder);
  69786. g.point2 = p2.resolve (nameFinder);
  69787. g.isRadial = v[radial];
  69788. StringArray colourSteps;
  69789. colourSteps.addTokens (v[colours].toString(), false);
  69790. for (int i = 0; i < colourSteps.size() / 2; ++i)
  69791. g.addColour (colourSteps[i * 2].getDoubleValue(),
  69792. Colour ((uint32) colourSteps[i * 2 + 1].getHexValue32()));
  69793. FillType fillType (g);
  69794. if (g.isRadial)
  69795. {
  69796. const Point<float> point3 (p3.resolve (nameFinder));
  69797. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69798. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69799. fillType.transform = AffineTransform::fromTargetPoints (g.point1.getX(), g.point1.getY(), g.point1.getX(), g.point1.getY(),
  69800. g.point2.getX(), g.point2.getY(), g.point2.getX(), g.point2.getY(),
  69801. point3Source.getX(), point3Source.getY(), point3.getX(), point3.getY());
  69802. }
  69803. return fillType;
  69804. }
  69805. else if (newType == "image")
  69806. {
  69807. Image im;
  69808. if (imageProvider != 0)
  69809. im = imageProvider->getImageForIdentifier (v[imageId]);
  69810. FillType f (im, AffineTransform::identity);
  69811. f.setOpacity ((float) v.getProperty (imageOpacity, 1.0f));
  69812. return f;
  69813. }
  69814. jassert (! v.isValid());
  69815. return FillType();
  69816. }
  69817. namespace DrawableShapeHelpers
  69818. {
  69819. const Point<float> calcThirdGradientPoint (const FillType& fillType)
  69820. {
  69821. const ColourGradient& g = *fillType.gradient;
  69822. const Point<float> point3Source (g.point1.getX() + g.point2.getY() - g.point1.getY(),
  69823. g.point1.getY() + g.point1.getX() - g.point2.getX());
  69824. return point3Source.transformedBy (fillType.transform);
  69825. }
  69826. }
  69827. void DrawableShape::FillAndStrokeState::writeFillType (ValueTree& v, const FillType& fillType,
  69828. const RelativePoint* const gp1, const RelativePoint* const gp2, const RelativePoint* gp3,
  69829. ImageProvider* imageProvider, UndoManager* const undoManager)
  69830. {
  69831. if (fillType.isColour())
  69832. {
  69833. v.setProperty (type, "solid", undoManager);
  69834. v.setProperty (colour, String::toHexString ((int) fillType.colour.getARGB()), undoManager);
  69835. }
  69836. else if (fillType.isGradient())
  69837. {
  69838. v.setProperty (type, "gradient", undoManager);
  69839. v.setProperty (gradientPoint1, gp1 != 0 ? gp1->toString() : fillType.gradient->point1.toString(), undoManager);
  69840. v.setProperty (gradientPoint2, gp2 != 0 ? gp2->toString() : fillType.gradient->point2.toString(), undoManager);
  69841. v.setProperty (gradientPoint3, gp3 != 0 ? gp3->toString() : DrawableShapeHelpers::calcThirdGradientPoint (fillType).toString(), undoManager);
  69842. v.setProperty (radial, fillType.gradient->isRadial, undoManager);
  69843. String s;
  69844. for (int i = 0; i < fillType.gradient->getNumColours(); ++i)
  69845. s << ' ' << fillType.gradient->getColourPosition (i)
  69846. << ' ' << String::toHexString ((int) fillType.gradient->getColour(i).getARGB());
  69847. v.setProperty (colours, s.trimStart(), undoManager);
  69848. }
  69849. else if (fillType.isTiledImage())
  69850. {
  69851. v.setProperty (type, "image", undoManager);
  69852. if (imageProvider != 0)
  69853. v.setProperty (imageId, imageProvider->getIdentifierForImage (fillType.image), undoManager);
  69854. if (fillType.getOpacity() < 1.0f)
  69855. v.setProperty (imageOpacity, fillType.getOpacity(), undoManager);
  69856. else
  69857. v.removeProperty (imageOpacity, undoManager);
  69858. }
  69859. else
  69860. {
  69861. jassertfalse;
  69862. }
  69863. }
  69864. END_JUCE_NAMESPACE
  69865. /*** End of inlined file: juce_DrawableShape.cpp ***/
  69866. /*** Start of inlined file: juce_DrawableComposite.cpp ***/
  69867. BEGIN_JUCE_NAMESPACE
  69868. DrawableComposite::DrawableComposite()
  69869. : bounds (Point<float>(), Point<float> (100.0f, 0.0f), Point<float> (0.0f, 100.0f))
  69870. {
  69871. setContentArea (RelativeRectangle (RelativeCoordinate (0.0),
  69872. RelativeCoordinate (100.0),
  69873. RelativeCoordinate (0.0),
  69874. RelativeCoordinate (100.0)));
  69875. }
  69876. DrawableComposite::DrawableComposite (const DrawableComposite& other)
  69877. {
  69878. bounds = other.bounds;
  69879. for (int i = 0; i < other.drawables.size(); ++i)
  69880. drawables.add (other.drawables.getUnchecked(i)->createCopy());
  69881. markersX.addCopiesOf (other.markersX);
  69882. markersY.addCopiesOf (other.markersY);
  69883. }
  69884. DrawableComposite::~DrawableComposite()
  69885. {
  69886. }
  69887. void DrawableComposite::insertDrawable (Drawable* drawable, const int index)
  69888. {
  69889. if (drawable != 0)
  69890. {
  69891. jassert (! drawables.contains (drawable)); // trying to add a drawable that's already in here!
  69892. jassert (drawable->parent == 0); // A drawable can only live inside one parent at a time!
  69893. drawables.insert (index, drawable);
  69894. drawable->parent = this;
  69895. }
  69896. }
  69897. void DrawableComposite::insertDrawable (const Drawable& drawable, const int index)
  69898. {
  69899. insertDrawable (drawable.createCopy(), index);
  69900. }
  69901. void DrawableComposite::removeDrawable (const int index, const bool deleteDrawable)
  69902. {
  69903. drawables.remove (index, deleteDrawable);
  69904. }
  69905. Drawable* DrawableComposite::getDrawableWithName (const String& name) const throw()
  69906. {
  69907. for (int i = drawables.size(); --i >= 0;)
  69908. if (drawables.getUnchecked(i)->getName() == name)
  69909. return drawables.getUnchecked(i);
  69910. return 0;
  69911. }
  69912. void DrawableComposite::bringToFront (const int index)
  69913. {
  69914. if (index >= 0 && index < drawables.size() - 1)
  69915. drawables.move (index, -1);
  69916. }
  69917. void DrawableComposite::setBoundingBox (const RelativeParallelogram& newBoundingBox)
  69918. {
  69919. bounds = newBoundingBox;
  69920. }
  69921. DrawableComposite::Marker::Marker (const DrawableComposite::Marker& other)
  69922. : name (other.name), position (other.position)
  69923. {
  69924. }
  69925. DrawableComposite::Marker::Marker (const String& name_, const RelativeCoordinate& position_)
  69926. : name (name_), position (position_)
  69927. {
  69928. }
  69929. bool DrawableComposite::Marker::operator!= (const DrawableComposite::Marker& other) const throw()
  69930. {
  69931. return name != other.name || position != other.position;
  69932. }
  69933. const char* const DrawableComposite::contentLeftMarkerName ("left");
  69934. const char* const DrawableComposite::contentRightMarkerName ("right");
  69935. const char* const DrawableComposite::contentTopMarkerName ("top");
  69936. const char* const DrawableComposite::contentBottomMarkerName ("bottom");
  69937. const RelativeRectangle DrawableComposite::getContentArea() const
  69938. {
  69939. jassert (markersX.size() >= 2 && getMarker (true, 0)->name == contentLeftMarkerName && getMarker (true, 1)->name == contentRightMarkerName);
  69940. jassert (markersY.size() >= 2 && getMarker (false, 0)->name == contentTopMarkerName && getMarker (false, 1)->name == contentBottomMarkerName);
  69941. return RelativeRectangle (markersX.getUnchecked(0)->position, markersX.getUnchecked(1)->position,
  69942. markersY.getUnchecked(0)->position, markersY.getUnchecked(1)->position);
  69943. }
  69944. void DrawableComposite::setContentArea (const RelativeRectangle& newArea)
  69945. {
  69946. setMarker (contentLeftMarkerName, true, newArea.left);
  69947. setMarker (contentRightMarkerName, true, newArea.right);
  69948. setMarker (contentTopMarkerName, false, newArea.top);
  69949. setMarker (contentBottomMarkerName, false, newArea.bottom);
  69950. }
  69951. void DrawableComposite::resetBoundingBoxToContentArea()
  69952. {
  69953. const RelativeRectangle content (getContentArea());
  69954. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  69955. RelativePoint (content.right, content.top),
  69956. RelativePoint (content.left, content.bottom)));
  69957. }
  69958. void DrawableComposite::resetContentAreaAndBoundingBoxToFitChildren()
  69959. {
  69960. const Rectangle<float> bounds (getUntransformedBounds (false));
  69961. setContentArea (RelativeRectangle (RelativeCoordinate (bounds.getX()),
  69962. RelativeCoordinate (bounds.getRight()),
  69963. RelativeCoordinate (bounds.getY()),
  69964. RelativeCoordinate (bounds.getBottom())));
  69965. resetBoundingBoxToContentArea();
  69966. }
  69967. int DrawableComposite::getNumMarkers (const bool xAxis) const throw()
  69968. {
  69969. return (xAxis ? markersX : markersY).size();
  69970. }
  69971. const DrawableComposite::Marker* DrawableComposite::getMarker (const bool xAxis, const int index) const throw()
  69972. {
  69973. return (xAxis ? markersX : markersY) [index];
  69974. }
  69975. void DrawableComposite::setMarker (const String& name, const bool xAxis, const RelativeCoordinate& position)
  69976. {
  69977. OwnedArray <Marker>& markers = (xAxis ? markersX : markersY);
  69978. for (int i = 0; i < markers.size(); ++i)
  69979. {
  69980. Marker* const m = markers.getUnchecked(i);
  69981. if (m->name == name)
  69982. {
  69983. if (m->position != position)
  69984. {
  69985. m->position = position;
  69986. invalidatePoints();
  69987. }
  69988. return;
  69989. }
  69990. }
  69991. (xAxis ? markersX : markersY).add (new Marker (name, position));
  69992. invalidatePoints();
  69993. }
  69994. void DrawableComposite::removeMarker (const bool xAxis, const int index)
  69995. {
  69996. jassert (index >= 2);
  69997. if (index >= 2)
  69998. (xAxis ? markersX : markersY).remove (index);
  69999. }
  70000. const AffineTransform DrawableComposite::calculateTransform() const
  70001. {
  70002. Point<float> resolved[3];
  70003. bounds.resolveThreePoints (resolved, parent);
  70004. const Rectangle<float> content (getContentArea().resolve (parent));
  70005. return AffineTransform::fromTargetPoints (content.getX(), content.getY(), resolved[0].getX(), resolved[0].getY(),
  70006. content.getRight(), content.getY(), resolved[1].getX(), resolved[1].getY(),
  70007. content.getX(), content.getBottom(), resolved[2].getX(), resolved[2].getY());
  70008. }
  70009. void DrawableComposite::render (const Drawable::RenderingContext& context) const
  70010. {
  70011. if (drawables.size() > 0 && context.opacity > 0)
  70012. {
  70013. if (context.opacity >= 1.0f || drawables.size() == 1)
  70014. {
  70015. Drawable::RenderingContext contextCopy (context);
  70016. contextCopy.transform = calculateTransform().followedBy (context.transform);
  70017. for (int i = 0; i < drawables.size(); ++i)
  70018. drawables.getUnchecked(i)->render (contextCopy);
  70019. }
  70020. else
  70021. {
  70022. // To correctly render a whole composite layer with an overall transparency,
  70023. // we need to render everything opaquely into a temp buffer, then blend that
  70024. // with the target opacity...
  70025. const Rectangle<int> clipBounds (context.g.getClipBounds());
  70026. if (! clipBounds.isEmpty())
  70027. {
  70028. Image tempImage (Image::ARGB, clipBounds.getWidth(), clipBounds.getHeight(), true);
  70029. {
  70030. Graphics tempG (tempImage);
  70031. tempG.setOrigin (-clipBounds.getX(), -clipBounds.getY());
  70032. Drawable::RenderingContext tempContext (tempG, context.transform, 1.0f);
  70033. render (tempContext);
  70034. }
  70035. context.g.setOpacity (context.opacity);
  70036. context.g.drawImageAt (tempImage, clipBounds.getX(), clipBounds.getY());
  70037. }
  70038. }
  70039. }
  70040. }
  70041. const Expression DrawableComposite::getSymbolValue (const String& symbol, const String& member) const
  70042. {
  70043. jassert (member.isEmpty()) // the only symbols available in a Drawable are markers.
  70044. int i;
  70045. for (i = 0; i < markersX.size(); ++i)
  70046. {
  70047. Marker* const m = markersX.getUnchecked(i);
  70048. if (m->name == symbol)
  70049. return m->position.getExpression();
  70050. }
  70051. for (i = 0; i < markersY.size(); ++i)
  70052. {
  70053. Marker* const m = markersY.getUnchecked(i);
  70054. if (m->name == symbol)
  70055. return m->position.getExpression();
  70056. }
  70057. throw Expression::EvaluationError (symbol, member);
  70058. }
  70059. const Rectangle<float> DrawableComposite::getUntransformedBounds (const bool includeMarkers) const
  70060. {
  70061. Rectangle<float> bounds;
  70062. int i;
  70063. for (i = 0; i < drawables.size(); ++i)
  70064. bounds = bounds.getUnion (drawables.getUnchecked(i)->getBounds());
  70065. if (includeMarkers)
  70066. {
  70067. if (markersX.size() > 0)
  70068. {
  70069. float minX = std::numeric_limits<float>::max();
  70070. float maxX = std::numeric_limits<float>::min();
  70071. for (i = markersX.size(); --i >= 0;)
  70072. {
  70073. const Marker* m = markersX.getUnchecked(i);
  70074. const float pos = (float) m->position.resolve (this);
  70075. minX = jmin (minX, pos);
  70076. maxX = jmax (maxX, pos);
  70077. }
  70078. if (minX <= maxX)
  70079. {
  70080. if (bounds.getHeight() > 0)
  70081. {
  70082. minX = jmin (minX, bounds.getX());
  70083. maxX = jmax (maxX, bounds.getRight());
  70084. }
  70085. bounds.setLeft (minX);
  70086. bounds.setWidth (maxX - minX);
  70087. }
  70088. }
  70089. if (markersY.size() > 0)
  70090. {
  70091. float minY = std::numeric_limits<float>::max();
  70092. float maxY = std::numeric_limits<float>::min();
  70093. for (i = markersY.size(); --i >= 0;)
  70094. {
  70095. const Marker* m = markersY.getUnchecked(i);
  70096. const float pos = (float) m->position.resolve (this);
  70097. minY = jmin (minY, pos);
  70098. maxY = jmax (maxY, pos);
  70099. }
  70100. if (minY <= maxY)
  70101. {
  70102. if (bounds.getHeight() > 0)
  70103. {
  70104. minY = jmin (minY, bounds.getY());
  70105. maxY = jmax (maxY, bounds.getBottom());
  70106. }
  70107. bounds.setTop (minY);
  70108. bounds.setHeight (maxY - minY);
  70109. }
  70110. }
  70111. }
  70112. return bounds;
  70113. }
  70114. const Rectangle<float> DrawableComposite::getBounds() const
  70115. {
  70116. return getUntransformedBounds (true).transformed (calculateTransform());
  70117. }
  70118. bool DrawableComposite::hitTest (float x, float y) const
  70119. {
  70120. calculateTransform().inverted().transformPoint (x, y);
  70121. for (int i = 0; i < drawables.size(); ++i)
  70122. if (drawables.getUnchecked(i)->hitTest (x, y))
  70123. return true;
  70124. return false;
  70125. }
  70126. Drawable* DrawableComposite::createCopy() const
  70127. {
  70128. return new DrawableComposite (*this);
  70129. }
  70130. void DrawableComposite::invalidatePoints()
  70131. {
  70132. for (int i = 0; i < drawables.size(); ++i)
  70133. drawables.getUnchecked(i)->invalidatePoints();
  70134. }
  70135. const Identifier DrawableComposite::valueTreeType ("Group");
  70136. const Identifier DrawableComposite::ValueTreeWrapper::topLeft ("topLeft");
  70137. const Identifier DrawableComposite::ValueTreeWrapper::topRight ("topRight");
  70138. const Identifier DrawableComposite::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70139. const Identifier DrawableComposite::ValueTreeWrapper::childGroupTag ("Drawables");
  70140. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagX ("MarkersX");
  70141. const Identifier DrawableComposite::ValueTreeWrapper::markerGroupTagY ("MarkersY");
  70142. const Identifier DrawableComposite::ValueTreeWrapper::markerTag ("Marker");
  70143. const Identifier DrawableComposite::ValueTreeWrapper::nameProperty ("name");
  70144. const Identifier DrawableComposite::ValueTreeWrapper::posProperty ("position");
  70145. DrawableComposite::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70146. : ValueTreeWrapperBase (state_)
  70147. {
  70148. jassert (state.hasType (valueTreeType));
  70149. }
  70150. ValueTree DrawableComposite::ValueTreeWrapper::getChildList() const
  70151. {
  70152. return state.getChildWithName (childGroupTag);
  70153. }
  70154. ValueTree DrawableComposite::ValueTreeWrapper::getChildListCreating (UndoManager* undoManager)
  70155. {
  70156. return state.getOrCreateChildWithName (childGroupTag, undoManager);
  70157. }
  70158. int DrawableComposite::ValueTreeWrapper::getNumDrawables() const
  70159. {
  70160. return getChildList().getNumChildren();
  70161. }
  70162. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableState (int index) const
  70163. {
  70164. return getChildList().getChild (index);
  70165. }
  70166. ValueTree DrawableComposite::ValueTreeWrapper::getDrawableWithId (const String& objectId, bool recursive) const
  70167. {
  70168. if (getID() == objectId)
  70169. return state;
  70170. if (! recursive)
  70171. {
  70172. return getChildList().getChildWithProperty (idProperty, objectId);
  70173. }
  70174. else
  70175. {
  70176. const ValueTree childList (getChildList());
  70177. for (int i = getNumDrawables(); --i >= 0;)
  70178. {
  70179. const ValueTree& child = childList.getChild (i);
  70180. if (child [Drawable::ValueTreeWrapperBase::idProperty] == objectId)
  70181. return child;
  70182. if (child.hasType (DrawableComposite::valueTreeType))
  70183. {
  70184. ValueTree v (DrawableComposite::ValueTreeWrapper (child).getDrawableWithId (objectId, true));
  70185. if (v.isValid())
  70186. return v;
  70187. }
  70188. }
  70189. return ValueTree::invalid;
  70190. }
  70191. }
  70192. int DrawableComposite::ValueTreeWrapper::indexOfDrawable (const ValueTree& item) const
  70193. {
  70194. return getChildList().indexOf (item);
  70195. }
  70196. void DrawableComposite::ValueTreeWrapper::addDrawable (const ValueTree& newDrawableState, int index, UndoManager* undoManager)
  70197. {
  70198. getChildListCreating (undoManager).addChild (newDrawableState, index, undoManager);
  70199. }
  70200. void DrawableComposite::ValueTreeWrapper::moveDrawableOrder (int currentIndex, int newIndex, UndoManager* undoManager)
  70201. {
  70202. getChildListCreating (undoManager).moveChild (currentIndex, newIndex, undoManager);
  70203. }
  70204. void DrawableComposite::ValueTreeWrapper::removeDrawable (const ValueTree& child, UndoManager* undoManager)
  70205. {
  70206. getChildList().removeChild (child, undoManager);
  70207. }
  70208. const RelativeParallelogram DrawableComposite::ValueTreeWrapper::getBoundingBox() const
  70209. {
  70210. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70211. state.getProperty (topRight, "100, 0"),
  70212. state.getProperty (bottomLeft, "0, 100"));
  70213. }
  70214. void DrawableComposite::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70215. {
  70216. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70217. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70218. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70219. }
  70220. void DrawableComposite::ValueTreeWrapper::resetBoundingBoxToContentArea (UndoManager* undoManager)
  70221. {
  70222. const RelativeRectangle content (getContentArea());
  70223. setBoundingBox (RelativeParallelogram (RelativePoint (content.left, content.top),
  70224. RelativePoint (content.right, content.top),
  70225. RelativePoint (content.left, content.bottom)), undoManager);
  70226. }
  70227. const RelativeRectangle DrawableComposite::ValueTreeWrapper::getContentArea() const
  70228. {
  70229. return RelativeRectangle (getMarker (true, getMarkerState (true, 0)).position,
  70230. getMarker (true, getMarkerState (true, 1)).position,
  70231. getMarker (false, getMarkerState (false, 0)).position,
  70232. getMarker (false, getMarkerState (false, 1)).position);
  70233. }
  70234. void DrawableComposite::ValueTreeWrapper::setContentArea (const RelativeRectangle& newArea, UndoManager* undoManager)
  70235. {
  70236. setMarker (true, Marker (contentLeftMarkerName, newArea.left), undoManager);
  70237. setMarker (true, Marker (contentRightMarkerName, newArea.right), undoManager);
  70238. setMarker (false, Marker (contentTopMarkerName, newArea.top), undoManager);
  70239. setMarker (false, Marker (contentBottomMarkerName, newArea.bottom), undoManager);
  70240. }
  70241. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerList (bool xAxis) const
  70242. {
  70243. return state.getChildWithName (xAxis ? markerGroupTagX : markerGroupTagY);
  70244. }
  70245. ValueTree DrawableComposite::ValueTreeWrapper::getMarkerListCreating (bool xAxis, UndoManager* undoManager)
  70246. {
  70247. return state.getOrCreateChildWithName (xAxis ? markerGroupTagX : markerGroupTagY, undoManager);
  70248. }
  70249. int DrawableComposite::ValueTreeWrapper::getNumMarkers (bool xAxis) const
  70250. {
  70251. return getMarkerList (xAxis).getNumChildren();
  70252. }
  70253. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, int index) const
  70254. {
  70255. return getMarkerList (xAxis).getChild (index);
  70256. }
  70257. const ValueTree DrawableComposite::ValueTreeWrapper::getMarkerState (bool xAxis, const String& name) const
  70258. {
  70259. return getMarkerList (xAxis).getChildWithProperty (nameProperty, name);
  70260. }
  70261. bool DrawableComposite::ValueTreeWrapper::containsMarker (bool xAxis, const ValueTree& state) const
  70262. {
  70263. return state.isAChildOf (getMarkerList (xAxis));
  70264. }
  70265. const DrawableComposite::Marker DrawableComposite::ValueTreeWrapper::getMarker (bool xAxis, const ValueTree& state) const
  70266. {
  70267. (void) xAxis;
  70268. jassert (containsMarker (xAxis, state));
  70269. return Marker (state [nameProperty], RelativeCoordinate (state [posProperty].toString()));
  70270. }
  70271. void DrawableComposite::ValueTreeWrapper::setMarker (bool xAxis, const Marker& m, UndoManager* undoManager)
  70272. {
  70273. ValueTree markerList (getMarkerListCreating (xAxis, undoManager));
  70274. ValueTree marker (markerList.getChildWithProperty (nameProperty, m.name));
  70275. if (marker.isValid())
  70276. {
  70277. marker.setProperty (posProperty, m.position.toString(), undoManager);
  70278. }
  70279. else
  70280. {
  70281. marker = ValueTree (markerTag);
  70282. marker.setProperty (nameProperty, m.name, 0);
  70283. marker.setProperty (posProperty, m.position.toString(), 0);
  70284. markerList.addChild (marker, -1, undoManager);
  70285. }
  70286. }
  70287. void DrawableComposite::ValueTreeWrapper::removeMarker (bool xAxis, const ValueTree& state, UndoManager* undoManager)
  70288. {
  70289. if (state [nameProperty].toString() != contentLeftMarkerName
  70290. && state [nameProperty].toString() != contentRightMarkerName
  70291. && state [nameProperty].toString() != contentTopMarkerName
  70292. && state [nameProperty].toString() != contentBottomMarkerName)
  70293. return getMarkerList (xAxis).removeChild (state, undoManager);
  70294. }
  70295. const Rectangle<float> DrawableComposite::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70296. {
  70297. const ValueTreeWrapper wrapper (tree);
  70298. setName (wrapper.getID());
  70299. Rectangle<float> damage;
  70300. bool redrawAll = false;
  70301. const RelativeParallelogram newBounds (wrapper.getBoundingBox());
  70302. if (bounds != newBounds)
  70303. {
  70304. redrawAll = true;
  70305. damage = getBounds();
  70306. bounds = newBounds;
  70307. }
  70308. const int numMarkersX = wrapper.getNumMarkers (true);
  70309. const int numMarkersY = wrapper.getNumMarkers (false);
  70310. // Remove deleted markers...
  70311. if (markersX.size() > numMarkersX || markersY.size() > numMarkersY)
  70312. {
  70313. if (! redrawAll)
  70314. {
  70315. redrawAll = true;
  70316. damage = getBounds();
  70317. }
  70318. markersX.removeRange (jmax (2, numMarkersX), markersX.size());
  70319. markersY.removeRange (jmax (2, numMarkersY), markersY.size());
  70320. }
  70321. // Update markers and add new ones..
  70322. int i;
  70323. for (i = 0; i < numMarkersX; ++i)
  70324. {
  70325. const Marker newMarker (wrapper.getMarker (true, wrapper.getMarkerState (true, i)));
  70326. Marker* m = markersX[i];
  70327. if (m == 0 || newMarker != *m)
  70328. {
  70329. if (! redrawAll)
  70330. {
  70331. redrawAll = true;
  70332. damage = getBounds();
  70333. }
  70334. if (m == 0)
  70335. markersX.add (new Marker (newMarker));
  70336. else
  70337. *m = newMarker;
  70338. }
  70339. }
  70340. for (i = 0; i < numMarkersY; ++i)
  70341. {
  70342. const Marker newMarker (wrapper.getMarker (false, wrapper.getMarkerState (false, i)));
  70343. Marker* m = markersY[i];
  70344. if (m == 0 || newMarker != *m)
  70345. {
  70346. if (! redrawAll)
  70347. {
  70348. redrawAll = true;
  70349. damage = getBounds();
  70350. }
  70351. if (m == 0)
  70352. markersY.add (new Marker (newMarker));
  70353. else
  70354. *m = newMarker;
  70355. }
  70356. }
  70357. // Remove deleted drawables..
  70358. for (i = drawables.size(); --i >= wrapper.getNumDrawables();)
  70359. {
  70360. Drawable* const d = drawables.getUnchecked(i);
  70361. if (! redrawAll)
  70362. damage = damage.getUnion (d->getBounds());
  70363. d->parent = 0;
  70364. drawables.remove (i);
  70365. }
  70366. // Update drawables and add new ones..
  70367. for (i = 0; i < wrapper.getNumDrawables(); ++i)
  70368. {
  70369. const ValueTree newDrawable (wrapper.getDrawableState (i));
  70370. Drawable* d = drawables[i];
  70371. if (d != 0)
  70372. {
  70373. if (newDrawable.hasType (d->getValueTreeType()))
  70374. {
  70375. const Rectangle<float> area (d->refreshFromValueTree (newDrawable, imageProvider));
  70376. if (! redrawAll)
  70377. damage = damage.getUnion (area);
  70378. }
  70379. else
  70380. {
  70381. if (! redrawAll)
  70382. damage = damage.getUnion (d->getBounds());
  70383. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70384. drawables.set (i, d);
  70385. if (! redrawAll)
  70386. damage = damage.getUnion (d->getBounds());
  70387. }
  70388. }
  70389. else
  70390. {
  70391. d = createChildFromValueTree (this, newDrawable, imageProvider);
  70392. drawables.set (i, d);
  70393. if (! redrawAll)
  70394. damage = damage.getUnion (d->getBounds());
  70395. }
  70396. }
  70397. invalidatePoints();
  70398. if (redrawAll)
  70399. damage = damage.getUnion (getBounds());
  70400. else if (! damage.isEmpty())
  70401. damage = damage.transformed (calculateTransform());
  70402. return damage;
  70403. }
  70404. const ValueTree DrawableComposite::createValueTree (ImageProvider* imageProvider) const
  70405. {
  70406. ValueTree tree (valueTreeType);
  70407. ValueTreeWrapper v (tree);
  70408. v.setID (getName(), 0);
  70409. v.setBoundingBox (bounds, 0);
  70410. int i;
  70411. for (i = 0; i < drawables.size(); ++i)
  70412. v.addDrawable (drawables.getUnchecked(i)->createValueTree (imageProvider), -1, 0);
  70413. for (i = 0; i < markersX.size(); ++i)
  70414. v.setMarker (true, *markersX.getUnchecked(i), 0);
  70415. for (i = 0; i < markersY.size(); ++i)
  70416. v.setMarker (false, *markersY.getUnchecked(i), 0);
  70417. return tree;
  70418. }
  70419. END_JUCE_NAMESPACE
  70420. /*** End of inlined file: juce_DrawableComposite.cpp ***/
  70421. /*** Start of inlined file: juce_DrawableImage.cpp ***/
  70422. BEGIN_JUCE_NAMESPACE
  70423. DrawableImage::DrawableImage()
  70424. : image (0),
  70425. opacity (1.0f),
  70426. overlayColour (0x00000000)
  70427. {
  70428. bounds.topRight = RelativePoint (Point<float> (1.0f, 0.0f));
  70429. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, 1.0f));
  70430. }
  70431. DrawableImage::DrawableImage (const DrawableImage& other)
  70432. : image (other.image),
  70433. opacity (other.opacity),
  70434. overlayColour (other.overlayColour),
  70435. bounds (other.bounds)
  70436. {
  70437. }
  70438. DrawableImage::~DrawableImage()
  70439. {
  70440. }
  70441. void DrawableImage::setImage (const Image& imageToUse)
  70442. {
  70443. image = imageToUse;
  70444. if (image.isValid())
  70445. {
  70446. bounds.topLeft = RelativePoint (Point<float> (0.0f, 0.0f));
  70447. bounds.topRight = RelativePoint (Point<float> ((float) image.getWidth(), 0.0f));
  70448. bounds.bottomLeft = RelativePoint (Point<float> (0.0f, (float) image.getHeight()));
  70449. }
  70450. }
  70451. void DrawableImage::setOpacity (const float newOpacity)
  70452. {
  70453. opacity = newOpacity;
  70454. }
  70455. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  70456. {
  70457. overlayColour = newOverlayColour;
  70458. }
  70459. void DrawableImage::setBoundingBox (const RelativeParallelogram& newBounds)
  70460. {
  70461. bounds = newBounds;
  70462. }
  70463. const AffineTransform DrawableImage::calculateTransform() const
  70464. {
  70465. if (image.isNull())
  70466. return AffineTransform::identity;
  70467. Point<float> resolved[3];
  70468. bounds.resolveThreePoints (resolved, parent);
  70469. const Point<float> tr (resolved[0] + (resolved[1] - resolved[0]) / (float) image.getWidth());
  70470. const Point<float> bl (resolved[0] + (resolved[2] - resolved[0]) / (float) image.getHeight());
  70471. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  70472. tr.getX(), tr.getY(),
  70473. bl.getX(), bl.getY());
  70474. }
  70475. void DrawableImage::render (const Drawable::RenderingContext& context) const
  70476. {
  70477. if (image.isValid())
  70478. {
  70479. const AffineTransform t (calculateTransform().followedBy (context.transform));
  70480. if (opacity > 0.0f && ! overlayColour.isOpaque())
  70481. {
  70482. context.g.setOpacity (context.opacity * opacity);
  70483. context.g.drawImageTransformed (image, t, false);
  70484. }
  70485. if (! overlayColour.isTransparent())
  70486. {
  70487. context.g.setColour (overlayColour.withMultipliedAlpha (context.opacity));
  70488. context.g.drawImageTransformed (image, t, true);
  70489. }
  70490. }
  70491. }
  70492. const Rectangle<float> DrawableImage::getBounds() const
  70493. {
  70494. if (image.isNull())
  70495. return Rectangle<float>();
  70496. return bounds.getBounds (parent);
  70497. }
  70498. bool DrawableImage::hitTest (float x, float y) const
  70499. {
  70500. if (image.isNull())
  70501. return false;
  70502. calculateTransform().inverted().transformPoint (x, y);
  70503. const int ix = roundToInt (x);
  70504. const int iy = roundToInt (y);
  70505. return ix >= 0
  70506. && iy >= 0
  70507. && ix < image.getWidth()
  70508. && iy < image.getHeight()
  70509. && image.getPixelAt (ix, iy).getAlpha() >= 127;
  70510. }
  70511. Drawable* DrawableImage::createCopy() const
  70512. {
  70513. return new DrawableImage (*this);
  70514. }
  70515. void DrawableImage::invalidatePoints()
  70516. {
  70517. }
  70518. const Identifier DrawableImage::valueTreeType ("Image");
  70519. const Identifier DrawableImage::ValueTreeWrapper::opacity ("opacity");
  70520. const Identifier DrawableImage::ValueTreeWrapper::overlay ("overlay");
  70521. const Identifier DrawableImage::ValueTreeWrapper::image ("image");
  70522. const Identifier DrawableImage::ValueTreeWrapper::topLeft ("topLeft");
  70523. const Identifier DrawableImage::ValueTreeWrapper::topRight ("topRight");
  70524. const Identifier DrawableImage::ValueTreeWrapper::bottomLeft ("bottomLeft");
  70525. DrawableImage::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70526. : ValueTreeWrapperBase (state_)
  70527. {
  70528. jassert (state.hasType (valueTreeType));
  70529. }
  70530. const var DrawableImage::ValueTreeWrapper::getImageIdentifier() const
  70531. {
  70532. return state [image];
  70533. }
  70534. Value DrawableImage::ValueTreeWrapper::getImageIdentifierValue (UndoManager* undoManager)
  70535. {
  70536. return state.getPropertyAsValue (image, undoManager);
  70537. }
  70538. void DrawableImage::ValueTreeWrapper::setImageIdentifier (const var& newIdentifier, UndoManager* undoManager)
  70539. {
  70540. state.setProperty (image, newIdentifier, undoManager);
  70541. }
  70542. float DrawableImage::ValueTreeWrapper::getOpacity() const
  70543. {
  70544. return (float) state.getProperty (opacity, 1.0);
  70545. }
  70546. Value DrawableImage::ValueTreeWrapper::getOpacityValue (UndoManager* undoManager)
  70547. {
  70548. if (! state.hasProperty (opacity))
  70549. state.setProperty (opacity, 1.0, undoManager);
  70550. return state.getPropertyAsValue (opacity, undoManager);
  70551. }
  70552. void DrawableImage::ValueTreeWrapper::setOpacity (float newOpacity, UndoManager* undoManager)
  70553. {
  70554. state.setProperty (opacity, newOpacity, undoManager);
  70555. }
  70556. const Colour DrawableImage::ValueTreeWrapper::getOverlayColour() const
  70557. {
  70558. return Colour (state [overlay].toString().getHexValue32());
  70559. }
  70560. void DrawableImage::ValueTreeWrapper::setOverlayColour (const Colour& newColour, UndoManager* undoManager)
  70561. {
  70562. if (newColour.isTransparent())
  70563. state.removeProperty (overlay, undoManager);
  70564. else
  70565. state.setProperty (overlay, String::toHexString ((int) newColour.getARGB()), undoManager);
  70566. }
  70567. Value DrawableImage::ValueTreeWrapper::getOverlayColourValue (UndoManager* undoManager)
  70568. {
  70569. return state.getPropertyAsValue (overlay, undoManager);
  70570. }
  70571. const RelativeParallelogram DrawableImage::ValueTreeWrapper::getBoundingBox() const
  70572. {
  70573. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  70574. state.getProperty (topRight, "100, 0"),
  70575. state.getProperty (bottomLeft, "0, 100"));
  70576. }
  70577. void DrawableImage::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  70578. {
  70579. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  70580. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  70581. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  70582. }
  70583. const Rectangle<float> DrawableImage::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70584. {
  70585. const ValueTreeWrapper controller (tree);
  70586. setName (controller.getID());
  70587. const float newOpacity = controller.getOpacity();
  70588. const Colour newOverlayColour (controller.getOverlayColour());
  70589. Image newImage;
  70590. const var imageIdentifier (controller.getImageIdentifier());
  70591. jassert (imageProvider != 0 || imageIdentifier.isVoid()); // if you're using images, you need to provide something that can load and save them!
  70592. if (imageProvider != 0)
  70593. newImage = imageProvider->getImageForIdentifier (imageIdentifier);
  70594. const RelativeParallelogram newBounds (controller.getBoundingBox());
  70595. if (newOpacity != opacity || overlayColour != newOverlayColour || image != newImage || bounds != newBounds)
  70596. {
  70597. const Rectangle<float> damage (getBounds());
  70598. opacity = newOpacity;
  70599. overlayColour = newOverlayColour;
  70600. bounds = newBounds;
  70601. image = newImage;
  70602. return damage.getUnion (getBounds());
  70603. }
  70604. return Rectangle<float>();
  70605. }
  70606. const ValueTree DrawableImage::createValueTree (ImageProvider* imageProvider) const
  70607. {
  70608. ValueTree tree (valueTreeType);
  70609. ValueTreeWrapper v (tree);
  70610. v.setID (getName(), 0);
  70611. v.setOpacity (opacity, 0);
  70612. v.setOverlayColour (overlayColour, 0);
  70613. v.setBoundingBox (bounds, 0);
  70614. if (image.isValid())
  70615. {
  70616. jassert (imageProvider != 0); // if you're using images, you need to provide something that can load and save them!
  70617. if (imageProvider != 0)
  70618. v.setImageIdentifier (imageProvider->getIdentifierForImage (image), 0);
  70619. }
  70620. return tree;
  70621. }
  70622. END_JUCE_NAMESPACE
  70623. /*** End of inlined file: juce_DrawableImage.cpp ***/
  70624. /*** Start of inlined file: juce_DrawablePath.cpp ***/
  70625. BEGIN_JUCE_NAMESPACE
  70626. DrawablePath::DrawablePath()
  70627. {
  70628. }
  70629. DrawablePath::DrawablePath (const DrawablePath& other)
  70630. : DrawableShape (other)
  70631. {
  70632. if (other.relativePath != 0)
  70633. relativePath = new RelativePointPath (*other.relativePath);
  70634. else
  70635. cachedPath = other.cachedPath;
  70636. }
  70637. DrawablePath::~DrawablePath()
  70638. {
  70639. }
  70640. Drawable* DrawablePath::createCopy() const
  70641. {
  70642. return new DrawablePath (*this);
  70643. }
  70644. void DrawablePath::setPath (const Path& newPath)
  70645. {
  70646. cachedPath = newPath;
  70647. strokeChanged();
  70648. }
  70649. const Path& DrawablePath::getPath() const
  70650. {
  70651. return getCachedPath();
  70652. }
  70653. const Path& DrawablePath::getStrokePath() const
  70654. {
  70655. return getCachedStrokePath();
  70656. }
  70657. bool DrawablePath::rebuildPath (Path& path) const
  70658. {
  70659. if (relativePath != 0)
  70660. {
  70661. path.clear();
  70662. relativePath->createPath (path, parent);
  70663. return true;
  70664. }
  70665. return false;
  70666. }
  70667. const Identifier DrawablePath::valueTreeType ("Path");
  70668. const Identifier DrawablePath::ValueTreeWrapper::nonZeroWinding ("nonZeroWinding");
  70669. const Identifier DrawablePath::ValueTreeWrapper::point1 ("p1");
  70670. const Identifier DrawablePath::ValueTreeWrapper::point2 ("p2");
  70671. const Identifier DrawablePath::ValueTreeWrapper::point3 ("p3");
  70672. DrawablePath::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  70673. : FillAndStrokeState (state_)
  70674. {
  70675. jassert (state.hasType (valueTreeType));
  70676. }
  70677. ValueTree DrawablePath::ValueTreeWrapper::getPathState()
  70678. {
  70679. return state.getOrCreateChildWithName (path, 0);
  70680. }
  70681. bool DrawablePath::ValueTreeWrapper::usesNonZeroWinding() const
  70682. {
  70683. return state [nonZeroWinding];
  70684. }
  70685. void DrawablePath::ValueTreeWrapper::setUsesNonZeroWinding (bool b, UndoManager* undoManager)
  70686. {
  70687. state.setProperty (nonZeroWinding, b, undoManager);
  70688. }
  70689. const Identifier DrawablePath::ValueTreeWrapper::Element::mode ("mode");
  70690. const Identifier DrawablePath::ValueTreeWrapper::Element::startSubPathElement ("Move");
  70691. const Identifier DrawablePath::ValueTreeWrapper::Element::closeSubPathElement ("Close");
  70692. const Identifier DrawablePath::ValueTreeWrapper::Element::lineToElement ("Line");
  70693. const Identifier DrawablePath::ValueTreeWrapper::Element::quadraticToElement ("Quad");
  70694. const Identifier DrawablePath::ValueTreeWrapper::Element::cubicToElement ("Cubic");
  70695. const char* DrawablePath::ValueTreeWrapper::Element::cornerMode = "corner";
  70696. const char* DrawablePath::ValueTreeWrapper::Element::roundedMode = "round";
  70697. const char* DrawablePath::ValueTreeWrapper::Element::symmetricMode = "symm";
  70698. DrawablePath::ValueTreeWrapper::Element::Element (const ValueTree& state_)
  70699. : state (state_)
  70700. {
  70701. }
  70702. DrawablePath::ValueTreeWrapper::Element::~Element()
  70703. {
  70704. }
  70705. DrawablePath::ValueTreeWrapper DrawablePath::ValueTreeWrapper::Element::getParent() const
  70706. {
  70707. return ValueTreeWrapper (state.getParent().getParent());
  70708. }
  70709. DrawablePath::ValueTreeWrapper::Element DrawablePath::ValueTreeWrapper::Element::getPreviousElement() const
  70710. {
  70711. return Element (state.getSibling (-1));
  70712. }
  70713. int DrawablePath::ValueTreeWrapper::Element::getNumControlPoints() const throw()
  70714. {
  70715. const Identifier i (state.getType());
  70716. if (i == startSubPathElement || i == lineToElement) return 1;
  70717. if (i == quadraticToElement) return 2;
  70718. if (i == cubicToElement) return 3;
  70719. return 0;
  70720. }
  70721. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getControlPoint (const int index) const
  70722. {
  70723. jassert (index >= 0 && index < getNumControlPoints());
  70724. return RelativePoint (state [index == 0 ? point1 : (index == 1 ? point2 : point3)].toString());
  70725. }
  70726. Value DrawablePath::ValueTreeWrapper::Element::getControlPointValue (int index, UndoManager* undoManager) const
  70727. {
  70728. jassert (index >= 0 && index < getNumControlPoints());
  70729. return state.getPropertyAsValue (index == 0 ? point1 : (index == 1 ? point2 : point3), undoManager);
  70730. }
  70731. void DrawablePath::ValueTreeWrapper::Element::setControlPoint (const int index, const RelativePoint& point, UndoManager* undoManager)
  70732. {
  70733. jassert (index >= 0 && index < getNumControlPoints());
  70734. return state.setProperty (index == 0 ? point1 : (index == 1 ? point2 : point3), point.toString(), undoManager);
  70735. }
  70736. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getStartPoint() const
  70737. {
  70738. const Identifier i (state.getType());
  70739. if (i == startSubPathElement)
  70740. return getControlPoint (0);
  70741. jassert (i == lineToElement || i == quadraticToElement || i == cubicToElement || i == closeSubPathElement);
  70742. return getPreviousElement().getEndPoint();
  70743. }
  70744. const RelativePoint DrawablePath::ValueTreeWrapper::Element::getEndPoint() const
  70745. {
  70746. const Identifier i (state.getType());
  70747. if (i == startSubPathElement || i == lineToElement) return getControlPoint (0);
  70748. if (i == quadraticToElement) return getControlPoint (1);
  70749. if (i == cubicToElement) return getControlPoint (2);
  70750. jassert (i == closeSubPathElement);
  70751. return RelativePoint();
  70752. }
  70753. float DrawablePath::ValueTreeWrapper::Element::getLength (Expression::EvaluationContext* nameFinder) const
  70754. {
  70755. const Identifier i (state.getType());
  70756. if (i == lineToElement || i == closeSubPathElement)
  70757. return getEndPoint().resolve (nameFinder).getDistanceFrom (getStartPoint().resolve (nameFinder));
  70758. if (i == cubicToElement)
  70759. {
  70760. Path p;
  70761. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70762. p.cubicTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder), getControlPoint (2).resolve (nameFinder));
  70763. return p.getLength();
  70764. }
  70765. if (i == quadraticToElement)
  70766. {
  70767. Path p;
  70768. p.startNewSubPath (getStartPoint().resolve (nameFinder));
  70769. p.quadraticTo (getControlPoint (0).resolve (nameFinder), getControlPoint (1).resolve (nameFinder));
  70770. return p.getLength();
  70771. }
  70772. jassert (i == startSubPathElement);
  70773. return 0;
  70774. }
  70775. const String DrawablePath::ValueTreeWrapper::Element::getModeOfEndPoint() const
  70776. {
  70777. return state [mode].toString();
  70778. }
  70779. void DrawablePath::ValueTreeWrapper::Element::setModeOfEndPoint (const String& newMode, UndoManager* undoManager)
  70780. {
  70781. if (state.hasType (cubicToElement))
  70782. state.setProperty (mode, newMode, undoManager);
  70783. }
  70784. void DrawablePath::ValueTreeWrapper::Element::convertToLine (UndoManager* undoManager)
  70785. {
  70786. const Identifier i (state.getType());
  70787. if (i == quadraticToElement || i == cubicToElement)
  70788. {
  70789. ValueTree newState (lineToElement);
  70790. Element e (newState);
  70791. e.setControlPoint (0, getEndPoint(), undoManager);
  70792. state = newState;
  70793. }
  70794. }
  70795. void DrawablePath::ValueTreeWrapper::Element::convertToCubic (Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70796. {
  70797. const Identifier i (state.getType());
  70798. if (i == lineToElement || i == quadraticToElement)
  70799. {
  70800. ValueTree newState (cubicToElement);
  70801. Element e (newState);
  70802. const RelativePoint start (getStartPoint());
  70803. const RelativePoint end (getEndPoint());
  70804. const Point<float> startResolved (start.resolve (nameFinder));
  70805. const Point<float> endResolved (end.resolve (nameFinder));
  70806. e.setControlPoint (0, startResolved + (endResolved - startResolved) * 0.3f, undoManager);
  70807. e.setControlPoint (1, startResolved + (endResolved - startResolved) * 0.7f, undoManager);
  70808. e.setControlPoint (2, end, undoManager);
  70809. state = newState;
  70810. }
  70811. }
  70812. void DrawablePath::ValueTreeWrapper::Element::convertToPathBreak (UndoManager* undoManager)
  70813. {
  70814. const Identifier i (state.getType());
  70815. if (i != startSubPathElement)
  70816. {
  70817. ValueTree newState (startSubPathElement);
  70818. Element e (newState);
  70819. e.setControlPoint (0, getEndPoint(), undoManager);
  70820. state = newState;
  70821. }
  70822. }
  70823. namespace DrawablePathHelpers
  70824. {
  70825. const Point<float> findCubicSubdivisionPoint (float proportion, const Point<float> points[4])
  70826. {
  70827. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70828. mid2 (points[1] + (points[2] - points[1]) * proportion),
  70829. mid3 (points[2] + (points[3] - points[2]) * proportion);
  70830. const Point<float> newCp1 (mid1 + (mid2 - mid1) * proportion),
  70831. newCp2 (mid2 + (mid3 - mid2) * proportion);
  70832. return newCp1 + (newCp2 - newCp1) * proportion;
  70833. }
  70834. const Point<float> findQuadraticSubdivisionPoint (float proportion, const Point<float> points[3])
  70835. {
  70836. const Point<float> mid1 (points[0] + (points[1] - points[0]) * proportion),
  70837. mid2 (points[1] + (points[2] - points[1]) * proportion);
  70838. return mid1 + (mid2 - mid1) * proportion;
  70839. }
  70840. }
  70841. float DrawablePath::ValueTreeWrapper::Element::findProportionAlongLine (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder) const
  70842. {
  70843. using namespace DrawablePathHelpers;
  70844. const Identifier i (state.getType());
  70845. float bestProp = 0;
  70846. if (i == cubicToElement)
  70847. {
  70848. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70849. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70850. float bestDistance = std::numeric_limits<float>::max();
  70851. for (int i = 110; --i >= 0;)
  70852. {
  70853. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70854. const Point<float> centre (findCubicSubdivisionPoint (prop, points));
  70855. const float distance = centre.getDistanceFrom (targetPoint);
  70856. if (distance < bestDistance)
  70857. {
  70858. bestProp = prop;
  70859. bestDistance = distance;
  70860. }
  70861. }
  70862. }
  70863. else if (i == quadraticToElement)
  70864. {
  70865. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70866. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70867. float bestDistance = std::numeric_limits<float>::max();
  70868. for (int i = 110; --i >= 0;)
  70869. {
  70870. float prop = i > 10 ? ((i - 10) / 100.0f) : (bestProp + ((i - 5) / 1000.0f));
  70871. const Point<float> centre (findQuadraticSubdivisionPoint ((float) prop, points));
  70872. const float distance = centre.getDistanceFrom (targetPoint);
  70873. if (distance < bestDistance)
  70874. {
  70875. bestProp = prop;
  70876. bestDistance = distance;
  70877. }
  70878. }
  70879. }
  70880. else if (i == lineToElement)
  70881. {
  70882. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70883. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70884. bestProp = line.findNearestProportionalPositionTo (targetPoint);
  70885. }
  70886. return bestProp;
  70887. }
  70888. ValueTree DrawablePath::ValueTreeWrapper::Element::insertPoint (const Point<float>& targetPoint, Expression::EvaluationContext* nameFinder, UndoManager* undoManager)
  70889. {
  70890. ValueTree newTree;
  70891. const Identifier i (state.getType());
  70892. if (i == cubicToElement)
  70893. {
  70894. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70895. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getControlPoint (1)), rp4 (getEndPoint());
  70896. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder), rp4.resolve (nameFinder) };
  70897. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70898. mid2 (points[1] + (points[2] - points[1]) * bestProp),
  70899. mid3 (points[2] + (points[3] - points[2]) * bestProp);
  70900. const Point<float> newCp1 (mid1 + (mid2 - mid1) * bestProp),
  70901. newCp2 (mid2 + (mid3 - mid2) * bestProp);
  70902. const Point<float> newCentre (newCp1 + (newCp2 - newCp1) * bestProp);
  70903. setControlPoint (0, mid1, undoManager);
  70904. setControlPoint (1, newCp1, undoManager);
  70905. setControlPoint (2, newCentre, undoManager);
  70906. setModeOfEndPoint (roundedMode, undoManager);
  70907. Element newElement (newTree = ValueTree (cubicToElement));
  70908. newElement.setControlPoint (0, newCp2, 0);
  70909. newElement.setControlPoint (1, mid3, 0);
  70910. newElement.setControlPoint (2, rp4, 0);
  70911. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70912. }
  70913. else if (i == quadraticToElement)
  70914. {
  70915. float bestProp = findProportionAlongLine (targetPoint, nameFinder);
  70916. RelativePoint rp1 (getStartPoint()), rp2 (getControlPoint (0)), rp3 (getEndPoint());
  70917. const Point<float> points[] = { rp1.resolve (nameFinder), rp2.resolve (nameFinder), rp3.resolve (nameFinder) };
  70918. const Point<float> mid1 (points[0] + (points[1] - points[0]) * bestProp),
  70919. mid2 (points[1] + (points[2] - points[1]) * bestProp);
  70920. const Point<float> newCentre (mid1 + (mid2 - mid1) * bestProp);
  70921. setControlPoint (0, mid1, undoManager);
  70922. setControlPoint (1, newCentre, undoManager);
  70923. setModeOfEndPoint (roundedMode, undoManager);
  70924. Element newElement (newTree = ValueTree (quadraticToElement));
  70925. newElement.setControlPoint (0, mid2, 0);
  70926. newElement.setControlPoint (1, rp3, 0);
  70927. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70928. }
  70929. else if (i == lineToElement)
  70930. {
  70931. RelativePoint rp1 (getStartPoint()), rp2 (getEndPoint());
  70932. const Line<float> line (rp1.resolve (nameFinder), rp2.resolve (nameFinder));
  70933. const Point<float> newPoint (line.findNearestPointTo (targetPoint));
  70934. setControlPoint (0, newPoint, undoManager);
  70935. Element newElement (newTree = ValueTree (lineToElement));
  70936. newElement.setControlPoint (0, rp2, 0);
  70937. state.getParent().addChild (newTree, state.getParent().indexOf (state) + 1, undoManager);
  70938. }
  70939. else if (i == closeSubPathElement)
  70940. {
  70941. }
  70942. return newTree;
  70943. }
  70944. void DrawablePath::ValueTreeWrapper::Element::removePoint (UndoManager* undoManager)
  70945. {
  70946. state.getParent().removeChild (state, undoManager);
  70947. }
  70948. const Rectangle<float> DrawablePath::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  70949. {
  70950. Rectangle<float> damageRect;
  70951. ValueTreeWrapper v (tree);
  70952. setName (v.getID());
  70953. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  70954. ScopedPointer<RelativePointPath> newRelativePath (new RelativePointPath (tree));
  70955. Path newPath;
  70956. newRelativePath->createPath (newPath, parent);
  70957. if (! newRelativePath->containsAnyDynamicPoints())
  70958. newRelativePath = 0;
  70959. const PathStrokeType newStroke (v.getStrokeType());
  70960. if (strokeType != newStroke || cachedPath != newPath)
  70961. {
  70962. damageRect = getBounds();
  70963. cachedPath.swapWithPath (newPath);
  70964. strokeChanged();
  70965. strokeType = newStroke;
  70966. needsRedraw = true;
  70967. }
  70968. relativePath = newRelativePath;
  70969. if (needsRedraw)
  70970. damageRect = damageRect.getUnion (getBounds());
  70971. return damageRect;
  70972. }
  70973. const ValueTree DrawablePath::createValueTree (ImageProvider* imageProvider) const
  70974. {
  70975. ValueTree tree (valueTreeType);
  70976. ValueTreeWrapper v (tree);
  70977. v.setID (getName(), 0);
  70978. writeTo (v, imageProvider, 0);
  70979. if (relativePath != 0)
  70980. {
  70981. relativePath->writeTo (tree, 0);
  70982. }
  70983. else
  70984. {
  70985. RelativePointPath rp (getCachedPath());
  70986. rp.writeTo (tree, 0);
  70987. }
  70988. return tree;
  70989. }
  70990. END_JUCE_NAMESPACE
  70991. /*** End of inlined file: juce_DrawablePath.cpp ***/
  70992. /*** Start of inlined file: juce_DrawableRectangle.cpp ***/
  70993. BEGIN_JUCE_NAMESPACE
  70994. DrawableRectangle::DrawableRectangle()
  70995. {
  70996. }
  70997. DrawableRectangle::DrawableRectangle (const DrawableRectangle& other)
  70998. : DrawableShape (other)
  70999. {
  71000. }
  71001. DrawableRectangle::~DrawableRectangle()
  71002. {
  71003. }
  71004. Drawable* DrawableRectangle::createCopy() const
  71005. {
  71006. return new DrawableRectangle (*this);
  71007. }
  71008. void DrawableRectangle::setRectangle (const RelativeParallelogram& newBounds)
  71009. {
  71010. bounds = newBounds;
  71011. pathChanged();
  71012. strokeChanged();
  71013. }
  71014. void DrawableRectangle::setCornerSize (const RelativePoint& newSize)
  71015. {
  71016. cornerSize = newSize;
  71017. pathChanged();
  71018. strokeChanged();
  71019. }
  71020. bool DrawableRectangle::rebuildPath (Path& path) const
  71021. {
  71022. Point<float> points[3];
  71023. bounds.resolveThreePoints (points, parent);
  71024. const float w = Line<float> (points[0], points[1]).getLength();
  71025. const float h = Line<float> (points[0], points[2]).getLength();
  71026. const float cornerSizeX = (float) cornerSize.x.resolve (parent);
  71027. const float cornerSizeY = (float) cornerSize.y.resolve (parent);
  71028. path.clear();
  71029. if (cornerSizeX > 0 && cornerSizeY > 0)
  71030. path.addRoundedRectangle (0, 0, w, h, cornerSizeX, cornerSizeY);
  71031. else
  71032. path.addRectangle (0, 0, w, h);
  71033. path.applyTransform (AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71034. w, 0, points[1].getX(), points[1].getY(),
  71035. 0, h, points[2].getX(), points[2].getY()));
  71036. return true;
  71037. }
  71038. const AffineTransform DrawableRectangle::calculateTransform() const
  71039. {
  71040. Point<float> resolved[3];
  71041. bounds.resolveThreePoints (resolved, parent);
  71042. return AffineTransform::fromTargetPoints (resolved[0].getX(), resolved[0].getY(),
  71043. resolved[1].getX(), resolved[1].getY(),
  71044. resolved[2].getX(), resolved[2].getY());
  71045. }
  71046. const Identifier DrawableRectangle::valueTreeType ("Rectangle");
  71047. const Identifier DrawableRectangle::ValueTreeWrapper::topLeft ("topLeft");
  71048. const Identifier DrawableRectangle::ValueTreeWrapper::topRight ("topRight");
  71049. const Identifier DrawableRectangle::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71050. const Identifier DrawableRectangle::ValueTreeWrapper::cornerSize ("cornerSize");
  71051. DrawableRectangle::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71052. : FillAndStrokeState (state_)
  71053. {
  71054. jassert (state.hasType (valueTreeType));
  71055. }
  71056. const RelativeParallelogram DrawableRectangle::ValueTreeWrapper::getRectangle() const
  71057. {
  71058. return RelativeParallelogram (state.getProperty (topLeft, "0, 0"),
  71059. state.getProperty (topRight, "100, 0"),
  71060. state.getProperty (bottomLeft, "0, 100"));
  71061. }
  71062. void DrawableRectangle::ValueTreeWrapper::setRectangle (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71063. {
  71064. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71065. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71066. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71067. }
  71068. void DrawableRectangle::ValueTreeWrapper::setCornerSize (const RelativePoint& newSize, UndoManager* undoManager)
  71069. {
  71070. state.setProperty (cornerSize, newSize.toString(), undoManager);
  71071. }
  71072. const RelativePoint DrawableRectangle::ValueTreeWrapper::getCornerSize() const
  71073. {
  71074. return RelativePoint (state [cornerSize]);
  71075. }
  71076. Value DrawableRectangle::ValueTreeWrapper::getCornerSizeValue (UndoManager* undoManager) const
  71077. {
  71078. return state.getPropertyAsValue (cornerSize, undoManager);
  71079. }
  71080. const Rectangle<float> DrawableRectangle::refreshFromValueTree (const ValueTree& tree, ImageProvider* imageProvider)
  71081. {
  71082. Rectangle<float> damageRect;
  71083. ValueTreeWrapper v (tree);
  71084. setName (v.getID());
  71085. bool needsRedraw = refreshFillTypes (v, parent, imageProvider);
  71086. RelativeParallelogram newBounds (v.getRectangle());
  71087. const PathStrokeType newStroke (v.getStrokeType());
  71088. const RelativePoint newCornerSize (v.getCornerSize());
  71089. if (strokeType != newStroke || newBounds != bounds || newCornerSize != cornerSize)
  71090. {
  71091. damageRect = getBounds();
  71092. bounds = newBounds;
  71093. strokeType = newStroke;
  71094. cornerSize = newCornerSize;
  71095. pathChanged();
  71096. strokeChanged();
  71097. needsRedraw = true;
  71098. }
  71099. if (needsRedraw)
  71100. damageRect = damageRect.getUnion (getBounds());
  71101. return damageRect;
  71102. }
  71103. const ValueTree DrawableRectangle::createValueTree (ImageProvider* imageProvider) const
  71104. {
  71105. ValueTree tree (valueTreeType);
  71106. ValueTreeWrapper v (tree);
  71107. v.setID (getName(), 0);
  71108. writeTo (v, imageProvider, 0);
  71109. v.setRectangle (bounds, 0);
  71110. v.setCornerSize (cornerSize, 0);
  71111. return tree;
  71112. }
  71113. END_JUCE_NAMESPACE
  71114. /*** End of inlined file: juce_DrawableRectangle.cpp ***/
  71115. /*** Start of inlined file: juce_DrawableText.cpp ***/
  71116. BEGIN_JUCE_NAMESPACE
  71117. DrawableText::DrawableText()
  71118. : colour (Colours::black),
  71119. justification (Justification::centredLeft)
  71120. {
  71121. setBoundingBox (RelativeParallelogram (RelativePoint (0.0f, 0.0f),
  71122. RelativePoint (50.0f, 0.0f),
  71123. RelativePoint (0.0f, 20.0f)));
  71124. setFont (Font (15.0f), true);
  71125. }
  71126. DrawableText::DrawableText (const DrawableText& other)
  71127. : bounds (other.bounds),
  71128. fontSizeControlPoint (other.fontSizeControlPoint),
  71129. font (other.font),
  71130. text (other.text),
  71131. colour (other.colour),
  71132. justification (other.justification)
  71133. {
  71134. }
  71135. DrawableText::~DrawableText()
  71136. {
  71137. }
  71138. void DrawableText::setText (const String& newText)
  71139. {
  71140. text = newText;
  71141. }
  71142. void DrawableText::setColour (const Colour& newColour)
  71143. {
  71144. colour = newColour;
  71145. }
  71146. void DrawableText::setFont (const Font& newFont, bool applySizeAndScale)
  71147. {
  71148. font = newFont;
  71149. if (applySizeAndScale)
  71150. {
  71151. Point<float> corners[3];
  71152. bounds.resolveThreePoints (corners, parent);
  71153. setFontSizeControlPoint (RelativePoint (RelativeParallelogram::getPointForInternalCoord (corners,
  71154. Point<float> (font.getHorizontalScale() * font.getHeight(), font.getHeight()))));
  71155. }
  71156. }
  71157. void DrawableText::setJustification (const Justification& newJustification)
  71158. {
  71159. justification = newJustification;
  71160. }
  71161. void DrawableText::setBoundingBox (const RelativeParallelogram& newBounds)
  71162. {
  71163. bounds = newBounds;
  71164. }
  71165. void DrawableText::setFontSizeControlPoint (const RelativePoint& newPoint)
  71166. {
  71167. fontSizeControlPoint = newPoint;
  71168. }
  71169. void DrawableText::render (const Drawable::RenderingContext& context) const
  71170. {
  71171. Point<float> points[3];
  71172. bounds.resolveThreePoints (points, parent);
  71173. const float w = Line<float> (points[0], points[1]).getLength();
  71174. const float h = Line<float> (points[0], points[2]).getLength();
  71175. const Point<float> fontCoords (bounds.getInternalCoordForPoint (points, fontSizeControlPoint.resolve (parent)));
  71176. const float fontHeight = jlimit (0.01f, jmax (0.01f, h), fontCoords.getY());
  71177. const float fontWidth = jlimit (0.01f, jmax (0.01f, w), fontCoords.getX());
  71178. Font f (font);
  71179. f.setHeight (fontHeight);
  71180. f.setHorizontalScale (fontWidth / fontHeight);
  71181. context.g.setColour (colour.withMultipliedAlpha (context.opacity));
  71182. GlyphArrangement ga;
  71183. ga.addFittedText (f, text, 0, 0, w, h, justification, 0x100000);
  71184. ga.draw (context.g,
  71185. AffineTransform::fromTargetPoints (0, 0, points[0].getX(), points[0].getY(),
  71186. w, 0, points[1].getX(), points[1].getY(),
  71187. 0, h, points[2].getX(), points[2].getY())
  71188. .followedBy (context.transform));
  71189. }
  71190. const Rectangle<float> DrawableText::getBounds() const
  71191. {
  71192. return bounds.getBounds (parent);
  71193. }
  71194. bool DrawableText::hitTest (float x, float y) const
  71195. {
  71196. Path p;
  71197. bounds.getPath (p, parent);
  71198. return p.contains (x, y);
  71199. }
  71200. Drawable* DrawableText::createCopy() const
  71201. {
  71202. return new DrawableText (*this);
  71203. }
  71204. void DrawableText::invalidatePoints()
  71205. {
  71206. }
  71207. const Identifier DrawableText::valueTreeType ("Text");
  71208. const Identifier DrawableText::ValueTreeWrapper::text ("text");
  71209. const Identifier DrawableText::ValueTreeWrapper::colour ("colour");
  71210. const Identifier DrawableText::ValueTreeWrapper::font ("font");
  71211. const Identifier DrawableText::ValueTreeWrapper::justification ("justification");
  71212. const Identifier DrawableText::ValueTreeWrapper::topLeft ("topLeft");
  71213. const Identifier DrawableText::ValueTreeWrapper::topRight ("topRight");
  71214. const Identifier DrawableText::ValueTreeWrapper::bottomLeft ("bottomLeft");
  71215. const Identifier DrawableText::ValueTreeWrapper::fontSizeAnchor ("fontSizeAnchor");
  71216. DrawableText::ValueTreeWrapper::ValueTreeWrapper (const ValueTree& state_)
  71217. : ValueTreeWrapperBase (state_)
  71218. {
  71219. jassert (state.hasType (valueTreeType));
  71220. }
  71221. const String DrawableText::ValueTreeWrapper::getText() const
  71222. {
  71223. return state [text].toString();
  71224. }
  71225. void DrawableText::ValueTreeWrapper::setText (const String& newText, UndoManager* undoManager)
  71226. {
  71227. state.setProperty (text, newText, undoManager);
  71228. }
  71229. Value DrawableText::ValueTreeWrapper::getTextValue (UndoManager* undoManager)
  71230. {
  71231. return state.getPropertyAsValue (text, undoManager);
  71232. }
  71233. const Colour DrawableText::ValueTreeWrapper::getColour() const
  71234. {
  71235. return Colour::fromString (state [colour].toString());
  71236. }
  71237. void DrawableText::ValueTreeWrapper::setColour (const Colour& newColour, UndoManager* undoManager)
  71238. {
  71239. state.setProperty (colour, newColour.toString(), undoManager);
  71240. }
  71241. const Justification DrawableText::ValueTreeWrapper::getJustification() const
  71242. {
  71243. return Justification ((int) state [justification]);
  71244. }
  71245. void DrawableText::ValueTreeWrapper::setJustification (const Justification& newJustification, UndoManager* undoManager)
  71246. {
  71247. state.setProperty (justification, newJustification.getFlags(), undoManager);
  71248. }
  71249. const Font DrawableText::ValueTreeWrapper::getFont() const
  71250. {
  71251. return Font::fromString (state [font]);
  71252. }
  71253. void DrawableText::ValueTreeWrapper::setFont (const Font& newFont, UndoManager* undoManager)
  71254. {
  71255. state.setProperty (font, newFont.toString(), undoManager);
  71256. }
  71257. Value DrawableText::ValueTreeWrapper::getFontValue (UndoManager* undoManager)
  71258. {
  71259. return state.getPropertyAsValue (font, undoManager);
  71260. }
  71261. const RelativeParallelogram DrawableText::ValueTreeWrapper::getBoundingBox() const
  71262. {
  71263. return RelativeParallelogram (state [topLeft].toString(), state [topRight].toString(), state [bottomLeft].toString());
  71264. }
  71265. void DrawableText::ValueTreeWrapper::setBoundingBox (const RelativeParallelogram& newBounds, UndoManager* undoManager)
  71266. {
  71267. state.setProperty (topLeft, newBounds.topLeft.toString(), undoManager);
  71268. state.setProperty (topRight, newBounds.topRight.toString(), undoManager);
  71269. state.setProperty (bottomLeft, newBounds.bottomLeft.toString(), undoManager);
  71270. }
  71271. const RelativePoint DrawableText::ValueTreeWrapper::getFontSizeControlPoint() const
  71272. {
  71273. return state [fontSizeAnchor].toString();
  71274. }
  71275. void DrawableText::ValueTreeWrapper::setFontSizeControlPoint (const RelativePoint& p, UndoManager* undoManager)
  71276. {
  71277. state.setProperty (fontSizeAnchor, p.toString(), undoManager);
  71278. }
  71279. const Rectangle<float> DrawableText::refreshFromValueTree (const ValueTree& tree, ImageProvider*)
  71280. {
  71281. ValueTreeWrapper v (tree);
  71282. setName (v.getID());
  71283. const RelativeParallelogram newBounds (v.getBoundingBox());
  71284. const RelativePoint newFontPoint (v.getFontSizeControlPoint());
  71285. const Colour newColour (v.getColour());
  71286. const Justification newJustification (v.getJustification());
  71287. const String newText (v.getText());
  71288. const Font newFont (v.getFont());
  71289. if (text != newText || font != newFont || justification != newJustification
  71290. || colour != newColour || bounds != newBounds || newFontPoint != fontSizeControlPoint)
  71291. {
  71292. const Rectangle<float> damage (getBounds());
  71293. setBoundingBox (newBounds);
  71294. setFontSizeControlPoint (newFontPoint);
  71295. setColour (newColour);
  71296. setFont (newFont, false);
  71297. setJustification (newJustification);
  71298. setText (newText);
  71299. return damage.getUnion (getBounds());
  71300. }
  71301. return Rectangle<float>();
  71302. }
  71303. const ValueTree DrawableText::createValueTree (ImageProvider*) const
  71304. {
  71305. ValueTree tree (valueTreeType);
  71306. ValueTreeWrapper v (tree);
  71307. v.setID (getName(), 0);
  71308. v.setText (text, 0);
  71309. v.setFont (font, 0);
  71310. v.setJustification (justification, 0);
  71311. v.setColour (colour, 0);
  71312. v.setBoundingBox (bounds, 0);
  71313. v.setFontSizeControlPoint (fontSizeControlPoint, 0);
  71314. return tree;
  71315. }
  71316. END_JUCE_NAMESPACE
  71317. /*** End of inlined file: juce_DrawableText.cpp ***/
  71318. /*** Start of inlined file: juce_SVGParser.cpp ***/
  71319. BEGIN_JUCE_NAMESPACE
  71320. class SVGState
  71321. {
  71322. public:
  71323. SVGState (const XmlElement* const topLevel)
  71324. : topLevelXml (topLevel),
  71325. elementX (0), elementY (0),
  71326. width (512), height (512),
  71327. viewBoxW (0), viewBoxH (0)
  71328. {
  71329. }
  71330. ~SVGState()
  71331. {
  71332. }
  71333. Drawable* parseSVGElement (const XmlElement& xml)
  71334. {
  71335. if (! xml.hasTagName ("svg"))
  71336. return 0;
  71337. DrawableComposite* const drawable = new DrawableComposite();
  71338. drawable->setName (xml.getStringAttribute ("id"));
  71339. SVGState newState (*this);
  71340. if (xml.hasAttribute ("transform"))
  71341. newState.addTransform (xml);
  71342. newState.elementX = getCoordLength (xml.getStringAttribute ("x", String (newState.elementX)), viewBoxW);
  71343. newState.elementY = getCoordLength (xml.getStringAttribute ("y", String (newState.elementY)), viewBoxH);
  71344. newState.width = getCoordLength (xml.getStringAttribute ("width", String (newState.width)), viewBoxW);
  71345. newState.height = getCoordLength (xml.getStringAttribute ("height", String (newState.height)), viewBoxH);
  71346. if (xml.hasAttribute ("viewBox"))
  71347. {
  71348. const String viewParams (xml.getStringAttribute ("viewBox"));
  71349. int i = 0;
  71350. float vx, vy, vw, vh;
  71351. if (parseCoords (viewParams, vx, vy, i, true)
  71352. && parseCoords (viewParams, vw, vh, i, true)
  71353. && vw > 0
  71354. && vh > 0)
  71355. {
  71356. newState.viewBoxW = vw;
  71357. newState.viewBoxH = vh;
  71358. int placementFlags = 0;
  71359. const String aspect (xml.getStringAttribute ("preserveAspectRatio"));
  71360. if (aspect.containsIgnoreCase ("none"))
  71361. {
  71362. placementFlags = RectanglePlacement::stretchToFit;
  71363. }
  71364. else
  71365. {
  71366. if (aspect.containsIgnoreCase ("slice"))
  71367. placementFlags |= RectanglePlacement::fillDestination;
  71368. if (aspect.containsIgnoreCase ("xMin"))
  71369. placementFlags |= RectanglePlacement::xLeft;
  71370. else if (aspect.containsIgnoreCase ("xMax"))
  71371. placementFlags |= RectanglePlacement::xRight;
  71372. else
  71373. placementFlags |= RectanglePlacement::xMid;
  71374. if (aspect.containsIgnoreCase ("yMin"))
  71375. placementFlags |= RectanglePlacement::yTop;
  71376. else if (aspect.containsIgnoreCase ("yMax"))
  71377. placementFlags |= RectanglePlacement::yBottom;
  71378. else
  71379. placementFlags |= RectanglePlacement::yMid;
  71380. }
  71381. const RectanglePlacement placement (placementFlags);
  71382. newState.transform
  71383. = placement.getTransformToFit (Rectangle<float> (vx, vy, vw, vh),
  71384. Rectangle<float> (0.0f, 0.0f, newState.width, newState.height))
  71385. .followedBy (newState.transform);
  71386. }
  71387. }
  71388. else
  71389. {
  71390. if (viewBoxW == 0)
  71391. newState.viewBoxW = newState.width;
  71392. if (viewBoxH == 0)
  71393. newState.viewBoxH = newState.height;
  71394. }
  71395. newState.parseSubElements (xml, drawable);
  71396. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71397. return drawable;
  71398. }
  71399. private:
  71400. const XmlElement* const topLevelXml;
  71401. float elementX, elementY, width, height, viewBoxW, viewBoxH;
  71402. AffineTransform transform;
  71403. String cssStyleText;
  71404. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  71405. {
  71406. forEachXmlChildElement (xml, e)
  71407. {
  71408. Drawable* d = 0;
  71409. if (e->hasTagName ("g")) d = parseGroupElement (*e);
  71410. else if (e->hasTagName ("svg")) d = parseSVGElement (*e);
  71411. else if (e->hasTagName ("path")) d = parsePath (*e);
  71412. else if (e->hasTagName ("rect")) d = parseRect (*e);
  71413. else if (e->hasTagName ("circle")) d = parseCircle (*e);
  71414. else if (e->hasTagName ("ellipse")) d = parseEllipse (*e);
  71415. else if (e->hasTagName ("line")) d = parseLine (*e);
  71416. else if (e->hasTagName ("polyline")) d = parsePolygon (*e, true);
  71417. else if (e->hasTagName ("polygon")) d = parsePolygon (*e, false);
  71418. else if (e->hasTagName ("text")) d = parseText (*e);
  71419. else if (e->hasTagName ("switch")) d = parseSwitch (*e);
  71420. else if (e->hasTagName ("style")) parseCSSStyle (*e);
  71421. parentDrawable->insertDrawable (d);
  71422. }
  71423. }
  71424. DrawableComposite* parseSwitch (const XmlElement& xml)
  71425. {
  71426. const XmlElement* const group = xml.getChildByName ("g");
  71427. if (group != 0)
  71428. return parseGroupElement (*group);
  71429. return 0;
  71430. }
  71431. DrawableComposite* parseGroupElement (const XmlElement& xml)
  71432. {
  71433. DrawableComposite* const drawable = new DrawableComposite();
  71434. drawable->setName (xml.getStringAttribute ("id"));
  71435. if (xml.hasAttribute ("transform"))
  71436. {
  71437. SVGState newState (*this);
  71438. newState.addTransform (xml);
  71439. newState.parseSubElements (xml, drawable);
  71440. }
  71441. else
  71442. {
  71443. parseSubElements (xml, drawable);
  71444. }
  71445. drawable->resetContentAreaAndBoundingBoxToFitChildren();
  71446. return drawable;
  71447. }
  71448. Drawable* parsePath (const XmlElement& xml) const
  71449. {
  71450. const String d (xml.getStringAttribute ("d").trimStart());
  71451. Path path;
  71452. if (getStyleAttribute (&xml, "fill-rule").trim().equalsIgnoreCase ("evenodd"))
  71453. path.setUsingNonZeroWinding (false);
  71454. int index = 0;
  71455. float lastX = 0, lastY = 0;
  71456. float lastX2 = 0, lastY2 = 0;
  71457. juce_wchar lastCommandChar = 0;
  71458. bool isRelative = true;
  71459. bool carryOn = true;
  71460. const String validCommandChars ("MmLlHhVvCcSsQqTtAaZz");
  71461. while (d[index] != 0)
  71462. {
  71463. float x, y, x2, y2, x3, y3;
  71464. if (validCommandChars.containsChar (d[index]))
  71465. {
  71466. lastCommandChar = d [index++];
  71467. isRelative = (lastCommandChar >= 'a' && lastCommandChar <= 'z');
  71468. }
  71469. switch (lastCommandChar)
  71470. {
  71471. case 'M':
  71472. case 'm':
  71473. case 'L':
  71474. case 'l':
  71475. if (parseCoords (d, x, y, index, false))
  71476. {
  71477. if (isRelative)
  71478. {
  71479. x += lastX;
  71480. y += lastY;
  71481. }
  71482. if (lastCommandChar == 'M' || lastCommandChar == 'm')
  71483. {
  71484. path.startNewSubPath (x, y);
  71485. lastCommandChar = 'l';
  71486. }
  71487. else
  71488. path.lineTo (x, y);
  71489. lastX2 = lastX;
  71490. lastY2 = lastY;
  71491. lastX = x;
  71492. lastY = y;
  71493. }
  71494. else
  71495. {
  71496. ++index;
  71497. }
  71498. break;
  71499. case 'H':
  71500. case 'h':
  71501. if (parseCoord (d, x, index, false, true))
  71502. {
  71503. if (isRelative)
  71504. x += lastX;
  71505. path.lineTo (x, lastY);
  71506. lastX2 = lastX;
  71507. lastX = x;
  71508. }
  71509. else
  71510. {
  71511. ++index;
  71512. }
  71513. break;
  71514. case 'V':
  71515. case 'v':
  71516. if (parseCoord (d, y, index, false, false))
  71517. {
  71518. if (isRelative)
  71519. y += lastY;
  71520. path.lineTo (lastX, y);
  71521. lastY2 = lastY;
  71522. lastY = y;
  71523. }
  71524. else
  71525. {
  71526. ++index;
  71527. }
  71528. break;
  71529. case 'C':
  71530. case 'c':
  71531. if (parseCoords (d, x, y, index, false)
  71532. && parseCoords (d, x2, y2, index, false)
  71533. && parseCoords (d, x3, y3, index, false))
  71534. {
  71535. if (isRelative)
  71536. {
  71537. x += lastX;
  71538. y += lastY;
  71539. x2 += lastX;
  71540. y2 += lastY;
  71541. x3 += lastX;
  71542. y3 += lastY;
  71543. }
  71544. path.cubicTo (x, y, x2, y2, x3, y3);
  71545. lastX2 = x2;
  71546. lastY2 = y2;
  71547. lastX = x3;
  71548. lastY = y3;
  71549. }
  71550. else
  71551. {
  71552. ++index;
  71553. }
  71554. break;
  71555. case 'S':
  71556. case 's':
  71557. if (parseCoords (d, x, y, index, false)
  71558. && parseCoords (d, x3, y3, index, false))
  71559. {
  71560. if (isRelative)
  71561. {
  71562. x += lastX;
  71563. y += lastY;
  71564. x3 += lastX;
  71565. y3 += lastY;
  71566. }
  71567. x2 = lastX + (lastX - lastX2);
  71568. y2 = lastY + (lastY - lastY2);
  71569. path.cubicTo (x2, y2, x, y, x3, y3);
  71570. lastX2 = x;
  71571. lastY2 = y;
  71572. lastX = x3;
  71573. lastY = y3;
  71574. }
  71575. else
  71576. {
  71577. ++index;
  71578. }
  71579. break;
  71580. case 'Q':
  71581. case 'q':
  71582. if (parseCoords (d, x, y, index, false)
  71583. && parseCoords (d, x2, y2, index, false))
  71584. {
  71585. if (isRelative)
  71586. {
  71587. x += lastX;
  71588. y += lastY;
  71589. x2 += lastX;
  71590. y2 += lastY;
  71591. }
  71592. path.quadraticTo (x, y, x2, y2);
  71593. lastX2 = x;
  71594. lastY2 = y;
  71595. lastX = x2;
  71596. lastY = y2;
  71597. }
  71598. else
  71599. {
  71600. ++index;
  71601. }
  71602. break;
  71603. case 'T':
  71604. case 't':
  71605. if (parseCoords (d, x, y, index, false))
  71606. {
  71607. if (isRelative)
  71608. {
  71609. x += lastX;
  71610. y += lastY;
  71611. }
  71612. x2 = lastX + (lastX - lastX2);
  71613. y2 = lastY + (lastY - lastY2);
  71614. path.quadraticTo (x2, y2, x, y);
  71615. lastX2 = x2;
  71616. lastY2 = y2;
  71617. lastX = x;
  71618. lastY = y;
  71619. }
  71620. else
  71621. {
  71622. ++index;
  71623. }
  71624. break;
  71625. case 'A':
  71626. case 'a':
  71627. if (parseCoords (d, x, y, index, false))
  71628. {
  71629. String num;
  71630. if (parseNextNumber (d, num, index, false))
  71631. {
  71632. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  71633. if (parseNextNumber (d, num, index, false))
  71634. {
  71635. const bool largeArc = num.getIntValue() != 0;
  71636. if (parseNextNumber (d, num, index, false))
  71637. {
  71638. const bool sweep = num.getIntValue() != 0;
  71639. if (parseCoords (d, x2, y2, index, false))
  71640. {
  71641. if (isRelative)
  71642. {
  71643. x2 += lastX;
  71644. y2 += lastY;
  71645. }
  71646. if (lastX != x2 || lastY != y2)
  71647. {
  71648. double centreX, centreY, startAngle, deltaAngle;
  71649. double rx = x, ry = y;
  71650. endpointToCentreParameters (lastX, lastY, x2, y2,
  71651. angle, largeArc, sweep,
  71652. rx, ry, centreX, centreY,
  71653. startAngle, deltaAngle);
  71654. path.addCentredArc ((float) centreX, (float) centreY,
  71655. (float) rx, (float) ry,
  71656. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  71657. false);
  71658. path.lineTo (x2, y2);
  71659. }
  71660. lastX2 = lastX;
  71661. lastY2 = lastY;
  71662. lastX = x2;
  71663. lastY = y2;
  71664. }
  71665. }
  71666. }
  71667. }
  71668. }
  71669. else
  71670. {
  71671. ++index;
  71672. }
  71673. break;
  71674. case 'Z':
  71675. case 'z':
  71676. path.closeSubPath();
  71677. while (CharacterFunctions::isWhitespace (d [index]))
  71678. ++index;
  71679. break;
  71680. default:
  71681. carryOn = false;
  71682. break;
  71683. }
  71684. if (! carryOn)
  71685. break;
  71686. }
  71687. return parseShape (xml, path);
  71688. }
  71689. Drawable* parseRect (const XmlElement& xml) const
  71690. {
  71691. Path rect;
  71692. const bool hasRX = xml.hasAttribute ("rx");
  71693. const bool hasRY = xml.hasAttribute ("ry");
  71694. if (hasRX || hasRY)
  71695. {
  71696. float rx = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71697. float ry = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71698. if (! hasRX)
  71699. rx = ry;
  71700. else if (! hasRY)
  71701. ry = rx;
  71702. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71703. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71704. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71705. getCoordLength (xml.getStringAttribute ("height"), viewBoxH),
  71706. rx, ry);
  71707. }
  71708. else
  71709. {
  71710. rect.addRectangle (getCoordLength (xml.getStringAttribute ("x"), viewBoxW),
  71711. getCoordLength (xml.getStringAttribute ("y"), viewBoxH),
  71712. getCoordLength (xml.getStringAttribute ("width"), viewBoxW),
  71713. getCoordLength (xml.getStringAttribute ("height"), viewBoxH));
  71714. }
  71715. return parseShape (xml, rect);
  71716. }
  71717. Drawable* parseCircle (const XmlElement& xml) const
  71718. {
  71719. Path circle;
  71720. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71721. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71722. const float radius = getCoordLength (xml.getStringAttribute ("r"), viewBoxW);
  71723. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  71724. return parseShape (xml, circle);
  71725. }
  71726. Drawable* parseEllipse (const XmlElement& xml) const
  71727. {
  71728. Path ellipse;
  71729. const float cx = getCoordLength (xml.getStringAttribute ("cx"), viewBoxW);
  71730. const float cy = getCoordLength (xml.getStringAttribute ("cy"), viewBoxH);
  71731. const float radiusX = getCoordLength (xml.getStringAttribute ("rx"), viewBoxW);
  71732. const float radiusY = getCoordLength (xml.getStringAttribute ("ry"), viewBoxH);
  71733. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  71734. return parseShape (xml, ellipse);
  71735. }
  71736. Drawable* parseLine (const XmlElement& xml) const
  71737. {
  71738. Path line;
  71739. const float x1 = getCoordLength (xml.getStringAttribute ("x1"), viewBoxW);
  71740. const float y1 = getCoordLength (xml.getStringAttribute ("y1"), viewBoxH);
  71741. const float x2 = getCoordLength (xml.getStringAttribute ("x2"), viewBoxW);
  71742. const float y2 = getCoordLength (xml.getStringAttribute ("y2"), viewBoxH);
  71743. line.startNewSubPath (x1, y1);
  71744. line.lineTo (x2, y2);
  71745. return parseShape (xml, line);
  71746. }
  71747. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  71748. {
  71749. const String points (xml.getStringAttribute ("points"));
  71750. Path path;
  71751. int index = 0;
  71752. float x, y;
  71753. if (parseCoords (points, x, y, index, true))
  71754. {
  71755. float firstX = x;
  71756. float firstY = y;
  71757. float lastX = 0, lastY = 0;
  71758. path.startNewSubPath (x, y);
  71759. while (parseCoords (points, x, y, index, true))
  71760. {
  71761. lastX = x;
  71762. lastY = y;
  71763. path.lineTo (x, y);
  71764. }
  71765. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  71766. path.closeSubPath();
  71767. }
  71768. return parseShape (xml, path);
  71769. }
  71770. Drawable* parseShape (const XmlElement& xml, Path& path,
  71771. const bool shouldParseTransform = true) const
  71772. {
  71773. if (shouldParseTransform && xml.hasAttribute ("transform"))
  71774. {
  71775. SVGState newState (*this);
  71776. newState.addTransform (xml);
  71777. return newState.parseShape (xml, path, false);
  71778. }
  71779. DrawablePath* dp = new DrawablePath();
  71780. dp->setName (xml.getStringAttribute ("id"));
  71781. dp->setFill (Colours::transparentBlack);
  71782. path.applyTransform (transform);
  71783. dp->setPath (path);
  71784. Path::Iterator iter (path);
  71785. bool containsClosedSubPath = false;
  71786. while (iter.next())
  71787. {
  71788. if (iter.elementType == Path::Iterator::closePath)
  71789. {
  71790. containsClosedSubPath = true;
  71791. break;
  71792. }
  71793. }
  71794. dp->setFill (getPathFillType (path,
  71795. getStyleAttribute (&xml, "fill"),
  71796. getStyleAttribute (&xml, "fill-opacity"),
  71797. getStyleAttribute (&xml, "opacity"),
  71798. containsClosedSubPath ? Colours::black
  71799. : Colours::transparentBlack));
  71800. const String strokeType (getStyleAttribute (&xml, "stroke"));
  71801. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase ("none"))
  71802. {
  71803. dp->setStrokeFill (getPathFillType (path, strokeType,
  71804. getStyleAttribute (&xml, "stroke-opacity"),
  71805. getStyleAttribute (&xml, "opacity"),
  71806. Colours::transparentBlack));
  71807. dp->setStrokeType (getStrokeFor (&xml));
  71808. }
  71809. return dp;
  71810. }
  71811. const XmlElement* findLinkedElement (const XmlElement* e) const
  71812. {
  71813. const String id (e->getStringAttribute ("xlink:href"));
  71814. if (! id.startsWithChar ('#'))
  71815. return 0;
  71816. return findElementForId (topLevelXml, id.substring (1));
  71817. }
  71818. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  71819. {
  71820. if (fillXml == 0)
  71821. return;
  71822. forEachXmlChildElementWithTagName (*fillXml, e, "stop")
  71823. {
  71824. int index = 0;
  71825. Colour col (parseColour (getStyleAttribute (e, "stop-color"), index, Colours::black));
  71826. const String opacity (getStyleAttribute (e, "stop-opacity", "1"));
  71827. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  71828. double offset = e->getDoubleAttribute ("offset");
  71829. if (e->getStringAttribute ("offset").containsChar ('%'))
  71830. offset *= 0.01;
  71831. cg.addColour (jlimit (0.0, 1.0, offset), col);
  71832. }
  71833. }
  71834. const FillType getPathFillType (const Path& path,
  71835. const String& fill,
  71836. const String& fillOpacity,
  71837. const String& overallOpacity,
  71838. const Colour& defaultColour) const
  71839. {
  71840. float opacity = 1.0f;
  71841. if (overallOpacity.isNotEmpty())
  71842. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  71843. if (fillOpacity.isNotEmpty())
  71844. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  71845. if (fill.startsWithIgnoreCase ("url"))
  71846. {
  71847. const String id (fill.fromFirstOccurrenceOf ("#", false, false)
  71848. .upToLastOccurrenceOf (")", false, false).trim());
  71849. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  71850. if (fillXml != 0
  71851. && (fillXml->hasTagName ("linearGradient")
  71852. || fillXml->hasTagName ("radialGradient")))
  71853. {
  71854. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  71855. ColourGradient gradient;
  71856. addGradientStopsIn (gradient, inheritedFrom);
  71857. addGradientStopsIn (gradient, fillXml);
  71858. if (gradient.getNumColours() > 0)
  71859. {
  71860. gradient.addColour (0.0, gradient.getColour (0));
  71861. gradient.addColour (1.0, gradient.getColour (gradient.getNumColours() - 1));
  71862. }
  71863. else
  71864. {
  71865. gradient.addColour (0.0, Colours::black);
  71866. gradient.addColour (1.0, Colours::black);
  71867. }
  71868. if (overallOpacity.isNotEmpty())
  71869. gradient.multiplyOpacity (overallOpacity.getFloatValue());
  71870. jassert (gradient.getNumColours() > 0);
  71871. gradient.isRadial = fillXml->hasTagName ("radialGradient");
  71872. float gradientWidth = viewBoxW;
  71873. float gradientHeight = viewBoxH;
  71874. float dx = 0.0f;
  71875. float dy = 0.0f;
  71876. const bool userSpace = fillXml->getStringAttribute ("gradientUnits").equalsIgnoreCase ("userSpaceOnUse");
  71877. if (! userSpace)
  71878. {
  71879. const Rectangle<float> bounds (path.getBounds());
  71880. dx = bounds.getX();
  71881. dy = bounds.getY();
  71882. gradientWidth = bounds.getWidth();
  71883. gradientHeight = bounds.getHeight();
  71884. }
  71885. if (gradient.isRadial)
  71886. {
  71887. if (userSpace)
  71888. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("cx", "50%"), gradientWidth),
  71889. dy + getCoordLength (fillXml->getStringAttribute ("cy", "50%"), gradientHeight));
  71890. else
  71891. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("cx", "50%"), 1.0f),
  71892. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("cy", "50%"), 1.0f));
  71893. const float radius = getCoordLength (fillXml->getStringAttribute ("r", "50%"), gradientWidth);
  71894. gradient.point2 = gradient.point1 + Point<float> (radius, 0.0f);
  71895. //xxx (the fx, fy focal point isn't handled properly here..)
  71896. }
  71897. else
  71898. {
  71899. if (userSpace)
  71900. {
  71901. gradient.point1.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x1", "0%"), gradientWidth),
  71902. dy + getCoordLength (fillXml->getStringAttribute ("y1", "0%"), gradientHeight));
  71903. gradient.point2.setXY (dx + getCoordLength (fillXml->getStringAttribute ("x2", "100%"), gradientWidth),
  71904. dy + getCoordLength (fillXml->getStringAttribute ("y2", "0%"), gradientHeight));
  71905. }
  71906. else
  71907. {
  71908. gradient.point1.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x1", "0%"), 1.0f),
  71909. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y1", "0%"), 1.0f));
  71910. gradient.point2.setXY (dx + gradientWidth * getCoordLength (fillXml->getStringAttribute ("x2", "100%"), 1.0f),
  71911. dy + gradientHeight * getCoordLength (fillXml->getStringAttribute ("y2", "0%"), 1.0f));
  71912. }
  71913. if (gradient.point1 == gradient.point2)
  71914. return Colour (gradient.getColour (gradient.getNumColours() - 1));
  71915. }
  71916. FillType type (gradient);
  71917. type.transform = parseTransform (fillXml->getStringAttribute ("gradientTransform"))
  71918. .followedBy (transform);
  71919. return type;
  71920. }
  71921. }
  71922. if (fill.equalsIgnoreCase ("none"))
  71923. return Colours::transparentBlack;
  71924. int i = 0;
  71925. const Colour colour (parseColour (fill, i, defaultColour));
  71926. return colour.withMultipliedAlpha (opacity);
  71927. }
  71928. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  71929. {
  71930. const String strokeWidth (getStyleAttribute (xml, "stroke-width"));
  71931. const String cap (getStyleAttribute (xml, "stroke-linecap"));
  71932. const String join (getStyleAttribute (xml, "stroke-linejoin"));
  71933. //const String mitreLimit (getStyleAttribute (xml, "stroke-miterlimit"));
  71934. //const String dashArray (getStyleAttribute (xml, "stroke-dasharray"));
  71935. //const String dashOffset (getStyleAttribute (xml, "stroke-dashoffset"));
  71936. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  71937. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  71938. if (join.equalsIgnoreCase ("round"))
  71939. joinStyle = PathStrokeType::curved;
  71940. else if (join.equalsIgnoreCase ("bevel"))
  71941. joinStyle = PathStrokeType::beveled;
  71942. if (cap.equalsIgnoreCase ("round"))
  71943. capStyle = PathStrokeType::rounded;
  71944. else if (cap.equalsIgnoreCase ("square"))
  71945. capStyle = PathStrokeType::square;
  71946. float ox = 0.0f, oy = 0.0f;
  71947. float x = getCoordLength (strokeWidth, viewBoxW), y = 0.0f;
  71948. transform.transformPoints (ox, oy, x, y);
  71949. return PathStrokeType (strokeWidth.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  71950. joinStyle, capStyle);
  71951. }
  71952. Drawable* parseText (const XmlElement& xml)
  71953. {
  71954. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  71955. getCoordList (xCoords, getInheritedAttribute (&xml, "x"), true, true);
  71956. getCoordList (yCoords, getInheritedAttribute (&xml, "y"), true, false);
  71957. getCoordList (dxCoords, getInheritedAttribute (&xml, "dx"), true, true);
  71958. getCoordList (dyCoords, getInheritedAttribute (&xml, "dy"), true, false);
  71959. //xxx not done text yet!
  71960. forEachXmlChildElement (xml, e)
  71961. {
  71962. if (e->isTextElement())
  71963. {
  71964. const String text (e->getText());
  71965. Path path;
  71966. Drawable* s = parseShape (*e, path);
  71967. delete s; // xxx not finished!
  71968. }
  71969. else if (e->hasTagName ("tspan"))
  71970. {
  71971. Drawable* s = parseText (*e);
  71972. delete s; // xxx not finished!
  71973. }
  71974. }
  71975. return 0;
  71976. }
  71977. void addTransform (const XmlElement& xml)
  71978. {
  71979. transform = parseTransform (xml.getStringAttribute ("transform"))
  71980. .followedBy (transform);
  71981. }
  71982. bool parseCoord (const String& s, float& value, int& index,
  71983. const bool allowUnits, const bool isX) const
  71984. {
  71985. String number;
  71986. if (! parseNextNumber (s, number, index, allowUnits))
  71987. {
  71988. value = 0;
  71989. return false;
  71990. }
  71991. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  71992. return true;
  71993. }
  71994. bool parseCoords (const String& s, float& x, float& y,
  71995. int& index, const bool allowUnits) const
  71996. {
  71997. return parseCoord (s, x, index, allowUnits, true)
  71998. && parseCoord (s, y, index, allowUnits, false);
  71999. }
  72000. float getCoordLength (const String& s, const float sizeForProportions) const
  72001. {
  72002. float n = s.getFloatValue();
  72003. const int len = s.length();
  72004. if (len > 2)
  72005. {
  72006. const float dpi = 96.0f;
  72007. const juce_wchar n1 = s [len - 2];
  72008. const juce_wchar n2 = s [len - 1];
  72009. if (n1 == 'i' && n2 == 'n')
  72010. n *= dpi;
  72011. else if (n1 == 'm' && n2 == 'm')
  72012. n *= dpi / 25.4f;
  72013. else if (n1 == 'c' && n2 == 'm')
  72014. n *= dpi / 2.54f;
  72015. else if (n1 == 'p' && n2 == 'c')
  72016. n *= 15.0f;
  72017. else if (n2 == '%')
  72018. n *= 0.01f * sizeForProportions;
  72019. }
  72020. return n;
  72021. }
  72022. void getCoordList (Array <float>& coords, const String& list,
  72023. const bool allowUnits, const bool isX) const
  72024. {
  72025. int index = 0;
  72026. float value;
  72027. while (parseCoord (list, value, index, allowUnits, isX))
  72028. coords.add (value);
  72029. }
  72030. void parseCSSStyle (const XmlElement& xml)
  72031. {
  72032. cssStyleText = xml.getAllSubText() + "\n" + cssStyleText;
  72033. }
  72034. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  72035. const String& defaultValue = String::empty) const
  72036. {
  72037. if (xml->hasAttribute (attributeName))
  72038. return xml->getStringAttribute (attributeName, defaultValue);
  72039. const String styleAtt (xml->getStringAttribute ("style"));
  72040. if (styleAtt.isNotEmpty())
  72041. {
  72042. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  72043. if (value.isNotEmpty())
  72044. return value;
  72045. }
  72046. else if (xml->hasAttribute ("class"))
  72047. {
  72048. const String className ("." + xml->getStringAttribute ("class"));
  72049. int index = cssStyleText.indexOfIgnoreCase (className + " ");
  72050. if (index < 0)
  72051. index = cssStyleText.indexOfIgnoreCase (className + "{");
  72052. if (index >= 0)
  72053. {
  72054. const int openBracket = cssStyleText.indexOfChar (index, '{');
  72055. if (openBracket > index)
  72056. {
  72057. const int closeBracket = cssStyleText.indexOfChar (openBracket, '}');
  72058. if (closeBracket > openBracket)
  72059. {
  72060. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  72061. if (value.isNotEmpty())
  72062. return value;
  72063. }
  72064. }
  72065. }
  72066. }
  72067. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72068. if (xml != 0)
  72069. return getStyleAttribute (xml, attributeName, defaultValue);
  72070. return defaultValue;
  72071. }
  72072. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  72073. {
  72074. if (xml->hasAttribute (attributeName))
  72075. return xml->getStringAttribute (attributeName);
  72076. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  72077. if (xml != 0)
  72078. return getInheritedAttribute (xml, attributeName);
  72079. return String::empty;
  72080. }
  72081. static bool isIdentifierChar (const juce_wchar c)
  72082. {
  72083. return CharacterFunctions::isLetter (c) || c == '-';
  72084. }
  72085. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  72086. {
  72087. int i = 0;
  72088. for (;;)
  72089. {
  72090. i = list.indexOf (i, attributeName);
  72091. if (i < 0)
  72092. break;
  72093. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  72094. && ! isIdentifierChar (list [i + attributeName.length()]))
  72095. {
  72096. i = list.indexOfChar (i, ':');
  72097. if (i < 0)
  72098. break;
  72099. int end = list.indexOfChar (i, ';');
  72100. if (end < 0)
  72101. end = 0x7ffff;
  72102. return list.substring (i + 1, end).trim();
  72103. }
  72104. ++i;
  72105. }
  72106. return defaultValue;
  72107. }
  72108. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  72109. {
  72110. const juce_wchar* const s = source;
  72111. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72112. ++index;
  72113. int start = index;
  72114. if (CharacterFunctions::isDigit (s[index]) || s[index] == '.' || s[index] == '-')
  72115. ++index;
  72116. while (CharacterFunctions::isDigit (s[index]) || s[index] == '.')
  72117. ++index;
  72118. if ((s[index] == 'e' || s[index] == 'E')
  72119. && (CharacterFunctions::isDigit (s[index + 1])
  72120. || s[index + 1] == '-'
  72121. || s[index + 1] == '+'))
  72122. {
  72123. index += 2;
  72124. while (CharacterFunctions::isDigit (s[index]))
  72125. ++index;
  72126. }
  72127. if (allowUnits)
  72128. {
  72129. while (CharacterFunctions::isLetter (s[index]))
  72130. ++index;
  72131. }
  72132. if (index == start)
  72133. return false;
  72134. value = String (s + start, index - start);
  72135. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == ',')
  72136. ++index;
  72137. return true;
  72138. }
  72139. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  72140. {
  72141. if (s [index] == '#')
  72142. {
  72143. uint32 hex [6];
  72144. zeromem (hex, sizeof (hex));
  72145. int numChars = 0;
  72146. for (int i = 6; --i >= 0;)
  72147. {
  72148. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  72149. if (hexValue >= 0)
  72150. hex [numChars++] = hexValue;
  72151. else
  72152. break;
  72153. }
  72154. if (numChars <= 3)
  72155. return Colour ((uint8) (hex [0] * 0x11),
  72156. (uint8) (hex [1] * 0x11),
  72157. (uint8) (hex [2] * 0x11));
  72158. else
  72159. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  72160. (uint8) ((hex [2] << 4) + hex [3]),
  72161. (uint8) ((hex [4] << 4) + hex [5]));
  72162. }
  72163. else if (s [index] == 'r'
  72164. && s [index + 1] == 'g'
  72165. && s [index + 2] == 'b')
  72166. {
  72167. const int openBracket = s.indexOfChar (index, '(');
  72168. const int closeBracket = s.indexOfChar (openBracket, ')');
  72169. if (openBracket >= 3 && closeBracket > openBracket)
  72170. {
  72171. index = closeBracket;
  72172. StringArray tokens;
  72173. tokens.addTokens (s.substring (openBracket + 1, closeBracket), ",", "");
  72174. tokens.trim();
  72175. tokens.removeEmptyStrings();
  72176. if (tokens[0].containsChar ('%'))
  72177. return Colour ((uint8) roundToInt (2.55 * tokens[0].getDoubleValue()),
  72178. (uint8) roundToInt (2.55 * tokens[1].getDoubleValue()),
  72179. (uint8) roundToInt (2.55 * tokens[2].getDoubleValue()));
  72180. else
  72181. return Colour ((uint8) tokens[0].getIntValue(),
  72182. (uint8) tokens[1].getIntValue(),
  72183. (uint8) tokens[2].getIntValue());
  72184. }
  72185. }
  72186. return Colours::findColourForName (s, defaultColour);
  72187. }
  72188. static const AffineTransform parseTransform (String t)
  72189. {
  72190. AffineTransform result;
  72191. while (t.isNotEmpty())
  72192. {
  72193. StringArray tokens;
  72194. tokens.addTokens (t.fromFirstOccurrenceOf ("(", false, false)
  72195. .upToFirstOccurrenceOf (")", false, false),
  72196. ", ", String::empty);
  72197. tokens.removeEmptyStrings (true);
  72198. float numbers [6];
  72199. for (int i = 0; i < 6; ++i)
  72200. numbers[i] = tokens[i].getFloatValue();
  72201. AffineTransform trans;
  72202. if (t.startsWithIgnoreCase ("matrix"))
  72203. {
  72204. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  72205. numbers[1], numbers[3], numbers[5]);
  72206. }
  72207. else if (t.startsWithIgnoreCase ("translate"))
  72208. {
  72209. jassert (tokens.size() == 2);
  72210. trans = AffineTransform::translation (numbers[0], numbers[1]);
  72211. }
  72212. else if (t.startsWithIgnoreCase ("scale"))
  72213. {
  72214. if (tokens.size() == 1)
  72215. trans = AffineTransform::scale (numbers[0], numbers[0]);
  72216. else
  72217. trans = AffineTransform::scale (numbers[0], numbers[1]);
  72218. }
  72219. else if (t.startsWithIgnoreCase ("rotate"))
  72220. {
  72221. if (tokens.size() != 3)
  72222. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi));
  72223. else
  72224. trans = AffineTransform::rotation (numbers[0] / (180.0f / float_Pi),
  72225. numbers[1], numbers[2]);
  72226. }
  72227. else if (t.startsWithIgnoreCase ("skewX"))
  72228. {
  72229. trans = AffineTransform (1.0f, std::tan (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  72230. 0.0f, 1.0f, 0.0f);
  72231. }
  72232. else if (t.startsWithIgnoreCase ("skewY"))
  72233. {
  72234. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  72235. std::tan (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  72236. }
  72237. result = trans.followedBy (result);
  72238. t = t.fromFirstOccurrenceOf (")", false, false).trimStart();
  72239. }
  72240. return result;
  72241. }
  72242. static void endpointToCentreParameters (const double x1, const double y1,
  72243. const double x2, const double y2,
  72244. const double angle,
  72245. const bool largeArc, const bool sweep,
  72246. double& rx, double& ry,
  72247. double& centreX, double& centreY,
  72248. double& startAngle, double& deltaAngle)
  72249. {
  72250. const double midX = (x1 - x2) * 0.5;
  72251. const double midY = (y1 - y2) * 0.5;
  72252. const double cosAngle = cos (angle);
  72253. const double sinAngle = sin (angle);
  72254. const double xp = cosAngle * midX + sinAngle * midY;
  72255. const double yp = cosAngle * midY - sinAngle * midX;
  72256. const double xp2 = xp * xp;
  72257. const double yp2 = yp * yp;
  72258. double rx2 = rx * rx;
  72259. double ry2 = ry * ry;
  72260. const double s = (xp2 / rx2) + (yp2 / ry2);
  72261. double c;
  72262. if (s <= 1.0)
  72263. {
  72264. c = std::sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  72265. / (( rx2 * yp2) + (ry2 * xp2))));
  72266. if (largeArc == sweep)
  72267. c = -c;
  72268. }
  72269. else
  72270. {
  72271. const double s2 = std::sqrt (s);
  72272. rx *= s2;
  72273. ry *= s2;
  72274. rx2 = rx * rx;
  72275. ry2 = ry * ry;
  72276. c = 0;
  72277. }
  72278. const double cpx = ((rx * yp) / ry) * c;
  72279. const double cpy = ((-ry * xp) / rx) * c;
  72280. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  72281. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  72282. const double ux = (xp - cpx) / rx;
  72283. const double uy = (yp - cpy) / ry;
  72284. const double vx = (-xp - cpx) / rx;
  72285. const double vy = (-yp - cpy) / ry;
  72286. const double length = juce_hypot (ux, uy);
  72287. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  72288. if (uy < 0)
  72289. startAngle = -startAngle;
  72290. startAngle += double_Pi * 0.5;
  72291. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  72292. / (length * juce_hypot (vx, vy))));
  72293. if ((ux * vy) - (uy * vx) < 0)
  72294. deltaAngle = -deltaAngle;
  72295. if (sweep)
  72296. {
  72297. if (deltaAngle < 0)
  72298. deltaAngle += double_Pi * 2.0;
  72299. }
  72300. else
  72301. {
  72302. if (deltaAngle > 0)
  72303. deltaAngle -= double_Pi * 2.0;
  72304. }
  72305. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  72306. }
  72307. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  72308. {
  72309. forEachXmlChildElement (*parent, e)
  72310. {
  72311. if (e->compareAttribute ("id", id))
  72312. return e;
  72313. const XmlElement* const found = findElementForId (e, id);
  72314. if (found != 0)
  72315. return found;
  72316. }
  72317. return 0;
  72318. }
  72319. SVGState& operator= (const SVGState&);
  72320. };
  72321. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  72322. {
  72323. SVGState state (&svgDocument);
  72324. return state.parseSVGElement (svgDocument);
  72325. }
  72326. END_JUCE_NAMESPACE
  72327. /*** End of inlined file: juce_SVGParser.cpp ***/
  72328. /*** Start of inlined file: juce_DropShadowEffect.cpp ***/
  72329. BEGIN_JUCE_NAMESPACE
  72330. #if JUCE_MSVC && JUCE_DEBUG
  72331. #pragma optimize ("t", on)
  72332. #endif
  72333. DropShadowEffect::DropShadowEffect()
  72334. : offsetX (0),
  72335. offsetY (0),
  72336. radius (4),
  72337. opacity (0.6f)
  72338. {
  72339. }
  72340. DropShadowEffect::~DropShadowEffect()
  72341. {
  72342. }
  72343. void DropShadowEffect::setShadowProperties (const float newRadius,
  72344. const float newOpacity,
  72345. const int newShadowOffsetX,
  72346. const int newShadowOffsetY)
  72347. {
  72348. radius = jmax (1.1f, newRadius);
  72349. offsetX = newShadowOffsetX;
  72350. offsetY = newShadowOffsetY;
  72351. opacity = newOpacity;
  72352. }
  72353. void DropShadowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72354. {
  72355. const int w = image.getWidth();
  72356. const int h = image.getHeight();
  72357. Image shadowImage (Image::SingleChannel, w, h, false);
  72358. const Image::BitmapData srcData (image, false);
  72359. const Image::BitmapData destData (shadowImage, true);
  72360. const int filter = roundToInt (63.0f / radius);
  72361. const int radiusMinus1 = roundToInt ((radius - 1.0f) * 63.0f);
  72362. for (int x = w; --x >= 0;)
  72363. {
  72364. int shadowAlpha = 0;
  72365. const PixelARGB* src = ((const PixelARGB*) srcData.data) + x;
  72366. uint8* shadowPix = destData.data + x;
  72367. for (int y = h; --y >= 0;)
  72368. {
  72369. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  72370. *shadowPix = (uint8) shadowAlpha;
  72371. src = (const PixelARGB*) (((const uint8*) src) + srcData.lineStride);
  72372. shadowPix += destData.lineStride;
  72373. }
  72374. }
  72375. for (int y = h; --y >= 0;)
  72376. {
  72377. int shadowAlpha = 0;
  72378. uint8* shadowPix = destData.getLinePointer (y);
  72379. for (int x = w; --x >= 0;)
  72380. {
  72381. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  72382. *shadowPix++ = (uint8) shadowAlpha;
  72383. }
  72384. }
  72385. g.setColour (Colours::black.withAlpha (opacity * alpha));
  72386. g.drawImageAt (shadowImage, offsetX, offsetY, true);
  72387. g.setOpacity (alpha);
  72388. g.drawImageAt (image, 0, 0);
  72389. }
  72390. #if JUCE_MSVC && JUCE_DEBUG
  72391. #pragma optimize ("", on) // resets optimisations to the project defaults
  72392. #endif
  72393. END_JUCE_NAMESPACE
  72394. /*** End of inlined file: juce_DropShadowEffect.cpp ***/
  72395. /*** Start of inlined file: juce_GlowEffect.cpp ***/
  72396. BEGIN_JUCE_NAMESPACE
  72397. GlowEffect::GlowEffect()
  72398. : radius (2.0f),
  72399. colour (Colours::white)
  72400. {
  72401. }
  72402. GlowEffect::~GlowEffect()
  72403. {
  72404. }
  72405. void GlowEffect::setGlowProperties (const float newRadius,
  72406. const Colour& newColour)
  72407. {
  72408. radius = newRadius;
  72409. colour = newColour;
  72410. }
  72411. void GlowEffect::applyEffect (Image& image, Graphics& g, float alpha)
  72412. {
  72413. Image temp (image.getFormat(), image.getWidth(), image.getHeight(), true);
  72414. ImageConvolutionKernel blurKernel (roundToInt (radius * 2.0f));
  72415. blurKernel.createGaussianBlur (radius);
  72416. blurKernel.rescaleAllValues (radius);
  72417. blurKernel.applyToImage (temp, image, image.getBounds());
  72418. g.setColour (colour.withMultipliedAlpha (alpha));
  72419. g.drawImageAt (temp, 0, 0, true);
  72420. g.setOpacity (alpha);
  72421. g.drawImageAt (image, 0, 0, false);
  72422. }
  72423. END_JUCE_NAMESPACE
  72424. /*** End of inlined file: juce_GlowEffect.cpp ***/
  72425. /*** Start of inlined file: juce_Font.cpp ***/
  72426. BEGIN_JUCE_NAMESPACE
  72427. namespace FontValues
  72428. {
  72429. static float limitFontHeight (const float height) throw()
  72430. {
  72431. return jlimit (0.1f, 10000.0f, height);
  72432. }
  72433. static const float defaultFontHeight = 14.0f;
  72434. static String fallbackFont;
  72435. }
  72436. Font::SharedFontInternal::SharedFontInternal (const String& typefaceName_, const float height_, const float horizontalScale_,
  72437. const float kerning_, const float ascent_, const int styleFlags_,
  72438. Typeface* const typeface_) throw()
  72439. : typefaceName (typefaceName_),
  72440. height (height_),
  72441. horizontalScale (horizontalScale_),
  72442. kerning (kerning_),
  72443. ascent (ascent_),
  72444. styleFlags (styleFlags_),
  72445. typeface (typeface_)
  72446. {
  72447. }
  72448. Font::SharedFontInternal::SharedFontInternal (const SharedFontInternal& other) throw()
  72449. : typefaceName (other.typefaceName),
  72450. height (other.height),
  72451. horizontalScale (other.horizontalScale),
  72452. kerning (other.kerning),
  72453. ascent (other.ascent),
  72454. styleFlags (other.styleFlags),
  72455. typeface (other.typeface)
  72456. {
  72457. }
  72458. Font::Font()
  72459. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::defaultFontHeight,
  72460. 1.0f, 0, 0, Font::plain, 0))
  72461. {
  72462. }
  72463. Font::Font (const float fontHeight, const int styleFlags_)
  72464. : font (new SharedFontInternal (getDefaultSansSerifFontName(), FontValues::limitFontHeight (fontHeight),
  72465. 1.0f, 0, 0, styleFlags_, 0))
  72466. {
  72467. }
  72468. Font::Font (const String& typefaceName_,
  72469. const float fontHeight,
  72470. const int styleFlags_)
  72471. : font (new SharedFontInternal (typefaceName_, FontValues::limitFontHeight (fontHeight),
  72472. 1.0f, 0, 0, styleFlags_, 0))
  72473. {
  72474. }
  72475. Font::Font (const Font& other) throw()
  72476. : font (other.font)
  72477. {
  72478. }
  72479. Font& Font::operator= (const Font& other) throw()
  72480. {
  72481. font = other.font;
  72482. return *this;
  72483. }
  72484. Font::~Font() throw()
  72485. {
  72486. }
  72487. Font::Font (const Typeface::Ptr& typeface)
  72488. : font (new SharedFontInternal (typeface->getName(), FontValues::defaultFontHeight,
  72489. 1.0f, 0, 0, Font::plain, typeface))
  72490. {
  72491. }
  72492. bool Font::operator== (const Font& other) const throw()
  72493. {
  72494. return font == other.font
  72495. || (font->height == other.font->height
  72496. && font->styleFlags == other.font->styleFlags
  72497. && font->horizontalScale == other.font->horizontalScale
  72498. && font->kerning == other.font->kerning
  72499. && font->typefaceName == other.font->typefaceName);
  72500. }
  72501. bool Font::operator!= (const Font& other) const throw()
  72502. {
  72503. return ! operator== (other);
  72504. }
  72505. void Font::dupeInternalIfShared()
  72506. {
  72507. if (font->getReferenceCount() > 1)
  72508. font = new SharedFontInternal (*font);
  72509. }
  72510. const String Font::getDefaultSansSerifFontName()
  72511. {
  72512. static const String name ("<Sans-Serif>");
  72513. return name;
  72514. }
  72515. const String Font::getDefaultSerifFontName()
  72516. {
  72517. static const String name ("<Serif>");
  72518. return name;
  72519. }
  72520. const String Font::getDefaultMonospacedFontName()
  72521. {
  72522. static const String name ("<Monospaced>");
  72523. return name;
  72524. }
  72525. void Font::setTypefaceName (const String& faceName)
  72526. {
  72527. if (faceName != font->typefaceName)
  72528. {
  72529. dupeInternalIfShared();
  72530. font->typefaceName = faceName;
  72531. font->typeface = 0;
  72532. font->ascent = 0;
  72533. }
  72534. }
  72535. const String Font::getFallbackFontName()
  72536. {
  72537. return FontValues::fallbackFont;
  72538. }
  72539. void Font::setFallbackFontName (const String& name)
  72540. {
  72541. FontValues::fallbackFont = name;
  72542. }
  72543. void Font::setHeight (float newHeight)
  72544. {
  72545. newHeight = FontValues::limitFontHeight (newHeight);
  72546. if (font->height != newHeight)
  72547. {
  72548. dupeInternalIfShared();
  72549. font->height = newHeight;
  72550. }
  72551. }
  72552. void Font::setHeightWithoutChangingWidth (float newHeight)
  72553. {
  72554. newHeight = FontValues::limitFontHeight (newHeight);
  72555. if (font->height != newHeight)
  72556. {
  72557. dupeInternalIfShared();
  72558. font->horizontalScale *= (font->height / newHeight);
  72559. font->height = newHeight;
  72560. }
  72561. }
  72562. void Font::setStyleFlags (const int newFlags)
  72563. {
  72564. if (font->styleFlags != newFlags)
  72565. {
  72566. dupeInternalIfShared();
  72567. font->styleFlags = newFlags;
  72568. font->typeface = 0;
  72569. font->ascent = 0;
  72570. }
  72571. }
  72572. void Font::setSizeAndStyle (float newHeight,
  72573. const int newStyleFlags,
  72574. const float newHorizontalScale,
  72575. const float newKerningAmount)
  72576. {
  72577. newHeight = FontValues::limitFontHeight (newHeight);
  72578. if (font->height != newHeight
  72579. || font->horizontalScale != newHorizontalScale
  72580. || font->kerning != newKerningAmount)
  72581. {
  72582. dupeInternalIfShared();
  72583. font->height = newHeight;
  72584. font->horizontalScale = newHorizontalScale;
  72585. font->kerning = newKerningAmount;
  72586. }
  72587. setStyleFlags (newStyleFlags);
  72588. }
  72589. void Font::setHorizontalScale (const float scaleFactor)
  72590. {
  72591. dupeInternalIfShared();
  72592. font->horizontalScale = scaleFactor;
  72593. }
  72594. void Font::setExtraKerningFactor (const float extraKerning)
  72595. {
  72596. dupeInternalIfShared();
  72597. font->kerning = extraKerning;
  72598. }
  72599. void Font::setBold (const bool shouldBeBold)
  72600. {
  72601. setStyleFlags (shouldBeBold ? (font->styleFlags | bold)
  72602. : (font->styleFlags & ~bold));
  72603. }
  72604. const Font Font::boldened() const
  72605. {
  72606. Font f (*this);
  72607. f.setBold (true);
  72608. return f;
  72609. }
  72610. bool Font::isBold() const throw()
  72611. {
  72612. return (font->styleFlags & bold) != 0;
  72613. }
  72614. void Font::setItalic (const bool shouldBeItalic)
  72615. {
  72616. setStyleFlags (shouldBeItalic ? (font->styleFlags | italic)
  72617. : (font->styleFlags & ~italic));
  72618. }
  72619. const Font Font::italicised() const
  72620. {
  72621. Font f (*this);
  72622. f.setItalic (true);
  72623. return f;
  72624. }
  72625. bool Font::isItalic() const throw()
  72626. {
  72627. return (font->styleFlags & italic) != 0;
  72628. }
  72629. void Font::setUnderline (const bool shouldBeUnderlined)
  72630. {
  72631. setStyleFlags (shouldBeUnderlined ? (font->styleFlags | underlined)
  72632. : (font->styleFlags & ~underlined));
  72633. }
  72634. bool Font::isUnderlined() const throw()
  72635. {
  72636. return (font->styleFlags & underlined) != 0;
  72637. }
  72638. float Font::getAscent() const
  72639. {
  72640. if (font->ascent == 0)
  72641. font->ascent = getTypeface()->getAscent();
  72642. return font->height * font->ascent;
  72643. }
  72644. float Font::getDescent() const
  72645. {
  72646. return font->height - getAscent();
  72647. }
  72648. int Font::getStringWidth (const String& text) const
  72649. {
  72650. return roundToInt (getStringWidthFloat (text));
  72651. }
  72652. float Font::getStringWidthFloat (const String& text) const
  72653. {
  72654. float w = getTypeface()->getStringWidth (text);
  72655. if (font->kerning != 0)
  72656. w += font->kerning * text.length();
  72657. return w * font->height * font->horizontalScale;
  72658. }
  72659. void Font::getGlyphPositions (const String& text, Array <int>& glyphs, Array <float>& xOffsets) const
  72660. {
  72661. getTypeface()->getGlyphPositions (text, glyphs, xOffsets);
  72662. const float scale = font->height * font->horizontalScale;
  72663. const int num = xOffsets.size();
  72664. if (num > 0)
  72665. {
  72666. float* const x = &(xOffsets.getReference(0));
  72667. if (font->kerning != 0)
  72668. {
  72669. for (int i = 0; i < num; ++i)
  72670. x[i] = (x[i] + i * font->kerning) * scale;
  72671. }
  72672. else
  72673. {
  72674. for (int i = 0; i < num; ++i)
  72675. x[i] *= scale;
  72676. }
  72677. }
  72678. }
  72679. void Font::findFonts (Array<Font>& destArray)
  72680. {
  72681. const StringArray names (findAllTypefaceNames());
  72682. for (int i = 0; i < names.size(); ++i)
  72683. destArray.add (Font (names[i], FontValues::defaultFontHeight, Font::plain));
  72684. }
  72685. const String Font::toString() const
  72686. {
  72687. String s (getTypefaceName());
  72688. if (s == getDefaultSansSerifFontName())
  72689. s = String::empty;
  72690. else
  72691. s += "; ";
  72692. s += String (getHeight(), 1);
  72693. if (isBold())
  72694. s += " bold";
  72695. if (isItalic())
  72696. s += " italic";
  72697. return s;
  72698. }
  72699. const Font Font::fromString (const String& fontDescription)
  72700. {
  72701. String name;
  72702. const int separator = fontDescription.indexOfChar (';');
  72703. if (separator > 0)
  72704. name = fontDescription.substring (0, separator).trim();
  72705. if (name.isEmpty())
  72706. name = getDefaultSansSerifFontName();
  72707. String sizeAndStyle (fontDescription.substring (separator + 1));
  72708. float height = sizeAndStyle.getFloatValue();
  72709. if (height <= 0)
  72710. height = 10.0f;
  72711. int flags = Font::plain;
  72712. if (sizeAndStyle.containsIgnoreCase ("bold"))
  72713. flags |= Font::bold;
  72714. if (sizeAndStyle.containsIgnoreCase ("italic"))
  72715. flags |= Font::italic;
  72716. return Font (name, height, flags);
  72717. }
  72718. class TypefaceCache : public DeletedAtShutdown
  72719. {
  72720. public:
  72721. TypefaceCache (int numToCache = 10)
  72722. : counter (1)
  72723. {
  72724. while (--numToCache >= 0)
  72725. faces.add (new CachedFace());
  72726. }
  72727. ~TypefaceCache()
  72728. {
  72729. clearSingletonInstance();
  72730. }
  72731. juce_DeclareSingleton_SingleThreaded_Minimal (TypefaceCache)
  72732. const Typeface::Ptr findTypefaceFor (const Font& font)
  72733. {
  72734. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  72735. const String faceName (font.getTypefaceName());
  72736. int i;
  72737. for (i = faces.size(); --i >= 0;)
  72738. {
  72739. CachedFace* const face = faces.getUnchecked(i);
  72740. if (face->flags == flags
  72741. && face->typefaceName == faceName)
  72742. {
  72743. face->lastUsageCount = ++counter;
  72744. return face->typeFace;
  72745. }
  72746. }
  72747. int replaceIndex = 0;
  72748. int bestLastUsageCount = std::numeric_limits<int>::max();
  72749. for (i = faces.size(); --i >= 0;)
  72750. {
  72751. const int lu = faces.getUnchecked(i)->lastUsageCount;
  72752. if (bestLastUsageCount > lu)
  72753. {
  72754. bestLastUsageCount = lu;
  72755. replaceIndex = i;
  72756. }
  72757. }
  72758. CachedFace* const face = faces.getUnchecked (replaceIndex);
  72759. face->typefaceName = faceName;
  72760. face->flags = flags;
  72761. face->lastUsageCount = ++counter;
  72762. face->typeFace = LookAndFeel::getDefaultLookAndFeel().getTypefaceForFont (font);
  72763. jassert (face->typeFace != 0); // the look and feel must return a typeface!
  72764. return face->typeFace;
  72765. }
  72766. juce_UseDebuggingNewOperator
  72767. private:
  72768. struct CachedFace
  72769. {
  72770. CachedFace() throw()
  72771. : lastUsageCount (0), flags (-1)
  72772. {
  72773. }
  72774. String typefaceName;
  72775. int lastUsageCount;
  72776. int flags;
  72777. Typeface::Ptr typeFace;
  72778. };
  72779. int counter;
  72780. OwnedArray <CachedFace> faces;
  72781. TypefaceCache (const TypefaceCache&);
  72782. TypefaceCache& operator= (const TypefaceCache&);
  72783. };
  72784. juce_ImplementSingleton_SingleThreaded (TypefaceCache)
  72785. Typeface* Font::getTypeface() const
  72786. {
  72787. if (font->typeface == 0)
  72788. font->typeface = TypefaceCache::getInstance()->findTypefaceFor (*this);
  72789. return font->typeface;
  72790. }
  72791. END_JUCE_NAMESPACE
  72792. /*** End of inlined file: juce_Font.cpp ***/
  72793. /*** Start of inlined file: juce_GlyphArrangement.cpp ***/
  72794. BEGIN_JUCE_NAMESPACE
  72795. PositionedGlyph::PositionedGlyph (const float x_, const float y_, const float w_, const Font& font_,
  72796. const juce_wchar character_, const int glyph_)
  72797. : x (x_),
  72798. y (y_),
  72799. w (w_),
  72800. font (font_),
  72801. character (character_),
  72802. glyph (glyph_)
  72803. {
  72804. }
  72805. PositionedGlyph::PositionedGlyph (const PositionedGlyph& other)
  72806. : x (other.x),
  72807. y (other.y),
  72808. w (other.w),
  72809. font (other.font),
  72810. character (other.character),
  72811. glyph (other.glyph)
  72812. {
  72813. }
  72814. void PositionedGlyph::draw (const Graphics& g) const
  72815. {
  72816. if (! isWhitespace())
  72817. {
  72818. g.getInternalContext()->setFont (font);
  72819. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y));
  72820. }
  72821. }
  72822. void PositionedGlyph::draw (const Graphics& g,
  72823. const AffineTransform& transform) const
  72824. {
  72825. if (! isWhitespace())
  72826. {
  72827. g.getInternalContext()->setFont (font);
  72828. g.getInternalContext()->drawGlyph (glyph, AffineTransform::translation (x, y)
  72829. .followedBy (transform));
  72830. }
  72831. }
  72832. void PositionedGlyph::createPath (Path& path) const
  72833. {
  72834. if (! isWhitespace())
  72835. {
  72836. Typeface* const t = font.getTypeface();
  72837. if (t != 0)
  72838. {
  72839. Path p;
  72840. t->getOutlineForGlyph (glyph, p);
  72841. path.addPath (p, AffineTransform::scale (font.getHeight() * font.getHorizontalScale(), font.getHeight())
  72842. .translated (x, y));
  72843. }
  72844. }
  72845. }
  72846. bool PositionedGlyph::hitTest (float px, float py) const
  72847. {
  72848. if (getBounds().contains (px, py) && ! isWhitespace())
  72849. {
  72850. Typeface* const t = font.getTypeface();
  72851. if (t != 0)
  72852. {
  72853. Path p;
  72854. t->getOutlineForGlyph (glyph, p);
  72855. AffineTransform::translation (-x, -y)
  72856. .scaled (1.0f / (font.getHeight() * font.getHorizontalScale()), 1.0f / font.getHeight())
  72857. .transformPoint (px, py);
  72858. return p.contains (px, py);
  72859. }
  72860. }
  72861. return false;
  72862. }
  72863. void PositionedGlyph::moveBy (const float deltaX,
  72864. const float deltaY)
  72865. {
  72866. x += deltaX;
  72867. y += deltaY;
  72868. }
  72869. GlyphArrangement::GlyphArrangement()
  72870. {
  72871. glyphs.ensureStorageAllocated (128);
  72872. }
  72873. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other)
  72874. {
  72875. addGlyphArrangement (other);
  72876. }
  72877. GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other)
  72878. {
  72879. if (this != &other)
  72880. {
  72881. clear();
  72882. addGlyphArrangement (other);
  72883. }
  72884. return *this;
  72885. }
  72886. GlyphArrangement::~GlyphArrangement()
  72887. {
  72888. }
  72889. void GlyphArrangement::clear()
  72890. {
  72891. glyphs.clear();
  72892. }
  72893. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const
  72894. {
  72895. jassert (((unsigned int) index) < (unsigned int) glyphs.size());
  72896. return *glyphs [index];
  72897. }
  72898. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other)
  72899. {
  72900. glyphs.ensureStorageAllocated (glyphs.size() + other.glyphs.size());
  72901. glyphs.addCopiesOf (other.glyphs);
  72902. }
  72903. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num)
  72904. {
  72905. glyphs.removeRange (startIndex, num < 0 ? glyphs.size() : num);
  72906. }
  72907. void GlyphArrangement::addLineOfText (const Font& font,
  72908. const String& text,
  72909. const float xOffset,
  72910. const float yOffset)
  72911. {
  72912. addCurtailedLineOfText (font, text,
  72913. xOffset, yOffset,
  72914. 1.0e10f, false);
  72915. }
  72916. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  72917. const String& text,
  72918. float xOffset,
  72919. const float yOffset,
  72920. const float maxWidthPixels,
  72921. const bool useEllipsis)
  72922. {
  72923. if (text.isNotEmpty())
  72924. {
  72925. Array <int> newGlyphs;
  72926. Array <float> xOffsets;
  72927. font.getGlyphPositions (text, newGlyphs, xOffsets);
  72928. const int textLen = newGlyphs.size();
  72929. const juce_wchar* const unicodeText = text;
  72930. for (int i = 0; i < textLen; ++i)
  72931. {
  72932. const float thisX = xOffsets.getUnchecked (i);
  72933. const float nextX = xOffsets.getUnchecked (i + 1);
  72934. if (nextX > maxWidthPixels + 1.0f)
  72935. {
  72936. // curtail the string if it's too wide..
  72937. if (useEllipsis && textLen > 3 && glyphs.size() >= 3)
  72938. insertEllipsis (font, xOffset + maxWidthPixels, 0, glyphs.size());
  72939. break;
  72940. }
  72941. else
  72942. {
  72943. glyphs.add (new PositionedGlyph (xOffset + thisX, yOffset, nextX - thisX,
  72944. font, unicodeText[i], newGlyphs.getUnchecked(i)));
  72945. }
  72946. }
  72947. }
  72948. }
  72949. int GlyphArrangement::insertEllipsis (const Font& font, const float maxXPos,
  72950. const int startIndex, int endIndex)
  72951. {
  72952. int numDeleted = 0;
  72953. if (glyphs.size() > 0)
  72954. {
  72955. Array<int> dotGlyphs;
  72956. Array<float> dotXs;
  72957. font.getGlyphPositions ("..", dotGlyphs, dotXs);
  72958. const float dx = dotXs[1];
  72959. float xOffset = 0.0f, yOffset = 0.0f;
  72960. while (endIndex > startIndex)
  72961. {
  72962. const PositionedGlyph* pg = glyphs.getUnchecked (--endIndex);
  72963. xOffset = pg->x;
  72964. yOffset = pg->y;
  72965. glyphs.remove (endIndex);
  72966. ++numDeleted;
  72967. if (xOffset + dx * 3 <= maxXPos)
  72968. break;
  72969. }
  72970. for (int i = 3; --i >= 0;)
  72971. {
  72972. glyphs.insert (endIndex++, new PositionedGlyph (xOffset, yOffset, dx,
  72973. font, '.', dotGlyphs.getFirst()));
  72974. --numDeleted;
  72975. xOffset += dx;
  72976. if (xOffset > maxXPos)
  72977. break;
  72978. }
  72979. }
  72980. return numDeleted;
  72981. }
  72982. void GlyphArrangement::addJustifiedText (const Font& font,
  72983. const String& text,
  72984. float x, float y,
  72985. const float maxLineWidth,
  72986. const Justification& horizontalLayout)
  72987. {
  72988. int lineStartIndex = glyphs.size();
  72989. addLineOfText (font, text, x, y);
  72990. const float originalY = y;
  72991. while (lineStartIndex < glyphs.size())
  72992. {
  72993. int i = lineStartIndex;
  72994. if (glyphs.getUnchecked(i)->getCharacter() != '\n'
  72995. && glyphs.getUnchecked(i)->getCharacter() != '\r')
  72996. ++i;
  72997. const float lineMaxX = glyphs.getUnchecked (lineStartIndex)->getLeft() + maxLineWidth;
  72998. int lastWordBreakIndex = -1;
  72999. while (i < glyphs.size())
  73000. {
  73001. const PositionedGlyph* pg = glyphs.getUnchecked (i);
  73002. const juce_wchar c = pg->getCharacter();
  73003. if (c == '\r' || c == '\n')
  73004. {
  73005. ++i;
  73006. if (c == '\r' && i < glyphs.size()
  73007. && glyphs.getUnchecked(i)->getCharacter() == '\n')
  73008. ++i;
  73009. break;
  73010. }
  73011. else if (pg->isWhitespace())
  73012. {
  73013. lastWordBreakIndex = i + 1;
  73014. }
  73015. else if (pg->getRight() - 0.0001f >= lineMaxX)
  73016. {
  73017. if (lastWordBreakIndex >= 0)
  73018. i = lastWordBreakIndex;
  73019. break;
  73020. }
  73021. ++i;
  73022. }
  73023. const float currentLineStartX = glyphs.getUnchecked (lineStartIndex)->getLeft();
  73024. float currentLineEndX = currentLineStartX;
  73025. for (int j = i; --j >= lineStartIndex;)
  73026. {
  73027. if (! glyphs.getUnchecked (j)->isWhitespace())
  73028. {
  73029. currentLineEndX = glyphs.getUnchecked (j)->getRight();
  73030. break;
  73031. }
  73032. }
  73033. float deltaX = 0.0f;
  73034. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  73035. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  73036. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  73037. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  73038. else if (horizontalLayout.testFlags (Justification::right))
  73039. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  73040. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  73041. x + deltaX - currentLineStartX, y - originalY);
  73042. lineStartIndex = i;
  73043. y += font.getHeight();
  73044. }
  73045. }
  73046. void GlyphArrangement::addFittedText (const Font& f,
  73047. const String& text,
  73048. const float x, const float y,
  73049. const float width, const float height,
  73050. const Justification& layout,
  73051. int maximumLines,
  73052. const float minimumHorizontalScale)
  73053. {
  73054. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  73055. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  73056. if (text.containsAnyOf ("\r\n"))
  73057. {
  73058. GlyphArrangement ga;
  73059. ga.addJustifiedText (f, text, x, y, width, layout);
  73060. const Rectangle<float> bb (ga.getBoundingBox (0, -1, false));
  73061. float dy = y - bb.getY();
  73062. if (layout.testFlags (Justification::verticallyCentred))
  73063. dy += (height - bb.getHeight()) * 0.5f;
  73064. else if (layout.testFlags (Justification::bottom))
  73065. dy += height - bb.getHeight();
  73066. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  73067. glyphs.ensureStorageAllocated (glyphs.size() + ga.glyphs.size());
  73068. for (int i = 0; i < ga.glyphs.size(); ++i)
  73069. glyphs.add (ga.glyphs.getUnchecked (i));
  73070. ga.glyphs.clear (false);
  73071. return;
  73072. }
  73073. int startIndex = glyphs.size();
  73074. addLineOfText (f, text.trim(), x, y);
  73075. if (glyphs.size() > startIndex)
  73076. {
  73077. float lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73078. - glyphs.getUnchecked (startIndex)->getLeft();
  73079. if (lineWidth <= 0)
  73080. return;
  73081. if (lineWidth * minimumHorizontalScale < width)
  73082. {
  73083. if (lineWidth > width)
  73084. stretchRangeOfGlyphs (startIndex, glyphs.size() - startIndex,
  73085. width / lineWidth);
  73086. justifyGlyphs (startIndex, glyphs.size() - startIndex,
  73087. x, y, width, height, layout);
  73088. }
  73089. else if (maximumLines <= 1)
  73090. {
  73091. fitLineIntoSpace (startIndex, glyphs.size() - startIndex,
  73092. x, y, width, height, f, layout, minimumHorizontalScale);
  73093. }
  73094. else
  73095. {
  73096. Font font (f);
  73097. String txt (text.trim());
  73098. const int length = txt.length();
  73099. const int originalStartIndex = startIndex;
  73100. int numLines = 1;
  73101. if (length <= 12 && ! txt.containsAnyOf (" -\t\r\n"))
  73102. maximumLines = 1;
  73103. maximumLines = jmin (maximumLines, length);
  73104. while (numLines < maximumLines)
  73105. {
  73106. ++numLines;
  73107. const float newFontHeight = height / (float) numLines;
  73108. if (newFontHeight < font.getHeight())
  73109. {
  73110. font.setHeight (jmax (8.0f, newFontHeight));
  73111. removeRangeOfGlyphs (startIndex, -1);
  73112. addLineOfText (font, txt, x, y);
  73113. lineWidth = glyphs.getUnchecked (glyphs.size() - 1)->getRight()
  73114. - glyphs.getUnchecked (startIndex)->getLeft();
  73115. }
  73116. if (numLines > lineWidth / width || newFontHeight < 8.0f)
  73117. break;
  73118. }
  73119. if (numLines < 1)
  73120. numLines = 1;
  73121. float lineY = y;
  73122. float widthPerLine = lineWidth / numLines;
  73123. int lastLineStartIndex = 0;
  73124. for (int line = 0; line < numLines; ++line)
  73125. {
  73126. int i = startIndex;
  73127. lastLineStartIndex = i;
  73128. float lineStartX = glyphs.getUnchecked (startIndex)->getLeft();
  73129. if (line == numLines - 1)
  73130. {
  73131. widthPerLine = width;
  73132. i = glyphs.size();
  73133. }
  73134. else
  73135. {
  73136. while (i < glyphs.size())
  73137. {
  73138. lineWidth = (glyphs.getUnchecked (i)->getRight() - lineStartX);
  73139. if (lineWidth > widthPerLine)
  73140. {
  73141. // got to a point where the line's too long, so skip forward to find a
  73142. // good place to break it..
  73143. const int searchStartIndex = i;
  73144. while (i < glyphs.size())
  73145. {
  73146. if ((glyphs.getUnchecked (i)->getRight() - lineStartX) * minimumHorizontalScale < width)
  73147. {
  73148. if (glyphs.getUnchecked (i)->isWhitespace()
  73149. || glyphs.getUnchecked (i)->getCharacter() == '-')
  73150. {
  73151. ++i;
  73152. break;
  73153. }
  73154. }
  73155. else
  73156. {
  73157. // can't find a suitable break, so try looking backwards..
  73158. i = searchStartIndex;
  73159. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  73160. {
  73161. if (glyphs.getUnchecked (i - back)->isWhitespace()
  73162. || glyphs.getUnchecked (i - back)->getCharacter() == '-')
  73163. {
  73164. i -= back - 1;
  73165. break;
  73166. }
  73167. }
  73168. break;
  73169. }
  73170. ++i;
  73171. }
  73172. break;
  73173. }
  73174. ++i;
  73175. }
  73176. int wsStart = i;
  73177. while (wsStart > 0 && glyphs.getUnchecked (wsStart - 1)->isWhitespace())
  73178. --wsStart;
  73179. int wsEnd = i;
  73180. while (wsEnd < glyphs.size() && glyphs.getUnchecked (wsEnd)->isWhitespace())
  73181. ++wsEnd;
  73182. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  73183. i = jmax (wsStart, startIndex + 1);
  73184. }
  73185. i -= fitLineIntoSpace (startIndex, i - startIndex,
  73186. x, lineY, width, font.getHeight(), font,
  73187. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  73188. minimumHorizontalScale);
  73189. startIndex = i;
  73190. lineY += font.getHeight();
  73191. if (startIndex >= glyphs.size())
  73192. break;
  73193. }
  73194. justifyGlyphs (originalStartIndex, glyphs.size() - originalStartIndex,
  73195. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  73196. }
  73197. }
  73198. }
  73199. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  73200. const float dx, const float dy)
  73201. {
  73202. jassert (startIndex >= 0);
  73203. if (dx != 0.0f || dy != 0.0f)
  73204. {
  73205. if (num < 0 || startIndex + num > glyphs.size())
  73206. num = glyphs.size() - startIndex;
  73207. while (--num >= 0)
  73208. glyphs.getUnchecked (startIndex++)->moveBy (dx, dy);
  73209. }
  73210. }
  73211. int GlyphArrangement::fitLineIntoSpace (int start, int numGlyphs, float x, float y, float w, float h, const Font& font,
  73212. const Justification& justification, float minimumHorizontalScale)
  73213. {
  73214. int numDeleted = 0;
  73215. const float lineStartX = glyphs.getUnchecked (start)->getLeft();
  73216. float lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX;
  73217. if (lineWidth > w)
  73218. {
  73219. if (minimumHorizontalScale < 1.0f)
  73220. {
  73221. stretchRangeOfGlyphs (start, numGlyphs, jmax (minimumHorizontalScale, w / lineWidth));
  73222. lineWidth = glyphs.getUnchecked (start + numGlyphs - 1)->getRight() - lineStartX - 0.5f;
  73223. }
  73224. if (lineWidth > w)
  73225. {
  73226. numDeleted = insertEllipsis (font, lineStartX + w, start, start + numGlyphs);
  73227. numGlyphs -= numDeleted;
  73228. }
  73229. }
  73230. justifyGlyphs (start, numGlyphs, x, y, w, h, justification);
  73231. return numDeleted;
  73232. }
  73233. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  73234. const float horizontalScaleFactor)
  73235. {
  73236. jassert (startIndex >= 0);
  73237. if (num < 0 || startIndex + num > glyphs.size())
  73238. num = glyphs.size() - startIndex;
  73239. if (num > 0)
  73240. {
  73241. const float xAnchor = glyphs.getUnchecked (startIndex)->getLeft();
  73242. while (--num >= 0)
  73243. {
  73244. PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73245. pg->x = xAnchor + (pg->x - xAnchor) * horizontalScaleFactor;
  73246. pg->font.setHorizontalScale (pg->font.getHorizontalScale() * horizontalScaleFactor);
  73247. pg->w *= horizontalScaleFactor;
  73248. }
  73249. }
  73250. }
  73251. const Rectangle<float> GlyphArrangement::getBoundingBox (int startIndex, int num, const bool includeWhitespace) const
  73252. {
  73253. jassert (startIndex >= 0);
  73254. if (num < 0 || startIndex + num > glyphs.size())
  73255. num = glyphs.size() - startIndex;
  73256. Rectangle<float> result;
  73257. while (--num >= 0)
  73258. {
  73259. const PositionedGlyph* const pg = glyphs.getUnchecked (startIndex++);
  73260. if (includeWhitespace || ! pg->isWhitespace())
  73261. result = result.getUnion (pg->getBounds());
  73262. }
  73263. return result;
  73264. }
  73265. void GlyphArrangement::justifyGlyphs (const int startIndex, const int num,
  73266. const float x, const float y, const float width, const float height,
  73267. const Justification& justification)
  73268. {
  73269. jassert (num >= 0 && startIndex >= 0);
  73270. if (glyphs.size() > 0 && num > 0)
  73271. {
  73272. const Rectangle<float> bb (getBoundingBox (startIndex, num, ! justification.testFlags (Justification::horizontallyJustified
  73273. | Justification::horizontallyCentred)));
  73274. float deltaX = 0.0f;
  73275. if (justification.testFlags (Justification::horizontallyJustified))
  73276. deltaX = x - bb.getX();
  73277. else if (justification.testFlags (Justification::horizontallyCentred))
  73278. deltaX = x + (width - bb.getWidth()) * 0.5f - bb.getX();
  73279. else if (justification.testFlags (Justification::right))
  73280. deltaX = (x + width) - bb.getRight();
  73281. else
  73282. deltaX = x - bb.getX();
  73283. float deltaY = 0.0f;
  73284. if (justification.testFlags (Justification::top))
  73285. deltaY = y - bb.getY();
  73286. else if (justification.testFlags (Justification::bottom))
  73287. deltaY = (y + height) - bb.getBottom();
  73288. else
  73289. deltaY = y + (height - bb.getHeight()) * 0.5f - bb.getY();
  73290. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  73291. if (justification.testFlags (Justification::horizontallyJustified))
  73292. {
  73293. int lineStart = 0;
  73294. float baseY = glyphs.getUnchecked (startIndex)->getBaselineY();
  73295. int i;
  73296. for (i = 0; i < num; ++i)
  73297. {
  73298. const float glyphY = glyphs.getUnchecked (startIndex + i)->getBaselineY();
  73299. if (glyphY != baseY)
  73300. {
  73301. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73302. lineStart = i;
  73303. baseY = glyphY;
  73304. }
  73305. }
  73306. if (i > lineStart)
  73307. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  73308. }
  73309. }
  73310. }
  73311. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth)
  73312. {
  73313. if (start + num < glyphs.size()
  73314. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\r'
  73315. && glyphs.getUnchecked (start + num - 1)->getCharacter() != '\n')
  73316. {
  73317. int numSpaces = 0;
  73318. int spacesAtEnd = 0;
  73319. for (int i = 0; i < num; ++i)
  73320. {
  73321. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73322. {
  73323. ++spacesAtEnd;
  73324. ++numSpaces;
  73325. }
  73326. else
  73327. {
  73328. spacesAtEnd = 0;
  73329. }
  73330. }
  73331. numSpaces -= spacesAtEnd;
  73332. if (numSpaces > 0)
  73333. {
  73334. const float startX = glyphs.getUnchecked (start)->getLeft();
  73335. const float endX = glyphs.getUnchecked (start + num - 1 - spacesAtEnd)->getRight();
  73336. const float extraPaddingBetweenWords
  73337. = (targetWidth - (endX - startX)) / (float) numSpaces;
  73338. float deltaX = 0.0f;
  73339. for (int i = 0; i < num; ++i)
  73340. {
  73341. glyphs.getUnchecked (start + i)->moveBy (deltaX, 0.0f);
  73342. if (glyphs.getUnchecked (start + i)->isWhitespace())
  73343. deltaX += extraPaddingBetweenWords;
  73344. }
  73345. }
  73346. }
  73347. }
  73348. void GlyphArrangement::draw (const Graphics& g) const
  73349. {
  73350. for (int i = 0; i < glyphs.size(); ++i)
  73351. {
  73352. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73353. if (pg->font.isUnderlined())
  73354. {
  73355. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73356. float nextX = pg->x + pg->w;
  73357. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73358. nextX = glyphs.getUnchecked (i + 1)->x;
  73359. g.fillRect (pg->x, pg->y + lineThickness * 2.0f,
  73360. nextX - pg->x, lineThickness);
  73361. }
  73362. pg->draw (g);
  73363. }
  73364. }
  73365. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const
  73366. {
  73367. for (int i = 0; i < glyphs.size(); ++i)
  73368. {
  73369. const PositionedGlyph* const pg = glyphs.getUnchecked(i);
  73370. if (pg->font.isUnderlined())
  73371. {
  73372. const float lineThickness = (pg->font.getDescent()) * 0.3f;
  73373. float nextX = pg->x + pg->w;
  73374. if (i < glyphs.size() - 1 && glyphs.getUnchecked (i + 1)->y == pg->y)
  73375. nextX = glyphs.getUnchecked (i + 1)->x;
  73376. Path p;
  73377. p.addLineSegment (Line<float> (pg->x, pg->y + lineThickness * 2.0f,
  73378. nextX, pg->y + lineThickness * 2.0f),
  73379. lineThickness);
  73380. g.fillPath (p, transform);
  73381. }
  73382. pg->draw (g, transform);
  73383. }
  73384. }
  73385. void GlyphArrangement::createPath (Path& path) const
  73386. {
  73387. for (int i = 0; i < glyphs.size(); ++i)
  73388. glyphs.getUnchecked (i)->createPath (path);
  73389. }
  73390. int GlyphArrangement::findGlyphIndexAt (float x, float y) const
  73391. {
  73392. for (int i = 0; i < glyphs.size(); ++i)
  73393. if (glyphs.getUnchecked (i)->hitTest (x, y))
  73394. return i;
  73395. return -1;
  73396. }
  73397. END_JUCE_NAMESPACE
  73398. /*** End of inlined file: juce_GlyphArrangement.cpp ***/
  73399. /*** Start of inlined file: juce_TextLayout.cpp ***/
  73400. BEGIN_JUCE_NAMESPACE
  73401. class TextLayout::Token
  73402. {
  73403. public:
  73404. String text;
  73405. Font font;
  73406. int x, y, w, h;
  73407. int line, lineHeight;
  73408. bool isWhitespace, isNewLine;
  73409. Token (const String& t,
  73410. const Font& f,
  73411. const bool isWhitespace_)
  73412. : text (t),
  73413. font (f),
  73414. x(0),
  73415. y(0),
  73416. isWhitespace (isWhitespace_)
  73417. {
  73418. w = font.getStringWidth (t);
  73419. h = roundToInt (f.getHeight());
  73420. isNewLine = t.containsChar ('\n') || t.containsChar ('\r');
  73421. }
  73422. Token (const Token& other)
  73423. : text (other.text),
  73424. font (other.font),
  73425. x (other.x),
  73426. y (other.y),
  73427. w (other.w),
  73428. h (other.h),
  73429. line (other.line),
  73430. lineHeight (other.lineHeight),
  73431. isWhitespace (other.isWhitespace),
  73432. isNewLine (other.isNewLine)
  73433. {
  73434. }
  73435. ~Token()
  73436. {
  73437. }
  73438. void draw (Graphics& g,
  73439. const int xOffset,
  73440. const int yOffset)
  73441. {
  73442. if (! isWhitespace)
  73443. {
  73444. g.setFont (font);
  73445. g.drawSingleLineText (text.trimEnd(),
  73446. xOffset + x,
  73447. yOffset + y + (lineHeight - h)
  73448. + roundToInt (font.getAscent()));
  73449. }
  73450. }
  73451. juce_UseDebuggingNewOperator
  73452. };
  73453. TextLayout::TextLayout()
  73454. : totalLines (0)
  73455. {
  73456. tokens.ensureStorageAllocated (64);
  73457. }
  73458. TextLayout::TextLayout (const String& text, const Font& font)
  73459. : totalLines (0)
  73460. {
  73461. tokens.ensureStorageAllocated (64);
  73462. appendText (text, font);
  73463. }
  73464. TextLayout::TextLayout (const TextLayout& other)
  73465. : totalLines (0)
  73466. {
  73467. *this = other;
  73468. }
  73469. TextLayout& TextLayout::operator= (const TextLayout& other)
  73470. {
  73471. if (this != &other)
  73472. {
  73473. clear();
  73474. totalLines = other.totalLines;
  73475. tokens.addCopiesOf (other.tokens);
  73476. }
  73477. return *this;
  73478. }
  73479. TextLayout::~TextLayout()
  73480. {
  73481. clear();
  73482. }
  73483. void TextLayout::clear()
  73484. {
  73485. tokens.clear();
  73486. totalLines = 0;
  73487. }
  73488. bool TextLayout::isEmpty() const
  73489. {
  73490. return tokens.size() == 0;
  73491. }
  73492. void TextLayout::appendText (const String& text, const Font& font)
  73493. {
  73494. const juce_wchar* t = text;
  73495. String currentString;
  73496. int lastCharType = 0;
  73497. for (;;)
  73498. {
  73499. const juce_wchar c = *t++;
  73500. if (c == 0)
  73501. break;
  73502. int charType;
  73503. if (c == '\r' || c == '\n')
  73504. {
  73505. charType = 0;
  73506. }
  73507. else if (CharacterFunctions::isWhitespace (c))
  73508. {
  73509. charType = 2;
  73510. }
  73511. else
  73512. {
  73513. charType = 1;
  73514. }
  73515. if (charType == 0 || charType != lastCharType)
  73516. {
  73517. if (currentString.isNotEmpty())
  73518. {
  73519. tokens.add (new Token (currentString, font,
  73520. lastCharType == 2 || lastCharType == 0));
  73521. }
  73522. currentString = String::charToString (c);
  73523. if (c == '\r' && *t == '\n')
  73524. currentString += *t++;
  73525. }
  73526. else
  73527. {
  73528. currentString += c;
  73529. }
  73530. lastCharType = charType;
  73531. }
  73532. if (currentString.isNotEmpty())
  73533. tokens.add (new Token (currentString, font, lastCharType == 2));
  73534. }
  73535. void TextLayout::setText (const String& text, const Font& font)
  73536. {
  73537. clear();
  73538. appendText (text, font);
  73539. }
  73540. void TextLayout::layout (int maxWidth,
  73541. const Justification& justification,
  73542. const bool attemptToBalanceLineLengths)
  73543. {
  73544. if (attemptToBalanceLineLengths)
  73545. {
  73546. const int originalW = maxWidth;
  73547. int bestWidth = maxWidth;
  73548. float bestLineProportion = 0.0f;
  73549. while (maxWidth > originalW / 2)
  73550. {
  73551. layout (maxWidth, justification, false);
  73552. if (getNumLines() <= 1)
  73553. return;
  73554. const int lastLineW = getLineWidth (getNumLines() - 1);
  73555. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  73556. const float prop = lastLineW / (float) lastButOneLineW;
  73557. if (prop > 0.9f)
  73558. return;
  73559. if (prop > bestLineProportion)
  73560. {
  73561. bestLineProportion = prop;
  73562. bestWidth = maxWidth;
  73563. }
  73564. maxWidth -= 10;
  73565. }
  73566. layout (bestWidth, justification, false);
  73567. }
  73568. else
  73569. {
  73570. int x = 0;
  73571. int y = 0;
  73572. int h = 0;
  73573. totalLines = 0;
  73574. int i;
  73575. for (i = 0; i < tokens.size(); ++i)
  73576. {
  73577. Token* const t = tokens.getUnchecked(i);
  73578. t->x = x;
  73579. t->y = y;
  73580. t->line = totalLines;
  73581. x += t->w;
  73582. h = jmax (h, t->h);
  73583. const Token* nextTok = tokens [i + 1];
  73584. if (nextTok == 0)
  73585. break;
  73586. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  73587. {
  73588. // finished a line, so go back and update the heights of the things on it
  73589. for (int j = i; j >= 0; --j)
  73590. {
  73591. Token* const tok = tokens.getUnchecked(j);
  73592. if (tok->line == totalLines)
  73593. tok->lineHeight = h;
  73594. else
  73595. break;
  73596. }
  73597. x = 0;
  73598. y += h;
  73599. h = 0;
  73600. ++totalLines;
  73601. }
  73602. }
  73603. // finished a line, so go back and update the heights of the things on it
  73604. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  73605. {
  73606. Token* const t = tokens.getUnchecked(j);
  73607. if (t->line == totalLines)
  73608. t->lineHeight = h;
  73609. else
  73610. break;
  73611. }
  73612. ++totalLines;
  73613. if (! justification.testFlags (Justification::left))
  73614. {
  73615. int totalW = getWidth();
  73616. for (i = totalLines; --i >= 0;)
  73617. {
  73618. const int lineW = getLineWidth (i);
  73619. int dx = 0;
  73620. if (justification.testFlags (Justification::horizontallyCentred))
  73621. dx = (totalW - lineW) / 2;
  73622. else if (justification.testFlags (Justification::right))
  73623. dx = totalW - lineW;
  73624. for (int j = tokens.size(); --j >= 0;)
  73625. {
  73626. Token* const t = tokens.getUnchecked(j);
  73627. if (t->line == i)
  73628. t->x += dx;
  73629. }
  73630. }
  73631. }
  73632. }
  73633. }
  73634. int TextLayout::getLineWidth (const int lineNumber) const
  73635. {
  73636. int maxW = 0;
  73637. for (int i = tokens.size(); --i >= 0;)
  73638. {
  73639. const Token* const t = tokens.getUnchecked(i);
  73640. if (t->line == lineNumber && ! t->isWhitespace)
  73641. maxW = jmax (maxW, t->x + t->w);
  73642. }
  73643. return maxW;
  73644. }
  73645. int TextLayout::getWidth() const
  73646. {
  73647. int maxW = 0;
  73648. for (int i = tokens.size(); --i >= 0;)
  73649. {
  73650. const Token* const t = tokens.getUnchecked(i);
  73651. if (! t->isWhitespace)
  73652. maxW = jmax (maxW, t->x + t->w);
  73653. }
  73654. return maxW;
  73655. }
  73656. int TextLayout::getHeight() const
  73657. {
  73658. int maxH = 0;
  73659. for (int i = tokens.size(); --i >= 0;)
  73660. {
  73661. const Token* const t = tokens.getUnchecked(i);
  73662. if (! t->isWhitespace)
  73663. maxH = jmax (maxH, t->y + t->h);
  73664. }
  73665. return maxH;
  73666. }
  73667. void TextLayout::draw (Graphics& g,
  73668. const int xOffset,
  73669. const int yOffset) const
  73670. {
  73671. for (int i = tokens.size(); --i >= 0;)
  73672. tokens.getUnchecked(i)->draw (g, xOffset, yOffset);
  73673. }
  73674. void TextLayout::drawWithin (Graphics& g,
  73675. int x, int y, int w, int h,
  73676. const Justification& justification) const
  73677. {
  73678. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  73679. x, y, w, h);
  73680. draw (g, x, y);
  73681. }
  73682. END_JUCE_NAMESPACE
  73683. /*** End of inlined file: juce_TextLayout.cpp ***/
  73684. /*** Start of inlined file: juce_Typeface.cpp ***/
  73685. BEGIN_JUCE_NAMESPACE
  73686. Typeface::Typeface (const String& name_) throw()
  73687. : name (name_)
  73688. {
  73689. }
  73690. Typeface::~Typeface()
  73691. {
  73692. }
  73693. class CustomTypeface::GlyphInfo
  73694. {
  73695. public:
  73696. GlyphInfo (const juce_wchar character_, const Path& path_, const float width_) throw()
  73697. : character (character_), path (path_), width (width_)
  73698. {
  73699. }
  73700. ~GlyphInfo() throw()
  73701. {
  73702. }
  73703. struct KerningPair
  73704. {
  73705. juce_wchar character2;
  73706. float kerningAmount;
  73707. };
  73708. void addKerningPair (const juce_wchar subsequentCharacter,
  73709. const float extraKerningAmount) throw()
  73710. {
  73711. KerningPair kp;
  73712. kp.character2 = subsequentCharacter;
  73713. kp.kerningAmount = extraKerningAmount;
  73714. kerningPairs.add (kp);
  73715. }
  73716. float getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  73717. {
  73718. if (subsequentCharacter != 0)
  73719. {
  73720. for (int i = kerningPairs.size(); --i >= 0;)
  73721. if (kerningPairs.getReference(i).character2 == subsequentCharacter)
  73722. return width + kerningPairs.getReference(i).kerningAmount;
  73723. }
  73724. return width;
  73725. }
  73726. const juce_wchar character;
  73727. const Path path;
  73728. float width;
  73729. Array <KerningPair> kerningPairs;
  73730. juce_UseDebuggingNewOperator
  73731. private:
  73732. GlyphInfo (const GlyphInfo&);
  73733. GlyphInfo& operator= (const GlyphInfo&);
  73734. };
  73735. CustomTypeface::CustomTypeface()
  73736. : Typeface (String::empty)
  73737. {
  73738. clear();
  73739. }
  73740. CustomTypeface::CustomTypeface (InputStream& serialisedTypefaceStream)
  73741. : Typeface (String::empty)
  73742. {
  73743. clear();
  73744. GZIPDecompressorInputStream gzin (serialisedTypefaceStream);
  73745. BufferedInputStream in (gzin, 32768);
  73746. name = in.readString();
  73747. isBold = in.readBool();
  73748. isItalic = in.readBool();
  73749. ascent = in.readFloat();
  73750. defaultCharacter = (juce_wchar) in.readShort();
  73751. int i, numChars = in.readInt();
  73752. for (i = 0; i < numChars; ++i)
  73753. {
  73754. const juce_wchar c = (juce_wchar) in.readShort();
  73755. const float width = in.readFloat();
  73756. Path p;
  73757. p.loadPathFromStream (in);
  73758. addGlyph (c, p, width);
  73759. }
  73760. const int numKerningPairs = in.readInt();
  73761. for (i = 0; i < numKerningPairs; ++i)
  73762. {
  73763. const juce_wchar char1 = (juce_wchar) in.readShort();
  73764. const juce_wchar char2 = (juce_wchar) in.readShort();
  73765. addKerningPair (char1, char2, in.readFloat());
  73766. }
  73767. }
  73768. CustomTypeface::~CustomTypeface()
  73769. {
  73770. }
  73771. void CustomTypeface::clear()
  73772. {
  73773. defaultCharacter = 0;
  73774. ascent = 1.0f;
  73775. isBold = isItalic = false;
  73776. zeromem (lookupTable, sizeof (lookupTable));
  73777. glyphs.clear();
  73778. }
  73779. void CustomTypeface::setCharacteristics (const String& name_, const float ascent_, const bool isBold_,
  73780. const bool isItalic_, const juce_wchar defaultCharacter_) throw()
  73781. {
  73782. name = name_;
  73783. defaultCharacter = defaultCharacter_;
  73784. ascent = ascent_;
  73785. isBold = isBold_;
  73786. isItalic = isItalic_;
  73787. }
  73788. void CustomTypeface::addGlyph (const juce_wchar character, const Path& path, const float width) throw()
  73789. {
  73790. // Check that you're not trying to add the same character twice..
  73791. jassert (findGlyph (character, false) == 0);
  73792. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable))
  73793. lookupTable [character] = (short) glyphs.size();
  73794. glyphs.add (new GlyphInfo (character, path, width));
  73795. }
  73796. void CustomTypeface::addKerningPair (const juce_wchar char1, const juce_wchar char2, const float extraAmount) throw()
  73797. {
  73798. if (extraAmount != 0)
  73799. {
  73800. GlyphInfo* const g = findGlyph (char1, true);
  73801. jassert (g != 0); // can only add kerning pairs for characters that exist!
  73802. if (g != 0)
  73803. g->addKerningPair (char2, extraAmount);
  73804. }
  73805. }
  73806. CustomTypeface::GlyphInfo* CustomTypeface::findGlyph (const juce_wchar character, const bool loadIfNeeded) throw()
  73807. {
  73808. if (((unsigned int) character) < (unsigned int) numElementsInArray (lookupTable) && lookupTable [character] > 0)
  73809. return glyphs [(int) lookupTable [(int) character]];
  73810. for (int i = 0; i < glyphs.size(); ++i)
  73811. {
  73812. GlyphInfo* const g = glyphs.getUnchecked(i);
  73813. if (g->character == character)
  73814. return g;
  73815. }
  73816. if (loadIfNeeded && loadGlyphIfPossible (character))
  73817. return findGlyph (character, false);
  73818. return 0;
  73819. }
  73820. CustomTypeface::GlyphInfo* CustomTypeface::findGlyphSubstituting (const juce_wchar character) throw()
  73821. {
  73822. GlyphInfo* glyph = findGlyph (character, true);
  73823. if (glyph == 0)
  73824. {
  73825. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  73826. glyph = findGlyph (L' ', true);
  73827. if (glyph == 0)
  73828. {
  73829. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  73830. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  73831. if (fallbackTypeface != 0 && fallbackTypeface != this)
  73832. {
  73833. //xxx
  73834. }
  73835. if (glyph == 0)
  73836. glyph = findGlyph (defaultCharacter, true);
  73837. }
  73838. }
  73839. return glyph;
  73840. }
  73841. bool CustomTypeface::loadGlyphIfPossible (const juce_wchar /*characterNeeded*/)
  73842. {
  73843. return false;
  73844. }
  73845. void CustomTypeface::addGlyphsFromOtherTypeface (Typeface& typefaceToCopy, juce_wchar characterStartIndex, int numCharacters) throw()
  73846. {
  73847. setCharacteristics (name, typefaceToCopy.getAscent(), isBold, isItalic, defaultCharacter);
  73848. for (int i = 0; i < numCharacters; ++i)
  73849. {
  73850. const juce_wchar c = (juce_wchar) (characterStartIndex + i);
  73851. Array <int> glyphIndexes;
  73852. Array <float> offsets;
  73853. typefaceToCopy.getGlyphPositions (String::charToString (c), glyphIndexes, offsets);
  73854. const int glyphIndex = glyphIndexes.getFirst();
  73855. if (glyphIndex >= 0 && glyphIndexes.size() > 0)
  73856. {
  73857. const float glyphWidth = offsets[1];
  73858. Path p;
  73859. typefaceToCopy.getOutlineForGlyph (glyphIndex, p);
  73860. addGlyph (c, p, glyphWidth);
  73861. for (int j = glyphs.size() - 1; --j >= 0;)
  73862. {
  73863. const juce_wchar char2 = glyphs.getUnchecked (j)->character;
  73864. glyphIndexes.clearQuick();
  73865. offsets.clearQuick();
  73866. typefaceToCopy.getGlyphPositions (String::charToString (c) + String::charToString (char2), glyphIndexes, offsets);
  73867. if (offsets.size() > 1)
  73868. addKerningPair (c, char2, offsets[1] - glyphWidth);
  73869. }
  73870. }
  73871. }
  73872. }
  73873. bool CustomTypeface::writeToStream (OutputStream& outputStream)
  73874. {
  73875. GZIPCompressorOutputStream out (&outputStream);
  73876. out.writeString (name);
  73877. out.writeBool (isBold);
  73878. out.writeBool (isItalic);
  73879. out.writeFloat (ascent);
  73880. out.writeShort ((short) (unsigned short) defaultCharacter);
  73881. out.writeInt (glyphs.size());
  73882. int i, numKerningPairs = 0;
  73883. for (i = 0; i < glyphs.size(); ++i)
  73884. {
  73885. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73886. out.writeShort ((short) (unsigned short) g->character);
  73887. out.writeFloat (g->width);
  73888. g->path.writePathToStream (out);
  73889. numKerningPairs += g->kerningPairs.size();
  73890. }
  73891. out.writeInt (numKerningPairs);
  73892. for (i = 0; i < glyphs.size(); ++i)
  73893. {
  73894. const GlyphInfo* const g = glyphs.getUnchecked (i);
  73895. for (int j = 0; j < g->kerningPairs.size(); ++j)
  73896. {
  73897. const GlyphInfo::KerningPair& p = g->kerningPairs.getReference (j);
  73898. out.writeShort ((short) (unsigned short) g->character);
  73899. out.writeShort ((short) (unsigned short) p.character2);
  73900. out.writeFloat (p.kerningAmount);
  73901. }
  73902. }
  73903. return true;
  73904. }
  73905. float CustomTypeface::getAscent() const
  73906. {
  73907. return ascent;
  73908. }
  73909. float CustomTypeface::getDescent() const
  73910. {
  73911. return 1.0f - ascent;
  73912. }
  73913. float CustomTypeface::getStringWidth (const String& text)
  73914. {
  73915. float x = 0;
  73916. const juce_wchar* t = text;
  73917. while (*t != 0)
  73918. {
  73919. const GlyphInfo* const glyph = findGlyphSubstituting (*t++);
  73920. if (glyph != 0)
  73921. x += glyph->getHorizontalSpacing (*t);
  73922. }
  73923. return x;
  73924. }
  73925. void CustomTypeface::getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array<float>& xOffsets)
  73926. {
  73927. xOffsets.add (0);
  73928. float x = 0;
  73929. const juce_wchar* t = text;
  73930. while (*t != 0)
  73931. {
  73932. const juce_wchar c = *t++;
  73933. const GlyphInfo* const glyph = findGlyphSubstituting (c);
  73934. if (glyph != 0)
  73935. {
  73936. x += glyph->getHorizontalSpacing (*t);
  73937. resultGlyphs.add ((int) glyph->character);
  73938. xOffsets.add (x);
  73939. }
  73940. }
  73941. }
  73942. bool CustomTypeface::getOutlineForGlyph (int glyphNumber, Path& path)
  73943. {
  73944. const GlyphInfo* const glyph = findGlyphSubstituting ((juce_wchar) glyphNumber);
  73945. if (glyph != 0)
  73946. {
  73947. path = glyph->path;
  73948. return true;
  73949. }
  73950. return false;
  73951. }
  73952. END_JUCE_NAMESPACE
  73953. /*** End of inlined file: juce_Typeface.cpp ***/
  73954. /*** Start of inlined file: juce_AffineTransform.cpp ***/
  73955. BEGIN_JUCE_NAMESPACE
  73956. AffineTransform::AffineTransform() throw()
  73957. : mat00 (1.0f),
  73958. mat01 (0),
  73959. mat02 (0),
  73960. mat10 (0),
  73961. mat11 (1.0f),
  73962. mat12 (0)
  73963. {
  73964. }
  73965. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  73966. : mat00 (other.mat00),
  73967. mat01 (other.mat01),
  73968. mat02 (other.mat02),
  73969. mat10 (other.mat10),
  73970. mat11 (other.mat11),
  73971. mat12 (other.mat12)
  73972. {
  73973. }
  73974. AffineTransform::AffineTransform (const float mat00_,
  73975. const float mat01_,
  73976. const float mat02_,
  73977. const float mat10_,
  73978. const float mat11_,
  73979. const float mat12_) throw()
  73980. : mat00 (mat00_),
  73981. mat01 (mat01_),
  73982. mat02 (mat02_),
  73983. mat10 (mat10_),
  73984. mat11 (mat11_),
  73985. mat12 (mat12_)
  73986. {
  73987. }
  73988. AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  73989. {
  73990. mat00 = other.mat00;
  73991. mat01 = other.mat01;
  73992. mat02 = other.mat02;
  73993. mat10 = other.mat10;
  73994. mat11 = other.mat11;
  73995. mat12 = other.mat12;
  73996. return *this;
  73997. }
  73998. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  73999. {
  74000. return mat00 == other.mat00
  74001. && mat01 == other.mat01
  74002. && mat02 == other.mat02
  74003. && mat10 == other.mat10
  74004. && mat11 == other.mat11
  74005. && mat12 == other.mat12;
  74006. }
  74007. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  74008. {
  74009. return ! operator== (other);
  74010. }
  74011. bool AffineTransform::isIdentity() const throw()
  74012. {
  74013. return (mat01 == 0)
  74014. && (mat02 == 0)
  74015. && (mat10 == 0)
  74016. && (mat12 == 0)
  74017. && (mat00 == 1.0f)
  74018. && (mat11 == 1.0f);
  74019. }
  74020. const AffineTransform AffineTransform::identity;
  74021. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  74022. {
  74023. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  74024. other.mat00 * mat01 + other.mat01 * mat11,
  74025. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  74026. other.mat10 * mat00 + other.mat11 * mat10,
  74027. other.mat10 * mat01 + other.mat11 * mat11,
  74028. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  74029. }
  74030. const AffineTransform AffineTransform::followedBy (const float omat00,
  74031. const float omat01,
  74032. const float omat02,
  74033. const float omat10,
  74034. const float omat11,
  74035. const float omat12) const throw()
  74036. {
  74037. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  74038. omat00 * mat01 + omat01 * mat11,
  74039. omat00 * mat02 + omat01 * mat12 + omat02,
  74040. omat10 * mat00 + omat11 * mat10,
  74041. omat10 * mat01 + omat11 * mat11,
  74042. omat10 * mat02 + omat11 * mat12 + omat12);
  74043. }
  74044. const AffineTransform AffineTransform::translated (const float dx,
  74045. const float dy) const throw()
  74046. {
  74047. return AffineTransform (mat00, mat01, mat02 + dx,
  74048. mat10, mat11, mat12 + dy);
  74049. }
  74050. const AffineTransform AffineTransform::translation (const float dx,
  74051. const float dy) throw()
  74052. {
  74053. return AffineTransform (1.0f, 0, dx,
  74054. 0, 1.0f, dy);
  74055. }
  74056. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  74057. {
  74058. const float cosRad = std::cos (rad);
  74059. const float sinRad = std::sin (rad);
  74060. return followedBy (cosRad, -sinRad, 0,
  74061. sinRad, cosRad, 0);
  74062. }
  74063. const AffineTransform AffineTransform::rotation (const float rad) throw()
  74064. {
  74065. const float cosRad = std::cos (rad);
  74066. const float sinRad = std::sin (rad);
  74067. return AffineTransform (cosRad, -sinRad, 0,
  74068. sinRad, cosRad, 0);
  74069. }
  74070. const AffineTransform AffineTransform::rotated (const float angle,
  74071. const float pivotX,
  74072. const float pivotY) const throw()
  74073. {
  74074. return translated (-pivotX, -pivotY)
  74075. .rotated (angle)
  74076. .translated (pivotX, pivotY);
  74077. }
  74078. const AffineTransform AffineTransform::rotation (const float angle,
  74079. const float pivotX,
  74080. const float pivotY) throw()
  74081. {
  74082. return translation (-pivotX, -pivotY)
  74083. .rotated (angle)
  74084. .translated (pivotX, pivotY);
  74085. }
  74086. const AffineTransform AffineTransform::scaled (const float factorX,
  74087. const float factorY) const throw()
  74088. {
  74089. return AffineTransform (factorX * mat00, factorX * mat01, factorX * mat02,
  74090. factorY * mat10, factorY * mat11, factorY * mat12);
  74091. }
  74092. const AffineTransform AffineTransform::scale (const float factorX,
  74093. const float factorY) throw()
  74094. {
  74095. return AffineTransform (factorX, 0, 0,
  74096. 0, factorY, 0);
  74097. }
  74098. const AffineTransform AffineTransform::sheared (const float shearX,
  74099. const float shearY) const throw()
  74100. {
  74101. return followedBy (1.0f, shearX, 0,
  74102. shearY, 1.0f, 0);
  74103. }
  74104. const AffineTransform AffineTransform::inverted() const throw()
  74105. {
  74106. double determinant = (mat00 * mat11 - mat10 * mat01);
  74107. if (determinant != 0.0)
  74108. {
  74109. determinant = 1.0 / determinant;
  74110. const float dst00 = (float) (mat11 * determinant);
  74111. const float dst10 = (float) (-mat10 * determinant);
  74112. const float dst01 = (float) (-mat01 * determinant);
  74113. const float dst11 = (float) (mat00 * determinant);
  74114. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  74115. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  74116. }
  74117. else
  74118. {
  74119. // singularity..
  74120. return *this;
  74121. }
  74122. }
  74123. bool AffineTransform::isSingularity() const throw()
  74124. {
  74125. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  74126. }
  74127. const AffineTransform AffineTransform::fromTargetPoints (const float x00, const float y00,
  74128. const float x10, const float y10,
  74129. const float x01, const float y01) throw()
  74130. {
  74131. return AffineTransform (x10 - x00, x01 - x00, x00,
  74132. y10 - y00, y01 - y00, y00);
  74133. }
  74134. const AffineTransform AffineTransform::fromTargetPoints (const float sx1, const float sy1, const float tx1, const float ty1,
  74135. const float sx2, const float sy2, const float tx2, const float ty2,
  74136. const float sx3, const float sy3, const float tx3, const float ty3) throw()
  74137. {
  74138. return fromTargetPoints (sx1, sy1, sx2, sy2, sx3, sy3)
  74139. .inverted()
  74140. .followedBy (fromTargetPoints (tx1, ty1, tx2, ty2, tx3, ty3));
  74141. }
  74142. bool AffineTransform::isOnlyTranslation() const throw()
  74143. {
  74144. return (mat01 == 0)
  74145. && (mat10 == 0)
  74146. && (mat00 == 1.0f)
  74147. && (mat11 == 1.0f);
  74148. }
  74149. END_JUCE_NAMESPACE
  74150. /*** End of inlined file: juce_AffineTransform.cpp ***/
  74151. /*** Start of inlined file: juce_BorderSize.cpp ***/
  74152. BEGIN_JUCE_NAMESPACE
  74153. BorderSize::BorderSize() throw()
  74154. : top (0),
  74155. left (0),
  74156. bottom (0),
  74157. right (0)
  74158. {
  74159. }
  74160. BorderSize::BorderSize (const BorderSize& other) throw()
  74161. : top (other.top),
  74162. left (other.left),
  74163. bottom (other.bottom),
  74164. right (other.right)
  74165. {
  74166. }
  74167. BorderSize::BorderSize (const int topGap,
  74168. const int leftGap,
  74169. const int bottomGap,
  74170. const int rightGap) throw()
  74171. : top (topGap),
  74172. left (leftGap),
  74173. bottom (bottomGap),
  74174. right (rightGap)
  74175. {
  74176. }
  74177. BorderSize::BorderSize (const int allGaps) throw()
  74178. : top (allGaps),
  74179. left (allGaps),
  74180. bottom (allGaps),
  74181. right (allGaps)
  74182. {
  74183. }
  74184. BorderSize::~BorderSize() throw()
  74185. {
  74186. }
  74187. void BorderSize::setTop (const int newTopGap) throw()
  74188. {
  74189. top = newTopGap;
  74190. }
  74191. void BorderSize::setLeft (const int newLeftGap) throw()
  74192. {
  74193. left = newLeftGap;
  74194. }
  74195. void BorderSize::setBottom (const int newBottomGap) throw()
  74196. {
  74197. bottom = newBottomGap;
  74198. }
  74199. void BorderSize::setRight (const int newRightGap) throw()
  74200. {
  74201. right = newRightGap;
  74202. }
  74203. const Rectangle<int> BorderSize::subtractedFrom (const Rectangle<int>& r) const throw()
  74204. {
  74205. return Rectangle<int> (r.getX() + left,
  74206. r.getY() + top,
  74207. r.getWidth() - (left + right),
  74208. r.getHeight() - (top + bottom));
  74209. }
  74210. void BorderSize::subtractFrom (Rectangle<int>& r) const throw()
  74211. {
  74212. r.setBounds (r.getX() + left,
  74213. r.getY() + top,
  74214. r.getWidth() - (left + right),
  74215. r.getHeight() - (top + bottom));
  74216. }
  74217. const Rectangle<int> BorderSize::addedTo (const Rectangle<int>& r) const throw()
  74218. {
  74219. return Rectangle<int> (r.getX() - left,
  74220. r.getY() - top,
  74221. r.getWidth() + (left + right),
  74222. r.getHeight() + (top + bottom));
  74223. }
  74224. void BorderSize::addTo (Rectangle<int>& r) const throw()
  74225. {
  74226. r.setBounds (r.getX() - left,
  74227. r.getY() - top,
  74228. r.getWidth() + (left + right),
  74229. r.getHeight() + (top + bottom));
  74230. }
  74231. bool BorderSize::operator== (const BorderSize& other) const throw()
  74232. {
  74233. return top == other.top
  74234. && left == other.left
  74235. && bottom == other.bottom
  74236. && right == other.right;
  74237. }
  74238. bool BorderSize::operator!= (const BorderSize& other) const throw()
  74239. {
  74240. return ! operator== (other);
  74241. }
  74242. END_JUCE_NAMESPACE
  74243. /*** End of inlined file: juce_BorderSize.cpp ***/
  74244. /*** Start of inlined file: juce_Path.cpp ***/
  74245. BEGIN_JUCE_NAMESPACE
  74246. // tests that some co-ords aren't NaNs
  74247. #define CHECK_COORDS_ARE_VALID(x, y) \
  74248. jassert (x == x && y == y);
  74249. namespace PathHelpers
  74250. {
  74251. static const float ellipseAngularIncrement = 0.05f;
  74252. static const String nextToken (const juce_wchar*& t)
  74253. {
  74254. while (CharacterFunctions::isWhitespace (*t))
  74255. ++t;
  74256. const juce_wchar* const start = t;
  74257. while (*t != 0 && ! CharacterFunctions::isWhitespace (*t))
  74258. ++t;
  74259. return String (start, (int) (t - start));
  74260. }
  74261. }
  74262. const float Path::lineMarker = 100001.0f;
  74263. const float Path::moveMarker = 100002.0f;
  74264. const float Path::quadMarker = 100003.0f;
  74265. const float Path::cubicMarker = 100004.0f;
  74266. const float Path::closeSubPathMarker = 100005.0f;
  74267. Path::Path()
  74268. : numElements (0),
  74269. pathXMin (0),
  74270. pathXMax (0),
  74271. pathYMin (0),
  74272. pathYMax (0),
  74273. useNonZeroWinding (true)
  74274. {
  74275. }
  74276. Path::~Path()
  74277. {
  74278. }
  74279. Path::Path (const Path& other)
  74280. : numElements (other.numElements),
  74281. pathXMin (other.pathXMin),
  74282. pathXMax (other.pathXMax),
  74283. pathYMin (other.pathYMin),
  74284. pathYMax (other.pathYMax),
  74285. useNonZeroWinding (other.useNonZeroWinding)
  74286. {
  74287. if (numElements > 0)
  74288. {
  74289. data.setAllocatedSize ((int) numElements);
  74290. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74291. }
  74292. }
  74293. Path& Path::operator= (const Path& other)
  74294. {
  74295. if (this != &other)
  74296. {
  74297. data.ensureAllocatedSize ((int) other.numElements);
  74298. numElements = other.numElements;
  74299. pathXMin = other.pathXMin;
  74300. pathXMax = other.pathXMax;
  74301. pathYMin = other.pathYMin;
  74302. pathYMax = other.pathYMax;
  74303. useNonZeroWinding = other.useNonZeroWinding;
  74304. if (numElements > 0)
  74305. memcpy (data.elements, other.data.elements, numElements * sizeof (float));
  74306. }
  74307. return *this;
  74308. }
  74309. bool Path::operator== (const Path& other) const throw()
  74310. {
  74311. return ! operator!= (other);
  74312. }
  74313. bool Path::operator!= (const Path& other) const throw()
  74314. {
  74315. if (numElements != other.numElements || useNonZeroWinding != other.useNonZeroWinding)
  74316. return true;
  74317. for (size_t i = 0; i < numElements; ++i)
  74318. if (data.elements[i] != other.data.elements[i])
  74319. return true;
  74320. return false;
  74321. }
  74322. void Path::clear() throw()
  74323. {
  74324. numElements = 0;
  74325. pathXMin = 0;
  74326. pathYMin = 0;
  74327. pathYMax = 0;
  74328. pathXMax = 0;
  74329. }
  74330. void Path::swapWithPath (Path& other) throw()
  74331. {
  74332. data.swapWith (other.data);
  74333. swapVariables <size_t> (numElements, other.numElements);
  74334. swapVariables <float> (pathXMin, other.pathXMin);
  74335. swapVariables <float> (pathXMax, other.pathXMax);
  74336. swapVariables <float> (pathYMin, other.pathYMin);
  74337. swapVariables <float> (pathYMax, other.pathYMax);
  74338. swapVariables <bool> (useNonZeroWinding, other.useNonZeroWinding);
  74339. }
  74340. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  74341. {
  74342. useNonZeroWinding = isNonZero;
  74343. }
  74344. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  74345. const bool preserveProportions) throw()
  74346. {
  74347. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  74348. }
  74349. bool Path::isEmpty() const throw()
  74350. {
  74351. size_t i = 0;
  74352. while (i < numElements)
  74353. {
  74354. const float type = data.elements [i++];
  74355. if (type == moveMarker)
  74356. {
  74357. i += 2;
  74358. }
  74359. else if (type == lineMarker
  74360. || type == quadMarker
  74361. || type == cubicMarker)
  74362. {
  74363. return false;
  74364. }
  74365. }
  74366. return true;
  74367. }
  74368. const Rectangle<float> Path::getBounds() const throw()
  74369. {
  74370. return Rectangle<float> (pathXMin, pathYMin,
  74371. pathXMax - pathXMin,
  74372. pathYMax - pathYMin);
  74373. }
  74374. const Rectangle<float> Path::getBoundsTransformed (const AffineTransform& transform) const throw()
  74375. {
  74376. return getBounds().transformed (transform);
  74377. }
  74378. void Path::startNewSubPath (const float x, const float y)
  74379. {
  74380. CHECK_COORDS_ARE_VALID (x, y);
  74381. if (numElements == 0)
  74382. {
  74383. pathXMin = pathXMax = x;
  74384. pathYMin = pathYMax = y;
  74385. }
  74386. else
  74387. {
  74388. pathXMin = jmin (pathXMin, x);
  74389. pathXMax = jmax (pathXMax, x);
  74390. pathYMin = jmin (pathYMin, y);
  74391. pathYMax = jmax (pathYMax, y);
  74392. }
  74393. data.ensureAllocatedSize ((int) numElements + 3);
  74394. data.elements [numElements++] = moveMarker;
  74395. data.elements [numElements++] = x;
  74396. data.elements [numElements++] = y;
  74397. }
  74398. void Path::startNewSubPath (const Point<float>& start)
  74399. {
  74400. startNewSubPath (start.getX(), start.getY());
  74401. }
  74402. void Path::lineTo (const float x, const float y)
  74403. {
  74404. CHECK_COORDS_ARE_VALID (x, y);
  74405. if (numElements == 0)
  74406. startNewSubPath (0, 0);
  74407. data.ensureAllocatedSize ((int) numElements + 3);
  74408. data.elements [numElements++] = lineMarker;
  74409. data.elements [numElements++] = x;
  74410. data.elements [numElements++] = y;
  74411. pathXMin = jmin (pathXMin, x);
  74412. pathXMax = jmax (pathXMax, x);
  74413. pathYMin = jmin (pathYMin, y);
  74414. pathYMax = jmax (pathYMax, y);
  74415. }
  74416. void Path::lineTo (const Point<float>& end)
  74417. {
  74418. lineTo (end.getX(), end.getY());
  74419. }
  74420. void Path::quadraticTo (const float x1, const float y1,
  74421. const float x2, const float y2)
  74422. {
  74423. CHECK_COORDS_ARE_VALID (x1, y1);
  74424. CHECK_COORDS_ARE_VALID (x2, y2);
  74425. if (numElements == 0)
  74426. startNewSubPath (0, 0);
  74427. data.ensureAllocatedSize ((int) numElements + 5);
  74428. data.elements [numElements++] = quadMarker;
  74429. data.elements [numElements++] = x1;
  74430. data.elements [numElements++] = y1;
  74431. data.elements [numElements++] = x2;
  74432. data.elements [numElements++] = y2;
  74433. pathXMin = jmin (pathXMin, x1, x2);
  74434. pathXMax = jmax (pathXMax, x1, x2);
  74435. pathYMin = jmin (pathYMin, y1, y2);
  74436. pathYMax = jmax (pathYMax, y1, y2);
  74437. }
  74438. void Path::quadraticTo (const Point<float>& controlPoint,
  74439. const Point<float>& endPoint)
  74440. {
  74441. quadraticTo (controlPoint.getX(), controlPoint.getY(),
  74442. endPoint.getX(), endPoint.getY());
  74443. }
  74444. void Path::cubicTo (const float x1, const float y1,
  74445. const float x2, const float y2,
  74446. const float x3, const float y3)
  74447. {
  74448. CHECK_COORDS_ARE_VALID (x1, y1);
  74449. CHECK_COORDS_ARE_VALID (x2, y2);
  74450. CHECK_COORDS_ARE_VALID (x3, y3);
  74451. if (numElements == 0)
  74452. startNewSubPath (0, 0);
  74453. data.ensureAllocatedSize ((int) numElements + 7);
  74454. data.elements [numElements++] = cubicMarker;
  74455. data.elements [numElements++] = x1;
  74456. data.elements [numElements++] = y1;
  74457. data.elements [numElements++] = x2;
  74458. data.elements [numElements++] = y2;
  74459. data.elements [numElements++] = x3;
  74460. data.elements [numElements++] = y3;
  74461. pathXMin = jmin (pathXMin, x1, x2, x3);
  74462. pathXMax = jmax (pathXMax, x1, x2, x3);
  74463. pathYMin = jmin (pathYMin, y1, y2, y3);
  74464. pathYMax = jmax (pathYMax, y1, y2, y3);
  74465. }
  74466. void Path::cubicTo (const Point<float>& controlPoint1,
  74467. const Point<float>& controlPoint2,
  74468. const Point<float>& endPoint)
  74469. {
  74470. cubicTo (controlPoint1.getX(), controlPoint1.getY(),
  74471. controlPoint2.getX(), controlPoint2.getY(),
  74472. endPoint.getX(), endPoint.getY());
  74473. }
  74474. void Path::closeSubPath()
  74475. {
  74476. if (numElements > 0
  74477. && data.elements [numElements - 1] != closeSubPathMarker)
  74478. {
  74479. data.ensureAllocatedSize ((int) numElements + 1);
  74480. data.elements [numElements++] = closeSubPathMarker;
  74481. }
  74482. }
  74483. const Point<float> Path::getCurrentPosition() const
  74484. {
  74485. size_t i = numElements - 1;
  74486. if (i > 0 && data.elements[i] == closeSubPathMarker)
  74487. {
  74488. while (i >= 0)
  74489. {
  74490. if (data.elements[i] == moveMarker)
  74491. {
  74492. i += 2;
  74493. break;
  74494. }
  74495. --i;
  74496. }
  74497. }
  74498. if (i > 0)
  74499. return Point<float> (data.elements [i - 1], data.elements [i]);
  74500. return Point<float>();
  74501. }
  74502. void Path::addRectangle (const float x, const float y,
  74503. const float w, const float h)
  74504. {
  74505. float x1 = x, y1 = y, x2 = x + w, y2 = y + h;
  74506. if (w < 0)
  74507. swapVariables (x1, x2);
  74508. if (h < 0)
  74509. swapVariables (y1, y2);
  74510. data.ensureAllocatedSize ((int) numElements + 13);
  74511. if (numElements == 0)
  74512. {
  74513. pathXMin = x1;
  74514. pathXMax = x2;
  74515. pathYMin = y1;
  74516. pathYMax = y2;
  74517. }
  74518. else
  74519. {
  74520. pathXMin = jmin (pathXMin, x1);
  74521. pathXMax = jmax (pathXMax, x2);
  74522. pathYMin = jmin (pathYMin, y1);
  74523. pathYMax = jmax (pathYMax, y2);
  74524. }
  74525. data.elements [numElements++] = moveMarker;
  74526. data.elements [numElements++] = x1;
  74527. data.elements [numElements++] = y2;
  74528. data.elements [numElements++] = lineMarker;
  74529. data.elements [numElements++] = x1;
  74530. data.elements [numElements++] = y1;
  74531. data.elements [numElements++] = lineMarker;
  74532. data.elements [numElements++] = x2;
  74533. data.elements [numElements++] = y1;
  74534. data.elements [numElements++] = lineMarker;
  74535. data.elements [numElements++] = x2;
  74536. data.elements [numElements++] = y2;
  74537. data.elements [numElements++] = closeSubPathMarker;
  74538. }
  74539. void Path::addRoundedRectangle (const float x, const float y,
  74540. const float w, const float h,
  74541. float csx,
  74542. float csy)
  74543. {
  74544. csx = jmin (csx, w * 0.5f);
  74545. csy = jmin (csy, h * 0.5f);
  74546. const float cs45x = csx * 0.45f;
  74547. const float cs45y = csy * 0.45f;
  74548. const float x2 = x + w;
  74549. const float y2 = y + h;
  74550. startNewSubPath (x + csx, y);
  74551. lineTo (x2 - csx, y);
  74552. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  74553. lineTo (x2, y2 - csy);
  74554. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  74555. lineTo (x + csx, y2);
  74556. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  74557. lineTo (x, y + csy);
  74558. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  74559. closeSubPath();
  74560. }
  74561. void Path::addRoundedRectangle (const float x, const float y,
  74562. const float w, const float h,
  74563. float cs)
  74564. {
  74565. addRoundedRectangle (x, y, w, h, cs, cs);
  74566. }
  74567. void Path::addTriangle (const float x1, const float y1,
  74568. const float x2, const float y2,
  74569. const float x3, const float y3)
  74570. {
  74571. startNewSubPath (x1, y1);
  74572. lineTo (x2, y2);
  74573. lineTo (x3, y3);
  74574. closeSubPath();
  74575. }
  74576. void Path::addQuadrilateral (const float x1, const float y1,
  74577. const float x2, const float y2,
  74578. const float x3, const float y3,
  74579. const float x4, const float y4)
  74580. {
  74581. startNewSubPath (x1, y1);
  74582. lineTo (x2, y2);
  74583. lineTo (x3, y3);
  74584. lineTo (x4, y4);
  74585. closeSubPath();
  74586. }
  74587. void Path::addEllipse (const float x, const float y,
  74588. const float w, const float h)
  74589. {
  74590. const float hw = w * 0.5f;
  74591. const float hw55 = hw * 0.55f;
  74592. const float hh = h * 0.5f;
  74593. const float hh55 = hh * 0.55f;
  74594. const float cx = x + hw;
  74595. const float cy = y + hh;
  74596. startNewSubPath (cx, cy - hh);
  74597. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh55, cx + hw, cy);
  74598. cubicTo (cx + hw, cy + hh55, cx + hw55, cy + hh, cx, cy + hh);
  74599. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh55, cx - hw, cy);
  74600. cubicTo (cx - hw, cy - hh55, cx - hw55, cy - hh, cx, cy - hh);
  74601. closeSubPath();
  74602. }
  74603. void Path::addArc (const float x, const float y,
  74604. const float w, const float h,
  74605. const float fromRadians,
  74606. const float toRadians,
  74607. const bool startAsNewSubPath)
  74608. {
  74609. const float radiusX = w / 2.0f;
  74610. const float radiusY = h / 2.0f;
  74611. addCentredArc (x + radiusX,
  74612. y + radiusY,
  74613. radiusX, radiusY,
  74614. 0.0f,
  74615. fromRadians, toRadians,
  74616. startAsNewSubPath);
  74617. }
  74618. void Path::addCentredArc (const float centreX, const float centreY,
  74619. const float radiusX, const float radiusY,
  74620. const float rotationOfEllipse,
  74621. const float fromRadians,
  74622. const float toRadians,
  74623. const bool startAsNewSubPath)
  74624. {
  74625. if (radiusX > 0.0f && radiusY > 0.0f)
  74626. {
  74627. const Point<float> centre (centreX, centreY);
  74628. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  74629. float angle = fromRadians;
  74630. if (startAsNewSubPath)
  74631. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74632. if (fromRadians < toRadians)
  74633. {
  74634. if (startAsNewSubPath)
  74635. angle += PathHelpers::ellipseAngularIncrement;
  74636. while (angle < toRadians)
  74637. {
  74638. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74639. angle += PathHelpers::ellipseAngularIncrement;
  74640. }
  74641. }
  74642. else
  74643. {
  74644. if (startAsNewSubPath)
  74645. angle -= PathHelpers::ellipseAngularIncrement;
  74646. while (angle > toRadians)
  74647. {
  74648. lineTo (centre.getPointOnCircumference (radiusX, radiusY, angle).transformedBy (rotation));
  74649. angle -= PathHelpers::ellipseAngularIncrement;
  74650. }
  74651. }
  74652. lineTo (centre.getPointOnCircumference (radiusX, radiusY, toRadians).transformedBy (rotation));
  74653. }
  74654. }
  74655. void Path::addPieSegment (const float x, const float y,
  74656. const float width, const float height,
  74657. const float fromRadians,
  74658. const float toRadians,
  74659. const float innerCircleProportionalSize)
  74660. {
  74661. float radiusX = width * 0.5f;
  74662. float radiusY = height * 0.5f;
  74663. const Point<float> centre (x + radiusX, y + radiusY);
  74664. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, fromRadians));
  74665. addArc (x, y, width, height, fromRadians, toRadians);
  74666. if (std::abs (fromRadians - toRadians) > float_Pi * 1.999f)
  74667. {
  74668. closeSubPath();
  74669. if (innerCircleProportionalSize > 0)
  74670. {
  74671. radiusX *= innerCircleProportionalSize;
  74672. radiusY *= innerCircleProportionalSize;
  74673. startNewSubPath (centre.getPointOnCircumference (radiusX, radiusY, toRadians));
  74674. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74675. }
  74676. }
  74677. else
  74678. {
  74679. if (innerCircleProportionalSize > 0)
  74680. {
  74681. radiusX *= innerCircleProportionalSize;
  74682. radiusY *= innerCircleProportionalSize;
  74683. addArc (centre.getX() - radiusX, centre.getY() - radiusY, radiusX * 2.0f, radiusY * 2.0f, toRadians, fromRadians);
  74684. }
  74685. else
  74686. {
  74687. lineTo (centre);
  74688. }
  74689. }
  74690. closeSubPath();
  74691. }
  74692. void Path::addLineSegment (const Line<float>& line, float lineThickness)
  74693. {
  74694. const Line<float> reversed (line.reversed());
  74695. lineThickness *= 0.5f;
  74696. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74697. lineTo (line.getPointAlongLine (0, -lineThickness));
  74698. lineTo (reversed.getPointAlongLine (0, lineThickness));
  74699. lineTo (reversed.getPointAlongLine (0, -lineThickness));
  74700. closeSubPath();
  74701. }
  74702. void Path::addArrow (const Line<float>& line, float lineThickness,
  74703. float arrowheadWidth, float arrowheadLength)
  74704. {
  74705. const Line<float> reversed (line.reversed());
  74706. lineThickness *= 0.5f;
  74707. arrowheadWidth *= 0.5f;
  74708. arrowheadLength = jmin (arrowheadLength, 0.8f * line.getLength());
  74709. startNewSubPath (line.getPointAlongLine (0, lineThickness));
  74710. lineTo (line.getPointAlongLine (0, -lineThickness));
  74711. lineTo (reversed.getPointAlongLine (arrowheadLength, lineThickness));
  74712. lineTo (reversed.getPointAlongLine (arrowheadLength, arrowheadWidth));
  74713. lineTo (line.getEnd());
  74714. lineTo (reversed.getPointAlongLine (arrowheadLength, -arrowheadWidth));
  74715. lineTo (reversed.getPointAlongLine (arrowheadLength, -lineThickness));
  74716. closeSubPath();
  74717. }
  74718. void Path::addPolygon (const Point<float>& centre, const int numberOfSides,
  74719. const float radius, const float startAngle)
  74720. {
  74721. jassert (numberOfSides > 1); // this would be silly.
  74722. if (numberOfSides > 1)
  74723. {
  74724. const float angleBetweenPoints = float_Pi * 2.0f / numberOfSides;
  74725. for (int i = 0; i < numberOfSides; ++i)
  74726. {
  74727. const float angle = startAngle + i * angleBetweenPoints;
  74728. const Point<float> p (centre.getPointOnCircumference (radius, angle));
  74729. if (i == 0)
  74730. startNewSubPath (p);
  74731. else
  74732. lineTo (p);
  74733. }
  74734. closeSubPath();
  74735. }
  74736. }
  74737. void Path::addStar (const Point<float>& centre, const int numberOfPoints,
  74738. const float innerRadius, const float outerRadius, const float startAngle)
  74739. {
  74740. jassert (numberOfPoints > 1); // this would be silly.
  74741. if (numberOfPoints > 1)
  74742. {
  74743. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  74744. for (int i = 0; i < numberOfPoints; ++i)
  74745. {
  74746. const float angle = startAngle + i * angleBetweenPoints;
  74747. const Point<float> p (centre.getPointOnCircumference (outerRadius, angle));
  74748. if (i == 0)
  74749. startNewSubPath (p);
  74750. else
  74751. lineTo (p);
  74752. lineTo (centre.getPointOnCircumference (innerRadius, angle + angleBetweenPoints * 0.5f));
  74753. }
  74754. closeSubPath();
  74755. }
  74756. }
  74757. void Path::addBubble (float x, float y,
  74758. float w, float h,
  74759. float cs,
  74760. float tipX,
  74761. float tipY,
  74762. int whichSide,
  74763. float arrowPos,
  74764. float arrowWidth)
  74765. {
  74766. if (w > 1.0f && h > 1.0f)
  74767. {
  74768. cs = jmin (cs, w * 0.5f, h * 0.5f);
  74769. const float cs2 = 2.0f * cs;
  74770. startNewSubPath (x + cs, y);
  74771. if (whichSide == 0)
  74772. {
  74773. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74774. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74775. lineTo (arrowX1, y);
  74776. lineTo (tipX, tipY);
  74777. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  74778. }
  74779. lineTo (x + w - cs, y);
  74780. if (cs > 0.0f)
  74781. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  74782. if (whichSide == 3)
  74783. {
  74784. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74785. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74786. lineTo (x + w, arrowY1);
  74787. lineTo (tipX, tipY);
  74788. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  74789. }
  74790. lineTo (x + w, y + h - cs);
  74791. if (cs > 0.0f)
  74792. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  74793. if (whichSide == 2)
  74794. {
  74795. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  74796. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  74797. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  74798. lineTo (tipX, tipY);
  74799. lineTo (arrowX1, y + h);
  74800. }
  74801. lineTo (x + cs, y + h);
  74802. if (cs > 0.0f)
  74803. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  74804. if (whichSide == 1)
  74805. {
  74806. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  74807. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  74808. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  74809. lineTo (tipX, tipY);
  74810. lineTo (x, arrowY1);
  74811. }
  74812. lineTo (x, y + cs);
  74813. if (cs > 0.0f)
  74814. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - PathHelpers::ellipseAngularIncrement);
  74815. closeSubPath();
  74816. }
  74817. }
  74818. void Path::addPath (const Path& other)
  74819. {
  74820. size_t i = 0;
  74821. while (i < other.numElements)
  74822. {
  74823. const float type = other.data.elements [i++];
  74824. if (type == moveMarker)
  74825. {
  74826. startNewSubPath (other.data.elements [i],
  74827. other.data.elements [i + 1]);
  74828. i += 2;
  74829. }
  74830. else if (type == lineMarker)
  74831. {
  74832. lineTo (other.data.elements [i],
  74833. other.data.elements [i + 1]);
  74834. i += 2;
  74835. }
  74836. else if (type == quadMarker)
  74837. {
  74838. quadraticTo (other.data.elements [i],
  74839. other.data.elements [i + 1],
  74840. other.data.elements [i + 2],
  74841. other.data.elements [i + 3]);
  74842. i += 4;
  74843. }
  74844. else if (type == cubicMarker)
  74845. {
  74846. cubicTo (other.data.elements [i],
  74847. other.data.elements [i + 1],
  74848. other.data.elements [i + 2],
  74849. other.data.elements [i + 3],
  74850. other.data.elements [i + 4],
  74851. other.data.elements [i + 5]);
  74852. i += 6;
  74853. }
  74854. else if (type == closeSubPathMarker)
  74855. {
  74856. closeSubPath();
  74857. }
  74858. else
  74859. {
  74860. // something's gone wrong with the element list!
  74861. jassertfalse;
  74862. }
  74863. }
  74864. }
  74865. void Path::addPath (const Path& other,
  74866. const AffineTransform& transformToApply)
  74867. {
  74868. size_t i = 0;
  74869. while (i < other.numElements)
  74870. {
  74871. const float type = other.data.elements [i++];
  74872. if (type == closeSubPathMarker)
  74873. {
  74874. closeSubPath();
  74875. }
  74876. else
  74877. {
  74878. float x = other.data.elements [i++];
  74879. float y = other.data.elements [i++];
  74880. transformToApply.transformPoint (x, y);
  74881. if (type == moveMarker)
  74882. {
  74883. startNewSubPath (x, y);
  74884. }
  74885. else if (type == lineMarker)
  74886. {
  74887. lineTo (x, y);
  74888. }
  74889. else if (type == quadMarker)
  74890. {
  74891. float x2 = other.data.elements [i++];
  74892. float y2 = other.data.elements [i++];
  74893. transformToApply.transformPoint (x2, y2);
  74894. quadraticTo (x, y, x2, y2);
  74895. }
  74896. else if (type == cubicMarker)
  74897. {
  74898. float x2 = other.data.elements [i++];
  74899. float y2 = other.data.elements [i++];
  74900. float x3 = other.data.elements [i++];
  74901. float y3 = other.data.elements [i++];
  74902. transformToApply.transformPoints (x2, y2, x3, y3);
  74903. cubicTo (x, y, x2, y2, x3, y3);
  74904. }
  74905. else
  74906. {
  74907. // something's gone wrong with the element list!
  74908. jassertfalse;
  74909. }
  74910. }
  74911. }
  74912. }
  74913. void Path::applyTransform (const AffineTransform& transform) throw()
  74914. {
  74915. size_t i = 0;
  74916. pathYMin = pathXMin = 0;
  74917. pathYMax = pathXMax = 0;
  74918. bool setMaxMin = false;
  74919. while (i < numElements)
  74920. {
  74921. const float type = data.elements [i++];
  74922. if (type == moveMarker)
  74923. {
  74924. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74925. if (setMaxMin)
  74926. {
  74927. pathXMin = jmin (pathXMin, data.elements [i]);
  74928. pathXMax = jmax (pathXMax, data.elements [i]);
  74929. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74930. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74931. }
  74932. else
  74933. {
  74934. pathXMin = pathXMax = data.elements [i];
  74935. pathYMin = pathYMax = data.elements [i + 1];
  74936. setMaxMin = true;
  74937. }
  74938. i += 2;
  74939. }
  74940. else if (type == lineMarker)
  74941. {
  74942. transform.transformPoint (data.elements [i], data.elements [i + 1]);
  74943. pathXMin = jmin (pathXMin, data.elements [i]);
  74944. pathXMax = jmax (pathXMax, data.elements [i]);
  74945. pathYMin = jmin (pathYMin, data.elements [i + 1]);
  74946. pathYMax = jmax (pathYMax, data.elements [i + 1]);
  74947. i += 2;
  74948. }
  74949. else if (type == quadMarker)
  74950. {
  74951. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74952. data.elements [i + 2], data.elements [i + 3]);
  74953. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2]);
  74954. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2]);
  74955. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3]);
  74956. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3]);
  74957. i += 4;
  74958. }
  74959. else if (type == cubicMarker)
  74960. {
  74961. transform.transformPoints (data.elements [i], data.elements [i + 1],
  74962. data.elements [i + 2], data.elements [i + 3],
  74963. data.elements [i + 4], data.elements [i + 5]);
  74964. pathXMin = jmin (pathXMin, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74965. pathXMax = jmax (pathXMax, data.elements [i], data.elements [i + 2], data.elements [i + 4]);
  74966. pathYMin = jmin (pathYMin, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74967. pathYMax = jmax (pathYMax, data.elements [i + 1], data.elements [i + 3], data.elements [i + 5]);
  74968. i += 6;
  74969. }
  74970. }
  74971. }
  74972. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  74973. const float w, const float h,
  74974. const bool preserveProportions,
  74975. const Justification& justification) const
  74976. {
  74977. Rectangle<float> bounds (getBounds());
  74978. if (preserveProportions)
  74979. {
  74980. if (w <= 0 || h <= 0 || bounds.isEmpty())
  74981. return AffineTransform::identity;
  74982. float newW, newH;
  74983. const float srcRatio = bounds.getHeight() / bounds.getWidth();
  74984. if (srcRatio > h / w)
  74985. {
  74986. newW = h / srcRatio;
  74987. newH = h;
  74988. }
  74989. else
  74990. {
  74991. newW = w;
  74992. newH = w * srcRatio;
  74993. }
  74994. float newXCentre = x;
  74995. float newYCentre = y;
  74996. if (justification.testFlags (Justification::left))
  74997. newXCentre += newW * 0.5f;
  74998. else if (justification.testFlags (Justification::right))
  74999. newXCentre += w - newW * 0.5f;
  75000. else
  75001. newXCentre += w * 0.5f;
  75002. if (justification.testFlags (Justification::top))
  75003. newYCentre += newH * 0.5f;
  75004. else if (justification.testFlags (Justification::bottom))
  75005. newYCentre += h - newH * 0.5f;
  75006. else
  75007. newYCentre += h * 0.5f;
  75008. return AffineTransform::translation (bounds.getWidth() * -0.5f - bounds.getX(),
  75009. bounds.getHeight() * -0.5f - bounds.getY())
  75010. .scaled (newW / bounds.getWidth(), newH / bounds.getHeight())
  75011. .translated (newXCentre, newYCentre);
  75012. }
  75013. else
  75014. {
  75015. return AffineTransform::translation (-bounds.getX(), -bounds.getY())
  75016. .scaled (w / bounds.getWidth(), h / bounds.getHeight())
  75017. .translated (x, y);
  75018. }
  75019. }
  75020. bool Path::contains (const float x, const float y, const float tolerence) const
  75021. {
  75022. if (x <= pathXMin || x >= pathXMax
  75023. || y <= pathYMin || y >= pathYMax)
  75024. return false;
  75025. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  75026. int positiveCrossings = 0;
  75027. int negativeCrossings = 0;
  75028. while (i.next())
  75029. {
  75030. if ((i.y1 <= y && i.y2 > y) || (i.y2 <= y && i.y1 > y))
  75031. {
  75032. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  75033. if (intersectX <= x)
  75034. {
  75035. if (i.y1 < i.y2)
  75036. ++positiveCrossings;
  75037. else
  75038. ++negativeCrossings;
  75039. }
  75040. }
  75041. }
  75042. return useNonZeroWinding ? (negativeCrossings != positiveCrossings)
  75043. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  75044. }
  75045. bool Path::contains (const Point<float>& point, const float tolerence) const
  75046. {
  75047. return contains (point.getX(), point.getY(), tolerence);
  75048. }
  75049. bool Path::intersectsLine (const Line<float>& line, const float tolerence)
  75050. {
  75051. PathFlatteningIterator i (*this, AffineTransform::identity, tolerence);
  75052. Point<float> intersection;
  75053. while (i.next())
  75054. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75055. return true;
  75056. return false;
  75057. }
  75058. const Line<float> Path::getClippedLine (const Line<float>& line, const bool keepSectionOutsidePath) const
  75059. {
  75060. Line<float> result (line);
  75061. const bool startInside = contains (line.getStart());
  75062. const bool endInside = contains (line.getEnd());
  75063. if (startInside == endInside)
  75064. {
  75065. if (keepSectionOutsidePath == startInside)
  75066. result = Line<float>();
  75067. }
  75068. else
  75069. {
  75070. PathFlatteningIterator i (*this, AffineTransform::identity);
  75071. Point<float> intersection;
  75072. while (i.next())
  75073. {
  75074. if (line.intersects (Line<float> (i.x1, i.y1, i.x2, i.y2), intersection))
  75075. {
  75076. if ((startInside && keepSectionOutsidePath) || (endInside && ! keepSectionOutsidePath))
  75077. result.setStart (intersection);
  75078. else
  75079. result.setEnd (intersection);
  75080. }
  75081. }
  75082. }
  75083. return result;
  75084. }
  75085. float Path::getLength (const AffineTransform& transform) const
  75086. {
  75087. float length = 0;
  75088. PathFlatteningIterator i (*this, transform);
  75089. while (i.next())
  75090. length += Line<float> (i.x1, i.y1, i.x2, i.y2).getLength();
  75091. return length;
  75092. }
  75093. const Point<float> Path::getPointAlongPath (float distanceFromStart, const AffineTransform& transform) const
  75094. {
  75095. PathFlatteningIterator i (*this, transform);
  75096. while (i.next())
  75097. {
  75098. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75099. const float lineLength = line.getLength();
  75100. if (distanceFromStart <= lineLength)
  75101. return line.getPointAlongLine (distanceFromStart);
  75102. distanceFromStart -= lineLength;
  75103. }
  75104. return Point<float> (i.x2, i.y2);
  75105. }
  75106. float Path::getNearestPoint (const Point<float>& targetPoint, Point<float>& pointOnPath,
  75107. const AffineTransform& transform) const
  75108. {
  75109. PathFlatteningIterator i (*this, transform);
  75110. float bestPosition = 0, bestDistance = std::numeric_limits<float>::max();
  75111. float length = 0;
  75112. Point<float> pointOnLine;
  75113. while (i.next())
  75114. {
  75115. const Line<float> line (i.x1, i.y1, i.x2, i.y2);
  75116. const float distance = line.getDistanceFromPoint (targetPoint, pointOnLine);
  75117. if (distance < bestDistance)
  75118. {
  75119. bestDistance = distance;
  75120. bestPosition = length + pointOnLine.getDistanceFrom (line.getStart());
  75121. pointOnPath = pointOnLine;
  75122. }
  75123. length += line.getLength();
  75124. }
  75125. return bestPosition;
  75126. }
  75127. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const
  75128. {
  75129. if (cornerRadius <= 0.01f)
  75130. return *this;
  75131. size_t indexOfPathStart = 0, indexOfPathStartThis = 0;
  75132. size_t n = 0;
  75133. bool lastWasLine = false, firstWasLine = false;
  75134. Path p;
  75135. while (n < numElements)
  75136. {
  75137. const float type = data.elements [n++];
  75138. if (type == moveMarker)
  75139. {
  75140. indexOfPathStart = p.numElements;
  75141. indexOfPathStartThis = n - 1;
  75142. const float x = data.elements [n++];
  75143. const float y = data.elements [n++];
  75144. p.startNewSubPath (x, y);
  75145. lastWasLine = false;
  75146. firstWasLine = (data.elements [n] == lineMarker);
  75147. }
  75148. else if (type == lineMarker || type == closeSubPathMarker)
  75149. {
  75150. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  75151. if (type == lineMarker)
  75152. {
  75153. endX = data.elements [n++];
  75154. endY = data.elements [n++];
  75155. if (n > 8)
  75156. {
  75157. startX = data.elements [n - 8];
  75158. startY = data.elements [n - 7];
  75159. joinX = data.elements [n - 5];
  75160. joinY = data.elements [n - 4];
  75161. }
  75162. }
  75163. else
  75164. {
  75165. endX = data.elements [indexOfPathStartThis + 1];
  75166. endY = data.elements [indexOfPathStartThis + 2];
  75167. if (n > 6)
  75168. {
  75169. startX = data.elements [n - 6];
  75170. startY = data.elements [n - 5];
  75171. joinX = data.elements [n - 3];
  75172. joinY = data.elements [n - 2];
  75173. }
  75174. }
  75175. if (lastWasLine)
  75176. {
  75177. const double len1 = juce_hypot (startX - joinX,
  75178. startY - joinY);
  75179. if (len1 > 0)
  75180. {
  75181. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75182. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75183. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75184. }
  75185. const double len2 = juce_hypot (endX - joinX,
  75186. endY - joinY);
  75187. if (len2 > 0)
  75188. {
  75189. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75190. p.quadraticTo (joinX, joinY,
  75191. (float) (joinX + (endX - joinX) * propNeeded),
  75192. (float) (joinY + (endY - joinY) * propNeeded));
  75193. }
  75194. p.lineTo (endX, endY);
  75195. }
  75196. else if (type == lineMarker)
  75197. {
  75198. p.lineTo (endX, endY);
  75199. lastWasLine = true;
  75200. }
  75201. if (type == closeSubPathMarker)
  75202. {
  75203. if (firstWasLine)
  75204. {
  75205. startX = data.elements [n - 3];
  75206. startY = data.elements [n - 2];
  75207. joinX = endX;
  75208. joinY = endY;
  75209. endX = data.elements [indexOfPathStartThis + 4];
  75210. endY = data.elements [indexOfPathStartThis + 5];
  75211. const double len1 = juce_hypot (startX - joinX,
  75212. startY - joinY);
  75213. if (len1 > 0)
  75214. {
  75215. const double propNeeded = jmin (0.5, cornerRadius / len1);
  75216. p.data.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  75217. p.data.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  75218. }
  75219. const double len2 = juce_hypot (endX - joinX,
  75220. endY - joinY);
  75221. if (len2 > 0)
  75222. {
  75223. const double propNeeded = jmin (0.5, cornerRadius / len2);
  75224. endX = (float) (joinX + (endX - joinX) * propNeeded);
  75225. endY = (float) (joinY + (endY - joinY) * propNeeded);
  75226. p.quadraticTo (joinX, joinY, endX, endY);
  75227. p.data.elements [indexOfPathStart + 1] = endX;
  75228. p.data.elements [indexOfPathStart + 2] = endY;
  75229. }
  75230. }
  75231. p.closeSubPath();
  75232. }
  75233. }
  75234. else if (type == quadMarker)
  75235. {
  75236. lastWasLine = false;
  75237. const float x1 = data.elements [n++];
  75238. const float y1 = data.elements [n++];
  75239. const float x2 = data.elements [n++];
  75240. const float y2 = data.elements [n++];
  75241. p.quadraticTo (x1, y1, x2, y2);
  75242. }
  75243. else if (type == cubicMarker)
  75244. {
  75245. lastWasLine = false;
  75246. const float x1 = data.elements [n++];
  75247. const float y1 = data.elements [n++];
  75248. const float x2 = data.elements [n++];
  75249. const float y2 = data.elements [n++];
  75250. const float x3 = data.elements [n++];
  75251. const float y3 = data.elements [n++];
  75252. p.cubicTo (x1, y1, x2, y2, x3, y3);
  75253. }
  75254. }
  75255. return p;
  75256. }
  75257. void Path::loadPathFromStream (InputStream& source)
  75258. {
  75259. while (! source.isExhausted())
  75260. {
  75261. switch (source.readByte())
  75262. {
  75263. case 'm':
  75264. {
  75265. const float x = source.readFloat();
  75266. const float y = source.readFloat();
  75267. startNewSubPath (x, y);
  75268. break;
  75269. }
  75270. case 'l':
  75271. {
  75272. const float x = source.readFloat();
  75273. const float y = source.readFloat();
  75274. lineTo (x, y);
  75275. break;
  75276. }
  75277. case 'q':
  75278. {
  75279. const float x1 = source.readFloat();
  75280. const float y1 = source.readFloat();
  75281. const float x2 = source.readFloat();
  75282. const float y2 = source.readFloat();
  75283. quadraticTo (x1, y1, x2, y2);
  75284. break;
  75285. }
  75286. case 'b':
  75287. {
  75288. const float x1 = source.readFloat();
  75289. const float y1 = source.readFloat();
  75290. const float x2 = source.readFloat();
  75291. const float y2 = source.readFloat();
  75292. const float x3 = source.readFloat();
  75293. const float y3 = source.readFloat();
  75294. cubicTo (x1, y1, x2, y2, x3, y3);
  75295. break;
  75296. }
  75297. case 'c':
  75298. closeSubPath();
  75299. break;
  75300. case 'n':
  75301. useNonZeroWinding = true;
  75302. break;
  75303. case 'z':
  75304. useNonZeroWinding = false;
  75305. break;
  75306. case 'e':
  75307. return; // end of path marker
  75308. default:
  75309. jassertfalse; // illegal char in the stream
  75310. break;
  75311. }
  75312. }
  75313. }
  75314. void Path::loadPathFromData (const void* const pathData, const int numberOfBytes)
  75315. {
  75316. MemoryInputStream in (pathData, numberOfBytes, false);
  75317. loadPathFromStream (in);
  75318. }
  75319. void Path::writePathToStream (OutputStream& dest) const
  75320. {
  75321. dest.writeByte (useNonZeroWinding ? 'n' : 'z');
  75322. size_t i = 0;
  75323. while (i < numElements)
  75324. {
  75325. const float type = data.elements [i++];
  75326. if (type == moveMarker)
  75327. {
  75328. dest.writeByte ('m');
  75329. dest.writeFloat (data.elements [i++]);
  75330. dest.writeFloat (data.elements [i++]);
  75331. }
  75332. else if (type == lineMarker)
  75333. {
  75334. dest.writeByte ('l');
  75335. dest.writeFloat (data.elements [i++]);
  75336. dest.writeFloat (data.elements [i++]);
  75337. }
  75338. else if (type == quadMarker)
  75339. {
  75340. dest.writeByte ('q');
  75341. dest.writeFloat (data.elements [i++]);
  75342. dest.writeFloat (data.elements [i++]);
  75343. dest.writeFloat (data.elements [i++]);
  75344. dest.writeFloat (data.elements [i++]);
  75345. }
  75346. else if (type == cubicMarker)
  75347. {
  75348. dest.writeByte ('b');
  75349. dest.writeFloat (data.elements [i++]);
  75350. dest.writeFloat (data.elements [i++]);
  75351. dest.writeFloat (data.elements [i++]);
  75352. dest.writeFloat (data.elements [i++]);
  75353. dest.writeFloat (data.elements [i++]);
  75354. dest.writeFloat (data.elements [i++]);
  75355. }
  75356. else if (type == closeSubPathMarker)
  75357. {
  75358. dest.writeByte ('c');
  75359. }
  75360. }
  75361. dest.writeByte ('e'); // marks the end-of-path
  75362. }
  75363. const String Path::toString() const
  75364. {
  75365. MemoryOutputStream s (2048);
  75366. if (! useNonZeroWinding)
  75367. s << 'a';
  75368. size_t i = 0;
  75369. float lastMarker = 0.0f;
  75370. while (i < numElements)
  75371. {
  75372. const float marker = data.elements [i++];
  75373. char markerChar = 0;
  75374. int numCoords = 0;
  75375. if (marker == moveMarker)
  75376. {
  75377. markerChar = 'm';
  75378. numCoords = 2;
  75379. }
  75380. else if (marker == lineMarker)
  75381. {
  75382. markerChar = 'l';
  75383. numCoords = 2;
  75384. }
  75385. else if (marker == quadMarker)
  75386. {
  75387. markerChar = 'q';
  75388. numCoords = 4;
  75389. }
  75390. else if (marker == cubicMarker)
  75391. {
  75392. markerChar = 'c';
  75393. numCoords = 6;
  75394. }
  75395. else
  75396. {
  75397. jassert (marker == closeSubPathMarker);
  75398. markerChar = 'z';
  75399. }
  75400. if (marker != lastMarker)
  75401. {
  75402. if (s.getDataSize() != 0)
  75403. s << ' ';
  75404. s << markerChar;
  75405. lastMarker = marker;
  75406. }
  75407. while (--numCoords >= 0 && i < numElements)
  75408. {
  75409. String coord (data.elements [i++], 3);
  75410. while (coord.endsWithChar ('0') && coord != "0")
  75411. coord = coord.dropLastCharacters (1);
  75412. if (coord.endsWithChar ('.'))
  75413. coord = coord.dropLastCharacters (1);
  75414. if (s.getDataSize() != 0)
  75415. s << ' ';
  75416. s << coord;
  75417. }
  75418. }
  75419. return s.toUTF8();
  75420. }
  75421. void Path::restoreFromString (const String& stringVersion)
  75422. {
  75423. clear();
  75424. setUsingNonZeroWinding (true);
  75425. const juce_wchar* t = stringVersion;
  75426. juce_wchar marker = 'm';
  75427. int numValues = 2;
  75428. float values [6];
  75429. for (;;)
  75430. {
  75431. const String token (PathHelpers::nextToken (t));
  75432. const juce_wchar firstChar = token[0];
  75433. int startNum = 0;
  75434. if (firstChar == 0)
  75435. break;
  75436. if (firstChar == 'm' || firstChar == 'l')
  75437. {
  75438. marker = firstChar;
  75439. numValues = 2;
  75440. }
  75441. else if (firstChar == 'q')
  75442. {
  75443. marker = firstChar;
  75444. numValues = 4;
  75445. }
  75446. else if (firstChar == 'c')
  75447. {
  75448. marker = firstChar;
  75449. numValues = 6;
  75450. }
  75451. else if (firstChar == 'z')
  75452. {
  75453. marker = firstChar;
  75454. numValues = 0;
  75455. }
  75456. else if (firstChar == 'a')
  75457. {
  75458. setUsingNonZeroWinding (false);
  75459. continue;
  75460. }
  75461. else
  75462. {
  75463. ++startNum;
  75464. values [0] = token.getFloatValue();
  75465. }
  75466. for (int i = startNum; i < numValues; ++i)
  75467. values [i] = PathHelpers::nextToken (t).getFloatValue();
  75468. switch (marker)
  75469. {
  75470. case 'm': startNewSubPath (values[0], values[1]); break;
  75471. case 'l': lineTo (values[0], values[1]); break;
  75472. case 'q': quadraticTo (values[0], values[1], values[2], values[3]); break;
  75473. case 'c': cubicTo (values[0], values[1], values[2], values[3], values[4], values[5]); break;
  75474. case 'z': closeSubPath(); break;
  75475. default: jassertfalse; break; // illegal string format?
  75476. }
  75477. }
  75478. }
  75479. Path::Iterator::Iterator (const Path& path_)
  75480. : path (path_),
  75481. index (0)
  75482. {
  75483. }
  75484. Path::Iterator::~Iterator()
  75485. {
  75486. }
  75487. bool Path::Iterator::next()
  75488. {
  75489. const float* const elements = path.data.elements;
  75490. if (index < path.numElements)
  75491. {
  75492. const float type = elements [index++];
  75493. if (type == moveMarker)
  75494. {
  75495. elementType = startNewSubPath;
  75496. x1 = elements [index++];
  75497. y1 = elements [index++];
  75498. }
  75499. else if (type == lineMarker)
  75500. {
  75501. elementType = lineTo;
  75502. x1 = elements [index++];
  75503. y1 = elements [index++];
  75504. }
  75505. else if (type == quadMarker)
  75506. {
  75507. elementType = quadraticTo;
  75508. x1 = elements [index++];
  75509. y1 = elements [index++];
  75510. x2 = elements [index++];
  75511. y2 = elements [index++];
  75512. }
  75513. else if (type == cubicMarker)
  75514. {
  75515. elementType = cubicTo;
  75516. x1 = elements [index++];
  75517. y1 = elements [index++];
  75518. x2 = elements [index++];
  75519. y2 = elements [index++];
  75520. x3 = elements [index++];
  75521. y3 = elements [index++];
  75522. }
  75523. else if (type == closeSubPathMarker)
  75524. {
  75525. elementType = closePath;
  75526. }
  75527. return true;
  75528. }
  75529. return false;
  75530. }
  75531. END_JUCE_NAMESPACE
  75532. /*** End of inlined file: juce_Path.cpp ***/
  75533. /*** Start of inlined file: juce_PathIterator.cpp ***/
  75534. BEGIN_JUCE_NAMESPACE
  75535. #if JUCE_MSVC && JUCE_DEBUG
  75536. #pragma optimize ("t", on)
  75537. #endif
  75538. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  75539. const AffineTransform& transform_,
  75540. float tolerence_)
  75541. : x2 (0),
  75542. y2 (0),
  75543. closesSubPath (false),
  75544. subPathIndex (-1),
  75545. path (path_),
  75546. transform (transform_),
  75547. points (path_.data.elements),
  75548. tolerence (tolerence_ * tolerence_),
  75549. subPathCloseX (0),
  75550. subPathCloseY (0),
  75551. isIdentityTransform (transform_.isIdentity()),
  75552. stackBase (32),
  75553. index (0),
  75554. stackSize (32)
  75555. {
  75556. stackPos = stackBase;
  75557. }
  75558. PathFlatteningIterator::~PathFlatteningIterator()
  75559. {
  75560. }
  75561. bool PathFlatteningIterator::next()
  75562. {
  75563. x1 = x2;
  75564. y1 = y2;
  75565. float x3 = 0;
  75566. float y3 = 0;
  75567. float x4 = 0;
  75568. float y4 = 0;
  75569. float type;
  75570. for (;;)
  75571. {
  75572. if (stackPos == stackBase)
  75573. {
  75574. if (index >= path.numElements)
  75575. {
  75576. return false;
  75577. }
  75578. else
  75579. {
  75580. type = points [index++];
  75581. if (type != Path::closeSubPathMarker)
  75582. {
  75583. x2 = points [index++];
  75584. y2 = points [index++];
  75585. if (type == Path::quadMarker)
  75586. {
  75587. x3 = points [index++];
  75588. y3 = points [index++];
  75589. if (! isIdentityTransform)
  75590. transform.transformPoints (x2, y2, x3, y3);
  75591. }
  75592. else if (type == Path::cubicMarker)
  75593. {
  75594. x3 = points [index++];
  75595. y3 = points [index++];
  75596. x4 = points [index++];
  75597. y4 = points [index++];
  75598. if (! isIdentityTransform)
  75599. transform.transformPoints (x2, y2, x3, y3, x4, y4);
  75600. }
  75601. else
  75602. {
  75603. if (! isIdentityTransform)
  75604. transform.transformPoint (x2, y2);
  75605. }
  75606. }
  75607. }
  75608. }
  75609. else
  75610. {
  75611. type = *--stackPos;
  75612. if (type != Path::closeSubPathMarker)
  75613. {
  75614. x2 = *--stackPos;
  75615. y2 = *--stackPos;
  75616. if (type == Path::quadMarker)
  75617. {
  75618. x3 = *--stackPos;
  75619. y3 = *--stackPos;
  75620. }
  75621. else if (type == Path::cubicMarker)
  75622. {
  75623. x3 = *--stackPos;
  75624. y3 = *--stackPos;
  75625. x4 = *--stackPos;
  75626. y4 = *--stackPos;
  75627. }
  75628. }
  75629. }
  75630. if (type == Path::lineMarker)
  75631. {
  75632. ++subPathIndex;
  75633. closesSubPath = (stackPos == stackBase)
  75634. && (index < path.numElements)
  75635. && (points [index] == Path::closeSubPathMarker)
  75636. && x2 == subPathCloseX
  75637. && y2 == subPathCloseY;
  75638. return true;
  75639. }
  75640. else if (type == Path::quadMarker)
  75641. {
  75642. const size_t offset = (size_t) (stackPos - stackBase);
  75643. if (offset >= stackSize - 10)
  75644. {
  75645. stackSize <<= 1;
  75646. stackBase.realloc (stackSize);
  75647. stackPos = stackBase + offset;
  75648. }
  75649. const float dx1 = x1 - x2;
  75650. const float dy1 = y1 - y2;
  75651. const float dx2 = x2 - x3;
  75652. const float dy2 = y2 - y3;
  75653. const float m1x = (x1 + x2) * 0.5f;
  75654. const float m1y = (y1 + y2) * 0.5f;
  75655. const float m2x = (x2 + x3) * 0.5f;
  75656. const float m2y = (y2 + y3) * 0.5f;
  75657. const float m3x = (m1x + m2x) * 0.5f;
  75658. const float m3y = (m1y + m2y) * 0.5f;
  75659. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  75660. {
  75661. *stackPos++ = y3;
  75662. *stackPos++ = x3;
  75663. *stackPos++ = m2y;
  75664. *stackPos++ = m2x;
  75665. *stackPos++ = Path::quadMarker;
  75666. *stackPos++ = m3y;
  75667. *stackPos++ = m3x;
  75668. *stackPos++ = m1y;
  75669. *stackPos++ = m1x;
  75670. *stackPos++ = Path::quadMarker;
  75671. }
  75672. else
  75673. {
  75674. *stackPos++ = y3;
  75675. *stackPos++ = x3;
  75676. *stackPos++ = Path::lineMarker;
  75677. *stackPos++ = m3y;
  75678. *stackPos++ = m3x;
  75679. *stackPos++ = Path::lineMarker;
  75680. }
  75681. jassert (stackPos < stackBase + stackSize);
  75682. }
  75683. else if (type == Path::cubicMarker)
  75684. {
  75685. const size_t offset = (size_t) (stackPos - stackBase);
  75686. if (offset >= stackSize - 16)
  75687. {
  75688. stackSize <<= 1;
  75689. stackBase.realloc (stackSize);
  75690. stackPos = stackBase + offset;
  75691. }
  75692. const float dx1 = x1 - x2;
  75693. const float dy1 = y1 - y2;
  75694. const float dx2 = x2 - x3;
  75695. const float dy2 = y2 - y3;
  75696. const float dx3 = x3 - x4;
  75697. const float dy3 = y3 - y4;
  75698. const float m1x = (x1 + x2) * 0.5f;
  75699. const float m1y = (y1 + y2) * 0.5f;
  75700. const float m2x = (x3 + x2) * 0.5f;
  75701. const float m2y = (y3 + y2) * 0.5f;
  75702. const float m3x = (x3 + x4) * 0.5f;
  75703. const float m3y = (y3 + y4) * 0.5f;
  75704. const float m4x = (m1x + m2x) * 0.5f;
  75705. const float m4y = (m1y + m2y) * 0.5f;
  75706. const float m5x = (m3x + m2x) * 0.5f;
  75707. const float m5y = (m3y + m2y) * 0.5f;
  75708. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  75709. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  75710. {
  75711. *stackPos++ = y4;
  75712. *stackPos++ = x4;
  75713. *stackPos++ = m3y;
  75714. *stackPos++ = m3x;
  75715. *stackPos++ = m5y;
  75716. *stackPos++ = m5x;
  75717. *stackPos++ = Path::cubicMarker;
  75718. *stackPos++ = (m4y + m5y) * 0.5f;
  75719. *stackPos++ = (m4x + m5x) * 0.5f;
  75720. *stackPos++ = m4y;
  75721. *stackPos++ = m4x;
  75722. *stackPos++ = m1y;
  75723. *stackPos++ = m1x;
  75724. *stackPos++ = Path::cubicMarker;
  75725. }
  75726. else
  75727. {
  75728. *stackPos++ = y4;
  75729. *stackPos++ = x4;
  75730. *stackPos++ = Path::lineMarker;
  75731. *stackPos++ = m5y;
  75732. *stackPos++ = m5x;
  75733. *stackPos++ = Path::lineMarker;
  75734. *stackPos++ = m4y;
  75735. *stackPos++ = m4x;
  75736. *stackPos++ = Path::lineMarker;
  75737. }
  75738. }
  75739. else if (type == Path::closeSubPathMarker)
  75740. {
  75741. if (x2 != subPathCloseX || y2 != subPathCloseY)
  75742. {
  75743. x1 = x2;
  75744. y1 = y2;
  75745. x2 = subPathCloseX;
  75746. y2 = subPathCloseY;
  75747. closesSubPath = true;
  75748. return true;
  75749. }
  75750. }
  75751. else
  75752. {
  75753. jassert (type == Path::moveMarker);
  75754. subPathIndex = -1;
  75755. subPathCloseX = x1 = x2;
  75756. subPathCloseY = y1 = y2;
  75757. }
  75758. }
  75759. }
  75760. #if JUCE_MSVC && JUCE_DEBUG
  75761. #pragma optimize ("", on) // resets optimisations to the project defaults
  75762. #endif
  75763. END_JUCE_NAMESPACE
  75764. /*** End of inlined file: juce_PathIterator.cpp ***/
  75765. /*** Start of inlined file: juce_PathStrokeType.cpp ***/
  75766. BEGIN_JUCE_NAMESPACE
  75767. PathStrokeType::PathStrokeType (const float strokeThickness,
  75768. const JointStyle jointStyle_,
  75769. const EndCapStyle endStyle_) throw()
  75770. : thickness (strokeThickness),
  75771. jointStyle (jointStyle_),
  75772. endStyle (endStyle_)
  75773. {
  75774. }
  75775. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  75776. : thickness (other.thickness),
  75777. jointStyle (other.jointStyle),
  75778. endStyle (other.endStyle)
  75779. {
  75780. }
  75781. PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  75782. {
  75783. thickness = other.thickness;
  75784. jointStyle = other.jointStyle;
  75785. endStyle = other.endStyle;
  75786. return *this;
  75787. }
  75788. PathStrokeType::~PathStrokeType() throw()
  75789. {
  75790. }
  75791. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  75792. {
  75793. return thickness == other.thickness
  75794. && jointStyle == other.jointStyle
  75795. && endStyle == other.endStyle;
  75796. }
  75797. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  75798. {
  75799. return ! operator== (other);
  75800. }
  75801. namespace PathStrokeHelpers
  75802. {
  75803. static bool lineIntersection (const float x1, const float y1,
  75804. const float x2, const float y2,
  75805. const float x3, const float y3,
  75806. const float x4, const float y4,
  75807. float& intersectionX,
  75808. float& intersectionY,
  75809. float& distanceBeyondLine1EndSquared) throw()
  75810. {
  75811. if (x2 != x3 || y2 != y3)
  75812. {
  75813. const float dx1 = x2 - x1;
  75814. const float dy1 = y2 - y1;
  75815. const float dx2 = x4 - x3;
  75816. const float dy2 = y4 - y3;
  75817. const float divisor = dx1 * dy2 - dx2 * dy1;
  75818. if (divisor == 0)
  75819. {
  75820. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  75821. {
  75822. if (dy1 == 0 && dy2 != 0)
  75823. {
  75824. const float along = (y1 - y3) / dy2;
  75825. intersectionX = x3 + along * dx2;
  75826. intersectionY = y1;
  75827. distanceBeyondLine1EndSquared = intersectionX - x2;
  75828. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75829. if ((x2 > x1) == (intersectionX < x2))
  75830. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75831. return along >= 0 && along <= 1.0f;
  75832. }
  75833. else if (dy2 == 0 && dy1 != 0)
  75834. {
  75835. const float along = (y3 - y1) / dy1;
  75836. intersectionX = x1 + along * dx1;
  75837. intersectionY = y3;
  75838. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  75839. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75840. if (along < 1.0f)
  75841. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75842. return along >= 0 && along <= 1.0f;
  75843. }
  75844. else if (dx1 == 0 && dx2 != 0)
  75845. {
  75846. const float along = (x1 - x3) / dx2;
  75847. intersectionX = x1;
  75848. intersectionY = y3 + along * dy2;
  75849. distanceBeyondLine1EndSquared = intersectionY - y2;
  75850. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75851. if ((y2 > y1) == (intersectionY < y2))
  75852. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75853. return along >= 0 && along <= 1.0f;
  75854. }
  75855. else if (dx2 == 0 && dx1 != 0)
  75856. {
  75857. const float along = (x3 - x1) / dx1;
  75858. intersectionX = x3;
  75859. intersectionY = y1 + along * dy1;
  75860. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  75861. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75862. if (along < 1.0f)
  75863. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75864. return along >= 0 && along <= 1.0f;
  75865. }
  75866. }
  75867. intersectionX = 0.5f * (x2 + x3);
  75868. intersectionY = 0.5f * (y2 + y3);
  75869. distanceBeyondLine1EndSquared = 0.0f;
  75870. return false;
  75871. }
  75872. else
  75873. {
  75874. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  75875. intersectionX = x1 + along1 * dx1;
  75876. intersectionY = y1 + along1 * dy1;
  75877. if (along1 >= 0 && along1 <= 1.0f)
  75878. {
  75879. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  75880. if (along2 >= 0 && along2 <= divisor)
  75881. {
  75882. distanceBeyondLine1EndSquared = 0.0f;
  75883. return true;
  75884. }
  75885. }
  75886. distanceBeyondLine1EndSquared = along1 - 1.0f;
  75887. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  75888. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  75889. if (along1 < 1.0f)
  75890. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  75891. return false;
  75892. }
  75893. }
  75894. intersectionX = x2;
  75895. intersectionY = y2;
  75896. distanceBeyondLine1EndSquared = 0.0f;
  75897. return true;
  75898. }
  75899. static void addEdgeAndJoint (Path& destPath,
  75900. const PathStrokeType::JointStyle style,
  75901. const float maxMiterExtensionSquared, const float width,
  75902. const float x1, const float y1,
  75903. const float x2, const float y2,
  75904. const float x3, const float y3,
  75905. const float x4, const float y4,
  75906. const float midX, const float midY)
  75907. {
  75908. if (style == PathStrokeType::beveled
  75909. || (x3 == x4 && y3 == y4)
  75910. || (x1 == x2 && y1 == y2))
  75911. {
  75912. destPath.lineTo (x2, y2);
  75913. destPath.lineTo (x3, y3);
  75914. }
  75915. else
  75916. {
  75917. float jx, jy, distanceBeyondLine1EndSquared;
  75918. // if they intersect, use this point..
  75919. if (lineIntersection (x1, y1, x2, y2,
  75920. x3, y3, x4, y4,
  75921. jx, jy, distanceBeyondLine1EndSquared))
  75922. {
  75923. destPath.lineTo (jx, jy);
  75924. }
  75925. else
  75926. {
  75927. if (style == PathStrokeType::mitered)
  75928. {
  75929. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  75930. && distanceBeyondLine1EndSquared > 0.0f)
  75931. {
  75932. destPath.lineTo (jx, jy);
  75933. }
  75934. else
  75935. {
  75936. // the end sticks out too far, so just use a blunt joint
  75937. destPath.lineTo (x2, y2);
  75938. destPath.lineTo (x3, y3);
  75939. }
  75940. }
  75941. else
  75942. {
  75943. // curved joints
  75944. float angle1 = std::atan2 (x2 - midX, y2 - midY);
  75945. float angle2 = std::atan2 (x3 - midX, y3 - midY);
  75946. const float angleIncrement = 0.1f;
  75947. destPath.lineTo (x2, y2);
  75948. if (std::abs (angle1 - angle2) > angleIncrement)
  75949. {
  75950. if (angle2 > angle1 + float_Pi
  75951. || (angle2 < angle1 && angle2 >= angle1 - float_Pi))
  75952. {
  75953. if (angle2 > angle1)
  75954. angle2 -= float_Pi * 2.0f;
  75955. jassert (angle1 <= angle2 + float_Pi);
  75956. angle1 -= angleIncrement;
  75957. while (angle1 > angle2)
  75958. {
  75959. destPath.lineTo (midX + width * std::sin (angle1),
  75960. midY + width * std::cos (angle1));
  75961. angle1 -= angleIncrement;
  75962. }
  75963. }
  75964. else
  75965. {
  75966. if (angle1 > angle2)
  75967. angle1 -= float_Pi * 2.0f;
  75968. jassert (angle1 >= angle2 - float_Pi);
  75969. angle1 += angleIncrement;
  75970. while (angle1 < angle2)
  75971. {
  75972. destPath.lineTo (midX + width * std::sin (angle1),
  75973. midY + width * std::cos (angle1));
  75974. angle1 += angleIncrement;
  75975. }
  75976. }
  75977. }
  75978. destPath.lineTo (x3, y3);
  75979. }
  75980. }
  75981. }
  75982. }
  75983. static void addLineEnd (Path& destPath,
  75984. const PathStrokeType::EndCapStyle style,
  75985. const float x1, const float y1,
  75986. const float x2, const float y2,
  75987. const float width)
  75988. {
  75989. if (style == PathStrokeType::butt)
  75990. {
  75991. destPath.lineTo (x2, y2);
  75992. }
  75993. else
  75994. {
  75995. float offx1, offy1, offx2, offy2;
  75996. float dx = x2 - x1;
  75997. float dy = y2 - y1;
  75998. const float len = juce_hypotf (dx, dy);
  75999. if (len == 0)
  76000. {
  76001. offx1 = offx2 = x1;
  76002. offy1 = offy2 = y1;
  76003. }
  76004. else
  76005. {
  76006. const float offset = width / len;
  76007. dx *= offset;
  76008. dy *= offset;
  76009. offx1 = x1 + dy;
  76010. offy1 = y1 - dx;
  76011. offx2 = x2 + dy;
  76012. offy2 = y2 - dx;
  76013. }
  76014. if (style == PathStrokeType::square)
  76015. {
  76016. // sqaure ends
  76017. destPath.lineTo (offx1, offy1);
  76018. destPath.lineTo (offx2, offy2);
  76019. destPath.lineTo (x2, y2);
  76020. }
  76021. else
  76022. {
  76023. // rounded ends
  76024. const float midx = (offx1 + offx2) * 0.5f;
  76025. const float midy = (offy1 + offy2) * 0.5f;
  76026. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  76027. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  76028. midx, midy);
  76029. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  76030. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  76031. x2, y2);
  76032. }
  76033. }
  76034. }
  76035. struct Arrowhead
  76036. {
  76037. float startWidth, startLength;
  76038. float endWidth, endLength;
  76039. };
  76040. static void addArrowhead (Path& destPath,
  76041. const float x1, const float y1,
  76042. const float x2, const float y2,
  76043. const float tipX, const float tipY,
  76044. const float width,
  76045. const float arrowheadWidth)
  76046. {
  76047. Line<float> line (x1, y1, x2, y2);
  76048. destPath.lineTo (line.getPointAlongLine (-(arrowheadWidth / 2.0f - width), 0));
  76049. destPath.lineTo (tipX, tipY);
  76050. destPath.lineTo (line.getPointAlongLine (arrowheadWidth - (arrowheadWidth / 2.0f - width), 0));
  76051. destPath.lineTo (x2, y2);
  76052. }
  76053. struct LineSection
  76054. {
  76055. float x1, y1, x2, y2; // original line
  76056. float lx1, ly1, lx2, ly2; // the left-hand stroke
  76057. float rx1, ry1, rx2, ry2; // the right-hand stroke
  76058. };
  76059. static void shortenSubPath (Array<LineSection>& subPath, float amountAtStart, float amountAtEnd)
  76060. {
  76061. while (amountAtEnd > 0 && subPath.size() > 0)
  76062. {
  76063. LineSection& l = subPath.getReference (subPath.size() - 1);
  76064. float dx = l.rx2 - l.rx1;
  76065. float dy = l.ry2 - l.ry1;
  76066. const float len = juce_hypotf (dx, dy);
  76067. if (len <= amountAtEnd && subPath.size() > 1)
  76068. {
  76069. LineSection& prev = subPath.getReference (subPath.size() - 2);
  76070. prev.x2 = l.x2;
  76071. prev.y2 = l.y2;
  76072. subPath.removeLast();
  76073. amountAtEnd -= len;
  76074. }
  76075. else
  76076. {
  76077. const float prop = jmin (0.9999f, amountAtEnd / len);
  76078. dx *= prop;
  76079. dy *= prop;
  76080. l.rx1 += dx;
  76081. l.ry1 += dy;
  76082. l.lx2 += dx;
  76083. l.ly2 += dy;
  76084. break;
  76085. }
  76086. }
  76087. while (amountAtStart > 0 && subPath.size() > 0)
  76088. {
  76089. LineSection& l = subPath.getReference (0);
  76090. float dx = l.rx2 - l.rx1;
  76091. float dy = l.ry2 - l.ry1;
  76092. const float len = juce_hypotf (dx, dy);
  76093. if (len <= amountAtStart && subPath.size() > 1)
  76094. {
  76095. LineSection& next = subPath.getReference (1);
  76096. next.x1 = l.x1;
  76097. next.y1 = l.y1;
  76098. subPath.remove (0);
  76099. amountAtStart -= len;
  76100. }
  76101. else
  76102. {
  76103. const float prop = jmin (0.9999f, amountAtStart / len);
  76104. dx *= prop;
  76105. dy *= prop;
  76106. l.rx2 -= dx;
  76107. l.ry2 -= dy;
  76108. l.lx1 -= dx;
  76109. l.ly1 -= dy;
  76110. break;
  76111. }
  76112. }
  76113. }
  76114. static void addSubPath (Path& destPath, Array<LineSection>& subPath,
  76115. const bool isClosed, const float width, const float maxMiterExtensionSquared,
  76116. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle,
  76117. const Arrowhead* const arrowhead)
  76118. {
  76119. jassert (subPath.size() > 0);
  76120. if (arrowhead != 0)
  76121. shortenSubPath (subPath, arrowhead->startLength, arrowhead->endLength);
  76122. const LineSection& firstLine = subPath.getReference (0);
  76123. float lastX1 = firstLine.lx1;
  76124. float lastY1 = firstLine.ly1;
  76125. float lastX2 = firstLine.lx2;
  76126. float lastY2 = firstLine.ly2;
  76127. if (isClosed)
  76128. {
  76129. destPath.startNewSubPath (lastX1, lastY1);
  76130. }
  76131. else
  76132. {
  76133. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  76134. if (arrowhead != 0)
  76135. addArrowhead (destPath, firstLine.rx2, firstLine.ry2, lastX1, lastY1, firstLine.x1, firstLine.y1,
  76136. width, arrowhead->startWidth);
  76137. else
  76138. addLineEnd (destPath, endStyle, firstLine.rx2, firstLine.ry2, lastX1, lastY1, width);
  76139. }
  76140. int i;
  76141. for (i = 1; i < subPath.size(); ++i)
  76142. {
  76143. const LineSection& l = subPath.getReference (i);
  76144. addEdgeAndJoint (destPath, jointStyle,
  76145. maxMiterExtensionSquared, width,
  76146. lastX1, lastY1, lastX2, lastY2,
  76147. l.lx1, l.ly1, l.lx2, l.ly2,
  76148. l.x1, l.y1);
  76149. lastX1 = l.lx1;
  76150. lastY1 = l.ly1;
  76151. lastX2 = l.lx2;
  76152. lastY2 = l.ly2;
  76153. }
  76154. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  76155. if (isClosed)
  76156. {
  76157. const LineSection& l = subPath.getReference (0);
  76158. addEdgeAndJoint (destPath, jointStyle,
  76159. maxMiterExtensionSquared, width,
  76160. lastX1, lastY1, lastX2, lastY2,
  76161. l.lx1, l.ly1, l.lx2, l.ly2,
  76162. l.x1, l.y1);
  76163. destPath.closeSubPath();
  76164. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  76165. }
  76166. else
  76167. {
  76168. destPath.lineTo (lastX2, lastY2);
  76169. if (arrowhead != 0)
  76170. addArrowhead (destPath, lastX2, lastY2, lastLine.rx1, lastLine.ry1, lastLine.x2, lastLine.y2,
  76171. width, arrowhead->endWidth);
  76172. else
  76173. addLineEnd (destPath, endStyle, lastX2, lastY2, lastLine.rx1, lastLine.ry1, width);
  76174. }
  76175. lastX1 = lastLine.rx1;
  76176. lastY1 = lastLine.ry1;
  76177. lastX2 = lastLine.rx2;
  76178. lastY2 = lastLine.ry2;
  76179. for (i = subPath.size() - 1; --i >= 0;)
  76180. {
  76181. const LineSection& l = subPath.getReference (i);
  76182. addEdgeAndJoint (destPath, jointStyle,
  76183. maxMiterExtensionSquared, width,
  76184. lastX1, lastY1, lastX2, lastY2,
  76185. l.rx1, l.ry1, l.rx2, l.ry2,
  76186. l.x2, l.y2);
  76187. lastX1 = l.rx1;
  76188. lastY1 = l.ry1;
  76189. lastX2 = l.rx2;
  76190. lastY2 = l.ry2;
  76191. }
  76192. if (isClosed)
  76193. {
  76194. addEdgeAndJoint (destPath, jointStyle,
  76195. maxMiterExtensionSquared, width,
  76196. lastX1, lastY1, lastX2, lastY2,
  76197. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  76198. lastLine.x2, lastLine.y2);
  76199. }
  76200. else
  76201. {
  76202. // do the last line
  76203. destPath.lineTo (lastX2, lastY2);
  76204. }
  76205. destPath.closeSubPath();
  76206. }
  76207. static void createStroke (const float thickness, const PathStrokeType::JointStyle jointStyle,
  76208. const PathStrokeType::EndCapStyle endStyle,
  76209. Path& destPath, const Path& source,
  76210. const AffineTransform& transform,
  76211. const float extraAccuracy, const Arrowhead* const arrowhead)
  76212. {
  76213. if (thickness <= 0)
  76214. {
  76215. destPath.clear();
  76216. return;
  76217. }
  76218. const Path* sourcePath = &source;
  76219. Path temp;
  76220. if (sourcePath == &destPath)
  76221. {
  76222. destPath.swapWithPath (temp);
  76223. sourcePath = &temp;
  76224. }
  76225. else
  76226. {
  76227. destPath.clear();
  76228. }
  76229. destPath.setUsingNonZeroWinding (true);
  76230. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  76231. const float width = 0.5f * thickness;
  76232. // Iterate the path, creating a list of the
  76233. // left/right-hand lines along either side of it...
  76234. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  76235. Array <LineSection> subPath;
  76236. subPath.ensureStorageAllocated (512);
  76237. LineSection l;
  76238. l.x1 = 0;
  76239. l.y1 = 0;
  76240. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  76241. while (it.next())
  76242. {
  76243. if (it.subPathIndex == 0)
  76244. {
  76245. if (subPath.size() > 0)
  76246. {
  76247. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76248. subPath.clearQuick();
  76249. }
  76250. l.x1 = it.x1;
  76251. l.y1 = it.y1;
  76252. }
  76253. l.x2 = it.x2;
  76254. l.y2 = it.y2;
  76255. float dx = l.x2 - l.x1;
  76256. float dy = l.y2 - l.y1;
  76257. const float hypotSquared = dx*dx + dy*dy;
  76258. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  76259. {
  76260. const float len = std::sqrt (hypotSquared);
  76261. if (len == 0)
  76262. {
  76263. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  76264. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  76265. }
  76266. else
  76267. {
  76268. const float offset = width / len;
  76269. dx *= offset;
  76270. dy *= offset;
  76271. l.rx2 = l.x1 - dy;
  76272. l.ry2 = l.y1 + dx;
  76273. l.lx1 = l.x1 + dy;
  76274. l.ly1 = l.y1 - dx;
  76275. l.lx2 = l.x2 + dy;
  76276. l.ly2 = l.y2 - dx;
  76277. l.rx1 = l.x2 - dy;
  76278. l.ry1 = l.y2 + dx;
  76279. }
  76280. subPath.add (l);
  76281. if (it.closesSubPath)
  76282. {
  76283. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76284. subPath.clearQuick();
  76285. }
  76286. else
  76287. {
  76288. l.x1 = it.x2;
  76289. l.y1 = it.y2;
  76290. }
  76291. }
  76292. }
  76293. if (subPath.size() > 0)
  76294. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle, arrowhead);
  76295. }
  76296. }
  76297. void PathStrokeType::createStrokedPath (Path& destPath, const Path& sourcePath,
  76298. const AffineTransform& transform, const float extraAccuracy) const
  76299. {
  76300. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle, destPath, sourcePath,
  76301. transform, extraAccuracy, 0);
  76302. }
  76303. void PathStrokeType::createDashedStroke (Path& destPath,
  76304. const Path& sourcePath,
  76305. const float* dashLengths,
  76306. int numDashLengths,
  76307. const AffineTransform& transform,
  76308. const float extraAccuracy) const
  76309. {
  76310. if (thickness <= 0)
  76311. return;
  76312. // this should really be an even number..
  76313. jassert ((numDashLengths & 1) == 0);
  76314. Path newDestPath;
  76315. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  76316. bool first = true;
  76317. int dashNum = 0;
  76318. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  76319. float dx = 0.0f, dy = 0.0f;
  76320. for (;;)
  76321. {
  76322. const bool isSolid = ((dashNum & 1) == 0);
  76323. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  76324. jassert (dashLen > 0); // must be a positive increment!
  76325. if (dashLen <= 0)
  76326. break;
  76327. pos += dashLen;
  76328. while (pos > lineEndPos)
  76329. {
  76330. if (! it.next())
  76331. {
  76332. if (isSolid && ! first)
  76333. newDestPath.lineTo (it.x2, it.y2);
  76334. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  76335. return;
  76336. }
  76337. if (isSolid && ! first)
  76338. newDestPath.lineTo (it.x1, it.y1);
  76339. else
  76340. newDestPath.startNewSubPath (it.x1, it.y1);
  76341. dx = it.x2 - it.x1;
  76342. dy = it.y2 - it.y1;
  76343. lineLen = juce_hypotf (dx, dy);
  76344. lineEndPos += lineLen;
  76345. first = it.closesSubPath;
  76346. }
  76347. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  76348. if (isSolid)
  76349. newDestPath.lineTo (it.x1 + dx * alpha,
  76350. it.y1 + dy * alpha);
  76351. else
  76352. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  76353. it.y1 + dy * alpha);
  76354. }
  76355. }
  76356. void PathStrokeType::createStrokeWithArrowheads (Path& destPath,
  76357. const Path& sourcePath,
  76358. const float arrowheadStartWidth, const float arrowheadStartLength,
  76359. const float arrowheadEndWidth, const float arrowheadEndLength,
  76360. const AffineTransform& transform,
  76361. const float extraAccuracy) const
  76362. {
  76363. PathStrokeHelpers::Arrowhead head;
  76364. head.startWidth = arrowheadStartWidth;
  76365. head.startLength = arrowheadStartLength;
  76366. head.endWidth = arrowheadEndWidth;
  76367. head.endLength = arrowheadEndLength;
  76368. PathStrokeHelpers::createStroke (thickness, jointStyle, endStyle,
  76369. destPath, sourcePath, transform, extraAccuracy, &head);
  76370. }
  76371. END_JUCE_NAMESPACE
  76372. /*** End of inlined file: juce_PathStrokeType.cpp ***/
  76373. /*** Start of inlined file: juce_PositionedRectangle.cpp ***/
  76374. BEGIN_JUCE_NAMESPACE
  76375. PositionedRectangle::PositionedRectangle() throw()
  76376. : x (0.0),
  76377. y (0.0),
  76378. w (0.0),
  76379. h (0.0),
  76380. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76381. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  76382. wMode (absoluteSize),
  76383. hMode (absoluteSize)
  76384. {
  76385. }
  76386. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  76387. : x (other.x),
  76388. y (other.y),
  76389. w (other.w),
  76390. h (other.h),
  76391. xMode (other.xMode),
  76392. yMode (other.yMode),
  76393. wMode (other.wMode),
  76394. hMode (other.hMode)
  76395. {
  76396. }
  76397. PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  76398. {
  76399. x = other.x;
  76400. y = other.y;
  76401. w = other.w;
  76402. h = other.h;
  76403. xMode = other.xMode;
  76404. yMode = other.yMode;
  76405. wMode = other.wMode;
  76406. hMode = other.hMode;
  76407. return *this;
  76408. }
  76409. PositionedRectangle::~PositionedRectangle() throw()
  76410. {
  76411. }
  76412. bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  76413. {
  76414. return x == other.x
  76415. && y == other.y
  76416. && w == other.w
  76417. && h == other.h
  76418. && xMode == other.xMode
  76419. && yMode == other.yMode
  76420. && wMode == other.wMode
  76421. && hMode == other.hMode;
  76422. }
  76423. bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  76424. {
  76425. return ! operator== (other);
  76426. }
  76427. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  76428. {
  76429. StringArray tokens;
  76430. tokens.addTokens (stringVersion, false);
  76431. decodePosString (tokens [0], xMode, x);
  76432. decodePosString (tokens [1], yMode, y);
  76433. decodeSizeString (tokens [2], wMode, w);
  76434. decodeSizeString (tokens [3], hMode, h);
  76435. }
  76436. const String PositionedRectangle::toString() const throw()
  76437. {
  76438. String s;
  76439. s.preallocateStorage (12);
  76440. addPosDescription (s, xMode, x);
  76441. s << ' ';
  76442. addPosDescription (s, yMode, y);
  76443. s << ' ';
  76444. addSizeDescription (s, wMode, w);
  76445. s << ' ';
  76446. addSizeDescription (s, hMode, h);
  76447. return s;
  76448. }
  76449. const Rectangle<int> PositionedRectangle::getRectangle (const Rectangle<int>& target) const throw()
  76450. {
  76451. jassert (! target.isEmpty());
  76452. double x_, y_, w_, h_;
  76453. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76454. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76455. return Rectangle<int> (roundToInt (x_), roundToInt (y_),
  76456. roundToInt (w_), roundToInt (h_));
  76457. }
  76458. void PositionedRectangle::getRectangleDouble (const Rectangle<int>& target,
  76459. double& x_, double& y_,
  76460. double& w_, double& h_) const throw()
  76461. {
  76462. jassert (! target.isEmpty());
  76463. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  76464. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  76465. }
  76466. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  76467. {
  76468. comp.setBounds (getRectangle (Rectangle<int> (comp.getParentWidth(), comp.getParentHeight())));
  76469. }
  76470. void PositionedRectangle::updateFrom (const Rectangle<int>& rectangle,
  76471. const Rectangle<int>& target) throw()
  76472. {
  76473. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  76474. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  76475. }
  76476. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  76477. const double newW, const double newH,
  76478. const Rectangle<int>& target) throw()
  76479. {
  76480. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  76481. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  76482. }
  76483. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  76484. {
  76485. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  76486. updateFrom (comp.getBounds(), Rectangle<int>());
  76487. else
  76488. updateFrom (comp.getBounds(), Rectangle<int> (comp.getParentWidth(), comp.getParentHeight()));
  76489. }
  76490. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  76491. {
  76492. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76493. }
  76494. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  76495. {
  76496. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  76497. | absoluteFromParentBottomRight
  76498. | absoluteFromParentCentre
  76499. | proportionOfParentSize));
  76500. }
  76501. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  76502. {
  76503. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  76504. }
  76505. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  76506. {
  76507. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  76508. | absoluteFromParentBottomRight
  76509. | absoluteFromParentCentre
  76510. | proportionOfParentSize));
  76511. }
  76512. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  76513. {
  76514. return (SizeMode) wMode;
  76515. }
  76516. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  76517. {
  76518. return (SizeMode) hMode;
  76519. }
  76520. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  76521. const PositionMode xMode_,
  76522. const AnchorPoint yAnchor,
  76523. const PositionMode yMode_,
  76524. const SizeMode widthMode,
  76525. const SizeMode heightMode,
  76526. const Rectangle<int>& target) throw()
  76527. {
  76528. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  76529. {
  76530. double tx, tw;
  76531. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  76532. xMode = (uint8) (xAnchor | xMode_);
  76533. wMode = (uint8) widthMode;
  76534. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  76535. }
  76536. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  76537. {
  76538. double ty, th;
  76539. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  76540. yMode = (uint8) (yAnchor | yMode_);
  76541. hMode = (uint8) heightMode;
  76542. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  76543. }
  76544. }
  76545. bool PositionedRectangle::isPositionAbsolute() const throw()
  76546. {
  76547. return xMode == absoluteFromParentTopLeft
  76548. && yMode == absoluteFromParentTopLeft
  76549. && wMode == absoluteSize
  76550. && hMode == absoluteSize;
  76551. }
  76552. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  76553. {
  76554. if ((mode & proportionOfParentSize) != 0)
  76555. {
  76556. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76557. }
  76558. else
  76559. {
  76560. s << (roundToInt (value * 100.0) / 100.0);
  76561. if ((mode & absoluteFromParentBottomRight) != 0)
  76562. s << 'R';
  76563. else if ((mode & absoluteFromParentCentre) != 0)
  76564. s << 'C';
  76565. }
  76566. if ((mode & anchorAtRightOrBottom) != 0)
  76567. s << 'r';
  76568. else if ((mode & anchorAtCentre) != 0)
  76569. s << 'c';
  76570. }
  76571. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  76572. {
  76573. if (mode == proportionalSize)
  76574. s << (roundToInt (value * 100000.0) / 1000.0) << '%';
  76575. else if (mode == parentSizeMinusAbsolute)
  76576. s << (roundToInt (value * 100.0) / 100.0) << 'M';
  76577. else
  76578. s << (roundToInt (value * 100.0) / 100.0);
  76579. }
  76580. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  76581. {
  76582. if (s.containsChar ('r'))
  76583. mode = anchorAtRightOrBottom;
  76584. else if (s.containsChar ('c'))
  76585. mode = anchorAtCentre;
  76586. else
  76587. mode = anchorAtLeftOrTop;
  76588. if (s.containsChar ('%'))
  76589. {
  76590. mode |= proportionOfParentSize;
  76591. value = s.removeCharacters ("%rcRC").getDoubleValue() / 100.0;
  76592. }
  76593. else
  76594. {
  76595. if (s.containsChar ('R'))
  76596. mode |= absoluteFromParentBottomRight;
  76597. else if (s.containsChar ('C'))
  76598. mode |= absoluteFromParentCentre;
  76599. else
  76600. mode |= absoluteFromParentTopLeft;
  76601. value = s.removeCharacters ("rcRC").getDoubleValue();
  76602. }
  76603. }
  76604. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  76605. {
  76606. if (s.containsChar ('%'))
  76607. {
  76608. mode = proportionalSize;
  76609. value = s.upToFirstOccurrenceOf ("%", false, false).getDoubleValue() / 100.0;
  76610. }
  76611. else if (s.containsChar ('M'))
  76612. {
  76613. mode = parentSizeMinusAbsolute;
  76614. value = s.getDoubleValue();
  76615. }
  76616. else
  76617. {
  76618. mode = absoluteSize;
  76619. value = s.getDoubleValue();
  76620. }
  76621. }
  76622. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  76623. const double x_, const double w_,
  76624. const uint8 xMode_, const uint8 wMode_,
  76625. const int parentPos,
  76626. const int parentSize) const throw()
  76627. {
  76628. if (wMode_ == proportionalSize)
  76629. wOut = roundToInt (w_ * parentSize);
  76630. else if (wMode_ == parentSizeMinusAbsolute)
  76631. wOut = jmax (0, parentSize - roundToInt (w_));
  76632. else
  76633. wOut = roundToInt (w_);
  76634. if ((xMode_ & proportionOfParentSize) != 0)
  76635. xOut = parentPos + x_ * parentSize;
  76636. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76637. xOut = (parentPos + parentSize) - x_;
  76638. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76639. xOut = x_ + (parentPos + parentSize / 2);
  76640. else
  76641. xOut = x_ + parentPos;
  76642. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76643. xOut -= wOut;
  76644. else if ((xMode_ & anchorAtCentre) != 0)
  76645. xOut -= wOut / 2;
  76646. }
  76647. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  76648. double x_, const double w_,
  76649. const uint8 xMode_, const uint8 wMode_,
  76650. const int parentPos,
  76651. const int parentSize) const throw()
  76652. {
  76653. if (wMode_ == proportionalSize)
  76654. {
  76655. if (parentSize > 0)
  76656. wOut = w_ / parentSize;
  76657. }
  76658. else if (wMode_ == parentSizeMinusAbsolute)
  76659. wOut = parentSize - w_;
  76660. else
  76661. wOut = w_;
  76662. if ((xMode_ & anchorAtRightOrBottom) != 0)
  76663. x_ += w_;
  76664. else if ((xMode_ & anchorAtCentre) != 0)
  76665. x_ += w_ / 2;
  76666. if ((xMode_ & proportionOfParentSize) != 0)
  76667. {
  76668. if (parentSize > 0)
  76669. xOut = (x_ - parentPos) / parentSize;
  76670. }
  76671. else if ((xMode_ & absoluteFromParentBottomRight) != 0)
  76672. xOut = (parentPos + parentSize) - x_;
  76673. else if ((xMode_ & absoluteFromParentCentre) != 0)
  76674. xOut = x_ - (parentPos + parentSize / 2);
  76675. else
  76676. xOut = x_ - parentPos;
  76677. }
  76678. END_JUCE_NAMESPACE
  76679. /*** End of inlined file: juce_PositionedRectangle.cpp ***/
  76680. /*** Start of inlined file: juce_RectangleList.cpp ***/
  76681. BEGIN_JUCE_NAMESPACE
  76682. RectangleList::RectangleList() throw()
  76683. {
  76684. }
  76685. RectangleList::RectangleList (const Rectangle<int>& rect)
  76686. {
  76687. if (! rect.isEmpty())
  76688. rects.add (rect);
  76689. }
  76690. RectangleList::RectangleList (const RectangleList& other)
  76691. : rects (other.rects)
  76692. {
  76693. }
  76694. RectangleList& RectangleList::operator= (const RectangleList& other)
  76695. {
  76696. rects = other.rects;
  76697. return *this;
  76698. }
  76699. RectangleList::~RectangleList()
  76700. {
  76701. }
  76702. void RectangleList::clear()
  76703. {
  76704. rects.clearQuick();
  76705. }
  76706. const Rectangle<int> RectangleList::getRectangle (const int index) const throw()
  76707. {
  76708. if (((unsigned int) index) < (unsigned int) rects.size())
  76709. return rects.getReference (index);
  76710. return Rectangle<int>();
  76711. }
  76712. bool RectangleList::isEmpty() const throw()
  76713. {
  76714. return rects.size() == 0;
  76715. }
  76716. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  76717. : current (0),
  76718. owner (list),
  76719. index (list.rects.size())
  76720. {
  76721. }
  76722. RectangleList::Iterator::~Iterator()
  76723. {
  76724. }
  76725. bool RectangleList::Iterator::next() throw()
  76726. {
  76727. if (--index >= 0)
  76728. {
  76729. current = & (owner.rects.getReference (index));
  76730. return true;
  76731. }
  76732. return false;
  76733. }
  76734. void RectangleList::add (const Rectangle<int>& rect)
  76735. {
  76736. if (! rect.isEmpty())
  76737. {
  76738. if (rects.size() == 0)
  76739. {
  76740. rects.add (rect);
  76741. }
  76742. else
  76743. {
  76744. bool anyOverlaps = false;
  76745. int i;
  76746. for (i = rects.size(); --i >= 0;)
  76747. {
  76748. Rectangle<int>& ourRect = rects.getReference (i);
  76749. if (rect.intersects (ourRect))
  76750. {
  76751. if (rect.contains (ourRect))
  76752. rects.remove (i);
  76753. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  76754. anyOverlaps = true;
  76755. }
  76756. }
  76757. if (anyOverlaps && rects.size() > 0)
  76758. {
  76759. RectangleList r (rect);
  76760. for (i = rects.size(); --i >= 0;)
  76761. {
  76762. const Rectangle<int>& ourRect = rects.getReference (i);
  76763. if (rect.intersects (ourRect))
  76764. {
  76765. r.subtract (ourRect);
  76766. if (r.rects.size() == 0)
  76767. return;
  76768. }
  76769. }
  76770. for (i = r.getNumRectangles(); --i >= 0;)
  76771. rects.add (r.rects.getReference (i));
  76772. }
  76773. else
  76774. {
  76775. rects.add (rect);
  76776. }
  76777. }
  76778. }
  76779. }
  76780. void RectangleList::addWithoutMerging (const Rectangle<int>& rect)
  76781. {
  76782. if (! rect.isEmpty())
  76783. rects.add (rect);
  76784. }
  76785. void RectangleList::add (const int x, const int y, const int w, const int h)
  76786. {
  76787. if (rects.size() == 0)
  76788. {
  76789. if (w > 0 && h > 0)
  76790. rects.add (Rectangle<int> (x, y, w, h));
  76791. }
  76792. else
  76793. {
  76794. add (Rectangle<int> (x, y, w, h));
  76795. }
  76796. }
  76797. void RectangleList::add (const RectangleList& other)
  76798. {
  76799. for (int i = 0; i < other.rects.size(); ++i)
  76800. add (other.rects.getReference (i));
  76801. }
  76802. void RectangleList::subtract (const Rectangle<int>& rect)
  76803. {
  76804. const int originalNumRects = rects.size();
  76805. if (originalNumRects > 0)
  76806. {
  76807. const int x1 = rect.x;
  76808. const int y1 = rect.y;
  76809. const int x2 = x1 + rect.w;
  76810. const int y2 = y1 + rect.h;
  76811. for (int i = getNumRectangles(); --i >= 0;)
  76812. {
  76813. Rectangle<int>& r = rects.getReference (i);
  76814. const int rx1 = r.x;
  76815. const int ry1 = r.y;
  76816. const int rx2 = rx1 + r.w;
  76817. const int ry2 = ry1 + r.h;
  76818. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  76819. {
  76820. if (x1 > rx1 && x1 < rx2)
  76821. {
  76822. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  76823. {
  76824. r.w = x1 - rx1;
  76825. }
  76826. else
  76827. {
  76828. r.x = x1;
  76829. r.w = rx2 - x1;
  76830. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x1 - rx1, ry2 - ry1));
  76831. i += 2;
  76832. }
  76833. }
  76834. else if (x2 > rx1 && x2 < rx2)
  76835. {
  76836. r.x = x2;
  76837. r.w = rx2 - x2;
  76838. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  76839. {
  76840. rects.insert (i + 1, Rectangle<int> (rx1, ry1, x2 - rx1, ry2 - ry1));
  76841. i += 2;
  76842. }
  76843. }
  76844. else if (y1 > ry1 && y1 < ry2)
  76845. {
  76846. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  76847. {
  76848. r.h = y1 - ry1;
  76849. }
  76850. else
  76851. {
  76852. r.y = y1;
  76853. r.h = ry2 - y1;
  76854. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y1 - ry1));
  76855. i += 2;
  76856. }
  76857. }
  76858. else if (y2 > ry1 && y2 < ry2)
  76859. {
  76860. r.y = y2;
  76861. r.h = ry2 - y2;
  76862. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  76863. {
  76864. rects.insert (i + 1, Rectangle<int> (rx1, ry1, rx2 - rx1, y2 - ry1));
  76865. i += 2;
  76866. }
  76867. }
  76868. else
  76869. {
  76870. rects.remove (i);
  76871. }
  76872. }
  76873. }
  76874. }
  76875. }
  76876. bool RectangleList::subtract (const RectangleList& otherList)
  76877. {
  76878. for (int i = otherList.rects.size(); --i >= 0 && rects.size() > 0;)
  76879. subtract (otherList.rects.getReference (i));
  76880. return rects.size() > 0;
  76881. }
  76882. bool RectangleList::clipTo (const Rectangle<int>& rect)
  76883. {
  76884. bool notEmpty = false;
  76885. if (rect.isEmpty())
  76886. {
  76887. clear();
  76888. }
  76889. else
  76890. {
  76891. for (int i = rects.size(); --i >= 0;)
  76892. {
  76893. Rectangle<int>& r = rects.getReference (i);
  76894. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76895. rects.remove (i);
  76896. else
  76897. notEmpty = true;
  76898. }
  76899. }
  76900. return notEmpty;
  76901. }
  76902. bool RectangleList::clipTo (const RectangleList& other)
  76903. {
  76904. if (rects.size() == 0)
  76905. return false;
  76906. RectangleList result;
  76907. for (int j = 0; j < rects.size(); ++j)
  76908. {
  76909. const Rectangle<int>& rect = rects.getReference (j);
  76910. for (int i = other.rects.size(); --i >= 0;)
  76911. {
  76912. Rectangle<int> r (other.rects.getReference (i));
  76913. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76914. result.rects.add (r);
  76915. }
  76916. }
  76917. swapWith (result);
  76918. return ! isEmpty();
  76919. }
  76920. bool RectangleList::getIntersectionWith (const Rectangle<int>& rect, RectangleList& destRegion) const
  76921. {
  76922. destRegion.clear();
  76923. if (! rect.isEmpty())
  76924. {
  76925. for (int i = rects.size(); --i >= 0;)
  76926. {
  76927. Rectangle<int> r (rects.getReference (i));
  76928. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  76929. destRegion.rects.add (r);
  76930. }
  76931. }
  76932. return destRegion.rects.size() > 0;
  76933. }
  76934. void RectangleList::swapWith (RectangleList& otherList) throw()
  76935. {
  76936. rects.swapWithArray (otherList.rects);
  76937. }
  76938. void RectangleList::consolidate()
  76939. {
  76940. int i;
  76941. for (i = 0; i < getNumRectangles() - 1; ++i)
  76942. {
  76943. Rectangle<int>& r = rects.getReference (i);
  76944. const int rx1 = r.x;
  76945. const int ry1 = r.y;
  76946. const int rx2 = rx1 + r.w;
  76947. const int ry2 = ry1 + r.h;
  76948. for (int j = rects.size(); --j > i;)
  76949. {
  76950. Rectangle<int>& r2 = rects.getReference (j);
  76951. const int jrx1 = r2.x;
  76952. const int jry1 = r2.y;
  76953. const int jrx2 = jrx1 + r2.w;
  76954. const int jry2 = jry1 + r2.h;
  76955. // if the vertical edges of any blocks are touching and their horizontals don't
  76956. // line up, split them horizontally..
  76957. if (jrx1 == rx2 || jrx2 == rx1)
  76958. {
  76959. if (jry1 > ry1 && jry1 < ry2)
  76960. {
  76961. r.h = jry1 - ry1;
  76962. rects.add (Rectangle<int> (rx1, jry1, rx2 - rx1, ry2 - jry1));
  76963. i = -1;
  76964. break;
  76965. }
  76966. if (jry2 > ry1 && jry2 < ry2)
  76967. {
  76968. r.h = jry2 - ry1;
  76969. rects.add (Rectangle<int> (rx1, jry2, rx2 - rx1, ry2 - jry2));
  76970. i = -1;
  76971. break;
  76972. }
  76973. else if (ry1 > jry1 && ry1 < jry2)
  76974. {
  76975. r2.h = ry1 - jry1;
  76976. rects.add (Rectangle<int> (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  76977. i = -1;
  76978. break;
  76979. }
  76980. else if (ry2 > jry1 && ry2 < jry2)
  76981. {
  76982. r2.h = ry2 - jry1;
  76983. rects.add (Rectangle<int> (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  76984. i = -1;
  76985. break;
  76986. }
  76987. }
  76988. }
  76989. }
  76990. for (i = 0; i < rects.size() - 1; ++i)
  76991. {
  76992. Rectangle<int>& r = rects.getReference (i);
  76993. for (int j = rects.size(); --j > i;)
  76994. {
  76995. if (r.enlargeIfAdjacent (rects.getReference (j)))
  76996. {
  76997. rects.remove (j);
  76998. i = -1;
  76999. break;
  77000. }
  77001. }
  77002. }
  77003. }
  77004. bool RectangleList::containsPoint (const int x, const int y) const throw()
  77005. {
  77006. for (int i = getNumRectangles(); --i >= 0;)
  77007. if (rects.getReference (i).contains (x, y))
  77008. return true;
  77009. return false;
  77010. }
  77011. bool RectangleList::containsRectangle (const Rectangle<int>& rectangleToCheck) const
  77012. {
  77013. if (rects.size() > 1)
  77014. {
  77015. RectangleList r (rectangleToCheck);
  77016. for (int i = rects.size(); --i >= 0;)
  77017. {
  77018. r.subtract (rects.getReference (i));
  77019. if (r.rects.size() == 0)
  77020. return true;
  77021. }
  77022. }
  77023. else if (rects.size() > 0)
  77024. {
  77025. return rects.getReference (0).contains (rectangleToCheck);
  77026. }
  77027. return false;
  77028. }
  77029. bool RectangleList::intersectsRectangle (const Rectangle<int>& rectangleToCheck) const throw()
  77030. {
  77031. for (int i = rects.size(); --i >= 0;)
  77032. if (rects.getReference (i).intersects (rectangleToCheck))
  77033. return true;
  77034. return false;
  77035. }
  77036. bool RectangleList::intersects (const RectangleList& other) const throw()
  77037. {
  77038. for (int i = rects.size(); --i >= 0;)
  77039. if (other.intersectsRectangle (rects.getReference (i)))
  77040. return true;
  77041. return false;
  77042. }
  77043. const Rectangle<int> RectangleList::getBounds() const throw()
  77044. {
  77045. if (rects.size() <= 1)
  77046. {
  77047. if (rects.size() == 0)
  77048. return Rectangle<int>();
  77049. else
  77050. return rects.getReference (0);
  77051. }
  77052. else
  77053. {
  77054. const Rectangle<int>& r = rects.getReference (0);
  77055. int minX = r.x;
  77056. int minY = r.y;
  77057. int maxX = minX + r.w;
  77058. int maxY = minY + r.h;
  77059. for (int i = rects.size(); --i > 0;)
  77060. {
  77061. const Rectangle<int>& r2 = rects.getReference (i);
  77062. minX = jmin (minX, r2.x);
  77063. minY = jmin (minY, r2.y);
  77064. maxX = jmax (maxX, r2.getRight());
  77065. maxY = jmax (maxY, r2.getBottom());
  77066. }
  77067. return Rectangle<int> (minX, minY, maxX - minX, maxY - minY);
  77068. }
  77069. }
  77070. void RectangleList::offsetAll (const int dx, const int dy) throw()
  77071. {
  77072. for (int i = rects.size(); --i >= 0;)
  77073. {
  77074. Rectangle<int>& r = rects.getReference (i);
  77075. r.x += dx;
  77076. r.y += dy;
  77077. }
  77078. }
  77079. const Path RectangleList::toPath() const
  77080. {
  77081. Path p;
  77082. for (int i = rects.size(); --i >= 0;)
  77083. {
  77084. const Rectangle<int>& r = rects.getReference (i);
  77085. p.addRectangle ((float) r.x,
  77086. (float) r.y,
  77087. (float) r.w,
  77088. (float) r.h);
  77089. }
  77090. return p;
  77091. }
  77092. END_JUCE_NAMESPACE
  77093. /*** End of inlined file: juce_RectangleList.cpp ***/
  77094. /*** Start of inlined file: juce_Image.cpp ***/
  77095. BEGIN_JUCE_NAMESPACE
  77096. Image::SharedImage::SharedImage (const PixelFormat format_, const int width_, const int height_)
  77097. : format (format_), width (width_), height (height_)
  77098. {
  77099. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  77100. jassert (width > 0 && height > 0); // It's illegal to create a zero-sized image!
  77101. }
  77102. Image::SharedImage::~SharedImage()
  77103. {
  77104. }
  77105. inline uint8* Image::SharedImage::getPixelData (const int x, const int y) const throw()
  77106. {
  77107. return imageData + lineStride * y + pixelStride * x;
  77108. }
  77109. class SoftwareSharedImage : public Image::SharedImage
  77110. {
  77111. public:
  77112. SoftwareSharedImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  77113. : Image::SharedImage (format_, width_, height_)
  77114. {
  77115. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  77116. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  77117. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  77118. imageData = imageDataAllocated;
  77119. }
  77120. ~SoftwareSharedImage()
  77121. {
  77122. }
  77123. Image::ImageType getType() const
  77124. {
  77125. return Image::SoftwareImage;
  77126. }
  77127. LowLevelGraphicsContext* createLowLevelContext()
  77128. {
  77129. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  77130. }
  77131. SharedImage* clone()
  77132. {
  77133. SoftwareSharedImage* s = new SoftwareSharedImage (format, width, height, false);
  77134. memcpy (s->imageData, imageData, lineStride * height);
  77135. return s;
  77136. }
  77137. private:
  77138. HeapBlock<uint8> imageDataAllocated;
  77139. };
  77140. Image::SharedImage* Image::SharedImage::createSoftwareImage (Image::PixelFormat format, int width, int height, bool clearImage)
  77141. {
  77142. return new SoftwareSharedImage (format, width, height, clearImage);
  77143. }
  77144. class SubsectionSharedImage : public Image::SharedImage
  77145. {
  77146. public:
  77147. SubsectionSharedImage (Image::SharedImage* const image_, const Rectangle<int>& area_)
  77148. : Image::SharedImage (image_->getPixelFormat(), area_.getWidth(), area_.getHeight()),
  77149. image (image_), area (area_)
  77150. {
  77151. pixelStride = image_->getPixelStride();
  77152. lineStride = image_->getLineStride();
  77153. imageData = image_->getPixelData (area_.getX(), area_.getY());
  77154. }
  77155. ~SubsectionSharedImage() {}
  77156. Image::ImageType getType() const
  77157. {
  77158. return Image::SoftwareImage;
  77159. }
  77160. LowLevelGraphicsContext* createLowLevelContext()
  77161. {
  77162. LowLevelGraphicsContext* g = image->createLowLevelContext();
  77163. g->clipToRectangle (area);
  77164. g->setOrigin (area.getX(), area.getY());
  77165. return g;
  77166. }
  77167. SharedImage* clone()
  77168. {
  77169. return new SubsectionSharedImage (image->clone(), area);
  77170. }
  77171. private:
  77172. const ReferenceCountedObjectPtr<Image::SharedImage> image;
  77173. const Rectangle<int> area;
  77174. SubsectionSharedImage (const SubsectionSharedImage&);
  77175. SubsectionSharedImage& operator= (const SubsectionSharedImage&);
  77176. };
  77177. const Image Image::getClippedImage (const Rectangle<int>& area) const
  77178. {
  77179. if (area.contains (getBounds()))
  77180. return *this;
  77181. const Rectangle<int> validArea (area.getIntersection (getBounds()));
  77182. if (validArea.isEmpty())
  77183. return Image::null;
  77184. return Image (new SubsectionSharedImage (image, validArea));
  77185. }
  77186. Image::Image()
  77187. {
  77188. }
  77189. Image::Image (SharedImage* const instance)
  77190. : image (instance)
  77191. {
  77192. }
  77193. Image::Image (const PixelFormat format,
  77194. const int width, const int height,
  77195. const bool clearImage, const ImageType type)
  77196. : image (type == Image::NativeImage ? SharedImage::createNativeImage (format, width, height, clearImage)
  77197. : new SoftwareSharedImage (format, width, height, clearImage))
  77198. {
  77199. }
  77200. Image::Image (const Image& other)
  77201. : image (other.image)
  77202. {
  77203. }
  77204. Image& Image::operator= (const Image& other)
  77205. {
  77206. image = other.image;
  77207. return *this;
  77208. }
  77209. Image::~Image()
  77210. {
  77211. }
  77212. const Image Image::null;
  77213. LowLevelGraphicsContext* Image::createLowLevelContext() const
  77214. {
  77215. return image == 0 ? 0 : image->createLowLevelContext();
  77216. }
  77217. void Image::duplicateIfShared()
  77218. {
  77219. if (image != 0 && image->getReferenceCount() > 1)
  77220. image = image->clone();
  77221. }
  77222. const Image Image::rescaled (const int newWidth, const int newHeight, const Graphics::ResamplingQuality quality) const
  77223. {
  77224. if (image == 0 || (image->width == newWidth && image->height == newHeight))
  77225. return *this;
  77226. Image newImage (image->format, newWidth, newHeight, hasAlphaChannel(), image->getType());
  77227. Graphics g (newImage);
  77228. g.setImageResamplingQuality (quality);
  77229. g.drawImage (*this, 0, 0, newWidth, newHeight, 0, 0, image->width, image->height, false);
  77230. return newImage;
  77231. }
  77232. const Image Image::convertedToFormat (PixelFormat newFormat) const
  77233. {
  77234. if (image == 0 || newFormat == image->format)
  77235. return *this;
  77236. Image newImage (newFormat, image->width, image->height, false, image->getType());
  77237. if (newFormat == SingleChannel)
  77238. {
  77239. if (! hasAlphaChannel())
  77240. {
  77241. newImage.clear (getBounds(), Colours::black);
  77242. }
  77243. else
  77244. {
  77245. const BitmapData destData (newImage, 0, 0, image->width, image->height, true);
  77246. const BitmapData srcData (*this, 0, 0, image->width, image->height);
  77247. for (int y = 0; y < image->height; ++y)
  77248. {
  77249. const PixelARGB* src = (const PixelARGB*) srcData.getLinePointer(y);
  77250. uint8* dst = destData.getLinePointer (y);
  77251. for (int x = image->width; --x >= 0;)
  77252. {
  77253. *dst++ = src->getAlpha();
  77254. ++src;
  77255. }
  77256. }
  77257. }
  77258. }
  77259. else
  77260. {
  77261. if (hasAlphaChannel())
  77262. newImage.clear (getBounds());
  77263. Graphics g (newImage);
  77264. g.drawImageAt (*this, 0, 0);
  77265. }
  77266. return newImage;
  77267. }
  77268. NamedValueSet* Image::getProperties() const
  77269. {
  77270. return image == 0 ? 0 : &(image->userData);
  77271. }
  77272. Image::BitmapData::BitmapData (Image& image, const int x, const int y, const int w, const int h, const bool /*makeWritable*/)
  77273. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77274. pixelFormat (image.getFormat()),
  77275. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77276. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77277. width (w),
  77278. height (h)
  77279. {
  77280. jassert (data != 0);
  77281. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77282. }
  77283. Image::BitmapData::BitmapData (const Image& image, const int x, const int y, const int w, const int h)
  77284. : data (image.image == 0 ? 0 : image.image->getPixelData (x, y)),
  77285. pixelFormat (image.getFormat()),
  77286. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77287. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77288. width (w),
  77289. height (h)
  77290. {
  77291. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= image.getWidth() && y + h <= image.getHeight());
  77292. }
  77293. Image::BitmapData::BitmapData (const Image& image, bool /*needsToBeWritable*/)
  77294. : data (image.image == 0 ? 0 : image.image->imageData),
  77295. pixelFormat (image.getFormat()),
  77296. lineStride (image.image == 0 ? 0 : image.image->lineStride),
  77297. pixelStride (image.image == 0 ? 0 : image.image->pixelStride),
  77298. width (image.getWidth()),
  77299. height (image.getHeight())
  77300. {
  77301. }
  77302. Image::BitmapData::~BitmapData()
  77303. {
  77304. }
  77305. const Colour Image::BitmapData::getPixelColour (const int x, const int y) const throw()
  77306. {
  77307. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77308. const uint8* const pixel = getPixelPointer (x, y);
  77309. switch (pixelFormat)
  77310. {
  77311. case Image::ARGB:
  77312. {
  77313. PixelARGB p (*(const PixelARGB*) pixel);
  77314. p.unpremultiply();
  77315. return Colour (p.getARGB());
  77316. }
  77317. case Image::RGB:
  77318. return Colour (((const PixelRGB*) pixel)->getARGB());
  77319. case Image::SingleChannel:
  77320. return Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixel);
  77321. default:
  77322. jassertfalse;
  77323. break;
  77324. }
  77325. return Colour();
  77326. }
  77327. void Image::BitmapData::setPixelColour (const int x, const int y, const Colour& colour) const throw()
  77328. {
  77329. jassert (((unsigned int) x) < (unsigned int) width && ((unsigned int) y) < (unsigned int) height);
  77330. uint8* const pixel = getPixelPointer (x, y);
  77331. const PixelARGB col (colour.getPixelARGB());
  77332. switch (pixelFormat)
  77333. {
  77334. case Image::ARGB: ((PixelARGB*) pixel)->set (col); break;
  77335. case Image::RGB: ((PixelRGB*) pixel)->set (col); break;
  77336. case Image::SingleChannel: *pixel = col.getAlpha(); break;
  77337. default: jassertfalse; break;
  77338. }
  77339. }
  77340. void Image::setPixelData (int x, int y, int w, int h,
  77341. const uint8* const sourcePixelData, const int sourceLineStride)
  77342. {
  77343. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= getWidth() && y + h <= getHeight());
  77344. if (Rectangle<int>::intersectRectangles (x, y, w, h, 0, 0, getWidth(), getHeight()))
  77345. {
  77346. const BitmapData dest (*this, x, y, w, h, true);
  77347. for (int i = 0; i < h; ++i)
  77348. {
  77349. memcpy (dest.getLinePointer(i),
  77350. sourcePixelData + sourceLineStride * i,
  77351. w * dest.pixelStride);
  77352. }
  77353. }
  77354. }
  77355. void Image::clear (const Rectangle<int>& area, const Colour& colourToClearTo)
  77356. {
  77357. const Rectangle<int> clipped (area.getIntersection (getBounds()));
  77358. if (! clipped.isEmpty())
  77359. {
  77360. const PixelARGB col (colourToClearTo.getPixelARGB());
  77361. const BitmapData destData (*this, clipped.getX(), clipped.getY(), clipped.getWidth(), clipped.getHeight(), true);
  77362. uint8* dest = destData.data;
  77363. int dh = clipped.getHeight();
  77364. while (--dh >= 0)
  77365. {
  77366. uint8* line = dest;
  77367. dest += destData.lineStride;
  77368. if (isARGB())
  77369. {
  77370. for (int x = clipped.getWidth(); --x >= 0;)
  77371. {
  77372. ((PixelARGB*) line)->set (col);
  77373. line += destData.pixelStride;
  77374. }
  77375. }
  77376. else if (isRGB())
  77377. {
  77378. for (int x = clipped.getWidth(); --x >= 0;)
  77379. {
  77380. ((PixelRGB*) line)->set (col);
  77381. line += destData.pixelStride;
  77382. }
  77383. }
  77384. else
  77385. {
  77386. for (int x = clipped.getWidth(); --x >= 0;)
  77387. {
  77388. *line = col.getAlpha();
  77389. line += destData.pixelStride;
  77390. }
  77391. }
  77392. }
  77393. }
  77394. }
  77395. const Colour Image::getPixelAt (const int x, const int y) const
  77396. {
  77397. if (((unsigned int) x) < (unsigned int) getWidth()
  77398. && ((unsigned int) y) < (unsigned int) getHeight())
  77399. {
  77400. const BitmapData srcData (*this, x, y, 1, 1);
  77401. return srcData.getPixelColour (0, 0);
  77402. }
  77403. return Colour();
  77404. }
  77405. void Image::setPixelAt (const int x, const int y, const Colour& colour)
  77406. {
  77407. if (((unsigned int) x) < (unsigned int) getWidth()
  77408. && ((unsigned int) y) < (unsigned int) getHeight())
  77409. {
  77410. const BitmapData destData (*this, x, y, 1, 1, true);
  77411. destData.setPixelColour (0, 0, colour);
  77412. }
  77413. }
  77414. void Image::multiplyAlphaAt (const int x, const int y, const float multiplier)
  77415. {
  77416. if (((unsigned int) x) < (unsigned int) getWidth()
  77417. && ((unsigned int) y) < (unsigned int) getHeight()
  77418. && hasAlphaChannel())
  77419. {
  77420. const BitmapData destData (*this, x, y, 1, 1, true);
  77421. if (isARGB())
  77422. ((PixelARGB*) destData.data)->multiplyAlpha (multiplier);
  77423. else
  77424. *(destData.data) = (uint8) (*(destData.data) * multiplier);
  77425. }
  77426. }
  77427. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  77428. {
  77429. if (hasAlphaChannel())
  77430. {
  77431. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77432. if (isARGB())
  77433. {
  77434. for (int y = 0; y < destData.height; ++y)
  77435. {
  77436. uint8* p = destData.getLinePointer (y);
  77437. for (int x = 0; x < destData.width; ++x)
  77438. {
  77439. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  77440. p += destData.pixelStride;
  77441. }
  77442. }
  77443. }
  77444. else
  77445. {
  77446. for (int y = 0; y < destData.height; ++y)
  77447. {
  77448. uint8* p = destData.getLinePointer (y);
  77449. for (int x = 0; x < destData.width; ++x)
  77450. {
  77451. *p = (uint8) (*p * amountToMultiplyBy);
  77452. p += destData.pixelStride;
  77453. }
  77454. }
  77455. }
  77456. }
  77457. else
  77458. {
  77459. jassertfalse; // can't do this without an alpha-channel!
  77460. }
  77461. }
  77462. void Image::desaturate()
  77463. {
  77464. if (isARGB() || isRGB())
  77465. {
  77466. const BitmapData destData (*this, 0, 0, getWidth(), getHeight(), true);
  77467. if (isARGB())
  77468. {
  77469. for (int y = 0; y < destData.height; ++y)
  77470. {
  77471. uint8* p = destData.getLinePointer (y);
  77472. for (int x = 0; x < destData.width; ++x)
  77473. {
  77474. ((PixelARGB*) p)->desaturate();
  77475. p += destData.pixelStride;
  77476. }
  77477. }
  77478. }
  77479. else
  77480. {
  77481. for (int y = 0; y < destData.height; ++y)
  77482. {
  77483. uint8* p = destData.getLinePointer (y);
  77484. for (int x = 0; x < destData.width; ++x)
  77485. {
  77486. ((PixelRGB*) p)->desaturate();
  77487. p += destData.pixelStride;
  77488. }
  77489. }
  77490. }
  77491. }
  77492. }
  77493. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  77494. {
  77495. if (hasAlphaChannel())
  77496. {
  77497. const uint8 threshold = (uint8) jlimit (0, 255, roundToInt (alphaThreshold * 255.0f));
  77498. SparseSet<int> pixelsOnRow;
  77499. const BitmapData srcData (*this, 0, 0, getWidth(), getHeight());
  77500. for (int y = 0; y < srcData.height; ++y)
  77501. {
  77502. pixelsOnRow.clear();
  77503. const uint8* lineData = srcData.getLinePointer (y);
  77504. if (isARGB())
  77505. {
  77506. for (int x = 0; x < srcData.width; ++x)
  77507. {
  77508. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  77509. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77510. lineData += srcData.pixelStride;
  77511. }
  77512. }
  77513. else
  77514. {
  77515. for (int x = 0; x < srcData.width; ++x)
  77516. {
  77517. if (*lineData >= threshold)
  77518. pixelsOnRow.addRange (Range<int> (x, x + 1));
  77519. lineData += srcData.pixelStride;
  77520. }
  77521. }
  77522. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  77523. {
  77524. const Range<int> range (pixelsOnRow.getRange (i));
  77525. result.add (Rectangle<int> (range.getStart(), y, range.getLength(), 1));
  77526. }
  77527. result.consolidate();
  77528. }
  77529. }
  77530. else
  77531. {
  77532. result.add (0, 0, getWidth(), getHeight());
  77533. }
  77534. }
  77535. void Image::moveImageSection (int dx, int dy,
  77536. int sx, int sy,
  77537. int w, int h)
  77538. {
  77539. if (dx < 0)
  77540. {
  77541. w += dx;
  77542. sx -= dx;
  77543. dx = 0;
  77544. }
  77545. if (dy < 0)
  77546. {
  77547. h += dy;
  77548. sy -= dy;
  77549. dy = 0;
  77550. }
  77551. if (sx < 0)
  77552. {
  77553. w += sx;
  77554. dx -= sx;
  77555. sx = 0;
  77556. }
  77557. if (sy < 0)
  77558. {
  77559. h += sy;
  77560. dy -= sy;
  77561. sy = 0;
  77562. }
  77563. const int minX = jmin (dx, sx);
  77564. const int minY = jmin (dy, sy);
  77565. w = jmin (w, getWidth() - jmax (sx, dx));
  77566. h = jmin (h, getHeight() - jmax (sy, dy));
  77567. if (w > 0 && h > 0)
  77568. {
  77569. const int maxX = jmax (dx, sx) + w;
  77570. const int maxY = jmax (dy, sy) + h;
  77571. const BitmapData destData (*this, minX, minY, maxX - minX, maxY - minY, true);
  77572. uint8* dst = destData.getPixelPointer (dx - minX, dy - minY);
  77573. const uint8* src = destData.getPixelPointer (sx - minX, sy - minY);
  77574. const int lineSize = destData.pixelStride * w;
  77575. if (dy > sy)
  77576. {
  77577. while (--h >= 0)
  77578. {
  77579. const int offset = h * destData.lineStride;
  77580. memmove (dst + offset, src + offset, lineSize);
  77581. }
  77582. }
  77583. else if (dst != src)
  77584. {
  77585. while (--h >= 0)
  77586. {
  77587. memmove (dst, src, lineSize);
  77588. dst += destData.lineStride;
  77589. src += destData.lineStride;
  77590. }
  77591. }
  77592. }
  77593. }
  77594. END_JUCE_NAMESPACE
  77595. /*** End of inlined file: juce_Image.cpp ***/
  77596. /*** Start of inlined file: juce_ImageCache.cpp ***/
  77597. BEGIN_JUCE_NAMESPACE
  77598. class ImageCache::Pimpl : public Timer,
  77599. public DeletedAtShutdown
  77600. {
  77601. public:
  77602. Pimpl()
  77603. : cacheTimeout (5000)
  77604. {
  77605. }
  77606. ~Pimpl()
  77607. {
  77608. clearSingletonInstance();
  77609. }
  77610. const Image getFromHashCode (const int64 hashCode)
  77611. {
  77612. const ScopedLock sl (lock);
  77613. for (int i = images.size(); --i >= 0;)
  77614. {
  77615. Item* const item = images.getUnchecked(i);
  77616. if (item->hashCode == hashCode)
  77617. return item->image;
  77618. }
  77619. return Image::null;
  77620. }
  77621. void addImageToCache (const Image& image, const int64 hashCode)
  77622. {
  77623. if (image.isValid())
  77624. {
  77625. if (! isTimerRunning())
  77626. startTimer (2000);
  77627. Item* const item = new Item();
  77628. item->hashCode = hashCode;
  77629. item->image = image;
  77630. item->lastUseTime = Time::getApproximateMillisecondCounter();
  77631. const ScopedLock sl (lock);
  77632. images.add (item);
  77633. }
  77634. }
  77635. void timerCallback()
  77636. {
  77637. const uint32 now = Time::getApproximateMillisecondCounter();
  77638. const ScopedLock sl (lock);
  77639. for (int i = images.size(); --i >= 0;)
  77640. {
  77641. Item* const item = images.getUnchecked(i);
  77642. if (item->image.getReferenceCount() <= 1)
  77643. {
  77644. if (now > item->lastUseTime + cacheTimeout || now < item->lastUseTime - 1000)
  77645. images.remove (i);
  77646. }
  77647. else
  77648. {
  77649. item->lastUseTime = now; // multiply-referenced, so this image is still in use.
  77650. }
  77651. }
  77652. if (images.size() == 0)
  77653. stopTimer();
  77654. }
  77655. struct Item
  77656. {
  77657. Image image;
  77658. int64 hashCode;
  77659. uint32 lastUseTime;
  77660. };
  77661. int cacheTimeout;
  77662. juce_DeclareSingleton_SingleThreaded_Minimal (ImageCache::Pimpl);
  77663. private:
  77664. OwnedArray<Item> images;
  77665. CriticalSection lock;
  77666. Pimpl (const Pimpl&);
  77667. Pimpl& operator= (const Pimpl&);
  77668. };
  77669. juce_ImplementSingleton_SingleThreaded (ImageCache::Pimpl);
  77670. const Image ImageCache::getFromHashCode (const int64 hashCode)
  77671. {
  77672. if (Pimpl::getInstanceWithoutCreating() != 0)
  77673. return Pimpl::getInstanceWithoutCreating()->getFromHashCode (hashCode);
  77674. return Image::null;
  77675. }
  77676. void ImageCache::addImageToCache (const Image& image, const int64 hashCode)
  77677. {
  77678. Pimpl::getInstance()->addImageToCache (image, hashCode);
  77679. }
  77680. const Image ImageCache::getFromFile (const File& file)
  77681. {
  77682. const int64 hashCode = file.hashCode64();
  77683. Image image (getFromHashCode (hashCode));
  77684. if (image.isNull())
  77685. {
  77686. image = ImageFileFormat::loadFrom (file);
  77687. addImageToCache (image, hashCode);
  77688. }
  77689. return image;
  77690. }
  77691. const Image ImageCache::getFromMemory (const void* imageData, const int dataSize)
  77692. {
  77693. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  77694. Image image (getFromHashCode (hashCode));
  77695. if (image.isNull())
  77696. {
  77697. image = ImageFileFormat::loadFrom (imageData, dataSize);
  77698. addImageToCache (image, hashCode);
  77699. }
  77700. return image;
  77701. }
  77702. void ImageCache::setCacheTimeout (const int millisecs)
  77703. {
  77704. Pimpl::getInstance()->cacheTimeout = millisecs;
  77705. }
  77706. END_JUCE_NAMESPACE
  77707. /*** End of inlined file: juce_ImageCache.cpp ***/
  77708. /*** Start of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77709. BEGIN_JUCE_NAMESPACE
  77710. ImageConvolutionKernel::ImageConvolutionKernel (const int size_)
  77711. : values (size_ * size_),
  77712. size (size_)
  77713. {
  77714. clear();
  77715. }
  77716. ImageConvolutionKernel::~ImageConvolutionKernel()
  77717. {
  77718. }
  77719. float ImageConvolutionKernel::getKernelValue (const int x, const int y) const throw()
  77720. {
  77721. if (((unsigned int) x) < (unsigned int) size
  77722. && ((unsigned int) y) < (unsigned int) size)
  77723. {
  77724. return values [x + y * size];
  77725. }
  77726. else
  77727. {
  77728. jassertfalse;
  77729. return 0;
  77730. }
  77731. }
  77732. void ImageConvolutionKernel::setKernelValue (const int x, const int y, const float value) throw()
  77733. {
  77734. if (((unsigned int) x) < (unsigned int) size
  77735. && ((unsigned int) y) < (unsigned int) size)
  77736. {
  77737. values [x + y * size] = value;
  77738. }
  77739. else
  77740. {
  77741. jassertfalse;
  77742. }
  77743. }
  77744. void ImageConvolutionKernel::clear()
  77745. {
  77746. for (int i = size * size; --i >= 0;)
  77747. values[i] = 0;
  77748. }
  77749. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum)
  77750. {
  77751. double currentTotal = 0.0;
  77752. for (int i = size * size; --i >= 0;)
  77753. currentTotal += values[i];
  77754. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  77755. }
  77756. void ImageConvolutionKernel::rescaleAllValues (const float multiplier)
  77757. {
  77758. for (int i = size * size; --i >= 0;)
  77759. values[i] *= multiplier;
  77760. }
  77761. void ImageConvolutionKernel::createGaussianBlur (const float radius)
  77762. {
  77763. const double radiusFactor = -1.0 / (radius * radius * 2);
  77764. const int centre = size >> 1;
  77765. for (int y = size; --y >= 0;)
  77766. {
  77767. for (int x = size; --x >= 0;)
  77768. {
  77769. const int cx = x - centre;
  77770. const int cy = y - centre;
  77771. values [x + y * size] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  77772. }
  77773. }
  77774. setOverallSum (1.0f);
  77775. }
  77776. void ImageConvolutionKernel::applyToImage (Image& destImage,
  77777. const Image& sourceImage,
  77778. const Rectangle<int>& destinationArea) const
  77779. {
  77780. if (sourceImage == destImage)
  77781. {
  77782. destImage.duplicateIfShared();
  77783. }
  77784. else
  77785. {
  77786. if (sourceImage.getWidth() != destImage.getWidth()
  77787. || sourceImage.getHeight() != destImage.getHeight()
  77788. || sourceImage.getFormat() != destImage.getFormat())
  77789. {
  77790. jassertfalse;
  77791. return;
  77792. }
  77793. }
  77794. const Rectangle<int> area (destinationArea.getIntersection (destImage.getBounds()));
  77795. if (area.isEmpty())
  77796. return;
  77797. const int right = area.getRight();
  77798. const int bottom = area.getBottom();
  77799. const Image::BitmapData destData (destImage, area.getX(), area.getY(), area.getWidth(), area.getHeight(), true);
  77800. uint8* line = destData.data;
  77801. const Image::BitmapData srcData (sourceImage, false);
  77802. if (destData.pixelStride == 4)
  77803. {
  77804. for (int y = area.getY(); y < bottom; ++y)
  77805. {
  77806. uint8* dest = line;
  77807. line += destData.lineStride;
  77808. for (int x = area.getX(); x < right; ++x)
  77809. {
  77810. float c1 = 0;
  77811. float c2 = 0;
  77812. float c3 = 0;
  77813. float c4 = 0;
  77814. for (int yy = 0; yy < size; ++yy)
  77815. {
  77816. const int sy = y + yy - (size >> 1);
  77817. if (sy >= srcData.height)
  77818. break;
  77819. if (sy >= 0)
  77820. {
  77821. int sx = x - (size >> 1);
  77822. const uint8* src = srcData.getPixelPointer (sx, sy);
  77823. for (int xx = 0; xx < size; ++xx)
  77824. {
  77825. if (sx >= srcData.width)
  77826. break;
  77827. if (sx >= 0)
  77828. {
  77829. const float kernelMult = values [xx + yy * size];
  77830. c1 += kernelMult * *src++;
  77831. c2 += kernelMult * *src++;
  77832. c3 += kernelMult * *src++;
  77833. c4 += kernelMult * *src++;
  77834. }
  77835. else
  77836. {
  77837. src += 4;
  77838. }
  77839. ++sx;
  77840. }
  77841. }
  77842. }
  77843. *dest++ = (uint8) jmin (0xff, roundToInt (c1));
  77844. *dest++ = (uint8) jmin (0xff, roundToInt (c2));
  77845. *dest++ = (uint8) jmin (0xff, roundToInt (c3));
  77846. *dest++ = (uint8) jmin (0xff, roundToInt (c4));
  77847. }
  77848. }
  77849. }
  77850. else if (destData.pixelStride == 3)
  77851. {
  77852. for (int y = area.getY(); y < bottom; ++y)
  77853. {
  77854. uint8* dest = line;
  77855. line += destData.lineStride;
  77856. for (int x = area.getX(); x < right; ++x)
  77857. {
  77858. float c1 = 0;
  77859. float c2 = 0;
  77860. float c3 = 0;
  77861. for (int yy = 0; yy < size; ++yy)
  77862. {
  77863. const int sy = y + yy - (size >> 1);
  77864. if (sy >= srcData.height)
  77865. break;
  77866. if (sy >= 0)
  77867. {
  77868. int sx = x - (size >> 1);
  77869. const uint8* src = srcData.getPixelPointer (sx, sy);
  77870. for (int xx = 0; xx < size; ++xx)
  77871. {
  77872. if (sx >= srcData.width)
  77873. break;
  77874. if (sx >= 0)
  77875. {
  77876. const float kernelMult = values [xx + yy * size];
  77877. c1 += kernelMult * *src++;
  77878. c2 += kernelMult * *src++;
  77879. c3 += kernelMult * *src++;
  77880. }
  77881. else
  77882. {
  77883. src += 3;
  77884. }
  77885. ++sx;
  77886. }
  77887. }
  77888. }
  77889. *dest++ = (uint8) roundToInt (c1);
  77890. *dest++ = (uint8) roundToInt (c2);
  77891. *dest++ = (uint8) roundToInt (c3);
  77892. }
  77893. }
  77894. }
  77895. }
  77896. END_JUCE_NAMESPACE
  77897. /*** End of inlined file: juce_ImageConvolutionKernel.cpp ***/
  77898. /*** Start of inlined file: juce_ImageFileFormat.cpp ***/
  77899. BEGIN_JUCE_NAMESPACE
  77900. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  77901. {
  77902. static PNGImageFormat png;
  77903. static JPEGImageFormat jpg;
  77904. static GIFImageFormat gif;
  77905. ImageFileFormat* formats[4];
  77906. int numFormats = 0;
  77907. formats [numFormats++] = &png;
  77908. formats [numFormats++] = &jpg;
  77909. formats [numFormats++] = &gif;
  77910. const int64 streamPos = input.getPosition();
  77911. for (int i = 0; i < numFormats; ++i)
  77912. {
  77913. const bool found = formats[i]->canUnderstand (input);
  77914. input.setPosition (streamPos);
  77915. if (found)
  77916. return formats[i];
  77917. }
  77918. return 0;
  77919. }
  77920. const Image ImageFileFormat::loadFrom (InputStream& input)
  77921. {
  77922. ImageFileFormat* const format = findImageFormatForStream (input);
  77923. if (format != 0)
  77924. return format->decodeImage (input);
  77925. return Image::null;
  77926. }
  77927. const Image ImageFileFormat::loadFrom (const File& file)
  77928. {
  77929. InputStream* const in = file.createInputStream();
  77930. if (in != 0)
  77931. {
  77932. BufferedInputStream b (in, 8192, true);
  77933. return loadFrom (b);
  77934. }
  77935. return Image::null;
  77936. }
  77937. const Image ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  77938. {
  77939. if (rawData != 0 && numBytes > 4)
  77940. {
  77941. MemoryInputStream stream (rawData, numBytes, false);
  77942. return loadFrom (stream);
  77943. }
  77944. return Image::null;
  77945. }
  77946. END_JUCE_NAMESPACE
  77947. /*** End of inlined file: juce_ImageFileFormat.cpp ***/
  77948. /*** Start of inlined file: juce_GIFLoader.cpp ***/
  77949. BEGIN_JUCE_NAMESPACE
  77950. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  77951. const Image juce_loadWithCoreImage (InputStream& input);
  77952. #else
  77953. class GIFLoader
  77954. {
  77955. public:
  77956. GIFLoader (InputStream& in)
  77957. : input (in),
  77958. dataBlockIsZero (false),
  77959. fresh (false),
  77960. finished (false)
  77961. {
  77962. currentBit = lastBit = lastByteIndex = 0;
  77963. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  77964. firstcode = oldcode = 0;
  77965. clearCode = end_code = 0;
  77966. int imageWidth, imageHeight;
  77967. int transparent = -1;
  77968. if (! getSizeFromHeader (imageWidth, imageHeight))
  77969. return;
  77970. if ((imageWidth <= 0) || (imageHeight <= 0))
  77971. return;
  77972. unsigned char buf [16];
  77973. if (in.read (buf, 3) != 3)
  77974. return;
  77975. int numColours = 2 << (buf[0] & 7);
  77976. if ((buf[0] & 0x80) != 0)
  77977. readPalette (numColours);
  77978. for (;;)
  77979. {
  77980. if (input.read (buf, 1) != 1 || buf[0] == ';')
  77981. break;
  77982. if (buf[0] == '!')
  77983. {
  77984. if (input.read (buf, 1) != 1)
  77985. break;
  77986. if (processExtension (buf[0], transparent) < 0)
  77987. break;
  77988. continue;
  77989. }
  77990. if (buf[0] != ',')
  77991. continue;
  77992. if (input.read (buf, 9) != 9)
  77993. break;
  77994. imageWidth = makeWord (buf[4], buf[5]);
  77995. imageHeight = makeWord (buf[6], buf[7]);
  77996. numColours = 2 << (buf[8] & 7);
  77997. if ((buf[8] & 0x80) != 0)
  77998. if (! readPalette (numColours))
  77999. break;
  78000. image = Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  78001. imageWidth, imageHeight, (transparent >= 0));
  78002. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  78003. readImage ((buf[8] & 0x40) != 0, transparent);
  78004. break;
  78005. }
  78006. }
  78007. ~GIFLoader() {}
  78008. Image image;
  78009. private:
  78010. InputStream& input;
  78011. uint8 buffer [300];
  78012. uint8 palette [256][4];
  78013. bool dataBlockIsZero, fresh, finished;
  78014. int currentBit, lastBit, lastByteIndex;
  78015. int codeSize, setCodeSize;
  78016. int maxCode, maxCodeSize;
  78017. int firstcode, oldcode;
  78018. int clearCode, end_code;
  78019. enum { maxGifCode = 1 << 12 };
  78020. int table [2] [maxGifCode];
  78021. int stack [2 * maxGifCode];
  78022. int *sp;
  78023. bool getSizeFromHeader (int& w, int& h)
  78024. {
  78025. char b[8];
  78026. if (input.read (b, 6) == 6)
  78027. {
  78028. if ((strncmp ("GIF87a", b, 6) == 0)
  78029. || (strncmp ("GIF89a", b, 6) == 0))
  78030. {
  78031. if (input.read (b, 4) == 4)
  78032. {
  78033. w = makeWord (b[0], b[1]);
  78034. h = makeWord (b[2], b[3]);
  78035. return true;
  78036. }
  78037. }
  78038. }
  78039. return false;
  78040. }
  78041. bool readPalette (const int numCols)
  78042. {
  78043. unsigned char rgb[4];
  78044. for (int i = 0; i < numCols; ++i)
  78045. {
  78046. input.read (rgb, 3);
  78047. palette [i][0] = rgb[0];
  78048. palette [i][1] = rgb[1];
  78049. palette [i][2] = rgb[2];
  78050. palette [i][3] = 0xff;
  78051. }
  78052. return true;
  78053. }
  78054. int readDataBlock (unsigned char* dest)
  78055. {
  78056. unsigned char n;
  78057. if (input.read (&n, 1) == 1)
  78058. {
  78059. dataBlockIsZero = (n == 0);
  78060. if (dataBlockIsZero || (input.read (dest, n) == n))
  78061. return n;
  78062. }
  78063. return -1;
  78064. }
  78065. int processExtension (const int type, int& transparent)
  78066. {
  78067. unsigned char b [300];
  78068. int n = 0;
  78069. if (type == 0xf9)
  78070. {
  78071. n = readDataBlock (b);
  78072. if (n < 0)
  78073. return 1;
  78074. if ((b[0] & 0x1) != 0)
  78075. transparent = b[3];
  78076. }
  78077. do
  78078. {
  78079. n = readDataBlock (b);
  78080. }
  78081. while (n > 0);
  78082. return n;
  78083. }
  78084. int readLZWByte (const bool initialise, const int inputCodeSize)
  78085. {
  78086. int code, incode, i;
  78087. if (initialise)
  78088. {
  78089. setCodeSize = inputCodeSize;
  78090. codeSize = setCodeSize + 1;
  78091. clearCode = 1 << setCodeSize;
  78092. end_code = clearCode + 1;
  78093. maxCodeSize = 2 * clearCode;
  78094. maxCode = clearCode + 2;
  78095. getCode (0, true);
  78096. fresh = true;
  78097. for (i = 0; i < clearCode; ++i)
  78098. {
  78099. table[0][i] = 0;
  78100. table[1][i] = i;
  78101. }
  78102. for (; i < maxGifCode; ++i)
  78103. {
  78104. table[0][i] = 0;
  78105. table[1][i] = 0;
  78106. }
  78107. sp = stack;
  78108. return 0;
  78109. }
  78110. else if (fresh)
  78111. {
  78112. fresh = false;
  78113. do
  78114. {
  78115. firstcode = oldcode
  78116. = getCode (codeSize, false);
  78117. }
  78118. while (firstcode == clearCode);
  78119. return firstcode;
  78120. }
  78121. if (sp > stack)
  78122. return *--sp;
  78123. while ((code = getCode (codeSize, false)) >= 0)
  78124. {
  78125. if (code == clearCode)
  78126. {
  78127. for (i = 0; i < clearCode; ++i)
  78128. {
  78129. table[0][i] = 0;
  78130. table[1][i] = i;
  78131. }
  78132. for (; i < maxGifCode; ++i)
  78133. {
  78134. table[0][i] = 0;
  78135. table[1][i] = 0;
  78136. }
  78137. codeSize = setCodeSize + 1;
  78138. maxCodeSize = 2 * clearCode;
  78139. maxCode = clearCode + 2;
  78140. sp = stack;
  78141. firstcode = oldcode = getCode (codeSize, false);
  78142. return firstcode;
  78143. }
  78144. else if (code == end_code)
  78145. {
  78146. if (dataBlockIsZero)
  78147. return -2;
  78148. unsigned char buf [260];
  78149. int n;
  78150. while ((n = readDataBlock (buf)) > 0)
  78151. {}
  78152. if (n != 0)
  78153. return -2;
  78154. }
  78155. incode = code;
  78156. if (code >= maxCode)
  78157. {
  78158. *sp++ = firstcode;
  78159. code = oldcode;
  78160. }
  78161. while (code >= clearCode)
  78162. {
  78163. *sp++ = table[1][code];
  78164. if (code == table[0][code])
  78165. return -2;
  78166. code = table[0][code];
  78167. }
  78168. *sp++ = firstcode = table[1][code];
  78169. if ((code = maxCode) < maxGifCode)
  78170. {
  78171. table[0][code] = oldcode;
  78172. table[1][code] = firstcode;
  78173. ++maxCode;
  78174. if ((maxCode >= maxCodeSize)
  78175. && (maxCodeSize < maxGifCode))
  78176. {
  78177. maxCodeSize <<= 1;
  78178. ++codeSize;
  78179. }
  78180. }
  78181. oldcode = incode;
  78182. if (sp > stack)
  78183. return *--sp;
  78184. }
  78185. return code;
  78186. }
  78187. int getCode (const int codeSize_, const bool initialise)
  78188. {
  78189. if (initialise)
  78190. {
  78191. currentBit = 0;
  78192. lastBit = 0;
  78193. finished = false;
  78194. return 0;
  78195. }
  78196. if ((currentBit + codeSize_) >= lastBit)
  78197. {
  78198. if (finished)
  78199. return -1;
  78200. buffer[0] = buffer [lastByteIndex - 2];
  78201. buffer[1] = buffer [lastByteIndex - 1];
  78202. const int n = readDataBlock (&buffer[2]);
  78203. if (n == 0)
  78204. finished = true;
  78205. lastByteIndex = 2 + n;
  78206. currentBit = (currentBit - lastBit) + 16;
  78207. lastBit = (2 + n) * 8 ;
  78208. }
  78209. int result = 0;
  78210. int i = currentBit;
  78211. for (int j = 0; j < codeSize_; ++j)
  78212. {
  78213. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  78214. ++i;
  78215. }
  78216. currentBit += codeSize_;
  78217. return result;
  78218. }
  78219. bool readImage (const int interlace, const int transparent)
  78220. {
  78221. unsigned char c;
  78222. if (input.read (&c, 1) != 1
  78223. || readLZWByte (true, c) < 0)
  78224. return false;
  78225. if (transparent >= 0)
  78226. {
  78227. palette [transparent][0] = 0;
  78228. palette [transparent][1] = 0;
  78229. palette [transparent][2] = 0;
  78230. palette [transparent][3] = 0;
  78231. }
  78232. int index;
  78233. int xpos = 0, ypos = 0, pass = 0;
  78234. const Image::BitmapData destData (image, true);
  78235. uint8* p = destData.data;
  78236. const bool hasAlpha = image.hasAlphaChannel();
  78237. while ((index = readLZWByte (false, c)) >= 0)
  78238. {
  78239. const uint8* const paletteEntry = palette [index];
  78240. if (hasAlpha)
  78241. {
  78242. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  78243. paletteEntry[0],
  78244. paletteEntry[1],
  78245. paletteEntry[2]);
  78246. ((PixelARGB*) p)->premultiply();
  78247. }
  78248. else
  78249. {
  78250. ((PixelRGB*) p)->setARGB (0,
  78251. paletteEntry[0],
  78252. paletteEntry[1],
  78253. paletteEntry[2]);
  78254. }
  78255. p += destData.pixelStride;
  78256. ++xpos;
  78257. if (xpos == destData.width)
  78258. {
  78259. xpos = 0;
  78260. if (interlace)
  78261. {
  78262. switch (pass)
  78263. {
  78264. case 0:
  78265. case 1: ypos += 8; break;
  78266. case 2: ypos += 4; break;
  78267. case 3: ypos += 2; break;
  78268. }
  78269. while (ypos >= destData.height)
  78270. {
  78271. ++pass;
  78272. switch (pass)
  78273. {
  78274. case 1: ypos = 4; break;
  78275. case 2: ypos = 2; break;
  78276. case 3: ypos = 1; break;
  78277. default: return true;
  78278. }
  78279. }
  78280. }
  78281. else
  78282. {
  78283. ++ypos;
  78284. }
  78285. p = destData.getPixelPointer (xpos, ypos);
  78286. }
  78287. if (ypos >= destData.height)
  78288. break;
  78289. }
  78290. return true;
  78291. }
  78292. static inline int makeWord (const uint8 a, const uint8 b) { return (b << 8) | a; }
  78293. GIFLoader (const GIFLoader&);
  78294. GIFLoader& operator= (const GIFLoader&);
  78295. };
  78296. #endif
  78297. GIFImageFormat::GIFImageFormat() {}
  78298. GIFImageFormat::~GIFImageFormat() {}
  78299. const String GIFImageFormat::getFormatName() { return "GIF"; }
  78300. bool GIFImageFormat::canUnderstand (InputStream& in)
  78301. {
  78302. char header [4];
  78303. return (in.read (header, sizeof (header)) == sizeof (header))
  78304. && header[0] == 'G'
  78305. && header[1] == 'I'
  78306. && header[2] == 'F';
  78307. }
  78308. const Image GIFImageFormat::decodeImage (InputStream& in)
  78309. {
  78310. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  78311. return juce_loadWithCoreImage (in);
  78312. #else
  78313. const ScopedPointer <GIFLoader> loader (new GIFLoader (in));
  78314. return loader->image;
  78315. #endif
  78316. }
  78317. bool GIFImageFormat::writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  78318. {
  78319. jassertfalse; // writing isn't implemented for GIFs!
  78320. return false;
  78321. }
  78322. END_JUCE_NAMESPACE
  78323. /*** End of inlined file: juce_GIFLoader.cpp ***/
  78324. #endif
  78325. //==============================================================================
  78326. // some files include lots of library code, so leave them to the end to avoid cluttering
  78327. // up the build for the clean files.
  78328. #if JUCE_BUILD_CORE
  78329. /*** Start of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  78330. namespace zlibNamespace
  78331. {
  78332. #if JUCE_INCLUDE_ZLIB_CODE
  78333. #undef OS_CODE
  78334. #undef fdopen
  78335. /*** Start of inlined file: zlib.h ***/
  78336. #ifndef ZLIB_H
  78337. #define ZLIB_H
  78338. /*** Start of inlined file: zconf.h ***/
  78339. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  78340. #ifndef ZCONF_H
  78341. #define ZCONF_H
  78342. // *** Just a few hacks here to make it compile nicely with Juce..
  78343. #define Z_PREFIX 1
  78344. #undef __MACTYPES__
  78345. #ifdef _MSC_VER
  78346. #pragma warning (disable : 4131 4127 4244 4267)
  78347. #endif
  78348. /*
  78349. * If you *really* need a unique prefix for all types and library functions,
  78350. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  78351. */
  78352. #ifdef Z_PREFIX
  78353. # define deflateInit_ z_deflateInit_
  78354. # define deflate z_deflate
  78355. # define deflateEnd z_deflateEnd
  78356. # define inflateInit_ z_inflateInit_
  78357. # define inflate z_inflate
  78358. # define inflateEnd z_inflateEnd
  78359. # define inflatePrime z_inflatePrime
  78360. # define inflateGetHeader z_inflateGetHeader
  78361. # define adler32_combine z_adler32_combine
  78362. # define crc32_combine z_crc32_combine
  78363. # define deflateInit2_ z_deflateInit2_
  78364. # define deflateSetDictionary z_deflateSetDictionary
  78365. # define deflateCopy z_deflateCopy
  78366. # define deflateReset z_deflateReset
  78367. # define deflateParams z_deflateParams
  78368. # define deflateBound z_deflateBound
  78369. # define deflatePrime z_deflatePrime
  78370. # define inflateInit2_ z_inflateInit2_
  78371. # define inflateSetDictionary z_inflateSetDictionary
  78372. # define inflateSync z_inflateSync
  78373. # define inflateSyncPoint z_inflateSyncPoint
  78374. # define inflateCopy z_inflateCopy
  78375. # define inflateReset z_inflateReset
  78376. # define inflateBack z_inflateBack
  78377. # define inflateBackEnd z_inflateBackEnd
  78378. # define compress z_compress
  78379. # define compress2 z_compress2
  78380. # define compressBound z_compressBound
  78381. # define uncompress z_uncompress
  78382. # define adler32 z_adler32
  78383. # define crc32 z_crc32
  78384. # define get_crc_table z_get_crc_table
  78385. # define zError z_zError
  78386. # define alloc_func z_alloc_func
  78387. # define free_func z_free_func
  78388. # define in_func z_in_func
  78389. # define out_func z_out_func
  78390. # define Byte z_Byte
  78391. # define uInt z_uInt
  78392. # define uLong z_uLong
  78393. # define Bytef z_Bytef
  78394. # define charf z_charf
  78395. # define intf z_intf
  78396. # define uIntf z_uIntf
  78397. # define uLongf z_uLongf
  78398. # define voidpf z_voidpf
  78399. # define voidp z_voidp
  78400. #endif
  78401. #if defined(__MSDOS__) && !defined(MSDOS)
  78402. # define MSDOS
  78403. #endif
  78404. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  78405. # define OS2
  78406. #endif
  78407. #if defined(_WINDOWS) && !defined(WINDOWS)
  78408. # define WINDOWS
  78409. #endif
  78410. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  78411. # ifndef WIN32
  78412. # define WIN32
  78413. # endif
  78414. #endif
  78415. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  78416. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  78417. # ifndef SYS16BIT
  78418. # define SYS16BIT
  78419. # endif
  78420. # endif
  78421. #endif
  78422. /*
  78423. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  78424. * than 64k bytes at a time (needed on systems with 16-bit int).
  78425. */
  78426. #ifdef SYS16BIT
  78427. # define MAXSEG_64K
  78428. #endif
  78429. #ifdef MSDOS
  78430. # define UNALIGNED_OK
  78431. #endif
  78432. #ifdef __STDC_VERSION__
  78433. # ifndef STDC
  78434. # define STDC
  78435. # endif
  78436. # if __STDC_VERSION__ >= 199901L
  78437. # ifndef STDC99
  78438. # define STDC99
  78439. # endif
  78440. # endif
  78441. #endif
  78442. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  78443. # define STDC
  78444. #endif
  78445. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  78446. # define STDC
  78447. #endif
  78448. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  78449. # define STDC
  78450. #endif
  78451. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  78452. # define STDC
  78453. #endif
  78454. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  78455. # define STDC
  78456. #endif
  78457. #ifndef STDC
  78458. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  78459. # define const /* note: need a more gentle solution here */
  78460. # endif
  78461. #endif
  78462. /* Some Mac compilers merge all .h files incorrectly: */
  78463. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  78464. # define NO_DUMMY_DECL
  78465. #endif
  78466. /* Maximum value for memLevel in deflateInit2 */
  78467. #ifndef MAX_MEM_LEVEL
  78468. # ifdef MAXSEG_64K
  78469. # define MAX_MEM_LEVEL 8
  78470. # else
  78471. # define MAX_MEM_LEVEL 9
  78472. # endif
  78473. #endif
  78474. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  78475. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  78476. * created by gzip. (Files created by minigzip can still be extracted by
  78477. * gzip.)
  78478. */
  78479. #ifndef MAX_WBITS
  78480. # define MAX_WBITS 15 /* 32K LZ77 window */
  78481. #endif
  78482. /* The memory requirements for deflate are (in bytes):
  78483. (1 << (windowBits+2)) + (1 << (memLevel+9))
  78484. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  78485. plus a few kilobytes for small objects. For example, if you want to reduce
  78486. the default memory requirements from 256K to 128K, compile with
  78487. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  78488. Of course this will generally degrade compression (there's no free lunch).
  78489. The memory requirements for inflate are (in bytes) 1 << windowBits
  78490. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  78491. for small objects.
  78492. */
  78493. /* Type declarations */
  78494. #ifndef OF /* function prototypes */
  78495. # ifdef STDC
  78496. # define OF(args) args
  78497. # else
  78498. # define OF(args) ()
  78499. # endif
  78500. #endif
  78501. /* The following definitions for FAR are needed only for MSDOS mixed
  78502. * model programming (small or medium model with some far allocations).
  78503. * This was tested only with MSC; for other MSDOS compilers you may have
  78504. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  78505. * just define FAR to be empty.
  78506. */
  78507. #ifdef SYS16BIT
  78508. # if defined(M_I86SM) || defined(M_I86MM)
  78509. /* MSC small or medium model */
  78510. # define SMALL_MEDIUM
  78511. # ifdef _MSC_VER
  78512. # define FAR _far
  78513. # else
  78514. # define FAR far
  78515. # endif
  78516. # endif
  78517. # if (defined(__SMALL__) || defined(__MEDIUM__))
  78518. /* Turbo C small or medium model */
  78519. # define SMALL_MEDIUM
  78520. # ifdef __BORLANDC__
  78521. # define FAR _far
  78522. # else
  78523. # define FAR far
  78524. # endif
  78525. # endif
  78526. #endif
  78527. #if defined(WINDOWS) || defined(WIN32)
  78528. /* If building or using zlib as a DLL, define ZLIB_DLL.
  78529. * This is not mandatory, but it offers a little performance increase.
  78530. */
  78531. # ifdef ZLIB_DLL
  78532. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  78533. # ifdef ZLIB_INTERNAL
  78534. # define ZEXTERN extern __declspec(dllexport)
  78535. # else
  78536. # define ZEXTERN extern __declspec(dllimport)
  78537. # endif
  78538. # endif
  78539. # endif /* ZLIB_DLL */
  78540. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  78541. * define ZLIB_WINAPI.
  78542. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  78543. */
  78544. # ifdef ZLIB_WINAPI
  78545. # ifdef FAR
  78546. # undef FAR
  78547. # endif
  78548. # include <windows.h>
  78549. /* No need for _export, use ZLIB.DEF instead. */
  78550. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  78551. # define ZEXPORT WINAPI
  78552. # ifdef WIN32
  78553. # define ZEXPORTVA WINAPIV
  78554. # else
  78555. # define ZEXPORTVA FAR CDECL
  78556. # endif
  78557. # endif
  78558. #endif
  78559. #if defined (__BEOS__)
  78560. # ifdef ZLIB_DLL
  78561. # ifdef ZLIB_INTERNAL
  78562. # define ZEXPORT __declspec(dllexport)
  78563. # define ZEXPORTVA __declspec(dllexport)
  78564. # else
  78565. # define ZEXPORT __declspec(dllimport)
  78566. # define ZEXPORTVA __declspec(dllimport)
  78567. # endif
  78568. # endif
  78569. #endif
  78570. #ifndef ZEXTERN
  78571. # define ZEXTERN extern
  78572. #endif
  78573. #ifndef ZEXPORT
  78574. # define ZEXPORT
  78575. #endif
  78576. #ifndef ZEXPORTVA
  78577. # define ZEXPORTVA
  78578. #endif
  78579. #ifndef FAR
  78580. # define FAR
  78581. #endif
  78582. #if !defined(__MACTYPES__)
  78583. typedef unsigned char Byte; /* 8 bits */
  78584. #endif
  78585. typedef unsigned int uInt; /* 16 bits or more */
  78586. typedef unsigned long uLong; /* 32 bits or more */
  78587. #ifdef SMALL_MEDIUM
  78588. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  78589. # define Bytef Byte FAR
  78590. #else
  78591. typedef Byte FAR Bytef;
  78592. #endif
  78593. typedef char FAR charf;
  78594. typedef int FAR intf;
  78595. typedef uInt FAR uIntf;
  78596. typedef uLong FAR uLongf;
  78597. #ifdef STDC
  78598. typedef void const *voidpc;
  78599. typedef void FAR *voidpf;
  78600. typedef void *voidp;
  78601. #else
  78602. typedef Byte const *voidpc;
  78603. typedef Byte FAR *voidpf;
  78604. typedef Byte *voidp;
  78605. #endif
  78606. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  78607. # include <sys/types.h> /* for off_t */
  78608. # include <unistd.h> /* for SEEK_* and off_t */
  78609. # ifdef VMS
  78610. # include <unixio.h> /* for off_t */
  78611. # endif
  78612. # define z_off_t off_t
  78613. #endif
  78614. #ifndef SEEK_SET
  78615. # define SEEK_SET 0 /* Seek from beginning of file. */
  78616. # define SEEK_CUR 1 /* Seek from current position. */
  78617. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  78618. #endif
  78619. #ifndef z_off_t
  78620. # define z_off_t long
  78621. #endif
  78622. #if defined(__OS400__)
  78623. # define NO_vsnprintf
  78624. #endif
  78625. #if defined(__MVS__)
  78626. # define NO_vsnprintf
  78627. # ifdef FAR
  78628. # undef FAR
  78629. # endif
  78630. #endif
  78631. /* MVS linker does not support external names larger than 8 bytes */
  78632. #if defined(__MVS__)
  78633. # pragma map(deflateInit_,"DEIN")
  78634. # pragma map(deflateInit2_,"DEIN2")
  78635. # pragma map(deflateEnd,"DEEND")
  78636. # pragma map(deflateBound,"DEBND")
  78637. # pragma map(inflateInit_,"ININ")
  78638. # pragma map(inflateInit2_,"ININ2")
  78639. # pragma map(inflateEnd,"INEND")
  78640. # pragma map(inflateSync,"INSY")
  78641. # pragma map(inflateSetDictionary,"INSEDI")
  78642. # pragma map(compressBound,"CMBND")
  78643. # pragma map(inflate_table,"INTABL")
  78644. # pragma map(inflate_fast,"INFA")
  78645. # pragma map(inflate_copyright,"INCOPY")
  78646. #endif
  78647. #endif /* ZCONF_H */
  78648. /*** End of inlined file: zconf.h ***/
  78649. #ifdef __cplusplus
  78650. //extern "C" {
  78651. #endif
  78652. #define ZLIB_VERSION "1.2.3"
  78653. #define ZLIB_VERNUM 0x1230
  78654. /*
  78655. The 'zlib' compression library provides in-memory compression and
  78656. decompression functions, including integrity checks of the uncompressed
  78657. data. This version of the library supports only one compression method
  78658. (deflation) but other algorithms will be added later and will have the same
  78659. stream interface.
  78660. Compression can be done in a single step if the buffers are large
  78661. enough (for example if an input file is mmap'ed), or can be done by
  78662. repeated calls of the compression function. In the latter case, the
  78663. application must provide more input and/or consume the output
  78664. (providing more output space) before each call.
  78665. The compressed data format used by default by the in-memory functions is
  78666. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  78667. around a deflate stream, which is itself documented in RFC 1951.
  78668. The library also supports reading and writing files in gzip (.gz) format
  78669. with an interface similar to that of stdio using the functions that start
  78670. with "gz". The gzip format is different from the zlib format. gzip is a
  78671. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  78672. This library can optionally read and write gzip streams in memory as well.
  78673. The zlib format was designed to be compact and fast for use in memory
  78674. and on communications channels. The gzip format was designed for single-
  78675. file compression on file systems, has a larger header than zlib to maintain
  78676. directory information, and uses a different, slower check method than zlib.
  78677. The library does not install any signal handler. The decoder checks
  78678. the consistency of the compressed data, so the library should never
  78679. crash even in case of corrupted input.
  78680. */
  78681. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  78682. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  78683. struct internal_state;
  78684. typedef struct z_stream_s {
  78685. Bytef *next_in; /* next input byte */
  78686. uInt avail_in; /* number of bytes available at next_in */
  78687. uLong total_in; /* total nb of input bytes read so far */
  78688. Bytef *next_out; /* next output byte should be put there */
  78689. uInt avail_out; /* remaining free space at next_out */
  78690. uLong total_out; /* total nb of bytes output so far */
  78691. char *msg; /* last error message, NULL if no error */
  78692. struct internal_state FAR *state; /* not visible by applications */
  78693. alloc_func zalloc; /* used to allocate the internal state */
  78694. free_func zfree; /* used to free the internal state */
  78695. voidpf opaque; /* private data object passed to zalloc and zfree */
  78696. int data_type; /* best guess about the data type: binary or text */
  78697. uLong adler; /* adler32 value of the uncompressed data */
  78698. uLong reserved; /* reserved for future use */
  78699. } z_stream;
  78700. typedef z_stream FAR *z_streamp;
  78701. /*
  78702. gzip header information passed to and from zlib routines. See RFC 1952
  78703. for more details on the meanings of these fields.
  78704. */
  78705. typedef struct gz_header_s {
  78706. int text; /* true if compressed data believed to be text */
  78707. uLong time; /* modification time */
  78708. int xflags; /* extra flags (not used when writing a gzip file) */
  78709. int os; /* operating system */
  78710. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  78711. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  78712. uInt extra_max; /* space at extra (only when reading header) */
  78713. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  78714. uInt name_max; /* space at name (only when reading header) */
  78715. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  78716. uInt comm_max; /* space at comment (only when reading header) */
  78717. int hcrc; /* true if there was or will be a header crc */
  78718. int done; /* true when done reading gzip header (not used
  78719. when writing a gzip file) */
  78720. } gz_header;
  78721. typedef gz_header FAR *gz_headerp;
  78722. /*
  78723. The application must update next_in and avail_in when avail_in has
  78724. dropped to zero. It must update next_out and avail_out when avail_out
  78725. has dropped to zero. The application must initialize zalloc, zfree and
  78726. opaque before calling the init function. All other fields are set by the
  78727. compression library and must not be updated by the application.
  78728. The opaque value provided by the application will be passed as the first
  78729. parameter for calls of zalloc and zfree. This can be useful for custom
  78730. memory management. The compression library attaches no meaning to the
  78731. opaque value.
  78732. zalloc must return Z_NULL if there is not enough memory for the object.
  78733. If zlib is used in a multi-threaded application, zalloc and zfree must be
  78734. thread safe.
  78735. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  78736. exactly 65536 bytes, but will not be required to allocate more than this
  78737. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  78738. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  78739. have their offset normalized to zero. The default allocation function
  78740. provided by this library ensures this (see zutil.c). To reduce memory
  78741. requirements and avoid any allocation of 64K objects, at the expense of
  78742. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  78743. The fields total_in and total_out can be used for statistics or
  78744. progress reports. After compression, total_in holds the total size of
  78745. the uncompressed data and may be saved for use in the decompressor
  78746. (particularly if the decompressor wants to decompress everything in
  78747. a single step).
  78748. */
  78749. /* constants */
  78750. #define Z_NO_FLUSH 0
  78751. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  78752. #define Z_SYNC_FLUSH 2
  78753. #define Z_FULL_FLUSH 3
  78754. #define Z_FINISH 4
  78755. #define Z_BLOCK 5
  78756. /* Allowed flush values; see deflate() and inflate() below for details */
  78757. #define Z_OK 0
  78758. #define Z_STREAM_END 1
  78759. #define Z_NEED_DICT 2
  78760. #define Z_ERRNO (-1)
  78761. #define Z_STREAM_ERROR (-2)
  78762. #define Z_DATA_ERROR (-3)
  78763. #define Z_MEM_ERROR (-4)
  78764. #define Z_BUF_ERROR (-5)
  78765. #define Z_VERSION_ERROR (-6)
  78766. /* Return codes for the compression/decompression functions. Negative
  78767. * values are errors, positive values are used for special but normal events.
  78768. */
  78769. #define Z_NO_COMPRESSION 0
  78770. #define Z_BEST_SPEED 1
  78771. #define Z_BEST_COMPRESSION 9
  78772. #define Z_DEFAULT_COMPRESSION (-1)
  78773. /* compression levels */
  78774. #define Z_FILTERED 1
  78775. #define Z_HUFFMAN_ONLY 2
  78776. #define Z_RLE 3
  78777. #define Z_FIXED 4
  78778. #define Z_DEFAULT_STRATEGY 0
  78779. /* compression strategy; see deflateInit2() below for details */
  78780. #define Z_BINARY 0
  78781. #define Z_TEXT 1
  78782. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  78783. #define Z_UNKNOWN 2
  78784. /* Possible values of the data_type field (though see inflate()) */
  78785. #define Z_DEFLATED 8
  78786. /* The deflate compression method (the only one supported in this version) */
  78787. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  78788. #define zlib_version zlibVersion()
  78789. /* for compatibility with versions < 1.0.2 */
  78790. /* basic functions */
  78791. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  78792. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  78793. If the first character differs, the library code actually used is
  78794. not compatible with the zlib.h header file used by the application.
  78795. This check is automatically made by deflateInit and inflateInit.
  78796. */
  78797. /*
  78798. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  78799. Initializes the internal stream state for compression. The fields
  78800. zalloc, zfree and opaque must be initialized before by the caller.
  78801. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  78802. use default allocation functions.
  78803. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  78804. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  78805. all (the input data is simply copied a block at a time).
  78806. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  78807. compression (currently equivalent to level 6).
  78808. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  78809. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  78810. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  78811. with the version assumed by the caller (ZLIB_VERSION).
  78812. msg is set to null if there is no error message. deflateInit does not
  78813. perform any compression: this will be done by deflate().
  78814. */
  78815. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  78816. /*
  78817. deflate compresses as much data as possible, and stops when the input
  78818. buffer becomes empty or the output buffer becomes full. It may introduce some
  78819. output latency (reading input without producing any output) except when
  78820. forced to flush.
  78821. The detailed semantics are as follows. deflate performs one or both of the
  78822. following actions:
  78823. - Compress more input starting at next_in and update next_in and avail_in
  78824. accordingly. If not all input can be processed (because there is not
  78825. enough room in the output buffer), next_in and avail_in are updated and
  78826. processing will resume at this point for the next call of deflate().
  78827. - Provide more output starting at next_out and update next_out and avail_out
  78828. accordingly. This action is forced if the parameter flush is non zero.
  78829. Forcing flush frequently degrades the compression ratio, so this parameter
  78830. should be set only when necessary (in interactive applications).
  78831. Some output may be provided even if flush is not set.
  78832. Before the call of deflate(), the application should ensure that at least
  78833. one of the actions is possible, by providing more input and/or consuming
  78834. more output, and updating avail_in or avail_out accordingly; avail_out
  78835. should never be zero before the call. The application can consume the
  78836. compressed output when it wants, for example when the output buffer is full
  78837. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  78838. and with zero avail_out, it must be called again after making room in the
  78839. output buffer because there might be more output pending.
  78840. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  78841. decide how much data to accumualte before producing output, in order to
  78842. maximize compression.
  78843. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  78844. flushed to the output buffer and the output is aligned on a byte boundary, so
  78845. that the decompressor can get all input data available so far. (In particular
  78846. avail_in is zero after the call if enough output space has been provided
  78847. before the call.) Flushing may degrade compression for some compression
  78848. algorithms and so it should be used only when necessary.
  78849. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  78850. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  78851. restart from this point if previous compressed data has been damaged or if
  78852. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  78853. compression.
  78854. If deflate returns with avail_out == 0, this function must be called again
  78855. with the same value of the flush parameter and more output space (updated
  78856. avail_out), until the flush is complete (deflate returns with non-zero
  78857. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  78858. avail_out is greater than six to avoid repeated flush markers due to
  78859. avail_out == 0 on return.
  78860. If the parameter flush is set to Z_FINISH, pending input is processed,
  78861. pending output is flushed and deflate returns with Z_STREAM_END if there
  78862. was enough output space; if deflate returns with Z_OK, this function must be
  78863. called again with Z_FINISH and more output space (updated avail_out) but no
  78864. more input data, until it returns with Z_STREAM_END or an error. After
  78865. deflate has returned Z_STREAM_END, the only possible operations on the
  78866. stream are deflateReset or deflateEnd.
  78867. Z_FINISH can be used immediately after deflateInit if all the compression
  78868. is to be done in a single step. In this case, avail_out must be at least
  78869. the value returned by deflateBound (see below). If deflate does not return
  78870. Z_STREAM_END, then it must be called again as described above.
  78871. deflate() sets strm->adler to the adler32 checksum of all input read
  78872. so far (that is, total_in bytes).
  78873. deflate() may update strm->data_type if it can make a good guess about
  78874. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  78875. binary. This field is only for information purposes and does not affect
  78876. the compression algorithm in any manner.
  78877. deflate() returns Z_OK if some progress has been made (more input
  78878. processed or more output produced), Z_STREAM_END if all input has been
  78879. consumed and all output has been produced (only when flush is set to
  78880. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  78881. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  78882. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  78883. fatal, and deflate() can be called again with more input and more output
  78884. space to continue compressing.
  78885. */
  78886. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  78887. /*
  78888. All dynamically allocated data structures for this stream are freed.
  78889. This function discards any unprocessed input and does not flush any
  78890. pending output.
  78891. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  78892. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  78893. prematurely (some input or output was discarded). In the error case,
  78894. msg may be set but then points to a static string (which must not be
  78895. deallocated).
  78896. */
  78897. /*
  78898. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  78899. Initializes the internal stream state for decompression. The fields
  78900. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  78901. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  78902. value depends on the compression method), inflateInit determines the
  78903. compression method from the zlib header and allocates all data structures
  78904. accordingly; otherwise the allocation will be deferred to the first call of
  78905. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  78906. use default allocation functions.
  78907. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  78908. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  78909. version assumed by the caller. msg is set to null if there is no error
  78910. message. inflateInit does not perform any decompression apart from reading
  78911. the zlib header if present: this will be done by inflate(). (So next_in and
  78912. avail_in may be modified, but next_out and avail_out are unchanged.)
  78913. */
  78914. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  78915. /*
  78916. inflate decompresses as much data as possible, and stops when the input
  78917. buffer becomes empty or the output buffer becomes full. It may introduce
  78918. some output latency (reading input without producing any output) except when
  78919. forced to flush.
  78920. The detailed semantics are as follows. inflate performs one or both of the
  78921. following actions:
  78922. - Decompress more input starting at next_in and update next_in and avail_in
  78923. accordingly. If not all input can be processed (because there is not
  78924. enough room in the output buffer), next_in is updated and processing
  78925. will resume at this point for the next call of inflate().
  78926. - Provide more output starting at next_out and update next_out and avail_out
  78927. accordingly. inflate() provides as much output as possible, until there
  78928. is no more input data or no more space in the output buffer (see below
  78929. about the flush parameter).
  78930. Before the call of inflate(), the application should ensure that at least
  78931. one of the actions is possible, by providing more input and/or consuming
  78932. more output, and updating the next_* and avail_* values accordingly.
  78933. The application can consume the uncompressed output when it wants, for
  78934. example when the output buffer is full (avail_out == 0), or after each
  78935. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  78936. must be called again after making room in the output buffer because there
  78937. might be more output pending.
  78938. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  78939. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  78940. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  78941. if and when it gets to the next deflate block boundary. When decoding the
  78942. zlib or gzip format, this will cause inflate() to return immediately after
  78943. the header and before the first block. When doing a raw inflate, inflate()
  78944. will go ahead and process the first block, and will return when it gets to
  78945. the end of that block, or when it runs out of data.
  78946. The Z_BLOCK option assists in appending to or combining deflate streams.
  78947. Also to assist in this, on return inflate() will set strm->data_type to the
  78948. number of unused bits in the last byte taken from strm->next_in, plus 64
  78949. if inflate() is currently decoding the last block in the deflate stream,
  78950. plus 128 if inflate() returned immediately after decoding an end-of-block
  78951. code or decoding the complete header up to just before the first byte of the
  78952. deflate stream. The end-of-block will not be indicated until all of the
  78953. uncompressed data from that block has been written to strm->next_out. The
  78954. number of unused bits may in general be greater than seven, except when
  78955. bit 7 of data_type is set, in which case the number of unused bits will be
  78956. less than eight.
  78957. inflate() should normally be called until it returns Z_STREAM_END or an
  78958. error. However if all decompression is to be performed in a single step
  78959. (a single call of inflate), the parameter flush should be set to
  78960. Z_FINISH. In this case all pending input is processed and all pending
  78961. output is flushed; avail_out must be large enough to hold all the
  78962. uncompressed data. (The size of the uncompressed data may have been saved
  78963. by the compressor for this purpose.) The next operation on this stream must
  78964. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  78965. is never required, but can be used to inform inflate that a faster approach
  78966. may be used for the single inflate() call.
  78967. In this implementation, inflate() always flushes as much output as
  78968. possible to the output buffer, and always uses the faster approach on the
  78969. first call. So the only effect of the flush parameter in this implementation
  78970. is on the return value of inflate(), as noted below, or when it returns early
  78971. because Z_BLOCK is used.
  78972. If a preset dictionary is needed after this call (see inflateSetDictionary
  78973. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  78974. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  78975. strm->adler to the adler32 checksum of all output produced so far (that is,
  78976. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  78977. below. At the end of the stream, inflate() checks that its computed adler32
  78978. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  78979. only if the checksum is correct.
  78980. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  78981. deflate data. The header type is detected automatically. Any information
  78982. contained in the gzip header is not retained, so applications that need that
  78983. information should instead use raw inflate, see inflateInit2() below, or
  78984. inflateBack() and perform their own processing of the gzip header and
  78985. trailer.
  78986. inflate() returns Z_OK if some progress has been made (more input processed
  78987. or more output produced), Z_STREAM_END if the end of the compressed data has
  78988. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  78989. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  78990. corrupted (input stream not conforming to the zlib format or incorrect check
  78991. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  78992. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  78993. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  78994. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  78995. inflate() can be called again with more input and more output space to
  78996. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  78997. call inflateSync() to look for a good compression block if a partial recovery
  78998. of the data is desired.
  78999. */
  79000. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  79001. /*
  79002. All dynamically allocated data structures for this stream are freed.
  79003. This function discards any unprocessed input and does not flush any
  79004. pending output.
  79005. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  79006. was inconsistent. In the error case, msg may be set but then points to a
  79007. static string (which must not be deallocated).
  79008. */
  79009. /* Advanced functions */
  79010. /*
  79011. The following functions are needed only in some special applications.
  79012. */
  79013. /*
  79014. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  79015. int level,
  79016. int method,
  79017. int windowBits,
  79018. int memLevel,
  79019. int strategy));
  79020. This is another version of deflateInit with more compression options. The
  79021. fields next_in, zalloc, zfree and opaque must be initialized before by
  79022. the caller.
  79023. The method parameter is the compression method. It must be Z_DEFLATED in
  79024. this version of the library.
  79025. The windowBits parameter is the base two logarithm of the window size
  79026. (the size of the history buffer). It should be in the range 8..15 for this
  79027. version of the library. Larger values of this parameter result in better
  79028. compression at the expense of memory usage. The default value is 15 if
  79029. deflateInit is used instead.
  79030. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  79031. determines the window size. deflate() will then generate raw deflate data
  79032. with no zlib header or trailer, and will not compute an adler32 check value.
  79033. windowBits can also be greater than 15 for optional gzip encoding. Add
  79034. 16 to windowBits to write a simple gzip header and trailer around the
  79035. compressed data instead of a zlib wrapper. The gzip header will have no
  79036. file name, no extra data, no comment, no modification time (set to zero),
  79037. no header crc, and the operating system will be set to 255 (unknown). If a
  79038. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  79039. The memLevel parameter specifies how much memory should be allocated
  79040. for the internal compression state. memLevel=1 uses minimum memory but
  79041. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  79042. for optimal speed. The default value is 8. See zconf.h for total memory
  79043. usage as a function of windowBits and memLevel.
  79044. The strategy parameter is used to tune the compression algorithm. Use the
  79045. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  79046. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  79047. string match), or Z_RLE to limit match distances to one (run-length
  79048. encoding). Filtered data consists mostly of small values with a somewhat
  79049. random distribution. In this case, the compression algorithm is tuned to
  79050. compress them better. The effect of Z_FILTERED is to force more Huffman
  79051. coding and less string matching; it is somewhat intermediate between
  79052. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  79053. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  79054. parameter only affects the compression ratio but not the correctness of the
  79055. compressed output even if it is not set appropriately. Z_FIXED prevents the
  79056. use of dynamic Huffman codes, allowing for a simpler decoder for special
  79057. applications.
  79058. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79059. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  79060. method). msg is set to null if there is no error message. deflateInit2 does
  79061. not perform any compression: this will be done by deflate().
  79062. */
  79063. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  79064. const Bytef *dictionary,
  79065. uInt dictLength));
  79066. /*
  79067. Initializes the compression dictionary from the given byte sequence
  79068. without producing any compressed output. This function must be called
  79069. immediately after deflateInit, deflateInit2 or deflateReset, before any
  79070. call of deflate. The compressor and decompressor must use exactly the same
  79071. dictionary (see inflateSetDictionary).
  79072. The dictionary should consist of strings (byte sequences) that are likely
  79073. to be encountered later in the data to be compressed, with the most commonly
  79074. used strings preferably put towards the end of the dictionary. Using a
  79075. dictionary is most useful when the data to be compressed is short and can be
  79076. predicted with good accuracy; the data can then be compressed better than
  79077. with the default empty dictionary.
  79078. Depending on the size of the compression data structures selected by
  79079. deflateInit or deflateInit2, a part of the dictionary may in effect be
  79080. discarded, for example if the dictionary is larger than the window size in
  79081. deflate or deflate2. Thus the strings most likely to be useful should be
  79082. put at the end of the dictionary, not at the front. In addition, the
  79083. current implementation of deflate will use at most the window size minus
  79084. 262 bytes of the provided dictionary.
  79085. Upon return of this function, strm->adler is set to the adler32 value
  79086. of the dictionary; the decompressor may later use this value to determine
  79087. which dictionary has been used by the compressor. (The adler32 value
  79088. applies to the whole dictionary even if only a subset of the dictionary is
  79089. actually used by the compressor.) If a raw deflate was requested, then the
  79090. adler32 value is not computed and strm->adler is not set.
  79091. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  79092. parameter is invalid (such as NULL dictionary) or the stream state is
  79093. inconsistent (for example if deflate has already been called for this stream
  79094. or if the compression method is bsort). deflateSetDictionary does not
  79095. perform any compression: this will be done by deflate().
  79096. */
  79097. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  79098. z_streamp source));
  79099. /*
  79100. Sets the destination stream as a complete copy of the source stream.
  79101. This function can be useful when several compression strategies will be
  79102. tried, for example when there are several ways of pre-processing the input
  79103. data with a filter. The streams that will be discarded should then be freed
  79104. by calling deflateEnd. Note that deflateCopy duplicates the internal
  79105. compression state which can be quite large, so this strategy is slow and
  79106. can consume lots of memory.
  79107. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79108. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79109. (such as zalloc being NULL). msg is left unchanged in both source and
  79110. destination.
  79111. */
  79112. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  79113. /*
  79114. This function is equivalent to deflateEnd followed by deflateInit,
  79115. but does not free and reallocate all the internal compression state.
  79116. The stream will keep the same compression level and any other attributes
  79117. that may have been set by deflateInit2.
  79118. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79119. stream state was inconsistent (such as zalloc or state being NULL).
  79120. */
  79121. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  79122. int level,
  79123. int strategy));
  79124. /*
  79125. Dynamically update the compression level and compression strategy. The
  79126. interpretation of level and strategy is as in deflateInit2. This can be
  79127. used to switch between compression and straight copy of the input data, or
  79128. to switch to a different kind of input data requiring a different
  79129. strategy. If the compression level is changed, the input available so far
  79130. is compressed with the old level (and may be flushed); the new level will
  79131. take effect only at the next call of deflate().
  79132. Before the call of deflateParams, the stream state must be set as for
  79133. a call of deflate(), since the currently available input may have to
  79134. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  79135. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  79136. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  79137. if strm->avail_out was zero.
  79138. */
  79139. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  79140. int good_length,
  79141. int max_lazy,
  79142. int nice_length,
  79143. int max_chain));
  79144. /*
  79145. Fine tune deflate's internal compression parameters. This should only be
  79146. used by someone who understands the algorithm used by zlib's deflate for
  79147. searching for the best matching string, and even then only by the most
  79148. fanatic optimizer trying to squeeze out the last compressed bit for their
  79149. specific input data. Read the deflate.c source code for the meaning of the
  79150. max_lazy, good_length, nice_length, and max_chain parameters.
  79151. deflateTune() can be called after deflateInit() or deflateInit2(), and
  79152. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  79153. */
  79154. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  79155. uLong sourceLen));
  79156. /*
  79157. deflateBound() returns an upper bound on the compressed size after
  79158. deflation of sourceLen bytes. It must be called after deflateInit()
  79159. or deflateInit2(). This would be used to allocate an output buffer
  79160. for deflation in a single pass, and so would be called before deflate().
  79161. */
  79162. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  79163. int bits,
  79164. int value));
  79165. /*
  79166. deflatePrime() inserts bits in the deflate output stream. The intent
  79167. is that this function is used to start off the deflate output with the
  79168. bits leftover from a previous deflate stream when appending to it. As such,
  79169. this function can only be used for raw deflate, and must be used before the
  79170. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  79171. less than or equal to 16, and that many of the least significant bits of
  79172. value will be inserted in the output.
  79173. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79174. stream state was inconsistent.
  79175. */
  79176. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  79177. gz_headerp head));
  79178. /*
  79179. deflateSetHeader() provides gzip header information for when a gzip
  79180. stream is requested by deflateInit2(). deflateSetHeader() may be called
  79181. after deflateInit2() or deflateReset() and before the first call of
  79182. deflate(). The text, time, os, extra field, name, and comment information
  79183. in the provided gz_header structure are written to the gzip header (xflag is
  79184. ignored -- the extra flags are set according to the compression level). The
  79185. caller must assure that, if not Z_NULL, name and comment are terminated with
  79186. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  79187. available there. If hcrc is true, a gzip header crc is included. Note that
  79188. the current versions of the command-line version of gzip (up through version
  79189. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  79190. gzip file" and give up.
  79191. If deflateSetHeader is not used, the default gzip header has text false,
  79192. the time set to zero, and os set to 255, with no extra, name, or comment
  79193. fields. The gzip header is returned to the default state by deflateReset().
  79194. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79195. stream state was inconsistent.
  79196. */
  79197. /*
  79198. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  79199. int windowBits));
  79200. This is another version of inflateInit with an extra parameter. The
  79201. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  79202. before by the caller.
  79203. The windowBits parameter is the base two logarithm of the maximum window
  79204. size (the size of the history buffer). It should be in the range 8..15 for
  79205. this version of the library. The default value is 15 if inflateInit is used
  79206. instead. windowBits must be greater than or equal to the windowBits value
  79207. provided to deflateInit2() while compressing, or it must be equal to 15 if
  79208. deflateInit2() was not used. If a compressed stream with a larger window
  79209. size is given as input, inflate() will return with the error code
  79210. Z_DATA_ERROR instead of trying to allocate a larger window.
  79211. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  79212. determines the window size. inflate() will then process raw deflate data,
  79213. not looking for a zlib or gzip header, not generating a check value, and not
  79214. looking for any check values for comparison at the end of the stream. This
  79215. is for use with other formats that use the deflate compressed data format
  79216. such as zip. Those formats provide their own check values. If a custom
  79217. format is developed using the raw deflate format for compressed data, it is
  79218. recommended that a check value such as an adler32 or a crc32 be applied to
  79219. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  79220. most applications, the zlib format should be used as is. Note that comments
  79221. above on the use in deflateInit2() applies to the magnitude of windowBits.
  79222. windowBits can also be greater than 15 for optional gzip decoding. Add
  79223. 32 to windowBits to enable zlib and gzip decoding with automatic header
  79224. detection, or add 16 to decode only the gzip format (the zlib format will
  79225. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  79226. a crc32 instead of an adler32.
  79227. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79228. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  79229. is set to null if there is no error message. inflateInit2 does not perform
  79230. any decompression apart from reading the zlib header if present: this will
  79231. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  79232. and avail_out are unchanged.)
  79233. */
  79234. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  79235. const Bytef *dictionary,
  79236. uInt dictLength));
  79237. /*
  79238. Initializes the decompression dictionary from the given uncompressed byte
  79239. sequence. This function must be called immediately after a call of inflate,
  79240. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  79241. can be determined from the adler32 value returned by that call of inflate.
  79242. The compressor and decompressor must use exactly the same dictionary (see
  79243. deflateSetDictionary). For raw inflate, this function can be called
  79244. immediately after inflateInit2() or inflateReset() and before any call of
  79245. inflate() to set the dictionary. The application must insure that the
  79246. dictionary that was used for compression is provided.
  79247. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  79248. parameter is invalid (such as NULL dictionary) or the stream state is
  79249. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  79250. expected one (incorrect adler32 value). inflateSetDictionary does not
  79251. perform any decompression: this will be done by subsequent calls of
  79252. inflate().
  79253. */
  79254. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  79255. /*
  79256. Skips invalid compressed data until a full flush point (see above the
  79257. description of deflate with Z_FULL_FLUSH) can be found, or until all
  79258. available input is skipped. No output is provided.
  79259. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  79260. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  79261. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  79262. case, the application may save the current current value of total_in which
  79263. indicates where valid compressed data was found. In the error case, the
  79264. application may repeatedly call inflateSync, providing more input each time,
  79265. until success or end of the input data.
  79266. */
  79267. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  79268. z_streamp source));
  79269. /*
  79270. Sets the destination stream as a complete copy of the source stream.
  79271. This function can be useful when randomly accessing a large stream. The
  79272. first pass through the stream can periodically record the inflate state,
  79273. allowing restarting inflate at those points when randomly accessing the
  79274. stream.
  79275. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  79276. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  79277. (such as zalloc being NULL). msg is left unchanged in both source and
  79278. destination.
  79279. */
  79280. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  79281. /*
  79282. This function is equivalent to inflateEnd followed by inflateInit,
  79283. but does not free and reallocate all the internal decompression state.
  79284. The stream will keep attributes that may have been set by inflateInit2.
  79285. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  79286. stream state was inconsistent (such as zalloc or state being NULL).
  79287. */
  79288. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  79289. int bits,
  79290. int value));
  79291. /*
  79292. This function inserts bits in the inflate input stream. The intent is
  79293. that this function is used to start inflating at a bit position in the
  79294. middle of a byte. The provided bits will be used before any bytes are used
  79295. from next_in. This function should only be used with raw inflate, and
  79296. should be used before the first inflate() call after inflateInit2() or
  79297. inflateReset(). bits must be less than or equal to 16, and that many of the
  79298. least significant bits of value will be inserted in the input.
  79299. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  79300. stream state was inconsistent.
  79301. */
  79302. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  79303. gz_headerp head));
  79304. /*
  79305. inflateGetHeader() requests that gzip header information be stored in the
  79306. provided gz_header structure. inflateGetHeader() may be called after
  79307. inflateInit2() or inflateReset(), and before the first call of inflate().
  79308. As inflate() processes the gzip stream, head->done is zero until the header
  79309. is completed, at which time head->done is set to one. If a zlib stream is
  79310. being decoded, then head->done is set to -1 to indicate that there will be
  79311. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  79312. force inflate() to return immediately after header processing is complete
  79313. and before any actual data is decompressed.
  79314. The text, time, xflags, and os fields are filled in with the gzip header
  79315. contents. hcrc is set to true if there is a header CRC. (The header CRC
  79316. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  79317. contains the maximum number of bytes to write to extra. Once done is true,
  79318. extra_len contains the actual extra field length, and extra contains the
  79319. extra field, or that field truncated if extra_max is less than extra_len.
  79320. If name is not Z_NULL, then up to name_max characters are written there,
  79321. terminated with a zero unless the length is greater than name_max. If
  79322. comment is not Z_NULL, then up to comm_max characters are written there,
  79323. terminated with a zero unless the length is greater than comm_max. When
  79324. any of extra, name, or comment are not Z_NULL and the respective field is
  79325. not present in the header, then that field is set to Z_NULL to signal its
  79326. absence. This allows the use of deflateSetHeader() with the returned
  79327. structure to duplicate the header. However if those fields are set to
  79328. allocated memory, then the application will need to save those pointers
  79329. elsewhere so that they can be eventually freed.
  79330. If inflateGetHeader is not used, then the header information is simply
  79331. discarded. The header is always checked for validity, including the header
  79332. CRC if present. inflateReset() will reset the process to discard the header
  79333. information. The application would need to call inflateGetHeader() again to
  79334. retrieve the header from the next gzip stream.
  79335. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  79336. stream state was inconsistent.
  79337. */
  79338. /*
  79339. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  79340. unsigned char FAR *window));
  79341. Initialize the internal stream state for decompression using inflateBack()
  79342. calls. The fields zalloc, zfree and opaque in strm must be initialized
  79343. before the call. If zalloc and zfree are Z_NULL, then the default library-
  79344. derived memory allocation routines are used. windowBits is the base two
  79345. logarithm of the window size, in the range 8..15. window is a caller
  79346. supplied buffer of that size. Except for special applications where it is
  79347. assured that deflate was used with small window sizes, windowBits must be 15
  79348. and a 32K byte window must be supplied to be able to decompress general
  79349. deflate streams.
  79350. See inflateBack() for the usage of these routines.
  79351. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  79352. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  79353. be allocated, or Z_VERSION_ERROR if the version of the library does not
  79354. match the version of the header file.
  79355. */
  79356. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  79357. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  79358. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  79359. in_func in, void FAR *in_desc,
  79360. out_func out, void FAR *out_desc));
  79361. /*
  79362. inflateBack() does a raw inflate with a single call using a call-back
  79363. interface for input and output. This is more efficient than inflate() for
  79364. file i/o applications in that it avoids copying between the output and the
  79365. sliding window by simply making the window itself the output buffer. This
  79366. function trusts the application to not change the output buffer passed by
  79367. the output function, at least until inflateBack() returns.
  79368. inflateBackInit() must be called first to allocate the internal state
  79369. and to initialize the state with the user-provided window buffer.
  79370. inflateBack() may then be used multiple times to inflate a complete, raw
  79371. deflate stream with each call. inflateBackEnd() is then called to free
  79372. the allocated state.
  79373. A raw deflate stream is one with no zlib or gzip header or trailer.
  79374. This routine would normally be used in a utility that reads zip or gzip
  79375. files and writes out uncompressed files. The utility would decode the
  79376. header and process the trailer on its own, hence this routine expects
  79377. only the raw deflate stream to decompress. This is different from the
  79378. normal behavior of inflate(), which expects either a zlib or gzip header and
  79379. trailer around the deflate stream.
  79380. inflateBack() uses two subroutines supplied by the caller that are then
  79381. called by inflateBack() for input and output. inflateBack() calls those
  79382. routines until it reads a complete deflate stream and writes out all of the
  79383. uncompressed data, or until it encounters an error. The function's
  79384. parameters and return types are defined above in the in_func and out_func
  79385. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  79386. number of bytes of provided input, and a pointer to that input in buf. If
  79387. there is no input available, in() must return zero--buf is ignored in that
  79388. case--and inflateBack() will return a buffer error. inflateBack() will call
  79389. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  79390. should return zero on success, or non-zero on failure. If out() returns
  79391. non-zero, inflateBack() will return with an error. Neither in() nor out()
  79392. are permitted to change the contents of the window provided to
  79393. inflateBackInit(), which is also the buffer that out() uses to write from.
  79394. The length written by out() will be at most the window size. Any non-zero
  79395. amount of input may be provided by in().
  79396. For convenience, inflateBack() can be provided input on the first call by
  79397. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  79398. in() will be called. Therefore strm->next_in must be initialized before
  79399. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  79400. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  79401. must also be initialized, and then if strm->avail_in is not zero, input will
  79402. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  79403. The in_desc and out_desc parameters of inflateBack() is passed as the
  79404. first parameter of in() and out() respectively when they are called. These
  79405. descriptors can be optionally used to pass any information that the caller-
  79406. supplied in() and out() functions need to do their job.
  79407. On return, inflateBack() will set strm->next_in and strm->avail_in to
  79408. pass back any unused input that was provided by the last in() call. The
  79409. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  79410. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  79411. error in the deflate stream (in which case strm->msg is set to indicate the
  79412. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  79413. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  79414. distinguished using strm->next_in which will be Z_NULL only if in() returned
  79415. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  79416. out() returning non-zero. (in() will always be called before out(), so
  79417. strm->next_in is assured to be defined if out() returns non-zero.) Note
  79418. that inflateBack() cannot return Z_OK.
  79419. */
  79420. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  79421. /*
  79422. All memory allocated by inflateBackInit() is freed.
  79423. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  79424. state was inconsistent.
  79425. */
  79426. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  79427. /* Return flags indicating compile-time options.
  79428. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  79429. 1.0: size of uInt
  79430. 3.2: size of uLong
  79431. 5.4: size of voidpf (pointer)
  79432. 7.6: size of z_off_t
  79433. Compiler, assembler, and debug options:
  79434. 8: DEBUG
  79435. 9: ASMV or ASMINF -- use ASM code
  79436. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  79437. 11: 0 (reserved)
  79438. One-time table building (smaller code, but not thread-safe if true):
  79439. 12: BUILDFIXED -- build static block decoding tables when needed
  79440. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  79441. 14,15: 0 (reserved)
  79442. Library content (indicates missing functionality):
  79443. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  79444. deflate code when not needed)
  79445. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  79446. and decode gzip streams (to avoid linking crc code)
  79447. 18-19: 0 (reserved)
  79448. Operation variations (changes in library functionality):
  79449. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  79450. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  79451. 22,23: 0 (reserved)
  79452. The sprintf variant used by gzprintf (zero is best):
  79453. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  79454. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  79455. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  79456. Remainder:
  79457. 27-31: 0 (reserved)
  79458. */
  79459. /* utility functions */
  79460. /*
  79461. The following utility functions are implemented on top of the
  79462. basic stream-oriented functions. To simplify the interface, some
  79463. default options are assumed (compression level and memory usage,
  79464. standard memory allocation functions). The source code of these
  79465. utility functions can easily be modified if you need special options.
  79466. */
  79467. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  79468. const Bytef *source, uLong sourceLen));
  79469. /*
  79470. Compresses the source buffer into the destination buffer. sourceLen is
  79471. the byte length of the source buffer. Upon entry, destLen is the total
  79472. size of the destination buffer, which must be at least the value returned
  79473. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79474. compressed buffer.
  79475. This function can be used to compress a whole file at once if the
  79476. input file is mmap'ed.
  79477. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  79478. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79479. buffer.
  79480. */
  79481. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  79482. const Bytef *source, uLong sourceLen,
  79483. int level));
  79484. /*
  79485. Compresses the source buffer into the destination buffer. The level
  79486. parameter has the same meaning as in deflateInit. sourceLen is the byte
  79487. length of the source buffer. Upon entry, destLen is the total size of the
  79488. destination buffer, which must be at least the value returned by
  79489. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  79490. compressed buffer.
  79491. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  79492. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  79493. Z_STREAM_ERROR if the level parameter is invalid.
  79494. */
  79495. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  79496. /*
  79497. compressBound() returns an upper bound on the compressed size after
  79498. compress() or compress2() on sourceLen bytes. It would be used before
  79499. a compress() or compress2() call to allocate the destination buffer.
  79500. */
  79501. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  79502. const Bytef *source, uLong sourceLen));
  79503. /*
  79504. Decompresses the source buffer into the destination buffer. sourceLen is
  79505. the byte length of the source buffer. Upon entry, destLen is the total
  79506. size of the destination buffer, which must be large enough to hold the
  79507. entire uncompressed data. (The size of the uncompressed data must have
  79508. been saved previously by the compressor and transmitted to the decompressor
  79509. by some mechanism outside the scope of this compression library.)
  79510. Upon exit, destLen is the actual size of the compressed buffer.
  79511. This function can be used to decompress a whole file at once if the
  79512. input file is mmap'ed.
  79513. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  79514. enough memory, Z_BUF_ERROR if there was not enough room in the output
  79515. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  79516. */
  79517. typedef voidp gzFile;
  79518. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  79519. /*
  79520. Opens a gzip (.gz) file for reading or writing. The mode parameter
  79521. is as in fopen ("rb" or "wb") but can also include a compression level
  79522. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  79523. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  79524. as in "wb1R". (See the description of deflateInit2 for more information
  79525. about the strategy parameter.)
  79526. gzopen can be used to read a file which is not in gzip format; in this
  79527. case gzread will directly read from the file without decompression.
  79528. gzopen returns NULL if the file could not be opened or if there was
  79529. insufficient memory to allocate the (de)compression state; errno
  79530. can be checked to distinguish the two cases (if errno is zero, the
  79531. zlib error is Z_MEM_ERROR). */
  79532. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  79533. /*
  79534. gzdopen() associates a gzFile with the file descriptor fd. File
  79535. descriptors are obtained from calls like open, dup, creat, pipe or
  79536. fileno (in the file has been previously opened with fopen).
  79537. The mode parameter is as in gzopen.
  79538. The next call of gzclose on the returned gzFile will also close the
  79539. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  79540. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  79541. gzdopen returns NULL if there was insufficient memory to allocate
  79542. the (de)compression state.
  79543. */
  79544. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  79545. /*
  79546. Dynamically update the compression level or strategy. See the description
  79547. of deflateInit2 for the meaning of these parameters.
  79548. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  79549. opened for writing.
  79550. */
  79551. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  79552. /*
  79553. Reads the given number of uncompressed bytes from the compressed file.
  79554. If the input file was not in gzip format, gzread copies the given number
  79555. of bytes into the buffer.
  79556. gzread returns the number of uncompressed bytes actually read (0 for
  79557. end of file, -1 for error). */
  79558. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  79559. voidpc buf, unsigned len));
  79560. /*
  79561. Writes the given number of uncompressed bytes into the compressed file.
  79562. gzwrite returns the number of uncompressed bytes actually written
  79563. (0 in case of error).
  79564. */
  79565. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  79566. /*
  79567. Converts, formats, and writes the args to the compressed file under
  79568. control of the format string, as in fprintf. gzprintf returns the number of
  79569. uncompressed bytes actually written (0 in case of error). The number of
  79570. uncompressed bytes written is limited to 4095. The caller should assure that
  79571. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  79572. return an error (0) with nothing written. In this case, there may also be a
  79573. buffer overflow with unpredictable consequences, which is possible only if
  79574. zlib was compiled with the insecure functions sprintf() or vsprintf()
  79575. because the secure snprintf() or vsnprintf() functions were not available.
  79576. */
  79577. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  79578. /*
  79579. Writes the given null-terminated string to the compressed file, excluding
  79580. the terminating null character.
  79581. gzputs returns the number of characters written, or -1 in case of error.
  79582. */
  79583. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  79584. /*
  79585. Reads bytes from the compressed file until len-1 characters are read, or
  79586. a newline character is read and transferred to buf, or an end-of-file
  79587. condition is encountered. The string is then terminated with a null
  79588. character.
  79589. gzgets returns buf, or Z_NULL in case of error.
  79590. */
  79591. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  79592. /*
  79593. Writes c, converted to an unsigned char, into the compressed file.
  79594. gzputc returns the value that was written, or -1 in case of error.
  79595. */
  79596. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  79597. /*
  79598. Reads one byte from the compressed file. gzgetc returns this byte
  79599. or -1 in case of end of file or error.
  79600. */
  79601. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  79602. /*
  79603. Push one character back onto the stream to be read again later.
  79604. Only one character of push-back is allowed. gzungetc() returns the
  79605. character pushed, or -1 on failure. gzungetc() will fail if a
  79606. character has been pushed but not read yet, or if c is -1. The pushed
  79607. character will be discarded if the stream is repositioned with gzseek()
  79608. or gzrewind().
  79609. */
  79610. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  79611. /*
  79612. Flushes all pending output into the compressed file. The parameter
  79613. flush is as in the deflate() function. The return value is the zlib
  79614. error number (see function gzerror below). gzflush returns Z_OK if
  79615. the flush parameter is Z_FINISH and all output could be flushed.
  79616. gzflush should be called only when strictly necessary because it can
  79617. degrade compression.
  79618. */
  79619. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  79620. z_off_t offset, int whence));
  79621. /*
  79622. Sets the starting position for the next gzread or gzwrite on the
  79623. given compressed file. The offset represents a number of bytes in the
  79624. uncompressed data stream. The whence parameter is defined as in lseek(2);
  79625. the value SEEK_END is not supported.
  79626. If the file is opened for reading, this function is emulated but can be
  79627. extremely slow. If the file is opened for writing, only forward seeks are
  79628. supported; gzseek then compresses a sequence of zeroes up to the new
  79629. starting position.
  79630. gzseek returns the resulting offset location as measured in bytes from
  79631. the beginning of the uncompressed stream, or -1 in case of error, in
  79632. particular if the file is opened for writing and the new starting position
  79633. would be before the current position.
  79634. */
  79635. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  79636. /*
  79637. Rewinds the given file. This function is supported only for reading.
  79638. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  79639. */
  79640. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  79641. /*
  79642. Returns the starting position for the next gzread or gzwrite on the
  79643. given compressed file. This position represents a number of bytes in the
  79644. uncompressed data stream.
  79645. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  79646. */
  79647. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  79648. /*
  79649. Returns 1 when EOF has previously been detected reading the given
  79650. input stream, otherwise zero.
  79651. */
  79652. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  79653. /*
  79654. Returns 1 if file is being read directly without decompression, otherwise
  79655. zero.
  79656. */
  79657. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  79658. /*
  79659. Flushes all pending output if necessary, closes the compressed file
  79660. and deallocates all the (de)compression state. The return value is the zlib
  79661. error number (see function gzerror below).
  79662. */
  79663. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  79664. /*
  79665. Returns the error message for the last error which occurred on the
  79666. given compressed file. errnum is set to zlib error number. If an
  79667. error occurred in the file system and not in the compression library,
  79668. errnum is set to Z_ERRNO and the application may consult errno
  79669. to get the exact error code.
  79670. */
  79671. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  79672. /*
  79673. Clears the error and end-of-file flags for file. This is analogous to the
  79674. clearerr() function in stdio. This is useful for continuing to read a gzip
  79675. file that is being written concurrently.
  79676. */
  79677. /* checksum functions */
  79678. /*
  79679. These functions are not related to compression but are exported
  79680. anyway because they might be useful in applications using the
  79681. compression library.
  79682. */
  79683. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  79684. /*
  79685. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  79686. return the updated checksum. If buf is NULL, this function returns
  79687. the required initial value for the checksum.
  79688. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  79689. much faster. Usage example:
  79690. uLong adler = adler32(0L, Z_NULL, 0);
  79691. while (read_buffer(buffer, length) != EOF) {
  79692. adler = adler32(adler, buffer, length);
  79693. }
  79694. if (adler != original_adler) error();
  79695. */
  79696. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  79697. z_off_t len2));
  79698. /*
  79699. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  79700. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  79701. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  79702. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  79703. */
  79704. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  79705. /*
  79706. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  79707. updated CRC-32. If buf is NULL, this function returns the required initial
  79708. value for the for the crc. Pre- and post-conditioning (one's complement) is
  79709. performed within this function so it shouldn't be done by the application.
  79710. Usage example:
  79711. uLong crc = crc32(0L, Z_NULL, 0);
  79712. while (read_buffer(buffer, length) != EOF) {
  79713. crc = crc32(crc, buffer, length);
  79714. }
  79715. if (crc != original_crc) error();
  79716. */
  79717. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  79718. /*
  79719. Combine two CRC-32 check values into one. For two sequences of bytes,
  79720. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  79721. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  79722. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  79723. len2.
  79724. */
  79725. /* various hacks, don't look :) */
  79726. /* deflateInit and inflateInit are macros to allow checking the zlib version
  79727. * and the compiler's view of z_stream:
  79728. */
  79729. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  79730. const char *version, int stream_size));
  79731. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  79732. const char *version, int stream_size));
  79733. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  79734. int windowBits, int memLevel,
  79735. int strategy, const char *version,
  79736. int stream_size));
  79737. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  79738. const char *version, int stream_size));
  79739. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  79740. unsigned char FAR *window,
  79741. const char *version,
  79742. int stream_size));
  79743. #define deflateInit(strm, level) \
  79744. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  79745. #define inflateInit(strm) \
  79746. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  79747. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  79748. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  79749. (strategy), ZLIB_VERSION, sizeof(z_stream))
  79750. #define inflateInit2(strm, windowBits) \
  79751. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  79752. #define inflateBackInit(strm, windowBits, window) \
  79753. inflateBackInit_((strm), (windowBits), (window), \
  79754. ZLIB_VERSION, sizeof(z_stream))
  79755. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  79756. struct internal_state {int dummy;}; /* hack for buggy compilers */
  79757. #endif
  79758. ZEXTERN const char * ZEXPORT zError OF((int));
  79759. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  79760. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  79761. #ifdef __cplusplus
  79762. //}
  79763. #endif
  79764. #endif /* ZLIB_H */
  79765. /*** End of inlined file: zlib.h ***/
  79766. #undef OS_CODE
  79767. #else
  79768. #include <zlib.h>
  79769. #endif
  79770. }
  79771. BEGIN_JUCE_NAMESPACE
  79772. // internal helper object that holds the zlib structures so they don't have to be
  79773. // included publicly.
  79774. class GZIPCompressorOutputStream::GZIPCompressorHelper
  79775. {
  79776. public:
  79777. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  79778. : data (0),
  79779. dataSize (0),
  79780. compLevel (compressionLevel),
  79781. strategy (0),
  79782. setParams (true),
  79783. streamIsValid (false),
  79784. finished (false),
  79785. shouldFinish (false)
  79786. {
  79787. using namespace zlibNamespace;
  79788. zerostruct (stream);
  79789. streamIsValid = (deflateInit2 (&stream, compLevel, Z_DEFLATED,
  79790. nowrap ? -MAX_WBITS : MAX_WBITS,
  79791. 8, strategy) == Z_OK);
  79792. }
  79793. ~GZIPCompressorHelper()
  79794. {
  79795. using namespace zlibNamespace;
  79796. if (streamIsValid)
  79797. deflateEnd (&stream);
  79798. }
  79799. bool needsInput() const throw()
  79800. {
  79801. return dataSize <= 0;
  79802. }
  79803. void setInput (const uint8* const newData, const int size) throw()
  79804. {
  79805. data = newData;
  79806. dataSize = size;
  79807. }
  79808. int doNextBlock (uint8* const dest, const int destSize) throw()
  79809. {
  79810. using namespace zlibNamespace;
  79811. if (streamIsValid)
  79812. {
  79813. stream.next_in = const_cast <uint8*> (data);
  79814. stream.next_out = dest;
  79815. stream.avail_in = dataSize;
  79816. stream.avail_out = destSize;
  79817. const int result = setParams ? deflateParams (&stream, compLevel, strategy)
  79818. : deflate (&stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  79819. setParams = false;
  79820. switch (result)
  79821. {
  79822. case Z_STREAM_END:
  79823. finished = true;
  79824. // Deliberate fall-through..
  79825. case Z_OK:
  79826. data += dataSize - stream.avail_in;
  79827. dataSize = stream.avail_in;
  79828. return destSize - stream.avail_out;
  79829. default:
  79830. break;
  79831. }
  79832. }
  79833. return 0;
  79834. }
  79835. enum { gzipCompBufferSize = 32768 };
  79836. private:
  79837. zlibNamespace::z_stream stream;
  79838. const uint8* data;
  79839. int dataSize, compLevel, strategy;
  79840. bool setParams, streamIsValid;
  79841. public:
  79842. bool finished, shouldFinish;
  79843. };
  79844. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  79845. int compressionLevel,
  79846. const bool deleteDestStream,
  79847. const bool noWrap)
  79848. : destStream (destStream_),
  79849. streamToDelete (deleteDestStream ? destStream_ : 0),
  79850. buffer ((size_t) GZIPCompressorHelper::gzipCompBufferSize)
  79851. {
  79852. if (compressionLevel < 1 || compressionLevel > 9)
  79853. compressionLevel = -1;
  79854. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  79855. }
  79856. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  79857. {
  79858. flush();
  79859. }
  79860. void GZIPCompressorOutputStream::flush()
  79861. {
  79862. if (! helper->finished)
  79863. {
  79864. helper->shouldFinish = true;
  79865. while (! helper->finished)
  79866. doNextBlock();
  79867. }
  79868. destStream->flush();
  79869. }
  79870. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  79871. {
  79872. if (! helper->finished)
  79873. {
  79874. helper->setInput (static_cast <const uint8*> (destBuffer), howMany);
  79875. while (! helper->needsInput())
  79876. {
  79877. if (! doNextBlock())
  79878. return false;
  79879. }
  79880. }
  79881. return true;
  79882. }
  79883. bool GZIPCompressorOutputStream::doNextBlock()
  79884. {
  79885. const int len = helper->doNextBlock (buffer, (int) GZIPCompressorHelper::gzipCompBufferSize);
  79886. if (len > 0)
  79887. return destStream->write (buffer, len);
  79888. else
  79889. return true;
  79890. }
  79891. int64 GZIPCompressorOutputStream::getPosition()
  79892. {
  79893. return destStream->getPosition();
  79894. }
  79895. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  79896. {
  79897. jassertfalse; // can't do it!
  79898. return false;
  79899. }
  79900. END_JUCE_NAMESPACE
  79901. /*** End of inlined file: juce_GZIPCompressorOutputStream.cpp ***/
  79902. /*** Start of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  79903. #if JUCE_MSVC
  79904. #pragma warning (push)
  79905. #pragma warning (disable: 4309 4305)
  79906. #endif
  79907. namespace zlibNamespace
  79908. {
  79909. #if JUCE_INCLUDE_ZLIB_CODE
  79910. #undef OS_CODE
  79911. #undef fdopen
  79912. #define ZLIB_INTERNAL
  79913. #define NO_DUMMY_DECL
  79914. /*** Start of inlined file: adler32.c ***/
  79915. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79916. #define ZLIB_INTERNAL
  79917. #define BASE 65521UL /* largest prime smaller than 65536 */
  79918. #define NMAX 5552
  79919. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  79920. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  79921. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  79922. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  79923. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  79924. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  79925. /* use NO_DIVIDE if your processor does not do division in hardware */
  79926. #ifdef NO_DIVIDE
  79927. # define MOD(a) \
  79928. do { \
  79929. if (a >= (BASE << 16)) a -= (BASE << 16); \
  79930. if (a >= (BASE << 15)) a -= (BASE << 15); \
  79931. if (a >= (BASE << 14)) a -= (BASE << 14); \
  79932. if (a >= (BASE << 13)) a -= (BASE << 13); \
  79933. if (a >= (BASE << 12)) a -= (BASE << 12); \
  79934. if (a >= (BASE << 11)) a -= (BASE << 11); \
  79935. if (a >= (BASE << 10)) a -= (BASE << 10); \
  79936. if (a >= (BASE << 9)) a -= (BASE << 9); \
  79937. if (a >= (BASE << 8)) a -= (BASE << 8); \
  79938. if (a >= (BASE << 7)) a -= (BASE << 7); \
  79939. if (a >= (BASE << 6)) a -= (BASE << 6); \
  79940. if (a >= (BASE << 5)) a -= (BASE << 5); \
  79941. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79942. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79943. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79944. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79945. if (a >= BASE) a -= BASE; \
  79946. } while (0)
  79947. # define MOD4(a) \
  79948. do { \
  79949. if (a >= (BASE << 4)) a -= (BASE << 4); \
  79950. if (a >= (BASE << 3)) a -= (BASE << 3); \
  79951. if (a >= (BASE << 2)) a -= (BASE << 2); \
  79952. if (a >= (BASE << 1)) a -= (BASE << 1); \
  79953. if (a >= BASE) a -= BASE; \
  79954. } while (0)
  79955. #else
  79956. # define MOD(a) a %= BASE
  79957. # define MOD4(a) a %= BASE
  79958. #endif
  79959. /* ========================================================================= */
  79960. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  79961. {
  79962. unsigned long sum2;
  79963. unsigned n;
  79964. /* split Adler-32 into component sums */
  79965. sum2 = (adler >> 16) & 0xffff;
  79966. adler &= 0xffff;
  79967. /* in case user likes doing a byte at a time, keep it fast */
  79968. if (len == 1) {
  79969. adler += buf[0];
  79970. if (adler >= BASE)
  79971. adler -= BASE;
  79972. sum2 += adler;
  79973. if (sum2 >= BASE)
  79974. sum2 -= BASE;
  79975. return adler | (sum2 << 16);
  79976. }
  79977. /* initial Adler-32 value (deferred check for len == 1 speed) */
  79978. if (buf == Z_NULL)
  79979. return 1L;
  79980. /* in case short lengths are provided, keep it somewhat fast */
  79981. if (len < 16) {
  79982. while (len--) {
  79983. adler += *buf++;
  79984. sum2 += adler;
  79985. }
  79986. if (adler >= BASE)
  79987. adler -= BASE;
  79988. MOD4(sum2); /* only added so many BASE's */
  79989. return adler | (sum2 << 16);
  79990. }
  79991. /* do length NMAX blocks -- requires just one modulo operation */
  79992. while (len >= NMAX) {
  79993. len -= NMAX;
  79994. n = NMAX / 16; /* NMAX is divisible by 16 */
  79995. do {
  79996. DO16(buf); /* 16 sums unrolled */
  79997. buf += 16;
  79998. } while (--n);
  79999. MOD(adler);
  80000. MOD(sum2);
  80001. }
  80002. /* do remaining bytes (less than NMAX, still just one modulo) */
  80003. if (len) { /* avoid modulos if none remaining */
  80004. while (len >= 16) {
  80005. len -= 16;
  80006. DO16(buf);
  80007. buf += 16;
  80008. }
  80009. while (len--) {
  80010. adler += *buf++;
  80011. sum2 += adler;
  80012. }
  80013. MOD(adler);
  80014. MOD(sum2);
  80015. }
  80016. /* return recombined sums */
  80017. return adler | (sum2 << 16);
  80018. }
  80019. /* ========================================================================= */
  80020. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  80021. {
  80022. unsigned long sum1;
  80023. unsigned long sum2;
  80024. unsigned rem;
  80025. /* the derivation of this formula is left as an exercise for the reader */
  80026. rem = (unsigned)(len2 % BASE);
  80027. sum1 = adler1 & 0xffff;
  80028. sum2 = rem * sum1;
  80029. MOD(sum2);
  80030. sum1 += (adler2 & 0xffff) + BASE - 1;
  80031. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  80032. if (sum1 > BASE) sum1 -= BASE;
  80033. if (sum1 > BASE) sum1 -= BASE;
  80034. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  80035. if (sum2 > BASE) sum2 -= BASE;
  80036. return sum1 | (sum2 << 16);
  80037. }
  80038. /*** End of inlined file: adler32.c ***/
  80039. /*** Start of inlined file: compress.c ***/
  80040. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80041. #define ZLIB_INTERNAL
  80042. /* ===========================================================================
  80043. Compresses the source buffer into the destination buffer. The level
  80044. parameter has the same meaning as in deflateInit. sourceLen is the byte
  80045. length of the source buffer. Upon entry, destLen is the total size of the
  80046. destination buffer, which must be at least 0.1% larger than sourceLen plus
  80047. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  80048. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  80049. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  80050. Z_STREAM_ERROR if the level parameter is invalid.
  80051. */
  80052. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  80053. uLong sourceLen, int level)
  80054. {
  80055. z_stream stream;
  80056. int err;
  80057. stream.next_in = (Bytef*)source;
  80058. stream.avail_in = (uInt)sourceLen;
  80059. #ifdef MAXSEG_64K
  80060. /* Check for source > 64K on 16-bit machine: */
  80061. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80062. #endif
  80063. stream.next_out = dest;
  80064. stream.avail_out = (uInt)*destLen;
  80065. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80066. stream.zalloc = (alloc_func)0;
  80067. stream.zfree = (free_func)0;
  80068. stream.opaque = (voidpf)0;
  80069. err = deflateInit(&stream, level);
  80070. if (err != Z_OK) return err;
  80071. err = deflate(&stream, Z_FINISH);
  80072. if (err != Z_STREAM_END) {
  80073. deflateEnd(&stream);
  80074. return err == Z_OK ? Z_BUF_ERROR : err;
  80075. }
  80076. *destLen = stream.total_out;
  80077. err = deflateEnd(&stream);
  80078. return err;
  80079. }
  80080. /* ===========================================================================
  80081. */
  80082. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  80083. {
  80084. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  80085. }
  80086. /* ===========================================================================
  80087. If the default memLevel or windowBits for deflateInit() is changed, then
  80088. this function needs to be updated.
  80089. */
  80090. uLong ZEXPORT compressBound (uLong sourceLen)
  80091. {
  80092. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  80093. }
  80094. /*** End of inlined file: compress.c ***/
  80095. #undef DO1
  80096. #undef DO8
  80097. /*** Start of inlined file: crc32.c ***/
  80098. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80099. /*
  80100. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  80101. protection on the static variables used to control the first-use generation
  80102. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  80103. first call get_crc_table() to initialize the tables before allowing more than
  80104. one thread to use crc32().
  80105. */
  80106. #ifdef MAKECRCH
  80107. # include <stdio.h>
  80108. # ifndef DYNAMIC_CRC_TABLE
  80109. # define DYNAMIC_CRC_TABLE
  80110. # endif /* !DYNAMIC_CRC_TABLE */
  80111. #endif /* MAKECRCH */
  80112. /*** Start of inlined file: zutil.h ***/
  80113. /* WARNING: this file should *not* be used by applications. It is
  80114. part of the implementation of the compression library and is
  80115. subject to change. Applications should only use zlib.h.
  80116. */
  80117. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80118. #ifndef ZUTIL_H
  80119. #define ZUTIL_H
  80120. #define ZLIB_INTERNAL
  80121. #ifdef STDC
  80122. # ifndef _WIN32_WCE
  80123. # include <stddef.h>
  80124. # endif
  80125. # include <string.h>
  80126. # include <stdlib.h>
  80127. #endif
  80128. #ifdef NO_ERRNO_H
  80129. # ifdef _WIN32_WCE
  80130. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80131. * errno. We define it as a global variable to simplify porting.
  80132. * Its value is always 0 and should not be used. We rename it to
  80133. * avoid conflict with other libraries that use the same workaround.
  80134. */
  80135. # define errno z_errno
  80136. # endif
  80137. extern int errno;
  80138. #else
  80139. # ifndef _WIN32_WCE
  80140. # include <errno.h>
  80141. # endif
  80142. #endif
  80143. #ifndef local
  80144. # define local static
  80145. #endif
  80146. /* compile with -Dlocal if your debugger can't find static symbols */
  80147. typedef unsigned char uch;
  80148. typedef uch FAR uchf;
  80149. typedef unsigned short ush;
  80150. typedef ush FAR ushf;
  80151. typedef unsigned long ulg;
  80152. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  80153. /* (size given to avoid silly warnings with Visual C++) */
  80154. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  80155. #define ERR_RETURN(strm,err) \
  80156. return (strm->msg = (char*)ERR_MSG(err), (err))
  80157. /* To be used only when the state is known to be valid */
  80158. /* common constants */
  80159. #ifndef DEF_WBITS
  80160. # define DEF_WBITS MAX_WBITS
  80161. #endif
  80162. /* default windowBits for decompression. MAX_WBITS is for compression only */
  80163. #if MAX_MEM_LEVEL >= 8
  80164. # define DEF_MEM_LEVEL 8
  80165. #else
  80166. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  80167. #endif
  80168. /* default memLevel */
  80169. #define STORED_BLOCK 0
  80170. #define STATIC_TREES 1
  80171. #define DYN_TREES 2
  80172. /* The three kinds of block type */
  80173. #define MIN_MATCH 3
  80174. #define MAX_MATCH 258
  80175. /* The minimum and maximum match lengths */
  80176. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  80177. /* target dependencies */
  80178. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  80179. # define OS_CODE 0x00
  80180. # if defined(__TURBOC__) || defined(__BORLANDC__)
  80181. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  80182. /* Allow compilation with ANSI keywords only enabled */
  80183. void _Cdecl farfree( void *block );
  80184. void *_Cdecl farmalloc( unsigned long nbytes );
  80185. # else
  80186. # include <alloc.h>
  80187. # endif
  80188. # else /* MSC or DJGPP */
  80189. # include <malloc.h>
  80190. # endif
  80191. #endif
  80192. #ifdef AMIGA
  80193. # define OS_CODE 0x01
  80194. #endif
  80195. #if defined(VAXC) || defined(VMS)
  80196. # define OS_CODE 0x02
  80197. # define F_OPEN(name, mode) \
  80198. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  80199. #endif
  80200. #if defined(ATARI) || defined(atarist)
  80201. # define OS_CODE 0x05
  80202. #endif
  80203. #ifdef OS2
  80204. # define OS_CODE 0x06
  80205. # ifdef M_I86
  80206. #include <malloc.h>
  80207. # endif
  80208. #endif
  80209. #if defined(MACOS) || TARGET_OS_MAC
  80210. # define OS_CODE 0x07
  80211. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  80212. # include <unix.h> /* for fdopen */
  80213. # else
  80214. # ifndef fdopen
  80215. # define fdopen(fd,mode) NULL /* No fdopen() */
  80216. # endif
  80217. # endif
  80218. #endif
  80219. #ifdef TOPS20
  80220. # define OS_CODE 0x0a
  80221. #endif
  80222. #ifdef WIN32
  80223. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  80224. # define OS_CODE 0x0b
  80225. # endif
  80226. #endif
  80227. #ifdef __50SERIES /* Prime/PRIMOS */
  80228. # define OS_CODE 0x0f
  80229. #endif
  80230. #if defined(_BEOS_) || defined(RISCOS)
  80231. # define fdopen(fd,mode) NULL /* No fdopen() */
  80232. #endif
  80233. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  80234. # if defined(_WIN32_WCE)
  80235. # define fdopen(fd,mode) NULL /* No fdopen() */
  80236. # ifndef _PTRDIFF_T_DEFINED
  80237. typedef int ptrdiff_t;
  80238. # define _PTRDIFF_T_DEFINED
  80239. # endif
  80240. # else
  80241. # define fdopen(fd,type) _fdopen(fd,type)
  80242. # endif
  80243. #endif
  80244. /* common defaults */
  80245. #ifndef OS_CODE
  80246. # define OS_CODE 0x03 /* assume Unix */
  80247. #endif
  80248. #ifndef F_OPEN
  80249. # define F_OPEN(name, mode) fopen((name), (mode))
  80250. #endif
  80251. /* functions */
  80252. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  80253. # ifndef HAVE_VSNPRINTF
  80254. # define HAVE_VSNPRINTF
  80255. # endif
  80256. #endif
  80257. #if defined(__CYGWIN__)
  80258. # ifndef HAVE_VSNPRINTF
  80259. # define HAVE_VSNPRINTF
  80260. # endif
  80261. #endif
  80262. #ifndef HAVE_VSNPRINTF
  80263. # ifdef MSDOS
  80264. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  80265. but for now we just assume it doesn't. */
  80266. # define NO_vsnprintf
  80267. # endif
  80268. # ifdef __TURBOC__
  80269. # define NO_vsnprintf
  80270. # endif
  80271. # ifdef WIN32
  80272. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  80273. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  80274. # define vsnprintf _vsnprintf
  80275. # endif
  80276. # endif
  80277. # ifdef __SASC
  80278. # define NO_vsnprintf
  80279. # endif
  80280. #endif
  80281. #ifdef VMS
  80282. # define NO_vsnprintf
  80283. #endif
  80284. #if defined(pyr)
  80285. # define NO_MEMCPY
  80286. #endif
  80287. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  80288. /* Use our own functions for small and medium model with MSC <= 5.0.
  80289. * You may have to use the same strategy for Borland C (untested).
  80290. * The __SC__ check is for Symantec.
  80291. */
  80292. # define NO_MEMCPY
  80293. #endif
  80294. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  80295. # define HAVE_MEMCPY
  80296. #endif
  80297. #ifdef HAVE_MEMCPY
  80298. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  80299. # define zmemcpy _fmemcpy
  80300. # define zmemcmp _fmemcmp
  80301. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  80302. # else
  80303. # define zmemcpy memcpy
  80304. # define zmemcmp memcmp
  80305. # define zmemzero(dest, len) memset(dest, 0, len)
  80306. # endif
  80307. #else
  80308. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  80309. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  80310. extern void zmemzero OF((Bytef* dest, uInt len));
  80311. #endif
  80312. /* Diagnostic functions */
  80313. #ifdef DEBUG
  80314. # include <stdio.h>
  80315. extern int z_verbose;
  80316. extern void z_error OF((const char *m));
  80317. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  80318. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  80319. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  80320. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  80321. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  80322. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  80323. #else
  80324. # define Assert(cond,msg)
  80325. # define Trace(x)
  80326. # define Tracev(x)
  80327. # define Tracevv(x)
  80328. # define Tracec(c,x)
  80329. # define Tracecv(c,x)
  80330. #endif
  80331. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  80332. void zcfree OF((voidpf opaque, voidpf ptr));
  80333. #define ZALLOC(strm, items, size) \
  80334. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  80335. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  80336. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  80337. #endif /* ZUTIL_H */
  80338. /*** End of inlined file: zutil.h ***/
  80339. /* for STDC and FAR definitions */
  80340. #define local static
  80341. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  80342. #ifndef NOBYFOUR
  80343. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  80344. # include <limits.h>
  80345. # define BYFOUR
  80346. # if (UINT_MAX == 0xffffffffUL)
  80347. typedef unsigned int u4;
  80348. # else
  80349. # if (ULONG_MAX == 0xffffffffUL)
  80350. typedef unsigned long u4;
  80351. # else
  80352. # if (USHRT_MAX == 0xffffffffUL)
  80353. typedef unsigned short u4;
  80354. # else
  80355. # undef BYFOUR /* can't find a four-byte integer type! */
  80356. # endif
  80357. # endif
  80358. # endif
  80359. # endif /* STDC */
  80360. #endif /* !NOBYFOUR */
  80361. /* Definitions for doing the crc four data bytes at a time. */
  80362. #ifdef BYFOUR
  80363. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  80364. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  80365. local unsigned long crc32_little OF((unsigned long,
  80366. const unsigned char FAR *, unsigned));
  80367. local unsigned long crc32_big OF((unsigned long,
  80368. const unsigned char FAR *, unsigned));
  80369. # define TBLS 8
  80370. #else
  80371. # define TBLS 1
  80372. #endif /* BYFOUR */
  80373. /* Local functions for crc concatenation */
  80374. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  80375. unsigned long vec));
  80376. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  80377. #ifdef DYNAMIC_CRC_TABLE
  80378. local volatile int crc_table_empty = 1;
  80379. local unsigned long FAR crc_table[TBLS][256];
  80380. local void make_crc_table OF((void));
  80381. #ifdef MAKECRCH
  80382. local void write_table OF((FILE *, const unsigned long FAR *));
  80383. #endif /* MAKECRCH */
  80384. /*
  80385. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  80386. 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.
  80387. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  80388. with the lowest powers in the most significant bit. Then adding polynomials
  80389. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  80390. one. If we call the above polynomial p, and represent a byte as the
  80391. polynomial q, also with the lowest power in the most significant bit (so the
  80392. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  80393. where a mod b means the remainder after dividing a by b.
  80394. This calculation is done using the shift-register method of multiplying and
  80395. taking the remainder. The register is initialized to zero, and for each
  80396. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  80397. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  80398. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  80399. out is a one). We start with the highest power (least significant bit) of
  80400. q and repeat for all eight bits of q.
  80401. The first table is simply the CRC of all possible eight bit values. This is
  80402. all the information needed to generate CRCs on data a byte at a time for all
  80403. combinations of CRC register values and incoming bytes. The remaining tables
  80404. allow for word-at-a-time CRC calculation for both big-endian and little-
  80405. endian machines, where a word is four bytes.
  80406. */
  80407. local void make_crc_table()
  80408. {
  80409. unsigned long c;
  80410. int n, k;
  80411. unsigned long poly; /* polynomial exclusive-or pattern */
  80412. /* terms of polynomial defining this crc (except x^32): */
  80413. static volatile int first = 1; /* flag to limit concurrent making */
  80414. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  80415. /* See if another task is already doing this (not thread-safe, but better
  80416. than nothing -- significantly reduces duration of vulnerability in
  80417. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  80418. if (first) {
  80419. first = 0;
  80420. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  80421. poly = 0UL;
  80422. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  80423. poly |= 1UL << (31 - p[n]);
  80424. /* generate a crc for every 8-bit value */
  80425. for (n = 0; n < 256; n++) {
  80426. c = (unsigned long)n;
  80427. for (k = 0; k < 8; k++)
  80428. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  80429. crc_table[0][n] = c;
  80430. }
  80431. #ifdef BYFOUR
  80432. /* generate crc for each value followed by one, two, and three zeros,
  80433. and then the byte reversal of those as well as the first table */
  80434. for (n = 0; n < 256; n++) {
  80435. c = crc_table[0][n];
  80436. crc_table[4][n] = REV(c);
  80437. for (k = 1; k < 4; k++) {
  80438. c = crc_table[0][c & 0xff] ^ (c >> 8);
  80439. crc_table[k][n] = c;
  80440. crc_table[k + 4][n] = REV(c);
  80441. }
  80442. }
  80443. #endif /* BYFOUR */
  80444. crc_table_empty = 0;
  80445. }
  80446. else { /* not first */
  80447. /* wait for the other guy to finish (not efficient, but rare) */
  80448. while (crc_table_empty)
  80449. ;
  80450. }
  80451. #ifdef MAKECRCH
  80452. /* write out CRC tables to crc32.h */
  80453. {
  80454. FILE *out;
  80455. out = fopen("crc32.h", "w");
  80456. if (out == NULL) return;
  80457. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  80458. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  80459. fprintf(out, "local const unsigned long FAR ");
  80460. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  80461. write_table(out, crc_table[0]);
  80462. # ifdef BYFOUR
  80463. fprintf(out, "#ifdef BYFOUR\n");
  80464. for (k = 1; k < 8; k++) {
  80465. fprintf(out, " },\n {\n");
  80466. write_table(out, crc_table[k]);
  80467. }
  80468. fprintf(out, "#endif\n");
  80469. # endif /* BYFOUR */
  80470. fprintf(out, " }\n};\n");
  80471. fclose(out);
  80472. }
  80473. #endif /* MAKECRCH */
  80474. }
  80475. #ifdef MAKECRCH
  80476. local void write_table(out, table)
  80477. FILE *out;
  80478. const unsigned long FAR *table;
  80479. {
  80480. int n;
  80481. for (n = 0; n < 256; n++)
  80482. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  80483. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  80484. }
  80485. #endif /* MAKECRCH */
  80486. #else /* !DYNAMIC_CRC_TABLE */
  80487. /* ========================================================================
  80488. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  80489. */
  80490. /*** Start of inlined file: crc32.h ***/
  80491. local const unsigned long FAR crc_table[TBLS][256] =
  80492. {
  80493. {
  80494. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  80495. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  80496. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  80497. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  80498. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  80499. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  80500. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  80501. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  80502. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  80503. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  80504. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  80505. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  80506. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  80507. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  80508. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  80509. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  80510. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  80511. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  80512. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  80513. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  80514. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  80515. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  80516. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  80517. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  80518. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  80519. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  80520. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  80521. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  80522. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  80523. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  80524. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  80525. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  80526. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  80527. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  80528. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  80529. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  80530. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  80531. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  80532. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  80533. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  80534. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  80535. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  80536. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  80537. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  80538. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  80539. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  80540. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  80541. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  80542. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  80543. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  80544. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  80545. 0x2d02ef8dUL
  80546. #ifdef BYFOUR
  80547. },
  80548. {
  80549. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  80550. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  80551. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  80552. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  80553. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  80554. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  80555. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  80556. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  80557. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  80558. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  80559. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  80560. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  80561. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  80562. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  80563. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  80564. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  80565. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  80566. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  80567. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  80568. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  80569. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  80570. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  80571. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  80572. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  80573. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  80574. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  80575. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  80576. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  80577. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  80578. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  80579. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  80580. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  80581. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  80582. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  80583. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  80584. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  80585. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  80586. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  80587. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  80588. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  80589. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  80590. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  80591. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  80592. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  80593. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  80594. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  80595. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  80596. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  80597. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  80598. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  80599. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  80600. 0x9324fd72UL
  80601. },
  80602. {
  80603. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  80604. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  80605. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  80606. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  80607. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  80608. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  80609. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  80610. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  80611. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  80612. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  80613. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  80614. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  80615. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  80616. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  80617. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  80618. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  80619. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  80620. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  80621. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  80622. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  80623. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  80624. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  80625. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  80626. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  80627. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  80628. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  80629. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  80630. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  80631. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  80632. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  80633. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  80634. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  80635. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  80636. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  80637. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  80638. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  80639. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  80640. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  80641. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  80642. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  80643. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  80644. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  80645. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  80646. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  80647. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  80648. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  80649. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  80650. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  80651. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  80652. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  80653. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  80654. 0xbe9834edUL
  80655. },
  80656. {
  80657. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  80658. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  80659. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  80660. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  80661. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  80662. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  80663. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  80664. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  80665. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  80666. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  80667. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  80668. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  80669. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  80670. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  80671. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  80672. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  80673. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  80674. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  80675. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  80676. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  80677. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  80678. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  80679. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  80680. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  80681. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  80682. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  80683. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  80684. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  80685. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  80686. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  80687. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  80688. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  80689. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  80690. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  80691. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  80692. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  80693. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  80694. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  80695. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  80696. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  80697. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  80698. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  80699. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  80700. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  80701. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  80702. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  80703. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  80704. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  80705. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  80706. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  80707. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  80708. 0xde0506f1UL
  80709. },
  80710. {
  80711. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  80712. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  80713. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  80714. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  80715. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  80716. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  80717. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  80718. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  80719. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  80720. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  80721. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  80722. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  80723. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  80724. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  80725. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  80726. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  80727. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  80728. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  80729. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  80730. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  80731. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  80732. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  80733. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  80734. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  80735. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  80736. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  80737. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  80738. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  80739. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  80740. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  80741. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  80742. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  80743. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  80744. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  80745. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  80746. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  80747. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  80748. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  80749. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  80750. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  80751. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  80752. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  80753. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  80754. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  80755. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  80756. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  80757. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  80758. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  80759. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  80760. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  80761. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  80762. 0x8def022dUL
  80763. },
  80764. {
  80765. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  80766. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  80767. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  80768. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  80769. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  80770. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  80771. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  80772. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  80773. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  80774. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  80775. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  80776. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  80777. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  80778. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  80779. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  80780. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  80781. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  80782. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  80783. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  80784. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  80785. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  80786. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  80787. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  80788. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  80789. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  80790. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  80791. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  80792. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  80793. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  80794. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  80795. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  80796. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  80797. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  80798. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  80799. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  80800. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  80801. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  80802. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  80803. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  80804. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  80805. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  80806. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  80807. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  80808. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  80809. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  80810. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  80811. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  80812. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  80813. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  80814. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  80815. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  80816. 0x72fd2493UL
  80817. },
  80818. {
  80819. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  80820. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  80821. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  80822. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  80823. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  80824. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  80825. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  80826. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  80827. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  80828. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  80829. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  80830. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  80831. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  80832. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  80833. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  80834. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  80835. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  80836. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  80837. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  80838. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  80839. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  80840. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  80841. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  80842. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  80843. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  80844. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  80845. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  80846. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  80847. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  80848. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  80849. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  80850. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  80851. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  80852. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  80853. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  80854. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  80855. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  80856. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  80857. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  80858. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  80859. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  80860. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  80861. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  80862. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  80863. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  80864. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  80865. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  80866. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  80867. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  80868. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  80869. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  80870. 0xed3498beUL
  80871. },
  80872. {
  80873. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  80874. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  80875. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  80876. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  80877. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  80878. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  80879. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  80880. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  80881. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  80882. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  80883. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  80884. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  80885. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  80886. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  80887. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  80888. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  80889. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  80890. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  80891. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  80892. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  80893. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  80894. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  80895. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  80896. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  80897. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  80898. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  80899. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  80900. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  80901. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  80902. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  80903. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  80904. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  80905. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  80906. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  80907. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  80908. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  80909. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  80910. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  80911. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  80912. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  80913. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  80914. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  80915. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  80916. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  80917. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  80918. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  80919. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  80920. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  80921. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  80922. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  80923. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  80924. 0xf10605deUL
  80925. #endif
  80926. }
  80927. };
  80928. /*** End of inlined file: crc32.h ***/
  80929. #endif /* DYNAMIC_CRC_TABLE */
  80930. /* =========================================================================
  80931. * This function can be used by asm versions of crc32()
  80932. */
  80933. const unsigned long FAR * ZEXPORT get_crc_table()
  80934. {
  80935. #ifdef DYNAMIC_CRC_TABLE
  80936. if (crc_table_empty)
  80937. make_crc_table();
  80938. #endif /* DYNAMIC_CRC_TABLE */
  80939. return (const unsigned long FAR *)crc_table;
  80940. }
  80941. /* ========================================================================= */
  80942. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  80943. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  80944. /* ========================================================================= */
  80945. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80946. {
  80947. if (buf == Z_NULL) return 0UL;
  80948. #ifdef DYNAMIC_CRC_TABLE
  80949. if (crc_table_empty)
  80950. make_crc_table();
  80951. #endif /* DYNAMIC_CRC_TABLE */
  80952. #ifdef BYFOUR
  80953. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  80954. u4 endian;
  80955. endian = 1;
  80956. if (*((unsigned char *)(&endian)))
  80957. return crc32_little(crc, buf, len);
  80958. else
  80959. return crc32_big(crc, buf, len);
  80960. }
  80961. #endif /* BYFOUR */
  80962. crc = crc ^ 0xffffffffUL;
  80963. while (len >= 8) {
  80964. DO8;
  80965. len -= 8;
  80966. }
  80967. if (len) do {
  80968. DO1;
  80969. } while (--len);
  80970. return crc ^ 0xffffffffUL;
  80971. }
  80972. #ifdef BYFOUR
  80973. /* ========================================================================= */
  80974. #define DOLIT4 c ^= *buf4++; \
  80975. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  80976. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  80977. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  80978. /* ========================================================================= */
  80979. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  80980. {
  80981. register u4 c;
  80982. register const u4 FAR *buf4;
  80983. c = (u4)crc;
  80984. c = ~c;
  80985. while (len && ((ptrdiff_t)buf & 3)) {
  80986. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  80987. len--;
  80988. }
  80989. buf4 = (const u4 FAR *)(const void FAR *)buf;
  80990. while (len >= 32) {
  80991. DOLIT32;
  80992. len -= 32;
  80993. }
  80994. while (len >= 4) {
  80995. DOLIT4;
  80996. len -= 4;
  80997. }
  80998. buf = (const unsigned char FAR *)buf4;
  80999. if (len) do {
  81000. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  81001. } while (--len);
  81002. c = ~c;
  81003. return (unsigned long)c;
  81004. }
  81005. /* ========================================================================= */
  81006. #define DOBIG4 c ^= *++buf4; \
  81007. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  81008. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  81009. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  81010. /* ========================================================================= */
  81011. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  81012. {
  81013. register u4 c;
  81014. register const u4 FAR *buf4;
  81015. c = REV((u4)crc);
  81016. c = ~c;
  81017. while (len && ((ptrdiff_t)buf & 3)) {
  81018. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81019. len--;
  81020. }
  81021. buf4 = (const u4 FAR *)(const void FAR *)buf;
  81022. buf4--;
  81023. while (len >= 32) {
  81024. DOBIG32;
  81025. len -= 32;
  81026. }
  81027. while (len >= 4) {
  81028. DOBIG4;
  81029. len -= 4;
  81030. }
  81031. buf4++;
  81032. buf = (const unsigned char FAR *)buf4;
  81033. if (len) do {
  81034. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  81035. } while (--len);
  81036. c = ~c;
  81037. return (unsigned long)(REV(c));
  81038. }
  81039. #endif /* BYFOUR */
  81040. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  81041. /* ========================================================================= */
  81042. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  81043. {
  81044. unsigned long sum;
  81045. sum = 0;
  81046. while (vec) {
  81047. if (vec & 1)
  81048. sum ^= *mat;
  81049. vec >>= 1;
  81050. mat++;
  81051. }
  81052. return sum;
  81053. }
  81054. /* ========================================================================= */
  81055. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  81056. {
  81057. int n;
  81058. for (n = 0; n < GF2_DIM; n++)
  81059. square[n] = gf2_matrix_times(mat, mat[n]);
  81060. }
  81061. /* ========================================================================= */
  81062. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  81063. {
  81064. int n;
  81065. unsigned long row;
  81066. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  81067. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  81068. /* degenerate case */
  81069. if (len2 == 0)
  81070. return crc1;
  81071. /* put operator for one zero bit in odd */
  81072. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  81073. row = 1;
  81074. for (n = 1; n < GF2_DIM; n++) {
  81075. odd[n] = row;
  81076. row <<= 1;
  81077. }
  81078. /* put operator for two zero bits in even */
  81079. gf2_matrix_square(even, odd);
  81080. /* put operator for four zero bits in odd */
  81081. gf2_matrix_square(odd, even);
  81082. /* apply len2 zeros to crc1 (first square will put the operator for one
  81083. zero byte, eight zero bits, in even) */
  81084. do {
  81085. /* apply zeros operator for this bit of len2 */
  81086. gf2_matrix_square(even, odd);
  81087. if (len2 & 1)
  81088. crc1 = gf2_matrix_times(even, crc1);
  81089. len2 >>= 1;
  81090. /* if no more bits set, then done */
  81091. if (len2 == 0)
  81092. break;
  81093. /* another iteration of the loop with odd and even swapped */
  81094. gf2_matrix_square(odd, even);
  81095. if (len2 & 1)
  81096. crc1 = gf2_matrix_times(odd, crc1);
  81097. len2 >>= 1;
  81098. /* if no more bits set, then done */
  81099. } while (len2 != 0);
  81100. /* return combined crc */
  81101. crc1 ^= crc2;
  81102. return crc1;
  81103. }
  81104. /*** End of inlined file: crc32.c ***/
  81105. /*** Start of inlined file: deflate.c ***/
  81106. /*
  81107. * ALGORITHM
  81108. *
  81109. * The "deflation" process depends on being able to identify portions
  81110. * of the input text which are identical to earlier input (within a
  81111. * sliding window trailing behind the input currently being processed).
  81112. *
  81113. * The most straightforward technique turns out to be the fastest for
  81114. * most input files: try all possible matches and select the longest.
  81115. * The key feature of this algorithm is that insertions into the string
  81116. * dictionary are very simple and thus fast, and deletions are avoided
  81117. * completely. Insertions are performed at each input character, whereas
  81118. * string matches are performed only when the previous match ends. So it
  81119. * is preferable to spend more time in matches to allow very fast string
  81120. * insertions and avoid deletions. The matching algorithm for small
  81121. * strings is inspired from that of Rabin & Karp. A brute force approach
  81122. * is used to find longer strings when a small match has been found.
  81123. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  81124. * (by Leonid Broukhis).
  81125. * A previous version of this file used a more sophisticated algorithm
  81126. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  81127. * time, but has a larger average cost, uses more memory and is patented.
  81128. * However the F&G algorithm may be faster for some highly redundant
  81129. * files if the parameter max_chain_length (described below) is too large.
  81130. *
  81131. * ACKNOWLEDGEMENTS
  81132. *
  81133. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  81134. * I found it in 'freeze' written by Leonid Broukhis.
  81135. * Thanks to many people for bug reports and testing.
  81136. *
  81137. * REFERENCES
  81138. *
  81139. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  81140. * Available in http://www.ietf.org/rfc/rfc1951.txt
  81141. *
  81142. * A description of the Rabin and Karp algorithm is given in the book
  81143. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  81144. *
  81145. * Fiala,E.R., and Greene,D.H.
  81146. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  81147. *
  81148. */
  81149. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81150. /*** Start of inlined file: deflate.h ***/
  81151. /* WARNING: this file should *not* be used by applications. It is
  81152. part of the implementation of the compression library and is
  81153. subject to change. Applications should only use zlib.h.
  81154. */
  81155. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  81156. #ifndef DEFLATE_H
  81157. #define DEFLATE_H
  81158. /* define NO_GZIP when compiling if you want to disable gzip header and
  81159. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  81160. the crc code when it is not needed. For shared libraries, gzip encoding
  81161. should be left enabled. */
  81162. #ifndef NO_GZIP
  81163. # define GZIP
  81164. #endif
  81165. #define NO_DUMMY_DECL
  81166. /* ===========================================================================
  81167. * Internal compression state.
  81168. */
  81169. #define LENGTH_CODES 29
  81170. /* number of length codes, not counting the special END_BLOCK code */
  81171. #define LITERALS 256
  81172. /* number of literal bytes 0..255 */
  81173. #define L_CODES (LITERALS+1+LENGTH_CODES)
  81174. /* number of Literal or Length codes, including the END_BLOCK code */
  81175. #define D_CODES 30
  81176. /* number of distance codes */
  81177. #define BL_CODES 19
  81178. /* number of codes used to transfer the bit lengths */
  81179. #define HEAP_SIZE (2*L_CODES+1)
  81180. /* maximum heap size */
  81181. #define MAX_BITS 15
  81182. /* All codes must not exceed MAX_BITS bits */
  81183. #define INIT_STATE 42
  81184. #define EXTRA_STATE 69
  81185. #define NAME_STATE 73
  81186. #define COMMENT_STATE 91
  81187. #define HCRC_STATE 103
  81188. #define BUSY_STATE 113
  81189. #define FINISH_STATE 666
  81190. /* Stream status */
  81191. /* Data structure describing a single value and its code string. */
  81192. typedef struct ct_data_s {
  81193. union {
  81194. ush freq; /* frequency count */
  81195. ush code; /* bit string */
  81196. } fc;
  81197. union {
  81198. ush dad; /* father node in Huffman tree */
  81199. ush len; /* length of bit string */
  81200. } dl;
  81201. } FAR ct_data;
  81202. #define Freq fc.freq
  81203. #define Code fc.code
  81204. #define Dad dl.dad
  81205. #define Len dl.len
  81206. typedef struct static_tree_desc_s static_tree_desc;
  81207. typedef struct tree_desc_s {
  81208. ct_data *dyn_tree; /* the dynamic tree */
  81209. int max_code; /* largest code with non zero frequency */
  81210. static_tree_desc *stat_desc; /* the corresponding static tree */
  81211. } FAR tree_desc;
  81212. typedef ush Pos;
  81213. typedef Pos FAR Posf;
  81214. typedef unsigned IPos;
  81215. /* A Pos is an index in the character window. We use short instead of int to
  81216. * save space in the various tables. IPos is used only for parameter passing.
  81217. */
  81218. typedef struct internal_state {
  81219. z_streamp strm; /* pointer back to this zlib stream */
  81220. int status; /* as the name implies */
  81221. Bytef *pending_buf; /* output still pending */
  81222. ulg pending_buf_size; /* size of pending_buf */
  81223. Bytef *pending_out; /* next pending byte to output to the stream */
  81224. uInt pending; /* nb of bytes in the pending buffer */
  81225. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  81226. gz_headerp gzhead; /* gzip header information to write */
  81227. uInt gzindex; /* where in extra, name, or comment */
  81228. Byte method; /* STORED (for zip only) or DEFLATED */
  81229. int last_flush; /* value of flush param for previous deflate call */
  81230. /* used by deflate.c: */
  81231. uInt w_size; /* LZ77 window size (32K by default) */
  81232. uInt w_bits; /* log2(w_size) (8..16) */
  81233. uInt w_mask; /* w_size - 1 */
  81234. Bytef *window;
  81235. /* Sliding window. Input bytes are read into the second half of the window,
  81236. * and move to the first half later to keep a dictionary of at least wSize
  81237. * bytes. With this organization, matches are limited to a distance of
  81238. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  81239. * performed with a length multiple of the block size. Also, it limits
  81240. * the window size to 64K, which is quite useful on MSDOS.
  81241. * To do: use the user input buffer as sliding window.
  81242. */
  81243. ulg window_size;
  81244. /* Actual size of window: 2*wSize, except when the user input buffer
  81245. * is directly used as sliding window.
  81246. */
  81247. Posf *prev;
  81248. /* Link to older string with same hash index. To limit the size of this
  81249. * array to 64K, this link is maintained only for the last 32K strings.
  81250. * An index in this array is thus a window index modulo 32K.
  81251. */
  81252. Posf *head; /* Heads of the hash chains or NIL. */
  81253. uInt ins_h; /* hash index of string to be inserted */
  81254. uInt hash_size; /* number of elements in hash table */
  81255. uInt hash_bits; /* log2(hash_size) */
  81256. uInt hash_mask; /* hash_size-1 */
  81257. uInt hash_shift;
  81258. /* Number of bits by which ins_h must be shifted at each input
  81259. * step. It must be such that after MIN_MATCH steps, the oldest
  81260. * byte no longer takes part in the hash key, that is:
  81261. * hash_shift * MIN_MATCH >= hash_bits
  81262. */
  81263. long block_start;
  81264. /* Window position at the beginning of the current output block. Gets
  81265. * negative when the window is moved backwards.
  81266. */
  81267. uInt match_length; /* length of best match */
  81268. IPos prev_match; /* previous match */
  81269. int match_available; /* set if previous match exists */
  81270. uInt strstart; /* start of string to insert */
  81271. uInt match_start; /* start of matching string */
  81272. uInt lookahead; /* number of valid bytes ahead in window */
  81273. uInt prev_length;
  81274. /* Length of the best match at previous step. Matches not greater than this
  81275. * are discarded. This is used in the lazy match evaluation.
  81276. */
  81277. uInt max_chain_length;
  81278. /* To speed up deflation, hash chains are never searched beyond this
  81279. * length. A higher limit improves compression ratio but degrades the
  81280. * speed.
  81281. */
  81282. uInt max_lazy_match;
  81283. /* Attempt to find a better match only when the current match is strictly
  81284. * smaller than this value. This mechanism is used only for compression
  81285. * levels >= 4.
  81286. */
  81287. # define max_insert_length max_lazy_match
  81288. /* Insert new strings in the hash table only if the match length is not
  81289. * greater than this length. This saves time but degrades compression.
  81290. * max_insert_length is used only for compression levels <= 3.
  81291. */
  81292. int level; /* compression level (1..9) */
  81293. int strategy; /* favor or force Huffman coding*/
  81294. uInt good_match;
  81295. /* Use a faster search when the previous match is longer than this */
  81296. int nice_match; /* Stop searching when current match exceeds this */
  81297. /* used by trees.c: */
  81298. /* Didn't use ct_data typedef below to supress compiler warning */
  81299. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  81300. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  81301. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  81302. struct tree_desc_s l_desc; /* desc. for literal tree */
  81303. struct tree_desc_s d_desc; /* desc. for distance tree */
  81304. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  81305. ush bl_count[MAX_BITS+1];
  81306. /* number of codes at each bit length for an optimal tree */
  81307. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  81308. int heap_len; /* number of elements in the heap */
  81309. int heap_max; /* element of largest frequency */
  81310. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  81311. * The same heap array is used to build all trees.
  81312. */
  81313. uch depth[2*L_CODES+1];
  81314. /* Depth of each subtree used as tie breaker for trees of equal frequency
  81315. */
  81316. uchf *l_buf; /* buffer for literals or lengths */
  81317. uInt lit_bufsize;
  81318. /* Size of match buffer for literals/lengths. There are 4 reasons for
  81319. * limiting lit_bufsize to 64K:
  81320. * - frequencies can be kept in 16 bit counters
  81321. * - if compression is not successful for the first block, all input
  81322. * data is still in the window so we can still emit a stored block even
  81323. * when input comes from standard input. (This can also be done for
  81324. * all blocks if lit_bufsize is not greater than 32K.)
  81325. * - if compression is not successful for a file smaller than 64K, we can
  81326. * even emit a stored file instead of a stored block (saving 5 bytes).
  81327. * This is applicable only for zip (not gzip or zlib).
  81328. * - creating new Huffman trees less frequently may not provide fast
  81329. * adaptation to changes in the input data statistics. (Take for
  81330. * example a binary file with poorly compressible code followed by
  81331. * a highly compressible string table.) Smaller buffer sizes give
  81332. * fast adaptation but have of course the overhead of transmitting
  81333. * trees more frequently.
  81334. * - I can't count above 4
  81335. */
  81336. uInt last_lit; /* running index in l_buf */
  81337. ushf *d_buf;
  81338. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  81339. * the same number of elements. To use different lengths, an extra flag
  81340. * array would be necessary.
  81341. */
  81342. ulg opt_len; /* bit length of current block with optimal trees */
  81343. ulg static_len; /* bit length of current block with static trees */
  81344. uInt matches; /* number of string matches in current block */
  81345. int last_eob_len; /* bit length of EOB code for last block */
  81346. #ifdef DEBUG
  81347. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  81348. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  81349. #endif
  81350. ush bi_buf;
  81351. /* Output buffer. bits are inserted starting at the bottom (least
  81352. * significant bits).
  81353. */
  81354. int bi_valid;
  81355. /* Number of valid bits in bi_buf. All bits above the last valid bit
  81356. * are always zero.
  81357. */
  81358. } FAR deflate_state;
  81359. /* Output a byte on the stream.
  81360. * IN assertion: there is enough room in pending_buf.
  81361. */
  81362. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  81363. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81364. /* Minimum amount of lookahead, except at the end of the input file.
  81365. * See deflate.c for comments about the MIN_MATCH+1.
  81366. */
  81367. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  81368. /* In order to simplify the code, particularly on 16 bit machines, match
  81369. * distances are limited to MAX_DIST instead of WSIZE.
  81370. */
  81371. /* in trees.c */
  81372. void _tr_init OF((deflate_state *s));
  81373. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  81374. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81375. int eof));
  81376. void _tr_align OF((deflate_state *s));
  81377. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  81378. int eof));
  81379. #define d_code(dist) \
  81380. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  81381. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  81382. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  81383. * used.
  81384. */
  81385. #ifndef DEBUG
  81386. /* Inline versions of _tr_tally for speed: */
  81387. #if defined(GEN_TREES_H) || !defined(STDC)
  81388. extern uch _length_code[];
  81389. extern uch _dist_code[];
  81390. #else
  81391. extern const uch _length_code[];
  81392. extern const uch _dist_code[];
  81393. #endif
  81394. # define _tr_tally_lit(s, c, flush) \
  81395. { uch cc = (c); \
  81396. s->d_buf[s->last_lit] = 0; \
  81397. s->l_buf[s->last_lit++] = cc; \
  81398. s->dyn_ltree[cc].Freq++; \
  81399. flush = (s->last_lit == s->lit_bufsize-1); \
  81400. }
  81401. # define _tr_tally_dist(s, distance, length, flush) \
  81402. { uch len = (length); \
  81403. ush dist = (distance); \
  81404. s->d_buf[s->last_lit] = dist; \
  81405. s->l_buf[s->last_lit++] = len; \
  81406. dist--; \
  81407. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  81408. s->dyn_dtree[d_code(dist)].Freq++; \
  81409. flush = (s->last_lit == s->lit_bufsize-1); \
  81410. }
  81411. #else
  81412. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  81413. # define _tr_tally_dist(s, distance, length, flush) \
  81414. flush = _tr_tally(s, distance, length)
  81415. #endif
  81416. #endif /* DEFLATE_H */
  81417. /*** End of inlined file: deflate.h ***/
  81418. const char deflate_copyright[] =
  81419. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  81420. /*
  81421. If you use the zlib library in a product, an acknowledgment is welcome
  81422. in the documentation of your product. If for some reason you cannot
  81423. include such an acknowledgment, I would appreciate that you keep this
  81424. copyright string in the executable of your product.
  81425. */
  81426. /* ===========================================================================
  81427. * Function prototypes.
  81428. */
  81429. typedef enum {
  81430. need_more, /* block not completed, need more input or more output */
  81431. block_done, /* block flush performed */
  81432. finish_started, /* finish started, need only more output at next deflate */
  81433. finish_done /* finish done, accept no more input or output */
  81434. } block_state;
  81435. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  81436. /* Compression function. Returns the block state after the call. */
  81437. local void fill_window OF((deflate_state *s));
  81438. local block_state deflate_stored OF((deflate_state *s, int flush));
  81439. local block_state deflate_fast OF((deflate_state *s, int flush));
  81440. #ifndef FASTEST
  81441. local block_state deflate_slow OF((deflate_state *s, int flush));
  81442. #endif
  81443. local void lm_init OF((deflate_state *s));
  81444. local void putShortMSB OF((deflate_state *s, uInt b));
  81445. local void flush_pending OF((z_streamp strm));
  81446. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  81447. #ifndef FASTEST
  81448. #ifdef ASMV
  81449. void match_init OF((void)); /* asm code initialization */
  81450. uInt longest_match OF((deflate_state *s, IPos cur_match));
  81451. #else
  81452. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  81453. #endif
  81454. #endif
  81455. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  81456. #ifdef DEBUG
  81457. local void check_match OF((deflate_state *s, IPos start, IPos match,
  81458. int length));
  81459. #endif
  81460. /* ===========================================================================
  81461. * Local data
  81462. */
  81463. #define NIL 0
  81464. /* Tail of hash chains */
  81465. #ifndef TOO_FAR
  81466. # define TOO_FAR 4096
  81467. #endif
  81468. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  81469. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  81470. /* Minimum amount of lookahead, except at the end of the input file.
  81471. * See deflate.c for comments about the MIN_MATCH+1.
  81472. */
  81473. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  81474. * the desired pack level (0..9). The values given below have been tuned to
  81475. * exclude worst case performance for pathological files. Better values may be
  81476. * found for specific files.
  81477. */
  81478. typedef struct config_s {
  81479. ush good_length; /* reduce lazy search above this match length */
  81480. ush max_lazy; /* do not perform lazy search above this match length */
  81481. ush nice_length; /* quit search above this match length */
  81482. ush max_chain;
  81483. compress_func func;
  81484. } config;
  81485. #ifdef FASTEST
  81486. local const config configuration_table[2] = {
  81487. /* good lazy nice chain */
  81488. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81489. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  81490. #else
  81491. local const config configuration_table[10] = {
  81492. /* good lazy nice chain */
  81493. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  81494. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  81495. /* 2 */ {4, 5, 16, 8, deflate_fast},
  81496. /* 3 */ {4, 6, 32, 32, deflate_fast},
  81497. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  81498. /* 5 */ {8, 16, 32, 32, deflate_slow},
  81499. /* 6 */ {8, 16, 128, 128, deflate_slow},
  81500. /* 7 */ {8, 32, 128, 256, deflate_slow},
  81501. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  81502. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  81503. #endif
  81504. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  81505. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  81506. * meaning.
  81507. */
  81508. #define EQUAL 0
  81509. /* result of memcmp for equal strings */
  81510. #ifndef NO_DUMMY_DECL
  81511. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  81512. #endif
  81513. /* ===========================================================================
  81514. * Update a hash value with the given input byte
  81515. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  81516. * input characters, so that a running hash key can be computed from the
  81517. * previous key instead of complete recalculation each time.
  81518. */
  81519. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  81520. /* ===========================================================================
  81521. * Insert string str in the dictionary and set match_head to the previous head
  81522. * of the hash chain (the most recent string with same hash key). Return
  81523. * the previous length of the hash chain.
  81524. * If this file is compiled with -DFASTEST, the compression level is forced
  81525. * to 1, and no hash chains are maintained.
  81526. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  81527. * input characters and the first MIN_MATCH bytes of str are valid
  81528. * (except for the last MIN_MATCH-1 bytes of the input file).
  81529. */
  81530. #ifdef FASTEST
  81531. #define INSERT_STRING(s, str, match_head) \
  81532. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81533. match_head = s->head[s->ins_h], \
  81534. s->head[s->ins_h] = (Pos)(str))
  81535. #else
  81536. #define INSERT_STRING(s, str, match_head) \
  81537. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  81538. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  81539. s->head[s->ins_h] = (Pos)(str))
  81540. #endif
  81541. /* ===========================================================================
  81542. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  81543. * prev[] will be initialized on the fly.
  81544. */
  81545. #define CLEAR_HASH(s) \
  81546. s->head[s->hash_size-1] = NIL; \
  81547. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  81548. /* ========================================================================= */
  81549. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  81550. {
  81551. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  81552. Z_DEFAULT_STRATEGY, version, stream_size);
  81553. /* To do: ignore strm->next_in if we use it as window */
  81554. }
  81555. /* ========================================================================= */
  81556. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  81557. {
  81558. deflate_state *s;
  81559. int wrap = 1;
  81560. static const char my_version[] = ZLIB_VERSION;
  81561. ushf *overlay;
  81562. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  81563. * output size for (length,distance) codes is <= 24 bits.
  81564. */
  81565. if (version == Z_NULL || version[0] != my_version[0] ||
  81566. stream_size != sizeof(z_stream)) {
  81567. return Z_VERSION_ERROR;
  81568. }
  81569. if (strm == Z_NULL) return Z_STREAM_ERROR;
  81570. strm->msg = Z_NULL;
  81571. if (strm->zalloc == (alloc_func)0) {
  81572. strm->zalloc = zcalloc;
  81573. strm->opaque = (voidpf)0;
  81574. }
  81575. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  81576. #ifdef FASTEST
  81577. if (level != 0) level = 1;
  81578. #else
  81579. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81580. #endif
  81581. if (windowBits < 0) { /* suppress zlib wrapper */
  81582. wrap = 0;
  81583. windowBits = -windowBits;
  81584. }
  81585. #ifdef GZIP
  81586. else if (windowBits > 15) {
  81587. wrap = 2; /* write gzip wrapper instead */
  81588. windowBits -= 16;
  81589. }
  81590. #endif
  81591. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  81592. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  81593. strategy < 0 || strategy > Z_FIXED) {
  81594. return Z_STREAM_ERROR;
  81595. }
  81596. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  81597. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  81598. if (s == Z_NULL) return Z_MEM_ERROR;
  81599. strm->state = (struct internal_state FAR *)s;
  81600. s->strm = strm;
  81601. s->wrap = wrap;
  81602. s->gzhead = Z_NULL;
  81603. s->w_bits = windowBits;
  81604. s->w_size = 1 << s->w_bits;
  81605. s->w_mask = s->w_size - 1;
  81606. s->hash_bits = memLevel + 7;
  81607. s->hash_size = 1 << s->hash_bits;
  81608. s->hash_mask = s->hash_size - 1;
  81609. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  81610. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  81611. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  81612. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  81613. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  81614. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  81615. s->pending_buf = (uchf *) overlay;
  81616. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  81617. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  81618. s->pending_buf == Z_NULL) {
  81619. s->status = FINISH_STATE;
  81620. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  81621. deflateEnd (strm);
  81622. return Z_MEM_ERROR;
  81623. }
  81624. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  81625. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  81626. s->level = level;
  81627. s->strategy = strategy;
  81628. s->method = (Byte)method;
  81629. return deflateReset(strm);
  81630. }
  81631. /* ========================================================================= */
  81632. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  81633. {
  81634. deflate_state *s;
  81635. uInt length = dictLength;
  81636. uInt n;
  81637. IPos hash_head = 0;
  81638. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  81639. strm->state->wrap == 2 ||
  81640. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  81641. return Z_STREAM_ERROR;
  81642. s = strm->state;
  81643. if (s->wrap)
  81644. strm->adler = adler32(strm->adler, dictionary, dictLength);
  81645. if (length < MIN_MATCH) return Z_OK;
  81646. if (length > MAX_DIST(s)) {
  81647. length = MAX_DIST(s);
  81648. dictionary += dictLength - length; /* use the tail of the dictionary */
  81649. }
  81650. zmemcpy(s->window, dictionary, length);
  81651. s->strstart = length;
  81652. s->block_start = (long)length;
  81653. /* Insert all strings in the hash table (except for the last two bytes).
  81654. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  81655. * call of fill_window.
  81656. */
  81657. s->ins_h = s->window[0];
  81658. UPDATE_HASH(s, s->ins_h, s->window[1]);
  81659. for (n = 0; n <= length - MIN_MATCH; n++) {
  81660. INSERT_STRING(s, n, hash_head);
  81661. }
  81662. if (hash_head) hash_head = 0; /* to make compiler happy */
  81663. return Z_OK;
  81664. }
  81665. /* ========================================================================= */
  81666. int ZEXPORT deflateReset (z_streamp strm)
  81667. {
  81668. deflate_state *s;
  81669. if (strm == Z_NULL || strm->state == Z_NULL ||
  81670. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  81671. return Z_STREAM_ERROR;
  81672. }
  81673. strm->total_in = strm->total_out = 0;
  81674. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  81675. strm->data_type = Z_UNKNOWN;
  81676. s = (deflate_state *)strm->state;
  81677. s->pending = 0;
  81678. s->pending_out = s->pending_buf;
  81679. if (s->wrap < 0) {
  81680. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  81681. }
  81682. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  81683. strm->adler =
  81684. #ifdef GZIP
  81685. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  81686. #endif
  81687. adler32(0L, Z_NULL, 0);
  81688. s->last_flush = Z_NO_FLUSH;
  81689. _tr_init(s);
  81690. lm_init(s);
  81691. return Z_OK;
  81692. }
  81693. /* ========================================================================= */
  81694. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  81695. {
  81696. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81697. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  81698. strm->state->gzhead = head;
  81699. return Z_OK;
  81700. }
  81701. /* ========================================================================= */
  81702. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  81703. {
  81704. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81705. strm->state->bi_valid = bits;
  81706. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  81707. return Z_OK;
  81708. }
  81709. /* ========================================================================= */
  81710. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  81711. {
  81712. deflate_state *s;
  81713. compress_func func;
  81714. int err = Z_OK;
  81715. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81716. s = strm->state;
  81717. #ifdef FASTEST
  81718. if (level != 0) level = 1;
  81719. #else
  81720. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  81721. #endif
  81722. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  81723. return Z_STREAM_ERROR;
  81724. }
  81725. func = configuration_table[s->level].func;
  81726. if (func != configuration_table[level].func && strm->total_in != 0) {
  81727. /* Flush the last buffer: */
  81728. err = deflate(strm, Z_PARTIAL_FLUSH);
  81729. }
  81730. if (s->level != level) {
  81731. s->level = level;
  81732. s->max_lazy_match = configuration_table[level].max_lazy;
  81733. s->good_match = configuration_table[level].good_length;
  81734. s->nice_match = configuration_table[level].nice_length;
  81735. s->max_chain_length = configuration_table[level].max_chain;
  81736. }
  81737. s->strategy = strategy;
  81738. return err;
  81739. }
  81740. /* ========================================================================= */
  81741. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  81742. {
  81743. deflate_state *s;
  81744. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  81745. s = strm->state;
  81746. s->good_match = good_length;
  81747. s->max_lazy_match = max_lazy;
  81748. s->nice_match = nice_length;
  81749. s->max_chain_length = max_chain;
  81750. return Z_OK;
  81751. }
  81752. /* =========================================================================
  81753. * For the default windowBits of 15 and memLevel of 8, this function returns
  81754. * a close to exact, as well as small, upper bound on the compressed size.
  81755. * They are coded as constants here for a reason--if the #define's are
  81756. * changed, then this function needs to be changed as well. The return
  81757. * value for 15 and 8 only works for those exact settings.
  81758. *
  81759. * For any setting other than those defaults for windowBits and memLevel,
  81760. * the value returned is a conservative worst case for the maximum expansion
  81761. * resulting from using fixed blocks instead of stored blocks, which deflate
  81762. * can emit on compressed data for some combinations of the parameters.
  81763. *
  81764. * This function could be more sophisticated to provide closer upper bounds
  81765. * for every combination of windowBits and memLevel, as well as wrap.
  81766. * But even the conservative upper bound of about 14% expansion does not
  81767. * seem onerous for output buffer allocation.
  81768. */
  81769. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  81770. {
  81771. deflate_state *s;
  81772. uLong destLen;
  81773. /* conservative upper bound */
  81774. destLen = sourceLen +
  81775. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  81776. /* if can't get parameters, return conservative bound */
  81777. if (strm == Z_NULL || strm->state == Z_NULL)
  81778. return destLen;
  81779. /* if not default parameters, return conservative bound */
  81780. s = strm->state;
  81781. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  81782. return destLen;
  81783. /* default settings: return tight bound for that case */
  81784. return compressBound(sourceLen);
  81785. }
  81786. /* =========================================================================
  81787. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  81788. * IN assertion: the stream state is correct and there is enough room in
  81789. * pending_buf.
  81790. */
  81791. local void putShortMSB (deflate_state *s, uInt b)
  81792. {
  81793. put_byte(s, (Byte)(b >> 8));
  81794. put_byte(s, (Byte)(b & 0xff));
  81795. }
  81796. /* =========================================================================
  81797. * Flush as much pending output as possible. All deflate() output goes
  81798. * through this function so some applications may wish to modify it
  81799. * to avoid allocating a large strm->next_out buffer and copying into it.
  81800. * (See also read_buf()).
  81801. */
  81802. local void flush_pending (z_streamp strm)
  81803. {
  81804. unsigned len = strm->state->pending;
  81805. if (len > strm->avail_out) len = strm->avail_out;
  81806. if (len == 0) return;
  81807. zmemcpy(strm->next_out, strm->state->pending_out, len);
  81808. strm->next_out += len;
  81809. strm->state->pending_out += len;
  81810. strm->total_out += len;
  81811. strm->avail_out -= len;
  81812. strm->state->pending -= len;
  81813. if (strm->state->pending == 0) {
  81814. strm->state->pending_out = strm->state->pending_buf;
  81815. }
  81816. }
  81817. /* ========================================================================= */
  81818. int ZEXPORT deflate (z_streamp strm, int flush)
  81819. {
  81820. int old_flush; /* value of flush param for previous deflate call */
  81821. deflate_state *s;
  81822. if (strm == Z_NULL || strm->state == Z_NULL ||
  81823. flush > Z_FINISH || flush < 0) {
  81824. return Z_STREAM_ERROR;
  81825. }
  81826. s = strm->state;
  81827. if (strm->next_out == Z_NULL ||
  81828. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  81829. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  81830. ERR_RETURN(strm, Z_STREAM_ERROR);
  81831. }
  81832. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  81833. s->strm = strm; /* just in case */
  81834. old_flush = s->last_flush;
  81835. s->last_flush = flush;
  81836. /* Write the header */
  81837. if (s->status == INIT_STATE) {
  81838. #ifdef GZIP
  81839. if (s->wrap == 2) {
  81840. strm->adler = crc32(0L, Z_NULL, 0);
  81841. put_byte(s, 31);
  81842. put_byte(s, 139);
  81843. put_byte(s, 8);
  81844. if (s->gzhead == NULL) {
  81845. put_byte(s, 0);
  81846. put_byte(s, 0);
  81847. put_byte(s, 0);
  81848. put_byte(s, 0);
  81849. put_byte(s, 0);
  81850. put_byte(s, s->level == 9 ? 2 :
  81851. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81852. 4 : 0));
  81853. put_byte(s, OS_CODE);
  81854. s->status = BUSY_STATE;
  81855. }
  81856. else {
  81857. put_byte(s, (s->gzhead->text ? 1 : 0) +
  81858. (s->gzhead->hcrc ? 2 : 0) +
  81859. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  81860. (s->gzhead->name == Z_NULL ? 0 : 8) +
  81861. (s->gzhead->comment == Z_NULL ? 0 : 16)
  81862. );
  81863. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  81864. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  81865. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  81866. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  81867. put_byte(s, s->level == 9 ? 2 :
  81868. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  81869. 4 : 0));
  81870. put_byte(s, s->gzhead->os & 0xff);
  81871. if (s->gzhead->extra != NULL) {
  81872. put_byte(s, s->gzhead->extra_len & 0xff);
  81873. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  81874. }
  81875. if (s->gzhead->hcrc)
  81876. strm->adler = crc32(strm->adler, s->pending_buf,
  81877. s->pending);
  81878. s->gzindex = 0;
  81879. s->status = EXTRA_STATE;
  81880. }
  81881. }
  81882. else
  81883. #endif
  81884. {
  81885. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  81886. uInt level_flags;
  81887. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  81888. level_flags = 0;
  81889. else if (s->level < 6)
  81890. level_flags = 1;
  81891. else if (s->level == 6)
  81892. level_flags = 2;
  81893. else
  81894. level_flags = 3;
  81895. header |= (level_flags << 6);
  81896. if (s->strstart != 0) header |= PRESET_DICT;
  81897. header += 31 - (header % 31);
  81898. s->status = BUSY_STATE;
  81899. putShortMSB(s, header);
  81900. /* Save the adler32 of the preset dictionary: */
  81901. if (s->strstart != 0) {
  81902. putShortMSB(s, (uInt)(strm->adler >> 16));
  81903. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  81904. }
  81905. strm->adler = adler32(0L, Z_NULL, 0);
  81906. }
  81907. }
  81908. #ifdef GZIP
  81909. if (s->status == EXTRA_STATE) {
  81910. if (s->gzhead->extra != NULL) {
  81911. uInt beg = s->pending; /* start of bytes to update crc */
  81912. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  81913. if (s->pending == s->pending_buf_size) {
  81914. if (s->gzhead->hcrc && s->pending > beg)
  81915. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81916. s->pending - beg);
  81917. flush_pending(strm);
  81918. beg = s->pending;
  81919. if (s->pending == s->pending_buf_size)
  81920. break;
  81921. }
  81922. put_byte(s, s->gzhead->extra[s->gzindex]);
  81923. s->gzindex++;
  81924. }
  81925. if (s->gzhead->hcrc && s->pending > beg)
  81926. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81927. s->pending - beg);
  81928. if (s->gzindex == s->gzhead->extra_len) {
  81929. s->gzindex = 0;
  81930. s->status = NAME_STATE;
  81931. }
  81932. }
  81933. else
  81934. s->status = NAME_STATE;
  81935. }
  81936. if (s->status == NAME_STATE) {
  81937. if (s->gzhead->name != NULL) {
  81938. uInt beg = s->pending; /* start of bytes to update crc */
  81939. int val;
  81940. do {
  81941. if (s->pending == s->pending_buf_size) {
  81942. if (s->gzhead->hcrc && s->pending > beg)
  81943. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81944. s->pending - beg);
  81945. flush_pending(strm);
  81946. beg = s->pending;
  81947. if (s->pending == s->pending_buf_size) {
  81948. val = 1;
  81949. break;
  81950. }
  81951. }
  81952. val = s->gzhead->name[s->gzindex++];
  81953. put_byte(s, val);
  81954. } while (val != 0);
  81955. if (s->gzhead->hcrc && s->pending > beg)
  81956. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81957. s->pending - beg);
  81958. if (val == 0) {
  81959. s->gzindex = 0;
  81960. s->status = COMMENT_STATE;
  81961. }
  81962. }
  81963. else
  81964. s->status = COMMENT_STATE;
  81965. }
  81966. if (s->status == COMMENT_STATE) {
  81967. if (s->gzhead->comment != NULL) {
  81968. uInt beg = s->pending; /* start of bytes to update crc */
  81969. int val;
  81970. do {
  81971. if (s->pending == s->pending_buf_size) {
  81972. if (s->gzhead->hcrc && s->pending > beg)
  81973. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81974. s->pending - beg);
  81975. flush_pending(strm);
  81976. beg = s->pending;
  81977. if (s->pending == s->pending_buf_size) {
  81978. val = 1;
  81979. break;
  81980. }
  81981. }
  81982. val = s->gzhead->comment[s->gzindex++];
  81983. put_byte(s, val);
  81984. } while (val != 0);
  81985. if (s->gzhead->hcrc && s->pending > beg)
  81986. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  81987. s->pending - beg);
  81988. if (val == 0)
  81989. s->status = HCRC_STATE;
  81990. }
  81991. else
  81992. s->status = HCRC_STATE;
  81993. }
  81994. if (s->status == HCRC_STATE) {
  81995. if (s->gzhead->hcrc) {
  81996. if (s->pending + 2 > s->pending_buf_size)
  81997. flush_pending(strm);
  81998. if (s->pending + 2 <= s->pending_buf_size) {
  81999. put_byte(s, (Byte)(strm->adler & 0xff));
  82000. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82001. strm->adler = crc32(0L, Z_NULL, 0);
  82002. s->status = BUSY_STATE;
  82003. }
  82004. }
  82005. else
  82006. s->status = BUSY_STATE;
  82007. }
  82008. #endif
  82009. /* Flush as much pending output as possible */
  82010. if (s->pending != 0) {
  82011. flush_pending(strm);
  82012. if (strm->avail_out == 0) {
  82013. /* Since avail_out is 0, deflate will be called again with
  82014. * more output space, but possibly with both pending and
  82015. * avail_in equal to zero. There won't be anything to do,
  82016. * but this is not an error situation so make sure we
  82017. * return OK instead of BUF_ERROR at next call of deflate:
  82018. */
  82019. s->last_flush = -1;
  82020. return Z_OK;
  82021. }
  82022. /* Make sure there is something to do and avoid duplicate consecutive
  82023. * flushes. For repeated and useless calls with Z_FINISH, we keep
  82024. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  82025. */
  82026. } else if (strm->avail_in == 0 && flush <= old_flush &&
  82027. flush != Z_FINISH) {
  82028. ERR_RETURN(strm, Z_BUF_ERROR);
  82029. }
  82030. /* User must not provide more input after the first FINISH: */
  82031. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  82032. ERR_RETURN(strm, Z_BUF_ERROR);
  82033. }
  82034. /* Start a new block or continue the current one.
  82035. */
  82036. if (strm->avail_in != 0 || s->lookahead != 0 ||
  82037. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  82038. block_state bstate;
  82039. bstate = (*(configuration_table[s->level].func))(s, flush);
  82040. if (bstate == finish_started || bstate == finish_done) {
  82041. s->status = FINISH_STATE;
  82042. }
  82043. if (bstate == need_more || bstate == finish_started) {
  82044. if (strm->avail_out == 0) {
  82045. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  82046. }
  82047. return Z_OK;
  82048. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  82049. * of deflate should use the same flush parameter to make sure
  82050. * that the flush is complete. So we don't have to output an
  82051. * empty block here, this will be done at next call. This also
  82052. * ensures that for a very small output buffer, we emit at most
  82053. * one empty block.
  82054. */
  82055. }
  82056. if (bstate == block_done) {
  82057. if (flush == Z_PARTIAL_FLUSH) {
  82058. _tr_align(s);
  82059. } else { /* FULL_FLUSH or SYNC_FLUSH */
  82060. _tr_stored_block(s, (char*)0, 0L, 0);
  82061. /* For a full flush, this empty block will be recognized
  82062. * as a special marker by inflate_sync().
  82063. */
  82064. if (flush == Z_FULL_FLUSH) {
  82065. CLEAR_HASH(s); /* forget history */
  82066. }
  82067. }
  82068. flush_pending(strm);
  82069. if (strm->avail_out == 0) {
  82070. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  82071. return Z_OK;
  82072. }
  82073. }
  82074. }
  82075. Assert(strm->avail_out > 0, "bug2");
  82076. if (flush != Z_FINISH) return Z_OK;
  82077. if (s->wrap <= 0) return Z_STREAM_END;
  82078. /* Write the trailer */
  82079. #ifdef GZIP
  82080. if (s->wrap == 2) {
  82081. put_byte(s, (Byte)(strm->adler & 0xff));
  82082. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  82083. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  82084. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  82085. put_byte(s, (Byte)(strm->total_in & 0xff));
  82086. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  82087. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  82088. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  82089. }
  82090. else
  82091. #endif
  82092. {
  82093. putShortMSB(s, (uInt)(strm->adler >> 16));
  82094. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  82095. }
  82096. flush_pending(strm);
  82097. /* If avail_out is zero, the application will call deflate again
  82098. * to flush the rest.
  82099. */
  82100. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  82101. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  82102. }
  82103. /* ========================================================================= */
  82104. int ZEXPORT deflateEnd (z_streamp strm)
  82105. {
  82106. int status;
  82107. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  82108. status = strm->state->status;
  82109. if (status != INIT_STATE &&
  82110. status != EXTRA_STATE &&
  82111. status != NAME_STATE &&
  82112. status != COMMENT_STATE &&
  82113. status != HCRC_STATE &&
  82114. status != BUSY_STATE &&
  82115. status != FINISH_STATE) {
  82116. return Z_STREAM_ERROR;
  82117. }
  82118. /* Deallocate in reverse order of allocations: */
  82119. TRY_FREE(strm, strm->state->pending_buf);
  82120. TRY_FREE(strm, strm->state->head);
  82121. TRY_FREE(strm, strm->state->prev);
  82122. TRY_FREE(strm, strm->state->window);
  82123. ZFREE(strm, strm->state);
  82124. strm->state = Z_NULL;
  82125. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  82126. }
  82127. /* =========================================================================
  82128. * Copy the source state to the destination state.
  82129. * To simplify the source, this is not supported for 16-bit MSDOS (which
  82130. * doesn't have enough memory anyway to duplicate compression states).
  82131. */
  82132. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  82133. {
  82134. #ifdef MAXSEG_64K
  82135. return Z_STREAM_ERROR;
  82136. #else
  82137. deflate_state *ds;
  82138. deflate_state *ss;
  82139. ushf *overlay;
  82140. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  82141. return Z_STREAM_ERROR;
  82142. }
  82143. ss = source->state;
  82144. zmemcpy(dest, source, sizeof(z_stream));
  82145. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  82146. if (ds == Z_NULL) return Z_MEM_ERROR;
  82147. dest->state = (struct internal_state FAR *) ds;
  82148. zmemcpy(ds, ss, sizeof(deflate_state));
  82149. ds->strm = dest;
  82150. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  82151. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  82152. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  82153. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  82154. ds->pending_buf = (uchf *) overlay;
  82155. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  82156. ds->pending_buf == Z_NULL) {
  82157. deflateEnd (dest);
  82158. return Z_MEM_ERROR;
  82159. }
  82160. /* following zmemcpy do not work for 16-bit MSDOS */
  82161. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  82162. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  82163. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  82164. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  82165. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  82166. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  82167. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  82168. ds->l_desc.dyn_tree = ds->dyn_ltree;
  82169. ds->d_desc.dyn_tree = ds->dyn_dtree;
  82170. ds->bl_desc.dyn_tree = ds->bl_tree;
  82171. return Z_OK;
  82172. #endif /* MAXSEG_64K */
  82173. }
  82174. /* ===========================================================================
  82175. * Read a new buffer from the current input stream, update the adler32
  82176. * and total number of bytes read. All deflate() input goes through
  82177. * this function so some applications may wish to modify it to avoid
  82178. * allocating a large strm->next_in buffer and copying from it.
  82179. * (See also flush_pending()).
  82180. */
  82181. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  82182. {
  82183. unsigned len = strm->avail_in;
  82184. if (len > size) len = size;
  82185. if (len == 0) return 0;
  82186. strm->avail_in -= len;
  82187. if (strm->state->wrap == 1) {
  82188. strm->adler = adler32(strm->adler, strm->next_in, len);
  82189. }
  82190. #ifdef GZIP
  82191. else if (strm->state->wrap == 2) {
  82192. strm->adler = crc32(strm->adler, strm->next_in, len);
  82193. }
  82194. #endif
  82195. zmemcpy(buf, strm->next_in, len);
  82196. strm->next_in += len;
  82197. strm->total_in += len;
  82198. return (int)len;
  82199. }
  82200. /* ===========================================================================
  82201. * Initialize the "longest match" routines for a new zlib stream
  82202. */
  82203. local void lm_init (deflate_state *s)
  82204. {
  82205. s->window_size = (ulg)2L*s->w_size;
  82206. CLEAR_HASH(s);
  82207. /* Set the default configuration parameters:
  82208. */
  82209. s->max_lazy_match = configuration_table[s->level].max_lazy;
  82210. s->good_match = configuration_table[s->level].good_length;
  82211. s->nice_match = configuration_table[s->level].nice_length;
  82212. s->max_chain_length = configuration_table[s->level].max_chain;
  82213. s->strstart = 0;
  82214. s->block_start = 0L;
  82215. s->lookahead = 0;
  82216. s->match_length = s->prev_length = MIN_MATCH-1;
  82217. s->match_available = 0;
  82218. s->ins_h = 0;
  82219. #ifndef FASTEST
  82220. #ifdef ASMV
  82221. match_init(); /* initialize the asm code */
  82222. #endif
  82223. #endif
  82224. }
  82225. #ifndef FASTEST
  82226. /* ===========================================================================
  82227. * Set match_start to the longest match starting at the given string and
  82228. * return its length. Matches shorter or equal to prev_length are discarded,
  82229. * in which case the result is equal to prev_length and match_start is
  82230. * garbage.
  82231. * IN assertions: cur_match is the head of the hash chain for the current
  82232. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  82233. * OUT assertion: the match length is not greater than s->lookahead.
  82234. */
  82235. #ifndef ASMV
  82236. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  82237. * match.S. The code will be functionally equivalent.
  82238. */
  82239. local uInt longest_match(deflate_state *s, IPos cur_match)
  82240. {
  82241. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  82242. register Bytef *scan = s->window + s->strstart; /* current string */
  82243. register Bytef *match; /* matched string */
  82244. register int len; /* length of current match */
  82245. int best_len = s->prev_length; /* best match length so far */
  82246. int nice_match = s->nice_match; /* stop if match long enough */
  82247. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  82248. s->strstart - (IPos)MAX_DIST(s) : NIL;
  82249. /* Stop when cur_match becomes <= limit. To simplify the code,
  82250. * we prevent matches with the string of window index 0.
  82251. */
  82252. Posf *prev = s->prev;
  82253. uInt wmask = s->w_mask;
  82254. #ifdef UNALIGNED_OK
  82255. /* Compare two bytes at a time. Note: this is not always beneficial.
  82256. * Try with and without -DUNALIGNED_OK to check.
  82257. */
  82258. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  82259. register ush scan_start = *(ushf*)scan;
  82260. register ush scan_end = *(ushf*)(scan+best_len-1);
  82261. #else
  82262. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82263. register Byte scan_end1 = scan[best_len-1];
  82264. register Byte scan_end = scan[best_len];
  82265. #endif
  82266. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82267. * It is easy to get rid of this optimization if necessary.
  82268. */
  82269. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82270. /* Do not waste too much time if we already have a good match: */
  82271. if (s->prev_length >= s->good_match) {
  82272. chain_length >>= 2;
  82273. }
  82274. /* Do not look for matches beyond the end of the input. This is necessary
  82275. * to make deflate deterministic.
  82276. */
  82277. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  82278. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82279. do {
  82280. Assert(cur_match < s->strstart, "no future");
  82281. match = s->window + cur_match;
  82282. /* Skip to next match if the match length cannot increase
  82283. * or if the match length is less than 2. Note that the checks below
  82284. * for insufficient lookahead only occur occasionally for performance
  82285. * reasons. Therefore uninitialized memory will be accessed, and
  82286. * conditional jumps will be made that depend on those values.
  82287. * However the length of the match is limited to the lookahead, so
  82288. * the output of deflate is not affected by the uninitialized values.
  82289. */
  82290. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  82291. /* This code assumes sizeof(unsigned short) == 2. Do not use
  82292. * UNALIGNED_OK if your compiler uses a different size.
  82293. */
  82294. if (*(ushf*)(match+best_len-1) != scan_end ||
  82295. *(ushf*)match != scan_start) continue;
  82296. /* It is not necessary to compare scan[2] and match[2] since they are
  82297. * always equal when the other bytes match, given that the hash keys
  82298. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  82299. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  82300. * lookahead only every 4th comparison; the 128th check will be made
  82301. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  82302. * necessary to put more guard bytes at the end of the window, or
  82303. * to check more often for insufficient lookahead.
  82304. */
  82305. Assert(scan[2] == match[2], "scan[2]?");
  82306. scan++, match++;
  82307. do {
  82308. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82309. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82310. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82311. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  82312. scan < strend);
  82313. /* The funny "do {}" generates better code on most compilers */
  82314. /* Here, scan <= window+strstart+257 */
  82315. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82316. if (*scan == *match) scan++;
  82317. len = (MAX_MATCH - 1) - (int)(strend-scan);
  82318. scan = strend - (MAX_MATCH-1);
  82319. #else /* UNALIGNED_OK */
  82320. if (match[best_len] != scan_end ||
  82321. match[best_len-1] != scan_end1 ||
  82322. *match != *scan ||
  82323. *++match != scan[1]) continue;
  82324. /* The check at best_len-1 can be removed because it will be made
  82325. * again later. (This heuristic is not always a win.)
  82326. * It is not necessary to compare scan[2] and match[2] since they
  82327. * are always equal when the other bytes match, given that
  82328. * the hash keys are equal and that HASH_BITS >= 8.
  82329. */
  82330. scan += 2, match++;
  82331. Assert(*scan == *match, "match[2]?");
  82332. /* We check for insufficient lookahead only every 8th comparison;
  82333. * the 256th check will be made at strstart+258.
  82334. */
  82335. do {
  82336. } while (*++scan == *++match && *++scan == *++match &&
  82337. *++scan == *++match && *++scan == *++match &&
  82338. *++scan == *++match && *++scan == *++match &&
  82339. *++scan == *++match && *++scan == *++match &&
  82340. scan < strend);
  82341. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82342. len = MAX_MATCH - (int)(strend - scan);
  82343. scan = strend - MAX_MATCH;
  82344. #endif /* UNALIGNED_OK */
  82345. if (len > best_len) {
  82346. s->match_start = cur_match;
  82347. best_len = len;
  82348. if (len >= nice_match) break;
  82349. #ifdef UNALIGNED_OK
  82350. scan_end = *(ushf*)(scan+best_len-1);
  82351. #else
  82352. scan_end1 = scan[best_len-1];
  82353. scan_end = scan[best_len];
  82354. #endif
  82355. }
  82356. } while ((cur_match = prev[cur_match & wmask]) > limit
  82357. && --chain_length != 0);
  82358. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  82359. return s->lookahead;
  82360. }
  82361. #endif /* ASMV */
  82362. #endif /* FASTEST */
  82363. /* ---------------------------------------------------------------------------
  82364. * Optimized version for level == 1 or strategy == Z_RLE only
  82365. */
  82366. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  82367. {
  82368. register Bytef *scan = s->window + s->strstart; /* current string */
  82369. register Bytef *match; /* matched string */
  82370. register int len; /* length of current match */
  82371. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  82372. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  82373. * It is easy to get rid of this optimization if necessary.
  82374. */
  82375. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  82376. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  82377. Assert(cur_match < s->strstart, "no future");
  82378. match = s->window + cur_match;
  82379. /* Return failure if the match length is less than 2:
  82380. */
  82381. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  82382. /* The check at best_len-1 can be removed because it will be made
  82383. * again later. (This heuristic is not always a win.)
  82384. * It is not necessary to compare scan[2] and match[2] since they
  82385. * are always equal when the other bytes match, given that
  82386. * the hash keys are equal and that HASH_BITS >= 8.
  82387. */
  82388. scan += 2, match += 2;
  82389. Assert(*scan == *match, "match[2]?");
  82390. /* We check for insufficient lookahead only every 8th comparison;
  82391. * the 256th check will be made at strstart+258.
  82392. */
  82393. do {
  82394. } while (*++scan == *++match && *++scan == *++match &&
  82395. *++scan == *++match && *++scan == *++match &&
  82396. *++scan == *++match && *++scan == *++match &&
  82397. *++scan == *++match && *++scan == *++match &&
  82398. scan < strend);
  82399. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  82400. len = MAX_MATCH - (int)(strend - scan);
  82401. if (len < MIN_MATCH) return MIN_MATCH - 1;
  82402. s->match_start = cur_match;
  82403. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  82404. }
  82405. #ifdef DEBUG
  82406. /* ===========================================================================
  82407. * Check that the match at match_start is indeed a match.
  82408. */
  82409. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  82410. {
  82411. /* check that the match is indeed a match */
  82412. if (zmemcmp(s->window + match,
  82413. s->window + start, length) != EQUAL) {
  82414. fprintf(stderr, " start %u, match %u, length %d\n",
  82415. start, match, length);
  82416. do {
  82417. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  82418. } while (--length != 0);
  82419. z_error("invalid match");
  82420. }
  82421. if (z_verbose > 1) {
  82422. fprintf(stderr,"\\[%d,%d]", start-match, length);
  82423. do { putc(s->window[start++], stderr); } while (--length != 0);
  82424. }
  82425. }
  82426. #else
  82427. # define check_match(s, start, match, length)
  82428. #endif /* DEBUG */
  82429. /* ===========================================================================
  82430. * Fill the window when the lookahead becomes insufficient.
  82431. * Updates strstart and lookahead.
  82432. *
  82433. * IN assertion: lookahead < MIN_LOOKAHEAD
  82434. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  82435. * At least one byte has been read, or avail_in == 0; reads are
  82436. * performed for at least two bytes (required for the zip translate_eol
  82437. * option -- not supported here).
  82438. */
  82439. local void fill_window (deflate_state *s)
  82440. {
  82441. register unsigned n, m;
  82442. register Posf *p;
  82443. unsigned more; /* Amount of free space at the end of the window. */
  82444. uInt wsize = s->w_size;
  82445. do {
  82446. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  82447. /* Deal with !@#$% 64K limit: */
  82448. if (sizeof(int) <= 2) {
  82449. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  82450. more = wsize;
  82451. } else if (more == (unsigned)(-1)) {
  82452. /* Very unlikely, but possible on 16 bit machine if
  82453. * strstart == 0 && lookahead == 1 (input done a byte at time)
  82454. */
  82455. more--;
  82456. }
  82457. }
  82458. /* If the window is almost full and there is insufficient lookahead,
  82459. * move the upper half to the lower one to make room in the upper half.
  82460. */
  82461. if (s->strstart >= wsize+MAX_DIST(s)) {
  82462. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  82463. s->match_start -= wsize;
  82464. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  82465. s->block_start -= (long) wsize;
  82466. /* Slide the hash table (could be avoided with 32 bit values
  82467. at the expense of memory usage). We slide even when level == 0
  82468. to keep the hash table consistent if we switch back to level > 0
  82469. later. (Using level 0 permanently is not an optimal usage of
  82470. zlib, so we don't care about this pathological case.)
  82471. */
  82472. /* %%% avoid this when Z_RLE */
  82473. n = s->hash_size;
  82474. p = &s->head[n];
  82475. do {
  82476. m = *--p;
  82477. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82478. } while (--n);
  82479. n = wsize;
  82480. #ifndef FASTEST
  82481. p = &s->prev[n];
  82482. do {
  82483. m = *--p;
  82484. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  82485. /* If n is not on any hash chain, prev[n] is garbage but
  82486. * its value will never be used.
  82487. */
  82488. } while (--n);
  82489. #endif
  82490. more += wsize;
  82491. }
  82492. if (s->strm->avail_in == 0) return;
  82493. /* If there was no sliding:
  82494. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  82495. * more == window_size - lookahead - strstart
  82496. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  82497. * => more >= window_size - 2*WSIZE + 2
  82498. * In the BIG_MEM or MMAP case (not yet supported),
  82499. * window_size == input_size + MIN_LOOKAHEAD &&
  82500. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  82501. * Otherwise, window_size == 2*WSIZE so more >= 2.
  82502. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  82503. */
  82504. Assert(more >= 2, "more < 2");
  82505. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  82506. s->lookahead += n;
  82507. /* Initialize the hash value now that we have some input: */
  82508. if (s->lookahead >= MIN_MATCH) {
  82509. s->ins_h = s->window[s->strstart];
  82510. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82511. #if MIN_MATCH != 3
  82512. Call UPDATE_HASH() MIN_MATCH-3 more times
  82513. #endif
  82514. }
  82515. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  82516. * but this is not important since only literal bytes will be emitted.
  82517. */
  82518. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  82519. }
  82520. /* ===========================================================================
  82521. * Flush the current block, with given end-of-file flag.
  82522. * IN assertion: strstart is set to the end of the current match.
  82523. */
  82524. #define FLUSH_BLOCK_ONLY(s, eof) { \
  82525. _tr_flush_block(s, (s->block_start >= 0L ? \
  82526. (charf *)&s->window[(unsigned)s->block_start] : \
  82527. (charf *)Z_NULL), \
  82528. (ulg)((long)s->strstart - s->block_start), \
  82529. (eof)); \
  82530. s->block_start = s->strstart; \
  82531. flush_pending(s->strm); \
  82532. Tracev((stderr,"[FLUSH]")); \
  82533. }
  82534. /* Same but force premature exit if necessary. */
  82535. #define FLUSH_BLOCK(s, eof) { \
  82536. FLUSH_BLOCK_ONLY(s, eof); \
  82537. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  82538. }
  82539. /* ===========================================================================
  82540. * Copy without compression as much as possible from the input stream, return
  82541. * the current block state.
  82542. * This function does not insert new strings in the dictionary since
  82543. * uncompressible data is probably not useful. This function is used
  82544. * only for the level=0 compression option.
  82545. * NOTE: this function should be optimized to avoid extra copying from
  82546. * window to pending_buf.
  82547. */
  82548. local block_state deflate_stored(deflate_state *s, int flush)
  82549. {
  82550. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  82551. * to pending_buf_size, and each stored block has a 5 byte header:
  82552. */
  82553. ulg max_block_size = 0xffff;
  82554. ulg max_start;
  82555. if (max_block_size > s->pending_buf_size - 5) {
  82556. max_block_size = s->pending_buf_size - 5;
  82557. }
  82558. /* Copy as much as possible from input to output: */
  82559. for (;;) {
  82560. /* Fill the window as much as possible: */
  82561. if (s->lookahead <= 1) {
  82562. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  82563. s->block_start >= (long)s->w_size, "slide too late");
  82564. fill_window(s);
  82565. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  82566. if (s->lookahead == 0) break; /* flush the current block */
  82567. }
  82568. Assert(s->block_start >= 0L, "block gone");
  82569. s->strstart += s->lookahead;
  82570. s->lookahead = 0;
  82571. /* Emit a stored block if pending_buf will be full: */
  82572. max_start = s->block_start + max_block_size;
  82573. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  82574. /* strstart == 0 is possible when wraparound on 16-bit machine */
  82575. s->lookahead = (uInt)(s->strstart - max_start);
  82576. s->strstart = (uInt)max_start;
  82577. FLUSH_BLOCK(s, 0);
  82578. }
  82579. /* Flush if we may have to slide, otherwise block_start may become
  82580. * negative and the data will be gone:
  82581. */
  82582. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  82583. FLUSH_BLOCK(s, 0);
  82584. }
  82585. }
  82586. FLUSH_BLOCK(s, flush == Z_FINISH);
  82587. return flush == Z_FINISH ? finish_done : block_done;
  82588. }
  82589. /* ===========================================================================
  82590. * Compress as much as possible from the input stream, return the current
  82591. * block state.
  82592. * This function does not perform lazy evaluation of matches and inserts
  82593. * new strings in the dictionary only for unmatched strings or for short
  82594. * matches. It is used only for the fast compression options.
  82595. */
  82596. local block_state deflate_fast(deflate_state *s, int flush)
  82597. {
  82598. IPos hash_head = NIL; /* head of the hash chain */
  82599. int bflush; /* set if current block must be flushed */
  82600. for (;;) {
  82601. /* Make sure that we always have enough lookahead, except
  82602. * at the end of the input file. We need MAX_MATCH bytes
  82603. * for the next match, plus MIN_MATCH bytes to insert the
  82604. * string following the next match.
  82605. */
  82606. if (s->lookahead < MIN_LOOKAHEAD) {
  82607. fill_window(s);
  82608. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82609. return need_more;
  82610. }
  82611. if (s->lookahead == 0) break; /* flush the current block */
  82612. }
  82613. /* Insert the string window[strstart .. strstart+2] in the
  82614. * dictionary, and set hash_head to the head of the hash chain:
  82615. */
  82616. if (s->lookahead >= MIN_MATCH) {
  82617. INSERT_STRING(s, s->strstart, hash_head);
  82618. }
  82619. /* Find the longest match, discarding those <= prev_length.
  82620. * At this point we have always match_length < MIN_MATCH
  82621. */
  82622. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  82623. /* To simplify the code, we prevent matches with the string
  82624. * of window index 0 (in particular we have to avoid a match
  82625. * of the string with itself at the start of the input file).
  82626. */
  82627. #ifdef FASTEST
  82628. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  82629. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  82630. s->match_length = longest_match_fast (s, hash_head);
  82631. }
  82632. #else
  82633. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82634. s->match_length = longest_match (s, hash_head);
  82635. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82636. s->match_length = longest_match_fast (s, hash_head);
  82637. }
  82638. #endif
  82639. /* longest_match() or longest_match_fast() sets match_start */
  82640. }
  82641. if (s->match_length >= MIN_MATCH) {
  82642. check_match(s, s->strstart, s->match_start, s->match_length);
  82643. _tr_tally_dist(s, s->strstart - s->match_start,
  82644. s->match_length - MIN_MATCH, bflush);
  82645. s->lookahead -= s->match_length;
  82646. /* Insert new strings in the hash table only if the match length
  82647. * is not too large. This saves time but degrades compression.
  82648. */
  82649. #ifndef FASTEST
  82650. if (s->match_length <= s->max_insert_length &&
  82651. s->lookahead >= MIN_MATCH) {
  82652. s->match_length--; /* string at strstart already in table */
  82653. do {
  82654. s->strstart++;
  82655. INSERT_STRING(s, s->strstart, hash_head);
  82656. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  82657. * always MIN_MATCH bytes ahead.
  82658. */
  82659. } while (--s->match_length != 0);
  82660. s->strstart++;
  82661. } else
  82662. #endif
  82663. {
  82664. s->strstart += s->match_length;
  82665. s->match_length = 0;
  82666. s->ins_h = s->window[s->strstart];
  82667. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  82668. #if MIN_MATCH != 3
  82669. Call UPDATE_HASH() MIN_MATCH-3 more times
  82670. #endif
  82671. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  82672. * matter since it will be recomputed at next deflate call.
  82673. */
  82674. }
  82675. } else {
  82676. /* No match, output a literal byte */
  82677. Tracevv((stderr,"%c", s->window[s->strstart]));
  82678. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82679. s->lookahead--;
  82680. s->strstart++;
  82681. }
  82682. if (bflush) FLUSH_BLOCK(s, 0);
  82683. }
  82684. FLUSH_BLOCK(s, flush == Z_FINISH);
  82685. return flush == Z_FINISH ? finish_done : block_done;
  82686. }
  82687. #ifndef FASTEST
  82688. /* ===========================================================================
  82689. * Same as above, but achieves better compression. We use a lazy
  82690. * evaluation for matches: a match is finally adopted only if there is
  82691. * no better match at the next window position.
  82692. */
  82693. local block_state deflate_slow(deflate_state *s, int flush)
  82694. {
  82695. IPos hash_head = NIL; /* head of hash chain */
  82696. int bflush; /* set if current block must be flushed */
  82697. /* Process the input block. */
  82698. for (;;) {
  82699. /* Make sure that we always have enough lookahead, except
  82700. * at the end of the input file. We need MAX_MATCH bytes
  82701. * for the next match, plus MIN_MATCH bytes to insert the
  82702. * string following the next match.
  82703. */
  82704. if (s->lookahead < MIN_LOOKAHEAD) {
  82705. fill_window(s);
  82706. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  82707. return need_more;
  82708. }
  82709. if (s->lookahead == 0) break; /* flush the current block */
  82710. }
  82711. /* Insert the string window[strstart .. strstart+2] in the
  82712. * dictionary, and set hash_head to the head of the hash chain:
  82713. */
  82714. if (s->lookahead >= MIN_MATCH) {
  82715. INSERT_STRING(s, s->strstart, hash_head);
  82716. }
  82717. /* Find the longest match, discarding those <= prev_length.
  82718. */
  82719. s->prev_length = s->match_length, s->prev_match = s->match_start;
  82720. s->match_length = MIN_MATCH-1;
  82721. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  82722. s->strstart - hash_head <= MAX_DIST(s)) {
  82723. /* To simplify the code, we prevent matches with the string
  82724. * of window index 0 (in particular we have to avoid a match
  82725. * of the string with itself at the start of the input file).
  82726. */
  82727. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  82728. s->match_length = longest_match (s, hash_head);
  82729. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  82730. s->match_length = longest_match_fast (s, hash_head);
  82731. }
  82732. /* longest_match() or longest_match_fast() sets match_start */
  82733. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  82734. #if TOO_FAR <= 32767
  82735. || (s->match_length == MIN_MATCH &&
  82736. s->strstart - s->match_start > TOO_FAR)
  82737. #endif
  82738. )) {
  82739. /* If prev_match is also MIN_MATCH, match_start is garbage
  82740. * but we will ignore the current match anyway.
  82741. */
  82742. s->match_length = MIN_MATCH-1;
  82743. }
  82744. }
  82745. /* If there was a match at the previous step and the current
  82746. * match is not better, output the previous match:
  82747. */
  82748. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  82749. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  82750. /* Do not insert strings in hash table beyond this. */
  82751. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  82752. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  82753. s->prev_length - MIN_MATCH, bflush);
  82754. /* Insert in hash table all strings up to the end of the match.
  82755. * strstart-1 and strstart are already inserted. If there is not
  82756. * enough lookahead, the last two strings are not inserted in
  82757. * the hash table.
  82758. */
  82759. s->lookahead -= s->prev_length-1;
  82760. s->prev_length -= 2;
  82761. do {
  82762. if (++s->strstart <= max_insert) {
  82763. INSERT_STRING(s, s->strstart, hash_head);
  82764. }
  82765. } while (--s->prev_length != 0);
  82766. s->match_available = 0;
  82767. s->match_length = MIN_MATCH-1;
  82768. s->strstart++;
  82769. if (bflush) FLUSH_BLOCK(s, 0);
  82770. } else if (s->match_available) {
  82771. /* If there was no match at the previous position, output a
  82772. * single literal. If there was a match but the current match
  82773. * is longer, truncate the previous match to a single literal.
  82774. */
  82775. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82776. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82777. if (bflush) {
  82778. FLUSH_BLOCK_ONLY(s, 0);
  82779. }
  82780. s->strstart++;
  82781. s->lookahead--;
  82782. if (s->strm->avail_out == 0) return need_more;
  82783. } else {
  82784. /* There is no previous match to compare with, wait for
  82785. * the next step to decide.
  82786. */
  82787. s->match_available = 1;
  82788. s->strstart++;
  82789. s->lookahead--;
  82790. }
  82791. }
  82792. Assert (flush != Z_NO_FLUSH, "no flush?");
  82793. if (s->match_available) {
  82794. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  82795. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  82796. s->match_available = 0;
  82797. }
  82798. FLUSH_BLOCK(s, flush == Z_FINISH);
  82799. return flush == Z_FINISH ? finish_done : block_done;
  82800. }
  82801. #endif /* FASTEST */
  82802. #if 0
  82803. /* ===========================================================================
  82804. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  82805. * one. Do not maintain a hash table. (It will be regenerated if this run of
  82806. * deflate switches away from Z_RLE.)
  82807. */
  82808. local block_state deflate_rle(s, flush)
  82809. deflate_state *s;
  82810. int flush;
  82811. {
  82812. int bflush; /* set if current block must be flushed */
  82813. uInt run; /* length of run */
  82814. uInt max; /* maximum length of run */
  82815. uInt prev; /* byte at distance one to match */
  82816. Bytef *scan; /* scan for end of run */
  82817. for (;;) {
  82818. /* Make sure that we always have enough lookahead, except
  82819. * at the end of the input file. We need MAX_MATCH bytes
  82820. * for the longest encodable run.
  82821. */
  82822. if (s->lookahead < MAX_MATCH) {
  82823. fill_window(s);
  82824. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  82825. return need_more;
  82826. }
  82827. if (s->lookahead == 0) break; /* flush the current block */
  82828. }
  82829. /* See how many times the previous byte repeats */
  82830. run = 0;
  82831. if (s->strstart > 0) { /* if there is a previous byte, that is */
  82832. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  82833. scan = s->window + s->strstart - 1;
  82834. prev = *scan++;
  82835. do {
  82836. if (*scan++ != prev)
  82837. break;
  82838. } while (++run < max);
  82839. }
  82840. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  82841. if (run >= MIN_MATCH) {
  82842. check_match(s, s->strstart, s->strstart - 1, run);
  82843. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  82844. s->lookahead -= run;
  82845. s->strstart += run;
  82846. } else {
  82847. /* No match, output a literal byte */
  82848. Tracevv((stderr,"%c", s->window[s->strstart]));
  82849. _tr_tally_lit (s, s->window[s->strstart], bflush);
  82850. s->lookahead--;
  82851. s->strstart++;
  82852. }
  82853. if (bflush) FLUSH_BLOCK(s, 0);
  82854. }
  82855. FLUSH_BLOCK(s, flush == Z_FINISH);
  82856. return flush == Z_FINISH ? finish_done : block_done;
  82857. }
  82858. #endif
  82859. /*** End of inlined file: deflate.c ***/
  82860. /*** Start of inlined file: inffast.c ***/
  82861. /*** Start of inlined file: inftrees.h ***/
  82862. /* WARNING: this file should *not* be used by applications. It is
  82863. part of the implementation of the compression library and is
  82864. subject to change. Applications should only use zlib.h.
  82865. */
  82866. #ifndef _INFTREES_H_
  82867. #define _INFTREES_H_
  82868. /* Structure for decoding tables. Each entry provides either the
  82869. information needed to do the operation requested by the code that
  82870. indexed that table entry, or it provides a pointer to another
  82871. table that indexes more bits of the code. op indicates whether
  82872. the entry is a pointer to another table, a literal, a length or
  82873. distance, an end-of-block, or an invalid code. For a table
  82874. pointer, the low four bits of op is the number of index bits of
  82875. that table. For a length or distance, the low four bits of op
  82876. is the number of extra bits to get after the code. bits is
  82877. the number of bits in this code or part of the code to drop off
  82878. of the bit buffer. val is the actual byte to output in the case
  82879. of a literal, the base length or distance, or the offset from
  82880. the current table to the next table. Each entry is four bytes. */
  82881. typedef struct {
  82882. unsigned char op; /* operation, extra bits, table bits */
  82883. unsigned char bits; /* bits in this part of the code */
  82884. unsigned short val; /* offset in table or code value */
  82885. } code;
  82886. /* op values as set by inflate_table():
  82887. 00000000 - literal
  82888. 0000tttt - table link, tttt != 0 is the number of table index bits
  82889. 0001eeee - length or distance, eeee is the number of extra bits
  82890. 01100000 - end of block
  82891. 01000000 - invalid code
  82892. */
  82893. /* Maximum size of dynamic tree. The maximum found in a long but non-
  82894. exhaustive search was 1444 code structures (852 for length/literals
  82895. and 592 for distances, the latter actually the result of an
  82896. exhaustive search). The true maximum is not known, but the value
  82897. below is more than safe. */
  82898. #define ENOUGH 2048
  82899. #define MAXD 592
  82900. /* Type of code to build for inftable() */
  82901. typedef enum {
  82902. CODES,
  82903. LENS,
  82904. DISTS
  82905. } codetype;
  82906. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  82907. unsigned codes, code FAR * FAR *table,
  82908. unsigned FAR *bits, unsigned short FAR *work));
  82909. #endif
  82910. /*** End of inlined file: inftrees.h ***/
  82911. /*** Start of inlined file: inflate.h ***/
  82912. /* WARNING: this file should *not* be used by applications. It is
  82913. part of the implementation of the compression library and is
  82914. subject to change. Applications should only use zlib.h.
  82915. */
  82916. #ifndef _INFLATE_H_
  82917. #define _INFLATE_H_
  82918. /* define NO_GZIP when compiling if you want to disable gzip header and
  82919. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  82920. the crc code when it is not needed. For shared libraries, gzip decoding
  82921. should be left enabled. */
  82922. #ifndef NO_GZIP
  82923. # define GUNZIP
  82924. #endif
  82925. /* Possible inflate modes between inflate() calls */
  82926. typedef enum {
  82927. HEAD, /* i: waiting for magic header */
  82928. FLAGS, /* i: waiting for method and flags (gzip) */
  82929. TIME, /* i: waiting for modification time (gzip) */
  82930. OS, /* i: waiting for extra flags and operating system (gzip) */
  82931. EXLEN, /* i: waiting for extra length (gzip) */
  82932. EXTRA, /* i: waiting for extra bytes (gzip) */
  82933. NAME, /* i: waiting for end of file name (gzip) */
  82934. COMMENT, /* i: waiting for end of comment (gzip) */
  82935. HCRC, /* i: waiting for header crc (gzip) */
  82936. DICTID, /* i: waiting for dictionary check value */
  82937. DICT, /* waiting for inflateSetDictionary() call */
  82938. TYPE, /* i: waiting for type bits, including last-flag bit */
  82939. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  82940. STORED, /* i: waiting for stored size (length and complement) */
  82941. COPY, /* i/o: waiting for input or output to copy stored block */
  82942. TABLE, /* i: waiting for dynamic block table lengths */
  82943. LENLENS, /* i: waiting for code length code lengths */
  82944. CODELENS, /* i: waiting for length/lit and distance code lengths */
  82945. LEN, /* i: waiting for length/lit code */
  82946. LENEXT, /* i: waiting for length extra bits */
  82947. DIST, /* i: waiting for distance code */
  82948. DISTEXT, /* i: waiting for distance extra bits */
  82949. MATCH, /* o: waiting for output space to copy string */
  82950. LIT, /* o: waiting for output space to write literal */
  82951. CHECK, /* i: waiting for 32-bit check value */
  82952. LENGTH, /* i: waiting for 32-bit length (gzip) */
  82953. DONE, /* finished check, done -- remain here until reset */
  82954. BAD, /* got a data error -- remain here until reset */
  82955. MEM, /* got an inflate() memory error -- remain here until reset */
  82956. SYNC /* looking for synchronization bytes to restart inflate() */
  82957. } inflate_mode;
  82958. /*
  82959. State transitions between above modes -
  82960. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  82961. Process header:
  82962. HEAD -> (gzip) or (zlib)
  82963. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  82964. NAME -> COMMENT -> HCRC -> TYPE
  82965. (zlib) -> DICTID or TYPE
  82966. DICTID -> DICT -> TYPE
  82967. Read deflate blocks:
  82968. TYPE -> STORED or TABLE or LEN or CHECK
  82969. STORED -> COPY -> TYPE
  82970. TABLE -> LENLENS -> CODELENS -> LEN
  82971. Read deflate codes:
  82972. LEN -> LENEXT or LIT or TYPE
  82973. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  82974. LIT -> LEN
  82975. Process trailer:
  82976. CHECK -> LENGTH -> DONE
  82977. */
  82978. /* state maintained between inflate() calls. Approximately 7K bytes. */
  82979. struct inflate_state {
  82980. inflate_mode mode; /* current inflate mode */
  82981. int last; /* true if processing last block */
  82982. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  82983. int havedict; /* true if dictionary provided */
  82984. int flags; /* gzip header method and flags (0 if zlib) */
  82985. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  82986. unsigned long check; /* protected copy of check value */
  82987. unsigned long total; /* protected copy of output count */
  82988. gz_headerp head; /* where to save gzip header information */
  82989. /* sliding window */
  82990. unsigned wbits; /* log base 2 of requested window size */
  82991. unsigned wsize; /* window size or zero if not using window */
  82992. unsigned whave; /* valid bytes in the window */
  82993. unsigned write; /* window write index */
  82994. unsigned char FAR *window; /* allocated sliding window, if needed */
  82995. /* bit accumulator */
  82996. unsigned long hold; /* input bit accumulator */
  82997. unsigned bits; /* number of bits in "in" */
  82998. /* for string and stored block copying */
  82999. unsigned length; /* literal or length of data to copy */
  83000. unsigned offset; /* distance back to copy string from */
  83001. /* for table and code decoding */
  83002. unsigned extra; /* extra bits needed */
  83003. /* fixed and dynamic code tables */
  83004. code const FAR *lencode; /* starting table for length/literal codes */
  83005. code const FAR *distcode; /* starting table for distance codes */
  83006. unsigned lenbits; /* index bits for lencode */
  83007. unsigned distbits; /* index bits for distcode */
  83008. /* dynamic table building */
  83009. unsigned ncode; /* number of code length code lengths */
  83010. unsigned nlen; /* number of length code lengths */
  83011. unsigned ndist; /* number of distance code lengths */
  83012. unsigned have; /* number of code lengths in lens[] */
  83013. code FAR *next; /* next available space in codes[] */
  83014. unsigned short lens[320]; /* temporary storage for code lengths */
  83015. unsigned short work[288]; /* work area for code table building */
  83016. code codes[ENOUGH]; /* space for code tables */
  83017. };
  83018. #endif
  83019. /*** End of inlined file: inflate.h ***/
  83020. /*** Start of inlined file: inffast.h ***/
  83021. /* WARNING: this file should *not* be used by applications. It is
  83022. part of the implementation of the compression library and is
  83023. subject to change. Applications should only use zlib.h.
  83024. */
  83025. void inflate_fast OF((z_streamp strm, unsigned start));
  83026. /*** End of inlined file: inffast.h ***/
  83027. #ifndef ASMINF
  83028. /* Allow machine dependent optimization for post-increment or pre-increment.
  83029. Based on testing to date,
  83030. Pre-increment preferred for:
  83031. - PowerPC G3 (Adler)
  83032. - MIPS R5000 (Randers-Pehrson)
  83033. Post-increment preferred for:
  83034. - none
  83035. No measurable difference:
  83036. - Pentium III (Anderson)
  83037. - M68060 (Nikl)
  83038. */
  83039. #ifdef POSTINC
  83040. # define OFF 0
  83041. # define PUP(a) *(a)++
  83042. #else
  83043. # define OFF 1
  83044. # define PUP(a) *++(a)
  83045. #endif
  83046. /*
  83047. Decode literal, length, and distance codes and write out the resulting
  83048. literal and match bytes until either not enough input or output is
  83049. available, an end-of-block is encountered, or a data error is encountered.
  83050. When large enough input and output buffers are supplied to inflate(), for
  83051. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  83052. inflate execution time is spent in this routine.
  83053. Entry assumptions:
  83054. state->mode == LEN
  83055. strm->avail_in >= 6
  83056. strm->avail_out >= 258
  83057. start >= strm->avail_out
  83058. state->bits < 8
  83059. On return, state->mode is one of:
  83060. LEN -- ran out of enough output space or enough available input
  83061. TYPE -- reached end of block code, inflate() to interpret next block
  83062. BAD -- error in block data
  83063. Notes:
  83064. - The maximum input bits used by a length/distance pair is 15 bits for the
  83065. length code, 5 bits for the length extra, 15 bits for the distance code,
  83066. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  83067. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  83068. checking for available input while decoding.
  83069. - The maximum bytes that a single length/distance pair can output is 258
  83070. bytes, which is the maximum length that can be coded. inflate_fast()
  83071. requires strm->avail_out >= 258 for each loop to avoid checking for
  83072. output space.
  83073. */
  83074. void inflate_fast (z_streamp strm, unsigned start)
  83075. {
  83076. struct inflate_state FAR *state;
  83077. unsigned char FAR *in; /* local strm->next_in */
  83078. unsigned char FAR *last; /* while in < last, enough input available */
  83079. unsigned char FAR *out; /* local strm->next_out */
  83080. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  83081. unsigned char FAR *end; /* while out < end, enough space available */
  83082. #ifdef INFLATE_STRICT
  83083. unsigned dmax; /* maximum distance from zlib header */
  83084. #endif
  83085. unsigned wsize; /* window size or zero if not using window */
  83086. unsigned whave; /* valid bytes in the window */
  83087. unsigned write; /* window write index */
  83088. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  83089. unsigned long hold; /* local strm->hold */
  83090. unsigned bits; /* local strm->bits */
  83091. code const FAR *lcode; /* local strm->lencode */
  83092. code const FAR *dcode; /* local strm->distcode */
  83093. unsigned lmask; /* mask for first level of length codes */
  83094. unsigned dmask; /* mask for first level of distance codes */
  83095. code thisx; /* retrieved table entry */
  83096. unsigned op; /* code bits, operation, extra bits, or */
  83097. /* window position, window bytes to copy */
  83098. unsigned len; /* match length, unused bytes */
  83099. unsigned dist; /* match distance */
  83100. unsigned char FAR *from; /* where to copy match from */
  83101. /* copy state to local variables */
  83102. state = (struct inflate_state FAR *)strm->state;
  83103. in = strm->next_in - OFF;
  83104. last = in + (strm->avail_in - 5);
  83105. out = strm->next_out - OFF;
  83106. beg = out - (start - strm->avail_out);
  83107. end = out + (strm->avail_out - 257);
  83108. #ifdef INFLATE_STRICT
  83109. dmax = state->dmax;
  83110. #endif
  83111. wsize = state->wsize;
  83112. whave = state->whave;
  83113. write = state->write;
  83114. window = state->window;
  83115. hold = state->hold;
  83116. bits = state->bits;
  83117. lcode = state->lencode;
  83118. dcode = state->distcode;
  83119. lmask = (1U << state->lenbits) - 1;
  83120. dmask = (1U << state->distbits) - 1;
  83121. /* decode literals and length/distances until end-of-block or not enough
  83122. input data or output space */
  83123. do {
  83124. if (bits < 15) {
  83125. hold += (unsigned long)(PUP(in)) << bits;
  83126. bits += 8;
  83127. hold += (unsigned long)(PUP(in)) << bits;
  83128. bits += 8;
  83129. }
  83130. thisx = lcode[hold & lmask];
  83131. dolen:
  83132. op = (unsigned)(thisx.bits);
  83133. hold >>= op;
  83134. bits -= op;
  83135. op = (unsigned)(thisx.op);
  83136. if (op == 0) { /* literal */
  83137. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  83138. "inflate: literal '%c'\n" :
  83139. "inflate: literal 0x%02x\n", thisx.val));
  83140. PUP(out) = (unsigned char)(thisx.val);
  83141. }
  83142. else if (op & 16) { /* length base */
  83143. len = (unsigned)(thisx.val);
  83144. op &= 15; /* number of extra bits */
  83145. if (op) {
  83146. if (bits < op) {
  83147. hold += (unsigned long)(PUP(in)) << bits;
  83148. bits += 8;
  83149. }
  83150. len += (unsigned)hold & ((1U << op) - 1);
  83151. hold >>= op;
  83152. bits -= op;
  83153. }
  83154. Tracevv((stderr, "inflate: length %u\n", len));
  83155. if (bits < 15) {
  83156. hold += (unsigned long)(PUP(in)) << bits;
  83157. bits += 8;
  83158. hold += (unsigned long)(PUP(in)) << bits;
  83159. bits += 8;
  83160. }
  83161. thisx = dcode[hold & dmask];
  83162. dodist:
  83163. op = (unsigned)(thisx.bits);
  83164. hold >>= op;
  83165. bits -= op;
  83166. op = (unsigned)(thisx.op);
  83167. if (op & 16) { /* distance base */
  83168. dist = (unsigned)(thisx.val);
  83169. op &= 15; /* number of extra bits */
  83170. if (bits < op) {
  83171. hold += (unsigned long)(PUP(in)) << bits;
  83172. bits += 8;
  83173. if (bits < op) {
  83174. hold += (unsigned long)(PUP(in)) << bits;
  83175. bits += 8;
  83176. }
  83177. }
  83178. dist += (unsigned)hold & ((1U << op) - 1);
  83179. #ifdef INFLATE_STRICT
  83180. if (dist > dmax) {
  83181. strm->msg = (char *)"invalid distance too far back";
  83182. state->mode = BAD;
  83183. break;
  83184. }
  83185. #endif
  83186. hold >>= op;
  83187. bits -= op;
  83188. Tracevv((stderr, "inflate: distance %u\n", dist));
  83189. op = (unsigned)(out - beg); /* max distance in output */
  83190. if (dist > op) { /* see if copy from window */
  83191. op = dist - op; /* distance back in window */
  83192. if (op > whave) {
  83193. strm->msg = (char *)"invalid distance too far back";
  83194. state->mode = BAD;
  83195. break;
  83196. }
  83197. from = window - OFF;
  83198. if (write == 0) { /* very common case */
  83199. from += wsize - op;
  83200. if (op < len) { /* some from window */
  83201. len -= op;
  83202. do {
  83203. PUP(out) = PUP(from);
  83204. } while (--op);
  83205. from = out - dist; /* rest from output */
  83206. }
  83207. }
  83208. else if (write < op) { /* wrap around window */
  83209. from += wsize + write - op;
  83210. op -= write;
  83211. if (op < len) { /* some from end of window */
  83212. len -= op;
  83213. do {
  83214. PUP(out) = PUP(from);
  83215. } while (--op);
  83216. from = window - OFF;
  83217. if (write < len) { /* some from start of window */
  83218. op = write;
  83219. len -= op;
  83220. do {
  83221. PUP(out) = PUP(from);
  83222. } while (--op);
  83223. from = out - dist; /* rest from output */
  83224. }
  83225. }
  83226. }
  83227. else { /* contiguous in window */
  83228. from += write - op;
  83229. if (op < len) { /* some from window */
  83230. len -= op;
  83231. do {
  83232. PUP(out) = PUP(from);
  83233. } while (--op);
  83234. from = out - dist; /* rest from output */
  83235. }
  83236. }
  83237. while (len > 2) {
  83238. PUP(out) = PUP(from);
  83239. PUP(out) = PUP(from);
  83240. PUP(out) = PUP(from);
  83241. len -= 3;
  83242. }
  83243. if (len) {
  83244. PUP(out) = PUP(from);
  83245. if (len > 1)
  83246. PUP(out) = PUP(from);
  83247. }
  83248. }
  83249. else {
  83250. from = out - dist; /* copy direct from output */
  83251. do { /* minimum length is three */
  83252. PUP(out) = PUP(from);
  83253. PUP(out) = PUP(from);
  83254. PUP(out) = PUP(from);
  83255. len -= 3;
  83256. } while (len > 2);
  83257. if (len) {
  83258. PUP(out) = PUP(from);
  83259. if (len > 1)
  83260. PUP(out) = PUP(from);
  83261. }
  83262. }
  83263. }
  83264. else if ((op & 64) == 0) { /* 2nd level distance code */
  83265. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  83266. goto dodist;
  83267. }
  83268. else {
  83269. strm->msg = (char *)"invalid distance code";
  83270. state->mode = BAD;
  83271. break;
  83272. }
  83273. }
  83274. else if ((op & 64) == 0) { /* 2nd level length code */
  83275. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  83276. goto dolen;
  83277. }
  83278. else if (op & 32) { /* end-of-block */
  83279. Tracevv((stderr, "inflate: end of block\n"));
  83280. state->mode = TYPE;
  83281. break;
  83282. }
  83283. else {
  83284. strm->msg = (char *)"invalid literal/length code";
  83285. state->mode = BAD;
  83286. break;
  83287. }
  83288. } while (in < last && out < end);
  83289. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  83290. len = bits >> 3;
  83291. in -= len;
  83292. bits -= len << 3;
  83293. hold &= (1U << bits) - 1;
  83294. /* update state and return */
  83295. strm->next_in = in + OFF;
  83296. strm->next_out = out + OFF;
  83297. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  83298. strm->avail_out = (unsigned)(out < end ?
  83299. 257 + (end - out) : 257 - (out - end));
  83300. state->hold = hold;
  83301. state->bits = bits;
  83302. return;
  83303. }
  83304. /*
  83305. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  83306. - Using bit fields for code structure
  83307. - Different op definition to avoid & for extra bits (do & for table bits)
  83308. - Three separate decoding do-loops for direct, window, and write == 0
  83309. - Special case for distance > 1 copies to do overlapped load and store copy
  83310. - Explicit branch predictions (based on measured branch probabilities)
  83311. - Deferring match copy and interspersed it with decoding subsequent codes
  83312. - Swapping literal/length else
  83313. - Swapping window/direct else
  83314. - Larger unrolled copy loops (three is about right)
  83315. - Moving len -= 3 statement into middle of loop
  83316. */
  83317. #endif /* !ASMINF */
  83318. /*** End of inlined file: inffast.c ***/
  83319. #undef PULLBYTE
  83320. #undef LOAD
  83321. #undef RESTORE
  83322. #undef INITBITS
  83323. #undef NEEDBITS
  83324. #undef DROPBITS
  83325. #undef BYTEBITS
  83326. /*** Start of inlined file: inflate.c ***/
  83327. /*
  83328. * Change history:
  83329. *
  83330. * 1.2.beta0 24 Nov 2002
  83331. * - First version -- complete rewrite of inflate to simplify code, avoid
  83332. * creation of window when not needed, minimize use of window when it is
  83333. * needed, make inffast.c even faster, implement gzip decoding, and to
  83334. * improve code readability and style over the previous zlib inflate code
  83335. *
  83336. * 1.2.beta1 25 Nov 2002
  83337. * - Use pointers for available input and output checking in inffast.c
  83338. * - Remove input and output counters in inffast.c
  83339. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  83340. * - Remove unnecessary second byte pull from length extra in inffast.c
  83341. * - Unroll direct copy to three copies per loop in inffast.c
  83342. *
  83343. * 1.2.beta2 4 Dec 2002
  83344. * - Change external routine names to reduce potential conflicts
  83345. * - Correct filename to inffixed.h for fixed tables in inflate.c
  83346. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  83347. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  83348. * to avoid negation problem on Alphas (64 bit) in inflate.c
  83349. *
  83350. * 1.2.beta3 22 Dec 2002
  83351. * - Add comments on state->bits assertion in inffast.c
  83352. * - Add comments on op field in inftrees.h
  83353. * - Fix bug in reuse of allocated window after inflateReset()
  83354. * - Remove bit fields--back to byte structure for speed
  83355. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  83356. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  83357. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  83358. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  83359. * - Use local copies of stream next and avail values, as well as local bit
  83360. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  83361. *
  83362. * 1.2.beta4 1 Jan 2003
  83363. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  83364. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  83365. * - Add comments in inffast.c to introduce the inflate_fast() routine
  83366. * - Rearrange window copies in inflate_fast() for speed and simplification
  83367. * - Unroll last copy for window match in inflate_fast()
  83368. * - Use local copies of window variables in inflate_fast() for speed
  83369. * - Pull out common write == 0 case for speed in inflate_fast()
  83370. * - Make op and len in inflate_fast() unsigned for consistency
  83371. * - Add FAR to lcode and dcode declarations in inflate_fast()
  83372. * - Simplified bad distance check in inflate_fast()
  83373. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  83374. * source file infback.c to provide a call-back interface to inflate for
  83375. * programs like gzip and unzip -- uses window as output buffer to avoid
  83376. * window copying
  83377. *
  83378. * 1.2.beta5 1 Jan 2003
  83379. * - Improved inflateBack() interface to allow the caller to provide initial
  83380. * input in strm.
  83381. * - Fixed stored blocks bug in inflateBack()
  83382. *
  83383. * 1.2.beta6 4 Jan 2003
  83384. * - Added comments in inffast.c on effectiveness of POSTINC
  83385. * - Typecasting all around to reduce compiler warnings
  83386. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  83387. * make compilers happy
  83388. * - Changed type of window in inflateBackInit() to unsigned char *
  83389. *
  83390. * 1.2.beta7 27 Jan 2003
  83391. * - Changed many types to unsigned or unsigned short to avoid warnings
  83392. * - Added inflateCopy() function
  83393. *
  83394. * 1.2.0 9 Mar 2003
  83395. * - Changed inflateBack() interface to provide separate opaque descriptors
  83396. * for the in() and out() functions
  83397. * - Changed inflateBack() argument and in_func typedef to swap the length
  83398. * and buffer address return values for the input function
  83399. * - Check next_in and next_out for Z_NULL on entry to inflate()
  83400. *
  83401. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  83402. */
  83403. /*** Start of inlined file: inffast.h ***/
  83404. /* WARNING: this file should *not* be used by applications. It is
  83405. part of the implementation of the compression library and is
  83406. subject to change. Applications should only use zlib.h.
  83407. */
  83408. void inflate_fast OF((z_streamp strm, unsigned start));
  83409. /*** End of inlined file: inffast.h ***/
  83410. #ifdef MAKEFIXED
  83411. # ifndef BUILDFIXED
  83412. # define BUILDFIXED
  83413. # endif
  83414. #endif
  83415. /* function prototypes */
  83416. local void fixedtables OF((struct inflate_state FAR *state));
  83417. local int updatewindow OF((z_streamp strm, unsigned out));
  83418. #ifdef BUILDFIXED
  83419. void makefixed OF((void));
  83420. #endif
  83421. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  83422. unsigned len));
  83423. int ZEXPORT inflateReset (z_streamp strm)
  83424. {
  83425. struct inflate_state FAR *state;
  83426. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83427. state = (struct inflate_state FAR *)strm->state;
  83428. strm->total_in = strm->total_out = state->total = 0;
  83429. strm->msg = Z_NULL;
  83430. strm->adler = 1; /* to support ill-conceived Java test suite */
  83431. state->mode = HEAD;
  83432. state->last = 0;
  83433. state->havedict = 0;
  83434. state->dmax = 32768U;
  83435. state->head = Z_NULL;
  83436. state->wsize = 0;
  83437. state->whave = 0;
  83438. state->write = 0;
  83439. state->hold = 0;
  83440. state->bits = 0;
  83441. state->lencode = state->distcode = state->next = state->codes;
  83442. Tracev((stderr, "inflate: reset\n"));
  83443. return Z_OK;
  83444. }
  83445. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  83446. {
  83447. struct inflate_state FAR *state;
  83448. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  83449. state = (struct inflate_state FAR *)strm->state;
  83450. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  83451. value &= (1L << bits) - 1;
  83452. state->hold += value << state->bits;
  83453. state->bits += bits;
  83454. return Z_OK;
  83455. }
  83456. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  83457. {
  83458. struct inflate_state FAR *state;
  83459. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  83460. stream_size != (int)(sizeof(z_stream)))
  83461. return Z_VERSION_ERROR;
  83462. if (strm == Z_NULL) return Z_STREAM_ERROR;
  83463. strm->msg = Z_NULL; /* in case we return an error */
  83464. if (strm->zalloc == (alloc_func)0) {
  83465. strm->zalloc = zcalloc;
  83466. strm->opaque = (voidpf)0;
  83467. }
  83468. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  83469. state = (struct inflate_state FAR *)
  83470. ZALLOC(strm, 1, sizeof(struct inflate_state));
  83471. if (state == Z_NULL) return Z_MEM_ERROR;
  83472. Tracev((stderr, "inflate: allocated\n"));
  83473. strm->state = (struct internal_state FAR *)state;
  83474. if (windowBits < 0) {
  83475. state->wrap = 0;
  83476. windowBits = -windowBits;
  83477. }
  83478. else {
  83479. state->wrap = (windowBits >> 4) + 1;
  83480. #ifdef GUNZIP
  83481. if (windowBits < 48) windowBits &= 15;
  83482. #endif
  83483. }
  83484. if (windowBits < 8 || windowBits > 15) {
  83485. ZFREE(strm, state);
  83486. strm->state = Z_NULL;
  83487. return Z_STREAM_ERROR;
  83488. }
  83489. state->wbits = (unsigned)windowBits;
  83490. state->window = Z_NULL;
  83491. return inflateReset(strm);
  83492. }
  83493. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  83494. {
  83495. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  83496. }
  83497. /*
  83498. Return state with length and distance decoding tables and index sizes set to
  83499. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  83500. If BUILDFIXED is defined, then instead this routine builds the tables the
  83501. first time it's called, and returns those tables the first time and
  83502. thereafter. This reduces the size of the code by about 2K bytes, in
  83503. exchange for a little execution time. However, BUILDFIXED should not be
  83504. used for threaded applications, since the rewriting of the tables and virgin
  83505. may not be thread-safe.
  83506. */
  83507. local void fixedtables (struct inflate_state FAR *state)
  83508. {
  83509. #ifdef BUILDFIXED
  83510. static int virgin = 1;
  83511. static code *lenfix, *distfix;
  83512. static code fixed[544];
  83513. /* build fixed huffman tables if first call (may not be thread safe) */
  83514. if (virgin) {
  83515. unsigned sym, bits;
  83516. static code *next;
  83517. /* literal/length table */
  83518. sym = 0;
  83519. while (sym < 144) state->lens[sym++] = 8;
  83520. while (sym < 256) state->lens[sym++] = 9;
  83521. while (sym < 280) state->lens[sym++] = 7;
  83522. while (sym < 288) state->lens[sym++] = 8;
  83523. next = fixed;
  83524. lenfix = next;
  83525. bits = 9;
  83526. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  83527. /* distance table */
  83528. sym = 0;
  83529. while (sym < 32) state->lens[sym++] = 5;
  83530. distfix = next;
  83531. bits = 5;
  83532. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  83533. /* do this just once */
  83534. virgin = 0;
  83535. }
  83536. #else /* !BUILDFIXED */
  83537. /*** Start of inlined file: inffixed.h ***/
  83538. /* WARNING: this file should *not* be used by applications. It
  83539. is part of the implementation of the compression library and
  83540. is subject to change. Applications should only use zlib.h.
  83541. */
  83542. static const code lenfix[512] = {
  83543. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  83544. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  83545. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  83546. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  83547. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  83548. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  83549. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  83550. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  83551. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  83552. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  83553. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  83554. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  83555. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  83556. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  83557. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  83558. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  83559. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  83560. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  83561. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  83562. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  83563. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  83564. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  83565. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  83566. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  83567. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  83568. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  83569. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  83570. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  83571. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  83572. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  83573. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  83574. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  83575. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  83576. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  83577. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  83578. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  83579. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  83580. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  83581. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  83582. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  83583. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  83584. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  83585. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  83586. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  83587. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  83588. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  83589. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  83590. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  83591. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  83592. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  83593. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  83594. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  83595. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  83596. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  83597. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  83598. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  83599. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  83600. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  83601. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  83602. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  83603. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  83604. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  83605. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  83606. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  83607. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  83608. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  83609. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  83610. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  83611. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  83612. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  83613. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  83614. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  83615. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  83616. {0,9,255}
  83617. };
  83618. static const code distfix[32] = {
  83619. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  83620. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  83621. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  83622. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  83623. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  83624. {22,5,193},{64,5,0}
  83625. };
  83626. /*** End of inlined file: inffixed.h ***/
  83627. #endif /* BUILDFIXED */
  83628. state->lencode = lenfix;
  83629. state->lenbits = 9;
  83630. state->distcode = distfix;
  83631. state->distbits = 5;
  83632. }
  83633. #ifdef MAKEFIXED
  83634. #include <stdio.h>
  83635. /*
  83636. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  83637. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  83638. those tables to stdout, which would be piped to inffixed.h. A small program
  83639. can simply call makefixed to do this:
  83640. void makefixed(void);
  83641. int main(void)
  83642. {
  83643. makefixed();
  83644. return 0;
  83645. }
  83646. Then that can be linked with zlib built with MAKEFIXED defined and run:
  83647. a.out > inffixed.h
  83648. */
  83649. void makefixed()
  83650. {
  83651. unsigned low, size;
  83652. struct inflate_state state;
  83653. fixedtables(&state);
  83654. puts(" /* inffixed.h -- table for decoding fixed codes");
  83655. puts(" * Generated automatically by makefixed().");
  83656. puts(" */");
  83657. puts("");
  83658. puts(" /* WARNING: this file should *not* be used by applications.");
  83659. puts(" It is part of the implementation of this library and is");
  83660. puts(" subject to change. Applications should only use zlib.h.");
  83661. puts(" */");
  83662. puts("");
  83663. size = 1U << 9;
  83664. printf(" static const code lenfix[%u] = {", size);
  83665. low = 0;
  83666. for (;;) {
  83667. if ((low % 7) == 0) printf("\n ");
  83668. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  83669. state.lencode[low].val);
  83670. if (++low == size) break;
  83671. putchar(',');
  83672. }
  83673. puts("\n };");
  83674. size = 1U << 5;
  83675. printf("\n static const code distfix[%u] = {", size);
  83676. low = 0;
  83677. for (;;) {
  83678. if ((low % 6) == 0) printf("\n ");
  83679. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  83680. state.distcode[low].val);
  83681. if (++low == size) break;
  83682. putchar(',');
  83683. }
  83684. puts("\n };");
  83685. }
  83686. #endif /* MAKEFIXED */
  83687. /*
  83688. Update the window with the last wsize (normally 32K) bytes written before
  83689. returning. If window does not exist yet, create it. This is only called
  83690. when a window is already in use, or when output has been written during this
  83691. inflate call, but the end of the deflate stream has not been reached yet.
  83692. It is also called to create a window for dictionary data when a dictionary
  83693. is loaded.
  83694. Providing output buffers larger than 32K to inflate() should provide a speed
  83695. advantage, since only the last 32K of output is copied to the sliding window
  83696. upon return from inflate(), and since all distances after the first 32K of
  83697. output will fall in the output data, making match copies simpler and faster.
  83698. The advantage may be dependent on the size of the processor's data caches.
  83699. */
  83700. local int updatewindow (z_streamp strm, unsigned out)
  83701. {
  83702. struct inflate_state FAR *state;
  83703. unsigned copy, dist;
  83704. state = (struct inflate_state FAR *)strm->state;
  83705. /* if it hasn't been done already, allocate space for the window */
  83706. if (state->window == Z_NULL) {
  83707. state->window = (unsigned char FAR *)
  83708. ZALLOC(strm, 1U << state->wbits,
  83709. sizeof(unsigned char));
  83710. if (state->window == Z_NULL) return 1;
  83711. }
  83712. /* if window not in use yet, initialize */
  83713. if (state->wsize == 0) {
  83714. state->wsize = 1U << state->wbits;
  83715. state->write = 0;
  83716. state->whave = 0;
  83717. }
  83718. /* copy state->wsize or less output bytes into the circular window */
  83719. copy = out - strm->avail_out;
  83720. if (copy >= state->wsize) {
  83721. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  83722. state->write = 0;
  83723. state->whave = state->wsize;
  83724. }
  83725. else {
  83726. dist = state->wsize - state->write;
  83727. if (dist > copy) dist = copy;
  83728. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  83729. copy -= dist;
  83730. if (copy) {
  83731. zmemcpy(state->window, strm->next_out - copy, copy);
  83732. state->write = copy;
  83733. state->whave = state->wsize;
  83734. }
  83735. else {
  83736. state->write += dist;
  83737. if (state->write == state->wsize) state->write = 0;
  83738. if (state->whave < state->wsize) state->whave += dist;
  83739. }
  83740. }
  83741. return 0;
  83742. }
  83743. /* Macros for inflate(): */
  83744. /* check function to use adler32() for zlib or crc32() for gzip */
  83745. #ifdef GUNZIP
  83746. # define UPDATE(check, buf, len) \
  83747. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  83748. #else
  83749. # define UPDATE(check, buf, len) adler32(check, buf, len)
  83750. #endif
  83751. /* check macros for header crc */
  83752. #ifdef GUNZIP
  83753. # define CRC2(check, word) \
  83754. do { \
  83755. hbuf[0] = (unsigned char)(word); \
  83756. hbuf[1] = (unsigned char)((word) >> 8); \
  83757. check = crc32(check, hbuf, 2); \
  83758. } while (0)
  83759. # define CRC4(check, word) \
  83760. do { \
  83761. hbuf[0] = (unsigned char)(word); \
  83762. hbuf[1] = (unsigned char)((word) >> 8); \
  83763. hbuf[2] = (unsigned char)((word) >> 16); \
  83764. hbuf[3] = (unsigned char)((word) >> 24); \
  83765. check = crc32(check, hbuf, 4); \
  83766. } while (0)
  83767. #endif
  83768. /* Load registers with state in inflate() for speed */
  83769. #define LOAD() \
  83770. do { \
  83771. put = strm->next_out; \
  83772. left = strm->avail_out; \
  83773. next = strm->next_in; \
  83774. have = strm->avail_in; \
  83775. hold = state->hold; \
  83776. bits = state->bits; \
  83777. } while (0)
  83778. /* Restore state from registers in inflate() */
  83779. #define RESTORE() \
  83780. do { \
  83781. strm->next_out = put; \
  83782. strm->avail_out = left; \
  83783. strm->next_in = next; \
  83784. strm->avail_in = have; \
  83785. state->hold = hold; \
  83786. state->bits = bits; \
  83787. } while (0)
  83788. /* Clear the input bit accumulator */
  83789. #define INITBITS() \
  83790. do { \
  83791. hold = 0; \
  83792. bits = 0; \
  83793. } while (0)
  83794. /* Get a byte of input into the bit accumulator, or return from inflate()
  83795. if there is no input available. */
  83796. #define PULLBYTE() \
  83797. do { \
  83798. if (have == 0) goto inf_leave; \
  83799. have--; \
  83800. hold += (unsigned long)(*next++) << bits; \
  83801. bits += 8; \
  83802. } while (0)
  83803. /* Assure that there are at least n bits in the bit accumulator. If there is
  83804. not enough available input to do that, then return from inflate(). */
  83805. #define NEEDBITS(n) \
  83806. do { \
  83807. while (bits < (unsigned)(n)) \
  83808. PULLBYTE(); \
  83809. } while (0)
  83810. /* Return the low n bits of the bit accumulator (n < 16) */
  83811. #define BITS(n) \
  83812. ((unsigned)hold & ((1U << (n)) - 1))
  83813. /* Remove n bits from the bit accumulator */
  83814. #define DROPBITS(n) \
  83815. do { \
  83816. hold >>= (n); \
  83817. bits -= (unsigned)(n); \
  83818. } while (0)
  83819. /* Remove zero to seven bits as needed to go to a byte boundary */
  83820. #define BYTEBITS() \
  83821. do { \
  83822. hold >>= bits & 7; \
  83823. bits -= bits & 7; \
  83824. } while (0)
  83825. /* Reverse the bytes in a 32-bit value */
  83826. #define REVERSE(q) \
  83827. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  83828. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  83829. /*
  83830. inflate() uses a state machine to process as much input data and generate as
  83831. much output data as possible before returning. The state machine is
  83832. structured roughly as follows:
  83833. for (;;) switch (state) {
  83834. ...
  83835. case STATEn:
  83836. if (not enough input data or output space to make progress)
  83837. return;
  83838. ... make progress ...
  83839. state = STATEm;
  83840. break;
  83841. ...
  83842. }
  83843. so when inflate() is called again, the same case is attempted again, and
  83844. if the appropriate resources are provided, the machine proceeds to the
  83845. next state. The NEEDBITS() macro is usually the way the state evaluates
  83846. whether it can proceed or should return. NEEDBITS() does the return if
  83847. the requested bits are not available. The typical use of the BITS macros
  83848. is:
  83849. NEEDBITS(n);
  83850. ... do something with BITS(n) ...
  83851. DROPBITS(n);
  83852. where NEEDBITS(n) either returns from inflate() if there isn't enough
  83853. input left to load n bits into the accumulator, or it continues. BITS(n)
  83854. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  83855. the low n bits off the accumulator. INITBITS() clears the accumulator
  83856. and sets the number of available bits to zero. BYTEBITS() discards just
  83857. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  83858. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  83859. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  83860. if there is no input available. The decoding of variable length codes uses
  83861. PULLBYTE() directly in order to pull just enough bytes to decode the next
  83862. code, and no more.
  83863. Some states loop until they get enough input, making sure that enough
  83864. state information is maintained to continue the loop where it left off
  83865. if NEEDBITS() returns in the loop. For example, want, need, and keep
  83866. would all have to actually be part of the saved state in case NEEDBITS()
  83867. returns:
  83868. case STATEw:
  83869. while (want < need) {
  83870. NEEDBITS(n);
  83871. keep[want++] = BITS(n);
  83872. DROPBITS(n);
  83873. }
  83874. state = STATEx;
  83875. case STATEx:
  83876. As shown above, if the next state is also the next case, then the break
  83877. is omitted.
  83878. A state may also return if there is not enough output space available to
  83879. complete that state. Those states are copying stored data, writing a
  83880. literal byte, and copying a matching string.
  83881. When returning, a "goto inf_leave" is used to update the total counters,
  83882. update the check value, and determine whether any progress has been made
  83883. during that inflate() call in order to return the proper return code.
  83884. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  83885. When there is a window, goto inf_leave will update the window with the last
  83886. output written. If a goto inf_leave occurs in the middle of decompression
  83887. and there is no window currently, goto inf_leave will create one and copy
  83888. output to the window for the next call of inflate().
  83889. In this implementation, the flush parameter of inflate() only affects the
  83890. return code (per zlib.h). inflate() always writes as much as possible to
  83891. strm->next_out, given the space available and the provided input--the effect
  83892. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  83893. the allocation of and copying into a sliding window until necessary, which
  83894. provides the effect documented in zlib.h for Z_FINISH when the entire input
  83895. stream available. So the only thing the flush parameter actually does is:
  83896. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  83897. will return Z_BUF_ERROR if it has not reached the end of the stream.
  83898. */
  83899. int ZEXPORT inflate (z_streamp strm, int flush)
  83900. {
  83901. struct inflate_state FAR *state;
  83902. unsigned char FAR *next; /* next input */
  83903. unsigned char FAR *put; /* next output */
  83904. unsigned have, left; /* available input and output */
  83905. unsigned long hold; /* bit buffer */
  83906. unsigned bits; /* bits in bit buffer */
  83907. unsigned in, out; /* save starting available input and output */
  83908. unsigned copy; /* number of stored or match bytes to copy */
  83909. unsigned char FAR *from; /* where to copy match bytes from */
  83910. code thisx; /* current decoding table entry */
  83911. code last; /* parent table entry */
  83912. unsigned len; /* length to copy for repeats, bits to drop */
  83913. int ret; /* return code */
  83914. #ifdef GUNZIP
  83915. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  83916. #endif
  83917. static const unsigned short order[19] = /* permutation of code lengths */
  83918. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  83919. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  83920. (strm->next_in == Z_NULL && strm->avail_in != 0))
  83921. return Z_STREAM_ERROR;
  83922. state = (struct inflate_state FAR *)strm->state;
  83923. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  83924. LOAD();
  83925. in = have;
  83926. out = left;
  83927. ret = Z_OK;
  83928. for (;;)
  83929. switch (state->mode) {
  83930. case HEAD:
  83931. if (state->wrap == 0) {
  83932. state->mode = TYPEDO;
  83933. break;
  83934. }
  83935. NEEDBITS(16);
  83936. #ifdef GUNZIP
  83937. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  83938. state->check = crc32(0L, Z_NULL, 0);
  83939. CRC2(state->check, hold);
  83940. INITBITS();
  83941. state->mode = FLAGS;
  83942. break;
  83943. }
  83944. state->flags = 0; /* expect zlib header */
  83945. if (state->head != Z_NULL)
  83946. state->head->done = -1;
  83947. if (!(state->wrap & 1) || /* check if zlib header allowed */
  83948. #else
  83949. if (
  83950. #endif
  83951. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  83952. strm->msg = (char *)"incorrect header check";
  83953. state->mode = BAD;
  83954. break;
  83955. }
  83956. if (BITS(4) != Z_DEFLATED) {
  83957. strm->msg = (char *)"unknown compression method";
  83958. state->mode = BAD;
  83959. break;
  83960. }
  83961. DROPBITS(4);
  83962. len = BITS(4) + 8;
  83963. if (len > state->wbits) {
  83964. strm->msg = (char *)"invalid window size";
  83965. state->mode = BAD;
  83966. break;
  83967. }
  83968. state->dmax = 1U << len;
  83969. Tracev((stderr, "inflate: zlib header ok\n"));
  83970. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  83971. state->mode = hold & 0x200 ? DICTID : TYPE;
  83972. INITBITS();
  83973. break;
  83974. #ifdef GUNZIP
  83975. case FLAGS:
  83976. NEEDBITS(16);
  83977. state->flags = (int)(hold);
  83978. if ((state->flags & 0xff) != Z_DEFLATED) {
  83979. strm->msg = (char *)"unknown compression method";
  83980. state->mode = BAD;
  83981. break;
  83982. }
  83983. if (state->flags & 0xe000) {
  83984. strm->msg = (char *)"unknown header flags set";
  83985. state->mode = BAD;
  83986. break;
  83987. }
  83988. if (state->head != Z_NULL)
  83989. state->head->text = (int)((hold >> 8) & 1);
  83990. if (state->flags & 0x0200) CRC2(state->check, hold);
  83991. INITBITS();
  83992. state->mode = TIME;
  83993. case TIME:
  83994. NEEDBITS(32);
  83995. if (state->head != Z_NULL)
  83996. state->head->time = hold;
  83997. if (state->flags & 0x0200) CRC4(state->check, hold);
  83998. INITBITS();
  83999. state->mode = OS;
  84000. case OS:
  84001. NEEDBITS(16);
  84002. if (state->head != Z_NULL) {
  84003. state->head->xflags = (int)(hold & 0xff);
  84004. state->head->os = (int)(hold >> 8);
  84005. }
  84006. if (state->flags & 0x0200) CRC2(state->check, hold);
  84007. INITBITS();
  84008. state->mode = EXLEN;
  84009. case EXLEN:
  84010. if (state->flags & 0x0400) {
  84011. NEEDBITS(16);
  84012. state->length = (unsigned)(hold);
  84013. if (state->head != Z_NULL)
  84014. state->head->extra_len = (unsigned)hold;
  84015. if (state->flags & 0x0200) CRC2(state->check, hold);
  84016. INITBITS();
  84017. }
  84018. else if (state->head != Z_NULL)
  84019. state->head->extra = Z_NULL;
  84020. state->mode = EXTRA;
  84021. case EXTRA:
  84022. if (state->flags & 0x0400) {
  84023. copy = state->length;
  84024. if (copy > have) copy = have;
  84025. if (copy) {
  84026. if (state->head != Z_NULL &&
  84027. state->head->extra != Z_NULL) {
  84028. len = state->head->extra_len - state->length;
  84029. zmemcpy(state->head->extra + len, next,
  84030. len + copy > state->head->extra_max ?
  84031. state->head->extra_max - len : copy);
  84032. }
  84033. if (state->flags & 0x0200)
  84034. state->check = crc32(state->check, next, copy);
  84035. have -= copy;
  84036. next += copy;
  84037. state->length -= copy;
  84038. }
  84039. if (state->length) goto inf_leave;
  84040. }
  84041. state->length = 0;
  84042. state->mode = NAME;
  84043. case NAME:
  84044. if (state->flags & 0x0800) {
  84045. if (have == 0) goto inf_leave;
  84046. copy = 0;
  84047. do {
  84048. len = (unsigned)(next[copy++]);
  84049. if (state->head != Z_NULL &&
  84050. state->head->name != Z_NULL &&
  84051. state->length < state->head->name_max)
  84052. state->head->name[state->length++] = len;
  84053. } while (len && copy < have);
  84054. if (state->flags & 0x0200)
  84055. state->check = crc32(state->check, next, copy);
  84056. have -= copy;
  84057. next += copy;
  84058. if (len) goto inf_leave;
  84059. }
  84060. else if (state->head != Z_NULL)
  84061. state->head->name = Z_NULL;
  84062. state->length = 0;
  84063. state->mode = COMMENT;
  84064. case COMMENT:
  84065. if (state->flags & 0x1000) {
  84066. if (have == 0) goto inf_leave;
  84067. copy = 0;
  84068. do {
  84069. len = (unsigned)(next[copy++]);
  84070. if (state->head != Z_NULL &&
  84071. state->head->comment != Z_NULL &&
  84072. state->length < state->head->comm_max)
  84073. state->head->comment[state->length++] = len;
  84074. } while (len && copy < have);
  84075. if (state->flags & 0x0200)
  84076. state->check = crc32(state->check, next, copy);
  84077. have -= copy;
  84078. next += copy;
  84079. if (len) goto inf_leave;
  84080. }
  84081. else if (state->head != Z_NULL)
  84082. state->head->comment = Z_NULL;
  84083. state->mode = HCRC;
  84084. case HCRC:
  84085. if (state->flags & 0x0200) {
  84086. NEEDBITS(16);
  84087. if (hold != (state->check & 0xffff)) {
  84088. strm->msg = (char *)"header crc mismatch";
  84089. state->mode = BAD;
  84090. break;
  84091. }
  84092. INITBITS();
  84093. }
  84094. if (state->head != Z_NULL) {
  84095. state->head->hcrc = (int)((state->flags >> 9) & 1);
  84096. state->head->done = 1;
  84097. }
  84098. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  84099. state->mode = TYPE;
  84100. break;
  84101. #endif
  84102. case DICTID:
  84103. NEEDBITS(32);
  84104. strm->adler = state->check = REVERSE(hold);
  84105. INITBITS();
  84106. state->mode = DICT;
  84107. case DICT:
  84108. if (state->havedict == 0) {
  84109. RESTORE();
  84110. return Z_NEED_DICT;
  84111. }
  84112. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  84113. state->mode = TYPE;
  84114. case TYPE:
  84115. if (flush == Z_BLOCK) goto inf_leave;
  84116. case TYPEDO:
  84117. if (state->last) {
  84118. BYTEBITS();
  84119. state->mode = CHECK;
  84120. break;
  84121. }
  84122. NEEDBITS(3);
  84123. state->last = BITS(1);
  84124. DROPBITS(1);
  84125. switch (BITS(2)) {
  84126. case 0: /* stored block */
  84127. Tracev((stderr, "inflate: stored block%s\n",
  84128. state->last ? " (last)" : ""));
  84129. state->mode = STORED;
  84130. break;
  84131. case 1: /* fixed block */
  84132. fixedtables(state);
  84133. Tracev((stderr, "inflate: fixed codes block%s\n",
  84134. state->last ? " (last)" : ""));
  84135. state->mode = LEN; /* decode codes */
  84136. break;
  84137. case 2: /* dynamic block */
  84138. Tracev((stderr, "inflate: dynamic codes block%s\n",
  84139. state->last ? " (last)" : ""));
  84140. state->mode = TABLE;
  84141. break;
  84142. case 3:
  84143. strm->msg = (char *)"invalid block type";
  84144. state->mode = BAD;
  84145. }
  84146. DROPBITS(2);
  84147. break;
  84148. case STORED:
  84149. BYTEBITS(); /* go to byte boundary */
  84150. NEEDBITS(32);
  84151. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  84152. strm->msg = (char *)"invalid stored block lengths";
  84153. state->mode = BAD;
  84154. break;
  84155. }
  84156. state->length = (unsigned)hold & 0xffff;
  84157. Tracev((stderr, "inflate: stored length %u\n",
  84158. state->length));
  84159. INITBITS();
  84160. state->mode = COPY;
  84161. case COPY:
  84162. copy = state->length;
  84163. if (copy) {
  84164. if (copy > have) copy = have;
  84165. if (copy > left) copy = left;
  84166. if (copy == 0) goto inf_leave;
  84167. zmemcpy(put, next, copy);
  84168. have -= copy;
  84169. next += copy;
  84170. left -= copy;
  84171. put += copy;
  84172. state->length -= copy;
  84173. break;
  84174. }
  84175. Tracev((stderr, "inflate: stored end\n"));
  84176. state->mode = TYPE;
  84177. break;
  84178. case TABLE:
  84179. NEEDBITS(14);
  84180. state->nlen = BITS(5) + 257;
  84181. DROPBITS(5);
  84182. state->ndist = BITS(5) + 1;
  84183. DROPBITS(5);
  84184. state->ncode = BITS(4) + 4;
  84185. DROPBITS(4);
  84186. #ifndef PKZIP_BUG_WORKAROUND
  84187. if (state->nlen > 286 || state->ndist > 30) {
  84188. strm->msg = (char *)"too many length or distance symbols";
  84189. state->mode = BAD;
  84190. break;
  84191. }
  84192. #endif
  84193. Tracev((stderr, "inflate: table sizes ok\n"));
  84194. state->have = 0;
  84195. state->mode = LENLENS;
  84196. case LENLENS:
  84197. while (state->have < state->ncode) {
  84198. NEEDBITS(3);
  84199. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  84200. DROPBITS(3);
  84201. }
  84202. while (state->have < 19)
  84203. state->lens[order[state->have++]] = 0;
  84204. state->next = state->codes;
  84205. state->lencode = (code const FAR *)(state->next);
  84206. state->lenbits = 7;
  84207. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  84208. &(state->lenbits), state->work);
  84209. if (ret) {
  84210. strm->msg = (char *)"invalid code lengths set";
  84211. state->mode = BAD;
  84212. break;
  84213. }
  84214. Tracev((stderr, "inflate: code lengths ok\n"));
  84215. state->have = 0;
  84216. state->mode = CODELENS;
  84217. case CODELENS:
  84218. while (state->have < state->nlen + state->ndist) {
  84219. for (;;) {
  84220. thisx = state->lencode[BITS(state->lenbits)];
  84221. if ((unsigned)(thisx.bits) <= bits) break;
  84222. PULLBYTE();
  84223. }
  84224. if (thisx.val < 16) {
  84225. NEEDBITS(thisx.bits);
  84226. DROPBITS(thisx.bits);
  84227. state->lens[state->have++] = thisx.val;
  84228. }
  84229. else {
  84230. if (thisx.val == 16) {
  84231. NEEDBITS(thisx.bits + 2);
  84232. DROPBITS(thisx.bits);
  84233. if (state->have == 0) {
  84234. strm->msg = (char *)"invalid bit length repeat";
  84235. state->mode = BAD;
  84236. break;
  84237. }
  84238. len = state->lens[state->have - 1];
  84239. copy = 3 + BITS(2);
  84240. DROPBITS(2);
  84241. }
  84242. else if (thisx.val == 17) {
  84243. NEEDBITS(thisx.bits + 3);
  84244. DROPBITS(thisx.bits);
  84245. len = 0;
  84246. copy = 3 + BITS(3);
  84247. DROPBITS(3);
  84248. }
  84249. else {
  84250. NEEDBITS(thisx.bits + 7);
  84251. DROPBITS(thisx.bits);
  84252. len = 0;
  84253. copy = 11 + BITS(7);
  84254. DROPBITS(7);
  84255. }
  84256. if (state->have + copy > state->nlen + state->ndist) {
  84257. strm->msg = (char *)"invalid bit length repeat";
  84258. state->mode = BAD;
  84259. break;
  84260. }
  84261. while (copy--)
  84262. state->lens[state->have++] = (unsigned short)len;
  84263. }
  84264. }
  84265. /* handle error breaks in while */
  84266. if (state->mode == BAD) break;
  84267. /* build code tables */
  84268. state->next = state->codes;
  84269. state->lencode = (code const FAR *)(state->next);
  84270. state->lenbits = 9;
  84271. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  84272. &(state->lenbits), state->work);
  84273. if (ret) {
  84274. strm->msg = (char *)"invalid literal/lengths set";
  84275. state->mode = BAD;
  84276. break;
  84277. }
  84278. state->distcode = (code const FAR *)(state->next);
  84279. state->distbits = 6;
  84280. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  84281. &(state->next), &(state->distbits), state->work);
  84282. if (ret) {
  84283. strm->msg = (char *)"invalid distances set";
  84284. state->mode = BAD;
  84285. break;
  84286. }
  84287. Tracev((stderr, "inflate: codes ok\n"));
  84288. state->mode = LEN;
  84289. case LEN:
  84290. if (have >= 6 && left >= 258) {
  84291. RESTORE();
  84292. inflate_fast(strm, out);
  84293. LOAD();
  84294. break;
  84295. }
  84296. for (;;) {
  84297. thisx = state->lencode[BITS(state->lenbits)];
  84298. if ((unsigned)(thisx.bits) <= bits) break;
  84299. PULLBYTE();
  84300. }
  84301. if (thisx.op && (thisx.op & 0xf0) == 0) {
  84302. last = thisx;
  84303. for (;;) {
  84304. thisx = state->lencode[last.val +
  84305. (BITS(last.bits + last.op) >> last.bits)];
  84306. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84307. PULLBYTE();
  84308. }
  84309. DROPBITS(last.bits);
  84310. }
  84311. DROPBITS(thisx.bits);
  84312. state->length = (unsigned)thisx.val;
  84313. if ((int)(thisx.op) == 0) {
  84314. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  84315. "inflate: literal '%c'\n" :
  84316. "inflate: literal 0x%02x\n", thisx.val));
  84317. state->mode = LIT;
  84318. break;
  84319. }
  84320. if (thisx.op & 32) {
  84321. Tracevv((stderr, "inflate: end of block\n"));
  84322. state->mode = TYPE;
  84323. break;
  84324. }
  84325. if (thisx.op & 64) {
  84326. strm->msg = (char *)"invalid literal/length code";
  84327. state->mode = BAD;
  84328. break;
  84329. }
  84330. state->extra = (unsigned)(thisx.op) & 15;
  84331. state->mode = LENEXT;
  84332. case LENEXT:
  84333. if (state->extra) {
  84334. NEEDBITS(state->extra);
  84335. state->length += BITS(state->extra);
  84336. DROPBITS(state->extra);
  84337. }
  84338. Tracevv((stderr, "inflate: length %u\n", state->length));
  84339. state->mode = DIST;
  84340. case DIST:
  84341. for (;;) {
  84342. thisx = state->distcode[BITS(state->distbits)];
  84343. if ((unsigned)(thisx.bits) <= bits) break;
  84344. PULLBYTE();
  84345. }
  84346. if ((thisx.op & 0xf0) == 0) {
  84347. last = thisx;
  84348. for (;;) {
  84349. thisx = state->distcode[last.val +
  84350. (BITS(last.bits + last.op) >> last.bits)];
  84351. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  84352. PULLBYTE();
  84353. }
  84354. DROPBITS(last.bits);
  84355. }
  84356. DROPBITS(thisx.bits);
  84357. if (thisx.op & 64) {
  84358. strm->msg = (char *)"invalid distance code";
  84359. state->mode = BAD;
  84360. break;
  84361. }
  84362. state->offset = (unsigned)thisx.val;
  84363. state->extra = (unsigned)(thisx.op) & 15;
  84364. state->mode = DISTEXT;
  84365. case DISTEXT:
  84366. if (state->extra) {
  84367. NEEDBITS(state->extra);
  84368. state->offset += BITS(state->extra);
  84369. DROPBITS(state->extra);
  84370. }
  84371. #ifdef INFLATE_STRICT
  84372. if (state->offset > state->dmax) {
  84373. strm->msg = (char *)"invalid distance too far back";
  84374. state->mode = BAD;
  84375. break;
  84376. }
  84377. #endif
  84378. if (state->offset > state->whave + out - left) {
  84379. strm->msg = (char *)"invalid distance too far back";
  84380. state->mode = BAD;
  84381. break;
  84382. }
  84383. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  84384. state->mode = MATCH;
  84385. case MATCH:
  84386. if (left == 0) goto inf_leave;
  84387. copy = out - left;
  84388. if (state->offset > copy) { /* copy from window */
  84389. copy = state->offset - copy;
  84390. if (copy > state->write) {
  84391. copy -= state->write;
  84392. from = state->window + (state->wsize - copy);
  84393. }
  84394. else
  84395. from = state->window + (state->write - copy);
  84396. if (copy > state->length) copy = state->length;
  84397. }
  84398. else { /* copy from output */
  84399. from = put - state->offset;
  84400. copy = state->length;
  84401. }
  84402. if (copy > left) copy = left;
  84403. left -= copy;
  84404. state->length -= copy;
  84405. do {
  84406. *put++ = *from++;
  84407. } while (--copy);
  84408. if (state->length == 0) state->mode = LEN;
  84409. break;
  84410. case LIT:
  84411. if (left == 0) goto inf_leave;
  84412. *put++ = (unsigned char)(state->length);
  84413. left--;
  84414. state->mode = LEN;
  84415. break;
  84416. case CHECK:
  84417. if (state->wrap) {
  84418. NEEDBITS(32);
  84419. out -= left;
  84420. strm->total_out += out;
  84421. state->total += out;
  84422. if (out)
  84423. strm->adler = state->check =
  84424. UPDATE(state->check, put - out, out);
  84425. out = left;
  84426. if ((
  84427. #ifdef GUNZIP
  84428. state->flags ? hold :
  84429. #endif
  84430. REVERSE(hold)) != state->check) {
  84431. strm->msg = (char *)"incorrect data check";
  84432. state->mode = BAD;
  84433. break;
  84434. }
  84435. INITBITS();
  84436. Tracev((stderr, "inflate: check matches trailer\n"));
  84437. }
  84438. #ifdef GUNZIP
  84439. state->mode = LENGTH;
  84440. case LENGTH:
  84441. if (state->wrap && state->flags) {
  84442. NEEDBITS(32);
  84443. if (hold != (state->total & 0xffffffffUL)) {
  84444. strm->msg = (char *)"incorrect length check";
  84445. state->mode = BAD;
  84446. break;
  84447. }
  84448. INITBITS();
  84449. Tracev((stderr, "inflate: length matches trailer\n"));
  84450. }
  84451. #endif
  84452. state->mode = DONE;
  84453. case DONE:
  84454. ret = Z_STREAM_END;
  84455. goto inf_leave;
  84456. case BAD:
  84457. ret = Z_DATA_ERROR;
  84458. goto inf_leave;
  84459. case MEM:
  84460. return Z_MEM_ERROR;
  84461. case SYNC:
  84462. default:
  84463. return Z_STREAM_ERROR;
  84464. }
  84465. /*
  84466. Return from inflate(), updating the total counts and the check value.
  84467. If there was no progress during the inflate() call, return a buffer
  84468. error. Call updatewindow() to create and/or update the window state.
  84469. Note: a memory error from inflate() is non-recoverable.
  84470. */
  84471. inf_leave:
  84472. RESTORE();
  84473. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  84474. if (updatewindow(strm, out)) {
  84475. state->mode = MEM;
  84476. return Z_MEM_ERROR;
  84477. }
  84478. in -= strm->avail_in;
  84479. out -= strm->avail_out;
  84480. strm->total_in += in;
  84481. strm->total_out += out;
  84482. state->total += out;
  84483. if (state->wrap && out)
  84484. strm->adler = state->check =
  84485. UPDATE(state->check, strm->next_out - out, out);
  84486. strm->data_type = state->bits + (state->last ? 64 : 0) +
  84487. (state->mode == TYPE ? 128 : 0);
  84488. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  84489. ret = Z_BUF_ERROR;
  84490. return ret;
  84491. }
  84492. int ZEXPORT inflateEnd (z_streamp strm)
  84493. {
  84494. struct inflate_state FAR *state;
  84495. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  84496. return Z_STREAM_ERROR;
  84497. state = (struct inflate_state FAR *)strm->state;
  84498. if (state->window != Z_NULL) ZFREE(strm, state->window);
  84499. ZFREE(strm, strm->state);
  84500. strm->state = Z_NULL;
  84501. Tracev((stderr, "inflate: end\n"));
  84502. return Z_OK;
  84503. }
  84504. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  84505. {
  84506. struct inflate_state FAR *state;
  84507. unsigned long id_;
  84508. /* check state */
  84509. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84510. state = (struct inflate_state FAR *)strm->state;
  84511. if (state->wrap != 0 && state->mode != DICT)
  84512. return Z_STREAM_ERROR;
  84513. /* check for correct dictionary id */
  84514. if (state->mode == DICT) {
  84515. id_ = adler32(0L, Z_NULL, 0);
  84516. id_ = adler32(id_, dictionary, dictLength);
  84517. if (id_ != state->check)
  84518. return Z_DATA_ERROR;
  84519. }
  84520. /* copy dictionary to window */
  84521. if (updatewindow(strm, strm->avail_out)) {
  84522. state->mode = MEM;
  84523. return Z_MEM_ERROR;
  84524. }
  84525. if (dictLength > state->wsize) {
  84526. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  84527. state->wsize);
  84528. state->whave = state->wsize;
  84529. }
  84530. else {
  84531. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  84532. dictLength);
  84533. state->whave = dictLength;
  84534. }
  84535. state->havedict = 1;
  84536. Tracev((stderr, "inflate: dictionary set\n"));
  84537. return Z_OK;
  84538. }
  84539. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  84540. {
  84541. struct inflate_state FAR *state;
  84542. /* check state */
  84543. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84544. state = (struct inflate_state FAR *)strm->state;
  84545. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  84546. /* save header structure */
  84547. state->head = head;
  84548. head->done = 0;
  84549. return Z_OK;
  84550. }
  84551. /*
  84552. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  84553. or when out of input. When called, *have is the number of pattern bytes
  84554. found in order so far, in 0..3. On return *have is updated to the new
  84555. state. If on return *have equals four, then the pattern was found and the
  84556. return value is how many bytes were read including the last byte of the
  84557. pattern. If *have is less than four, then the pattern has not been found
  84558. yet and the return value is len. In the latter case, syncsearch() can be
  84559. called again with more data and the *have state. *have is initialized to
  84560. zero for the first call.
  84561. */
  84562. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  84563. {
  84564. unsigned got;
  84565. unsigned next;
  84566. got = *have;
  84567. next = 0;
  84568. while (next < len && got < 4) {
  84569. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  84570. got++;
  84571. else if (buf[next])
  84572. got = 0;
  84573. else
  84574. got = 4 - got;
  84575. next++;
  84576. }
  84577. *have = got;
  84578. return next;
  84579. }
  84580. int ZEXPORT inflateSync (z_streamp strm)
  84581. {
  84582. unsigned len; /* number of bytes to look at or looked at */
  84583. unsigned long in, out; /* temporary to save total_in and total_out */
  84584. unsigned char buf[4]; /* to restore bit buffer to byte string */
  84585. struct inflate_state FAR *state;
  84586. /* check parameters */
  84587. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84588. state = (struct inflate_state FAR *)strm->state;
  84589. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  84590. /* if first time, start search in bit buffer */
  84591. if (state->mode != SYNC) {
  84592. state->mode = SYNC;
  84593. state->hold <<= state->bits & 7;
  84594. state->bits -= state->bits & 7;
  84595. len = 0;
  84596. while (state->bits >= 8) {
  84597. buf[len++] = (unsigned char)(state->hold);
  84598. state->hold >>= 8;
  84599. state->bits -= 8;
  84600. }
  84601. state->have = 0;
  84602. syncsearch(&(state->have), buf, len);
  84603. }
  84604. /* search available input */
  84605. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  84606. strm->avail_in -= len;
  84607. strm->next_in += len;
  84608. strm->total_in += len;
  84609. /* return no joy or set up to restart inflate() on a new block */
  84610. if (state->have != 4) return Z_DATA_ERROR;
  84611. in = strm->total_in; out = strm->total_out;
  84612. inflateReset(strm);
  84613. strm->total_in = in; strm->total_out = out;
  84614. state->mode = TYPE;
  84615. return Z_OK;
  84616. }
  84617. /*
  84618. Returns true if inflate is currently at the end of a block generated by
  84619. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  84620. implementation to provide an additional safety check. PPP uses
  84621. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  84622. block. When decompressing, PPP checks that at the end of input packet,
  84623. inflate is waiting for these length bytes.
  84624. */
  84625. int ZEXPORT inflateSyncPoint (z_streamp strm)
  84626. {
  84627. struct inflate_state FAR *state;
  84628. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  84629. state = (struct inflate_state FAR *)strm->state;
  84630. return state->mode == STORED && state->bits == 0;
  84631. }
  84632. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  84633. {
  84634. struct inflate_state FAR *state;
  84635. struct inflate_state FAR *copy;
  84636. unsigned char FAR *window;
  84637. unsigned wsize;
  84638. /* check input */
  84639. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  84640. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  84641. return Z_STREAM_ERROR;
  84642. state = (struct inflate_state FAR *)source->state;
  84643. /* allocate space */
  84644. copy = (struct inflate_state FAR *)
  84645. ZALLOC(source, 1, sizeof(struct inflate_state));
  84646. if (copy == Z_NULL) return Z_MEM_ERROR;
  84647. window = Z_NULL;
  84648. if (state->window != Z_NULL) {
  84649. window = (unsigned char FAR *)
  84650. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  84651. if (window == Z_NULL) {
  84652. ZFREE(source, copy);
  84653. return Z_MEM_ERROR;
  84654. }
  84655. }
  84656. /* copy state */
  84657. zmemcpy(dest, source, sizeof(z_stream));
  84658. zmemcpy(copy, state, sizeof(struct inflate_state));
  84659. if (state->lencode >= state->codes &&
  84660. state->lencode <= state->codes + ENOUGH - 1) {
  84661. copy->lencode = copy->codes + (state->lencode - state->codes);
  84662. copy->distcode = copy->codes + (state->distcode - state->codes);
  84663. }
  84664. copy->next = copy->codes + (state->next - state->codes);
  84665. if (window != Z_NULL) {
  84666. wsize = 1U << state->wbits;
  84667. zmemcpy(window, state->window, wsize);
  84668. }
  84669. copy->window = window;
  84670. dest->state = (struct internal_state FAR *)copy;
  84671. return Z_OK;
  84672. }
  84673. /*** End of inlined file: inflate.c ***/
  84674. /*** Start of inlined file: inftrees.c ***/
  84675. #define MAXBITS 15
  84676. const char inflate_copyright[] =
  84677. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  84678. /*
  84679. If you use the zlib library in a product, an acknowledgment is welcome
  84680. in the documentation of your product. If for some reason you cannot
  84681. include such an acknowledgment, I would appreciate that you keep this
  84682. copyright string in the executable of your product.
  84683. */
  84684. /*
  84685. Build a set of tables to decode the provided canonical Huffman code.
  84686. The code lengths are lens[0..codes-1]. The result starts at *table,
  84687. whose indices are 0..2^bits-1. work is a writable array of at least
  84688. lens shorts, which is used as a work area. type is the type of code
  84689. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  84690. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  84691. on return points to the next available entry's address. bits is the
  84692. requested root table index bits, and on return it is the actual root
  84693. table index bits. It will differ if the request is greater than the
  84694. longest code or if it is less than the shortest code.
  84695. */
  84696. int inflate_table (codetype type,
  84697. unsigned short FAR *lens,
  84698. unsigned codes,
  84699. code FAR * FAR *table,
  84700. unsigned FAR *bits,
  84701. unsigned short FAR *work)
  84702. {
  84703. unsigned len; /* a code's length in bits */
  84704. unsigned sym; /* index of code symbols */
  84705. unsigned min, max; /* minimum and maximum code lengths */
  84706. unsigned root; /* number of index bits for root table */
  84707. unsigned curr; /* number of index bits for current table */
  84708. unsigned drop; /* code bits to drop for sub-table */
  84709. int left; /* number of prefix codes available */
  84710. unsigned used; /* code entries in table used */
  84711. unsigned huff; /* Huffman code */
  84712. unsigned incr; /* for incrementing code, index */
  84713. unsigned fill; /* index for replicating entries */
  84714. unsigned low; /* low bits for current root entry */
  84715. unsigned mask; /* mask for low root bits */
  84716. code thisx; /* table entry for duplication */
  84717. code FAR *next; /* next available space in table */
  84718. const unsigned short FAR *base; /* base value table to use */
  84719. const unsigned short FAR *extra; /* extra bits table to use */
  84720. int end; /* use base and extra for symbol > end */
  84721. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  84722. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  84723. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  84724. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  84725. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  84726. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  84727. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  84728. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  84729. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  84730. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  84731. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  84732. 8193, 12289, 16385, 24577, 0, 0};
  84733. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  84734. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  84735. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  84736. 28, 28, 29, 29, 64, 64};
  84737. /*
  84738. Process a set of code lengths to create a canonical Huffman code. The
  84739. code lengths are lens[0..codes-1]. Each length corresponds to the
  84740. symbols 0..codes-1. The Huffman code is generated by first sorting the
  84741. symbols by length from short to long, and retaining the symbol order
  84742. for codes with equal lengths. Then the code starts with all zero bits
  84743. for the first code of the shortest length, and the codes are integer
  84744. increments for the same length, and zeros are appended as the length
  84745. increases. For the deflate format, these bits are stored backwards
  84746. from their more natural integer increment ordering, and so when the
  84747. decoding tables are built in the large loop below, the integer codes
  84748. are incremented backwards.
  84749. This routine assumes, but does not check, that all of the entries in
  84750. lens[] are in the range 0..MAXBITS. The caller must assure this.
  84751. 1..MAXBITS is interpreted as that code length. zero means that that
  84752. symbol does not occur in this code.
  84753. The codes are sorted by computing a count of codes for each length,
  84754. creating from that a table of starting indices for each length in the
  84755. sorted table, and then entering the symbols in order in the sorted
  84756. table. The sorted table is work[], with that space being provided by
  84757. the caller.
  84758. The length counts are used for other purposes as well, i.e. finding
  84759. the minimum and maximum length codes, determining if there are any
  84760. codes at all, checking for a valid set of lengths, and looking ahead
  84761. at length counts to determine sub-table sizes when building the
  84762. decoding tables.
  84763. */
  84764. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  84765. for (len = 0; len <= MAXBITS; len++)
  84766. count[len] = 0;
  84767. for (sym = 0; sym < codes; sym++)
  84768. count[lens[sym]]++;
  84769. /* bound code lengths, force root to be within code lengths */
  84770. root = *bits;
  84771. for (max = MAXBITS; max >= 1; max--)
  84772. if (count[max] != 0) break;
  84773. if (root > max) root = max;
  84774. if (max == 0) { /* no symbols to code at all */
  84775. thisx.op = (unsigned char)64; /* invalid code marker */
  84776. thisx.bits = (unsigned char)1;
  84777. thisx.val = (unsigned short)0;
  84778. *(*table)++ = thisx; /* make a table to force an error */
  84779. *(*table)++ = thisx;
  84780. *bits = 1;
  84781. return 0; /* no symbols, but wait for decoding to report error */
  84782. }
  84783. for (min = 1; min <= MAXBITS; min++)
  84784. if (count[min] != 0) break;
  84785. if (root < min) root = min;
  84786. /* check for an over-subscribed or incomplete set of lengths */
  84787. left = 1;
  84788. for (len = 1; len <= MAXBITS; len++) {
  84789. left <<= 1;
  84790. left -= count[len];
  84791. if (left < 0) return -1; /* over-subscribed */
  84792. }
  84793. if (left > 0 && (type == CODES || max != 1))
  84794. return -1; /* incomplete set */
  84795. /* generate offsets into symbol table for each length for sorting */
  84796. offs[1] = 0;
  84797. for (len = 1; len < MAXBITS; len++)
  84798. offs[len + 1] = offs[len] + count[len];
  84799. /* sort symbols by length, by symbol order within each length */
  84800. for (sym = 0; sym < codes; sym++)
  84801. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  84802. /*
  84803. Create and fill in decoding tables. In this loop, the table being
  84804. filled is at next and has curr index bits. The code being used is huff
  84805. with length len. That code is converted to an index by dropping drop
  84806. bits off of the bottom. For codes where len is less than drop + curr,
  84807. those top drop + curr - len bits are incremented through all values to
  84808. fill the table with replicated entries.
  84809. root is the number of index bits for the root table. When len exceeds
  84810. root, sub-tables are created pointed to by the root entry with an index
  84811. of the low root bits of huff. This is saved in low to check for when a
  84812. new sub-table should be started. drop is zero when the root table is
  84813. being filled, and drop is root when sub-tables are being filled.
  84814. When a new sub-table is needed, it is necessary to look ahead in the
  84815. code lengths to determine what size sub-table is needed. The length
  84816. counts are used for this, and so count[] is decremented as codes are
  84817. entered in the tables.
  84818. used keeps track of how many table entries have been allocated from the
  84819. provided *table space. It is checked when a LENS table is being made
  84820. against the space in *table, ENOUGH, minus the maximum space needed by
  84821. the worst case distance code, MAXD. This should never happen, but the
  84822. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  84823. This assumes that when type == LENS, bits == 9.
  84824. sym increments through all symbols, and the loop terminates when
  84825. all codes of length max, i.e. all codes, have been processed. This
  84826. routine permits incomplete codes, so another loop after this one fills
  84827. in the rest of the decoding tables with invalid code markers.
  84828. */
  84829. /* set up for code type */
  84830. switch (type) {
  84831. case CODES:
  84832. base = extra = work; /* dummy value--not used */
  84833. end = 19;
  84834. break;
  84835. case LENS:
  84836. base = lbase;
  84837. base -= 257;
  84838. extra = lext;
  84839. extra -= 257;
  84840. end = 256;
  84841. break;
  84842. default: /* DISTS */
  84843. base = dbase;
  84844. extra = dext;
  84845. end = -1;
  84846. }
  84847. /* initialize state for loop */
  84848. huff = 0; /* starting code */
  84849. sym = 0; /* starting code symbol */
  84850. len = min; /* starting code length */
  84851. next = *table; /* current table to fill in */
  84852. curr = root; /* current table index bits */
  84853. drop = 0; /* current bits to drop from code for index */
  84854. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  84855. used = 1U << root; /* use root table entries */
  84856. mask = used - 1; /* mask for comparing low */
  84857. /* check available table space */
  84858. if (type == LENS && used >= ENOUGH - MAXD)
  84859. return 1;
  84860. /* process all codes and make table entries */
  84861. for (;;) {
  84862. /* create table entry */
  84863. thisx.bits = (unsigned char)(len - drop);
  84864. if ((int)(work[sym]) < end) {
  84865. thisx.op = (unsigned char)0;
  84866. thisx.val = work[sym];
  84867. }
  84868. else if ((int)(work[sym]) > end) {
  84869. thisx.op = (unsigned char)(extra[work[sym]]);
  84870. thisx.val = base[work[sym]];
  84871. }
  84872. else {
  84873. thisx.op = (unsigned char)(32 + 64); /* end of block */
  84874. thisx.val = 0;
  84875. }
  84876. /* replicate for those indices with low len bits equal to huff */
  84877. incr = 1U << (len - drop);
  84878. fill = 1U << curr;
  84879. min = fill; /* save offset to next table */
  84880. do {
  84881. fill -= incr;
  84882. next[(huff >> drop) + fill] = thisx;
  84883. } while (fill != 0);
  84884. /* backwards increment the len-bit code huff */
  84885. incr = 1U << (len - 1);
  84886. while (huff & incr)
  84887. incr >>= 1;
  84888. if (incr != 0) {
  84889. huff &= incr - 1;
  84890. huff += incr;
  84891. }
  84892. else
  84893. huff = 0;
  84894. /* go to next symbol, update count, len */
  84895. sym++;
  84896. if (--(count[len]) == 0) {
  84897. if (len == max) break;
  84898. len = lens[work[sym]];
  84899. }
  84900. /* create new sub-table if needed */
  84901. if (len > root && (huff & mask) != low) {
  84902. /* if first time, transition to sub-tables */
  84903. if (drop == 0)
  84904. drop = root;
  84905. /* increment past last table */
  84906. next += min; /* here min is 1 << curr */
  84907. /* determine length of next table */
  84908. curr = len - drop;
  84909. left = (int)(1 << curr);
  84910. while (curr + drop < max) {
  84911. left -= count[curr + drop];
  84912. if (left <= 0) break;
  84913. curr++;
  84914. left <<= 1;
  84915. }
  84916. /* check for enough space */
  84917. used += 1U << curr;
  84918. if (type == LENS && used >= ENOUGH - MAXD)
  84919. return 1;
  84920. /* point entry in root table to sub-table */
  84921. low = huff & mask;
  84922. (*table)[low].op = (unsigned char)curr;
  84923. (*table)[low].bits = (unsigned char)root;
  84924. (*table)[low].val = (unsigned short)(next - *table);
  84925. }
  84926. }
  84927. /*
  84928. Fill in rest of table for incomplete codes. This loop is similar to the
  84929. loop above in incrementing huff for table indices. It is assumed that
  84930. len is equal to curr + drop, so there is no loop needed to increment
  84931. through high index bits. When the current sub-table is filled, the loop
  84932. drops back to the root table to fill in any remaining entries there.
  84933. */
  84934. thisx.op = (unsigned char)64; /* invalid code marker */
  84935. thisx.bits = (unsigned char)(len - drop);
  84936. thisx.val = (unsigned short)0;
  84937. while (huff != 0) {
  84938. /* when done with sub-table, drop back to root table */
  84939. if (drop != 0 && (huff & mask) != low) {
  84940. drop = 0;
  84941. len = root;
  84942. next = *table;
  84943. thisx.bits = (unsigned char)len;
  84944. }
  84945. /* put invalid code marker in table */
  84946. next[huff >> drop] = thisx;
  84947. /* backwards increment the len-bit code huff */
  84948. incr = 1U << (len - 1);
  84949. while (huff & incr)
  84950. incr >>= 1;
  84951. if (incr != 0) {
  84952. huff &= incr - 1;
  84953. huff += incr;
  84954. }
  84955. else
  84956. huff = 0;
  84957. }
  84958. /* set return parameters */
  84959. *table += used;
  84960. *bits = root;
  84961. return 0;
  84962. }
  84963. /*** End of inlined file: inftrees.c ***/
  84964. /*** Start of inlined file: trees.c ***/
  84965. /*
  84966. * ALGORITHM
  84967. *
  84968. * The "deflation" process uses several Huffman trees. The more
  84969. * common source values are represented by shorter bit sequences.
  84970. *
  84971. * Each code tree is stored in a compressed form which is itself
  84972. * a Huffman encoding of the lengths of all the code strings (in
  84973. * ascending order by source values). The actual code strings are
  84974. * reconstructed from the lengths in the inflate process, as described
  84975. * in the deflate specification.
  84976. *
  84977. * REFERENCES
  84978. *
  84979. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  84980. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  84981. *
  84982. * Storer, James A.
  84983. * Data Compression: Methods and Theory, pp. 49-50.
  84984. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  84985. *
  84986. * Sedgewick, R.
  84987. * Algorithms, p290.
  84988. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  84989. */
  84990. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  84991. /* #define GEN_TREES_H */
  84992. #ifdef DEBUG
  84993. # include <ctype.h>
  84994. #endif
  84995. /* ===========================================================================
  84996. * Constants
  84997. */
  84998. #define MAX_BL_BITS 7
  84999. /* Bit length codes must not exceed MAX_BL_BITS bits */
  85000. #define END_BLOCK 256
  85001. /* end of block literal code */
  85002. #define REP_3_6 16
  85003. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  85004. #define REPZ_3_10 17
  85005. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  85006. #define REPZ_11_138 18
  85007. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  85008. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  85009. = {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};
  85010. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  85011. = {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};
  85012. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  85013. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  85014. local const uch bl_order[BL_CODES]
  85015. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  85016. /* The lengths of the bit length codes are sent in order of decreasing
  85017. * probability, to avoid transmitting the lengths for unused bit length codes.
  85018. */
  85019. #define Buf_size (8 * 2*sizeof(char))
  85020. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  85021. * more than 16 bits on some systems.)
  85022. */
  85023. /* ===========================================================================
  85024. * Local data. These are initialized only once.
  85025. */
  85026. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  85027. #if defined(GEN_TREES_H) || !defined(STDC)
  85028. /* non ANSI compilers may not accept trees.h */
  85029. local ct_data static_ltree[L_CODES+2];
  85030. /* The static literal tree. Since the bit lengths are imposed, there is no
  85031. * need for the L_CODES extra codes used during heap construction. However
  85032. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  85033. * below).
  85034. */
  85035. local ct_data static_dtree[D_CODES];
  85036. /* The static distance tree. (Actually a trivial tree since all codes use
  85037. * 5 bits.)
  85038. */
  85039. uch _dist_code[DIST_CODE_LEN];
  85040. /* Distance codes. The first 256 values correspond to the distances
  85041. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  85042. * the 15 bit distances.
  85043. */
  85044. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  85045. /* length code for each normalized match length (0 == MIN_MATCH) */
  85046. local int base_length[LENGTH_CODES];
  85047. /* First normalized length for each code (0 = MIN_MATCH) */
  85048. local int base_dist[D_CODES];
  85049. /* First normalized distance for each code (0 = distance of 1) */
  85050. #else
  85051. /*** Start of inlined file: trees.h ***/
  85052. local const ct_data static_ltree[L_CODES+2] = {
  85053. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  85054. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  85055. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  85056. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  85057. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  85058. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  85059. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  85060. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  85061. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  85062. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  85063. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  85064. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  85065. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  85066. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  85067. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  85068. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  85069. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  85070. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  85071. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  85072. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  85073. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  85074. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  85075. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  85076. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  85077. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  85078. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  85079. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  85080. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  85081. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  85082. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  85083. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  85084. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  85085. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  85086. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  85087. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  85088. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  85089. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  85090. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  85091. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  85092. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  85093. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  85094. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  85095. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  85096. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  85097. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  85098. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  85099. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  85100. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  85101. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  85102. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  85103. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  85104. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  85105. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  85106. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  85107. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  85108. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  85109. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  85110. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  85111. };
  85112. local const ct_data static_dtree[D_CODES] = {
  85113. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  85114. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  85115. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  85116. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  85117. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  85118. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  85119. };
  85120. const uch _dist_code[DIST_CODE_LEN] = {
  85121. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  85122. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  85123. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  85124. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  85125. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  85126. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  85127. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85128. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85129. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  85130. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  85131. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85132. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  85133. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  85134. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  85135. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85136. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85137. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85138. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  85139. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85140. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85141. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85142. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  85143. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85144. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85145. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  85146. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  85147. };
  85148. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  85149. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  85150. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  85151. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  85152. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  85153. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  85154. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  85155. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85156. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  85157. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  85158. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  85159. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  85160. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  85161. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  85162. };
  85163. local const int base_length[LENGTH_CODES] = {
  85164. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  85165. 64, 80, 96, 112, 128, 160, 192, 224, 0
  85166. };
  85167. local const int base_dist[D_CODES] = {
  85168. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  85169. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  85170. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  85171. };
  85172. /*** End of inlined file: trees.h ***/
  85173. #endif /* GEN_TREES_H */
  85174. struct static_tree_desc_s {
  85175. const ct_data *static_tree; /* static tree or NULL */
  85176. const intf *extra_bits; /* extra bits for each code or NULL */
  85177. int extra_base; /* base index for extra_bits */
  85178. int elems; /* max number of elements in the tree */
  85179. int max_length; /* max bit length for the codes */
  85180. };
  85181. local static_tree_desc static_l_desc =
  85182. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  85183. local static_tree_desc static_d_desc =
  85184. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  85185. local static_tree_desc static_bl_desc =
  85186. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  85187. /* ===========================================================================
  85188. * Local (static) routines in this file.
  85189. */
  85190. local void tr_static_init OF((void));
  85191. local void init_block OF((deflate_state *s));
  85192. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  85193. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  85194. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  85195. local void build_tree OF((deflate_state *s, tree_desc *desc));
  85196. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85197. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  85198. local int build_bl_tree OF((deflate_state *s));
  85199. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  85200. int blcodes));
  85201. local void compress_block OF((deflate_state *s, ct_data *ltree,
  85202. ct_data *dtree));
  85203. local void set_data_type OF((deflate_state *s));
  85204. local unsigned bi_reverse OF((unsigned value, int length));
  85205. local void bi_windup OF((deflate_state *s));
  85206. local void bi_flush OF((deflate_state *s));
  85207. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  85208. int header));
  85209. #ifdef GEN_TREES_H
  85210. local void gen_trees_header OF((void));
  85211. #endif
  85212. #ifndef DEBUG
  85213. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  85214. /* Send a code of the given tree. c and tree must not have side effects */
  85215. #else /* DEBUG */
  85216. # define send_code(s, c, tree) \
  85217. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  85218. send_bits(s, tree[c].Code, tree[c].Len); }
  85219. #endif
  85220. /* ===========================================================================
  85221. * Output a short LSB first on the stream.
  85222. * IN assertion: there is enough room in pendingBuf.
  85223. */
  85224. #define put_short(s, w) { \
  85225. put_byte(s, (uch)((w) & 0xff)); \
  85226. put_byte(s, (uch)((ush)(w) >> 8)); \
  85227. }
  85228. /* ===========================================================================
  85229. * Send a value on a given number of bits.
  85230. * IN assertion: length <= 16 and value fits in length bits.
  85231. */
  85232. #ifdef DEBUG
  85233. local void send_bits OF((deflate_state *s, int value, int length));
  85234. local void send_bits (deflate_state *s, int value, int length)
  85235. {
  85236. Tracevv((stderr," l %2d v %4x ", length, value));
  85237. Assert(length > 0 && length <= 15, "invalid length");
  85238. s->bits_sent += (ulg)length;
  85239. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  85240. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  85241. * unused bits in value.
  85242. */
  85243. if (s->bi_valid > (int)Buf_size - length) {
  85244. s->bi_buf |= (value << s->bi_valid);
  85245. put_short(s, s->bi_buf);
  85246. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  85247. s->bi_valid += length - Buf_size;
  85248. } else {
  85249. s->bi_buf |= value << s->bi_valid;
  85250. s->bi_valid += length;
  85251. }
  85252. }
  85253. #else /* !DEBUG */
  85254. #define send_bits(s, value, length) \
  85255. { int len = length;\
  85256. if (s->bi_valid > (int)Buf_size - len) {\
  85257. int val = value;\
  85258. s->bi_buf |= (val << s->bi_valid);\
  85259. put_short(s, s->bi_buf);\
  85260. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  85261. s->bi_valid += len - Buf_size;\
  85262. } else {\
  85263. s->bi_buf |= (value) << s->bi_valid;\
  85264. s->bi_valid += len;\
  85265. }\
  85266. }
  85267. #endif /* DEBUG */
  85268. /* the arguments must not have side effects */
  85269. /* ===========================================================================
  85270. * Initialize the various 'constant' tables.
  85271. */
  85272. local void tr_static_init()
  85273. {
  85274. #if defined(GEN_TREES_H) || !defined(STDC)
  85275. static int static_init_done = 0;
  85276. int n; /* iterates over tree elements */
  85277. int bits; /* bit counter */
  85278. int length; /* length value */
  85279. int code; /* code value */
  85280. int dist; /* distance index */
  85281. ush bl_count[MAX_BITS+1];
  85282. /* number of codes at each bit length for an optimal tree */
  85283. if (static_init_done) return;
  85284. /* For some embedded targets, global variables are not initialized: */
  85285. static_l_desc.static_tree = static_ltree;
  85286. static_l_desc.extra_bits = extra_lbits;
  85287. static_d_desc.static_tree = static_dtree;
  85288. static_d_desc.extra_bits = extra_dbits;
  85289. static_bl_desc.extra_bits = extra_blbits;
  85290. /* Initialize the mapping length (0..255) -> length code (0..28) */
  85291. length = 0;
  85292. for (code = 0; code < LENGTH_CODES-1; code++) {
  85293. base_length[code] = length;
  85294. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  85295. _length_code[length++] = (uch)code;
  85296. }
  85297. }
  85298. Assert (length == 256, "tr_static_init: length != 256");
  85299. /* Note that the length 255 (match length 258) can be represented
  85300. * in two different ways: code 284 + 5 bits or code 285, so we
  85301. * overwrite length_code[255] to use the best encoding:
  85302. */
  85303. _length_code[length-1] = (uch)code;
  85304. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  85305. dist = 0;
  85306. for (code = 0 ; code < 16; code++) {
  85307. base_dist[code] = dist;
  85308. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  85309. _dist_code[dist++] = (uch)code;
  85310. }
  85311. }
  85312. Assert (dist == 256, "tr_static_init: dist != 256");
  85313. dist >>= 7; /* from now on, all distances are divided by 128 */
  85314. for ( ; code < D_CODES; code++) {
  85315. base_dist[code] = dist << 7;
  85316. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  85317. _dist_code[256 + dist++] = (uch)code;
  85318. }
  85319. }
  85320. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  85321. /* Construct the codes of the static literal tree */
  85322. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  85323. n = 0;
  85324. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  85325. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  85326. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  85327. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  85328. /* Codes 286 and 287 do not exist, but we must include them in the
  85329. * tree construction to get a canonical Huffman tree (longest code
  85330. * all ones)
  85331. */
  85332. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  85333. /* The static distance tree is trivial: */
  85334. for (n = 0; n < D_CODES; n++) {
  85335. static_dtree[n].Len = 5;
  85336. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  85337. }
  85338. static_init_done = 1;
  85339. # ifdef GEN_TREES_H
  85340. gen_trees_header();
  85341. # endif
  85342. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  85343. }
  85344. /* ===========================================================================
  85345. * Genererate the file trees.h describing the static trees.
  85346. */
  85347. #ifdef GEN_TREES_H
  85348. # ifndef DEBUG
  85349. # include <stdio.h>
  85350. # endif
  85351. # define SEPARATOR(i, last, width) \
  85352. ((i) == (last)? "\n};\n\n" : \
  85353. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  85354. void gen_trees_header()
  85355. {
  85356. FILE *header = fopen("trees.h", "w");
  85357. int i;
  85358. Assert (header != NULL, "Can't open trees.h");
  85359. fprintf(header,
  85360. "/* header created automatically with -DGEN_TREES_H */\n\n");
  85361. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  85362. for (i = 0; i < L_CODES+2; i++) {
  85363. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  85364. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  85365. }
  85366. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  85367. for (i = 0; i < D_CODES; i++) {
  85368. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  85369. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  85370. }
  85371. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  85372. for (i = 0; i < DIST_CODE_LEN; i++) {
  85373. fprintf(header, "%2u%s", _dist_code[i],
  85374. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  85375. }
  85376. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  85377. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  85378. fprintf(header, "%2u%s", _length_code[i],
  85379. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  85380. }
  85381. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  85382. for (i = 0; i < LENGTH_CODES; i++) {
  85383. fprintf(header, "%1u%s", base_length[i],
  85384. SEPARATOR(i, LENGTH_CODES-1, 20));
  85385. }
  85386. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  85387. for (i = 0; i < D_CODES; i++) {
  85388. fprintf(header, "%5u%s", base_dist[i],
  85389. SEPARATOR(i, D_CODES-1, 10));
  85390. }
  85391. fclose(header);
  85392. }
  85393. #endif /* GEN_TREES_H */
  85394. /* ===========================================================================
  85395. * Initialize the tree data structures for a new zlib stream.
  85396. */
  85397. void _tr_init(deflate_state *s)
  85398. {
  85399. tr_static_init();
  85400. s->l_desc.dyn_tree = s->dyn_ltree;
  85401. s->l_desc.stat_desc = &static_l_desc;
  85402. s->d_desc.dyn_tree = s->dyn_dtree;
  85403. s->d_desc.stat_desc = &static_d_desc;
  85404. s->bl_desc.dyn_tree = s->bl_tree;
  85405. s->bl_desc.stat_desc = &static_bl_desc;
  85406. s->bi_buf = 0;
  85407. s->bi_valid = 0;
  85408. s->last_eob_len = 8; /* enough lookahead for inflate */
  85409. #ifdef DEBUG
  85410. s->compressed_len = 0L;
  85411. s->bits_sent = 0L;
  85412. #endif
  85413. /* Initialize the first block of the first file: */
  85414. init_block(s);
  85415. }
  85416. /* ===========================================================================
  85417. * Initialize a new block.
  85418. */
  85419. local void init_block (deflate_state *s)
  85420. {
  85421. int n; /* iterates over tree elements */
  85422. /* Initialize the trees. */
  85423. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  85424. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  85425. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  85426. s->dyn_ltree[END_BLOCK].Freq = 1;
  85427. s->opt_len = s->static_len = 0L;
  85428. s->last_lit = s->matches = 0;
  85429. }
  85430. #define SMALLEST 1
  85431. /* Index within the heap array of least frequent node in the Huffman tree */
  85432. /* ===========================================================================
  85433. * Remove the smallest element from the heap and recreate the heap with
  85434. * one less element. Updates heap and heap_len.
  85435. */
  85436. #define pqremove(s, tree, top) \
  85437. {\
  85438. top = s->heap[SMALLEST]; \
  85439. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  85440. pqdownheap(s, tree, SMALLEST); \
  85441. }
  85442. /* ===========================================================================
  85443. * Compares to subtrees, using the tree depth as tie breaker when
  85444. * the subtrees have equal frequency. This minimizes the worst case length.
  85445. */
  85446. #define smaller(tree, n, m, depth) \
  85447. (tree[n].Freq < tree[m].Freq || \
  85448. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  85449. /* ===========================================================================
  85450. * Restore the heap property by moving down the tree starting at node k,
  85451. * exchanging a node with the smallest of its two sons if necessary, stopping
  85452. * when the heap property is re-established (each father smaller than its
  85453. * two sons).
  85454. */
  85455. local void pqdownheap (deflate_state *s,
  85456. ct_data *tree, /* the tree to restore */
  85457. int k) /* node to move down */
  85458. {
  85459. int v = s->heap[k];
  85460. int j = k << 1; /* left son of k */
  85461. while (j <= s->heap_len) {
  85462. /* Set j to the smallest of the two sons: */
  85463. if (j < s->heap_len &&
  85464. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  85465. j++;
  85466. }
  85467. /* Exit if v is smaller than both sons */
  85468. if (smaller(tree, v, s->heap[j], s->depth)) break;
  85469. /* Exchange v with the smallest son */
  85470. s->heap[k] = s->heap[j]; k = j;
  85471. /* And continue down the tree, setting j to the left son of k */
  85472. j <<= 1;
  85473. }
  85474. s->heap[k] = v;
  85475. }
  85476. /* ===========================================================================
  85477. * Compute the optimal bit lengths for a tree and update the total bit length
  85478. * for the current block.
  85479. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  85480. * above are the tree nodes sorted by increasing frequency.
  85481. * OUT assertions: the field len is set to the optimal bit length, the
  85482. * array bl_count contains the frequencies for each bit length.
  85483. * The length opt_len is updated; static_len is also updated if stree is
  85484. * not null.
  85485. */
  85486. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  85487. {
  85488. ct_data *tree = desc->dyn_tree;
  85489. int max_code = desc->max_code;
  85490. const ct_data *stree = desc->stat_desc->static_tree;
  85491. const intf *extra = desc->stat_desc->extra_bits;
  85492. int base = desc->stat_desc->extra_base;
  85493. int max_length = desc->stat_desc->max_length;
  85494. int h; /* heap index */
  85495. int n, m; /* iterate over the tree elements */
  85496. int bits; /* bit length */
  85497. int xbits; /* extra bits */
  85498. ush f; /* frequency */
  85499. int overflow = 0; /* number of elements with bit length too large */
  85500. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  85501. /* In a first pass, compute the optimal bit lengths (which may
  85502. * overflow in the case of the bit length tree).
  85503. */
  85504. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  85505. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  85506. n = s->heap[h];
  85507. bits = tree[tree[n].Dad].Len + 1;
  85508. if (bits > max_length) bits = max_length, overflow++;
  85509. tree[n].Len = (ush)bits;
  85510. /* We overwrite tree[n].Dad which is no longer needed */
  85511. if (n > max_code) continue; /* not a leaf node */
  85512. s->bl_count[bits]++;
  85513. xbits = 0;
  85514. if (n >= base) xbits = extra[n-base];
  85515. f = tree[n].Freq;
  85516. s->opt_len += (ulg)f * (bits + xbits);
  85517. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  85518. }
  85519. if (overflow == 0) return;
  85520. Trace((stderr,"\nbit length overflow\n"));
  85521. /* This happens for example on obj2 and pic of the Calgary corpus */
  85522. /* Find the first bit length which could increase: */
  85523. do {
  85524. bits = max_length-1;
  85525. while (s->bl_count[bits] == 0) bits--;
  85526. s->bl_count[bits]--; /* move one leaf down the tree */
  85527. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  85528. s->bl_count[max_length]--;
  85529. /* The brother of the overflow item also moves one step up,
  85530. * but this does not affect bl_count[max_length]
  85531. */
  85532. overflow -= 2;
  85533. } while (overflow > 0);
  85534. /* Now recompute all bit lengths, scanning in increasing frequency.
  85535. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  85536. * lengths instead of fixing only the wrong ones. This idea is taken
  85537. * from 'ar' written by Haruhiko Okumura.)
  85538. */
  85539. for (bits = max_length; bits != 0; bits--) {
  85540. n = s->bl_count[bits];
  85541. while (n != 0) {
  85542. m = s->heap[--h];
  85543. if (m > max_code) continue;
  85544. if ((unsigned) tree[m].Len != (unsigned) bits) {
  85545. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  85546. s->opt_len += ((long)bits - (long)tree[m].Len)
  85547. *(long)tree[m].Freq;
  85548. tree[m].Len = (ush)bits;
  85549. }
  85550. n--;
  85551. }
  85552. }
  85553. }
  85554. /* ===========================================================================
  85555. * Generate the codes for a given tree and bit counts (which need not be
  85556. * optimal).
  85557. * IN assertion: the array bl_count contains the bit length statistics for
  85558. * the given tree and the field len is set for all tree elements.
  85559. * OUT assertion: the field code is set for all tree elements of non
  85560. * zero code length.
  85561. */
  85562. local void gen_codes (ct_data *tree, /* the tree to decorate */
  85563. int max_code, /* largest code with non zero frequency */
  85564. ushf *bl_count) /* number of codes at each bit length */
  85565. {
  85566. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  85567. ush code = 0; /* running code value */
  85568. int bits; /* bit index */
  85569. int n; /* code index */
  85570. /* The distribution counts are first used to generate the code values
  85571. * without bit reversal.
  85572. */
  85573. for (bits = 1; bits <= MAX_BITS; bits++) {
  85574. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  85575. }
  85576. /* Check that the bit counts in bl_count are consistent. The last code
  85577. * must be all ones.
  85578. */
  85579. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  85580. "inconsistent bit counts");
  85581. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  85582. for (n = 0; n <= max_code; n++) {
  85583. int len = tree[n].Len;
  85584. if (len == 0) continue;
  85585. /* Now reverse the bits */
  85586. tree[n].Code = bi_reverse(next_code[len]++, len);
  85587. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  85588. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  85589. }
  85590. }
  85591. /* ===========================================================================
  85592. * Construct one Huffman tree and assigns the code bit strings and lengths.
  85593. * Update the total bit length for the current block.
  85594. * IN assertion: the field freq is set for all tree elements.
  85595. * OUT assertions: the fields len and code are set to the optimal bit length
  85596. * and corresponding code. The length opt_len is updated; static_len is
  85597. * also updated if stree is not null. The field max_code is set.
  85598. */
  85599. local void build_tree (deflate_state *s,
  85600. tree_desc *desc) /* the tree descriptor */
  85601. {
  85602. ct_data *tree = desc->dyn_tree;
  85603. const ct_data *stree = desc->stat_desc->static_tree;
  85604. int elems = desc->stat_desc->elems;
  85605. int n, m; /* iterate over heap elements */
  85606. int max_code = -1; /* largest code with non zero frequency */
  85607. int node; /* new node being created */
  85608. /* Construct the initial heap, with least frequent element in
  85609. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  85610. * heap[0] is not used.
  85611. */
  85612. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  85613. for (n = 0; n < elems; n++) {
  85614. if (tree[n].Freq != 0) {
  85615. s->heap[++(s->heap_len)] = max_code = n;
  85616. s->depth[n] = 0;
  85617. } else {
  85618. tree[n].Len = 0;
  85619. }
  85620. }
  85621. /* The pkzip format requires that at least one distance code exists,
  85622. * and that at least one bit should be sent even if there is only one
  85623. * possible code. So to avoid special checks later on we force at least
  85624. * two codes of non zero frequency.
  85625. */
  85626. while (s->heap_len < 2) {
  85627. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  85628. tree[node].Freq = 1;
  85629. s->depth[node] = 0;
  85630. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  85631. /* node is 0 or 1 so it does not have extra bits */
  85632. }
  85633. desc->max_code = max_code;
  85634. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  85635. * establish sub-heaps of increasing lengths:
  85636. */
  85637. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  85638. /* Construct the Huffman tree by repeatedly combining the least two
  85639. * frequent nodes.
  85640. */
  85641. node = elems; /* next internal node of the tree */
  85642. do {
  85643. pqremove(s, tree, n); /* n = node of least frequency */
  85644. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  85645. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  85646. s->heap[--(s->heap_max)] = m;
  85647. /* Create a new node father of n and m */
  85648. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  85649. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  85650. s->depth[n] : s->depth[m]) + 1);
  85651. tree[n].Dad = tree[m].Dad = (ush)node;
  85652. #ifdef DUMP_BL_TREE
  85653. if (tree == s->bl_tree) {
  85654. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  85655. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  85656. }
  85657. #endif
  85658. /* and insert the new node in the heap */
  85659. s->heap[SMALLEST] = node++;
  85660. pqdownheap(s, tree, SMALLEST);
  85661. } while (s->heap_len >= 2);
  85662. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  85663. /* At this point, the fields freq and dad are set. We can now
  85664. * generate the bit lengths.
  85665. */
  85666. gen_bitlen(s, (tree_desc *)desc);
  85667. /* The field len is now set, we can generate the bit codes */
  85668. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  85669. }
  85670. /* ===========================================================================
  85671. * Scan a literal or distance tree to determine the frequencies of the codes
  85672. * in the bit length tree.
  85673. */
  85674. local void scan_tree (deflate_state *s,
  85675. ct_data *tree, /* the tree to be scanned */
  85676. int max_code) /* and its largest code of non zero frequency */
  85677. {
  85678. int n; /* iterates over all tree elements */
  85679. int prevlen = -1; /* last emitted length */
  85680. int curlen; /* length of current code */
  85681. int nextlen = tree[0].Len; /* length of next code */
  85682. int count = 0; /* repeat count of the current code */
  85683. int max_count = 7; /* max repeat count */
  85684. int min_count = 4; /* min repeat count */
  85685. if (nextlen == 0) max_count = 138, min_count = 3;
  85686. tree[max_code+1].Len = (ush)0xffff; /* guard */
  85687. for (n = 0; n <= max_code; n++) {
  85688. curlen = nextlen; nextlen = tree[n+1].Len;
  85689. if (++count < max_count && curlen == nextlen) {
  85690. continue;
  85691. } else if (count < min_count) {
  85692. s->bl_tree[curlen].Freq += count;
  85693. } else if (curlen != 0) {
  85694. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  85695. s->bl_tree[REP_3_6].Freq++;
  85696. } else if (count <= 10) {
  85697. s->bl_tree[REPZ_3_10].Freq++;
  85698. } else {
  85699. s->bl_tree[REPZ_11_138].Freq++;
  85700. }
  85701. count = 0; prevlen = curlen;
  85702. if (nextlen == 0) {
  85703. max_count = 138, min_count = 3;
  85704. } else if (curlen == nextlen) {
  85705. max_count = 6, min_count = 3;
  85706. } else {
  85707. max_count = 7, min_count = 4;
  85708. }
  85709. }
  85710. }
  85711. /* ===========================================================================
  85712. * Send a literal or distance tree in compressed form, using the codes in
  85713. * bl_tree.
  85714. */
  85715. local void send_tree (deflate_state *s,
  85716. ct_data *tree, /* the tree to be scanned */
  85717. int max_code) /* and its largest code of non zero frequency */
  85718. {
  85719. int n; /* iterates over all tree elements */
  85720. int prevlen = -1; /* last emitted length */
  85721. int curlen; /* length of current code */
  85722. int nextlen = tree[0].Len; /* length of next code */
  85723. int count = 0; /* repeat count of the current code */
  85724. int max_count = 7; /* max repeat count */
  85725. int min_count = 4; /* min repeat count */
  85726. /* tree[max_code+1].Len = -1; */ /* guard already set */
  85727. if (nextlen == 0) max_count = 138, min_count = 3;
  85728. for (n = 0; n <= max_code; n++) {
  85729. curlen = nextlen; nextlen = tree[n+1].Len;
  85730. if (++count < max_count && curlen == nextlen) {
  85731. continue;
  85732. } else if (count < min_count) {
  85733. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  85734. } else if (curlen != 0) {
  85735. if (curlen != prevlen) {
  85736. send_code(s, curlen, s->bl_tree); count--;
  85737. }
  85738. Assert(count >= 3 && count <= 6, " 3_6?");
  85739. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  85740. } else if (count <= 10) {
  85741. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  85742. } else {
  85743. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  85744. }
  85745. count = 0; prevlen = curlen;
  85746. if (nextlen == 0) {
  85747. max_count = 138, min_count = 3;
  85748. } else if (curlen == nextlen) {
  85749. max_count = 6, min_count = 3;
  85750. } else {
  85751. max_count = 7, min_count = 4;
  85752. }
  85753. }
  85754. }
  85755. /* ===========================================================================
  85756. * Construct the Huffman tree for the bit lengths and return the index in
  85757. * bl_order of the last bit length code to send.
  85758. */
  85759. local int build_bl_tree (deflate_state *s)
  85760. {
  85761. int max_blindex; /* index of last bit length code of non zero freq */
  85762. /* Determine the bit length frequencies for literal and distance trees */
  85763. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  85764. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  85765. /* Build the bit length tree: */
  85766. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  85767. /* opt_len now includes the length of the tree representations, except
  85768. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  85769. */
  85770. /* Determine the number of bit length codes to send. The pkzip format
  85771. * requires that at least 4 bit length codes be sent. (appnote.txt says
  85772. * 3 but the actual value used is 4.)
  85773. */
  85774. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  85775. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  85776. }
  85777. /* Update opt_len to include the bit length tree and counts */
  85778. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  85779. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  85780. s->opt_len, s->static_len));
  85781. return max_blindex;
  85782. }
  85783. /* ===========================================================================
  85784. * Send the header for a block using dynamic Huffman trees: the counts, the
  85785. * lengths of the bit length codes, the literal tree and the distance tree.
  85786. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  85787. */
  85788. local void send_all_trees (deflate_state *s,
  85789. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  85790. {
  85791. int rank; /* index in bl_order */
  85792. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  85793. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  85794. "too many codes");
  85795. Tracev((stderr, "\nbl counts: "));
  85796. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  85797. send_bits(s, dcodes-1, 5);
  85798. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  85799. for (rank = 0; rank < blcodes; rank++) {
  85800. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  85801. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  85802. }
  85803. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  85804. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  85805. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  85806. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  85807. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  85808. }
  85809. /* ===========================================================================
  85810. * Send a stored block
  85811. */
  85812. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  85813. {
  85814. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  85815. #ifdef DEBUG
  85816. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  85817. s->compressed_len += (stored_len + 4) << 3;
  85818. #endif
  85819. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  85820. }
  85821. /* ===========================================================================
  85822. * Send one empty static block to give enough lookahead for inflate.
  85823. * This takes 10 bits, of which 7 may remain in the bit buffer.
  85824. * The current inflate code requires 9 bits of lookahead. If the
  85825. * last two codes for the previous block (real code plus EOB) were coded
  85826. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  85827. * the last real code. In this case we send two empty static blocks instead
  85828. * of one. (There are no problems if the previous block is stored or fixed.)
  85829. * To simplify the code, we assume the worst case of last real code encoded
  85830. * on one bit only.
  85831. */
  85832. void _tr_align (deflate_state *s)
  85833. {
  85834. send_bits(s, STATIC_TREES<<1, 3);
  85835. send_code(s, END_BLOCK, static_ltree);
  85836. #ifdef DEBUG
  85837. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  85838. #endif
  85839. bi_flush(s);
  85840. /* Of the 10 bits for the empty block, we have already sent
  85841. * (10 - bi_valid) bits. The lookahead for the last real code (before
  85842. * the EOB of the previous block) was thus at least one plus the length
  85843. * of the EOB plus what we have just sent of the empty static block.
  85844. */
  85845. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  85846. send_bits(s, STATIC_TREES<<1, 3);
  85847. send_code(s, END_BLOCK, static_ltree);
  85848. #ifdef DEBUG
  85849. s->compressed_len += 10L;
  85850. #endif
  85851. bi_flush(s);
  85852. }
  85853. s->last_eob_len = 7;
  85854. }
  85855. /* ===========================================================================
  85856. * Determine the best encoding for the current block: dynamic trees, static
  85857. * trees or store, and output the encoded block to the zip file.
  85858. */
  85859. void _tr_flush_block (deflate_state *s,
  85860. charf *buf, /* input block, or NULL if too old */
  85861. ulg stored_len, /* length of input block */
  85862. int eof) /* true if this is the last block for a file */
  85863. {
  85864. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  85865. int max_blindex = 0; /* index of last bit length code of non zero freq */
  85866. /* Build the Huffman trees unless a stored block is forced */
  85867. if (s->level > 0) {
  85868. /* Check if the file is binary or text */
  85869. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  85870. set_data_type(s);
  85871. /* Construct the literal and distance trees */
  85872. build_tree(s, (tree_desc *)(&(s->l_desc)));
  85873. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  85874. s->static_len));
  85875. build_tree(s, (tree_desc *)(&(s->d_desc)));
  85876. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  85877. s->static_len));
  85878. /* At this point, opt_len and static_len are the total bit lengths of
  85879. * the compressed block data, excluding the tree representations.
  85880. */
  85881. /* Build the bit length tree for the above two trees, and get the index
  85882. * in bl_order of the last bit length code to send.
  85883. */
  85884. max_blindex = build_bl_tree(s);
  85885. /* Determine the best encoding. Compute the block lengths in bytes. */
  85886. opt_lenb = (s->opt_len+3+7)>>3;
  85887. static_lenb = (s->static_len+3+7)>>3;
  85888. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  85889. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  85890. s->last_lit));
  85891. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  85892. } else {
  85893. Assert(buf != (char*)0, "lost buf");
  85894. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  85895. }
  85896. #ifdef FORCE_STORED
  85897. if (buf != (char*)0) { /* force stored block */
  85898. #else
  85899. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  85900. /* 4: two words for the lengths */
  85901. #endif
  85902. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  85903. * Otherwise we can't have processed more than WSIZE input bytes since
  85904. * the last block flush, because compression would have been
  85905. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  85906. * transform a block into a stored block.
  85907. */
  85908. _tr_stored_block(s, buf, stored_len, eof);
  85909. #ifdef FORCE_STATIC
  85910. } else if (static_lenb >= 0) { /* force static trees */
  85911. #else
  85912. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  85913. #endif
  85914. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  85915. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  85916. #ifdef DEBUG
  85917. s->compressed_len += 3 + s->static_len;
  85918. #endif
  85919. } else {
  85920. send_bits(s, (DYN_TREES<<1)+eof, 3);
  85921. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  85922. max_blindex+1);
  85923. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  85924. #ifdef DEBUG
  85925. s->compressed_len += 3 + s->opt_len;
  85926. #endif
  85927. }
  85928. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  85929. /* The above check is made mod 2^32, for files larger than 512 MB
  85930. * and uLong implemented on 32 bits.
  85931. */
  85932. init_block(s);
  85933. if (eof) {
  85934. bi_windup(s);
  85935. #ifdef DEBUG
  85936. s->compressed_len += 7; /* align on byte boundary */
  85937. #endif
  85938. }
  85939. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  85940. s->compressed_len-7*eof));
  85941. }
  85942. /* ===========================================================================
  85943. * Save the match info and tally the frequency counts. Return true if
  85944. * the current block must be flushed.
  85945. */
  85946. int _tr_tally (deflate_state *s,
  85947. unsigned dist, /* distance of matched string */
  85948. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  85949. {
  85950. s->d_buf[s->last_lit] = (ush)dist;
  85951. s->l_buf[s->last_lit++] = (uch)lc;
  85952. if (dist == 0) {
  85953. /* lc is the unmatched char */
  85954. s->dyn_ltree[lc].Freq++;
  85955. } else {
  85956. s->matches++;
  85957. /* Here, lc is the match length - MIN_MATCH */
  85958. dist--; /* dist = match distance - 1 */
  85959. Assert((ush)dist < (ush)MAX_DIST(s) &&
  85960. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  85961. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  85962. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  85963. s->dyn_dtree[d_code(dist)].Freq++;
  85964. }
  85965. #ifdef TRUNCATE_BLOCK
  85966. /* Try to guess if it is profitable to stop the current block here */
  85967. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  85968. /* Compute an upper bound for the compressed length */
  85969. ulg out_length = (ulg)s->last_lit*8L;
  85970. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  85971. int dcode;
  85972. for (dcode = 0; dcode < D_CODES; dcode++) {
  85973. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  85974. (5L+extra_dbits[dcode]);
  85975. }
  85976. out_length >>= 3;
  85977. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  85978. s->last_lit, in_length, out_length,
  85979. 100L - out_length*100L/in_length));
  85980. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  85981. }
  85982. #endif
  85983. return (s->last_lit == s->lit_bufsize-1);
  85984. /* We avoid equality with lit_bufsize because of wraparound at 64K
  85985. * on 16 bit machines and because stored blocks are restricted to
  85986. * 64K-1 bytes.
  85987. */
  85988. }
  85989. /* ===========================================================================
  85990. * Send the block data compressed using the given Huffman trees
  85991. */
  85992. local void compress_block (deflate_state *s,
  85993. ct_data *ltree, /* literal tree */
  85994. ct_data *dtree) /* distance tree */
  85995. {
  85996. unsigned dist; /* distance of matched string */
  85997. int lc; /* match length or unmatched char (if dist == 0) */
  85998. unsigned lx = 0; /* running index in l_buf */
  85999. unsigned code; /* the code to send */
  86000. int extra; /* number of extra bits to send */
  86001. if (s->last_lit != 0) do {
  86002. dist = s->d_buf[lx];
  86003. lc = s->l_buf[lx++];
  86004. if (dist == 0) {
  86005. send_code(s, lc, ltree); /* send a literal byte */
  86006. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  86007. } else {
  86008. /* Here, lc is the match length - MIN_MATCH */
  86009. code = _length_code[lc];
  86010. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  86011. extra = extra_lbits[code];
  86012. if (extra != 0) {
  86013. lc -= base_length[code];
  86014. send_bits(s, lc, extra); /* send the extra length bits */
  86015. }
  86016. dist--; /* dist is now the match distance - 1 */
  86017. code = d_code(dist);
  86018. Assert (code < D_CODES, "bad d_code");
  86019. send_code(s, code, dtree); /* send the distance code */
  86020. extra = extra_dbits[code];
  86021. if (extra != 0) {
  86022. dist -= base_dist[code];
  86023. send_bits(s, dist, extra); /* send the extra distance bits */
  86024. }
  86025. } /* literal or match pair ? */
  86026. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  86027. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  86028. "pendingBuf overflow");
  86029. } while (lx < s->last_lit);
  86030. send_code(s, END_BLOCK, ltree);
  86031. s->last_eob_len = ltree[END_BLOCK].Len;
  86032. }
  86033. /* ===========================================================================
  86034. * Set the data type to BINARY or TEXT, using a crude approximation:
  86035. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  86036. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  86037. * IN assertion: the fields Freq of dyn_ltree are set.
  86038. */
  86039. local void set_data_type (deflate_state *s)
  86040. {
  86041. int n;
  86042. for (n = 0; n < 9; n++)
  86043. if (s->dyn_ltree[n].Freq != 0)
  86044. break;
  86045. if (n == 9)
  86046. for (n = 14; n < 32; n++)
  86047. if (s->dyn_ltree[n].Freq != 0)
  86048. break;
  86049. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  86050. }
  86051. /* ===========================================================================
  86052. * Reverse the first len bits of a code, using straightforward code (a faster
  86053. * method would use a table)
  86054. * IN assertion: 1 <= len <= 15
  86055. */
  86056. local unsigned bi_reverse (unsigned code, int len)
  86057. {
  86058. register unsigned res = 0;
  86059. do {
  86060. res |= code & 1;
  86061. code >>= 1, res <<= 1;
  86062. } while (--len > 0);
  86063. return res >> 1;
  86064. }
  86065. /* ===========================================================================
  86066. * Flush the bit buffer, keeping at most 7 bits in it.
  86067. */
  86068. local void bi_flush (deflate_state *s)
  86069. {
  86070. if (s->bi_valid == 16) {
  86071. put_short(s, s->bi_buf);
  86072. s->bi_buf = 0;
  86073. s->bi_valid = 0;
  86074. } else if (s->bi_valid >= 8) {
  86075. put_byte(s, (Byte)s->bi_buf);
  86076. s->bi_buf >>= 8;
  86077. s->bi_valid -= 8;
  86078. }
  86079. }
  86080. /* ===========================================================================
  86081. * Flush the bit buffer and align the output on a byte boundary
  86082. */
  86083. local void bi_windup (deflate_state *s)
  86084. {
  86085. if (s->bi_valid > 8) {
  86086. put_short(s, s->bi_buf);
  86087. } else if (s->bi_valid > 0) {
  86088. put_byte(s, (Byte)s->bi_buf);
  86089. }
  86090. s->bi_buf = 0;
  86091. s->bi_valid = 0;
  86092. #ifdef DEBUG
  86093. s->bits_sent = (s->bits_sent+7) & ~7;
  86094. #endif
  86095. }
  86096. /* ===========================================================================
  86097. * Copy a stored block, storing first the length and its
  86098. * one's complement if requested.
  86099. */
  86100. local void copy_block(deflate_state *s,
  86101. charf *buf, /* the input data */
  86102. unsigned len, /* its length */
  86103. int header) /* true if block header must be written */
  86104. {
  86105. bi_windup(s); /* align on byte boundary */
  86106. s->last_eob_len = 8; /* enough lookahead for inflate */
  86107. if (header) {
  86108. put_short(s, (ush)len);
  86109. put_short(s, (ush)~len);
  86110. #ifdef DEBUG
  86111. s->bits_sent += 2*16;
  86112. #endif
  86113. }
  86114. #ifdef DEBUG
  86115. s->bits_sent += (ulg)len<<3;
  86116. #endif
  86117. while (len--) {
  86118. put_byte(s, *buf++);
  86119. }
  86120. }
  86121. /*** End of inlined file: trees.c ***/
  86122. /*** Start of inlined file: zutil.c ***/
  86123. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  86124. #ifndef NO_DUMMY_DECL
  86125. struct internal_state {int dummy;}; /* for buggy compilers */
  86126. #endif
  86127. const char * const z_errmsg[10] = {
  86128. "need dictionary", /* Z_NEED_DICT 2 */
  86129. "stream end", /* Z_STREAM_END 1 */
  86130. "", /* Z_OK 0 */
  86131. "file error", /* Z_ERRNO (-1) */
  86132. "stream error", /* Z_STREAM_ERROR (-2) */
  86133. "data error", /* Z_DATA_ERROR (-3) */
  86134. "insufficient memory", /* Z_MEM_ERROR (-4) */
  86135. "buffer error", /* Z_BUF_ERROR (-5) */
  86136. "incompatible version",/* Z_VERSION_ERROR (-6) */
  86137. ""};
  86138. /*const char * ZEXPORT zlibVersion()
  86139. {
  86140. return ZLIB_VERSION;
  86141. }
  86142. uLong ZEXPORT zlibCompileFlags()
  86143. {
  86144. uLong flags;
  86145. flags = 0;
  86146. switch (sizeof(uInt)) {
  86147. case 2: break;
  86148. case 4: flags += 1; break;
  86149. case 8: flags += 2; break;
  86150. default: flags += 3;
  86151. }
  86152. switch (sizeof(uLong)) {
  86153. case 2: break;
  86154. case 4: flags += 1 << 2; break;
  86155. case 8: flags += 2 << 2; break;
  86156. default: flags += 3 << 2;
  86157. }
  86158. switch (sizeof(voidpf)) {
  86159. case 2: break;
  86160. case 4: flags += 1 << 4; break;
  86161. case 8: flags += 2 << 4; break;
  86162. default: flags += 3 << 4;
  86163. }
  86164. switch (sizeof(z_off_t)) {
  86165. case 2: break;
  86166. case 4: flags += 1 << 6; break;
  86167. case 8: flags += 2 << 6; break;
  86168. default: flags += 3 << 6;
  86169. }
  86170. #ifdef DEBUG
  86171. flags += 1 << 8;
  86172. #endif
  86173. #if defined(ASMV) || defined(ASMINF)
  86174. flags += 1 << 9;
  86175. #endif
  86176. #ifdef ZLIB_WINAPI
  86177. flags += 1 << 10;
  86178. #endif
  86179. #ifdef BUILDFIXED
  86180. flags += 1 << 12;
  86181. #endif
  86182. #ifdef DYNAMIC_CRC_TABLE
  86183. flags += 1 << 13;
  86184. #endif
  86185. #ifdef NO_GZCOMPRESS
  86186. flags += 1L << 16;
  86187. #endif
  86188. #ifdef NO_GZIP
  86189. flags += 1L << 17;
  86190. #endif
  86191. #ifdef PKZIP_BUG_WORKAROUND
  86192. flags += 1L << 20;
  86193. #endif
  86194. #ifdef FASTEST
  86195. flags += 1L << 21;
  86196. #endif
  86197. #ifdef STDC
  86198. # ifdef NO_vsnprintf
  86199. flags += 1L << 25;
  86200. # ifdef HAS_vsprintf_void
  86201. flags += 1L << 26;
  86202. # endif
  86203. # else
  86204. # ifdef HAS_vsnprintf_void
  86205. flags += 1L << 26;
  86206. # endif
  86207. # endif
  86208. #else
  86209. flags += 1L << 24;
  86210. # ifdef NO_snprintf
  86211. flags += 1L << 25;
  86212. # ifdef HAS_sprintf_void
  86213. flags += 1L << 26;
  86214. # endif
  86215. # else
  86216. # ifdef HAS_snprintf_void
  86217. flags += 1L << 26;
  86218. # endif
  86219. # endif
  86220. #endif
  86221. return flags;
  86222. }*/
  86223. #ifdef DEBUG
  86224. # ifndef verbose
  86225. # define verbose 0
  86226. # endif
  86227. int z_verbose = verbose;
  86228. void z_error (const char *m)
  86229. {
  86230. fprintf(stderr, "%s\n", m);
  86231. exit(1);
  86232. }
  86233. #endif
  86234. /* exported to allow conversion of error code to string for compress() and
  86235. * uncompress()
  86236. */
  86237. const char * ZEXPORT zError(int err)
  86238. {
  86239. return ERR_MSG(err);
  86240. }
  86241. #if defined(_WIN32_WCE)
  86242. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  86243. * errno. We define it as a global variable to simplify porting.
  86244. * Its value is always 0 and should not be used.
  86245. */
  86246. int errno = 0;
  86247. #endif
  86248. #ifndef HAVE_MEMCPY
  86249. void zmemcpy(dest, source, len)
  86250. Bytef* dest;
  86251. const Bytef* source;
  86252. uInt len;
  86253. {
  86254. if (len == 0) return;
  86255. do {
  86256. *dest++ = *source++; /* ??? to be unrolled */
  86257. } while (--len != 0);
  86258. }
  86259. int zmemcmp(s1, s2, len)
  86260. const Bytef* s1;
  86261. const Bytef* s2;
  86262. uInt len;
  86263. {
  86264. uInt j;
  86265. for (j = 0; j < len; j++) {
  86266. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  86267. }
  86268. return 0;
  86269. }
  86270. void zmemzero(dest, len)
  86271. Bytef* dest;
  86272. uInt len;
  86273. {
  86274. if (len == 0) return;
  86275. do {
  86276. *dest++ = 0; /* ??? to be unrolled */
  86277. } while (--len != 0);
  86278. }
  86279. #endif
  86280. #ifdef SYS16BIT
  86281. #ifdef __TURBOC__
  86282. /* Turbo C in 16-bit mode */
  86283. # define MY_ZCALLOC
  86284. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  86285. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  86286. * must fix the pointer. Warning: the pointer must be put back to its
  86287. * original form in order to free it, use zcfree().
  86288. */
  86289. #define MAX_PTR 10
  86290. /* 10*64K = 640K */
  86291. local int next_ptr = 0;
  86292. typedef struct ptr_table_s {
  86293. voidpf org_ptr;
  86294. voidpf new_ptr;
  86295. } ptr_table;
  86296. local ptr_table table[MAX_PTR];
  86297. /* This table is used to remember the original form of pointers
  86298. * to large buffers (64K). Such pointers are normalized with a zero offset.
  86299. * Since MSDOS is not a preemptive multitasking OS, this table is not
  86300. * protected from concurrent access. This hack doesn't work anyway on
  86301. * a protected system like OS/2. Use Microsoft C instead.
  86302. */
  86303. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86304. {
  86305. voidpf buf = opaque; /* just to make some compilers happy */
  86306. ulg bsize = (ulg)items*size;
  86307. /* If we allocate less than 65520 bytes, we assume that farmalloc
  86308. * will return a usable pointer which doesn't have to be normalized.
  86309. */
  86310. if (bsize < 65520L) {
  86311. buf = farmalloc(bsize);
  86312. if (*(ush*)&buf != 0) return buf;
  86313. } else {
  86314. buf = farmalloc(bsize + 16L);
  86315. }
  86316. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  86317. table[next_ptr].org_ptr = buf;
  86318. /* Normalize the pointer to seg:0 */
  86319. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  86320. *(ush*)&buf = 0;
  86321. table[next_ptr++].new_ptr = buf;
  86322. return buf;
  86323. }
  86324. void zcfree (voidpf opaque, voidpf ptr)
  86325. {
  86326. int n;
  86327. if (*(ush*)&ptr != 0) { /* object < 64K */
  86328. farfree(ptr);
  86329. return;
  86330. }
  86331. /* Find the original pointer */
  86332. for (n = 0; n < next_ptr; n++) {
  86333. if (ptr != table[n].new_ptr) continue;
  86334. farfree(table[n].org_ptr);
  86335. while (++n < next_ptr) {
  86336. table[n-1] = table[n];
  86337. }
  86338. next_ptr--;
  86339. return;
  86340. }
  86341. ptr = opaque; /* just to make some compilers happy */
  86342. Assert(0, "zcfree: ptr not found");
  86343. }
  86344. #endif /* __TURBOC__ */
  86345. #ifdef M_I86
  86346. /* Microsoft C in 16-bit mode */
  86347. # define MY_ZCALLOC
  86348. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  86349. # define _halloc halloc
  86350. # define _hfree hfree
  86351. #endif
  86352. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86353. {
  86354. if (opaque) opaque = 0; /* to make compiler happy */
  86355. return _halloc((long)items, size);
  86356. }
  86357. void zcfree (voidpf opaque, voidpf ptr)
  86358. {
  86359. if (opaque) opaque = 0; /* to make compiler happy */
  86360. _hfree(ptr);
  86361. }
  86362. #endif /* M_I86 */
  86363. #endif /* SYS16BIT */
  86364. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  86365. #ifndef STDC
  86366. extern voidp malloc OF((uInt size));
  86367. extern voidp calloc OF((uInt items, uInt size));
  86368. extern void free OF((voidpf ptr));
  86369. #endif
  86370. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  86371. {
  86372. if (opaque) items += size - size; /* make compiler happy */
  86373. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  86374. (voidpf)calloc(items, size);
  86375. }
  86376. void zcfree (voidpf opaque, voidpf ptr)
  86377. {
  86378. free(ptr);
  86379. if (opaque) return; /* make compiler happy */
  86380. }
  86381. #endif /* MY_ZCALLOC */
  86382. /*** End of inlined file: zutil.c ***/
  86383. #undef Byte
  86384. #else
  86385. #include <zlib.h>
  86386. #endif
  86387. }
  86388. #if JUCE_MSVC
  86389. #pragma warning (pop)
  86390. #endif
  86391. BEGIN_JUCE_NAMESPACE
  86392. // internal helper object that holds the zlib structures so they don't have to be
  86393. // included publicly.
  86394. class GZIPDecompressorInputStream::GZIPDecompressHelper
  86395. {
  86396. public:
  86397. GZIPDecompressHelper (const bool noWrap)
  86398. : finished (true),
  86399. needsDictionary (false),
  86400. error (true),
  86401. streamIsValid (false),
  86402. data (0),
  86403. dataSize (0)
  86404. {
  86405. using namespace zlibNamespace;
  86406. zerostruct (stream);
  86407. streamIsValid = (inflateInit2 (&stream, noWrap ? -MAX_WBITS : MAX_WBITS) == Z_OK);
  86408. finished = error = ! streamIsValid;
  86409. }
  86410. ~GZIPDecompressHelper()
  86411. {
  86412. using namespace zlibNamespace;
  86413. if (streamIsValid)
  86414. inflateEnd (&stream);
  86415. }
  86416. bool needsInput() const throw() { return dataSize <= 0; }
  86417. void setInput (uint8* const data_, const int size) throw()
  86418. {
  86419. data = data_;
  86420. dataSize = size;
  86421. }
  86422. int doNextBlock (uint8* const dest, const int destSize)
  86423. {
  86424. using namespace zlibNamespace;
  86425. if (streamIsValid && data != 0 && ! finished)
  86426. {
  86427. stream.next_in = data;
  86428. stream.next_out = dest;
  86429. stream.avail_in = dataSize;
  86430. stream.avail_out = destSize;
  86431. switch (inflate (&stream, Z_PARTIAL_FLUSH))
  86432. {
  86433. case Z_STREAM_END:
  86434. finished = true;
  86435. // deliberate fall-through
  86436. case Z_OK:
  86437. data += dataSize - stream.avail_in;
  86438. dataSize = stream.avail_in;
  86439. return destSize - stream.avail_out;
  86440. case Z_NEED_DICT:
  86441. needsDictionary = true;
  86442. data += dataSize - stream.avail_in;
  86443. dataSize = stream.avail_in;
  86444. break;
  86445. case Z_DATA_ERROR:
  86446. case Z_MEM_ERROR:
  86447. error = true;
  86448. default:
  86449. break;
  86450. }
  86451. }
  86452. return 0;
  86453. }
  86454. bool finished, needsDictionary, error, streamIsValid;
  86455. enum { gzipDecompBufferSize = 32768 };
  86456. private:
  86457. zlibNamespace::z_stream stream;
  86458. uint8* data;
  86459. int dataSize;
  86460. GZIPDecompressHelper (const GZIPDecompressHelper&);
  86461. GZIPDecompressHelper& operator= (const GZIPDecompressHelper&);
  86462. };
  86463. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  86464. const bool deleteSourceWhenDestroyed,
  86465. const bool noWrap_,
  86466. const int64 uncompressedStreamLength_)
  86467. : sourceStream (sourceStream_),
  86468. streamToDelete (deleteSourceWhenDestroyed ? sourceStream_ : 0),
  86469. uncompressedStreamLength (uncompressedStreamLength_),
  86470. noWrap (noWrap_),
  86471. isEof (false),
  86472. activeBufferSize (0),
  86473. originalSourcePos (sourceStream_->getPosition()),
  86474. currentPos (0),
  86475. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86476. helper (new GZIPDecompressHelper (noWrap_))
  86477. {
  86478. }
  86479. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream& sourceStream_)
  86480. : sourceStream (&sourceStream_),
  86481. uncompressedStreamLength (-1),
  86482. noWrap (false),
  86483. isEof (false),
  86484. activeBufferSize (0),
  86485. originalSourcePos (sourceStream_.getPosition()),
  86486. currentPos (0),
  86487. buffer ((size_t) GZIPDecompressHelper::gzipDecompBufferSize),
  86488. helper (new GZIPDecompressHelper (false))
  86489. {
  86490. }
  86491. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  86492. {
  86493. }
  86494. int64 GZIPDecompressorInputStream::getTotalLength()
  86495. {
  86496. return uncompressedStreamLength;
  86497. }
  86498. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  86499. {
  86500. if ((howMany > 0) && ! isEof)
  86501. {
  86502. jassert (destBuffer != 0);
  86503. if (destBuffer != 0)
  86504. {
  86505. int numRead = 0;
  86506. uint8* d = static_cast <uint8*> (destBuffer);
  86507. while (! helper->error)
  86508. {
  86509. const int n = helper->doNextBlock (d, howMany);
  86510. currentPos += n;
  86511. if (n == 0)
  86512. {
  86513. if (helper->finished || helper->needsDictionary)
  86514. {
  86515. isEof = true;
  86516. return numRead;
  86517. }
  86518. if (helper->needsInput())
  86519. {
  86520. activeBufferSize = sourceStream->read (buffer, (int) GZIPDecompressHelper::gzipDecompBufferSize);
  86521. if (activeBufferSize > 0)
  86522. {
  86523. helper->setInput (buffer, activeBufferSize);
  86524. }
  86525. else
  86526. {
  86527. isEof = true;
  86528. return numRead;
  86529. }
  86530. }
  86531. }
  86532. else
  86533. {
  86534. numRead += n;
  86535. howMany -= n;
  86536. d += n;
  86537. if (howMany <= 0)
  86538. return numRead;
  86539. }
  86540. }
  86541. }
  86542. }
  86543. return 0;
  86544. }
  86545. bool GZIPDecompressorInputStream::isExhausted()
  86546. {
  86547. return helper->error || isEof;
  86548. }
  86549. int64 GZIPDecompressorInputStream::getPosition()
  86550. {
  86551. return currentPos;
  86552. }
  86553. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  86554. {
  86555. if (newPos < currentPos)
  86556. {
  86557. // to go backwards, reset the stream and start again..
  86558. isEof = false;
  86559. activeBufferSize = 0;
  86560. currentPos = 0;
  86561. helper = new GZIPDecompressHelper (noWrap);
  86562. sourceStream->setPosition (originalSourcePos);
  86563. }
  86564. skipNextBytes (newPos - currentPos);
  86565. return true;
  86566. }
  86567. END_JUCE_NAMESPACE
  86568. /*** End of inlined file: juce_GZIPDecompressorInputStream.cpp ***/
  86569. #endif
  86570. #if JUCE_BUILD_NATIVE && ! JUCE_ONLY_BUILD_CORE_LIBRARY
  86571. /*** Start of inlined file: juce_FlacAudioFormat.cpp ***/
  86572. #if JUCE_USE_FLAC
  86573. #if JUCE_WINDOWS
  86574. #include <windows.h>
  86575. #endif
  86576. namespace FlacNamespace
  86577. {
  86578. #if JUCE_INCLUDE_FLAC_CODE
  86579. #if JUCE_MSVC
  86580. #pragma warning (disable : 4505) // (unreferenced static function removal warning)
  86581. #endif
  86582. #define FLAC__NO_DLL 1
  86583. #if ! defined (SIZE_MAX)
  86584. #define SIZE_MAX 0xffffffff
  86585. #endif
  86586. #define __STDC_LIMIT_MACROS 1
  86587. /*** Start of inlined file: all.h ***/
  86588. #ifndef FLAC__ALL_H
  86589. #define FLAC__ALL_H
  86590. /*** Start of inlined file: export.h ***/
  86591. #ifndef FLAC__EXPORT_H
  86592. #define FLAC__EXPORT_H
  86593. /** \file include/FLAC/export.h
  86594. *
  86595. * \brief
  86596. * This module contains #defines and symbols for exporting function
  86597. * calls, and providing version information and compiled-in features.
  86598. *
  86599. * See the \link flac_export export \endlink module.
  86600. */
  86601. /** \defgroup flac_export FLAC/export.h: export symbols
  86602. * \ingroup flac
  86603. *
  86604. * \brief
  86605. * This module contains #defines and symbols for exporting function
  86606. * calls, and providing version information and compiled-in features.
  86607. *
  86608. * If you are compiling with MSVC and will link to the static library
  86609. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  86610. * make sure the symbols are exported properly.
  86611. *
  86612. * \{
  86613. */
  86614. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  86615. #define FLAC_API
  86616. #else
  86617. #ifdef FLAC_API_EXPORTS
  86618. #define FLAC_API _declspec(dllexport)
  86619. #else
  86620. #define FLAC_API _declspec(dllimport)
  86621. #endif
  86622. #endif
  86623. /** These #defines will mirror the libtool-based library version number, see
  86624. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  86625. */
  86626. #define FLAC_API_VERSION_CURRENT 10
  86627. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  86628. #define FLAC_API_VERSION_AGE 2 /**< see above */
  86629. #ifdef __cplusplus
  86630. extern "C" {
  86631. #endif
  86632. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  86633. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  86634. #ifdef __cplusplus
  86635. }
  86636. #endif
  86637. /* \} */
  86638. #endif
  86639. /*** End of inlined file: export.h ***/
  86640. /*** Start of inlined file: assert.h ***/
  86641. #ifndef FLAC__ASSERT_H
  86642. #define FLAC__ASSERT_H
  86643. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  86644. #ifdef DEBUG
  86645. #include <assert.h>
  86646. #define FLAC__ASSERT(x) assert(x)
  86647. #define FLAC__ASSERT_DECLARATION(x) x
  86648. #else
  86649. #define FLAC__ASSERT(x)
  86650. #define FLAC__ASSERT_DECLARATION(x)
  86651. #endif
  86652. #endif
  86653. /*** End of inlined file: assert.h ***/
  86654. /*** Start of inlined file: callback.h ***/
  86655. #ifndef FLAC__CALLBACK_H
  86656. #define FLAC__CALLBACK_H
  86657. /*** Start of inlined file: ordinals.h ***/
  86658. #ifndef FLAC__ORDINALS_H
  86659. #define FLAC__ORDINALS_H
  86660. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  86661. #include <inttypes.h>
  86662. #endif
  86663. typedef signed char FLAC__int8;
  86664. typedef unsigned char FLAC__uint8;
  86665. #if defined(_MSC_VER) || defined(__BORLANDC__)
  86666. typedef __int16 FLAC__int16;
  86667. typedef __int32 FLAC__int32;
  86668. typedef __int64 FLAC__int64;
  86669. typedef unsigned __int16 FLAC__uint16;
  86670. typedef unsigned __int32 FLAC__uint32;
  86671. typedef unsigned __int64 FLAC__uint64;
  86672. #elif defined(__EMX__)
  86673. typedef short FLAC__int16;
  86674. typedef long FLAC__int32;
  86675. typedef long long FLAC__int64;
  86676. typedef unsigned short FLAC__uint16;
  86677. typedef unsigned long FLAC__uint32;
  86678. typedef unsigned long long FLAC__uint64;
  86679. #else
  86680. typedef int16_t FLAC__int16;
  86681. typedef int32_t FLAC__int32;
  86682. typedef int64_t FLAC__int64;
  86683. typedef uint16_t FLAC__uint16;
  86684. typedef uint32_t FLAC__uint32;
  86685. typedef uint64_t FLAC__uint64;
  86686. #endif
  86687. typedef int FLAC__bool;
  86688. typedef FLAC__uint8 FLAC__byte;
  86689. #ifdef true
  86690. #undef true
  86691. #endif
  86692. #ifdef false
  86693. #undef false
  86694. #endif
  86695. #ifndef __cplusplus
  86696. #define true 1
  86697. #define false 0
  86698. #endif
  86699. #endif
  86700. /*** End of inlined file: ordinals.h ***/
  86701. #include <stdlib.h> /* for size_t */
  86702. /** \file include/FLAC/callback.h
  86703. *
  86704. * \brief
  86705. * This module defines the structures for describing I/O callbacks
  86706. * to the other FLAC interfaces.
  86707. *
  86708. * See the detailed documentation for callbacks in the
  86709. * \link flac_callbacks callbacks \endlink module.
  86710. */
  86711. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  86712. * \ingroup flac
  86713. *
  86714. * \brief
  86715. * This module defines the structures for describing I/O callbacks
  86716. * to the other FLAC interfaces.
  86717. *
  86718. * The purpose of the I/O callback functions is to create a common way
  86719. * for the metadata interfaces to handle I/O.
  86720. *
  86721. * Originally the metadata interfaces required filenames as the way of
  86722. * specifying FLAC files to operate on. This is problematic in some
  86723. * environments so there is an additional option to specify a set of
  86724. * callbacks for doing I/O on the FLAC file, instead of the filename.
  86725. *
  86726. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  86727. * opaque structure for a data source.
  86728. *
  86729. * The callback function prototypes are similar (but not identical) to the
  86730. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  86731. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  86732. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  86733. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  86734. * is required. \warning You generally CANNOT directly use fseek or ftell
  86735. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  86736. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  86737. * large files. You will have to find an equivalent function (e.g. ftello),
  86738. * or write a wrapper. The same is true for feof() since this is usually
  86739. * implemented as a macro, not as a function whose address can be taken.
  86740. *
  86741. * \{
  86742. */
  86743. #ifdef __cplusplus
  86744. extern "C" {
  86745. #endif
  86746. /** This is the opaque handle type used by the callbacks. Typically
  86747. * this is a \c FILE* or address of a file descriptor.
  86748. */
  86749. typedef void* FLAC__IOHandle;
  86750. /** Signature for the read callback.
  86751. * The signature and semantics match POSIX fread() implementations
  86752. * and can generally be used interchangeably.
  86753. *
  86754. * \param ptr The address of the read buffer.
  86755. * \param size The size of the records to be read.
  86756. * \param nmemb The number of records to be read.
  86757. * \param handle The handle to the data source.
  86758. * \retval size_t
  86759. * The number of records read.
  86760. */
  86761. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86762. /** Signature for the write callback.
  86763. * The signature and semantics match POSIX fwrite() implementations
  86764. * and can generally be used interchangeably.
  86765. *
  86766. * \param ptr The address of the write buffer.
  86767. * \param size The size of the records to be written.
  86768. * \param nmemb The number of records to be written.
  86769. * \param handle The handle to the data source.
  86770. * \retval size_t
  86771. * The number of records written.
  86772. */
  86773. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  86774. /** Signature for the seek callback.
  86775. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  86776. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  86777. * and 32-bits wide.
  86778. *
  86779. * \param handle The handle to the data source.
  86780. * \param offset The new position, relative to \a whence
  86781. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  86782. * \retval int
  86783. * \c 0 on success, \c -1 on error.
  86784. */
  86785. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  86786. /** Signature for the tell callback.
  86787. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  86788. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  86789. * and 32-bits wide.
  86790. *
  86791. * \param handle The handle to the data source.
  86792. * \retval FLAC__int64
  86793. * The current position on success, \c -1 on error.
  86794. */
  86795. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  86796. /** Signature for the EOF callback.
  86797. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  86798. * on many systems, feof() is a macro, so in this case a wrapper function
  86799. * must be provided instead.
  86800. *
  86801. * \param handle The handle to the data source.
  86802. * \retval int
  86803. * \c 0 if not at end of file, nonzero if at end of file.
  86804. */
  86805. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  86806. /** Signature for the close callback.
  86807. * The signature and semantics match POSIX fclose() implementations
  86808. * and can generally be used interchangeably.
  86809. *
  86810. * \param handle The handle to the data source.
  86811. * \retval int
  86812. * \c 0 on success, \c EOF on error.
  86813. */
  86814. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  86815. /** A structure for holding a set of callbacks.
  86816. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  86817. * describe which of the callbacks are required. The ones that are not
  86818. * required may be set to NULL.
  86819. *
  86820. * If the seek requirement for an interface is optional, you can signify that
  86821. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  86822. */
  86823. typedef struct {
  86824. FLAC__IOCallback_Read read;
  86825. FLAC__IOCallback_Write write;
  86826. FLAC__IOCallback_Seek seek;
  86827. FLAC__IOCallback_Tell tell;
  86828. FLAC__IOCallback_Eof eof;
  86829. FLAC__IOCallback_Close close;
  86830. } FLAC__IOCallbacks;
  86831. /* \} */
  86832. #ifdef __cplusplus
  86833. }
  86834. #endif
  86835. #endif
  86836. /*** End of inlined file: callback.h ***/
  86837. /*** Start of inlined file: format.h ***/
  86838. #ifndef FLAC__FORMAT_H
  86839. #define FLAC__FORMAT_H
  86840. #ifdef __cplusplus
  86841. extern "C" {
  86842. #endif
  86843. /** \file include/FLAC/format.h
  86844. *
  86845. * \brief
  86846. * This module contains structure definitions for the representation
  86847. * of FLAC format components in memory. These are the basic
  86848. * structures used by the rest of the interfaces.
  86849. *
  86850. * See the detailed documentation in the
  86851. * \link flac_format format \endlink module.
  86852. */
  86853. /** \defgroup flac_format FLAC/format.h: format components
  86854. * \ingroup flac
  86855. *
  86856. * \brief
  86857. * This module contains structure definitions for the representation
  86858. * of FLAC format components in memory. These are the basic
  86859. * structures used by the rest of the interfaces.
  86860. *
  86861. * First, you should be familiar with the
  86862. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  86863. * follow directly from the specification. As a user of libFLAC, the
  86864. * interesting parts really are the structures that describe the frame
  86865. * header and metadata blocks.
  86866. *
  86867. * The format structures here are very primitive, designed to store
  86868. * information in an efficient way. Reading information from the
  86869. * structures is easy but creating or modifying them directly is
  86870. * more complex. For the most part, as a user of a library, editing
  86871. * is not necessary; however, for metadata blocks it is, so there are
  86872. * convenience functions provided in the \link flac_metadata metadata
  86873. * module \endlink to simplify the manipulation of metadata blocks.
  86874. *
  86875. * \note
  86876. * It's not the best convention, but symbols ending in _LEN are in bits
  86877. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  86878. * global variables because they are usually used when declaring byte
  86879. * arrays and some compilers require compile-time knowledge of array
  86880. * sizes when declared on the stack.
  86881. *
  86882. * \{
  86883. */
  86884. /*
  86885. Most of the values described in this file are defined by the FLAC
  86886. format specification. There is nothing to tune here.
  86887. */
  86888. /** The largest legal metadata type code. */
  86889. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  86890. /** The minimum block size, in samples, permitted by the format. */
  86891. #define FLAC__MIN_BLOCK_SIZE (16u)
  86892. /** The maximum block size, in samples, permitted by the format. */
  86893. #define FLAC__MAX_BLOCK_SIZE (65535u)
  86894. /** The maximum block size, in samples, permitted by the FLAC subset for
  86895. * sample rates up to 48kHz. */
  86896. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  86897. /** The maximum number of channels permitted by the format. */
  86898. #define FLAC__MAX_CHANNELS (8u)
  86899. /** The minimum sample resolution permitted by the format. */
  86900. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  86901. /** The maximum sample resolution permitted by the format. */
  86902. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  86903. /** The maximum sample resolution permitted by libFLAC.
  86904. *
  86905. * \warning
  86906. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  86907. * the reference encoder/decoder is currently limited to 24 bits because
  86908. * of prevalent 32-bit math, so make sure and use this value when
  86909. * appropriate.
  86910. */
  86911. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  86912. /** The maximum sample rate permitted by the format. The value is
  86913. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  86914. * as to why.
  86915. */
  86916. #define FLAC__MAX_SAMPLE_RATE (655350u)
  86917. /** The maximum LPC order permitted by the format. */
  86918. #define FLAC__MAX_LPC_ORDER (32u)
  86919. /** The maximum LPC order permitted by the FLAC subset for sample rates
  86920. * up to 48kHz. */
  86921. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  86922. /** The minimum quantized linear predictor coefficient precision
  86923. * permitted by the format.
  86924. */
  86925. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  86926. /** The maximum quantized linear predictor coefficient precision
  86927. * permitted by the format.
  86928. */
  86929. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  86930. /** The maximum order of the fixed predictors permitted by the format. */
  86931. #define FLAC__MAX_FIXED_ORDER (4u)
  86932. /** The maximum Rice partition order permitted by the format. */
  86933. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  86934. /** The maximum Rice partition order permitted by the FLAC Subset. */
  86935. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  86936. /** The version string of the release, stamped onto the libraries and binaries.
  86937. *
  86938. * \note
  86939. * This does not correspond to the shared library version number, which
  86940. * is used to determine binary compatibility.
  86941. */
  86942. extern FLAC_API const char *FLAC__VERSION_STRING;
  86943. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  86944. * This is a NUL-terminated ASCII string; when inserted into the
  86945. * VORBIS_COMMENT the trailing null is stripped.
  86946. */
  86947. extern FLAC_API const char *FLAC__VENDOR_STRING;
  86948. /** The byte string representation of the beginning of a FLAC stream. */
  86949. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  86950. /** The 32-bit integer big-endian representation of the beginning of
  86951. * a FLAC stream.
  86952. */
  86953. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  86954. /** The length of the FLAC signature in bits. */
  86955. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  86956. /** The length of the FLAC signature in bytes. */
  86957. #define FLAC__STREAM_SYNC_LENGTH (4u)
  86958. /*****************************************************************************
  86959. *
  86960. * Subframe structures
  86961. *
  86962. *****************************************************************************/
  86963. /*****************************************************************************/
  86964. /** An enumeration of the available entropy coding methods. */
  86965. typedef enum {
  86966. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  86967. /**< Residual is coded by partitioning into contexts, each with it's own
  86968. * 4-bit Rice parameter. */
  86969. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  86970. /**< Residual is coded by partitioning into contexts, each with it's own
  86971. * 5-bit Rice parameter. */
  86972. } FLAC__EntropyCodingMethodType;
  86973. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  86974. *
  86975. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  86976. * give the string equivalent. The contents should not be modified.
  86977. */
  86978. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  86979. /** Contents of a Rice partitioned residual
  86980. */
  86981. typedef struct {
  86982. unsigned *parameters;
  86983. /**< The Rice parameters for each context. */
  86984. unsigned *raw_bits;
  86985. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  86986. * partitions and zero for unescaped partitions.
  86987. */
  86988. unsigned capacity_by_order;
  86989. /**< The capacity of the \a parameters and \a raw_bits arrays
  86990. * specified as an order, i.e. the number of array elements
  86991. * allocated is 2 ^ \a capacity_by_order.
  86992. */
  86993. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  86994. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  86995. */
  86996. typedef struct {
  86997. unsigned order;
  86998. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  86999. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  87000. /**< The context's Rice parameters and/or raw bits. */
  87001. } FLAC__EntropyCodingMethod_PartitionedRice;
  87002. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  87003. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  87004. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  87005. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  87006. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  87007. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  87008. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  87009. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  87010. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  87011. */
  87012. typedef struct {
  87013. FLAC__EntropyCodingMethodType type;
  87014. union {
  87015. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  87016. } data;
  87017. } FLAC__EntropyCodingMethod;
  87018. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  87019. /*****************************************************************************/
  87020. /** An enumeration of the available subframe types. */
  87021. typedef enum {
  87022. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  87023. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  87024. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  87025. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  87026. } FLAC__SubframeType;
  87027. /** Maps a FLAC__SubframeType to a C string.
  87028. *
  87029. * Using a FLAC__SubframeType as the index to this array will
  87030. * give the string equivalent. The contents should not be modified.
  87031. */
  87032. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  87033. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  87034. */
  87035. typedef struct {
  87036. FLAC__int32 value; /**< The constant signal value. */
  87037. } FLAC__Subframe_Constant;
  87038. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  87039. */
  87040. typedef struct {
  87041. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  87042. } FLAC__Subframe_Verbatim;
  87043. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  87044. */
  87045. typedef struct {
  87046. FLAC__EntropyCodingMethod entropy_coding_method;
  87047. /**< The residual coding method. */
  87048. unsigned order;
  87049. /**< The polynomial order. */
  87050. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  87051. /**< Warmup samples to prime the predictor, length == order. */
  87052. const FLAC__int32 *residual;
  87053. /**< The residual signal, length == (blocksize minus order) samples. */
  87054. } FLAC__Subframe_Fixed;
  87055. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  87056. */
  87057. typedef struct {
  87058. FLAC__EntropyCodingMethod entropy_coding_method;
  87059. /**< The residual coding method. */
  87060. unsigned order;
  87061. /**< The FIR order. */
  87062. unsigned qlp_coeff_precision;
  87063. /**< Quantized FIR filter coefficient precision in bits. */
  87064. int quantization_level;
  87065. /**< The qlp coeff shift needed. */
  87066. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  87067. /**< FIR filter coefficients. */
  87068. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  87069. /**< Warmup samples to prime the predictor, length == order. */
  87070. const FLAC__int32 *residual;
  87071. /**< The residual signal, length == (blocksize minus order) samples. */
  87072. } FLAC__Subframe_LPC;
  87073. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  87074. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  87075. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  87076. */
  87077. typedef struct {
  87078. FLAC__SubframeType type;
  87079. union {
  87080. FLAC__Subframe_Constant constant;
  87081. FLAC__Subframe_Fixed fixed;
  87082. FLAC__Subframe_LPC lpc;
  87083. FLAC__Subframe_Verbatim verbatim;
  87084. } data;
  87085. unsigned wasted_bits;
  87086. } FLAC__Subframe;
  87087. /** == 1 (bit)
  87088. *
  87089. * This used to be a zero-padding bit (hence the name
  87090. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  87091. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  87092. * to mean something else.
  87093. */
  87094. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  87095. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  87096. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  87097. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  87098. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  87099. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  87100. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  87101. /*****************************************************************************/
  87102. /*****************************************************************************
  87103. *
  87104. * Frame structures
  87105. *
  87106. *****************************************************************************/
  87107. /** An enumeration of the available channel assignments. */
  87108. typedef enum {
  87109. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  87110. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  87111. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  87112. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  87113. } FLAC__ChannelAssignment;
  87114. /** Maps a FLAC__ChannelAssignment to a C string.
  87115. *
  87116. * Using a FLAC__ChannelAssignment as the index to this array will
  87117. * give the string equivalent. The contents should not be modified.
  87118. */
  87119. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  87120. /** An enumeration of the possible frame numbering methods. */
  87121. typedef enum {
  87122. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  87123. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  87124. } FLAC__FrameNumberType;
  87125. /** Maps a FLAC__FrameNumberType to a C string.
  87126. *
  87127. * Using a FLAC__FrameNumberType as the index to this array will
  87128. * give the string equivalent. The contents should not be modified.
  87129. */
  87130. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  87131. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  87132. */
  87133. typedef struct {
  87134. unsigned blocksize;
  87135. /**< The number of samples per subframe. */
  87136. unsigned sample_rate;
  87137. /**< The sample rate in Hz. */
  87138. unsigned channels;
  87139. /**< The number of channels (== number of subframes). */
  87140. FLAC__ChannelAssignment channel_assignment;
  87141. /**< The channel assignment for the frame. */
  87142. unsigned bits_per_sample;
  87143. /**< The sample resolution. */
  87144. FLAC__FrameNumberType number_type;
  87145. /**< The numbering scheme used for the frame. As a convenience, the
  87146. * decoder will always convert a frame number to a sample number because
  87147. * the rules are complex. */
  87148. union {
  87149. FLAC__uint32 frame_number;
  87150. FLAC__uint64 sample_number;
  87151. } number;
  87152. /**< The frame number or sample number of first sample in frame;
  87153. * use the \a number_type value to determine which to use. */
  87154. FLAC__uint8 crc;
  87155. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  87156. * of the raw frame header bytes, meaning everything before the CRC byte
  87157. * including the sync code.
  87158. */
  87159. } FLAC__FrameHeader;
  87160. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  87161. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  87162. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  87163. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  87164. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  87165. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  87166. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  87167. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  87168. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  87169. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  87170. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  87171. */
  87172. typedef struct {
  87173. FLAC__uint16 crc;
  87174. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  87175. * 0) of the bytes before the crc, back to and including the frame header
  87176. * sync code.
  87177. */
  87178. } FLAC__FrameFooter;
  87179. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  87180. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  87181. */
  87182. typedef struct {
  87183. FLAC__FrameHeader header;
  87184. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  87185. FLAC__FrameFooter footer;
  87186. } FLAC__Frame;
  87187. /*****************************************************************************/
  87188. /*****************************************************************************
  87189. *
  87190. * Meta-data structures
  87191. *
  87192. *****************************************************************************/
  87193. /** An enumeration of the available metadata block types. */
  87194. typedef enum {
  87195. FLAC__METADATA_TYPE_STREAMINFO = 0,
  87196. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  87197. FLAC__METADATA_TYPE_PADDING = 1,
  87198. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  87199. FLAC__METADATA_TYPE_APPLICATION = 2,
  87200. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  87201. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  87202. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  87203. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  87204. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  87205. FLAC__METADATA_TYPE_CUESHEET = 5,
  87206. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  87207. FLAC__METADATA_TYPE_PICTURE = 6,
  87208. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  87209. FLAC__METADATA_TYPE_UNDEFINED = 7
  87210. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  87211. } FLAC__MetadataType;
  87212. /** Maps a FLAC__MetadataType to a C string.
  87213. *
  87214. * Using a FLAC__MetadataType as the index to this array will
  87215. * give the string equivalent. The contents should not be modified.
  87216. */
  87217. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  87218. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  87219. */
  87220. typedef struct {
  87221. unsigned min_blocksize, max_blocksize;
  87222. unsigned min_framesize, max_framesize;
  87223. unsigned sample_rate;
  87224. unsigned channels;
  87225. unsigned bits_per_sample;
  87226. FLAC__uint64 total_samples;
  87227. FLAC__byte md5sum[16];
  87228. } FLAC__StreamMetadata_StreamInfo;
  87229. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87230. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  87231. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87232. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  87233. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  87234. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  87235. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  87236. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  87237. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  87238. /** The total stream length of the STREAMINFO block in bytes. */
  87239. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  87240. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  87241. */
  87242. typedef struct {
  87243. int dummy;
  87244. /**< Conceptually this is an empty struct since we don't store the
  87245. * padding bytes. Empty structs are not allowed by some C compilers,
  87246. * hence the dummy.
  87247. */
  87248. } FLAC__StreamMetadata_Padding;
  87249. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  87250. */
  87251. typedef struct {
  87252. FLAC__byte id[4];
  87253. FLAC__byte *data;
  87254. } FLAC__StreamMetadata_Application;
  87255. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  87256. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  87257. */
  87258. typedef struct {
  87259. FLAC__uint64 sample_number;
  87260. /**< The sample number of the target frame. */
  87261. FLAC__uint64 stream_offset;
  87262. /**< The offset, in bytes, of the target frame with respect to
  87263. * beginning of the first frame. */
  87264. unsigned frame_samples;
  87265. /**< The number of samples in the target frame. */
  87266. } FLAC__StreamMetadata_SeekPoint;
  87267. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  87268. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  87269. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  87270. /** The total stream length of a seek point in bytes. */
  87271. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  87272. /** The value used in the \a sample_number field of
  87273. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  87274. * point (== 0xffffffffffffffff).
  87275. */
  87276. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  87277. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  87278. *
  87279. * \note From the format specification:
  87280. * - The seek points must be sorted by ascending sample number.
  87281. * - Each seek point's sample number must be the first sample of the
  87282. * target frame.
  87283. * - Each seek point's sample number must be unique within the table.
  87284. * - Existence of a SEEKTABLE block implies a correct setting of
  87285. * total_samples in the stream_info block.
  87286. * - Behavior is undefined when more than one SEEKTABLE block is
  87287. * present in a stream.
  87288. */
  87289. typedef struct {
  87290. unsigned num_points;
  87291. FLAC__StreamMetadata_SeekPoint *points;
  87292. } FLAC__StreamMetadata_SeekTable;
  87293. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87294. *
  87295. * For convenience, the APIs maintain a trailing NUL character at the end of
  87296. * \a entry which is not counted toward \a length, i.e.
  87297. * \code strlen(entry) == length \endcode
  87298. */
  87299. typedef struct {
  87300. FLAC__uint32 length;
  87301. FLAC__byte *entry;
  87302. } FLAC__StreamMetadata_VorbisComment_Entry;
  87303. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  87304. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  87305. */
  87306. typedef struct {
  87307. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  87308. FLAC__uint32 num_comments;
  87309. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  87310. } FLAC__StreamMetadata_VorbisComment;
  87311. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  87312. /** FLAC CUESHEET track index structure. (See the
  87313. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  87314. * the full description of each field.)
  87315. */
  87316. typedef struct {
  87317. FLAC__uint64 offset;
  87318. /**< Offset in samples, relative to the track offset, of the index
  87319. * point.
  87320. */
  87321. FLAC__byte number;
  87322. /**< The index point number. */
  87323. } FLAC__StreamMetadata_CueSheet_Index;
  87324. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  87325. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  87326. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  87327. /** FLAC CUESHEET track structure. (See the
  87328. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  87329. * the full description of each field.)
  87330. */
  87331. typedef struct {
  87332. FLAC__uint64 offset;
  87333. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  87334. FLAC__byte number;
  87335. /**< The track number. */
  87336. char isrc[13];
  87337. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  87338. unsigned type:1;
  87339. /**< The track type: 0 for audio, 1 for non-audio. */
  87340. unsigned pre_emphasis:1;
  87341. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  87342. FLAC__byte num_indices;
  87343. /**< The number of track index points. */
  87344. FLAC__StreamMetadata_CueSheet_Index *indices;
  87345. /**< NULL if num_indices == 0, else pointer to array of index points. */
  87346. } FLAC__StreamMetadata_CueSheet_Track;
  87347. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  87348. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  87349. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  87350. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  87351. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  87352. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  87353. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  87354. /** FLAC CUESHEET structure. (See the
  87355. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  87356. * for the full description of each field.)
  87357. */
  87358. typedef struct {
  87359. char media_catalog_number[129];
  87360. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  87361. * general, the media catalog number may be 0 to 128 bytes long; any
  87362. * unused characters should be right-padded with NUL characters.
  87363. */
  87364. FLAC__uint64 lead_in;
  87365. /**< The number of lead-in samples. */
  87366. FLAC__bool is_cd;
  87367. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  87368. unsigned num_tracks;
  87369. /**< The number of tracks. */
  87370. FLAC__StreamMetadata_CueSheet_Track *tracks;
  87371. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  87372. } FLAC__StreamMetadata_CueSheet;
  87373. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  87374. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  87375. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  87376. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  87377. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  87378. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  87379. typedef enum {
  87380. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  87381. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  87382. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  87383. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  87384. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  87385. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  87386. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  87387. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  87388. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  87389. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  87390. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  87391. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  87392. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  87393. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  87394. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  87395. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  87396. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  87397. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  87398. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  87399. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  87400. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  87401. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  87402. } FLAC__StreamMetadata_Picture_Type;
  87403. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  87404. *
  87405. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  87406. * will give the string equivalent. The contents should not be
  87407. * modified.
  87408. */
  87409. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  87410. /** FLAC PICTURE structure. (See the
  87411. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  87412. * for the full description of each field.)
  87413. */
  87414. typedef struct {
  87415. FLAC__StreamMetadata_Picture_Type type;
  87416. /**< The kind of picture stored. */
  87417. char *mime_type;
  87418. /**< Picture data's MIME type, in ASCII printable characters
  87419. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  87420. * use picture data of MIME type \c image/jpeg or \c image/png. A
  87421. * MIME type of '-->' is also allowed, in which case the picture
  87422. * data should be a complete URL. In file storage, the MIME type is
  87423. * stored as a 32-bit length followed by the ASCII string with no NUL
  87424. * terminator, but is converted to a plain C string in this structure
  87425. * for convenience.
  87426. */
  87427. FLAC__byte *description;
  87428. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  87429. * the description is stored as a 32-bit length followed by the UTF-8
  87430. * string with no NUL terminator, but is converted to a plain C string
  87431. * in this structure for convenience.
  87432. */
  87433. FLAC__uint32 width;
  87434. /**< Picture's width in pixels. */
  87435. FLAC__uint32 height;
  87436. /**< Picture's height in pixels. */
  87437. FLAC__uint32 depth;
  87438. /**< Picture's color depth in bits-per-pixel. */
  87439. FLAC__uint32 colors;
  87440. /**< For indexed palettes (like GIF), picture's number of colors (the
  87441. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  87442. */
  87443. FLAC__uint32 data_length;
  87444. /**< Length of binary picture data in bytes. */
  87445. FLAC__byte *data;
  87446. /**< Binary picture data. */
  87447. } FLAC__StreamMetadata_Picture;
  87448. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  87449. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  87450. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  87451. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  87452. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  87453. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  87454. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  87455. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  87456. /** Structure that is used when a metadata block of unknown type is loaded.
  87457. * The contents are opaque. The structure is used only internally to
  87458. * correctly handle unknown metadata.
  87459. */
  87460. typedef struct {
  87461. FLAC__byte *data;
  87462. } FLAC__StreamMetadata_Unknown;
  87463. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  87464. */
  87465. typedef struct {
  87466. FLAC__MetadataType type;
  87467. /**< The type of the metadata block; used determine which member of the
  87468. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  87469. * then \a data.unknown must be used. */
  87470. FLAC__bool is_last;
  87471. /**< \c true if this metadata block is the last, else \a false */
  87472. unsigned length;
  87473. /**< Length, in bytes, of the block data as it appears in the stream. */
  87474. union {
  87475. FLAC__StreamMetadata_StreamInfo stream_info;
  87476. FLAC__StreamMetadata_Padding padding;
  87477. FLAC__StreamMetadata_Application application;
  87478. FLAC__StreamMetadata_SeekTable seek_table;
  87479. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  87480. FLAC__StreamMetadata_CueSheet cue_sheet;
  87481. FLAC__StreamMetadata_Picture picture;
  87482. FLAC__StreamMetadata_Unknown unknown;
  87483. } data;
  87484. /**< Polymorphic block data; use the \a type value to determine which
  87485. * to use. */
  87486. } FLAC__StreamMetadata;
  87487. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  87488. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  87489. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  87490. /** The total stream length of a metadata block header in bytes. */
  87491. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  87492. /*****************************************************************************/
  87493. /*****************************************************************************
  87494. *
  87495. * Utility functions
  87496. *
  87497. *****************************************************************************/
  87498. /** Tests that a sample rate is valid for FLAC.
  87499. *
  87500. * \param sample_rate The sample rate to test for compliance.
  87501. * \retval FLAC__bool
  87502. * \c true if the given sample rate conforms to the specification, else
  87503. * \c false.
  87504. */
  87505. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  87506. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  87507. * for valid sample rates are slightly more complex since the rate has to
  87508. * be expressible completely in the frame header.
  87509. *
  87510. * \param sample_rate The sample rate to test for compliance.
  87511. * \retval FLAC__bool
  87512. * \c true if the given sample rate conforms to the specification for the
  87513. * subset, else \c false.
  87514. */
  87515. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  87516. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  87517. * comment specification.
  87518. *
  87519. * Vorbis comment names must be composed only of characters from
  87520. * [0x20-0x3C,0x3E-0x7D].
  87521. *
  87522. * \param name A NUL-terminated string to be checked.
  87523. * \assert
  87524. * \code name != 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_name_is_legal(const char *name);
  87529. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  87530. * comment specification.
  87531. *
  87532. * Vorbis comment values must be valid UTF-8 sequences.
  87533. *
  87534. * \param value A string to be checked.
  87535. * \param length A the length of \a value in bytes. May be
  87536. * \c (unsigned)(-1) to indicate that \a value is a plain
  87537. * UTF-8 NUL-terminated string.
  87538. * \assert
  87539. * \code value != NULL \endcode
  87540. * \retval FLAC__bool
  87541. * \c false if entry name is illegal, else \c true.
  87542. */
  87543. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  87544. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  87545. * comment specification.
  87546. *
  87547. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  87548. * 'value' must be legal according to
  87549. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  87550. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  87551. *
  87552. * \param entry An entry to be checked.
  87553. * \param length The length of \a entry in bytes.
  87554. * \assert
  87555. * \code value != NULL \endcode
  87556. * \retval FLAC__bool
  87557. * \c false if entry name is illegal, else \c true.
  87558. */
  87559. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  87560. /** Check a seek table to see if it conforms to the FLAC specification.
  87561. * See the format specification for limits on the contents of the
  87562. * seek table.
  87563. *
  87564. * \param seek_table A pointer to a seek table to be checked.
  87565. * \assert
  87566. * \code seek_table != NULL \endcode
  87567. * \retval FLAC__bool
  87568. * \c false if seek table is illegal, else \c true.
  87569. */
  87570. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  87571. /** Sort a seek table's seek points according to the format specification.
  87572. * This includes a "unique-ification" step to remove duplicates, i.e.
  87573. * seek points with identical \a sample_number values. Duplicate seek
  87574. * points are converted into placeholder points and sorted to the end of
  87575. * the table.
  87576. *
  87577. * \param seek_table A pointer to a seek table to be sorted.
  87578. * \assert
  87579. * \code seek_table != NULL \endcode
  87580. * \retval unsigned
  87581. * The number of duplicate seek points converted into placeholders.
  87582. */
  87583. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  87584. /** Check a cue sheet to see if it conforms to the FLAC specification.
  87585. * See the format specification for limits on the contents of the
  87586. * cue sheet.
  87587. *
  87588. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  87589. * \param check_cd_da_subset If \c true, check CUESHEET against more
  87590. * stringent requirements for a CD-DA (audio) disc.
  87591. * \param violation Address of a pointer to a string. If there is a
  87592. * violation, a pointer to a string explanation of the
  87593. * violation will be returned here. \a violation may be
  87594. * \c NULL if you don't need the returned string. Do not
  87595. * free the returned string; it will always point to static
  87596. * data.
  87597. * \assert
  87598. * \code cue_sheet != NULL \endcode
  87599. * \retval FLAC__bool
  87600. * \c false if cue sheet is illegal, else \c true.
  87601. */
  87602. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  87603. /** Check picture data to see if it conforms to the FLAC specification.
  87604. * See the format specification for limits on the contents of the
  87605. * PICTURE block.
  87606. *
  87607. * \param picture A pointer to existing picture data to be checked.
  87608. * \param violation Address of a pointer to a string. If there is a
  87609. * violation, a pointer to a string explanation of the
  87610. * violation will be returned here. \a violation may be
  87611. * \c NULL if you don't need the returned string. Do not
  87612. * free the returned string; it will always point to static
  87613. * data.
  87614. * \assert
  87615. * \code picture != NULL \endcode
  87616. * \retval FLAC__bool
  87617. * \c false if picture data is illegal, else \c true.
  87618. */
  87619. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  87620. /* \} */
  87621. #ifdef __cplusplus
  87622. }
  87623. #endif
  87624. #endif
  87625. /*** End of inlined file: format.h ***/
  87626. /*** Start of inlined file: metadata.h ***/
  87627. #ifndef FLAC__METADATA_H
  87628. #define FLAC__METADATA_H
  87629. #include <sys/types.h> /* for off_t */
  87630. /* --------------------------------------------------------------------
  87631. (For an example of how all these routines are used, see the source
  87632. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  87633. metaflac in src/metaflac/)
  87634. ------------------------------------------------------------------*/
  87635. /** \file include/FLAC/metadata.h
  87636. *
  87637. * \brief
  87638. * This module provides functions for creating and manipulating FLAC
  87639. * metadata blocks in memory, and three progressively more powerful
  87640. * interfaces for traversing and editing metadata in FLAC files.
  87641. *
  87642. * See the detailed documentation for each interface in the
  87643. * \link flac_metadata metadata \endlink module.
  87644. */
  87645. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  87646. * \ingroup flac
  87647. *
  87648. * \brief
  87649. * This module provides functions for creating and manipulating FLAC
  87650. * metadata blocks in memory, and three progressively more powerful
  87651. * interfaces for traversing and editing metadata in native FLAC files.
  87652. * Note that currently only the Chain interface (level 2) supports Ogg
  87653. * FLAC files, and it is read-only i.e. no writing back changed
  87654. * metadata to file.
  87655. *
  87656. * There are three metadata interfaces of increasing complexity:
  87657. *
  87658. * Level 0:
  87659. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  87660. * PICTURE blocks.
  87661. *
  87662. * Level 1:
  87663. * Read-write access to all metadata blocks. This level is write-
  87664. * efficient in most cases (more on this below), and uses less memory
  87665. * than level 2.
  87666. *
  87667. * Level 2:
  87668. * Read-write access to all metadata blocks. This level is write-
  87669. * efficient in all cases, but uses more memory since all metadata for
  87670. * the whole file is read into memory and manipulated before writing
  87671. * out again.
  87672. *
  87673. * What do we mean by efficient? Since FLAC metadata appears at the
  87674. * beginning of the file, when writing metadata back to a FLAC file
  87675. * it is possible to grow or shrink the metadata such that the entire
  87676. * file must be rewritten. However, if the size remains the same during
  87677. * changes or PADDING blocks are utilized, only the metadata needs to be
  87678. * overwritten, which is much faster.
  87679. *
  87680. * Efficient means the whole file is rewritten at most one time, and only
  87681. * when necessary. Level 1 is not efficient only in the case that you
  87682. * cause more than one metadata block to grow or shrink beyond what can
  87683. * be accomodated by padding. In this case you should probably use level
  87684. * 2, which allows you to edit all the metadata for a file in memory and
  87685. * write it out all at once.
  87686. *
  87687. * All levels know how to skip over and not disturb an ID3v2 tag at the
  87688. * front of the file.
  87689. *
  87690. * All levels access files via their filenames. In addition, level 2
  87691. * has additional alternative read and write functions that take an I/O
  87692. * handle and callbacks, for situations where access by filename is not
  87693. * possible.
  87694. *
  87695. * In addition to the three interfaces, this module defines functions for
  87696. * creating and manipulating various metadata objects in memory. As we see
  87697. * from the Format module, FLAC metadata blocks in memory are very primitive
  87698. * structures for storing information in an efficient way. Reading
  87699. * information from the structures is easy but creating or modifying them
  87700. * directly is more complex. The metadata object routines here facilitate
  87701. * this by taking care of the consistency and memory management drudgery.
  87702. *
  87703. * Unless you will be using the level 1 or 2 interfaces to modify existing
  87704. * metadata however, you will not probably not need these.
  87705. *
  87706. * From a dependency standpoint, none of the encoders or decoders require
  87707. * the metadata module. This is so that embedded users can strip out the
  87708. * metadata module from libFLAC to reduce the size and complexity.
  87709. */
  87710. #ifdef __cplusplus
  87711. extern "C" {
  87712. #endif
  87713. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  87714. * \ingroup flac_metadata
  87715. *
  87716. * \brief
  87717. * The level 0 interface consists of individual routines to read the
  87718. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  87719. * only a filename.
  87720. *
  87721. * They try to skip any ID3v2 tag at the head of the file.
  87722. *
  87723. * \{
  87724. */
  87725. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  87726. * will try to skip any ID3v2 tag at the head of the file.
  87727. *
  87728. * \param filename The path to the FLAC file to read.
  87729. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  87730. * FLAC__StreamMetadata is a simple structure with no
  87731. * memory allocation involved, you pass the address of
  87732. * an existing structure. It need not be initialized.
  87733. * \assert
  87734. * \code filename != NULL \endcode
  87735. * \code streaminfo != NULL \endcode
  87736. * \retval FLAC__bool
  87737. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  87738. * \c false if there was a memory allocation error, a file decoder error,
  87739. * or the file contained no STREAMINFO block. (A memory allocation error
  87740. * is possible because this function must set up a file decoder.)
  87741. */
  87742. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  87743. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  87744. * function will try to skip any ID3v2 tag at the head of the file.
  87745. *
  87746. * \param filename The path to the FLAC file to read.
  87747. * \param tags The address where the returned pointer will be
  87748. * stored. The \a tags object must be deleted by
  87749. * the caller using FLAC__metadata_object_delete().
  87750. * \assert
  87751. * \code filename != NULL \endcode
  87752. * \code tags != NULL \endcode
  87753. * \retval FLAC__bool
  87754. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  87755. * and \a *tags will be set to the address of the metadata structure.
  87756. * Returns \c false if there was a memory allocation error, a file
  87757. * decoder error, or the file contained no VORBIS_COMMENT block, and
  87758. * \a *tags will be set to \c NULL.
  87759. */
  87760. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  87761. /** Read the CUESHEET metadata block of the given FLAC file. This
  87762. * function will try to skip any ID3v2 tag at the head of the file.
  87763. *
  87764. * \param filename The path to the FLAC file to read.
  87765. * \param cuesheet The address where the returned pointer will be
  87766. * stored. The \a cuesheet object must be deleted by
  87767. * the caller using FLAC__metadata_object_delete().
  87768. * \assert
  87769. * \code filename != NULL \endcode
  87770. * \code cuesheet != NULL \endcode
  87771. * \retval FLAC__bool
  87772. * \c true if a valid CUESHEET block was read from \a filename,
  87773. * and \a *cuesheet will be set to the address of the metadata
  87774. * structure. Returns \c false if there was a memory allocation
  87775. * error, a file decoder error, or the file contained no CUESHEET
  87776. * block, and \a *cuesheet will be set to \c NULL.
  87777. */
  87778. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  87779. /** Read a PICTURE metadata block of the given FLAC file. This
  87780. * function will try to skip any ID3v2 tag at the head of the file.
  87781. * Since there can be more than one PICTURE block in a file, this
  87782. * function takes a number of parameters that act as constraints to
  87783. * the search. The PICTURE block with the largest area matching all
  87784. * the constraints will be returned, or \a *picture will be set to
  87785. * \c NULL if there was no such block.
  87786. *
  87787. * \param filename The path to the FLAC file to read.
  87788. * \param picture The address where the returned pointer will be
  87789. * stored. The \a picture object must be deleted by
  87790. * the caller using FLAC__metadata_object_delete().
  87791. * \param type The desired picture type. Use \c -1 to mean
  87792. * "any type".
  87793. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  87794. * string will be matched exactly. Use \c NULL to
  87795. * mean "any MIME type".
  87796. * \param description The desired description. The string will be
  87797. * matched exactly. Use \c NULL to mean "any
  87798. * description".
  87799. * \param max_width The maximum width in pixels desired. Use
  87800. * \c (unsigned)(-1) to mean "any width".
  87801. * \param max_height The maximum height in pixels desired. Use
  87802. * \c (unsigned)(-1) to mean "any height".
  87803. * \param max_depth The maximum color depth in bits-per-pixel desired.
  87804. * Use \c (unsigned)(-1) to mean "any depth".
  87805. * \param max_colors The maximum number of colors desired. Use
  87806. * \c (unsigned)(-1) to mean "any number of colors".
  87807. * \assert
  87808. * \code filename != NULL \endcode
  87809. * \code picture != NULL \endcode
  87810. * \retval FLAC__bool
  87811. * \c true if a valid PICTURE block was read from \a filename,
  87812. * and \a *picture will be set to the address of the metadata
  87813. * structure. Returns \c false if there was a memory allocation
  87814. * error, a file decoder error, or the file contained no PICTURE
  87815. * block, and \a *picture will be set to \c NULL.
  87816. */
  87817. 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);
  87818. /* \} */
  87819. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  87820. * \ingroup flac_metadata
  87821. *
  87822. * \brief
  87823. * The level 1 interface provides read-write access to FLAC file metadata and
  87824. * operates directly on the FLAC file.
  87825. *
  87826. * The general usage of this interface is:
  87827. *
  87828. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  87829. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  87830. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  87831. * see if the file is writable, or only read access is allowed.
  87832. * - Use FLAC__metadata_simple_iterator_next() and
  87833. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  87834. * This is does not read the actual blocks themselves.
  87835. * FLAC__metadata_simple_iterator_next() is relatively fast.
  87836. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  87837. * forward from the front of the file.
  87838. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  87839. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  87840. * the current iterator position. The returned object is yours to modify
  87841. * and free.
  87842. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  87843. * back. You must have write permission to the original file. Make sure to
  87844. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  87845. * below.
  87846. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  87847. * Use the object creation functions from
  87848. * \link flac_metadata_object here \endlink to generate new objects.
  87849. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  87850. * currently referred to by the iterator, or replace it with padding.
  87851. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  87852. * finished.
  87853. *
  87854. * \note
  87855. * The FLAC file remains open the whole time between
  87856. * FLAC__metadata_simple_iterator_init() and
  87857. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  87858. * the file during this time.
  87859. *
  87860. * \note
  87861. * Do not modify the \a is_last, \a length, or \a type fields of returned
  87862. * FLAC__StreamMetadata objects. These are managed automatically.
  87863. *
  87864. * \note
  87865. * If any of the modification functions
  87866. * (FLAC__metadata_simple_iterator_set_block(),
  87867. * FLAC__metadata_simple_iterator_delete_block(),
  87868. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  87869. * you should delete the iterator as it may no longer be valid.
  87870. *
  87871. * \{
  87872. */
  87873. struct FLAC__Metadata_SimpleIterator;
  87874. /** The opaque structure definition for the level 1 iterator type.
  87875. * See the
  87876. * \link flac_metadata_level1 metadata level 1 module \endlink
  87877. * for a detailed description.
  87878. */
  87879. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  87880. /** Status type for FLAC__Metadata_SimpleIterator.
  87881. *
  87882. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  87883. */
  87884. typedef enum {
  87885. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  87886. /**< The iterator is in the normal OK state */
  87887. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  87888. /**< The data passed into a function violated the function's usage criteria */
  87889. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  87890. /**< The iterator could not open the target file */
  87891. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  87892. /**< The iterator could not find the FLAC signature at the start of the file */
  87893. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  87894. /**< The iterator tried to write to a file that was not writable */
  87895. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  87896. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  87897. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  87898. /**< The iterator encountered an error while reading the FLAC file */
  87899. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  87900. /**< The iterator encountered an error while seeking in the FLAC file */
  87901. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  87902. /**< The iterator encountered an error while writing the FLAC file */
  87903. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  87904. /**< The iterator encountered an error renaming the FLAC file */
  87905. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  87906. /**< The iterator encountered an error removing the temporary file */
  87907. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  87908. /**< Memory allocation failed */
  87909. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  87910. /**< The caller violated an assertion or an unexpected error occurred */
  87911. } FLAC__Metadata_SimpleIteratorStatus;
  87912. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  87913. *
  87914. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  87915. * will give the string equivalent. The contents should not be modified.
  87916. */
  87917. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  87918. /** Create a new iterator instance.
  87919. *
  87920. * \retval FLAC__Metadata_SimpleIterator*
  87921. * \c NULL if there was an error allocating memory, else the new instance.
  87922. */
  87923. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  87924. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  87925. *
  87926. * \param iterator A pointer to an existing iterator.
  87927. * \assert
  87928. * \code iterator != NULL \endcode
  87929. */
  87930. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  87931. /** Get the current status of the iterator. Call this after a function
  87932. * returns \c false to get the reason for the error. Also resets the status
  87933. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  87934. *
  87935. * \param iterator A pointer to an existing iterator.
  87936. * \assert
  87937. * \code iterator != NULL \endcode
  87938. * \retval FLAC__Metadata_SimpleIteratorStatus
  87939. * The current status of the iterator.
  87940. */
  87941. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  87942. /** Initialize the iterator to point to the first metadata block in the
  87943. * given FLAC file.
  87944. *
  87945. * \param iterator A pointer to an existing iterator.
  87946. * \param filename The path to the FLAC file.
  87947. * \param read_only If \c true, the FLAC file will be opened
  87948. * in read-only mode; if \c false, the FLAC
  87949. * file will be opened for edit even if no
  87950. * edits are performed.
  87951. * \param preserve_file_stats If \c true, the owner and modification
  87952. * time will be preserved even if the FLAC
  87953. * file is written to.
  87954. * \assert
  87955. * \code iterator != NULL \endcode
  87956. * \code filename != NULL \endcode
  87957. * \retval FLAC__bool
  87958. * \c false if a memory allocation error occurs, the file can't be
  87959. * opened, or another error occurs, else \c true.
  87960. */
  87961. 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);
  87962. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  87963. * FLAC__metadata_simple_iterator_set_block() and
  87964. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  87965. *
  87966. * \param iterator A pointer to an existing iterator.
  87967. * \assert
  87968. * \code iterator != NULL \endcode
  87969. * \retval FLAC__bool
  87970. * See above.
  87971. */
  87972. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  87973. /** Moves the iterator forward one metadata block, returning \c false if
  87974. * already at the end.
  87975. *
  87976. * \param iterator A pointer to an existing initialized iterator.
  87977. * \assert
  87978. * \code iterator != NULL \endcode
  87979. * \a iterator has been successfully initialized with
  87980. * FLAC__metadata_simple_iterator_init()
  87981. * \retval FLAC__bool
  87982. * \c false if already at the last metadata block of the chain, else
  87983. * \c true.
  87984. */
  87985. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  87986. /** Moves the iterator backward one metadata block, returning \c false if
  87987. * already at the beginning.
  87988. *
  87989. * \param iterator A pointer to an existing initialized iterator.
  87990. * \assert
  87991. * \code iterator != NULL \endcode
  87992. * \a iterator has been successfully initialized with
  87993. * FLAC__metadata_simple_iterator_init()
  87994. * \retval FLAC__bool
  87995. * \c false if already at the first metadata block of the chain, else
  87996. * \c true.
  87997. */
  87998. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  87999. /** Returns a flag telling if the current metadata block is the last.
  88000. *
  88001. * \param iterator A pointer to an existing initialized iterator.
  88002. * \assert
  88003. * \code iterator != NULL \endcode
  88004. * \a iterator has been successfully initialized with
  88005. * FLAC__metadata_simple_iterator_init()
  88006. * \retval FLAC__bool
  88007. * \c true if the current metadata block is the last in the file,
  88008. * else \c false.
  88009. */
  88010. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  88011. /** Get the offset 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 off_t
  88021. * The offset of the metadata block at the current iterator position.
  88022. * This is the byte offset relative to the beginning of the file of
  88023. * the current metadata block's header.
  88024. */
  88025. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  88026. /** Get the type of the metadata block at the current position. This
  88027. * avoids reading the actual block data which can save time for large
  88028. * blocks.
  88029. *
  88030. * \param iterator A pointer to an existing initialized iterator.
  88031. * \assert
  88032. * \code iterator != NULL \endcode
  88033. * \a iterator has been successfully initialized with
  88034. * FLAC__metadata_simple_iterator_init()
  88035. * \retval FLAC__MetadataType
  88036. * The type of the metadata block at the current iterator position.
  88037. */
  88038. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  88039. /** Get the length of the metadata block at the current position. This
  88040. * avoids reading the actual block data which can save time for large
  88041. * blocks.
  88042. *
  88043. * \param iterator A pointer to an existing initialized iterator.
  88044. * \assert
  88045. * \code iterator != NULL \endcode
  88046. * \a iterator has been successfully initialized with
  88047. * FLAC__metadata_simple_iterator_init()
  88048. * \retval unsigned
  88049. * The length of the metadata block at the current iterator position.
  88050. * The is same length as that in the
  88051. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  88052. * i.e. the length of the metadata body that follows the header.
  88053. */
  88054. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  88055. /** Get the application ID of the \c APPLICATION block at the current
  88056. * position. This avoids reading the actual block data which can save
  88057. * time for large blocks.
  88058. *
  88059. * \param iterator A pointer to an existing initialized iterator.
  88060. * \param id A pointer to a buffer of at least \c 4 bytes where
  88061. * the ID will be stored.
  88062. * \assert
  88063. * \code iterator != NULL \endcode
  88064. * \code id != NULL \endcode
  88065. * \a iterator has been successfully initialized with
  88066. * FLAC__metadata_simple_iterator_init()
  88067. * \retval FLAC__bool
  88068. * \c true if the ID was successfully read, else \c false, in which
  88069. * case you should check FLAC__metadata_simple_iterator_status() to
  88070. * find out why. If the status is
  88071. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  88072. * current metadata block is not an \c APPLICATION block. Otherwise
  88073. * if the status is
  88074. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  88075. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  88076. * occurred and the iterator can no longer be used.
  88077. */
  88078. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  88079. /** Get the metadata block at the current position. You can modify the
  88080. * block but must use FLAC__metadata_simple_iterator_set_block() to
  88081. * write it back to the FLAC file.
  88082. *
  88083. * You must call FLAC__metadata_object_delete() on the returned object
  88084. * when you are finished with it.
  88085. *
  88086. * \param iterator A pointer to an existing initialized iterator.
  88087. * \assert
  88088. * \code iterator != NULL \endcode
  88089. * \a iterator has been successfully initialized with
  88090. * FLAC__metadata_simple_iterator_init()
  88091. * \retval FLAC__StreamMetadata*
  88092. * The current metadata block, or \c NULL if there was a memory
  88093. * allocation error.
  88094. */
  88095. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  88096. /** Write a block back to the FLAC file. This function tries to be
  88097. * as efficient as possible; how the block is actually written is
  88098. * shown by the following:
  88099. *
  88100. * Existing block is a STREAMINFO block and the new block is a
  88101. * STREAMINFO block: the new block is written in place. Make sure
  88102. * you know what you're doing when changing the values of a
  88103. * STREAMINFO block.
  88104. *
  88105. * Existing block is a STREAMINFO block and the new block is a
  88106. * not a STREAMINFO block: this is an error since the first block
  88107. * must be a STREAMINFO block. Returns \c false without altering the
  88108. * file.
  88109. *
  88110. * Existing block is not a STREAMINFO block and the new block is a
  88111. * STREAMINFO block: this is an error since there may be only one
  88112. * STREAMINFO block. Returns \c false without altering the file.
  88113. *
  88114. * Existing block and new block are the same length: the existing
  88115. * block will be replaced by the new block, written in place.
  88116. *
  88117. * Existing block is longer than new block: if use_padding is \c true,
  88118. * the existing block will be overwritten in place with the new
  88119. * block followed by a PADDING block, if possible, to make the total
  88120. * size the same as the existing block. Remember that a padding
  88121. * block requires at least four bytes so if the difference in size
  88122. * between the new block and existing block is less than that, the
  88123. * entire file will have to be rewritten, using the new block's
  88124. * exact size. If use_padding is \c false, the entire file will be
  88125. * rewritten, replacing the existing block by the new block.
  88126. *
  88127. * Existing block is shorter than new block: if use_padding is \c true,
  88128. * the function will try and expand the new block into the following
  88129. * PADDING block, if it exists and doing so won't shrink the PADDING
  88130. * block to less than 4 bytes. If there is no following PADDING
  88131. * block, or it will shrink to less than 4 bytes, or use_padding is
  88132. * \c false, the entire file is rewritten, replacing the existing block
  88133. * with the new block. Note that in this case any following PADDING
  88134. * block is preserved as is.
  88135. *
  88136. * After writing the block, the iterator will remain in the same
  88137. * place, i.e. pointing to the new block.
  88138. *
  88139. * \param iterator A pointer to an existing initialized iterator.
  88140. * \param block The block to set.
  88141. * \param use_padding See above.
  88142. * \assert
  88143. * \code iterator != NULL \endcode
  88144. * \a iterator has been successfully initialized with
  88145. * FLAC__metadata_simple_iterator_init()
  88146. * \code block != NULL \endcode
  88147. * \retval FLAC__bool
  88148. * \c true if successful, else \c false.
  88149. */
  88150. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88151. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  88152. * except that instead of writing over an existing block, it appends
  88153. * a block after the existing block. \a use_padding is again used to
  88154. * tell the function to try an expand into following padding in an
  88155. * attempt to avoid rewriting the entire file.
  88156. *
  88157. * This function will fail and return \c false if given a STREAMINFO
  88158. * block.
  88159. *
  88160. * After writing the block, the iterator will be pointing to the
  88161. * new block.
  88162. *
  88163. * \param iterator A pointer to an existing initialized iterator.
  88164. * \param block The block to set.
  88165. * \param use_padding See above.
  88166. * \assert
  88167. * \code iterator != NULL \endcode
  88168. * \a iterator has been successfully initialized with
  88169. * FLAC__metadata_simple_iterator_init()
  88170. * \code block != NULL \endcode
  88171. * \retval FLAC__bool
  88172. * \c true if successful, else \c false.
  88173. */
  88174. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  88175. /** Deletes the block at the current position. This will cause the
  88176. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  88177. * in which case the block will be replaced by an equal-sized PADDING
  88178. * block. The iterator will be left pointing to the block before the
  88179. * one just deleted.
  88180. *
  88181. * You may not delete the STREAMINFO block.
  88182. *
  88183. * \param iterator A pointer to an existing initialized iterator.
  88184. * \param use_padding See above.
  88185. * \assert
  88186. * \code iterator != NULL \endcode
  88187. * \a iterator has been successfully initialized with
  88188. * FLAC__metadata_simple_iterator_init()
  88189. * \retval FLAC__bool
  88190. * \c true if successful, else \c false.
  88191. */
  88192. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  88193. /* \} */
  88194. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  88195. * \ingroup flac_metadata
  88196. *
  88197. * \brief
  88198. * The level 2 interface provides read-write access to FLAC file metadata;
  88199. * all metadata is read into memory, operated on in memory, and then written
  88200. * to file, which is more efficient than level 1 when editing multiple blocks.
  88201. *
  88202. * Currently Ogg FLAC is supported for read only, via
  88203. * FLAC__metadata_chain_read_ogg() but a subsequent
  88204. * FLAC__metadata_chain_write() will fail.
  88205. *
  88206. * The general usage of this interface is:
  88207. *
  88208. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  88209. * linked list of FLAC metadata blocks.
  88210. * - Read all metadata into the the chain from a FLAC file using
  88211. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  88212. * check the status.
  88213. * - Optionally, consolidate the padding using
  88214. * FLAC__metadata_chain_merge_padding() or
  88215. * FLAC__metadata_chain_sort_padding().
  88216. * - Create a new iterator using FLAC__metadata_iterator_new()
  88217. * - Initialize the iterator to point to the first element in the chain
  88218. * using FLAC__metadata_iterator_init()
  88219. * - Traverse the chain using FLAC__metadata_iterator_next and
  88220. * FLAC__metadata_iterator_prev().
  88221. * - Get a block for reading or modification using
  88222. * FLAC__metadata_iterator_get_block(). The pointer to the object
  88223. * inside the chain is returned, so the block is yours to modify.
  88224. * Changes will be reflected in the FLAC file when you write the
  88225. * chain. You can also add and delete blocks (see functions below).
  88226. * - When done, write out the chain using FLAC__metadata_chain_write().
  88227. * Make sure to read the whole comment to the function below.
  88228. * - Delete the chain using FLAC__metadata_chain_delete().
  88229. *
  88230. * \note
  88231. * Even though the FLAC file is not open while the chain is being
  88232. * manipulated, you must not alter the file externally during
  88233. * this time. The chain assumes the FLAC file will not change
  88234. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  88235. * and FLAC__metadata_chain_write().
  88236. *
  88237. * \note
  88238. * Do not modify the is_last, length, or type fields of returned
  88239. * FLAC__StreamMetadata objects. These are managed automatically.
  88240. *
  88241. * \note
  88242. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  88243. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  88244. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  88245. * become owned by the chain and they will be deleted when the chain is
  88246. * deleted.
  88247. *
  88248. * \{
  88249. */
  88250. struct FLAC__Metadata_Chain;
  88251. /** The opaque structure definition for the level 2 chain type.
  88252. */
  88253. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  88254. struct FLAC__Metadata_Iterator;
  88255. /** The opaque structure definition for the level 2 iterator type.
  88256. */
  88257. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  88258. typedef enum {
  88259. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  88260. /**< The chain is in the normal OK state */
  88261. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  88262. /**< The data passed into a function violated the function's usage criteria */
  88263. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  88264. /**< The chain could not open the target file */
  88265. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  88266. /**< The chain could not find the FLAC signature at the start of the file */
  88267. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  88268. /**< The chain tried to write to a file that was not writable */
  88269. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  88270. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  88271. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  88272. /**< The chain encountered an error while reading the FLAC file */
  88273. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  88274. /**< The chain encountered an error while seeking in the FLAC file */
  88275. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  88276. /**< The chain encountered an error while writing the FLAC file */
  88277. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  88278. /**< The chain encountered an error renaming the FLAC file */
  88279. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  88280. /**< The chain encountered an error removing the temporary file */
  88281. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  88282. /**< Memory allocation failed */
  88283. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  88284. /**< The caller violated an assertion or an unexpected error occurred */
  88285. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  88286. /**< One or more of the required callbacks was NULL */
  88287. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  88288. /**< FLAC__metadata_chain_write() was called on a chain read by
  88289. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88290. * or
  88291. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  88292. * was called on a chain read by
  88293. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88294. * Matching read/write methods must always be used. */
  88295. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  88296. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  88297. * chain write requires a tempfile; use
  88298. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  88299. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  88300. * called when the chain write does not require a tempfile; use
  88301. * FLAC__metadata_chain_write_with_callbacks() instead.
  88302. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  88303. * before writing via callbacks. */
  88304. } FLAC__Metadata_ChainStatus;
  88305. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  88306. *
  88307. * Using a FLAC__Metadata_ChainStatus as the index to this array
  88308. * will give the string equivalent. The contents should not be modified.
  88309. */
  88310. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  88311. /*********** FLAC__Metadata_Chain ***********/
  88312. /** Create a new chain instance.
  88313. *
  88314. * \retval FLAC__Metadata_Chain*
  88315. * \c NULL if there was an error allocating memory, else the new instance.
  88316. */
  88317. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  88318. /** Free a chain instance. Deletes the object pointed to by \a chain.
  88319. *
  88320. * \param chain A pointer to an existing chain.
  88321. * \assert
  88322. * \code chain != NULL \endcode
  88323. */
  88324. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  88325. /** Get the current status of the chain. Call this after a function
  88326. * returns \c false to get the reason for the error. Also resets the
  88327. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  88328. *
  88329. * \param chain A pointer to an existing chain.
  88330. * \assert
  88331. * \code chain != NULL \endcode
  88332. * \retval FLAC__Metadata_ChainStatus
  88333. * The current status of the chain.
  88334. */
  88335. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  88336. /** Read all metadata from a FLAC file into the chain.
  88337. *
  88338. * \param chain A pointer to an existing chain.
  88339. * \param filename The path to the FLAC file to read.
  88340. * \assert
  88341. * \code chain != NULL \endcode
  88342. * \code filename != NULL \endcode
  88343. * \retval FLAC__bool
  88344. * \c true if a valid list of metadata blocks was read from
  88345. * \a filename, else \c false. On failure, check the status with
  88346. * FLAC__metadata_chain_status().
  88347. */
  88348. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  88349. /** Read all metadata from an Ogg FLAC file into the chain.
  88350. *
  88351. * \note Ogg FLAC metadata data writing is not supported yet and
  88352. * FLAC__metadata_chain_write() will fail.
  88353. *
  88354. * \param chain A pointer to an existing chain.
  88355. * \param filename The path to the Ogg FLAC file to read.
  88356. * \assert
  88357. * \code chain != NULL \endcode
  88358. * \code filename != NULL \endcode
  88359. * \retval FLAC__bool
  88360. * \c true if a valid list of metadata blocks was read from
  88361. * \a filename, else \c false. On failure, check the status with
  88362. * FLAC__metadata_chain_status().
  88363. */
  88364. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  88365. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  88366. *
  88367. * The \a handle need only be open for reading, but must be seekable.
  88368. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88369. * for Windows).
  88370. *
  88371. * \param chain A pointer to an existing chain.
  88372. * \param handle The I/O handle of the FLAC stream to read. The
  88373. * handle will NOT be closed after the metadata is read;
  88374. * that is the duty of the caller.
  88375. * \param callbacks
  88376. * A set of callbacks to use for I/O. The mandatory
  88377. * callbacks are \a read, \a seek, and \a tell.
  88378. * \assert
  88379. * \code chain != NULL \endcode
  88380. * \retval FLAC__bool
  88381. * \c true if a valid list of metadata blocks was read from
  88382. * \a handle, else \c false. On failure, check the status with
  88383. * FLAC__metadata_chain_status().
  88384. */
  88385. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88386. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  88387. *
  88388. * The \a handle need only be open for reading, but must be seekable.
  88389. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88390. * for Windows).
  88391. *
  88392. * \note Ogg FLAC metadata data writing is not supported yet and
  88393. * FLAC__metadata_chain_write() will fail.
  88394. *
  88395. * \param chain A pointer to an existing chain.
  88396. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  88397. * handle will NOT be closed after the metadata is read;
  88398. * that is the duty of the caller.
  88399. * \param callbacks
  88400. * A set of callbacks to use for I/O. The mandatory
  88401. * callbacks are \a read, \a seek, and \a tell.
  88402. * \assert
  88403. * \code chain != NULL \endcode
  88404. * \retval FLAC__bool
  88405. * \c true if a valid list of metadata blocks was read from
  88406. * \a handle, else \c false. On failure, check the status with
  88407. * FLAC__metadata_chain_status().
  88408. */
  88409. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88410. /** Checks if writing the given chain would require the use of a
  88411. * temporary file, or if it could be written in place.
  88412. *
  88413. * Under certain conditions, padding can be utilized so that writing
  88414. * edited metadata back to the FLAC file does not require rewriting the
  88415. * entire file. If rewriting is required, then a temporary workfile is
  88416. * required. When writing metadata using callbacks, you must check
  88417. * this function to know whether to call
  88418. * FLAC__metadata_chain_write_with_callbacks() or
  88419. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  88420. * writing with FLAC__metadata_chain_write(), the temporary file is
  88421. * handled internally.
  88422. *
  88423. * \param chain A pointer to an existing chain.
  88424. * \param use_padding
  88425. * Whether or not padding will be allowed to be used
  88426. * during the write. The value of \a use_padding given
  88427. * here must match the value later passed to
  88428. * FLAC__metadata_chain_write_with_callbacks() or
  88429. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  88430. * \assert
  88431. * \code chain != NULL \endcode
  88432. * \retval FLAC__bool
  88433. * \c true if writing the current chain would require a tempfile, or
  88434. * \c false if metadata can be written in place.
  88435. */
  88436. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  88437. /** Write all metadata out to the FLAC file. This function tries to be as
  88438. * efficient as possible; how the metadata is actually written is shown by
  88439. * the following:
  88440. *
  88441. * If the current chain is the same size as the existing metadata, the new
  88442. * data is written in place.
  88443. *
  88444. * If the current chain is longer than the existing metadata, and
  88445. * \a use_padding is \c true, and the last block is a PADDING block of
  88446. * sufficient length, the function will truncate the final padding block
  88447. * so that the overall size of the metadata is the same as the existing
  88448. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  88449. * the above conditions are met, the entire FLAC file must be rewritten.
  88450. * If you want to use padding this way it is a good idea to call
  88451. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  88452. * amount of padding to work with, unless you need to preserve ordering
  88453. * of the PADDING blocks for some reason.
  88454. *
  88455. * If the current chain is shorter than the existing metadata, and
  88456. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  88457. * is extended to make the overall size the same as the existing data. If
  88458. * \a use_padding is \c true and the last block is not a PADDING block, a new
  88459. * PADDING block is added to the end of the new data to make it the same
  88460. * size as the existing data (if possible, see the note to
  88461. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  88462. * and the new data is written in place. If none of the above apply or
  88463. * \a use_padding is \c false, the entire FLAC file is rewritten.
  88464. *
  88465. * If \a preserve_file_stats is \c true, the owner and modification time will
  88466. * be preserved even if the FLAC file is written.
  88467. *
  88468. * For this write function to be used, the chain must have been read with
  88469. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  88470. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  88471. *
  88472. * \param chain A pointer to an existing chain.
  88473. * \param use_padding See above.
  88474. * \param preserve_file_stats See above.
  88475. * \assert
  88476. * \code chain != NULL \endcode
  88477. * \retval FLAC__bool
  88478. * \c true if the write succeeded, else \c false. On failure,
  88479. * check the status with FLAC__metadata_chain_status().
  88480. */
  88481. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  88482. /** Write all metadata out to a FLAC stream via callbacks.
  88483. *
  88484. * (See FLAC__metadata_chain_write() for the details on how padding is
  88485. * used to write metadata in place if possible.)
  88486. *
  88487. * The \a handle must be open for updating and be seekable. The
  88488. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  88489. * for Windows).
  88490. *
  88491. * For this write function to be used, the chain must have been read with
  88492. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88493. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88494. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88495. * \c false.
  88496. *
  88497. * \param chain A pointer to an existing chain.
  88498. * \param use_padding See FLAC__metadata_chain_write()
  88499. * \param handle The I/O handle of the FLAC stream to write. The
  88500. * handle will NOT be closed after the metadata is
  88501. * written; that is the duty of the caller.
  88502. * \param callbacks A set of callbacks to use for I/O. The mandatory
  88503. * callbacks are \a write and \a seek.
  88504. * \assert
  88505. * \code chain != NULL \endcode
  88506. * \retval FLAC__bool
  88507. * \c true if the write succeeded, else \c false. On failure,
  88508. * check the status with FLAC__metadata_chain_status().
  88509. */
  88510. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  88511. /** Write all metadata out to a FLAC stream via callbacks.
  88512. *
  88513. * (See FLAC__metadata_chain_write() for the details on how padding is
  88514. * used to write metadata in place if possible.)
  88515. *
  88516. * This version of the write-with-callbacks function must be used when
  88517. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  88518. * this function, you must supply an I/O handle corresponding to the
  88519. * FLAC file to edit, and a temporary handle to which the new FLAC
  88520. * file will be written. It is the caller's job to move this temporary
  88521. * FLAC file on top of the original FLAC file to complete the metadata
  88522. * edit.
  88523. *
  88524. * The \a handle must be open for reading and be seekable. The
  88525. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  88526. * for Windows).
  88527. *
  88528. * The \a temp_handle must be open for writing. The
  88529. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  88530. * for Windows). It should be an empty stream, or at least positioned
  88531. * at the start-of-file (in which case it is the caller's duty to
  88532. * truncate it on return).
  88533. *
  88534. * For this write function to be used, the chain must have been read with
  88535. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  88536. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  88537. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  88538. * \c true.
  88539. *
  88540. * \param chain A pointer to an existing chain.
  88541. * \param use_padding See FLAC__metadata_chain_write()
  88542. * \param handle The I/O handle of the original FLAC stream to read.
  88543. * The handle will NOT be closed after the metadata is
  88544. * written; that is the duty of the caller.
  88545. * \param callbacks A set of callbacks to use for I/O on \a handle.
  88546. * The mandatory callbacks are \a read, \a seek, and
  88547. * \a eof.
  88548. * \param temp_handle The I/O handle of the FLAC stream to write. The
  88549. * handle will NOT be closed after the metadata is
  88550. * written; that is the duty of the caller.
  88551. * \param temp_callbacks
  88552. * A set of callbacks to use for I/O on temp_handle.
  88553. * The only mandatory callback is \a write.
  88554. * \assert
  88555. * \code chain != NULL \endcode
  88556. * \retval FLAC__bool
  88557. * \c true if the write succeeded, else \c false. On failure,
  88558. * check the status with FLAC__metadata_chain_status().
  88559. */
  88560. 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);
  88561. /** Merge adjacent PADDING blocks into a single block.
  88562. *
  88563. * \note This function does not write to the FLAC file, it only
  88564. * modifies the chain.
  88565. *
  88566. * \warning Any iterator on the current chain will become invalid after this
  88567. * call. You should delete the iterator and get a new one.
  88568. *
  88569. * \param chain A pointer to an existing chain.
  88570. * \assert
  88571. * \code chain != NULL \endcode
  88572. */
  88573. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  88574. /** This function will move all PADDING blocks to the end on the metadata,
  88575. * then merge them into a single block.
  88576. *
  88577. * \note This function does not write to the FLAC file, it only
  88578. * modifies the chain.
  88579. *
  88580. * \warning Any iterator on the current chain will become invalid after this
  88581. * call. You should delete the iterator and get a new one.
  88582. *
  88583. * \param chain A pointer to an existing chain.
  88584. * \assert
  88585. * \code chain != NULL \endcode
  88586. */
  88587. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  88588. /*********** FLAC__Metadata_Iterator ***********/
  88589. /** Create a new iterator instance.
  88590. *
  88591. * \retval FLAC__Metadata_Iterator*
  88592. * \c NULL if there was an error allocating memory, else the new instance.
  88593. */
  88594. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  88595. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  88596. *
  88597. * \param iterator A pointer to an existing iterator.
  88598. * \assert
  88599. * \code iterator != NULL \endcode
  88600. */
  88601. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  88602. /** Initialize the iterator to point to the first metadata block in the
  88603. * given chain.
  88604. *
  88605. * \param iterator A pointer to an existing iterator.
  88606. * \param chain A pointer to an existing and initialized (read) chain.
  88607. * \assert
  88608. * \code iterator != NULL \endcode
  88609. * \code chain != NULL \endcode
  88610. */
  88611. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  88612. /** Moves the iterator forward one metadata block, returning \c false if
  88613. * already at the end.
  88614. *
  88615. * \param iterator A pointer to an existing initialized iterator.
  88616. * \assert
  88617. * \code iterator != NULL \endcode
  88618. * \a iterator has been successfully initialized with
  88619. * FLAC__metadata_iterator_init()
  88620. * \retval FLAC__bool
  88621. * \c false if already at the last metadata block of the chain, else
  88622. * \c true.
  88623. */
  88624. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  88625. /** Moves the iterator backward one metadata block, returning \c false if
  88626. * already at the beginning.
  88627. *
  88628. * \param iterator A pointer to an existing initialized iterator.
  88629. * \assert
  88630. * \code iterator != NULL \endcode
  88631. * \a iterator has been successfully initialized with
  88632. * FLAC__metadata_iterator_init()
  88633. * \retval FLAC__bool
  88634. * \c false if already at the first metadata block of the chain, else
  88635. * \c true.
  88636. */
  88637. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  88638. /** Get the type of the metadata block at the current position.
  88639. *
  88640. * \param iterator A pointer to an existing initialized iterator.
  88641. * \assert
  88642. * \code iterator != NULL \endcode
  88643. * \a iterator has been successfully initialized with
  88644. * FLAC__metadata_iterator_init()
  88645. * \retval FLAC__MetadataType
  88646. * The type of the metadata block at the current iterator position.
  88647. */
  88648. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  88649. /** Get the metadata block at the current position. You can modify
  88650. * the block in place but must write the chain before the changes
  88651. * are reflected to the FLAC file. You do not need to call
  88652. * FLAC__metadata_iterator_set_block() to reflect the changes;
  88653. * the pointer returned by FLAC__metadata_iterator_get_block()
  88654. * points directly into the chain.
  88655. *
  88656. * \warning
  88657. * Do not call FLAC__metadata_object_delete() on the returned object;
  88658. * to delete a block use FLAC__metadata_iterator_delete_block().
  88659. *
  88660. * \param iterator A pointer to an existing initialized iterator.
  88661. * \assert
  88662. * \code iterator != NULL \endcode
  88663. * \a iterator has been successfully initialized with
  88664. * FLAC__metadata_iterator_init()
  88665. * \retval FLAC__StreamMetadata*
  88666. * The current metadata block.
  88667. */
  88668. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  88669. /** Set the metadata block at the current position, replacing the existing
  88670. * block. The new block passed in becomes owned by the chain and it will be
  88671. * deleted when the chain is deleted.
  88672. *
  88673. * \param iterator A pointer to an existing initialized iterator.
  88674. * \param block A pointer to a metadata block.
  88675. * \assert
  88676. * \code iterator != NULL \endcode
  88677. * \a iterator has been successfully initialized with
  88678. * FLAC__metadata_iterator_init()
  88679. * \code block != NULL \endcode
  88680. * \retval FLAC__bool
  88681. * \c false if the conditions in the above description are not met, or
  88682. * a memory allocation error occurs, otherwise \c true.
  88683. */
  88684. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88685. /** Removes the current block from the chain. If \a replace_with_padding is
  88686. * \c true, the block will instead be replaced with a padding block of equal
  88687. * size. You can not delete the STREAMINFO block. The iterator will be
  88688. * left pointing to the block before the one just "deleted", even if
  88689. * \a replace_with_padding is \c true.
  88690. *
  88691. * \param iterator A pointer to an existing initialized iterator.
  88692. * \param replace_with_padding See above.
  88693. * \assert
  88694. * \code iterator != NULL \endcode
  88695. * \a iterator has been successfully initialized with
  88696. * FLAC__metadata_iterator_init()
  88697. * \retval FLAC__bool
  88698. * \c false if the conditions in the above description are not met,
  88699. * otherwise \c true.
  88700. */
  88701. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  88702. /** Insert a new block before the current block. You cannot insert a block
  88703. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  88704. * as there can be only one, the one that already exists at the head when you
  88705. * read in a chain. The chain takes ownership of the new block and it will be
  88706. * deleted when the chain is deleted. The iterator will be left pointing to
  88707. * the new block.
  88708. *
  88709. * \param iterator A pointer to an existing initialized iterator.
  88710. * \param block A pointer to a metadata block to insert.
  88711. * \assert
  88712. * \code iterator != NULL \endcode
  88713. * \a iterator has been successfully initialized with
  88714. * FLAC__metadata_iterator_init()
  88715. * \retval FLAC__bool
  88716. * \c false if the conditions in the above description are not met, or
  88717. * a memory allocation error occurs, otherwise \c true.
  88718. */
  88719. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88720. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  88721. * block as there can be only one, the one that already exists at the head when
  88722. * you read in a chain. The chain takes ownership of the new block and it will
  88723. * be deleted when the chain is deleted. The iterator will be left pointing to
  88724. * the new block.
  88725. *
  88726. * \param iterator A pointer to an existing initialized iterator.
  88727. * \param block A pointer to a metadata block to insert.
  88728. * \assert
  88729. * \code iterator != NULL \endcode
  88730. * \a iterator has been successfully initialized with
  88731. * FLAC__metadata_iterator_init()
  88732. * \retval FLAC__bool
  88733. * \c false if the conditions in the above description are not met, or
  88734. * a memory allocation error occurs, otherwise \c true.
  88735. */
  88736. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  88737. /* \} */
  88738. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  88739. * \ingroup flac_metadata
  88740. *
  88741. * \brief
  88742. * This module contains methods for manipulating FLAC metadata objects.
  88743. *
  88744. * Since many are variable length we have to be careful about the memory
  88745. * management. We decree that all pointers to data in the object are
  88746. * owned by the object and memory-managed by the object.
  88747. *
  88748. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  88749. * functions to create all instances. When using the
  88750. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  88751. * \a copy to \c true to have the function make it's own copy of the data, or
  88752. * to \c false to give the object ownership of your data. In the latter case
  88753. * your pointer must be freeable by free() and will be free()d when the object
  88754. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  88755. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  88756. * the length argument is 0 and the \a copy argument is \c false.
  88757. *
  88758. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  88759. * will return \c NULL in the case of a memory allocation error, otherwise a new
  88760. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  88761. * case of a memory allocation error.
  88762. *
  88763. * We don't have the convenience of C++ here, so note that the library relies
  88764. * on you to keep the types straight. In other words, if you pass, for
  88765. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  88766. * FLAC__metadata_object_application_set_data(), you will get an assertion
  88767. * failure.
  88768. *
  88769. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  88770. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  88771. * toward the length or stored in the stream, but it can make working with plain
  88772. * comments (those that don't contain embedded-NULs in the value) easier.
  88773. * Entries passed into these functions have trailing NULs added if missing, and
  88774. * returned entries are guaranteed to have a trailing NUL.
  88775. *
  88776. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  88777. * comment entry/name/value will first validate that it complies with the Vorbis
  88778. * comment specification and return false if it does not.
  88779. *
  88780. * There is no need to recalculate the length field on metadata blocks you
  88781. * have modified. They will be calculated automatically before they are
  88782. * written back to a file.
  88783. *
  88784. * \{
  88785. */
  88786. /** Create a new metadata object instance of the given type.
  88787. *
  88788. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  88789. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  88790. * the vendor string set (but zero comments).
  88791. *
  88792. * Do not pass in a value greater than or equal to
  88793. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  88794. * doing.
  88795. *
  88796. * \param type Type of object to create
  88797. * \retval FLAC__StreamMetadata*
  88798. * \c NULL if there was an error allocating memory or the type code is
  88799. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  88800. */
  88801. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  88802. /** Create a copy of an existing metadata object.
  88803. *
  88804. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  88805. * object is also copied. The caller takes ownership of the new block and
  88806. * is responsible for freeing it with FLAC__metadata_object_delete().
  88807. *
  88808. * \param object Pointer to object to copy.
  88809. * \assert
  88810. * \code object != NULL \endcode
  88811. * \retval FLAC__StreamMetadata*
  88812. * \c NULL if there was an error allocating memory, else the new instance.
  88813. */
  88814. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  88815. /** Free a metadata object. Deletes the object pointed to by \a object.
  88816. *
  88817. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  88818. * object is also deleted.
  88819. *
  88820. * \param object A pointer to an existing object.
  88821. * \assert
  88822. * \code object != NULL \endcode
  88823. */
  88824. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  88825. /** Compares two metadata objects.
  88826. *
  88827. * The compare is "deep", i.e. dynamically allocated data within the
  88828. * object is also compared.
  88829. *
  88830. * \param block1 A pointer to an existing object.
  88831. * \param block2 A pointer to an existing object.
  88832. * \assert
  88833. * \code block1 != NULL \endcode
  88834. * \code block2 != NULL \endcode
  88835. * \retval FLAC__bool
  88836. * \c true if objects are identical, else \c false.
  88837. */
  88838. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  88839. /** Sets the application data of an APPLICATION block.
  88840. *
  88841. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  88842. * takes ownership of the pointer. The existing data will be freed if this
  88843. * function is successful, otherwise the original data will remain if \a copy
  88844. * is \c true and malloc() fails.
  88845. *
  88846. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  88847. *
  88848. * \param object A pointer to an existing APPLICATION object.
  88849. * \param data A pointer to the data to set.
  88850. * \param length The length of \a data in bytes.
  88851. * \param copy See above.
  88852. * \assert
  88853. * \code object != NULL \endcode
  88854. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  88855. * \code (data != NULL && length > 0) ||
  88856. * (data == NULL && length == 0 && copy == false) \endcode
  88857. * \retval FLAC__bool
  88858. * \c false if \a copy is \c true and malloc() fails, else \c true.
  88859. */
  88860. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  88861. /** Resize the seekpoint array.
  88862. *
  88863. * If the size shrinks, elements will truncated; if it grows, new placeholder
  88864. * points will be added to the end.
  88865. *
  88866. * \param object A pointer to an existing SEEKTABLE object.
  88867. * \param new_num_points The desired length of the array; may be \c 0.
  88868. * \assert
  88869. * \code object != NULL \endcode
  88870. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88871. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  88872. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  88873. * \retval FLAC__bool
  88874. * \c false if memory allocation error, else \c true.
  88875. */
  88876. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  88877. /** Set a seekpoint in a seektable.
  88878. *
  88879. * \param object A pointer to an existing SEEKTABLE object.
  88880. * \param point_num Index into seekpoint array to set.
  88881. * \param point The point to set.
  88882. * \assert
  88883. * \code object != NULL \endcode
  88884. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88885. * \code object->data.seek_table.num_points > point_num \endcode
  88886. */
  88887. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88888. /** Insert a seekpoint into a seektable.
  88889. *
  88890. * \param object A pointer to an existing SEEKTABLE object.
  88891. * \param point_num Index into seekpoint array to set.
  88892. * \param point The point to set.
  88893. * \assert
  88894. * \code object != NULL \endcode
  88895. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88896. * \code object->data.seek_table.num_points >= point_num \endcode
  88897. * \retval FLAC__bool
  88898. * \c false if memory allocation error, else \c true.
  88899. */
  88900. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  88901. /** Delete a seekpoint from a seektable.
  88902. *
  88903. * \param object A pointer to an existing SEEKTABLE object.
  88904. * \param point_num Index into seekpoint array to set.
  88905. * \assert
  88906. * \code object != NULL \endcode
  88907. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88908. * \code object->data.seek_table.num_points > point_num \endcode
  88909. * \retval FLAC__bool
  88910. * \c false if memory allocation error, else \c true.
  88911. */
  88912. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  88913. /** Check a seektable to see if it conforms to the FLAC specification.
  88914. * See the format specification for limits on the contents of the
  88915. * seektable.
  88916. *
  88917. * \param object A pointer to an existing SEEKTABLE object.
  88918. * \assert
  88919. * \code object != NULL \endcode
  88920. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88921. * \retval FLAC__bool
  88922. * \c false if seek table is illegal, else \c true.
  88923. */
  88924. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  88925. /** Append a number of placeholder points to the end of a seek table.
  88926. *
  88927. * \note
  88928. * As with the other ..._seektable_template_... functions, you should
  88929. * call FLAC__metadata_object_seektable_template_sort() when finished
  88930. * to make the seek table legal.
  88931. *
  88932. * \param object A pointer to an existing SEEKTABLE object.
  88933. * \param num The number of placeholder points to append.
  88934. * \assert
  88935. * \code object != NULL \endcode
  88936. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88937. * \retval FLAC__bool
  88938. * \c false if memory allocation fails, else \c true.
  88939. */
  88940. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  88941. /** Append a specific seek point template to the end of a seek table.
  88942. *
  88943. * \note
  88944. * As with the other ..._seektable_template_... functions, you should
  88945. * call FLAC__metadata_object_seektable_template_sort() when finished
  88946. * to make the seek table legal.
  88947. *
  88948. * \param object A pointer to an existing SEEKTABLE object.
  88949. * \param sample_number The sample number of the seek point template.
  88950. * \assert
  88951. * \code object != NULL \endcode
  88952. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88953. * \retval FLAC__bool
  88954. * \c false if memory allocation fails, else \c true.
  88955. */
  88956. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  88957. /** Append specific seek point templates to the end of a seek table.
  88958. *
  88959. * \note
  88960. * As with the other ..._seektable_template_... functions, you should
  88961. * call FLAC__metadata_object_seektable_template_sort() when finished
  88962. * to make the seek table legal.
  88963. *
  88964. * \param object A pointer to an existing SEEKTABLE object.
  88965. * \param sample_numbers An array of sample numbers for the seek points.
  88966. * \param num The number of seek point templates to append.
  88967. * \assert
  88968. * \code object != NULL \endcode
  88969. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88970. * \retval FLAC__bool
  88971. * \c false if memory allocation fails, else \c true.
  88972. */
  88973. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  88974. /** Append a set of evenly-spaced seek point templates to the end of a
  88975. * seek table.
  88976. *
  88977. * \note
  88978. * As with the other ..._seektable_template_... functions, you should
  88979. * call FLAC__metadata_object_seektable_template_sort() when finished
  88980. * to make the seek table legal.
  88981. *
  88982. * \param object A pointer to an existing SEEKTABLE object.
  88983. * \param num The number of placeholder points to append.
  88984. * \param total_samples The total number of samples to be encoded;
  88985. * the seekpoints will be spaced approximately
  88986. * \a total_samples / \a num samples apart.
  88987. * \assert
  88988. * \code object != NULL \endcode
  88989. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  88990. * \code total_samples > 0 \endcode
  88991. * \retval FLAC__bool
  88992. * \c false if memory allocation fails, else \c true.
  88993. */
  88994. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  88995. /** Append a set of evenly-spaced seek point templates to the end of a
  88996. * seek table.
  88997. *
  88998. * \note
  88999. * As with the other ..._seektable_template_... functions, you should
  89000. * call FLAC__metadata_object_seektable_template_sort() when finished
  89001. * to make the seek table legal.
  89002. *
  89003. * \param object A pointer to an existing SEEKTABLE object.
  89004. * \param samples The number of samples apart to space the placeholder
  89005. * points. The first point will be at sample \c 0, the
  89006. * second at sample \a samples, then 2*\a samples, and
  89007. * so on. As long as \a samples and \a total_samples
  89008. * are greater than \c 0, there will always be at least
  89009. * one seekpoint at sample \c 0.
  89010. * \param total_samples The total number of samples to be encoded;
  89011. * the seekpoints will be spaced
  89012. * \a samples samples apart.
  89013. * \assert
  89014. * \code object != NULL \endcode
  89015. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89016. * \code samples > 0 \endcode
  89017. * \code total_samples > 0 \endcode
  89018. * \retval FLAC__bool
  89019. * \c false if memory allocation fails, else \c true.
  89020. */
  89021. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  89022. /** Sort a seek table's seek points according to the format specification,
  89023. * removing duplicates.
  89024. *
  89025. * \param object A pointer to a seek table to be sorted.
  89026. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  89027. * If \c true, duplicates are deleted and the seek table is
  89028. * shrunk appropriately; the number of placeholder points
  89029. * present in the seek table will be the same after the call
  89030. * as before.
  89031. * \assert
  89032. * \code object != NULL \endcode
  89033. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  89034. * \retval FLAC__bool
  89035. * \c false if realloc() fails, else \c true.
  89036. */
  89037. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  89038. /** Sets the vendor string in a VORBIS_COMMENT block.
  89039. *
  89040. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89041. * one already.
  89042. *
  89043. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89044. * takes ownership of the \c entry.entry pointer.
  89045. *
  89046. * \note If this function returns \c false, the caller still owns the
  89047. * pointer.
  89048. *
  89049. * \param object A pointer to an existing VORBIS_COMMENT object.
  89050. * \param entry The entry to set the vendor string to.
  89051. * \param copy See above.
  89052. * \assert
  89053. * \code object != NULL \endcode
  89054. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89055. * \code (entry.entry != NULL && entry.length > 0) ||
  89056. * (entry.entry == NULL && entry.length == 0) \endcode
  89057. * \retval FLAC__bool
  89058. * \c false if memory allocation fails or \a entry does not comply with the
  89059. * Vorbis comment specification, else \c true.
  89060. */
  89061. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89062. /** Resize the comment array.
  89063. *
  89064. * If the size shrinks, elements will truncated; if it grows, new empty
  89065. * fields will be added to the end.
  89066. *
  89067. * \param object A pointer to an existing VORBIS_COMMENT object.
  89068. * \param new_num_comments The desired length of the array; may be \c 0.
  89069. * \assert
  89070. * \code object != NULL \endcode
  89071. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89072. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  89073. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  89074. * \retval FLAC__bool
  89075. * \c false if memory allocation fails, else \c true.
  89076. */
  89077. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  89078. /** Sets a comment in a VORBIS_COMMENT block.
  89079. *
  89080. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89081. * one already.
  89082. *
  89083. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89084. * takes ownership of the \c entry.entry pointer.
  89085. *
  89086. * \note If this function returns \c false, the caller still owns the
  89087. * pointer.
  89088. *
  89089. * \param object A pointer to an existing VORBIS_COMMENT object.
  89090. * \param comment_num Index into comment array to set.
  89091. * \param entry The entry to set the comment to.
  89092. * \param copy See above.
  89093. * \assert
  89094. * \code object != NULL \endcode
  89095. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89096. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  89097. * \code (entry.entry != NULL && entry.length > 0) ||
  89098. * (entry.entry == NULL && entry.length == 0) \endcode
  89099. * \retval FLAC__bool
  89100. * \c false if memory allocation fails or \a entry does not comply with the
  89101. * Vorbis comment specification, else \c true.
  89102. */
  89103. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89104. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  89105. *
  89106. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89107. * one already.
  89108. *
  89109. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89110. * takes ownership of the \c entry.entry pointer.
  89111. *
  89112. * \note If this function returns \c false, the caller still owns the
  89113. * pointer.
  89114. *
  89115. * \param object A pointer to an existing VORBIS_COMMENT object.
  89116. * \param comment_num The index at which to insert the comment. The comments
  89117. * at and after \a comment_num move right one position.
  89118. * To append a comment to the end, set \a comment_num to
  89119. * \c object->data.vorbis_comment.num_comments .
  89120. * \param entry The comment to insert.
  89121. * \param copy See above.
  89122. * \assert
  89123. * \code object != NULL \endcode
  89124. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89125. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  89126. * \code (entry.entry != NULL && entry.length > 0) ||
  89127. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89128. * \retval FLAC__bool
  89129. * \c false if memory allocation fails or \a entry does not comply with the
  89130. * Vorbis comment specification, else \c true.
  89131. */
  89132. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89133. /** Appends a comment to a VORBIS_COMMENT block.
  89134. *
  89135. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89136. * one already.
  89137. *
  89138. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89139. * takes ownership of the \c entry.entry pointer.
  89140. *
  89141. * \note If this function returns \c false, the caller still owns the
  89142. * pointer.
  89143. *
  89144. * \param object A pointer to an existing VORBIS_COMMENT object.
  89145. * \param entry The comment to insert.
  89146. * \param copy See above.
  89147. * \assert
  89148. * \code object != NULL \endcode
  89149. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89150. * \code (entry.entry != NULL && entry.length > 0) ||
  89151. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89152. * \retval FLAC__bool
  89153. * \c false if memory allocation fails or \a entry does not comply with the
  89154. * Vorbis comment specification, else \c true.
  89155. */
  89156. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  89157. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  89158. *
  89159. * For convenience, a trailing NUL is added to the entry if it doesn't have
  89160. * one already.
  89161. *
  89162. * Depending on the the value of \a all, either all or just the first comment
  89163. * whose field name(s) match the given entry's name will be replaced by the
  89164. * given entry. If no comments match, \a entry will simply be appended.
  89165. *
  89166. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  89167. * takes ownership of the \c entry.entry pointer.
  89168. *
  89169. * \note If this function returns \c false, the caller still owns the
  89170. * pointer.
  89171. *
  89172. * \param object A pointer to an existing VORBIS_COMMENT object.
  89173. * \param entry The comment to insert.
  89174. * \param all If \c true, all comments whose field name matches
  89175. * \a entry's field name will be removed, and \a entry will
  89176. * be inserted at the position of the first matching
  89177. * comment. If \c false, only the first comment whose
  89178. * field name matches \a entry's field name will be
  89179. * replaced with \a entry.
  89180. * \param copy See above.
  89181. * \assert
  89182. * \code object != NULL \endcode
  89183. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89184. * \code (entry.entry != NULL && entry.length > 0) ||
  89185. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  89186. * \retval FLAC__bool
  89187. * \c false if memory allocation fails or \a entry does not comply with the
  89188. * Vorbis comment specification, else \c true.
  89189. */
  89190. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  89191. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  89192. *
  89193. * \param object A pointer to an existing VORBIS_COMMENT object.
  89194. * \param comment_num The index of the comment to delete.
  89195. * \assert
  89196. * \code object != NULL \endcode
  89197. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89198. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  89199. * \retval FLAC__bool
  89200. * \c false if realloc() fails, else \c true.
  89201. */
  89202. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  89203. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  89204. *
  89205. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  89206. * memory and shall be owned by the caller. For convenience the entry will
  89207. * have a terminating NUL.
  89208. *
  89209. * \param entry A pointer to a Vorbis comment entry. The entry's
  89210. * \c entry pointer should not point to allocated
  89211. * memory as it will be overwritten.
  89212. * \param field_name The field name in ASCII, \c NUL terminated.
  89213. * \param field_value The field value in UTF-8, \c NUL terminated.
  89214. * \assert
  89215. * \code entry != NULL \endcode
  89216. * \code field_name != NULL \endcode
  89217. * \code field_value != NULL \endcode
  89218. * \retval FLAC__bool
  89219. * \c false if malloc() fails, or if \a field_name or \a field_value does
  89220. * not comply with the Vorbis comment specification, else \c true.
  89221. */
  89222. 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);
  89223. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  89224. *
  89225. * The returned pointers to name and value will be allocated by malloc()
  89226. * and shall be owned by the caller.
  89227. *
  89228. * \param entry An existing Vorbis comment entry.
  89229. * \param field_name The address of where the returned pointer to the
  89230. * field name will be stored.
  89231. * \param field_value The address of where the returned pointer to the
  89232. * field value will be stored.
  89233. * \assert
  89234. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89235. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  89236. * \code field_name != NULL \endcode
  89237. * \code field_value != NULL \endcode
  89238. * \retval FLAC__bool
  89239. * \c false if memory allocation fails or \a entry does not comply with the
  89240. * Vorbis comment specification, else \c true.
  89241. */
  89242. 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);
  89243. /** Check if the given Vorbis comment entry's field name matches the given
  89244. * field name.
  89245. *
  89246. * \param entry An existing Vorbis comment entry.
  89247. * \param field_name The field name to check.
  89248. * \param field_name_length The length of \a field_name, not including the
  89249. * terminating \c NUL.
  89250. * \assert
  89251. * \code (entry.entry != NULL && entry.length > 0) \endcode
  89252. * \retval FLAC__bool
  89253. * \c true if the field names match, else \c false
  89254. */
  89255. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  89256. /** Find a Vorbis comment with the given field name.
  89257. *
  89258. * The search begins at entry number \a offset; use an offset of 0 to
  89259. * search from the beginning of the comment array.
  89260. *
  89261. * \param object A pointer to an existing VORBIS_COMMENT object.
  89262. * \param offset The offset into the comment array from where to start
  89263. * the search.
  89264. * \param field_name The field name of the comment to find.
  89265. * \assert
  89266. * \code object != NULL \endcode
  89267. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89268. * \code field_name != NULL \endcode
  89269. * \retval int
  89270. * The offset in the comment array of the first comment whose field
  89271. * name matches \a field_name, or \c -1 if no match was found.
  89272. */
  89273. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  89274. /** Remove first Vorbis comment matching the given field name.
  89275. *
  89276. * \param object A pointer to an existing VORBIS_COMMENT object.
  89277. * \param field_name The field name of comment to delete.
  89278. * \assert
  89279. * \code object != NULL \endcode
  89280. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89281. * \retval int
  89282. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89283. * \c 1 for one matching entry deleted.
  89284. */
  89285. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  89286. /** Remove all Vorbis comments matching the given field name.
  89287. *
  89288. * \param object A pointer to an existing VORBIS_COMMENT object.
  89289. * \param field_name The field name of comments to delete.
  89290. * \assert
  89291. * \code object != NULL \endcode
  89292. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  89293. * \retval int
  89294. * \c -1 for memory allocation error, \c 0 for no matching entries,
  89295. * else the number of matching entries deleted.
  89296. */
  89297. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  89298. /** Create a new CUESHEET track instance.
  89299. *
  89300. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  89301. *
  89302. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89303. * \c NULL if there was an error allocating memory, else the new instance.
  89304. */
  89305. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  89306. /** Create a copy of an existing CUESHEET track object.
  89307. *
  89308. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  89309. * object is also copied. The caller takes ownership of the new object and
  89310. * is responsible for freeing it with
  89311. * FLAC__metadata_object_cuesheet_track_delete().
  89312. *
  89313. * \param object Pointer to object to copy.
  89314. * \assert
  89315. * \code object != NULL \endcode
  89316. * \retval FLAC__StreamMetadata_CueSheet_Track*
  89317. * \c NULL if there was an error allocating memory, else the new instance.
  89318. */
  89319. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  89320. /** Delete a CUESHEET track object
  89321. *
  89322. * \param object A pointer to an existing CUESHEET track object.
  89323. * \assert
  89324. * \code object != NULL \endcode
  89325. */
  89326. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  89327. /** Resize a track's index point array.
  89328. *
  89329. * If the size shrinks, elements will truncated; if it grows, new blank
  89330. * indices will be added to the end.
  89331. *
  89332. * \param object A pointer to an existing CUESHEET object.
  89333. * \param track_num The index of the track to modify. NOTE: this is not
  89334. * necessarily the same as the track's \a number field.
  89335. * \param new_num_indices The desired length of the array; may be \c 0.
  89336. * \assert
  89337. * \code object != NULL \endcode
  89338. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89339. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89340. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  89341. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  89342. * \retval FLAC__bool
  89343. * \c false if memory allocation error, else \c true.
  89344. */
  89345. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  89346. /** Insert an index point in a CUESHEET track at the given index.
  89347. *
  89348. * \param object A pointer to an existing CUESHEET object.
  89349. * \param track_num The index of the track to modify. NOTE: this is not
  89350. * necessarily the same as the track's \a number field.
  89351. * \param index_num The index into the track's index array at which to
  89352. * insert the index point. NOTE: this is not necessarily
  89353. * the same as the index point's \a number field. The
  89354. * indices at and after \a index_num move right one
  89355. * position. To append an index point to the end, set
  89356. * \a index_num to
  89357. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89358. * \param index The index point to insert.
  89359. * \assert
  89360. * \code object != NULL \endcode
  89361. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89362. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89363. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89364. * \retval FLAC__bool
  89365. * \c false if realloc() fails, else \c true.
  89366. */
  89367. 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);
  89368. /** Insert a blank index point in a CUESHEET track at the given index.
  89369. *
  89370. * A blank index point is one in which all field values are zero.
  89371. *
  89372. * \param object A pointer to an existing CUESHEET object.
  89373. * \param track_num The index of the track to modify. NOTE: this is not
  89374. * necessarily the same as the track's \a number field.
  89375. * \param index_num The index into the track's index array at which to
  89376. * insert the index point. NOTE: this is not necessarily
  89377. * the same as the index point's \a number field. The
  89378. * indices at and after \a index_num move right one
  89379. * position. To append an index point to the end, set
  89380. * \a index_num to
  89381. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  89382. * \assert
  89383. * \code object != NULL \endcode
  89384. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89385. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89386. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  89387. * \retval FLAC__bool
  89388. * \c false if realloc() fails, else \c true.
  89389. */
  89390. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89391. /** Delete an index point in a CUESHEET track at the given index.
  89392. *
  89393. * \param object A pointer to an existing CUESHEET object.
  89394. * \param track_num The index into the track array of the track to
  89395. * modify. NOTE: this is not necessarily the same
  89396. * as the track's \a number field.
  89397. * \param index_num The index into the track's index array of the index
  89398. * to delete. NOTE: this is not necessarily the same
  89399. * as the index's \a number field.
  89400. * \assert
  89401. * \code object != NULL \endcode
  89402. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89403. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89404. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  89405. * \retval FLAC__bool
  89406. * \c false if realloc() fails, else \c true.
  89407. */
  89408. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  89409. /** Resize the track array.
  89410. *
  89411. * If the size shrinks, elements will truncated; if it grows, new blank
  89412. * tracks will be added to the end.
  89413. *
  89414. * \param object A pointer to an existing CUESHEET object.
  89415. * \param new_num_tracks The desired length of the array; may be \c 0.
  89416. * \assert
  89417. * \code object != NULL \endcode
  89418. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89419. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  89420. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  89421. * \retval FLAC__bool
  89422. * \c false if memory allocation error, else \c true.
  89423. */
  89424. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  89425. /** Sets a track in a CUESHEET block.
  89426. *
  89427. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89428. * takes ownership of the \a track pointer.
  89429. *
  89430. * \param object A pointer to an existing CUESHEET object.
  89431. * \param track_num Index into track array to set. NOTE: this is not
  89432. * necessarily the same as the track's \a number field.
  89433. * \param track The track to set the track to. You may safely pass in
  89434. * a const pointer if \a copy is \c true.
  89435. * \param copy See above.
  89436. * \assert
  89437. * \code object != NULL \endcode
  89438. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89439. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  89440. * \code (track->indices != NULL && track->num_indices > 0) ||
  89441. * (track->indices == NULL && track->num_indices == 0)
  89442. * \retval FLAC__bool
  89443. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89444. */
  89445. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89446. /** Insert a track in a CUESHEET block at the given index.
  89447. *
  89448. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  89449. * takes ownership of the \a track pointer.
  89450. *
  89451. * \param object A pointer to an existing CUESHEET object.
  89452. * \param track_num The index at which to insert the track. NOTE: this
  89453. * is not necessarily the same as the track's \a number
  89454. * field. The tracks at and after \a track_num move right
  89455. * one position. To append a track to the end, set
  89456. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89457. * \param track The track to insert. You may safely pass in a const
  89458. * pointer if \a copy is \c true.
  89459. * \param copy See above.
  89460. * \assert
  89461. * \code object != NULL \endcode
  89462. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89463. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89464. * \retval FLAC__bool
  89465. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89466. */
  89467. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  89468. /** Insert a blank track in a CUESHEET block at the given index.
  89469. *
  89470. * A blank track is one in which all field values are zero.
  89471. *
  89472. * \param object A pointer to an existing CUESHEET object.
  89473. * \param track_num The index at which to insert the track. NOTE: this
  89474. * is not necessarily the same as the track's \a number
  89475. * field. The tracks at and after \a track_num move right
  89476. * one position. To append a track to the end, set
  89477. * \a track_num to \c object->data.cue_sheet.num_tracks .
  89478. * \assert
  89479. * \code object != NULL \endcode
  89480. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89481. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  89482. * \retval FLAC__bool
  89483. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89484. */
  89485. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  89486. /** Delete a track in a CUESHEET block at the given index.
  89487. *
  89488. * \param object A pointer to an existing CUESHEET object.
  89489. * \param track_num The index into the track array of the track to
  89490. * delete. NOTE: this is not necessarily the same
  89491. * as the track's \a number field.
  89492. * \assert
  89493. * \code object != NULL \endcode
  89494. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89495. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  89496. * \retval FLAC__bool
  89497. * \c false if realloc() fails, else \c true.
  89498. */
  89499. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  89500. /** Check a cue sheet to see if it conforms to the FLAC specification.
  89501. * See the format specification for limits on the contents of the
  89502. * cue sheet.
  89503. *
  89504. * \param object A pointer to an existing CUESHEET object.
  89505. * \param check_cd_da_subset If \c true, check CUESHEET against more
  89506. * stringent requirements for a CD-DA (audio) disc.
  89507. * \param violation Address of a pointer to a string. If there is a
  89508. * violation, a pointer to a string explanation of the
  89509. * violation will be returned here. \a violation may be
  89510. * \c NULL if you don't need the returned string. Do not
  89511. * free the returned string; it will always point to static
  89512. * data.
  89513. * \assert
  89514. * \code object != NULL \endcode
  89515. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89516. * \retval FLAC__bool
  89517. * \c false if cue sheet is illegal, else \c true.
  89518. */
  89519. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  89520. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  89521. * assumes the cue sheet corresponds to a CD; the result is undefined
  89522. * if the cuesheet's is_cd bit is not set.
  89523. *
  89524. * \param object A pointer to an existing CUESHEET object.
  89525. * \assert
  89526. * \code object != NULL \endcode
  89527. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  89528. * \retval FLAC__uint32
  89529. * The unsigned integer representation of the CDDB/freedb ID
  89530. */
  89531. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  89532. /** Sets the MIME type of a PICTURE block.
  89533. *
  89534. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89535. * takes ownership of the pointer. The existing string will be freed if this
  89536. * function is successful, otherwise the original string will remain if \a copy
  89537. * is \c true and malloc() fails.
  89538. *
  89539. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  89540. *
  89541. * \param object A pointer to an existing PICTURE object.
  89542. * \param mime_type A pointer to the MIME type string. The string must be
  89543. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  89544. * is done.
  89545. * \param copy See above.
  89546. * \assert
  89547. * \code object != NULL \endcode
  89548. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89549. * \code (mime_type != NULL) \endcode
  89550. * \retval FLAC__bool
  89551. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89552. */
  89553. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  89554. /** Sets the description of a PICTURE block.
  89555. *
  89556. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  89557. * takes ownership of the pointer. The existing string will be freed if this
  89558. * function is successful, otherwise the original string will remain if \a copy
  89559. * is \c true and malloc() fails.
  89560. *
  89561. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  89562. *
  89563. * \param object A pointer to an existing PICTURE object.
  89564. * \param description A pointer to the description string. The string must be
  89565. * valid UTF-8, NUL-terminated. No validation is done.
  89566. * \param copy See above.
  89567. * \assert
  89568. * \code object != NULL \endcode
  89569. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89570. * \code (description != NULL) \endcode
  89571. * \retval FLAC__bool
  89572. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89573. */
  89574. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  89575. /** Sets the picture data of a PICTURE block.
  89576. *
  89577. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  89578. * takes ownership of the pointer. Also sets the \a data_length field of the
  89579. * metadata object to what is passed in as the \a length parameter. The
  89580. * existing data will be freed if this function is successful, otherwise the
  89581. * original data and data_length will remain if \a copy is \c true and
  89582. * malloc() fails.
  89583. *
  89584. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  89585. *
  89586. * \param object A pointer to an existing PICTURE object.
  89587. * \param data A pointer to the data to set.
  89588. * \param length The length of \a data in bytes.
  89589. * \param copy See above.
  89590. * \assert
  89591. * \code object != NULL \endcode
  89592. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89593. * \code (data != NULL && length > 0) ||
  89594. * (data == NULL && length == 0 && copy == false) \endcode
  89595. * \retval FLAC__bool
  89596. * \c false if \a copy is \c true and malloc() fails, else \c true.
  89597. */
  89598. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  89599. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  89600. * See the format specification for limits on the contents of the
  89601. * PICTURE block.
  89602. *
  89603. * \param object A pointer to existing PICTURE block to be checked.
  89604. * \param violation Address of a pointer to a string. If there is a
  89605. * violation, a pointer to a string explanation of the
  89606. * violation will be returned here. \a violation may be
  89607. * \c NULL if you don't need the returned string. Do not
  89608. * free the returned string; it will always point to static
  89609. * data.
  89610. * \assert
  89611. * \code object != NULL \endcode
  89612. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  89613. * \retval FLAC__bool
  89614. * \c false if PICTURE block is illegal, else \c true.
  89615. */
  89616. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  89617. /* \} */
  89618. #ifdef __cplusplus
  89619. }
  89620. #endif
  89621. #endif
  89622. /*** End of inlined file: metadata.h ***/
  89623. /*** Start of inlined file: stream_decoder.h ***/
  89624. #ifndef FLAC__STREAM_DECODER_H
  89625. #define FLAC__STREAM_DECODER_H
  89626. #include <stdio.h> /* for FILE */
  89627. #ifdef __cplusplus
  89628. extern "C" {
  89629. #endif
  89630. /** \file include/FLAC/stream_decoder.h
  89631. *
  89632. * \brief
  89633. * This module contains the functions which implement the stream
  89634. * decoder.
  89635. *
  89636. * See the detailed documentation in the
  89637. * \link flac_stream_decoder stream decoder \endlink module.
  89638. */
  89639. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  89640. * \ingroup flac
  89641. *
  89642. * \brief
  89643. * This module describes the decoder layers provided by libFLAC.
  89644. *
  89645. * The stream decoder can be used to decode complete streams either from
  89646. * the client via callbacks, or directly from a file, depending on how
  89647. * it is initialized. When decoding via callbacks, the client provides
  89648. * callbacks for reading FLAC data and writing decoded samples, and
  89649. * handling metadata and errors. If the client also supplies seek-related
  89650. * callback, the decoder function for sample-accurate seeking within the
  89651. * FLAC input is also available. When decoding from a file, the client
  89652. * needs only supply a filename or open \c FILE* and write/metadata/error
  89653. * callbacks; the rest of the callbacks are supplied internally. For more
  89654. * info see the \link flac_stream_decoder stream decoder \endlink module.
  89655. */
  89656. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  89657. * \ingroup flac_decoder
  89658. *
  89659. * \brief
  89660. * This module contains the functions which implement the stream
  89661. * decoder.
  89662. *
  89663. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  89664. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  89665. *
  89666. * The basic usage of this decoder is as follows:
  89667. * - The program creates an instance of a decoder using
  89668. * FLAC__stream_decoder_new().
  89669. * - The program overrides the default settings using
  89670. * FLAC__stream_decoder_set_*() functions.
  89671. * - The program initializes the instance to validate the settings and
  89672. * prepare for decoding using
  89673. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  89674. * or FLAC__stream_decoder_init_file() for native FLAC,
  89675. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  89676. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  89677. * - The program calls the FLAC__stream_decoder_process_*() functions
  89678. * to decode data, which subsequently calls the callbacks.
  89679. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  89680. * which flushes the input and output and resets the decoder to the
  89681. * uninitialized state.
  89682. * - The instance may be used again or deleted with
  89683. * FLAC__stream_decoder_delete().
  89684. *
  89685. * In more detail, the program will create a new instance by calling
  89686. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  89687. * functions to override the default decoder options, and call
  89688. * one of the FLAC__stream_decoder_init_*() functions.
  89689. *
  89690. * There are three initialization functions for native FLAC, one for
  89691. * setting up the decoder to decode FLAC data from the client via
  89692. * callbacks, and two for decoding directly from a FLAC file.
  89693. *
  89694. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  89695. * You must also supply several callbacks for handling I/O. Some (like
  89696. * seeking) are optional, depending on the capabilities of the input.
  89697. *
  89698. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  89699. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  89700. * \c FILE* or filename and fewer callbacks; the decoder will handle
  89701. * the other callbacks internally.
  89702. *
  89703. * There are three similarly-named init functions for decoding from Ogg
  89704. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  89705. * library has been built with Ogg support.
  89706. *
  89707. * Once the decoder is initialized, your program will call one of several
  89708. * functions to start the decoding process:
  89709. *
  89710. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  89711. * most one metadata block or audio frame and return, calling either the
  89712. * metadata callback or write callback, respectively, once. If the decoder
  89713. * loses sync it will return with only the error callback being called.
  89714. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  89715. * to process the stream from the current location and stop upon reaching
  89716. * the first audio frame. The client will get one metadata, write, or error
  89717. * callback per metadata block, audio frame, or sync error, respectively.
  89718. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  89719. * to process the stream from the current location until the read callback
  89720. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  89721. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  89722. * write, or error callback per metadata block, audio frame, or sync error,
  89723. * respectively.
  89724. *
  89725. * When the decoder has finished decoding (normally or through an abort),
  89726. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  89727. * ensures the decoder is in the correct state and frees memory. Then the
  89728. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  89729. * again to decode another stream.
  89730. *
  89731. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  89732. * At any point after the stream decoder has been initialized, the client can
  89733. * call this function to seek to an exact sample within the stream.
  89734. * Subsequently, the first time the write callback is called it will be
  89735. * passed a (possibly partial) block starting at that sample.
  89736. *
  89737. * If the client cannot seek via the callback interface provided, but still
  89738. * has another way of seeking, it can flush the decoder using
  89739. * FLAC__stream_decoder_flush() and start feeding data from the new position
  89740. * through the read callback.
  89741. *
  89742. * The stream decoder also provides MD5 signature checking. If this is
  89743. * turned on before initialization, FLAC__stream_decoder_finish() will
  89744. * report when the decoded MD5 signature does not match the one stored
  89745. * in the STREAMINFO block. MD5 checking is automatically turned off
  89746. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  89747. * in the STREAMINFO block or when a seek is attempted.
  89748. *
  89749. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  89750. * attention. By default, the decoder only calls the metadata_callback for
  89751. * the STREAMINFO block. These functions allow you to tell the decoder
  89752. * explicitly which blocks to parse and return via the metadata_callback
  89753. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  89754. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  89755. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  89756. * which blocks to return. Remember that metadata blocks can potentially
  89757. * be big (for example, cover art) so filtering out the ones you don't
  89758. * use can reduce the memory requirements of the decoder. Also note the
  89759. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  89760. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  89761. * filtering APPLICATION blocks based on the application ID.
  89762. *
  89763. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  89764. * they still can legally be filtered from the metadata_callback.
  89765. *
  89766. * \note
  89767. * The "set" functions may only be called when the decoder is in the
  89768. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  89769. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  89770. * before FLAC__stream_decoder_init_*(). If this is the case they will
  89771. * return \c true, otherwise \c false.
  89772. *
  89773. * \note
  89774. * FLAC__stream_decoder_finish() resets all settings to the constructor
  89775. * defaults, including the callbacks.
  89776. *
  89777. * \{
  89778. */
  89779. /** State values for a FLAC__StreamDecoder
  89780. *
  89781. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  89782. */
  89783. typedef enum {
  89784. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  89785. /**< The decoder is ready to search for metadata. */
  89786. FLAC__STREAM_DECODER_READ_METADATA,
  89787. /**< The decoder is ready to or is in the process of reading metadata. */
  89788. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  89789. /**< The decoder is ready to or is in the process of searching for the
  89790. * frame sync code.
  89791. */
  89792. FLAC__STREAM_DECODER_READ_FRAME,
  89793. /**< The decoder is ready to or is in the process of reading a frame. */
  89794. FLAC__STREAM_DECODER_END_OF_STREAM,
  89795. /**< The decoder has reached the end of the stream. */
  89796. FLAC__STREAM_DECODER_OGG_ERROR,
  89797. /**< An error occurred in the underlying Ogg layer. */
  89798. FLAC__STREAM_DECODER_SEEK_ERROR,
  89799. /**< An error occurred while seeking. The decoder must be flushed
  89800. * with FLAC__stream_decoder_flush() or reset with
  89801. * FLAC__stream_decoder_reset() before decoding can continue.
  89802. */
  89803. FLAC__STREAM_DECODER_ABORTED,
  89804. /**< The decoder was aborted by the read callback. */
  89805. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  89806. /**< An error occurred allocating memory. The decoder is in an invalid
  89807. * state and can no longer be used.
  89808. */
  89809. FLAC__STREAM_DECODER_UNINITIALIZED
  89810. /**< The decoder is in the uninitialized state; one of the
  89811. * FLAC__stream_decoder_init_*() functions must be called before samples
  89812. * can be processed.
  89813. */
  89814. } FLAC__StreamDecoderState;
  89815. /** Maps a FLAC__StreamDecoderState to a C string.
  89816. *
  89817. * Using a FLAC__StreamDecoderState as the index to this array
  89818. * will give the string equivalent. The contents should not be modified.
  89819. */
  89820. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  89821. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  89822. */
  89823. typedef enum {
  89824. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  89825. /**< Initialization was successful. */
  89826. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  89827. /**< The library was not compiled with support for the given container
  89828. * format.
  89829. */
  89830. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  89831. /**< A required callback was not supplied. */
  89832. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  89833. /**< An error occurred allocating memory. */
  89834. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  89835. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  89836. * FLAC__stream_decoder_init_ogg_file(). */
  89837. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  89838. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  89839. * already initialized, usually because
  89840. * FLAC__stream_decoder_finish() was not called.
  89841. */
  89842. } FLAC__StreamDecoderInitStatus;
  89843. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  89844. *
  89845. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  89846. * will give the string equivalent. The contents should not be modified.
  89847. */
  89848. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  89849. /** Return values for the FLAC__StreamDecoder read callback.
  89850. */
  89851. typedef enum {
  89852. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  89853. /**< The read was OK and decoding can continue. */
  89854. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  89855. /**< The read was attempted while at the end of the stream. Note that
  89856. * the client must only return this value when the read callback was
  89857. * called when already at the end of the stream. Otherwise, if the read
  89858. * itself moves to the end of the stream, the client should still return
  89859. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  89860. * the next read callback it should return
  89861. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  89862. * of \c 0.
  89863. */
  89864. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  89865. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89866. } FLAC__StreamDecoderReadStatus;
  89867. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  89868. *
  89869. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  89870. * will give the string equivalent. The contents should not be modified.
  89871. */
  89872. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  89873. /** Return values for the FLAC__StreamDecoder seek callback.
  89874. */
  89875. typedef enum {
  89876. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  89877. /**< The seek was OK and decoding can continue. */
  89878. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  89879. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89880. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  89881. /**< Client does not support seeking. */
  89882. } FLAC__StreamDecoderSeekStatus;
  89883. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  89884. *
  89885. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  89886. * will give the string equivalent. The contents should not be modified.
  89887. */
  89888. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  89889. /** Return values for the FLAC__StreamDecoder tell callback.
  89890. */
  89891. typedef enum {
  89892. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  89893. /**< The tell was OK and decoding can continue. */
  89894. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  89895. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89896. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  89897. /**< Client does not support telling the position. */
  89898. } FLAC__StreamDecoderTellStatus;
  89899. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  89900. *
  89901. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  89902. * will give the string equivalent. The contents should not be modified.
  89903. */
  89904. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  89905. /** Return values for the FLAC__StreamDecoder length callback.
  89906. */
  89907. typedef enum {
  89908. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  89909. /**< The length call was OK and decoding can continue. */
  89910. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  89911. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89912. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  89913. /**< Client does not support reporting the length. */
  89914. } FLAC__StreamDecoderLengthStatus;
  89915. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  89916. *
  89917. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  89918. * will give the string equivalent. The contents should not be modified.
  89919. */
  89920. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  89921. /** Return values for the FLAC__StreamDecoder write callback.
  89922. */
  89923. typedef enum {
  89924. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  89925. /**< The write was OK and decoding can continue. */
  89926. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  89927. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  89928. } FLAC__StreamDecoderWriteStatus;
  89929. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  89930. *
  89931. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  89932. * will give the string equivalent. The contents should not be modified.
  89933. */
  89934. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  89935. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  89936. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  89937. * all. The rest could be caused by bad sync (false synchronization on
  89938. * data that is not the start of a frame) or corrupted data. The error
  89939. * itself is the decoder's best guess at what happened assuming a correct
  89940. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  89941. * could be caused by a correct sync on the start of a frame, but some
  89942. * data in the frame header was corrupted. Or it could be the result of
  89943. * syncing on a point the stream that looked like the starting of a frame
  89944. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89945. * could be because the decoder encountered a valid frame made by a future
  89946. * version of the encoder which it cannot parse, or because of a false
  89947. * sync making it appear as though an encountered frame was generated by
  89948. * a future encoder.
  89949. */
  89950. typedef enum {
  89951. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  89952. /**< An error in the stream caused the decoder to lose synchronization. */
  89953. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  89954. /**< The decoder encountered a corrupted frame header. */
  89955. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  89956. /**< The frame's data did not match the CRC in the footer. */
  89957. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  89958. /**< The decoder encountered reserved fields in use in the stream. */
  89959. } FLAC__StreamDecoderErrorStatus;
  89960. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  89961. *
  89962. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  89963. * will give the string equivalent. The contents should not be modified.
  89964. */
  89965. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  89966. /***********************************************************************
  89967. *
  89968. * class FLAC__StreamDecoder
  89969. *
  89970. ***********************************************************************/
  89971. struct FLAC__StreamDecoderProtected;
  89972. struct FLAC__StreamDecoderPrivate;
  89973. /** The opaque structure definition for the stream decoder type.
  89974. * See the \link flac_stream_decoder stream decoder module \endlink
  89975. * for a detailed description.
  89976. */
  89977. typedef struct {
  89978. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  89979. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  89980. } FLAC__StreamDecoder;
  89981. /** Signature for the read callback.
  89982. *
  89983. * A function pointer matching this signature must be passed to
  89984. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  89985. * called when the decoder needs more input data. The address of the
  89986. * buffer to be filled is supplied, along with the number of bytes the
  89987. * buffer can hold. The callback may choose to supply less data and
  89988. * modify the byte count but must be careful not to overflow the buffer.
  89989. * The callback then returns a status code chosen from
  89990. * FLAC__StreamDecoderReadStatus.
  89991. *
  89992. * Here is an example of a read callback for stdio streams:
  89993. * \code
  89994. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  89995. * {
  89996. * FILE *file = ((MyClientData*)client_data)->file;
  89997. * if(*bytes > 0) {
  89998. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  89999. * if(ferror(file))
  90000. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  90001. * else if(*bytes == 0)
  90002. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  90003. * else
  90004. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  90005. * }
  90006. * else
  90007. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  90008. * }
  90009. * \endcode
  90010. *
  90011. * \note In general, FLAC__StreamDecoder functions which change the
  90012. * state should not be called on the \a decoder while in the callback.
  90013. *
  90014. * \param decoder The decoder instance calling the callback.
  90015. * \param buffer A pointer to a location for the callee to store
  90016. * data to be decoded.
  90017. * \param bytes A pointer to the size of the buffer. On entry
  90018. * to the callback, it contains the maximum number
  90019. * of bytes that may be stored in \a buffer. The
  90020. * callee must set it to the actual number of bytes
  90021. * stored (0 in case of error or end-of-stream) before
  90022. * returning.
  90023. * \param client_data The callee's client data set through
  90024. * FLAC__stream_decoder_init_*().
  90025. * \retval FLAC__StreamDecoderReadStatus
  90026. * The callee's return status. Note that the callback should return
  90027. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  90028. * zero bytes were read and there is no more data to be read.
  90029. */
  90030. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  90031. /** Signature for the seek callback.
  90032. *
  90033. * A function pointer matching this signature may be passed to
  90034. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90035. * called when the decoder needs to seek the input stream. The decoder
  90036. * will pass the absolute byte offset to seek to, 0 meaning the
  90037. * beginning of the stream.
  90038. *
  90039. * Here is an example of a seek callback for stdio streams:
  90040. * \code
  90041. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  90042. * {
  90043. * FILE *file = ((MyClientData*)client_data)->file;
  90044. * if(file == stdin)
  90045. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  90046. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  90047. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  90048. * else
  90049. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  90050. * }
  90051. * \endcode
  90052. *
  90053. * \note In general, FLAC__StreamDecoder functions which change the
  90054. * state should not be called on the \a decoder while in the callback.
  90055. *
  90056. * \param decoder The decoder instance calling the callback.
  90057. * \param absolute_byte_offset The offset from the beginning of the stream
  90058. * to seek to.
  90059. * \param client_data The callee's client data set through
  90060. * FLAC__stream_decoder_init_*().
  90061. * \retval FLAC__StreamDecoderSeekStatus
  90062. * The callee's return status.
  90063. */
  90064. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  90065. /** Signature for the tell callback.
  90066. *
  90067. * A function pointer matching this signature may be passed to
  90068. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90069. * called when the decoder wants to know the current position of the
  90070. * stream. The callback should return the byte offset from the
  90071. * beginning of the stream.
  90072. *
  90073. * Here is an example of a tell callback for stdio streams:
  90074. * \code
  90075. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  90076. * {
  90077. * FILE *file = ((MyClientData*)client_data)->file;
  90078. * off_t pos;
  90079. * if(file == stdin)
  90080. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  90081. * else if((pos = ftello(file)) < 0)
  90082. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  90083. * else {
  90084. * *absolute_byte_offset = (FLAC__uint64)pos;
  90085. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  90086. * }
  90087. * }
  90088. * \endcode
  90089. *
  90090. * \note In general, FLAC__StreamDecoder functions which change the
  90091. * state should not be called on the \a decoder while in the callback.
  90092. *
  90093. * \param decoder The decoder instance calling the callback.
  90094. * \param absolute_byte_offset A pointer to storage for the current offset
  90095. * from the beginning of the stream.
  90096. * \param client_data The callee's client data set through
  90097. * FLAC__stream_decoder_init_*().
  90098. * \retval FLAC__StreamDecoderTellStatus
  90099. * The callee's return status.
  90100. */
  90101. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  90102. /** Signature for the length callback.
  90103. *
  90104. * A function pointer matching this signature may be passed to
  90105. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90106. * called when the decoder wants to know the total length of the stream
  90107. * in bytes.
  90108. *
  90109. * Here is an example of a length callback for stdio streams:
  90110. * \code
  90111. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  90112. * {
  90113. * FILE *file = ((MyClientData*)client_data)->file;
  90114. * struct stat filestats;
  90115. *
  90116. * if(file == stdin)
  90117. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  90118. * else if(fstat(fileno(file), &filestats) != 0)
  90119. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  90120. * else {
  90121. * *stream_length = (FLAC__uint64)filestats.st_size;
  90122. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  90123. * }
  90124. * }
  90125. * \endcode
  90126. *
  90127. * \note In general, FLAC__StreamDecoder functions which change the
  90128. * state should not be called on the \a decoder while in the callback.
  90129. *
  90130. * \param decoder The decoder instance calling the callback.
  90131. * \param stream_length A pointer to storage for the length of the stream
  90132. * in bytes.
  90133. * \param client_data The callee's client data set through
  90134. * FLAC__stream_decoder_init_*().
  90135. * \retval FLAC__StreamDecoderLengthStatus
  90136. * The callee's return status.
  90137. */
  90138. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  90139. /** Signature for the EOF callback.
  90140. *
  90141. * A function pointer matching this signature may be passed to
  90142. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  90143. * called when the decoder needs to know if the end of the stream has
  90144. * been reached.
  90145. *
  90146. * Here is an example of a EOF callback for stdio streams:
  90147. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  90148. * \code
  90149. * {
  90150. * FILE *file = ((MyClientData*)client_data)->file;
  90151. * return feof(file)? true : false;
  90152. * }
  90153. * \endcode
  90154. *
  90155. * \note In general, FLAC__StreamDecoder functions which change the
  90156. * state should not be called on the \a decoder while in the callback.
  90157. *
  90158. * \param decoder The decoder instance calling the callback.
  90159. * \param client_data The callee's client data set through
  90160. * FLAC__stream_decoder_init_*().
  90161. * \retval FLAC__bool
  90162. * \c true if the currently at the end of the stream, else \c false.
  90163. */
  90164. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  90165. /** Signature for the write callback.
  90166. *
  90167. * A function pointer matching this signature must be passed to one of
  90168. * the FLAC__stream_decoder_init_*() functions.
  90169. * The supplied function will be called when the decoder has decoded a
  90170. * single audio frame. The decoder will pass the frame metadata as well
  90171. * as an array of pointers (one for each channel) pointing to the
  90172. * decoded audio.
  90173. *
  90174. * \note In general, FLAC__StreamDecoder functions which change the
  90175. * state should not be called on the \a decoder while in the callback.
  90176. *
  90177. * \param decoder The decoder instance calling the callback.
  90178. * \param frame The description of the decoded frame. See
  90179. * FLAC__Frame.
  90180. * \param buffer An array of pointers to decoded channels of data.
  90181. * Each pointer will point to an array of signed
  90182. * samples of length \a frame->header.blocksize.
  90183. * Channels will be ordered according to the FLAC
  90184. * specification; see the documentation for the
  90185. * <A HREF="../format.html#frame_header">frame header</A>.
  90186. * \param client_data The callee's client data set through
  90187. * FLAC__stream_decoder_init_*().
  90188. * \retval FLAC__StreamDecoderWriteStatus
  90189. * The callee's return status.
  90190. */
  90191. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  90192. /** Signature for the metadata callback.
  90193. *
  90194. * A function pointer matching this signature must be passed to one of
  90195. * the FLAC__stream_decoder_init_*() functions.
  90196. * The supplied function will be called when the decoder has decoded a
  90197. * metadata block. In a valid FLAC file there will always be one
  90198. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  90199. * These will be supplied by the decoder in the same order as they
  90200. * appear in the stream and always before the first audio frame (i.e.
  90201. * write callback). The metadata block that is passed in must not be
  90202. * modified, and it doesn't live beyond the callback, so you should make
  90203. * a copy of it with FLAC__metadata_object_clone() if you will need it
  90204. * elsewhere. Since metadata blocks can potentially be large, by
  90205. * default the decoder only calls the metadata callback for the
  90206. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  90207. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  90208. *
  90209. * \note In general, FLAC__StreamDecoder functions which change the
  90210. * state should not be called on the \a decoder while in the callback.
  90211. *
  90212. * \param decoder The decoder instance calling the callback.
  90213. * \param metadata The decoded metadata block.
  90214. * \param client_data The callee's client data set through
  90215. * FLAC__stream_decoder_init_*().
  90216. */
  90217. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  90218. /** Signature for the error callback.
  90219. *
  90220. * A function pointer matching this signature must be passed to one of
  90221. * the FLAC__stream_decoder_init_*() functions.
  90222. * The supplied function will be called whenever an error occurs during
  90223. * decoding.
  90224. *
  90225. * \note In general, FLAC__StreamDecoder functions which change the
  90226. * state should not be called on the \a decoder while in the callback.
  90227. *
  90228. * \param decoder The decoder instance calling the callback.
  90229. * \param status The error encountered by the decoder.
  90230. * \param client_data The callee's client data set through
  90231. * FLAC__stream_decoder_init_*().
  90232. */
  90233. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  90234. /***********************************************************************
  90235. *
  90236. * Class constructor/destructor
  90237. *
  90238. ***********************************************************************/
  90239. /** Create a new stream decoder instance. The instance is created with
  90240. * default settings; see the individual FLAC__stream_decoder_set_*()
  90241. * functions for each setting's default.
  90242. *
  90243. * \retval FLAC__StreamDecoder*
  90244. * \c NULL if there was an error allocating memory, else the new instance.
  90245. */
  90246. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  90247. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  90248. *
  90249. * \param decoder A pointer to an existing decoder.
  90250. * \assert
  90251. * \code decoder != NULL \endcode
  90252. */
  90253. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  90254. /***********************************************************************
  90255. *
  90256. * Public class method prototypes
  90257. *
  90258. ***********************************************************************/
  90259. /** Set the serial number for the FLAC stream within the Ogg container.
  90260. * The default behavior is to use the serial number of the first Ogg
  90261. * page. Setting a serial number here will explicitly specify which
  90262. * stream is to be decoded.
  90263. *
  90264. * \note
  90265. * This does not need to be set for native FLAC decoding.
  90266. *
  90267. * \default \c use serial number of first page
  90268. * \param decoder A decoder instance to set.
  90269. * \param serial_number See above.
  90270. * \assert
  90271. * \code decoder != NULL \endcode
  90272. * \retval FLAC__bool
  90273. * \c false if the decoder is already initialized, else \c true.
  90274. */
  90275. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  90276. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  90277. * compute the MD5 signature of the unencoded audio data while decoding
  90278. * and compare it to the signature from the STREAMINFO block, if it
  90279. * exists, during FLAC__stream_decoder_finish().
  90280. *
  90281. * MD5 signature checking will be turned off (until the next
  90282. * FLAC__stream_decoder_reset()) if there is no signature in the
  90283. * STREAMINFO block or when a seek is attempted.
  90284. *
  90285. * Clients that do not use the MD5 check should leave this off to speed
  90286. * up decoding.
  90287. *
  90288. * \default \c false
  90289. * \param decoder A decoder instance to set.
  90290. * \param value Flag value (see above).
  90291. * \assert
  90292. * \code decoder != NULL \endcode
  90293. * \retval FLAC__bool
  90294. * \c false if the decoder is already initialized, else \c true.
  90295. */
  90296. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  90297. /** Direct the decoder to pass on all metadata blocks of type \a type.
  90298. *
  90299. * \default By default, only the \c STREAMINFO block is returned via the
  90300. * metadata callback.
  90301. * \param decoder A decoder instance to set.
  90302. * \param type See above.
  90303. * \assert
  90304. * \code decoder != NULL \endcode
  90305. * \a type is valid
  90306. * \retval FLAC__bool
  90307. * \c false if the decoder is already initialized, else \c true.
  90308. */
  90309. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90310. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  90311. * given \a id.
  90312. *
  90313. * \default By default, only the \c STREAMINFO block is returned via the
  90314. * metadata callback.
  90315. * \param decoder A decoder instance to set.
  90316. * \param id See above.
  90317. * \assert
  90318. * \code decoder != NULL \endcode
  90319. * \code id != NULL \endcode
  90320. * \retval FLAC__bool
  90321. * \c false if the decoder is already initialized, else \c true.
  90322. */
  90323. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90324. /** Direct the decoder to pass on all metadata blocks of any type.
  90325. *
  90326. * \default By default, only the \c STREAMINFO block is returned via the
  90327. * metadata callback.
  90328. * \param decoder A decoder instance to set.
  90329. * \assert
  90330. * \code decoder != NULL \endcode
  90331. * \retval FLAC__bool
  90332. * \c false if the decoder is already initialized, else \c true.
  90333. */
  90334. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  90335. /** Direct the decoder to filter out all metadata blocks of type \a type.
  90336. *
  90337. * \default By default, only the \c STREAMINFO block is returned via the
  90338. * metadata callback.
  90339. * \param decoder A decoder instance to set.
  90340. * \param type See above.
  90341. * \assert
  90342. * \code decoder != NULL \endcode
  90343. * \a type is valid
  90344. * \retval FLAC__bool
  90345. * \c false if the decoder is already initialized, else \c true.
  90346. */
  90347. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  90348. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  90349. * the given \a id.
  90350. *
  90351. * \default By default, only the \c STREAMINFO block is returned via the
  90352. * metadata callback.
  90353. * \param decoder A decoder instance to set.
  90354. * \param id See above.
  90355. * \assert
  90356. * \code decoder != NULL \endcode
  90357. * \code id != NULL \endcode
  90358. * \retval FLAC__bool
  90359. * \c false if the decoder is already initialized, else \c true.
  90360. */
  90361. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  90362. /** Direct the decoder to filter out all metadata blocks of any type.
  90363. *
  90364. * \default By default, only the \c STREAMINFO block is returned via the
  90365. * metadata callback.
  90366. * \param decoder A decoder instance to set.
  90367. * \assert
  90368. * \code decoder != NULL \endcode
  90369. * \retval FLAC__bool
  90370. * \c false if the decoder is already initialized, else \c true.
  90371. */
  90372. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  90373. /** Get the current decoder state.
  90374. *
  90375. * \param decoder A decoder instance to query.
  90376. * \assert
  90377. * \code decoder != NULL \endcode
  90378. * \retval FLAC__StreamDecoderState
  90379. * The current decoder state.
  90380. */
  90381. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  90382. /** Get the current decoder state as a C string.
  90383. *
  90384. * \param decoder A decoder instance to query.
  90385. * \assert
  90386. * \code decoder != NULL \endcode
  90387. * \retval const char *
  90388. * The decoder state as a C string. Do not modify the contents.
  90389. */
  90390. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  90391. /** Get the "MD5 signature checking" flag.
  90392. * This is the value of the setting, not whether or not the decoder is
  90393. * currently checking the MD5 (remember, it can be turned off automatically
  90394. * by a seek). When the decoder is reset the flag will be restored to the
  90395. * value returned by this function.
  90396. *
  90397. * \param decoder A decoder instance to query.
  90398. * \assert
  90399. * \code decoder != NULL \endcode
  90400. * \retval FLAC__bool
  90401. * See above.
  90402. */
  90403. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  90404. /** Get the total number of samples in the stream being decoded.
  90405. * Will only be valid after decoding has started and will contain the
  90406. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  90407. *
  90408. * \param decoder A decoder instance to query.
  90409. * \assert
  90410. * \code decoder != NULL \endcode
  90411. * \retval unsigned
  90412. * See above.
  90413. */
  90414. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  90415. /** Get the current number of channels in the stream being decoded.
  90416. * Will only be valid after decoding has started and will contain the
  90417. * value from the most recently decoded frame header.
  90418. *
  90419. * \param decoder A decoder instance to query.
  90420. * \assert
  90421. * \code decoder != NULL \endcode
  90422. * \retval unsigned
  90423. * See above.
  90424. */
  90425. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  90426. /** Get the current channel assignment in the stream being decoded.
  90427. * Will only be valid after decoding has started and will contain the
  90428. * value from the most recently decoded frame header.
  90429. *
  90430. * \param decoder A decoder instance to query.
  90431. * \assert
  90432. * \code decoder != NULL \endcode
  90433. * \retval FLAC__ChannelAssignment
  90434. * See above.
  90435. */
  90436. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  90437. /** Get the current sample resolution in the stream being decoded.
  90438. * Will only be valid after decoding has started and will contain the
  90439. * value from the most recently decoded frame header.
  90440. *
  90441. * \param decoder A decoder instance to query.
  90442. * \assert
  90443. * \code decoder != NULL \endcode
  90444. * \retval unsigned
  90445. * See above.
  90446. */
  90447. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  90448. /** Get the current sample rate in Hz of the stream being decoded.
  90449. * Will only be valid after decoding has started and will contain the
  90450. * value from the most recently decoded frame header.
  90451. *
  90452. * \param decoder A decoder instance to query.
  90453. * \assert
  90454. * \code decoder != NULL \endcode
  90455. * \retval unsigned
  90456. * See above.
  90457. */
  90458. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  90459. /** Get the current blocksize of the stream being decoded.
  90460. * Will only be valid after decoding has started and will contain the
  90461. * value from the most recently decoded frame header.
  90462. *
  90463. * \param decoder A decoder instance to query.
  90464. * \assert
  90465. * \code decoder != NULL \endcode
  90466. * \retval unsigned
  90467. * See above.
  90468. */
  90469. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  90470. /** Returns the decoder's current read position within the stream.
  90471. * The position is the byte offset from the start of the stream.
  90472. * Bytes before this position have been fully decoded. Note that
  90473. * there may still be undecoded bytes in the decoder's read FIFO.
  90474. * The returned position is correct even after a seek.
  90475. *
  90476. * \warning This function currently only works for native FLAC,
  90477. * not Ogg FLAC streams.
  90478. *
  90479. * \param decoder A decoder instance to query.
  90480. * \param position Address at which to return the desired position.
  90481. * \assert
  90482. * \code decoder != NULL \endcode
  90483. * \code position != NULL \endcode
  90484. * \retval FLAC__bool
  90485. * \c true if successful, \c false if the stream is not native FLAC,
  90486. * or there was an error from the 'tell' callback or it returned
  90487. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  90488. */
  90489. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  90490. /** Initialize the decoder instance to decode native FLAC streams.
  90491. *
  90492. * This flavor of initialization sets up the decoder to decode from a
  90493. * native FLAC stream. I/O is performed via callbacks to the client.
  90494. * For decoding from a plain file via filename or open FILE*,
  90495. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  90496. * provide a simpler interface.
  90497. *
  90498. * This function should be called after FLAC__stream_decoder_new() and
  90499. * FLAC__stream_decoder_set_*() but before any of the
  90500. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90501. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90502. * if initialization succeeded.
  90503. *
  90504. * \param decoder An uninitialized decoder instance.
  90505. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90506. * pointer must not be \c NULL.
  90507. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90508. * pointer may be \c NULL if seeking is not
  90509. * supported. If \a seek_callback is not \c NULL then a
  90510. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90511. * Alternatively, a dummy seek callback that just
  90512. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90513. * may also be supplied, all though this is slightly
  90514. * less efficient for the decoder.
  90515. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90516. * pointer may be \c NULL if not supported by the client. If
  90517. * \a seek_callback is not \c NULL then a
  90518. * \a tell_callback must also be supplied.
  90519. * Alternatively, a dummy tell callback that just
  90520. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90521. * may also be supplied, all though this is slightly
  90522. * less efficient for the decoder.
  90523. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90524. * pointer may be \c NULL if not supported by the client. If
  90525. * \a seek_callback is not \c NULL then a
  90526. * \a length_callback must also be supplied.
  90527. * Alternatively, a dummy length callback that just
  90528. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90529. * may also be supplied, all though this is slightly
  90530. * less efficient for the decoder.
  90531. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90532. * pointer may be \c NULL if not supported by the client. If
  90533. * \a seek_callback is not \c NULL then a
  90534. * \a eof_callback must also be supplied.
  90535. * Alternatively, a dummy length callback that just
  90536. * returns \c false
  90537. * may also be supplied, all though this is slightly
  90538. * less efficient for the decoder.
  90539. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90540. * pointer must not be \c NULL.
  90541. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90542. * pointer may be \c NULL if the callback is not
  90543. * desired.
  90544. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90545. * pointer must not be \c NULL.
  90546. * \param client_data This value will be supplied to callbacks in their
  90547. * \a client_data argument.
  90548. * \assert
  90549. * \code decoder != NULL \endcode
  90550. * \retval FLAC__StreamDecoderInitStatus
  90551. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90552. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90553. */
  90554. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  90555. FLAC__StreamDecoder *decoder,
  90556. FLAC__StreamDecoderReadCallback read_callback,
  90557. FLAC__StreamDecoderSeekCallback seek_callback,
  90558. FLAC__StreamDecoderTellCallback tell_callback,
  90559. FLAC__StreamDecoderLengthCallback length_callback,
  90560. FLAC__StreamDecoderEofCallback eof_callback,
  90561. FLAC__StreamDecoderWriteCallback write_callback,
  90562. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90563. FLAC__StreamDecoderErrorCallback error_callback,
  90564. void *client_data
  90565. );
  90566. /** Initialize the decoder instance to decode Ogg FLAC streams.
  90567. *
  90568. * This flavor of initialization sets up the decoder to decode from a
  90569. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  90570. * client. For decoding from a plain file via filename or open FILE*,
  90571. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  90572. * provide a simpler interface.
  90573. *
  90574. * This function should be called after FLAC__stream_decoder_new() and
  90575. * FLAC__stream_decoder_set_*() but before any of the
  90576. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90577. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90578. * if initialization succeeded.
  90579. *
  90580. * \note Support for Ogg FLAC in the library is optional. If this
  90581. * library has been built without support for Ogg FLAC, this function
  90582. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90583. *
  90584. * \param decoder An uninitialized decoder instance.
  90585. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  90586. * pointer must not be \c NULL.
  90587. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  90588. * pointer may be \c NULL if seeking is not
  90589. * supported. If \a seek_callback is not \c NULL then a
  90590. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  90591. * Alternatively, a dummy seek callback that just
  90592. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  90593. * may also be supplied, all though this is slightly
  90594. * less efficient for the decoder.
  90595. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  90596. * pointer may be \c NULL if not supported by the client. If
  90597. * \a seek_callback is not \c NULL then a
  90598. * \a tell_callback must also be supplied.
  90599. * Alternatively, a dummy tell callback that just
  90600. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  90601. * may also be supplied, all though this is slightly
  90602. * less efficient for the decoder.
  90603. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  90604. * pointer may be \c NULL if not supported by the client. If
  90605. * \a seek_callback is not \c NULL then a
  90606. * \a length_callback must also be supplied.
  90607. * Alternatively, a dummy length callback that just
  90608. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  90609. * may also be supplied, all though this is slightly
  90610. * less efficient for the decoder.
  90611. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  90612. * pointer may be \c NULL if not supported by the client. If
  90613. * \a seek_callback is not \c NULL then a
  90614. * \a eof_callback must also be supplied.
  90615. * Alternatively, a dummy length callback that just
  90616. * returns \c false
  90617. * may also be supplied, all though this is slightly
  90618. * less efficient for the decoder.
  90619. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90620. * pointer must not be \c NULL.
  90621. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90622. * pointer may be \c NULL if the callback is not
  90623. * desired.
  90624. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90625. * pointer must not be \c NULL.
  90626. * \param client_data This value will be supplied to callbacks in their
  90627. * \a client_data argument.
  90628. * \assert
  90629. * \code decoder != NULL \endcode
  90630. * \retval FLAC__StreamDecoderInitStatus
  90631. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90632. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90633. */
  90634. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  90635. FLAC__StreamDecoder *decoder,
  90636. FLAC__StreamDecoderReadCallback read_callback,
  90637. FLAC__StreamDecoderSeekCallback seek_callback,
  90638. FLAC__StreamDecoderTellCallback tell_callback,
  90639. FLAC__StreamDecoderLengthCallback length_callback,
  90640. FLAC__StreamDecoderEofCallback eof_callback,
  90641. FLAC__StreamDecoderWriteCallback write_callback,
  90642. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90643. FLAC__StreamDecoderErrorCallback error_callback,
  90644. void *client_data
  90645. );
  90646. /** Initialize the decoder instance to decode native FLAC files.
  90647. *
  90648. * This flavor of initialization sets up the decoder to decode from a
  90649. * plain native FLAC file. For non-stdio streams, you must use
  90650. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  90651. *
  90652. * This function should be called after FLAC__stream_decoder_new() and
  90653. * FLAC__stream_decoder_set_*() but before any of the
  90654. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90655. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90656. * if initialization succeeded.
  90657. *
  90658. * \param decoder An uninitialized decoder instance.
  90659. * \param file An open FLAC file. The file should have been
  90660. * opened with mode \c "rb" and rewound. The file
  90661. * becomes owned by the decoder and should not be
  90662. * manipulated by the client while decoding.
  90663. * Unless \a file is \c stdin, it will be closed
  90664. * when FLAC__stream_decoder_finish() is called.
  90665. * Note however that seeking will not work when
  90666. * decoding from \c stdout since it is not seekable.
  90667. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90668. * pointer must not be \c NULL.
  90669. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90670. * pointer may be \c NULL if the callback is not
  90671. * desired.
  90672. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90673. * pointer must not be \c NULL.
  90674. * \param client_data This value will be supplied to callbacks in their
  90675. * \a client_data argument.
  90676. * \assert
  90677. * \code decoder != NULL \endcode
  90678. * \code file != NULL \endcode
  90679. * \retval FLAC__StreamDecoderInitStatus
  90680. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90681. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90682. */
  90683. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  90684. FLAC__StreamDecoder *decoder,
  90685. FILE *file,
  90686. FLAC__StreamDecoderWriteCallback write_callback,
  90687. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90688. FLAC__StreamDecoderErrorCallback error_callback,
  90689. void *client_data
  90690. );
  90691. /** Initialize the decoder instance to decode Ogg FLAC files.
  90692. *
  90693. * This flavor of initialization sets up the decoder to decode from a
  90694. * plain Ogg FLAC file. For non-stdio streams, you must use
  90695. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  90696. *
  90697. * This function should be called after FLAC__stream_decoder_new() and
  90698. * FLAC__stream_decoder_set_*() but before any of the
  90699. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90700. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90701. * if initialization succeeded.
  90702. *
  90703. * \note Support for Ogg FLAC in the library is optional. If this
  90704. * library has been built without support for Ogg FLAC, this function
  90705. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90706. *
  90707. * \param decoder An uninitialized decoder instance.
  90708. * \param file An open FLAC file. The file should have been
  90709. * opened with mode \c "rb" and rewound. The file
  90710. * becomes owned by the decoder and should not be
  90711. * manipulated by the client while decoding.
  90712. * Unless \a file is \c stdin, it will be closed
  90713. * when FLAC__stream_decoder_finish() is called.
  90714. * Note however that seeking will not work when
  90715. * decoding from \c stdout since it is not seekable.
  90716. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90717. * pointer must not be \c NULL.
  90718. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90719. * pointer may be \c NULL if the callback is not
  90720. * desired.
  90721. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90722. * pointer must not be \c NULL.
  90723. * \param client_data This value will be supplied to callbacks in their
  90724. * \a client_data argument.
  90725. * \assert
  90726. * \code decoder != NULL \endcode
  90727. * \code file != NULL \endcode
  90728. * \retval FLAC__StreamDecoderInitStatus
  90729. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90730. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90731. */
  90732. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  90733. FLAC__StreamDecoder *decoder,
  90734. FILE *file,
  90735. FLAC__StreamDecoderWriteCallback write_callback,
  90736. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90737. FLAC__StreamDecoderErrorCallback error_callback,
  90738. void *client_data
  90739. );
  90740. /** Initialize the decoder instance to decode native FLAC files.
  90741. *
  90742. * This flavor of initialization sets up the decoder to decode from a plain
  90743. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90744. * example, with Unicode filenames on Windows), you must use
  90745. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  90746. * and provide callbacks for the I/O.
  90747. *
  90748. * This function should be called after FLAC__stream_decoder_new() and
  90749. * FLAC__stream_decoder_set_*() but before any of the
  90750. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90751. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90752. * if initialization succeeded.
  90753. *
  90754. * \param decoder An uninitialized decoder instance.
  90755. * \param filename The name of the file to decode from. The file will
  90756. * be opened with fopen(). Use \c NULL to decode from
  90757. * \c stdin. Note that \c stdin is not seekable.
  90758. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90759. * pointer must not be \c NULL.
  90760. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90761. * pointer may be \c NULL if the callback is not
  90762. * desired.
  90763. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90764. * pointer must not be \c NULL.
  90765. * \param client_data This value will be supplied to callbacks in their
  90766. * \a client_data argument.
  90767. * \assert
  90768. * \code decoder != NULL \endcode
  90769. * \retval FLAC__StreamDecoderInitStatus
  90770. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90771. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90772. */
  90773. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  90774. FLAC__StreamDecoder *decoder,
  90775. const char *filename,
  90776. FLAC__StreamDecoderWriteCallback write_callback,
  90777. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90778. FLAC__StreamDecoderErrorCallback error_callback,
  90779. void *client_data
  90780. );
  90781. /** Initialize the decoder instance to decode Ogg FLAC files.
  90782. *
  90783. * This flavor of initialization sets up the decoder to decode from a plain
  90784. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  90785. * example, with Unicode filenames on Windows), you must use
  90786. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  90787. * and provide callbacks for the I/O.
  90788. *
  90789. * This function should be called after FLAC__stream_decoder_new() and
  90790. * FLAC__stream_decoder_set_*() but before any of the
  90791. * FLAC__stream_decoder_process_*() functions. Will set and return the
  90792. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  90793. * if initialization succeeded.
  90794. *
  90795. * \note Support for Ogg FLAC in the library is optional. If this
  90796. * library has been built without support for Ogg FLAC, this function
  90797. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  90798. *
  90799. * \param decoder An uninitialized decoder instance.
  90800. * \param filename The name of the file to decode from. The file will
  90801. * be opened with fopen(). Use \c NULL to decode from
  90802. * \c stdin. Note that \c stdin is not seekable.
  90803. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  90804. * pointer must not be \c NULL.
  90805. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  90806. * pointer may be \c NULL if the callback is not
  90807. * desired.
  90808. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  90809. * pointer must not be \c NULL.
  90810. * \param client_data This value will be supplied to callbacks in their
  90811. * \a client_data argument.
  90812. * \assert
  90813. * \code decoder != NULL \endcode
  90814. * \retval FLAC__StreamDecoderInitStatus
  90815. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  90816. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  90817. */
  90818. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  90819. FLAC__StreamDecoder *decoder,
  90820. const char *filename,
  90821. FLAC__StreamDecoderWriteCallback write_callback,
  90822. FLAC__StreamDecoderMetadataCallback metadata_callback,
  90823. FLAC__StreamDecoderErrorCallback error_callback,
  90824. void *client_data
  90825. );
  90826. /** Finish the decoding process.
  90827. * Flushes the decoding buffer, releases resources, resets the decoder
  90828. * settings to their defaults, and returns the decoder state to
  90829. * FLAC__STREAM_DECODER_UNINITIALIZED.
  90830. *
  90831. * In the event of a prematurely-terminated decode, it is not strictly
  90832. * necessary to call this immediately before FLAC__stream_decoder_delete()
  90833. * but it is good practice to match every FLAC__stream_decoder_init_*()
  90834. * with a FLAC__stream_decoder_finish().
  90835. *
  90836. * \param decoder An uninitialized decoder instance.
  90837. * \assert
  90838. * \code decoder != NULL \endcode
  90839. * \retval FLAC__bool
  90840. * \c false if MD5 checking is on AND a STREAMINFO block was available
  90841. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  90842. * signature does not match the one computed by the decoder; else
  90843. * \c true.
  90844. */
  90845. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  90846. /** Flush the stream input.
  90847. * The decoder's input buffer will be cleared and the state set to
  90848. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  90849. * off MD5 checking.
  90850. *
  90851. * \param decoder A decoder instance.
  90852. * \assert
  90853. * \code decoder != NULL \endcode
  90854. * \retval FLAC__bool
  90855. * \c true if successful, else \c false if a memory allocation
  90856. * error occurs (in which case the state will be set to
  90857. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  90858. */
  90859. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  90860. /** Reset the decoding process.
  90861. * The decoder's input buffer will be cleared and the state set to
  90862. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  90863. * FLAC__stream_decoder_finish() except that the settings are
  90864. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  90865. * before decoding again. MD5 checking will be restored to its original
  90866. * setting.
  90867. *
  90868. * If the decoder is seekable, or was initialized with
  90869. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  90870. * the decoder will also attempt to seek to the beginning of the file.
  90871. * If this rewind fails, this function will return \c false. It follows
  90872. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  90873. * \c stdin.
  90874. *
  90875. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  90876. * and is not seekable (i.e. no seek callback was provided or the seek
  90877. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  90878. * is the duty of the client to start feeding data from the beginning of
  90879. * the stream on the next FLAC__stream_decoder_process() or
  90880. * FLAC__stream_decoder_process_interleaved() call.
  90881. *
  90882. * \param decoder A decoder instance.
  90883. * \assert
  90884. * \code decoder != NULL \endcode
  90885. * \retval FLAC__bool
  90886. * \c true if successful, else \c false if a memory allocation occurs
  90887. * (in which case the state will be set to
  90888. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  90889. * occurs (the state will be unchanged).
  90890. */
  90891. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  90892. /** Decode one metadata block or audio frame.
  90893. * This version instructs the decoder to decode a either a single metadata
  90894. * block or a single frame and stop, unless the callbacks return a fatal
  90895. * error or the read callback returns
  90896. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90897. *
  90898. * As the decoder needs more input it will call the read callback.
  90899. * Depending on what was decoded, the metadata or write callback will be
  90900. * called with the decoded metadata block or audio frame.
  90901. *
  90902. * Unless there is a fatal read error or end of stream, this function
  90903. * will return once one whole frame is decoded. In other words, if the
  90904. * stream is not synchronized or points to a corrupt frame header, the
  90905. * decoder will continue to try and resync until it gets to a valid
  90906. * frame, then decode one frame, then return. If the decoder points to
  90907. * a frame whose frame CRC in the frame footer does not match the
  90908. * computed frame CRC, this function will issue a
  90909. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  90910. * error callback, and return, having decoded one complete, although
  90911. * corrupt, frame. (Such corrupted frames are sent as silence of the
  90912. * correct length to the write callback.)
  90913. *
  90914. * \param decoder An initialized decoder instance.
  90915. * \assert
  90916. * \code decoder != NULL \endcode
  90917. * \retval FLAC__bool
  90918. * \c false if any fatal read, write, or memory allocation error
  90919. * occurred (meaning decoding must stop), else \c true; for more
  90920. * information about the decoder, check the decoder state with
  90921. * FLAC__stream_decoder_get_state().
  90922. */
  90923. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  90924. /** Decode until the end of the metadata.
  90925. * This version instructs the decoder to decode from the current position
  90926. * and continue until all the metadata has been read, or until the
  90927. * callbacks return a fatal error or the read callback returns
  90928. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90929. *
  90930. * As the decoder needs more input it will call the read callback.
  90931. * As each metadata block is decoded, the metadata callback will be called
  90932. * with the decoded metadata.
  90933. *
  90934. * \param decoder An initialized decoder instance.
  90935. * \assert
  90936. * \code decoder != NULL \endcode
  90937. * \retval FLAC__bool
  90938. * \c false if any fatal read, write, or memory allocation error
  90939. * occurred (meaning decoding must stop), else \c true; for more
  90940. * information about the decoder, check the decoder state with
  90941. * FLAC__stream_decoder_get_state().
  90942. */
  90943. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  90944. /** Decode until the end of the stream.
  90945. * This version instructs the decoder to decode from the current position
  90946. * and continue until the end of stream (the read callback returns
  90947. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  90948. * callbacks return a fatal error.
  90949. *
  90950. * As the decoder needs more input it will call the read callback.
  90951. * As each metadata block and frame is decoded, the metadata or write
  90952. * callback will be called with the decoded metadata or frame.
  90953. *
  90954. * \param decoder An initialized decoder instance.
  90955. * \assert
  90956. * \code decoder != NULL \endcode
  90957. * \retval FLAC__bool
  90958. * \c false if any fatal read, write, or memory allocation error
  90959. * occurred (meaning decoding must stop), else \c true; for more
  90960. * information about the decoder, check the decoder state with
  90961. * FLAC__stream_decoder_get_state().
  90962. */
  90963. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  90964. /** Skip one audio frame.
  90965. * This version instructs the decoder to 'skip' a single frame and stop,
  90966. * unless the callbacks return a fatal error or the read callback returns
  90967. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  90968. *
  90969. * The decoding flow is the same as what occurs when
  90970. * FLAC__stream_decoder_process_single() is called to process an audio
  90971. * frame, except that this function does not decode the parsed data into
  90972. * PCM or call the write callback. The integrity of the frame is still
  90973. * checked the same way as in the other process functions.
  90974. *
  90975. * This function will return once one whole frame is skipped, in the
  90976. * same way that FLAC__stream_decoder_process_single() will return once
  90977. * one whole frame is decoded.
  90978. *
  90979. * This function can be used in more quickly determining FLAC frame
  90980. * boundaries when decoding of the actual data is not needed, for
  90981. * example when an application is separating a FLAC stream into frames
  90982. * for editing or storing in a container. To do this, the application
  90983. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  90984. * to the next frame, then use
  90985. * FLAC__stream_decoder_get_decode_position() to find the new frame
  90986. * boundary.
  90987. *
  90988. * This function should only be called when the stream has advanced
  90989. * past all the metadata, otherwise it will return \c false.
  90990. *
  90991. * \param decoder An initialized decoder instance not in a metadata
  90992. * state.
  90993. * \assert
  90994. * \code decoder != NULL \endcode
  90995. * \retval FLAC__bool
  90996. * \c false if any fatal read, write, or memory allocation error
  90997. * occurred (meaning decoding must stop), or if the decoder
  90998. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  90999. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  91000. * information about the decoder, check the decoder state with
  91001. * FLAC__stream_decoder_get_state().
  91002. */
  91003. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  91004. /** Flush the input and seek to an absolute sample.
  91005. * Decoding will resume at the given sample. Note that because of
  91006. * this, the next write callback may contain a partial block. The
  91007. * client must support seeking the input or this function will fail
  91008. * and return \c false. Furthermore, if the decoder state is
  91009. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  91010. * with FLAC__stream_decoder_flush() or reset with
  91011. * FLAC__stream_decoder_reset() before decoding can continue.
  91012. *
  91013. * \param decoder A decoder instance.
  91014. * \param sample The target sample number to seek to.
  91015. * \assert
  91016. * \code decoder != NULL \endcode
  91017. * \retval FLAC__bool
  91018. * \c true if successful, else \c false.
  91019. */
  91020. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  91021. /* \} */
  91022. #ifdef __cplusplus
  91023. }
  91024. #endif
  91025. #endif
  91026. /*** End of inlined file: stream_decoder.h ***/
  91027. /*** Start of inlined file: stream_encoder.h ***/
  91028. #ifndef FLAC__STREAM_ENCODER_H
  91029. #define FLAC__STREAM_ENCODER_H
  91030. #include <stdio.h> /* for FILE */
  91031. #ifdef __cplusplus
  91032. extern "C" {
  91033. #endif
  91034. /** \file include/FLAC/stream_encoder.h
  91035. *
  91036. * \brief
  91037. * This module contains the functions which implement the stream
  91038. * encoder.
  91039. *
  91040. * See the detailed documentation in the
  91041. * \link flac_stream_encoder stream encoder \endlink module.
  91042. */
  91043. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  91044. * \ingroup flac
  91045. *
  91046. * \brief
  91047. * This module describes the encoder layers provided by libFLAC.
  91048. *
  91049. * The stream encoder can be used to encode complete streams either to the
  91050. * client via callbacks, or directly to a file, depending on how it is
  91051. * initialized. When encoding via callbacks, the client provides a write
  91052. * callback which will be called whenever FLAC data is ready to be written.
  91053. * If the client also supplies a seek callback, the encoder will also
  91054. * automatically handle the writing back of metadata discovered while
  91055. * encoding, like stream info, seek points offsets, etc. When encoding to
  91056. * a file, the client needs only supply a filename or open \c FILE* and an
  91057. * optional progress callback for periodic notification of progress; the
  91058. * write and seek callbacks are supplied internally. For more info see the
  91059. * \link flac_stream_encoder stream encoder \endlink module.
  91060. */
  91061. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  91062. * \ingroup flac_encoder
  91063. *
  91064. * \brief
  91065. * This module contains the functions which implement the stream
  91066. * encoder.
  91067. *
  91068. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  91069. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  91070. *
  91071. * The basic usage of this encoder is as follows:
  91072. * - The program creates an instance of an encoder using
  91073. * FLAC__stream_encoder_new().
  91074. * - The program overrides the default settings using
  91075. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  91076. * functions should be called:
  91077. * - FLAC__stream_encoder_set_channels()
  91078. * - FLAC__stream_encoder_set_bits_per_sample()
  91079. * - FLAC__stream_encoder_set_sample_rate()
  91080. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  91081. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  91082. * - If the application wants to control the compression level or set its own
  91083. * metadata, then the following should also be called:
  91084. * - FLAC__stream_encoder_set_compression_level()
  91085. * - FLAC__stream_encoder_set_verify()
  91086. * - FLAC__stream_encoder_set_metadata()
  91087. * - The rest of the set functions should only be called if the client needs
  91088. * exact control over how the audio is compressed; thorough understanding
  91089. * of the FLAC format is necessary to achieve good results.
  91090. * - The program initializes the instance to validate the settings and
  91091. * prepare for encoding using
  91092. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  91093. * or FLAC__stream_encoder_init_file() for native FLAC
  91094. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  91095. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  91096. * - The program calls FLAC__stream_encoder_process() or
  91097. * FLAC__stream_encoder_process_interleaved() to encode data, which
  91098. * subsequently calls the callbacks when there is encoder data ready
  91099. * to be written.
  91100. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  91101. * which causes the encoder to encode any data still in its input pipe,
  91102. * update the metadata with the final encoding statistics if output
  91103. * seeking is possible, and finally reset the encoder to the
  91104. * uninitialized state.
  91105. * - The instance may be used again or deleted with
  91106. * FLAC__stream_encoder_delete().
  91107. *
  91108. * In more detail, the stream encoder functions similarly to the
  91109. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  91110. * callbacks and more options. Typically the client will create a new
  91111. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  91112. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  91113. * calling one of the FLAC__stream_encoder_init_*() functions.
  91114. *
  91115. * Unlike the decoders, the stream encoder has many options that can
  91116. * affect the speed and compression ratio. When setting these parameters
  91117. * you should have some basic knowledge of the format (see the
  91118. * <A HREF="../documentation.html#format">user-level documentation</A>
  91119. * or the <A HREF="../format.html">formal description</A>). The
  91120. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  91121. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  91122. * functions will do this, so make sure to pay attention to the state
  91123. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  91124. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  91125. * before FLAC__stream_encoder_init_*() will take on the defaults from
  91126. * the constructor.
  91127. *
  91128. * There are three initialization functions for native FLAC, one for
  91129. * setting up the encoder to encode FLAC data to the client via
  91130. * callbacks, and two for encoding directly to a file.
  91131. *
  91132. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  91133. * You must also supply a write callback which will be called anytime
  91134. * there is raw encoded data to write. If the client can seek the output
  91135. * it is best to also supply seek and tell callbacks, as this allows the
  91136. * encoder to go back after encoding is finished to write back
  91137. * information that was collected while encoding, like seek point offsets,
  91138. * frame sizes, etc.
  91139. *
  91140. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  91141. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  91142. * filename or open \c FILE*; the encoder will handle all the callbacks
  91143. * internally. You may also supply a progress callback for periodic
  91144. * notification of the encoding progress.
  91145. *
  91146. * There are three similarly-named init functions for encoding to Ogg
  91147. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  91148. * library has been built with Ogg support.
  91149. *
  91150. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  91151. * call the write callback several times, once with the \c fLaC signature,
  91152. * and once for each encoded metadata block. Note that for Ogg FLAC
  91153. * encoding you will usually get at least twice the number of callbacks than
  91154. * with native FLAC, one for the Ogg page header and one for the page body.
  91155. *
  91156. * After initializing the instance, the client may feed audio data to the
  91157. * encoder in one of two ways:
  91158. *
  91159. * - Channel separate, through FLAC__stream_encoder_process() - The client
  91160. * will pass an array of pointers to buffers, one for each channel, to
  91161. * the encoder, each of the same length. The samples need not be
  91162. * block-aligned, but each channel should have the same number of samples.
  91163. * - Channel interleaved, through
  91164. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  91165. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  91166. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  91167. * Again, the samples need not be block-aligned but they must be
  91168. * sample-aligned, i.e. the first value should be channel0_sample0 and
  91169. * the last value channelN_sampleM.
  91170. *
  91171. * Note that for either process call, each sample in the buffers should be a
  91172. * signed integer, right-justified to the resolution set by
  91173. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  91174. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  91175. *
  91176. * When the client is finished encoding data, it calls
  91177. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  91178. * data still in its input pipe, and call the metadata callback with the
  91179. * final encoding statistics. Then the instance may be deleted with
  91180. * FLAC__stream_encoder_delete() or initialized again to encode another
  91181. * stream.
  91182. *
  91183. * For programs that write their own metadata, but that do not know the
  91184. * actual metadata until after encoding, it is advantageous to instruct
  91185. * the encoder to write a PADDING block of the correct size, so that
  91186. * instead of rewriting the whole stream after encoding, the program can
  91187. * just overwrite the PADDING block. If only the maximum size of the
  91188. * metadata is known, the program can write a slightly larger padding
  91189. * block, then split it after encoding.
  91190. *
  91191. * Make sure you understand how lengths are calculated. All FLAC metadata
  91192. * blocks have a 4 byte header which contains the type and length. This
  91193. * length does not include the 4 bytes of the header. See the format page
  91194. * for the specification of metadata blocks and their lengths.
  91195. *
  91196. * \note
  91197. * If you are writing the FLAC data to a file via callbacks, make sure it
  91198. * is open for update (e.g. mode "w+" for stdio streams). This is because
  91199. * after the first encoding pass, the encoder will try to seek back to the
  91200. * beginning of the stream, to the STREAMINFO block, to write some data
  91201. * there. (If using FLAC__stream_encoder_init*_file() or
  91202. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  91203. *
  91204. * \note
  91205. * The "set" functions may only be called when the encoder is in the
  91206. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  91207. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  91208. * before FLAC__stream_encoder_init_*(). If this is the case they will
  91209. * return \c true, otherwise \c false.
  91210. *
  91211. * \note
  91212. * FLAC__stream_encoder_finish() resets all settings to the constructor
  91213. * defaults.
  91214. *
  91215. * \{
  91216. */
  91217. /** State values for a FLAC__StreamEncoder.
  91218. *
  91219. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  91220. *
  91221. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  91222. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  91223. * must be deleted with FLAC__stream_encoder_delete().
  91224. */
  91225. typedef enum {
  91226. FLAC__STREAM_ENCODER_OK = 0,
  91227. /**< The encoder is in the normal OK state and samples can be processed. */
  91228. FLAC__STREAM_ENCODER_UNINITIALIZED,
  91229. /**< The encoder is in the uninitialized state; one of the
  91230. * FLAC__stream_encoder_init_*() functions must be called before samples
  91231. * can be processed.
  91232. */
  91233. FLAC__STREAM_ENCODER_OGG_ERROR,
  91234. /**< An error occurred in the underlying Ogg layer. */
  91235. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  91236. /**< An error occurred in the underlying verify stream decoder;
  91237. * check FLAC__stream_encoder_get_verify_decoder_state().
  91238. */
  91239. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  91240. /**< The verify decoder detected a mismatch between the original
  91241. * audio signal and the decoded audio signal.
  91242. */
  91243. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  91244. /**< One of the callbacks returned a fatal error. */
  91245. FLAC__STREAM_ENCODER_IO_ERROR,
  91246. /**< An I/O error occurred while opening/reading/writing a file.
  91247. * Check \c errno.
  91248. */
  91249. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  91250. /**< An error occurred while writing the stream; usually, the
  91251. * write_callback returned an error.
  91252. */
  91253. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  91254. /**< Memory allocation failed. */
  91255. } FLAC__StreamEncoderState;
  91256. /** Maps a FLAC__StreamEncoderState to a C string.
  91257. *
  91258. * Using a FLAC__StreamEncoderState as the index to this array
  91259. * will give the string equivalent. The contents should not be modified.
  91260. */
  91261. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  91262. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  91263. */
  91264. typedef enum {
  91265. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  91266. /**< Initialization was successful. */
  91267. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  91268. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  91269. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  91270. /**< The library was not compiled with support for the given container
  91271. * format.
  91272. */
  91273. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  91274. /**< A required callback was not supplied. */
  91275. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  91276. /**< The encoder has an invalid setting for number of channels. */
  91277. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  91278. /**< The encoder has an invalid setting for bits-per-sample.
  91279. * FLAC supports 4-32 bps but the reference encoder currently supports
  91280. * only up to 24 bps.
  91281. */
  91282. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  91283. /**< The encoder has an invalid setting for the input sample rate. */
  91284. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  91285. /**< The encoder has an invalid setting for the block size. */
  91286. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  91287. /**< The encoder has an invalid setting for the maximum LPC order. */
  91288. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  91289. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  91290. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  91291. /**< The specified block size is less than the maximum LPC order. */
  91292. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  91293. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  91294. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  91295. /**< The metadata input to the encoder is invalid, in one of the following ways:
  91296. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  91297. * - One of the metadata blocks contains an undefined type
  91298. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  91299. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  91300. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  91301. */
  91302. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  91303. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  91304. * already initialized, usually because
  91305. * FLAC__stream_encoder_finish() was not called.
  91306. */
  91307. } FLAC__StreamEncoderInitStatus;
  91308. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  91309. *
  91310. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  91311. * will give the string equivalent. The contents should not be modified.
  91312. */
  91313. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  91314. /** Return values for the FLAC__StreamEncoder read callback.
  91315. */
  91316. typedef enum {
  91317. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  91318. /**< The read was OK and decoding can continue. */
  91319. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  91320. /**< The read was attempted at the end of the stream. */
  91321. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  91322. /**< An unrecoverable error occurred. */
  91323. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  91324. /**< Client does not support reading back from the output. */
  91325. } FLAC__StreamEncoderReadStatus;
  91326. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  91327. *
  91328. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  91329. * will give the string equivalent. The contents should not be modified.
  91330. */
  91331. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  91332. /** Return values for the FLAC__StreamEncoder write callback.
  91333. */
  91334. typedef enum {
  91335. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  91336. /**< The write was OK and encoding can continue. */
  91337. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  91338. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  91339. } FLAC__StreamEncoderWriteStatus;
  91340. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  91341. *
  91342. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  91343. * will give the string equivalent. The contents should not be modified.
  91344. */
  91345. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  91346. /** Return values for the FLAC__StreamEncoder seek callback.
  91347. */
  91348. typedef enum {
  91349. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  91350. /**< The seek was OK and encoding can continue. */
  91351. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  91352. /**< An unrecoverable error occurred. */
  91353. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  91354. /**< Client does not support seeking. */
  91355. } FLAC__StreamEncoderSeekStatus;
  91356. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  91357. *
  91358. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  91359. * will give the string equivalent. The contents should not be modified.
  91360. */
  91361. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  91362. /** Return values for the FLAC__StreamEncoder tell callback.
  91363. */
  91364. typedef enum {
  91365. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  91366. /**< The tell was OK and encoding can continue. */
  91367. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  91368. /**< An unrecoverable error occurred. */
  91369. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  91370. /**< Client does not support seeking. */
  91371. } FLAC__StreamEncoderTellStatus;
  91372. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  91373. *
  91374. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  91375. * will give the string equivalent. The contents should not be modified.
  91376. */
  91377. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  91378. /***********************************************************************
  91379. *
  91380. * class FLAC__StreamEncoder
  91381. *
  91382. ***********************************************************************/
  91383. struct FLAC__StreamEncoderProtected;
  91384. struct FLAC__StreamEncoderPrivate;
  91385. /** The opaque structure definition for the stream encoder type.
  91386. * See the \link flac_stream_encoder stream encoder module \endlink
  91387. * for a detailed description.
  91388. */
  91389. typedef struct {
  91390. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  91391. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  91392. } FLAC__StreamEncoder;
  91393. /** Signature for the read callback.
  91394. *
  91395. * A function pointer matching this signature must be passed to
  91396. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  91397. * The supplied function will be called when the encoder needs to read back
  91398. * encoded data. This happens during the metadata callback, when the encoder
  91399. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  91400. * while encoding. The address of the buffer to be filled is supplied, along
  91401. * with the number of bytes the buffer can hold. The callback may choose to
  91402. * supply less data and modify the byte count but must be careful not to
  91403. * overflow the buffer. The callback then returns a status code chosen from
  91404. * FLAC__StreamEncoderReadStatus.
  91405. *
  91406. * Here is an example of a read callback for stdio streams:
  91407. * \code
  91408. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  91409. * {
  91410. * FILE *file = ((MyClientData*)client_data)->file;
  91411. * if(*bytes > 0) {
  91412. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  91413. * if(ferror(file))
  91414. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91415. * else if(*bytes == 0)
  91416. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  91417. * else
  91418. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  91419. * }
  91420. * else
  91421. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  91422. * }
  91423. * \endcode
  91424. *
  91425. * \note In general, FLAC__StreamEncoder functions which change the
  91426. * state should not be called on the \a encoder while in the callback.
  91427. *
  91428. * \param encoder The encoder instance calling the callback.
  91429. * \param buffer A pointer to a location for the callee to store
  91430. * data to be encoded.
  91431. * \param bytes A pointer to the size of the buffer. On entry
  91432. * to the callback, it contains the maximum number
  91433. * of bytes that may be stored in \a buffer. The
  91434. * callee must set it to the actual number of bytes
  91435. * stored (0 in case of error or end-of-stream) before
  91436. * returning.
  91437. * \param client_data The callee's client data set through
  91438. * FLAC__stream_encoder_set_client_data().
  91439. * \retval FLAC__StreamEncoderReadStatus
  91440. * The callee's return status.
  91441. */
  91442. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  91443. /** Signature for the write callback.
  91444. *
  91445. * A function pointer matching this signature must be passed to
  91446. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91447. * by the encoder anytime there is raw encoded data ready to write. It may
  91448. * include metadata mixed with encoded audio frames and the data is not
  91449. * guaranteed to be aligned on frame or metadata block boundaries.
  91450. *
  91451. * The only duty of the callback is to write out the \a bytes worth of data
  91452. * in \a buffer to the current position in the output stream. The arguments
  91453. * \a samples and \a current_frame are purely informational. If \a samples
  91454. * is greater than \c 0, then \a current_frame will hold the current frame
  91455. * number that is being written; otherwise it indicates that the write
  91456. * callback is being called to write metadata.
  91457. *
  91458. * \note
  91459. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  91460. * write callback will be called twice when writing each audio
  91461. * frame; once for the page header, and once for the page body.
  91462. * When writing the page header, the \a samples argument to the
  91463. * write callback will be \c 0.
  91464. *
  91465. * \note In general, FLAC__StreamEncoder functions which change the
  91466. * state should not be called on the \a encoder while in the callback.
  91467. *
  91468. * \param encoder The encoder instance calling the callback.
  91469. * \param buffer An array of encoded data of length \a bytes.
  91470. * \param bytes The byte length of \a buffer.
  91471. * \param samples The number of samples encoded by \a buffer.
  91472. * \c 0 has a special meaning; see above.
  91473. * \param current_frame The number of the current frame being encoded.
  91474. * \param client_data The callee's client data set through
  91475. * FLAC__stream_encoder_init_*().
  91476. * \retval FLAC__StreamEncoderWriteStatus
  91477. * The callee's return status.
  91478. */
  91479. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  91480. /** Signature for the seek callback.
  91481. *
  91482. * A function pointer matching this signature may be passed to
  91483. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91484. * when the encoder needs to seek the output stream. The encoder will pass
  91485. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  91486. *
  91487. * Here is an example of a seek callback for stdio streams:
  91488. * \code
  91489. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  91490. * {
  91491. * FILE *file = ((MyClientData*)client_data)->file;
  91492. * if(file == stdin)
  91493. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  91494. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  91495. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  91496. * else
  91497. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  91498. * }
  91499. * \endcode
  91500. *
  91501. * \note In general, FLAC__StreamEncoder functions which change the
  91502. * state should not be called on the \a encoder while in the callback.
  91503. *
  91504. * \param encoder The encoder instance calling the callback.
  91505. * \param absolute_byte_offset The offset from the beginning of the stream
  91506. * to seek to.
  91507. * \param client_data The callee's client data set through
  91508. * FLAC__stream_encoder_init_*().
  91509. * \retval FLAC__StreamEncoderSeekStatus
  91510. * The callee's return status.
  91511. */
  91512. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  91513. /** Signature for the tell callback.
  91514. *
  91515. * A function pointer matching this signature may be passed to
  91516. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91517. * when the encoder needs to know the current position of the output stream.
  91518. *
  91519. * \warning
  91520. * The callback must return the true current byte offset of the output to
  91521. * which the encoder is writing. If you are buffering the output, make
  91522. * sure and take this into account. If you are writing directly to a
  91523. * FILE* from your write callback, ftell() is sufficient. If you are
  91524. * writing directly to a file descriptor from your write callback, you
  91525. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  91526. * these points to rewrite metadata after encoding.
  91527. *
  91528. * Here is an example of a tell callback for stdio streams:
  91529. * \code
  91530. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  91531. * {
  91532. * FILE *file = ((MyClientData*)client_data)->file;
  91533. * off_t pos;
  91534. * if(file == stdin)
  91535. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  91536. * else if((pos = ftello(file)) < 0)
  91537. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  91538. * else {
  91539. * *absolute_byte_offset = (FLAC__uint64)pos;
  91540. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  91541. * }
  91542. * }
  91543. * \endcode
  91544. *
  91545. * \note In general, FLAC__StreamEncoder functions which change the
  91546. * state should not be called on the \a encoder while in the callback.
  91547. *
  91548. * \param encoder The encoder instance calling the callback.
  91549. * \param absolute_byte_offset The address at which to store the current
  91550. * position of the output.
  91551. * \param client_data The callee's client data set through
  91552. * FLAC__stream_encoder_init_*().
  91553. * \retval FLAC__StreamEncoderTellStatus
  91554. * The callee's return status.
  91555. */
  91556. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  91557. /** Signature for the metadata callback.
  91558. *
  91559. * A function pointer matching this signature may be passed to
  91560. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  91561. * once at the end of encoding with the populated STREAMINFO structure. This
  91562. * is so the client can seek back to the beginning of the file and write the
  91563. * STREAMINFO block with the correct statistics after encoding (like
  91564. * minimum/maximum frame size and total samples).
  91565. *
  91566. * \note In general, FLAC__StreamEncoder functions which change the
  91567. * state should not be called on the \a encoder while in the callback.
  91568. *
  91569. * \param encoder The encoder instance calling the callback.
  91570. * \param metadata The final populated STREAMINFO block.
  91571. * \param client_data The callee's client data set through
  91572. * FLAC__stream_encoder_init_*().
  91573. */
  91574. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  91575. /** Signature for the progress callback.
  91576. *
  91577. * A function pointer matching this signature may be passed to
  91578. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  91579. * The supplied function will be called when the encoder has finished
  91580. * writing a frame. The \c total_frames_estimate argument to the
  91581. * callback will be based on the value from
  91582. * FLAC__stream_encoder_set_total_samples_estimate().
  91583. *
  91584. * \note In general, FLAC__StreamEncoder functions which change the
  91585. * state should not be called on the \a encoder while in the callback.
  91586. *
  91587. * \param encoder The encoder instance calling the callback.
  91588. * \param bytes_written Bytes written so far.
  91589. * \param samples_written Samples written so far.
  91590. * \param frames_written Frames written so far.
  91591. * \param total_frames_estimate The estimate of the total number of
  91592. * frames to be written.
  91593. * \param client_data The callee's client data set through
  91594. * FLAC__stream_encoder_init_*().
  91595. */
  91596. 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);
  91597. /***********************************************************************
  91598. *
  91599. * Class constructor/destructor
  91600. *
  91601. ***********************************************************************/
  91602. /** Create a new stream encoder instance. The instance is created with
  91603. * default settings; see the individual FLAC__stream_encoder_set_*()
  91604. * functions for each setting's default.
  91605. *
  91606. * \retval FLAC__StreamEncoder*
  91607. * \c NULL if there was an error allocating memory, else the new instance.
  91608. */
  91609. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  91610. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  91611. *
  91612. * \param encoder A pointer to an existing encoder.
  91613. * \assert
  91614. * \code encoder != NULL \endcode
  91615. */
  91616. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  91617. /***********************************************************************
  91618. *
  91619. * Public class method prototypes
  91620. *
  91621. ***********************************************************************/
  91622. /** Set the serial number for the FLAC stream to use in the Ogg container.
  91623. *
  91624. * \note
  91625. * This does not need to be set for native FLAC encoding.
  91626. *
  91627. * \note
  91628. * It is recommended to set a serial number explicitly as the default of '0'
  91629. * may collide with other streams.
  91630. *
  91631. * \default \c 0
  91632. * \param encoder An encoder instance to set.
  91633. * \param serial_number 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_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  91640. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  91641. * encoded output by feeding it through an internal decoder and comparing
  91642. * the original signal against the decoded signal. If a mismatch occurs,
  91643. * the process call will return \c false. Note that this will slow the
  91644. * encoding process by the extra time required for decoding and comparison.
  91645. *
  91646. * \default \c false
  91647. * \param encoder An encoder instance to set.
  91648. * \param value Flag value (see above).
  91649. * \assert
  91650. * \code encoder != NULL \endcode
  91651. * \retval FLAC__bool
  91652. * \c false if the encoder is already initialized, else \c true.
  91653. */
  91654. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91655. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  91656. * the encoder will comply with the Subset and will check the
  91657. * settings during FLAC__stream_encoder_init_*() to see if all settings
  91658. * comply. If \c false, the settings may take advantage of the full
  91659. * range that the format allows.
  91660. *
  91661. * Make sure you know what it entails before setting this to \c false.
  91662. *
  91663. * \default \c true
  91664. * \param encoder An encoder instance to set.
  91665. * \param value Flag value (see above).
  91666. * \assert
  91667. * \code encoder != NULL \endcode
  91668. * \retval FLAC__bool
  91669. * \c false if the encoder is already initialized, else \c true.
  91670. */
  91671. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91672. /** Set the number of channels to be encoded.
  91673. *
  91674. * \default \c 2
  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_channels(FLAC__StreamEncoder *encoder, unsigned value);
  91683. /** Set the sample resolution of the input to be encoded.
  91684. *
  91685. * \warning
  91686. * Do not feed the encoder data that is wider than the value you
  91687. * set here or you will generate an invalid stream.
  91688. *
  91689. * \default \c 16
  91690. * \param encoder An encoder instance to set.
  91691. * \param value See above.
  91692. * \assert
  91693. * \code encoder != NULL \endcode
  91694. * \retval FLAC__bool
  91695. * \c false if the encoder is already initialized, else \c true.
  91696. */
  91697. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  91698. /** Set the sample rate (in Hz) of the input to be encoded.
  91699. *
  91700. * \default \c 44100
  91701. * \param encoder An encoder instance to set.
  91702. * \param value See above.
  91703. * \assert
  91704. * \code encoder != NULL \endcode
  91705. * \retval FLAC__bool
  91706. * \c false if the encoder is already initialized, else \c true.
  91707. */
  91708. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  91709. /** Set the compression level
  91710. *
  91711. * The compression level is roughly proportional to the amount of effort
  91712. * the encoder expends to compress the file. A higher level usually
  91713. * means more computation but higher compression. The default level is
  91714. * suitable for most applications.
  91715. *
  91716. * Currently the levels range from \c 0 (fastest, least compression) to
  91717. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  91718. * treated as \c 8.
  91719. *
  91720. * This function automatically calls the following other \c _set_
  91721. * functions with appropriate values, so the client does not need to
  91722. * unless it specifically wants to override them:
  91723. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  91724. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  91725. * - FLAC__stream_encoder_set_apodization()
  91726. * - FLAC__stream_encoder_set_max_lpc_order()
  91727. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  91728. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  91729. * - FLAC__stream_encoder_set_do_escape_coding()
  91730. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  91731. * - FLAC__stream_encoder_set_min_residual_partition_order()
  91732. * - FLAC__stream_encoder_set_max_residual_partition_order()
  91733. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  91734. *
  91735. * The actual values set for each level are:
  91736. * <table>
  91737. * <tr>
  91738. * <td><b>level</b><td>
  91739. * <td>do mid-side stereo<td>
  91740. * <td>loose mid-side stereo<td>
  91741. * <td>apodization<td>
  91742. * <td>max lpc order<td>
  91743. * <td>qlp coeff precision<td>
  91744. * <td>qlp coeff prec search<td>
  91745. * <td>escape coding<td>
  91746. * <td>exhaustive model search<td>
  91747. * <td>min residual partition order<td>
  91748. * <td>max residual partition order<td>
  91749. * <td>rice parameter search dist<td>
  91750. * </tr>
  91751. * <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>
  91752. * <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>
  91753. * <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>
  91754. * <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>
  91755. * <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>
  91756. * <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>
  91757. * <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>
  91758. * <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>
  91759. * <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>
  91760. * </table>
  91761. *
  91762. * \default \c 5
  91763. * \param encoder An encoder instance to set.
  91764. * \param value See above.
  91765. * \assert
  91766. * \code encoder != NULL \endcode
  91767. * \retval FLAC__bool
  91768. * \c false if the encoder is already initialized, else \c true.
  91769. */
  91770. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  91771. /** Set the blocksize to use while encoding.
  91772. *
  91773. * The number of samples to use per frame. Use \c 0 to let the encoder
  91774. * estimate a blocksize; this is usually best.
  91775. *
  91776. * \default \c 0
  91777. * \param encoder An encoder instance to set.
  91778. * \param value See above.
  91779. * \assert
  91780. * \code encoder != NULL \endcode
  91781. * \retval FLAC__bool
  91782. * \c false if the encoder is already initialized, else \c true.
  91783. */
  91784. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  91785. /** Set to \c true to enable mid-side encoding on stereo input. The
  91786. * number of channels must be 2 for this to have any effect. Set to
  91787. * \c false to use only independent channel coding.
  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_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91798. /** Set to \c true to enable adaptive switching between mid-side and
  91799. * left-right encoding on stereo input. Set to \c false to use
  91800. * exhaustive searching. Setting this to \c true requires
  91801. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  91802. * \c true in order to have any effect.
  91803. *
  91804. * \default \c false
  91805. * \param encoder An encoder instance to set.
  91806. * \param value Flag value (see above).
  91807. * \assert
  91808. * \code encoder != NULL \endcode
  91809. * \retval FLAC__bool
  91810. * \c false if the encoder is already initialized, else \c true.
  91811. */
  91812. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91813. /** Sets the apodization function(s) the encoder will use when windowing
  91814. * audio data for LPC analysis.
  91815. *
  91816. * The \a specification is a plain ASCII string which specifies exactly
  91817. * which functions to use. There may be more than one (up to 32),
  91818. * separated by \c ';' characters. Some functions take one or more
  91819. * comma-separated arguments in parentheses.
  91820. *
  91821. * The available functions are \c bartlett, \c bartlett_hann,
  91822. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  91823. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  91824. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  91825. *
  91826. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  91827. * (0<STDDEV<=0.5).
  91828. *
  91829. * For \c tukey(P), P specifies the fraction of the window that is
  91830. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  91831. * corresponds to \c hann.
  91832. *
  91833. * Example specifications are \c "blackman" or
  91834. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  91835. *
  91836. * Any function that is specified erroneously is silently dropped. Up
  91837. * to 32 functions are kept, the rest are dropped. If the specification
  91838. * is empty the encoder defaults to \c "tukey(0.5)".
  91839. *
  91840. * When more than one function is specified, then for every subframe the
  91841. * encoder will try each of them separately and choose the window that
  91842. * results in the smallest compressed subframe.
  91843. *
  91844. * Note that each function specified causes the encoder to occupy a
  91845. * floating point array in which to store the window.
  91846. *
  91847. * \default \c "tukey(0.5)"
  91848. * \param encoder An encoder instance to set.
  91849. * \param specification See above.
  91850. * \assert
  91851. * \code encoder != NULL \endcode
  91852. * \code specification != NULL \endcode
  91853. * \retval FLAC__bool
  91854. * \c false if the encoder is already initialized, else \c true.
  91855. */
  91856. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  91857. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  91858. *
  91859. * \default \c 0
  91860. * \param encoder An encoder instance to set.
  91861. * \param value See above.
  91862. * \assert
  91863. * \code encoder != NULL \endcode
  91864. * \retval FLAC__bool
  91865. * \c false if the encoder is already initialized, else \c true.
  91866. */
  91867. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  91868. /** Set the precision, in bits, of the quantized linear predictor
  91869. * coefficients, or \c 0 to let the encoder select it based on the
  91870. * blocksize.
  91871. *
  91872. * \note
  91873. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  91874. * be less than 32.
  91875. *
  91876. * \default \c 0
  91877. * \param encoder An encoder instance to set.
  91878. * \param value See above.
  91879. * \assert
  91880. * \code encoder != NULL \endcode
  91881. * \retval FLAC__bool
  91882. * \c false if the encoder is already initialized, else \c true.
  91883. */
  91884. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  91885. /** Set to \c false to use only the specified quantized linear predictor
  91886. * coefficient precision, or \c true to search neighboring precision
  91887. * values and use the best one.
  91888. *
  91889. * \default \c false
  91890. * \param encoder An encoder instance to set.
  91891. * \param value See above.
  91892. * \assert
  91893. * \code encoder != NULL \endcode
  91894. * \retval FLAC__bool
  91895. * \c false if the encoder is already initialized, else \c true.
  91896. */
  91897. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91898. /** Deprecated. Setting this value has no effect.
  91899. *
  91900. * \default \c false
  91901. * \param encoder An encoder instance to set.
  91902. * \param value See above.
  91903. * \assert
  91904. * \code encoder != NULL \endcode
  91905. * \retval FLAC__bool
  91906. * \c false if the encoder is already initialized, else \c true.
  91907. */
  91908. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91909. /** Set to \c false to let the encoder estimate the best model order
  91910. * based on the residual signal energy, or \c true to force the
  91911. * encoder to evaluate all order models and select the best.
  91912. *
  91913. * \default \c false
  91914. * \param encoder An encoder instance to set.
  91915. * \param value See above.
  91916. * \assert
  91917. * \code encoder != NULL \endcode
  91918. * \retval FLAC__bool
  91919. * \c false if the encoder is already initialized, else \c true.
  91920. */
  91921. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  91922. /** Set the minimum partition order to search when coding the residual.
  91923. * This is used in tandem with
  91924. * FLAC__stream_encoder_set_max_residual_partition_order().
  91925. *
  91926. * The partition order determines the context size in the residual.
  91927. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91928. *
  91929. * Set both min and max values to \c 0 to force a single context,
  91930. * whose Rice parameter is based on the residual signal variance.
  91931. * Otherwise, set a min and max order, and the encoder will search
  91932. * all orders, using the mean of each context for its Rice parameter,
  91933. * and use the best.
  91934. *
  91935. * \default \c 0
  91936. * \param encoder An encoder instance to set.
  91937. * \param value See above.
  91938. * \assert
  91939. * \code encoder != NULL \endcode
  91940. * \retval FLAC__bool
  91941. * \c false if the encoder is already initialized, else \c true.
  91942. */
  91943. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91944. /** Set the maximum partition order to search when coding the residual.
  91945. * This is used in tandem with
  91946. * FLAC__stream_encoder_set_min_residual_partition_order().
  91947. *
  91948. * The partition order determines the context size in the residual.
  91949. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  91950. *
  91951. * Set both min and max values to \c 0 to force a single context,
  91952. * whose Rice parameter is based on the residual signal variance.
  91953. * Otherwise, set a min and max order, and the encoder will search
  91954. * all orders, using the mean of each context for its Rice parameter,
  91955. * and use the best.
  91956. *
  91957. * \default \c 0
  91958. * \param encoder An encoder instance to set.
  91959. * \param value See above.
  91960. * \assert
  91961. * \code encoder != NULL \endcode
  91962. * \retval FLAC__bool
  91963. * \c false if the encoder is already initialized, else \c true.
  91964. */
  91965. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  91966. /** Deprecated. Setting this value has no effect.
  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_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  91977. /** Set an estimate of the total samples that will be encoded.
  91978. * This is merely an estimate and may be set to \c 0 if unknown.
  91979. * This value will be written to the STREAMINFO block before encoding,
  91980. * and can remove the need for the caller to rewrite the value later
  91981. * if the value is known before encoding.
  91982. *
  91983. * \default \c 0
  91984. * \param encoder An encoder instance to set.
  91985. * \param value See above.
  91986. * \assert
  91987. * \code encoder != NULL \endcode
  91988. * \retval FLAC__bool
  91989. * \c false if the encoder is already initialized, else \c true.
  91990. */
  91991. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  91992. /** Set the metadata blocks to be emitted to the stream before encoding.
  91993. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  91994. * array of pointers to metadata blocks. The array is non-const since
  91995. * the encoder may need to change the \a is_last flag inside them, and
  91996. * in some cases update seek point offsets. Otherwise, the encoder will
  91997. * not modify or free the blocks. It is up to the caller to free the
  91998. * metadata blocks after encoding finishes.
  91999. *
  92000. * \note
  92001. * The encoder stores only copies of the pointers in the \a metadata array;
  92002. * the metadata blocks themselves must survive at least until after
  92003. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  92004. *
  92005. * \note
  92006. * The STREAMINFO block is always written and no STREAMINFO block may
  92007. * occur in the supplied array.
  92008. *
  92009. * \note
  92010. * By default the encoder does not create a SEEKTABLE. If one is supplied
  92011. * in the \a metadata array, but the client has specified that it does not
  92012. * support seeking, then the SEEKTABLE will be written verbatim. However
  92013. * by itself this is not very useful as the client will not know the stream
  92014. * offsets for the seekpoints ahead of time. In order to get a proper
  92015. * seektable the client must support seeking. See next note.
  92016. *
  92017. * \note
  92018. * SEEKTABLE blocks are handled specially. Since you will not know
  92019. * the values for the seek point stream offsets, you should pass in
  92020. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  92021. * required sample numbers (or placeholder points), with \c 0 for the
  92022. * \a frame_samples and \a stream_offset fields for each point. If the
  92023. * client has specified that it supports seeking by providing a seek
  92024. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  92025. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  92026. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  92027. * then while it is encoding the encoder will fill the stream offsets in
  92028. * for you and when encoding is finished, it will seek back and write the
  92029. * real values into the SEEKTABLE block in the stream. There are helper
  92030. * routines for manipulating seektable template blocks; see metadata.h:
  92031. * FLAC__metadata_object_seektable_template_*(). If the client does
  92032. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  92033. * will slow down or remove the ability to seek in the FLAC stream.
  92034. *
  92035. * \note
  92036. * The encoder instance \b will modify the first \c SEEKTABLE block
  92037. * as it transforms the template to a valid seektable while encoding,
  92038. * but it is still up to the caller to free all metadata blocks after
  92039. * encoding.
  92040. *
  92041. * \note
  92042. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  92043. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  92044. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  92045. * will simply write it's own into the stream. If no VORBIS_COMMENT
  92046. * block is present in the \a metadata array, libFLAC will write an
  92047. * empty one, containing only the vendor string.
  92048. *
  92049. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  92050. * the second metadata block of the stream. The encoder already supplies
  92051. * the STREAMINFO block automatically. If \a metadata does not contain a
  92052. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  92053. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  92054. * first, the init function will reorder \a metadata by moving the
  92055. * VORBIS_COMMENT block to the front; the relative ordering of the other
  92056. * blocks will remain as they were.
  92057. *
  92058. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  92059. * stream to \c 65535. If \a num_blocks exceeds this the function will
  92060. * return \c false.
  92061. *
  92062. * \default \c NULL, 0
  92063. * \param encoder An encoder instance to set.
  92064. * \param metadata See above.
  92065. * \param num_blocks See above.
  92066. * \assert
  92067. * \code encoder != NULL \endcode
  92068. * \retval FLAC__bool
  92069. * \c false if the encoder is already initialized, else \c true.
  92070. * \c false if the encoder is already initialized, or if
  92071. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  92072. */
  92073. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  92074. /** Get the current encoder state.
  92075. *
  92076. * \param encoder An encoder instance to query.
  92077. * \assert
  92078. * \code encoder != NULL \endcode
  92079. * \retval FLAC__StreamEncoderState
  92080. * The current encoder state.
  92081. */
  92082. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  92083. /** Get the state of the verify stream decoder.
  92084. * Useful when the stream encoder state is
  92085. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  92086. *
  92087. * \param encoder An encoder instance to query.
  92088. * \assert
  92089. * \code encoder != NULL \endcode
  92090. * \retval FLAC__StreamDecoderState
  92091. * The verify stream decoder state.
  92092. */
  92093. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  92094. /** Get the current encoder state as a C string.
  92095. * This version automatically resolves
  92096. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  92097. * verify decoder's state.
  92098. *
  92099. * \param encoder A encoder instance to query.
  92100. * \assert
  92101. * \code encoder != NULL \endcode
  92102. * \retval const char *
  92103. * The encoder state as a C string. Do not modify the contents.
  92104. */
  92105. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  92106. /** Get relevant values about the nature of a verify decoder error.
  92107. * Useful when the stream encoder state is
  92108. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  92109. * be addresses in which the stats will be returned, or NULL if value
  92110. * is not desired.
  92111. *
  92112. * \param encoder An encoder instance to query.
  92113. * \param absolute_sample The absolute sample number of the mismatch.
  92114. * \param frame_number The number of the frame in which the mismatch occurred.
  92115. * \param channel The channel in which the mismatch occurred.
  92116. * \param sample The number of the sample (relative to the frame) in
  92117. * which the mismatch occurred.
  92118. * \param expected The expected value for the sample in question.
  92119. * \param got The actual value returned by the decoder.
  92120. * \assert
  92121. * \code encoder != NULL \endcode
  92122. */
  92123. 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);
  92124. /** Get the "verify" flag.
  92125. *
  92126. * \param encoder An encoder instance to query.
  92127. * \assert
  92128. * \code encoder != NULL \endcode
  92129. * \retval FLAC__bool
  92130. * See FLAC__stream_encoder_set_verify().
  92131. */
  92132. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  92133. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  92134. *
  92135. * \param encoder An encoder instance to query.
  92136. * \assert
  92137. * \code encoder != NULL \endcode
  92138. * \retval FLAC__bool
  92139. * See FLAC__stream_encoder_set_streamable_subset().
  92140. */
  92141. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  92142. /** Get the number of input channels being processed.
  92143. *
  92144. * \param encoder An encoder instance to query.
  92145. * \assert
  92146. * \code encoder != NULL \endcode
  92147. * \retval unsigned
  92148. * See FLAC__stream_encoder_set_channels().
  92149. */
  92150. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  92151. /** Get the input sample resolution setting.
  92152. *
  92153. * \param encoder An encoder instance to query.
  92154. * \assert
  92155. * \code encoder != NULL \endcode
  92156. * \retval unsigned
  92157. * See FLAC__stream_encoder_set_bits_per_sample().
  92158. */
  92159. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  92160. /** Get the input sample rate setting.
  92161. *
  92162. * \param encoder An encoder instance to query.
  92163. * \assert
  92164. * \code encoder != NULL \endcode
  92165. * \retval unsigned
  92166. * See FLAC__stream_encoder_set_sample_rate().
  92167. */
  92168. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  92169. /** Get the blocksize setting.
  92170. *
  92171. * \param encoder An encoder instance to query.
  92172. * \assert
  92173. * \code encoder != NULL \endcode
  92174. * \retval unsigned
  92175. * See FLAC__stream_encoder_set_blocksize().
  92176. */
  92177. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  92178. /** Get the "mid/side stereo coding" flag.
  92179. *
  92180. * \param encoder An encoder instance to query.
  92181. * \assert
  92182. * \code encoder != NULL \endcode
  92183. * \retval FLAC__bool
  92184. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  92185. */
  92186. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92187. /** Get the "adaptive mid/side switching" flag.
  92188. *
  92189. * \param encoder An encoder instance to query.
  92190. * \assert
  92191. * \code encoder != NULL \endcode
  92192. * \retval FLAC__bool
  92193. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  92194. */
  92195. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  92196. /** Get the maximum LPC order setting.
  92197. *
  92198. * \param encoder An encoder instance to query.
  92199. * \assert
  92200. * \code encoder != NULL \endcode
  92201. * \retval unsigned
  92202. * See FLAC__stream_encoder_set_max_lpc_order().
  92203. */
  92204. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  92205. /** Get the quantized linear predictor coefficient precision setting.
  92206. *
  92207. * \param encoder An encoder instance to query.
  92208. * \assert
  92209. * \code encoder != NULL \endcode
  92210. * \retval unsigned
  92211. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  92212. */
  92213. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  92214. /** Get the qlp coefficient precision search flag.
  92215. *
  92216. * \param encoder An encoder instance to query.
  92217. * \assert
  92218. * \code encoder != NULL \endcode
  92219. * \retval FLAC__bool
  92220. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  92221. */
  92222. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  92223. /** Get the "escape coding" flag.
  92224. *
  92225. * \param encoder An encoder instance to query.
  92226. * \assert
  92227. * \code encoder != NULL \endcode
  92228. * \retval FLAC__bool
  92229. * See FLAC__stream_encoder_set_do_escape_coding().
  92230. */
  92231. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  92232. /** Get the exhaustive model search flag.
  92233. *
  92234. * \param encoder An encoder instance to query.
  92235. * \assert
  92236. * \code encoder != NULL \endcode
  92237. * \retval FLAC__bool
  92238. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  92239. */
  92240. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  92241. /** Get the minimum residual partition order setting.
  92242. *
  92243. * \param encoder An encoder instance to query.
  92244. * \assert
  92245. * \code encoder != NULL \endcode
  92246. * \retval unsigned
  92247. * See FLAC__stream_encoder_set_min_residual_partition_order().
  92248. */
  92249. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92250. /** Get maximum residual partition order setting.
  92251. *
  92252. * \param encoder An encoder instance to query.
  92253. * \assert
  92254. * \code encoder != NULL \endcode
  92255. * \retval unsigned
  92256. * See FLAC__stream_encoder_set_max_residual_partition_order().
  92257. */
  92258. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  92259. /** Get the Rice parameter search distance setting.
  92260. *
  92261. * \param encoder An encoder instance to query.
  92262. * \assert
  92263. * \code encoder != NULL \endcode
  92264. * \retval unsigned
  92265. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  92266. */
  92267. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  92268. /** Get the previously set estimate of the total samples to be encoded.
  92269. * The encoder merely mimics back the value given to
  92270. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  92271. * other way of knowing how many samples the client will encode.
  92272. *
  92273. * \param encoder An encoder instance to set.
  92274. * \assert
  92275. * \code encoder != NULL \endcode
  92276. * \retval FLAC__uint64
  92277. * See FLAC__stream_encoder_get_total_samples_estimate().
  92278. */
  92279. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  92280. /** Initialize the encoder instance to encode native FLAC streams.
  92281. *
  92282. * This flavor of initialization sets up the encoder to encode to a
  92283. * native FLAC stream. I/O is performed via callbacks to the client.
  92284. * For encoding to a plain file via filename or open \c FILE*,
  92285. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  92286. * provide a simpler interface.
  92287. *
  92288. * This function should be called after FLAC__stream_encoder_new() and
  92289. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92290. * or FLAC__stream_encoder_process_interleaved().
  92291. * initialization succeeded.
  92292. *
  92293. * The call to FLAC__stream_encoder_init_stream() currently will also
  92294. * immediately call the write callback several times, once with the \c fLaC
  92295. * signature, and once for each encoded metadata block.
  92296. *
  92297. * \param encoder An uninitialized encoder instance.
  92298. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92299. * pointer must not be \c NULL.
  92300. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92301. * pointer may be \c NULL if seeking is not
  92302. * supported. The encoder uses seeking to go back
  92303. * and write some some stream statistics to the
  92304. * STREAMINFO block; this is recommended but not
  92305. * necessary to create a valid FLAC stream. If
  92306. * \a seek_callback is not \c NULL then a
  92307. * \a tell_callback must also be supplied.
  92308. * Alternatively, a dummy seek callback that just
  92309. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92310. * may also be supplied, all though this is slightly
  92311. * less efficient for the encoder.
  92312. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92313. * pointer may be \c NULL if seeking is not
  92314. * supported. If \a seek_callback is \c NULL then
  92315. * this argument will be ignored. If
  92316. * \a seek_callback is not \c NULL then a
  92317. * \a tell_callback must also be supplied.
  92318. * Alternatively, a dummy tell callback that just
  92319. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92320. * may also be supplied, all though this is slightly
  92321. * less efficient for the encoder.
  92322. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92323. * pointer may be \c NULL if the callback is not
  92324. * desired. If the client provides a seek callback,
  92325. * this function is not necessary as the encoder
  92326. * will automatically seek back and update the
  92327. * STREAMINFO block. It may also be \c NULL if the
  92328. * client does not support seeking, since it will
  92329. * have no way of going back to update the
  92330. * STREAMINFO. However the client can still supply
  92331. * a callback if it would like to know the details
  92332. * from the STREAMINFO.
  92333. * \param client_data This value will be supplied to callbacks in their
  92334. * \a client_data argument.
  92335. * \assert
  92336. * \code encoder != NULL \endcode
  92337. * \retval FLAC__StreamEncoderInitStatus
  92338. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92339. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92340. */
  92341. 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);
  92342. /** Initialize the encoder instance to encode Ogg FLAC streams.
  92343. *
  92344. * This flavor of initialization sets up the encoder to encode to a FLAC
  92345. * stream in an Ogg container. I/O is performed via callbacks to the
  92346. * client. For encoding to a plain file via filename or open \c FILE*,
  92347. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  92348. * provide a simpler interface.
  92349. *
  92350. * This function should be called after FLAC__stream_encoder_new() and
  92351. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92352. * or FLAC__stream_encoder_process_interleaved().
  92353. * initialization succeeded.
  92354. *
  92355. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  92356. * immediately call the write callback several times to write the metadata
  92357. * packets.
  92358. *
  92359. * \param encoder An uninitialized encoder instance.
  92360. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  92361. * pointer must not be \c NULL if \a seek_callback
  92362. * is non-NULL since they are both needed to be
  92363. * able to write data back to the Ogg FLAC stream
  92364. * in the post-encode phase.
  92365. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  92366. * pointer must not be \c NULL.
  92367. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  92368. * pointer may be \c NULL if seeking is not
  92369. * supported. The encoder uses seeking to go back
  92370. * and write some some stream statistics to the
  92371. * STREAMINFO block; this is recommended but not
  92372. * necessary to create a valid FLAC stream. If
  92373. * \a seek_callback is not \c NULL then a
  92374. * \a tell_callback must also be supplied.
  92375. * Alternatively, a dummy seek callback that just
  92376. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  92377. * may also be supplied, all though this is slightly
  92378. * less efficient for the encoder.
  92379. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  92380. * pointer may be \c NULL if seeking is not
  92381. * supported. If \a seek_callback is \c NULL then
  92382. * this argument will be ignored. If
  92383. * \a seek_callback is not \c NULL then a
  92384. * \a tell_callback must also be supplied.
  92385. * Alternatively, a dummy tell callback that just
  92386. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  92387. * may also be supplied, all though this is slightly
  92388. * less efficient for the encoder.
  92389. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  92390. * pointer may be \c NULL if the callback is not
  92391. * desired. If the client provides a seek callback,
  92392. * this function is not necessary as the encoder
  92393. * will automatically seek back and update the
  92394. * STREAMINFO block. It may also be \c NULL if the
  92395. * client does not support seeking, since it will
  92396. * have no way of going back to update the
  92397. * STREAMINFO. However the client can still supply
  92398. * a callback if it would like to know the details
  92399. * from the STREAMINFO.
  92400. * \param client_data This value will be supplied to callbacks in their
  92401. * \a client_data argument.
  92402. * \assert
  92403. * \code encoder != NULL \endcode
  92404. * \retval FLAC__StreamEncoderInitStatus
  92405. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92406. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92407. */
  92408. 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);
  92409. /** Initialize the encoder instance to encode native FLAC files.
  92410. *
  92411. * This flavor of initialization sets up the encoder to encode to a
  92412. * plain native FLAC file. For non-stdio streams, you must use
  92413. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  92414. *
  92415. * This function should be called after FLAC__stream_encoder_new() and
  92416. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92417. * or FLAC__stream_encoder_process_interleaved().
  92418. * initialization succeeded.
  92419. *
  92420. * \param encoder An uninitialized encoder instance.
  92421. * \param file An open file. The file should have been opened
  92422. * with mode \c "w+b" and rewound. The file
  92423. * becomes owned by the encoder and should not be
  92424. * manipulated by the client while encoding.
  92425. * Unless \a file is \c stdout, it will be closed
  92426. * when FLAC__stream_encoder_finish() is called.
  92427. * Note however that a proper SEEKTABLE cannot be
  92428. * created when encoding to \c stdout since it is
  92429. * not seekable.
  92430. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92431. * pointer may be \c NULL if the callback is not
  92432. * desired.
  92433. * \param client_data This value will be supplied to callbacks in their
  92434. * \a client_data argument.
  92435. * \assert
  92436. * \code encoder != NULL \endcode
  92437. * \code file != NULL \endcode
  92438. * \retval FLAC__StreamEncoderInitStatus
  92439. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92440. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92441. */
  92442. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92443. /** Initialize the encoder instance to encode Ogg FLAC files.
  92444. *
  92445. * This flavor of initialization sets up the encoder to encode to a
  92446. * plain Ogg FLAC file. For non-stdio streams, you must use
  92447. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  92448. *
  92449. * This function should be called after FLAC__stream_encoder_new() and
  92450. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92451. * or FLAC__stream_encoder_process_interleaved().
  92452. * initialization succeeded.
  92453. *
  92454. * \param encoder An uninitialized encoder instance.
  92455. * \param file An open file. The file should have been opened
  92456. * with mode \c "w+b" and rewound. The file
  92457. * becomes owned by the encoder and should not be
  92458. * manipulated by the client while encoding.
  92459. * Unless \a file is \c stdout, it will be closed
  92460. * when FLAC__stream_encoder_finish() is called.
  92461. * Note however that a proper SEEKTABLE cannot be
  92462. * created when encoding to \c stdout since it is
  92463. * not seekable.
  92464. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92465. * pointer may be \c NULL if the callback is not
  92466. * desired.
  92467. * \param client_data This value will be supplied to callbacks in their
  92468. * \a client_data argument.
  92469. * \assert
  92470. * \code encoder != NULL \endcode
  92471. * \code file != NULL \endcode
  92472. * \retval FLAC__StreamEncoderInitStatus
  92473. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92474. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92475. */
  92476. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92477. /** Initialize the encoder instance to encode native FLAC files.
  92478. *
  92479. * This flavor of initialization sets up the encoder to encode to a plain
  92480. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92481. * with Unicode filenames on Windows), you must use
  92482. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  92483. * and provide callbacks for the I/O.
  92484. *
  92485. * This function should be called after FLAC__stream_encoder_new() and
  92486. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92487. * or FLAC__stream_encoder_process_interleaved().
  92488. * initialization succeeded.
  92489. *
  92490. * \param encoder An uninitialized encoder instance.
  92491. * \param filename The name of the file to encode to. The file will
  92492. * be opened with fopen(). Use \c NULL to encode to
  92493. * \c stdout. Note however that a proper SEEKTABLE
  92494. * cannot be created when encoding to \c stdout since
  92495. * it is not seekable.
  92496. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92497. * pointer may be \c NULL if the callback is not
  92498. * desired.
  92499. * \param client_data This value will be supplied to callbacks in their
  92500. * \a client_data argument.
  92501. * \assert
  92502. * \code encoder != NULL \endcode
  92503. * \retval FLAC__StreamEncoderInitStatus
  92504. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92505. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92506. */
  92507. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92508. /** Initialize the encoder instance to encode Ogg FLAC files.
  92509. *
  92510. * This flavor of initialization sets up the encoder to encode to a plain
  92511. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  92512. * with Unicode filenames on Windows), you must use
  92513. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  92514. * and provide callbacks for the I/O.
  92515. *
  92516. * This function should be called after FLAC__stream_encoder_new() and
  92517. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  92518. * or FLAC__stream_encoder_process_interleaved().
  92519. * initialization succeeded.
  92520. *
  92521. * \param encoder An uninitialized encoder instance.
  92522. * \param filename The name of the file to encode to. The file will
  92523. * be opened with fopen(). Use \c NULL to encode to
  92524. * \c stdout. Note however that a proper SEEKTABLE
  92525. * cannot be created when encoding to \c stdout since
  92526. * it is not seekable.
  92527. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  92528. * pointer may be \c NULL if the callback is not
  92529. * desired.
  92530. * \param client_data This value will be supplied to callbacks in their
  92531. * \a client_data argument.
  92532. * \assert
  92533. * \code encoder != NULL \endcode
  92534. * \retval FLAC__StreamEncoderInitStatus
  92535. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  92536. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  92537. */
  92538. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  92539. /** Finish the encoding process.
  92540. * Flushes the encoding buffer, releases resources, resets the encoder
  92541. * settings to their defaults, and returns the encoder state to
  92542. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  92543. * one or more write callbacks before returning, and will generate
  92544. * a metadata callback.
  92545. *
  92546. * Note that in the course of processing the last frame, errors can
  92547. * occur, so the caller should be sure to check the return value to
  92548. * ensure the file was encoded properly.
  92549. *
  92550. * In the event of a prematurely-terminated encode, it is not strictly
  92551. * necessary to call this immediately before FLAC__stream_encoder_delete()
  92552. * but it is good practice to match every FLAC__stream_encoder_init_*()
  92553. * with a FLAC__stream_encoder_finish().
  92554. *
  92555. * \param encoder An uninitialized encoder instance.
  92556. * \assert
  92557. * \code encoder != NULL \endcode
  92558. * \retval FLAC__bool
  92559. * \c false if an error occurred processing the last frame; or if verify
  92560. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  92561. * verify mismatch; else \c true. If \c false, caller should check the
  92562. * state with FLAC__stream_encoder_get_state() for more information
  92563. * about the error.
  92564. */
  92565. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  92566. /** Submit data for encoding.
  92567. * This version allows you to supply the input data via an array of
  92568. * pointers, each pointer pointing to an array of \a samples samples
  92569. * representing one channel. The samples need not be block-aligned,
  92570. * but each channel should have the same number of samples. Each sample
  92571. * should be a signed integer, right-justified to the resolution set by
  92572. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92573. * resolution is 16 bits per sample, the samples should all be in the
  92574. * range [-32768,32767].
  92575. *
  92576. * For applications where channel order is important, channels must
  92577. * follow the order as described in the
  92578. * <A HREF="../format.html#frame_header">frame header</A>.
  92579. *
  92580. * \param encoder An initialized encoder instance in the OK state.
  92581. * \param buffer An array of pointers to each channel's signal.
  92582. * \param samples The number of samples in one channel.
  92583. * \assert
  92584. * \code encoder != NULL \endcode
  92585. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92586. * \retval FLAC__bool
  92587. * \c true if successful, else \c false; in this case, check the
  92588. * encoder state with FLAC__stream_encoder_get_state() to see what
  92589. * went wrong.
  92590. */
  92591. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  92592. /** Submit data for encoding.
  92593. * This version allows you to supply the input data where the channels
  92594. * are interleaved into a single array (i.e. channel0_sample0,
  92595. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  92596. * The samples need not be block-aligned but they must be
  92597. * sample-aligned, i.e. the first value should be channel0_sample0
  92598. * and the last value channelN_sampleM. Each sample should be a signed
  92599. * integer, right-justified to the resolution set by
  92600. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  92601. * resolution is 16 bits per sample, the samples should all be in the
  92602. * range [-32768,32767].
  92603. *
  92604. * For applications where channel order is important, channels must
  92605. * follow the order as described in the
  92606. * <A HREF="../format.html#frame_header">frame header</A>.
  92607. *
  92608. * \param encoder An initialized encoder instance in the OK state.
  92609. * \param buffer An array of channel-interleaved data (see above).
  92610. * \param samples The number of samples in one channel, the same as for
  92611. * FLAC__stream_encoder_process(). For example, if
  92612. * encoding two channels, \c 1000 \a samples corresponds
  92613. * to a \a buffer of 2000 values.
  92614. * \assert
  92615. * \code encoder != NULL \endcode
  92616. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  92617. * \retval FLAC__bool
  92618. * \c true if successful, else \c false; in this case, check the
  92619. * encoder state with FLAC__stream_encoder_get_state() to see what
  92620. * went wrong.
  92621. */
  92622. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  92623. /* \} */
  92624. #ifdef __cplusplus
  92625. }
  92626. #endif
  92627. #endif
  92628. /*** End of inlined file: stream_encoder.h ***/
  92629. #ifdef _MSC_VER
  92630. /* OPT: an MSVC built-in would be better */
  92631. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  92632. {
  92633. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  92634. return (x>>16) | (x<<16);
  92635. }
  92636. #endif
  92637. #if defined(_MSC_VER) && defined(_X86_)
  92638. /* OPT: an MSVC built-in would be better */
  92639. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  92640. {
  92641. __asm {
  92642. mov edx, start
  92643. mov ecx, len
  92644. test ecx, ecx
  92645. loop1:
  92646. jz done1
  92647. mov eax, [edx]
  92648. bswap eax
  92649. mov [edx], eax
  92650. add edx, 4
  92651. dec ecx
  92652. jmp short loop1
  92653. done1:
  92654. }
  92655. }
  92656. #endif
  92657. /** \mainpage
  92658. *
  92659. * \section intro Introduction
  92660. *
  92661. * This is the documentation for the FLAC C and C++ APIs. It is
  92662. * highly interconnected; this introduction should give you a top
  92663. * level idea of the structure and how to find the information you
  92664. * need. As a prerequisite you should have at least a basic
  92665. * knowledge of the FLAC format, documented
  92666. * <A HREF="../format.html">here</A>.
  92667. *
  92668. * \section c_api FLAC C API
  92669. *
  92670. * The FLAC C API is the interface to libFLAC, a set of structures
  92671. * describing the components of FLAC streams, and functions for
  92672. * encoding and decoding streams, as well as manipulating FLAC
  92673. * metadata in files. The public include files will be installed
  92674. * in your include area (for example /usr/include/FLAC/...).
  92675. *
  92676. * By writing a little code and linking against libFLAC, it is
  92677. * relatively easy to add FLAC support to another program. The
  92678. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  92679. * Complete source code of libFLAC as well as the command-line
  92680. * encoder and plugins is available and is a useful source of
  92681. * examples.
  92682. *
  92683. * Aside from encoders and decoders, libFLAC provides a powerful
  92684. * metadata interface for manipulating metadata in FLAC files. It
  92685. * allows the user to add, delete, and modify FLAC metadata blocks
  92686. * and it can automatically take advantage of PADDING blocks to avoid
  92687. * rewriting the entire FLAC file when changing the size of the
  92688. * metadata.
  92689. *
  92690. * libFLAC usually only requires the standard C library and C math
  92691. * library. In particular, threading is not used so there is no
  92692. * dependency on a thread library. However, libFLAC does not use
  92693. * global variables and should be thread-safe.
  92694. *
  92695. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  92696. * However the metadata editing interfaces currently have limited
  92697. * read-only support for Ogg FLAC files.
  92698. *
  92699. * \section cpp_api FLAC C++ API
  92700. *
  92701. * The FLAC C++ API is a set of classes that encapsulate the
  92702. * structures and functions in libFLAC. They provide slightly more
  92703. * functionality with respect to metadata but are otherwise
  92704. * equivalent. For the most part, they share the same usage as
  92705. * their counterparts in libFLAC, and the FLAC C API documentation
  92706. * can be used as a supplement. The public include files
  92707. * for the C++ API will be installed in your include area (for
  92708. * example /usr/include/FLAC++/...).
  92709. *
  92710. * libFLAC++ is also licensed under
  92711. * <A HREF="../license.html">Xiph's BSD license</A>.
  92712. *
  92713. * \section getting_started Getting Started
  92714. *
  92715. * A good starting point for learning the API is to browse through
  92716. * the <A HREF="modules.html">modules</A>. Modules are logical
  92717. * groupings of related functions or classes, which correspond roughly
  92718. * to header files or sections of header files. Each module includes a
  92719. * detailed description of the general usage of its functions or
  92720. * classes.
  92721. *
  92722. * From there you can go on to look at the documentation of
  92723. * individual functions. You can see different views of the individual
  92724. * functions through the links in top bar across this page.
  92725. *
  92726. * If you prefer a more hands-on approach, you can jump right to some
  92727. * <A HREF="../documentation_example_code.html">example code</A>.
  92728. *
  92729. * \section porting_guide Porting Guide
  92730. *
  92731. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  92732. * has been introduced which gives detailed instructions on how to
  92733. * port your code to newer versions of FLAC.
  92734. *
  92735. * \section embedded_developers Embedded Developers
  92736. *
  92737. * libFLAC has grown larger over time as more functionality has been
  92738. * included, but much of it may be unnecessary for a particular embedded
  92739. * implementation. Unused parts may be pruned by some simple editing of
  92740. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  92741. * metadata interface are all independent from each other.
  92742. *
  92743. * It is easiest to just describe the dependencies:
  92744. *
  92745. * - All modules depend on the \link flac_format Format \endlink module.
  92746. * - The decoders and encoders depend on the bitbuffer.
  92747. * - The decoder is independent of the encoder. The encoder uses the
  92748. * decoder because of the verify feature, but this can be removed if
  92749. * not needed.
  92750. * - Parts of the metadata interface require the stream decoder (but not
  92751. * the encoder).
  92752. * - Ogg support is selectable through the compile time macro
  92753. * \c FLAC__HAS_OGG.
  92754. *
  92755. * For example, if your application only requires the stream decoder, no
  92756. * encoder, and no metadata interface, you can remove the stream encoder
  92757. * and the metadata interface, which will greatly reduce the size of the
  92758. * library.
  92759. *
  92760. * Also, there are several places in the libFLAC code with comments marked
  92761. * with "OPT:" where a #define can be changed to enable code that might be
  92762. * faster on a specific platform. Experimenting with these can yield faster
  92763. * binaries.
  92764. */
  92765. /** \defgroup porting Porting Guide for New Versions
  92766. *
  92767. * This module describes differences in the library interfaces from
  92768. * version to version. It assists in the porting of code that uses
  92769. * the libraries to newer versions of FLAC.
  92770. *
  92771. * One simple facility for making porting easier that has been added
  92772. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  92773. * library's includes (e.g. \c include/FLAC/export.h). The
  92774. * \c #defines mirror the libraries'
  92775. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  92776. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  92777. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  92778. * These can be used to support multiple versions of an API during the
  92779. * transition phase, e.g.
  92780. *
  92781. * \code
  92782. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  92783. * legacy code
  92784. * #else
  92785. * new code
  92786. * #endif
  92787. * \endcode
  92788. *
  92789. * The the source will work for multiple versions and the legacy code can
  92790. * easily be removed when the transition is complete.
  92791. *
  92792. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  92793. * include/FLAC/export.h), which can be used to determine whether or not
  92794. * the library has been compiled with support for Ogg FLAC. This is
  92795. * simpler than trying to call an Ogg init function and catching the
  92796. * error.
  92797. */
  92798. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  92799. * \ingroup porting
  92800. *
  92801. * \brief
  92802. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  92803. *
  92804. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  92805. * been simplified. First, libOggFLAC has been merged into libFLAC and
  92806. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  92807. * decoding layers and three encoding layers have been merged into a
  92808. * single stream decoder and stream encoder. That is, the functionality
  92809. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  92810. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  92811. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  92812. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  92813. * is there is now a single API that can be used to encode or decode
  92814. * streams to/from native FLAC or Ogg FLAC and the single API can work
  92815. * on both seekable and non-seekable streams.
  92816. *
  92817. * Instead of creating an encoder or decoder of a certain layer, now the
  92818. * client will always create a FLAC__StreamEncoder or
  92819. * FLAC__StreamDecoder. The old layers are now differentiated by the
  92820. * initialization function. For example, for the decoder,
  92821. * FLAC__stream_decoder_init() has been replaced by
  92822. * FLAC__stream_decoder_init_stream(). This init function takes
  92823. * callbacks for the I/O, and the seeking callbacks are optional. This
  92824. * allows the client to use the same object for seekable and
  92825. * non-seekable streams. For decoding a FLAC file directly, the client
  92826. * can use FLAC__stream_decoder_init_file() and pass just a filename
  92827. * and fewer callbacks; most of the other callbacks are supplied
  92828. * internally. For situations where fopen()ing by filename is not
  92829. * possible (e.g. Unicode filenames on Windows) the client can instead
  92830. * open the file itself and supply the FILE* to
  92831. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  92832. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  92833. * Since the callbacks and client data are now passed to the init
  92834. * function, the FLAC__stream_decoder_set_*_callback() functions and
  92835. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  92836. * rest of the calls to the decoder are the same as before.
  92837. *
  92838. * There are counterpart init functions for Ogg FLAC, e.g.
  92839. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  92840. * and callbacks are the same as for native FLAC.
  92841. *
  92842. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  92843. * been set up like so:
  92844. *
  92845. * \code
  92846. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  92847. * if(decoder == NULL) do_something;
  92848. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  92849. * [... other settings ...]
  92850. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  92851. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  92852. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  92853. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  92854. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  92855. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  92856. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  92857. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  92858. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  92859. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  92860. * \endcode
  92861. *
  92862. * In FLAC 1.1.3 it is like this:
  92863. *
  92864. * \code
  92865. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  92866. * if(decoder == NULL) do_something;
  92867. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  92868. * [... other settings ...]
  92869. * if(FLAC__stream_decoder_init_stream(
  92870. * decoder,
  92871. * my_read_callback,
  92872. * my_seek_callback, // or NULL
  92873. * my_tell_callback, // or NULL
  92874. * my_length_callback, // or NULL
  92875. * my_eof_callback, // or NULL
  92876. * my_write_callback,
  92877. * my_metadata_callback, // or NULL
  92878. * my_error_callback,
  92879. * my_client_data
  92880. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92881. * \endcode
  92882. *
  92883. * or you could do;
  92884. *
  92885. * \code
  92886. * [...]
  92887. * FILE *file = fopen("somefile.flac","rb");
  92888. * if(file == NULL) do_somthing;
  92889. * if(FLAC__stream_decoder_init_FILE(
  92890. * decoder,
  92891. * file,
  92892. * my_write_callback,
  92893. * my_metadata_callback, // or NULL
  92894. * my_error_callback,
  92895. * my_client_data
  92896. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92897. * \endcode
  92898. *
  92899. * or just:
  92900. *
  92901. * \code
  92902. * [...]
  92903. * if(FLAC__stream_decoder_init_file(
  92904. * decoder,
  92905. * "somefile.flac",
  92906. * my_write_callback,
  92907. * my_metadata_callback, // or NULL
  92908. * my_error_callback,
  92909. * my_client_data
  92910. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  92911. * \endcode
  92912. *
  92913. * Another small change to the decoder is in how it handles unparseable
  92914. * streams. Before, when the decoder found an unparseable stream
  92915. * (reserved for when the decoder encounters a stream from a future
  92916. * encoder that it can't parse), it changed the state to
  92917. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  92918. * drops sync and calls the error callback with a new error code
  92919. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  92920. * more robust. If your error callback does not discriminate on the the
  92921. * error state, your code does not need to be changed.
  92922. *
  92923. * The encoder now has a new setting:
  92924. * FLAC__stream_encoder_set_apodization(). This is for setting the
  92925. * method used to window the data before LPC analysis. You only need to
  92926. * add a call to this function if the default is not suitable. There
  92927. * are also two new convenience functions that may be useful:
  92928. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  92929. * FLAC__metadata_get_cuesheet().
  92930. *
  92931. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  92932. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  92933. * is now \c size_t instead of \c unsigned.
  92934. */
  92935. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  92936. * \ingroup porting
  92937. *
  92938. * \brief
  92939. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  92940. *
  92941. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  92942. * There was a slight change in the implementation of
  92943. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  92944. * of the \a metadata array of pointers so the client no longer needs
  92945. * to maintain it after the call. The objects themselves that are
  92946. * pointed to by the array are still not copied though and must be
  92947. * maintained until the call to FLAC__stream_encoder_finish().
  92948. */
  92949. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  92950. * \ingroup porting
  92951. *
  92952. * \brief
  92953. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  92954. *
  92955. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  92956. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  92957. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  92958. *
  92959. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  92960. * has changed to reflect the conversion of one of the reserved bits
  92961. * into active use. It used to be \c 2 and now is \c 1. However the
  92962. * FLAC frame header length has not changed, so to skip the proper
  92963. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  92964. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  92965. */
  92966. /** \defgroup flac FLAC C API
  92967. *
  92968. * The FLAC C API is the interface to libFLAC, a set of structures
  92969. * describing the components of FLAC streams, and functions for
  92970. * encoding and decoding streams, as well as manipulating FLAC
  92971. * metadata in files.
  92972. *
  92973. * You should start with the format components as all other modules
  92974. * are dependent on it.
  92975. */
  92976. #endif
  92977. /*** End of inlined file: all.h ***/
  92978. /*** Start of inlined file: bitmath.c ***/
  92979. /*** Start of inlined file: juce_FlacHeader.h ***/
  92980. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92981. // tasks..
  92982. #define VERSION "1.2.1"
  92983. #define FLAC__NO_DLL 1
  92984. #if JUCE_MSVC
  92985. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92986. #endif
  92987. #if JUCE_MAC
  92988. #define FLAC__SYS_DARWIN 1
  92989. #endif
  92990. /*** End of inlined file: juce_FlacHeader.h ***/
  92991. #if JUCE_USE_FLAC
  92992. #if HAVE_CONFIG_H
  92993. # include <config.h>
  92994. #endif
  92995. /*** Start of inlined file: bitmath.h ***/
  92996. #ifndef FLAC__PRIVATE__BITMATH_H
  92997. #define FLAC__PRIVATE__BITMATH_H
  92998. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  92999. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  93000. unsigned FLAC__bitmath_silog2(int v);
  93001. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  93002. #endif
  93003. /*** End of inlined file: bitmath.h ***/
  93004. /* An example of what FLAC__bitmath_ilog2() computes:
  93005. *
  93006. * ilog2( 0) = assertion failure
  93007. * ilog2( 1) = 0
  93008. * ilog2( 2) = 1
  93009. * ilog2( 3) = 1
  93010. * ilog2( 4) = 2
  93011. * ilog2( 5) = 2
  93012. * ilog2( 6) = 2
  93013. * ilog2( 7) = 2
  93014. * ilog2( 8) = 3
  93015. * ilog2( 9) = 3
  93016. * ilog2(10) = 3
  93017. * ilog2(11) = 3
  93018. * ilog2(12) = 3
  93019. * ilog2(13) = 3
  93020. * ilog2(14) = 3
  93021. * ilog2(15) = 3
  93022. * ilog2(16) = 4
  93023. * ilog2(17) = 4
  93024. * ilog2(18) = 4
  93025. */
  93026. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  93027. {
  93028. unsigned l = 0;
  93029. FLAC__ASSERT(v > 0);
  93030. while(v >>= 1)
  93031. l++;
  93032. return l;
  93033. }
  93034. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  93035. {
  93036. unsigned l = 0;
  93037. FLAC__ASSERT(v > 0);
  93038. while(v >>= 1)
  93039. l++;
  93040. return l;
  93041. }
  93042. /* An example of what FLAC__bitmath_silog2() computes:
  93043. *
  93044. * silog2(-10) = 5
  93045. * silog2(- 9) = 5
  93046. * silog2(- 8) = 4
  93047. * silog2(- 7) = 4
  93048. * silog2(- 6) = 4
  93049. * silog2(- 5) = 4
  93050. * silog2(- 4) = 3
  93051. * silog2(- 3) = 3
  93052. * silog2(- 2) = 2
  93053. * silog2(- 1) = 2
  93054. * silog2( 0) = 0
  93055. * silog2( 1) = 2
  93056. * silog2( 2) = 3
  93057. * silog2( 3) = 3
  93058. * silog2( 4) = 4
  93059. * silog2( 5) = 4
  93060. * silog2( 6) = 4
  93061. * silog2( 7) = 4
  93062. * silog2( 8) = 5
  93063. * silog2( 9) = 5
  93064. * silog2( 10) = 5
  93065. */
  93066. unsigned FLAC__bitmath_silog2(int v)
  93067. {
  93068. while(1) {
  93069. if(v == 0) {
  93070. return 0;
  93071. }
  93072. else if(v > 0) {
  93073. unsigned l = 0;
  93074. while(v) {
  93075. l++;
  93076. v >>= 1;
  93077. }
  93078. return l+1;
  93079. }
  93080. else if(v == -1) {
  93081. return 2;
  93082. }
  93083. else {
  93084. v++;
  93085. v = -v;
  93086. }
  93087. }
  93088. }
  93089. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  93090. {
  93091. while(1) {
  93092. if(v == 0) {
  93093. return 0;
  93094. }
  93095. else if(v > 0) {
  93096. unsigned l = 0;
  93097. while(v) {
  93098. l++;
  93099. v >>= 1;
  93100. }
  93101. return l+1;
  93102. }
  93103. else if(v == -1) {
  93104. return 2;
  93105. }
  93106. else {
  93107. v++;
  93108. v = -v;
  93109. }
  93110. }
  93111. }
  93112. #endif
  93113. /*** End of inlined file: bitmath.c ***/
  93114. /*** Start of inlined file: bitreader.c ***/
  93115. /*** Start of inlined file: juce_FlacHeader.h ***/
  93116. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  93117. // tasks..
  93118. #define VERSION "1.2.1"
  93119. #define FLAC__NO_DLL 1
  93120. #if JUCE_MSVC
  93121. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  93122. #endif
  93123. #if JUCE_MAC
  93124. #define FLAC__SYS_DARWIN 1
  93125. #endif
  93126. /*** End of inlined file: juce_FlacHeader.h ***/
  93127. #if JUCE_USE_FLAC
  93128. #if HAVE_CONFIG_H
  93129. # include <config.h>
  93130. #endif
  93131. #include <stdlib.h> /* for malloc() */
  93132. #include <string.h> /* for memcpy(), memset() */
  93133. #ifdef _MSC_VER
  93134. #include <winsock.h> /* for ntohl() */
  93135. #elif defined FLAC__SYS_DARWIN
  93136. #include <machine/endian.h> /* for ntohl() */
  93137. #elif defined __MINGW32__
  93138. #include <winsock.h> /* for ntohl() */
  93139. #else
  93140. #include <netinet/in.h> /* for ntohl() */
  93141. #endif
  93142. /*** Start of inlined file: bitreader.h ***/
  93143. #ifndef FLAC__PRIVATE__BITREADER_H
  93144. #define FLAC__PRIVATE__BITREADER_H
  93145. #include <stdio.h> /* for FILE */
  93146. /*** Start of inlined file: cpu.h ***/
  93147. #ifndef FLAC__PRIVATE__CPU_H
  93148. #define FLAC__PRIVATE__CPU_H
  93149. #ifdef HAVE_CONFIG_H
  93150. #include <config.h>
  93151. #endif
  93152. typedef enum {
  93153. FLAC__CPUINFO_TYPE_IA32,
  93154. FLAC__CPUINFO_TYPE_PPC,
  93155. FLAC__CPUINFO_TYPE_UNKNOWN
  93156. } FLAC__CPUInfo_Type;
  93157. typedef struct {
  93158. FLAC__bool cpuid;
  93159. FLAC__bool bswap;
  93160. FLAC__bool cmov;
  93161. FLAC__bool mmx;
  93162. FLAC__bool fxsr;
  93163. FLAC__bool sse;
  93164. FLAC__bool sse2;
  93165. FLAC__bool sse3;
  93166. FLAC__bool ssse3;
  93167. FLAC__bool _3dnow;
  93168. FLAC__bool ext3dnow;
  93169. FLAC__bool extmmx;
  93170. } FLAC__CPUInfo_IA32;
  93171. typedef struct {
  93172. FLAC__bool altivec;
  93173. FLAC__bool ppc64;
  93174. } FLAC__CPUInfo_PPC;
  93175. typedef struct {
  93176. FLAC__bool use_asm;
  93177. FLAC__CPUInfo_Type type;
  93178. union {
  93179. FLAC__CPUInfo_IA32 ia32;
  93180. FLAC__CPUInfo_PPC ppc;
  93181. } data;
  93182. } FLAC__CPUInfo;
  93183. void FLAC__cpu_info(FLAC__CPUInfo *info);
  93184. #ifndef FLAC__NO_ASM
  93185. #ifdef FLAC__CPU_IA32
  93186. #ifdef FLAC__HAS_NASM
  93187. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  93188. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  93189. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  93190. #endif
  93191. #endif
  93192. #endif
  93193. #endif
  93194. /*** End of inlined file: cpu.h ***/
  93195. /*
  93196. * opaque structure definition
  93197. */
  93198. struct FLAC__BitReader;
  93199. typedef struct FLAC__BitReader FLAC__BitReader;
  93200. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  93201. /*
  93202. * construction, deletion, initialization, etc functions
  93203. */
  93204. FLAC__BitReader *FLAC__bitreader_new(void);
  93205. void FLAC__bitreader_delete(FLAC__BitReader *br);
  93206. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  93207. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  93208. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  93209. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  93210. /*
  93211. * CRC functions
  93212. */
  93213. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  93214. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  93215. /*
  93216. * info functions
  93217. */
  93218. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  93219. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  93220. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  93221. /*
  93222. * read functions
  93223. */
  93224. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  93225. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  93226. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  93227. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  93228. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  93229. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  93230. 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! */
  93231. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  93232. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93233. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93234. #ifndef FLAC__NO_ASM
  93235. # ifdef FLAC__CPU_IA32
  93236. # ifdef FLAC__HAS_NASM
  93237. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  93238. # endif
  93239. # endif
  93240. #endif
  93241. #if 0 /* UNUSED */
  93242. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  93243. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  93244. #endif
  93245. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  93246. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  93247. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  93248. #endif
  93249. /*** End of inlined file: bitreader.h ***/
  93250. /*** Start of inlined file: crc.h ***/
  93251. #ifndef FLAC__PRIVATE__CRC_H
  93252. #define FLAC__PRIVATE__CRC_H
  93253. /* 8 bit CRC generator, MSB shifted first
  93254. ** polynomial = x^8 + x^2 + x^1 + x^0
  93255. ** init = 0
  93256. */
  93257. extern FLAC__byte const FLAC__crc8_table[256];
  93258. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  93259. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  93260. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  93261. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  93262. /* 16 bit CRC generator, MSB shifted first
  93263. ** polynomial = x^16 + x^15 + x^2 + x^0
  93264. ** init = 0
  93265. */
  93266. extern unsigned FLAC__crc16_table[256];
  93267. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  93268. /* this alternate may be faster on some systems/compilers */
  93269. #if 0
  93270. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  93271. #endif
  93272. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  93273. #endif
  93274. /*** End of inlined file: crc.h ***/
  93275. /* Things should be fastest when this matches the machine word size */
  93276. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  93277. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  93278. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  93279. typedef FLAC__uint32 brword;
  93280. #define FLAC__BYTES_PER_WORD 4
  93281. #define FLAC__BITS_PER_WORD 32
  93282. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  93283. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  93284. #if WORDS_BIGENDIAN
  93285. #define SWAP_BE_WORD_TO_HOST(x) (x)
  93286. #else
  93287. #if defined (_MSC_VER) && defined (_X86_)
  93288. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  93289. #else
  93290. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  93291. #endif
  93292. #endif
  93293. /* counts the # of zero MSBs in a word */
  93294. #define COUNT_ZERO_MSBS(word) ( \
  93295. (word) <= 0xffff ? \
  93296. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  93297. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  93298. )
  93299. /* this alternate might be slightly faster on some systems/compilers: */
  93300. #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])) )
  93301. /*
  93302. * This should be at least twice as large as the largest number of words
  93303. * required to represent any 'number' (in any encoding) you are going to
  93304. * read. With FLAC this is on the order of maybe a few hundred bits.
  93305. * If the buffer is smaller than that, the decoder won't be able to read
  93306. * in a whole number that is in a variable length encoding (e.g. Rice).
  93307. * But to be practical it should be at least 1K bytes.
  93308. *
  93309. * Increase this number to decrease the number of read callbacks, at the
  93310. * expense of using more memory. Or decrease for the reverse effect,
  93311. * keeping in mind the limit from the first paragraph. The optimal size
  93312. * also depends on the CPU cache size and other factors; some twiddling
  93313. * may be necessary to squeeze out the best performance.
  93314. */
  93315. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  93316. static const unsigned char byte_to_unary_table[] = {
  93317. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  93318. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  93319. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93320. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  93321. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93322. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93323. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93324. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  93325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  93332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  93333. };
  93334. #ifdef min
  93335. #undef min
  93336. #endif
  93337. #define min(x,y) ((x)<(y)?(x):(y))
  93338. #ifdef max
  93339. #undef max
  93340. #endif
  93341. #define max(x,y) ((x)>(y)?(x):(y))
  93342. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  93343. #ifdef _MSC_VER
  93344. #define FLAC__U64L(x) x
  93345. #else
  93346. #define FLAC__U64L(x) x##LLU
  93347. #endif
  93348. #ifndef FLaC__INLINE
  93349. #define FLaC__INLINE
  93350. #endif
  93351. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  93352. struct FLAC__BitReader {
  93353. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  93354. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  93355. brword *buffer;
  93356. unsigned capacity; /* in words */
  93357. unsigned words; /* # of completed words in buffer */
  93358. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  93359. unsigned consumed_words; /* #words ... */
  93360. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  93361. unsigned read_crc16; /* the running frame CRC */
  93362. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  93363. FLAC__BitReaderReadCallback read_callback;
  93364. void *client_data;
  93365. FLAC__CPUInfo cpu_info;
  93366. };
  93367. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  93368. {
  93369. register unsigned crc = br->read_crc16;
  93370. #if FLAC__BYTES_PER_WORD == 4
  93371. switch(br->crc16_align) {
  93372. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  93373. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93374. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93375. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93376. }
  93377. #elif FLAC__BYTES_PER_WORD == 8
  93378. switch(br->crc16_align) {
  93379. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  93380. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  93381. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  93382. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  93383. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  93384. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  93385. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  93386. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  93387. }
  93388. #else
  93389. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  93390. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  93391. br->read_crc16 = crc;
  93392. #endif
  93393. br->crc16_align = 0;
  93394. }
  93395. /* would be static except it needs to be called by asm routines */
  93396. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  93397. {
  93398. unsigned start, end;
  93399. size_t bytes;
  93400. FLAC__byte *target;
  93401. /* first shift the unconsumed buffer data toward the front as much as possible */
  93402. if(br->consumed_words > 0) {
  93403. start = br->consumed_words;
  93404. end = br->words + (br->bytes? 1:0);
  93405. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  93406. br->words -= start;
  93407. br->consumed_words = 0;
  93408. }
  93409. /*
  93410. * set the target for reading, taking into account word alignment and endianness
  93411. */
  93412. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  93413. if(bytes == 0)
  93414. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  93415. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  93416. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  93417. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  93418. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  93419. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  93420. * ^^-------target, bytes=3
  93421. * on LE machines, have to byteswap the odd tail word so nothing is
  93422. * overwritten:
  93423. */
  93424. #if WORDS_BIGENDIAN
  93425. #else
  93426. if(br->bytes)
  93427. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  93428. #endif
  93429. /* now it looks like:
  93430. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  93431. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  93432. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  93433. * ^^-------target, bytes=3
  93434. */
  93435. /* read in the data; note that the callback may return a smaller number of bytes */
  93436. if(!br->read_callback(target, &bytes, br->client_data))
  93437. return false;
  93438. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  93439. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93440. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93441. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  93442. * now have to byteswap on LE machines:
  93443. */
  93444. #if WORDS_BIGENDIAN
  93445. #else
  93446. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  93447. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  93448. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  93449. start = br->words;
  93450. local_swap32_block_(br->buffer + start, end - start);
  93451. }
  93452. else
  93453. # endif
  93454. for(start = br->words; start < end; start++)
  93455. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  93456. #endif
  93457. /* now it looks like:
  93458. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  93459. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  93460. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  93461. * finally we'll update the reader values:
  93462. */
  93463. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  93464. br->words = end / FLAC__BYTES_PER_WORD;
  93465. br->bytes = end % FLAC__BYTES_PER_WORD;
  93466. return true;
  93467. }
  93468. /***********************************************************************
  93469. *
  93470. * Class constructor/destructor
  93471. *
  93472. ***********************************************************************/
  93473. FLAC__BitReader *FLAC__bitreader_new(void)
  93474. {
  93475. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  93476. /* calloc() implies:
  93477. memset(br, 0, sizeof(FLAC__BitReader));
  93478. br->buffer = 0;
  93479. br->capacity = 0;
  93480. br->words = br->bytes = 0;
  93481. br->consumed_words = br->consumed_bits = 0;
  93482. br->read_callback = 0;
  93483. br->client_data = 0;
  93484. */
  93485. return br;
  93486. }
  93487. void FLAC__bitreader_delete(FLAC__BitReader *br)
  93488. {
  93489. FLAC__ASSERT(0 != br);
  93490. FLAC__bitreader_free(br);
  93491. free(br);
  93492. }
  93493. /***********************************************************************
  93494. *
  93495. * Public class methods
  93496. *
  93497. ***********************************************************************/
  93498. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  93499. {
  93500. FLAC__ASSERT(0 != br);
  93501. br->words = br->bytes = 0;
  93502. br->consumed_words = br->consumed_bits = 0;
  93503. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  93504. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  93505. if(br->buffer == 0)
  93506. return false;
  93507. br->read_callback = rcb;
  93508. br->client_data = cd;
  93509. br->cpu_info = cpu;
  93510. return true;
  93511. }
  93512. void FLAC__bitreader_free(FLAC__BitReader *br)
  93513. {
  93514. FLAC__ASSERT(0 != br);
  93515. if(0 != br->buffer)
  93516. free(br->buffer);
  93517. br->buffer = 0;
  93518. br->capacity = 0;
  93519. br->words = br->bytes = 0;
  93520. br->consumed_words = br->consumed_bits = 0;
  93521. br->read_callback = 0;
  93522. br->client_data = 0;
  93523. }
  93524. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  93525. {
  93526. br->words = br->bytes = 0;
  93527. br->consumed_words = br->consumed_bits = 0;
  93528. return true;
  93529. }
  93530. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  93531. {
  93532. unsigned i, j;
  93533. if(br == 0) {
  93534. fprintf(out, "bitreader is NULL\n");
  93535. }
  93536. else {
  93537. 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);
  93538. for(i = 0; i < br->words; i++) {
  93539. fprintf(out, "%08X: ", i);
  93540. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  93541. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93542. fprintf(out, ".");
  93543. else
  93544. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  93545. fprintf(out, "\n");
  93546. }
  93547. if(br->bytes > 0) {
  93548. fprintf(out, "%08X: ", i);
  93549. for(j = 0; j < br->bytes*8; j++)
  93550. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  93551. fprintf(out, ".");
  93552. else
  93553. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  93554. fprintf(out, "\n");
  93555. }
  93556. }
  93557. }
  93558. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  93559. {
  93560. FLAC__ASSERT(0 != br);
  93561. FLAC__ASSERT(0 != br->buffer);
  93562. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93563. br->read_crc16 = (unsigned)seed;
  93564. br->crc16_align = br->consumed_bits;
  93565. }
  93566. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  93567. {
  93568. FLAC__ASSERT(0 != br);
  93569. FLAC__ASSERT(0 != br->buffer);
  93570. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  93571. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  93572. /* CRC any tail bytes in a partially-consumed word */
  93573. if(br->consumed_bits) {
  93574. const brword tail = br->buffer[br->consumed_words];
  93575. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  93576. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  93577. }
  93578. return br->read_crc16;
  93579. }
  93580. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  93581. {
  93582. return ((br->consumed_bits & 7) == 0);
  93583. }
  93584. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  93585. {
  93586. return 8 - (br->consumed_bits & 7);
  93587. }
  93588. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  93589. {
  93590. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  93591. }
  93592. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  93593. {
  93594. FLAC__ASSERT(0 != br);
  93595. FLAC__ASSERT(0 != br->buffer);
  93596. FLAC__ASSERT(bits <= 32);
  93597. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  93598. FLAC__ASSERT(br->consumed_words <= br->words);
  93599. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93600. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93601. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  93602. *val = 0;
  93603. return true;
  93604. }
  93605. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  93606. if(!bitreader_read_from_client_(br))
  93607. return false;
  93608. }
  93609. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93610. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93611. if(br->consumed_bits) {
  93612. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93613. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  93614. const brword word = br->buffer[br->consumed_words];
  93615. if(bits < n) {
  93616. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  93617. br->consumed_bits += bits;
  93618. return true;
  93619. }
  93620. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  93621. bits -= n;
  93622. crc16_update_word_(br, word);
  93623. br->consumed_words++;
  93624. br->consumed_bits = 0;
  93625. 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 */
  93626. *val <<= bits;
  93627. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  93628. br->consumed_bits = bits;
  93629. }
  93630. return true;
  93631. }
  93632. else {
  93633. const brword word = br->buffer[br->consumed_words];
  93634. if(bits < FLAC__BITS_PER_WORD) {
  93635. *val = word >> (FLAC__BITS_PER_WORD-bits);
  93636. br->consumed_bits = bits;
  93637. return true;
  93638. }
  93639. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  93640. *val = word;
  93641. crc16_update_word_(br, word);
  93642. br->consumed_words++;
  93643. return true;
  93644. }
  93645. }
  93646. else {
  93647. /* in this case we're starting our read at a partial tail word;
  93648. * the reader has guaranteed that we have at least 'bits' bits
  93649. * available to read, which makes this case simpler.
  93650. */
  93651. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  93652. if(br->consumed_bits) {
  93653. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  93654. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  93655. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  93656. br->consumed_bits += bits;
  93657. return true;
  93658. }
  93659. else {
  93660. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  93661. br->consumed_bits += bits;
  93662. return true;
  93663. }
  93664. }
  93665. }
  93666. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  93667. {
  93668. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  93669. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  93670. return false;
  93671. /* sign-extend: */
  93672. *val <<= (32-bits);
  93673. *val >>= (32-bits);
  93674. return true;
  93675. }
  93676. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  93677. {
  93678. FLAC__uint32 hi, lo;
  93679. if(bits > 32) {
  93680. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  93681. return false;
  93682. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  93683. return false;
  93684. *val = hi;
  93685. *val <<= 32;
  93686. *val |= lo;
  93687. }
  93688. else {
  93689. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  93690. return false;
  93691. *val = lo;
  93692. }
  93693. return true;
  93694. }
  93695. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  93696. {
  93697. FLAC__uint32 x8, x32 = 0;
  93698. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  93699. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  93700. return false;
  93701. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93702. return false;
  93703. x32 |= (x8 << 8);
  93704. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93705. return false;
  93706. x32 |= (x8 << 16);
  93707. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  93708. return false;
  93709. x32 |= (x8 << 24);
  93710. *val = x32;
  93711. return true;
  93712. }
  93713. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  93714. {
  93715. /*
  93716. * OPT: a faster implementation is possible but probably not that useful
  93717. * since this is only called a couple of times in the metadata readers.
  93718. */
  93719. FLAC__ASSERT(0 != br);
  93720. FLAC__ASSERT(0 != br->buffer);
  93721. if(bits > 0) {
  93722. const unsigned n = br->consumed_bits & 7;
  93723. unsigned m;
  93724. FLAC__uint32 x;
  93725. if(n != 0) {
  93726. m = min(8-n, bits);
  93727. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  93728. return false;
  93729. bits -= m;
  93730. }
  93731. m = bits / 8;
  93732. if(m > 0) {
  93733. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  93734. return false;
  93735. bits %= 8;
  93736. }
  93737. if(bits > 0) {
  93738. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  93739. return false;
  93740. }
  93741. }
  93742. return true;
  93743. }
  93744. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  93745. {
  93746. FLAC__uint32 x;
  93747. FLAC__ASSERT(0 != br);
  93748. FLAC__ASSERT(0 != br->buffer);
  93749. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93750. /* step 1: skip over partial head word to get word aligned */
  93751. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93752. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93753. return false;
  93754. nvals--;
  93755. }
  93756. if(0 == nvals)
  93757. return true;
  93758. /* step 2: skip whole words in chunks */
  93759. while(nvals >= FLAC__BYTES_PER_WORD) {
  93760. if(br->consumed_words < br->words) {
  93761. br->consumed_words++;
  93762. nvals -= FLAC__BYTES_PER_WORD;
  93763. }
  93764. else if(!bitreader_read_from_client_(br))
  93765. return false;
  93766. }
  93767. /* step 3: skip any remainder from partial tail bytes */
  93768. while(nvals) {
  93769. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93770. return false;
  93771. nvals--;
  93772. }
  93773. return true;
  93774. }
  93775. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  93776. {
  93777. FLAC__uint32 x;
  93778. FLAC__ASSERT(0 != br);
  93779. FLAC__ASSERT(0 != br->buffer);
  93780. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  93781. /* step 1: read from partial head word to get word aligned */
  93782. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  93783. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93784. return false;
  93785. *val++ = (FLAC__byte)x;
  93786. nvals--;
  93787. }
  93788. if(0 == nvals)
  93789. return true;
  93790. /* step 2: read whole words in chunks */
  93791. while(nvals >= FLAC__BYTES_PER_WORD) {
  93792. if(br->consumed_words < br->words) {
  93793. const brword word = br->buffer[br->consumed_words++];
  93794. #if FLAC__BYTES_PER_WORD == 4
  93795. val[0] = (FLAC__byte)(word >> 24);
  93796. val[1] = (FLAC__byte)(word >> 16);
  93797. val[2] = (FLAC__byte)(word >> 8);
  93798. val[3] = (FLAC__byte)word;
  93799. #elif FLAC__BYTES_PER_WORD == 8
  93800. val[0] = (FLAC__byte)(word >> 56);
  93801. val[1] = (FLAC__byte)(word >> 48);
  93802. val[2] = (FLAC__byte)(word >> 40);
  93803. val[3] = (FLAC__byte)(word >> 32);
  93804. val[4] = (FLAC__byte)(word >> 24);
  93805. val[5] = (FLAC__byte)(word >> 16);
  93806. val[6] = (FLAC__byte)(word >> 8);
  93807. val[7] = (FLAC__byte)word;
  93808. #else
  93809. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  93810. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  93811. #endif
  93812. val += FLAC__BYTES_PER_WORD;
  93813. nvals -= FLAC__BYTES_PER_WORD;
  93814. }
  93815. else if(!bitreader_read_from_client_(br))
  93816. return false;
  93817. }
  93818. /* step 3: read any remainder from partial tail bytes */
  93819. while(nvals) {
  93820. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  93821. return false;
  93822. *val++ = (FLAC__byte)x;
  93823. nvals--;
  93824. }
  93825. return true;
  93826. }
  93827. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  93828. #if 0 /* slow but readable version */
  93829. {
  93830. unsigned bit;
  93831. FLAC__ASSERT(0 != br);
  93832. FLAC__ASSERT(0 != br->buffer);
  93833. *val = 0;
  93834. while(1) {
  93835. if(!FLAC__bitreader_read_bit(br, &bit))
  93836. return false;
  93837. if(bit)
  93838. break;
  93839. else
  93840. *val++;
  93841. }
  93842. return true;
  93843. }
  93844. #else
  93845. {
  93846. unsigned i;
  93847. FLAC__ASSERT(0 != br);
  93848. FLAC__ASSERT(0 != br->buffer);
  93849. *val = 0;
  93850. while(1) {
  93851. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  93852. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  93853. if(b) {
  93854. i = COUNT_ZERO_MSBS(b);
  93855. *val += i;
  93856. i++;
  93857. br->consumed_bits += i;
  93858. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  93859. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93860. br->consumed_words++;
  93861. br->consumed_bits = 0;
  93862. }
  93863. return true;
  93864. }
  93865. else {
  93866. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  93867. crc16_update_word_(br, br->buffer[br->consumed_words]);
  93868. br->consumed_words++;
  93869. br->consumed_bits = 0;
  93870. /* didn't find stop bit yet, have to keep going... */
  93871. }
  93872. }
  93873. /* at this point we've eaten up all the whole words; have to try
  93874. * reading through any tail bytes before calling the read callback.
  93875. * this is a repeat of the above logic adjusted for the fact we
  93876. * don't have a whole word. note though if the client is feeding
  93877. * us data a byte at a time (unlikely), br->consumed_bits may not
  93878. * be zero.
  93879. */
  93880. if(br->bytes) {
  93881. const unsigned end = br->bytes * 8;
  93882. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  93883. if(b) {
  93884. i = COUNT_ZERO_MSBS(b);
  93885. *val += i;
  93886. i++;
  93887. br->consumed_bits += i;
  93888. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93889. return true;
  93890. }
  93891. else {
  93892. *val += end - br->consumed_bits;
  93893. br->consumed_bits += end;
  93894. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  93895. /* didn't find stop bit yet, have to keep going... */
  93896. }
  93897. }
  93898. if(!bitreader_read_from_client_(br))
  93899. return false;
  93900. }
  93901. }
  93902. #endif
  93903. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  93904. {
  93905. FLAC__uint32 lsbs = 0, msbs = 0;
  93906. unsigned uval;
  93907. FLAC__ASSERT(0 != br);
  93908. FLAC__ASSERT(0 != br->buffer);
  93909. FLAC__ASSERT(parameter <= 31);
  93910. /* read the unary MSBs and end bit */
  93911. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  93912. return false;
  93913. /* read the binary LSBs */
  93914. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  93915. return false;
  93916. /* compose the value */
  93917. uval = (msbs << parameter) | lsbs;
  93918. if(uval & 1)
  93919. *val = -((int)(uval >> 1)) - 1;
  93920. else
  93921. *val = (int)(uval >> 1);
  93922. return true;
  93923. }
  93924. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  93925. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  93926. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  93927. /* OPT: possibly faster version for use with MSVC */
  93928. #ifdef _MSC_VER
  93929. {
  93930. unsigned i;
  93931. unsigned uval = 0;
  93932. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  93933. /* try and get br->consumed_words and br->consumed_bits into register;
  93934. * must remember to flush them back to *br before calling other
  93935. * bitwriter functions that use them, and before returning */
  93936. register unsigned cwords;
  93937. register unsigned cbits;
  93938. FLAC__ASSERT(0 != br);
  93939. FLAC__ASSERT(0 != br->buffer);
  93940. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  93941. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  93942. FLAC__ASSERT(parameter < 32);
  93943. /* 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 */
  93944. if(nvals == 0)
  93945. return true;
  93946. cbits = br->consumed_bits;
  93947. cwords = br->consumed_words;
  93948. while(1) {
  93949. /* read unary part */
  93950. while(1) {
  93951. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  93952. brword b = br->buffer[cwords] << cbits;
  93953. if(b) {
  93954. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  93955. __asm {
  93956. bsr eax, b
  93957. not eax
  93958. and eax, 31
  93959. mov i, eax
  93960. }
  93961. #else
  93962. i = COUNT_ZERO_MSBS(b);
  93963. #endif
  93964. uval += i;
  93965. bits = parameter;
  93966. i++;
  93967. cbits += i;
  93968. if(cbits == FLAC__BITS_PER_WORD) {
  93969. crc16_update_word_(br, br->buffer[cwords]);
  93970. cwords++;
  93971. cbits = 0;
  93972. }
  93973. goto break1;
  93974. }
  93975. else {
  93976. uval += FLAC__BITS_PER_WORD - cbits;
  93977. crc16_update_word_(br, br->buffer[cwords]);
  93978. cwords++;
  93979. cbits = 0;
  93980. /* didn't find stop bit yet, have to keep going... */
  93981. }
  93982. }
  93983. /* at this point we've eaten up all the whole words; have to try
  93984. * reading through any tail bytes before calling the read callback.
  93985. * this is a repeat of the above logic adjusted for the fact we
  93986. * don't have a whole word. note though if the client is feeding
  93987. * us data a byte at a time (unlikely), br->consumed_bits may not
  93988. * be zero.
  93989. */
  93990. if(br->bytes) {
  93991. const unsigned end = br->bytes * 8;
  93992. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  93993. if(b) {
  93994. i = COUNT_ZERO_MSBS(b);
  93995. uval += i;
  93996. bits = parameter;
  93997. i++;
  93998. cbits += i;
  93999. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94000. goto break1;
  94001. }
  94002. else {
  94003. uval += end - cbits;
  94004. cbits += end;
  94005. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94006. /* didn't find stop bit yet, have to keep going... */
  94007. }
  94008. }
  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. break1:
  94020. /* read binary part */
  94021. FLAC__ASSERT(cwords <= br->words);
  94022. if(bits) {
  94023. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  94024. /* flush registers and read; bitreader_read_from_client_() does
  94025. * not touch br->consumed_bits at all but we still need to set
  94026. * it in case it fails and we have to return false.
  94027. */
  94028. br->consumed_bits = cbits;
  94029. br->consumed_words = cwords;
  94030. if(!bitreader_read_from_client_(br))
  94031. return false;
  94032. cwords = br->consumed_words;
  94033. }
  94034. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94035. if(cbits) {
  94036. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94037. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94038. const brword word = br->buffer[cwords];
  94039. if(bits < n) {
  94040. uval <<= bits;
  94041. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  94042. cbits += bits;
  94043. goto break2;
  94044. }
  94045. uval <<= n;
  94046. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94047. bits -= n;
  94048. crc16_update_word_(br, word);
  94049. cwords++;
  94050. cbits = 0;
  94051. 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 */
  94052. uval <<= bits;
  94053. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  94054. cbits = bits;
  94055. }
  94056. goto break2;
  94057. }
  94058. else {
  94059. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  94060. uval <<= bits;
  94061. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94062. cbits = bits;
  94063. goto break2;
  94064. }
  94065. }
  94066. else {
  94067. /* in this case we're starting our read at a partial tail word;
  94068. * the reader has guaranteed that we have at least 'bits' bits
  94069. * available to read, which makes this case simpler.
  94070. */
  94071. uval <<= bits;
  94072. if(cbits) {
  94073. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94074. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  94075. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  94076. cbits += bits;
  94077. goto break2;
  94078. }
  94079. else {
  94080. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  94081. cbits += bits;
  94082. goto break2;
  94083. }
  94084. }
  94085. }
  94086. break2:
  94087. /* compose the value */
  94088. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94089. /* are we done? */
  94090. --nvals;
  94091. if(nvals == 0) {
  94092. br->consumed_bits = cbits;
  94093. br->consumed_words = cwords;
  94094. return true;
  94095. }
  94096. uval = 0;
  94097. ++vals;
  94098. }
  94099. }
  94100. #else
  94101. {
  94102. unsigned i;
  94103. unsigned uval = 0;
  94104. /* try and get br->consumed_words and br->consumed_bits into register;
  94105. * must remember to flush them back to *br before calling other
  94106. * bitwriter functions that use them, and before returning */
  94107. register unsigned cwords;
  94108. register unsigned cbits;
  94109. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  94110. FLAC__ASSERT(0 != br);
  94111. FLAC__ASSERT(0 != br->buffer);
  94112. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94113. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94114. FLAC__ASSERT(parameter < 32);
  94115. /* 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 */
  94116. if(nvals == 0)
  94117. return true;
  94118. cbits = br->consumed_bits;
  94119. cwords = br->consumed_words;
  94120. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94121. while(1) {
  94122. /* read unary part */
  94123. while(1) {
  94124. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94125. brword b = br->buffer[cwords] << cbits;
  94126. if(b) {
  94127. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  94128. asm volatile (
  94129. "bsrl %1, %0;"
  94130. "notl %0;"
  94131. "andl $31, %0;"
  94132. : "=r"(i)
  94133. : "r"(b)
  94134. );
  94135. #else
  94136. i = COUNT_ZERO_MSBS(b);
  94137. #endif
  94138. uval += i;
  94139. cbits += i;
  94140. cbits++; /* skip over stop bit */
  94141. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  94142. crc16_update_word_(br, br->buffer[cwords]);
  94143. cwords++;
  94144. cbits = 0;
  94145. }
  94146. goto break1;
  94147. }
  94148. else {
  94149. uval += FLAC__BITS_PER_WORD - cbits;
  94150. crc16_update_word_(br, br->buffer[cwords]);
  94151. cwords++;
  94152. cbits = 0;
  94153. /* didn't find stop bit yet, have to keep going... */
  94154. }
  94155. }
  94156. /* at this point we've eaten up all the whole words; have to try
  94157. * reading through any tail bytes before calling the read callback.
  94158. * this is a repeat of the above logic adjusted for the fact we
  94159. * don't have a whole word. note though if the client is feeding
  94160. * us data a byte at a time (unlikely), br->consumed_bits may not
  94161. * be zero.
  94162. */
  94163. if(br->bytes) {
  94164. const unsigned end = br->bytes * 8;
  94165. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  94166. if(b) {
  94167. i = COUNT_ZERO_MSBS(b);
  94168. uval += i;
  94169. cbits += i;
  94170. cbits++; /* skip over stop bit */
  94171. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94172. goto break1;
  94173. }
  94174. else {
  94175. uval += end - cbits;
  94176. cbits += end;
  94177. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  94178. /* didn't find stop bit yet, have to keep going... */
  94179. }
  94180. }
  94181. /* flush registers and read; bitreader_read_from_client_() does
  94182. * not touch br->consumed_bits at all but we still need to set
  94183. * it in case it fails and we have to return false.
  94184. */
  94185. br->consumed_bits = cbits;
  94186. br->consumed_words = cwords;
  94187. if(!bitreader_read_from_client_(br))
  94188. return false;
  94189. cwords = br->consumed_words;
  94190. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  94191. /* + uval to offset our count by the # of unary bits already
  94192. * consumed before the read, because we will add these back
  94193. * in all at once at break1
  94194. */
  94195. }
  94196. break1:
  94197. ucbits -= uval;
  94198. ucbits--; /* account for stop bit */
  94199. /* read binary part */
  94200. FLAC__ASSERT(cwords <= br->words);
  94201. if(parameter) {
  94202. while(ucbits < parameter) {
  94203. /* flush registers and read; bitreader_read_from_client_() does
  94204. * not touch br->consumed_bits at all but we still need to set
  94205. * it in case it fails and we have to return false.
  94206. */
  94207. br->consumed_bits = cbits;
  94208. br->consumed_words = cwords;
  94209. if(!bitreader_read_from_client_(br))
  94210. return false;
  94211. cwords = br->consumed_words;
  94212. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  94213. }
  94214. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  94215. if(cbits) {
  94216. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  94217. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  94218. const brword word = br->buffer[cwords];
  94219. if(parameter < n) {
  94220. uval <<= parameter;
  94221. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  94222. cbits += parameter;
  94223. }
  94224. else {
  94225. uval <<= n;
  94226. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  94227. crc16_update_word_(br, word);
  94228. cwords++;
  94229. cbits = parameter - n;
  94230. 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 */
  94231. uval <<= cbits;
  94232. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  94233. }
  94234. }
  94235. }
  94236. else {
  94237. cbits = parameter;
  94238. uval <<= parameter;
  94239. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94240. }
  94241. }
  94242. else {
  94243. /* in this case we're starting our read at a partial tail word;
  94244. * the reader has guaranteed that we have at least 'parameter'
  94245. * bits available to read, which makes this case simpler.
  94246. */
  94247. uval <<= parameter;
  94248. if(cbits) {
  94249. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  94250. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  94251. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  94252. cbits += parameter;
  94253. }
  94254. else {
  94255. cbits = parameter;
  94256. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  94257. }
  94258. }
  94259. }
  94260. ucbits -= parameter;
  94261. /* compose the value */
  94262. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  94263. /* are we done? */
  94264. --nvals;
  94265. if(nvals == 0) {
  94266. br->consumed_bits = cbits;
  94267. br->consumed_words = cwords;
  94268. return true;
  94269. }
  94270. uval = 0;
  94271. ++vals;
  94272. }
  94273. }
  94274. #endif
  94275. #if 0 /* UNUSED */
  94276. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  94277. {
  94278. FLAC__uint32 lsbs = 0, msbs = 0;
  94279. unsigned bit, uval, k;
  94280. FLAC__ASSERT(0 != br);
  94281. FLAC__ASSERT(0 != br->buffer);
  94282. k = FLAC__bitmath_ilog2(parameter);
  94283. /* read the unary MSBs and end bit */
  94284. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94285. return false;
  94286. /* read the binary LSBs */
  94287. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94288. return false;
  94289. if(parameter == 1u<<k) {
  94290. /* compose the value */
  94291. uval = (msbs << k) | lsbs;
  94292. }
  94293. else {
  94294. unsigned d = (1 << (k+1)) - parameter;
  94295. if(lsbs >= d) {
  94296. if(!FLAC__bitreader_read_bit(br, &bit))
  94297. return false;
  94298. lsbs <<= 1;
  94299. lsbs |= bit;
  94300. lsbs -= d;
  94301. }
  94302. /* compose the value */
  94303. uval = msbs * parameter + lsbs;
  94304. }
  94305. /* unfold unsigned to signed */
  94306. if(uval & 1)
  94307. *val = -((int)(uval >> 1)) - 1;
  94308. else
  94309. *val = (int)(uval >> 1);
  94310. return true;
  94311. }
  94312. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  94313. {
  94314. FLAC__uint32 lsbs, msbs = 0;
  94315. unsigned bit, k;
  94316. FLAC__ASSERT(0 != br);
  94317. FLAC__ASSERT(0 != br->buffer);
  94318. k = FLAC__bitmath_ilog2(parameter);
  94319. /* read the unary MSBs and end bit */
  94320. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  94321. return false;
  94322. /* read the binary LSBs */
  94323. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  94324. return false;
  94325. if(parameter == 1u<<k) {
  94326. /* compose the value */
  94327. *val = (msbs << k) | lsbs;
  94328. }
  94329. else {
  94330. unsigned d = (1 << (k+1)) - parameter;
  94331. if(lsbs >= d) {
  94332. if(!FLAC__bitreader_read_bit(br, &bit))
  94333. return false;
  94334. lsbs <<= 1;
  94335. lsbs |= bit;
  94336. lsbs -= d;
  94337. }
  94338. /* compose the value */
  94339. *val = msbs * parameter + lsbs;
  94340. }
  94341. return true;
  94342. }
  94343. #endif /* UNUSED */
  94344. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94345. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  94346. {
  94347. FLAC__uint32 v = 0;
  94348. FLAC__uint32 x;
  94349. unsigned i;
  94350. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94351. return false;
  94352. if(raw)
  94353. raw[(*rawlen)++] = (FLAC__byte)x;
  94354. if(!(x & 0x80)) { /* 0xxxxxxx */
  94355. v = x;
  94356. i = 0;
  94357. }
  94358. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94359. v = x & 0x1F;
  94360. i = 1;
  94361. }
  94362. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94363. v = x & 0x0F;
  94364. i = 2;
  94365. }
  94366. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94367. v = x & 0x07;
  94368. i = 3;
  94369. }
  94370. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94371. v = x & 0x03;
  94372. i = 4;
  94373. }
  94374. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94375. v = x & 0x01;
  94376. i = 5;
  94377. }
  94378. else {
  94379. *val = 0xffffffff;
  94380. return true;
  94381. }
  94382. for( ; i; i--) {
  94383. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94384. return false;
  94385. if(raw)
  94386. raw[(*rawlen)++] = (FLAC__byte)x;
  94387. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94388. *val = 0xffffffff;
  94389. return true;
  94390. }
  94391. v <<= 6;
  94392. v |= (x & 0x3F);
  94393. }
  94394. *val = v;
  94395. return true;
  94396. }
  94397. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  94398. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  94399. {
  94400. FLAC__uint64 v = 0;
  94401. FLAC__uint32 x;
  94402. unsigned i;
  94403. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94404. return false;
  94405. if(raw)
  94406. raw[(*rawlen)++] = (FLAC__byte)x;
  94407. if(!(x & 0x80)) { /* 0xxxxxxx */
  94408. v = x;
  94409. i = 0;
  94410. }
  94411. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  94412. v = x & 0x1F;
  94413. i = 1;
  94414. }
  94415. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  94416. v = x & 0x0F;
  94417. i = 2;
  94418. }
  94419. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  94420. v = x & 0x07;
  94421. i = 3;
  94422. }
  94423. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  94424. v = x & 0x03;
  94425. i = 4;
  94426. }
  94427. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  94428. v = x & 0x01;
  94429. i = 5;
  94430. }
  94431. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  94432. v = 0;
  94433. i = 6;
  94434. }
  94435. else {
  94436. *val = FLAC__U64L(0xffffffffffffffff);
  94437. return true;
  94438. }
  94439. for( ; i; i--) {
  94440. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  94441. return false;
  94442. if(raw)
  94443. raw[(*rawlen)++] = (FLAC__byte)x;
  94444. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  94445. *val = FLAC__U64L(0xffffffffffffffff);
  94446. return true;
  94447. }
  94448. v <<= 6;
  94449. v |= (x & 0x3F);
  94450. }
  94451. *val = v;
  94452. return true;
  94453. }
  94454. #endif
  94455. /*** End of inlined file: bitreader.c ***/
  94456. /*** Start of inlined file: bitwriter.c ***/
  94457. /*** Start of inlined file: juce_FlacHeader.h ***/
  94458. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94459. // tasks..
  94460. #define VERSION "1.2.1"
  94461. #define FLAC__NO_DLL 1
  94462. #if JUCE_MSVC
  94463. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94464. #endif
  94465. #if JUCE_MAC
  94466. #define FLAC__SYS_DARWIN 1
  94467. #endif
  94468. /*** End of inlined file: juce_FlacHeader.h ***/
  94469. #if JUCE_USE_FLAC
  94470. #if HAVE_CONFIG_H
  94471. # include <config.h>
  94472. #endif
  94473. #include <stdlib.h> /* for malloc() */
  94474. #include <string.h> /* for memcpy(), memset() */
  94475. #ifdef _MSC_VER
  94476. #include <winsock.h> /* for ntohl() */
  94477. #elif defined FLAC__SYS_DARWIN
  94478. #include <machine/endian.h> /* for ntohl() */
  94479. #elif defined __MINGW32__
  94480. #include <winsock.h> /* for ntohl() */
  94481. #else
  94482. #include <netinet/in.h> /* for ntohl() */
  94483. #endif
  94484. #if 0 /* UNUSED */
  94485. #endif
  94486. /*** Start of inlined file: bitwriter.h ***/
  94487. #ifndef FLAC__PRIVATE__BITWRITER_H
  94488. #define FLAC__PRIVATE__BITWRITER_H
  94489. #include <stdio.h> /* for FILE */
  94490. /*
  94491. * opaque structure definition
  94492. */
  94493. struct FLAC__BitWriter;
  94494. typedef struct FLAC__BitWriter FLAC__BitWriter;
  94495. /*
  94496. * construction, deletion, initialization, etc functions
  94497. */
  94498. FLAC__BitWriter *FLAC__bitwriter_new(void);
  94499. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  94500. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  94501. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  94502. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  94503. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  94504. /*
  94505. * CRC functions
  94506. *
  94507. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  94508. */
  94509. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  94510. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  94511. /*
  94512. * info functions
  94513. */
  94514. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  94515. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  94516. /*
  94517. * direct buffer access
  94518. *
  94519. * there may be no calls on the bitwriter between get and release.
  94520. * the bitwriter continues to own the returned buffer.
  94521. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  94522. */
  94523. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  94524. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  94525. /*
  94526. * write functions
  94527. */
  94528. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  94529. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  94530. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  94531. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  94532. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  94533. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  94534. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  94535. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  94536. #if 0 /* UNUSED */
  94537. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  94538. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  94539. #endif
  94540. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  94541. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  94542. #if 0 /* UNUSED */
  94543. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  94544. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  94545. #endif
  94546. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  94547. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  94548. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  94549. #endif
  94550. /*** End of inlined file: bitwriter.h ***/
  94551. /*** Start of inlined file: alloc.h ***/
  94552. #ifndef FLAC__SHARE__ALLOC_H
  94553. #define FLAC__SHARE__ALLOC_H
  94554. #if HAVE_CONFIG_H
  94555. # include <config.h>
  94556. #endif
  94557. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  94558. * before #including this file, otherwise SIZE_MAX might not be defined
  94559. */
  94560. #include <limits.h> /* for SIZE_MAX */
  94561. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  94562. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  94563. #endif
  94564. #include <stdlib.h> /* for size_t, malloc(), etc */
  94565. #ifndef SIZE_MAX
  94566. # ifndef SIZE_T_MAX
  94567. # ifdef _MSC_VER
  94568. # define SIZE_T_MAX UINT_MAX
  94569. # else
  94570. # error
  94571. # endif
  94572. # endif
  94573. # define SIZE_MAX SIZE_T_MAX
  94574. #endif
  94575. #ifndef FLaC__INLINE
  94576. #define FLaC__INLINE
  94577. #endif
  94578. /* avoid malloc()ing 0 bytes, see:
  94579. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  94580. */
  94581. static FLaC__INLINE void *safe_malloc_(size_t size)
  94582. {
  94583. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94584. if(!size)
  94585. size++;
  94586. return malloc(size);
  94587. }
  94588. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  94589. {
  94590. if(!nmemb || !size)
  94591. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94592. return calloc(nmemb, size);
  94593. }
  94594. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  94595. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  94596. {
  94597. size2 += size1;
  94598. if(size2 < size1)
  94599. return 0;
  94600. return safe_malloc_(size2);
  94601. }
  94602. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  94603. {
  94604. size2 += size1;
  94605. if(size2 < size1)
  94606. return 0;
  94607. size3 += size2;
  94608. if(size3 < size2)
  94609. return 0;
  94610. return safe_malloc_(size3);
  94611. }
  94612. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  94613. {
  94614. size2 += size1;
  94615. if(size2 < size1)
  94616. return 0;
  94617. size3 += size2;
  94618. if(size3 < size2)
  94619. return 0;
  94620. size4 += size3;
  94621. if(size4 < size3)
  94622. return 0;
  94623. return safe_malloc_(size4);
  94624. }
  94625. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  94626. #if 0
  94627. needs support for cases where sizeof(size_t) != 4
  94628. {
  94629. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  94630. if(sizeof(size_t) == 4) {
  94631. if ((double)size1 * (double)size2 < 4294967296.0)
  94632. return malloc(size1*size2);
  94633. }
  94634. return 0;
  94635. }
  94636. #else
  94637. /* better? */
  94638. {
  94639. if(!size1 || !size2)
  94640. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94641. if(size1 > SIZE_MAX / size2)
  94642. return 0;
  94643. return malloc(size1*size2);
  94644. }
  94645. #endif
  94646. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  94647. {
  94648. if(!size1 || !size2 || !size3)
  94649. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94650. if(size1 > SIZE_MAX / size2)
  94651. return 0;
  94652. size1 *= size2;
  94653. if(size1 > SIZE_MAX / size3)
  94654. return 0;
  94655. return malloc(size1*size3);
  94656. }
  94657. /* size1*size2 + size3 */
  94658. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  94659. {
  94660. if(!size1 || !size2)
  94661. return safe_malloc_(size3);
  94662. if(size1 > SIZE_MAX / size2)
  94663. return 0;
  94664. return safe_malloc_add_2op_(size1*size2, size3);
  94665. }
  94666. /* size1 * (size2 + size3) */
  94667. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  94668. {
  94669. if(!size1 || (!size2 && !size3))
  94670. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  94671. size2 += size3;
  94672. if(size2 < size3)
  94673. return 0;
  94674. return safe_malloc_mul_2op_(size1, size2);
  94675. }
  94676. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  94677. {
  94678. size2 += size1;
  94679. if(size2 < size1)
  94680. return 0;
  94681. return realloc(ptr, size2);
  94682. }
  94683. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  94684. {
  94685. size2 += size1;
  94686. if(size2 < size1)
  94687. return 0;
  94688. size3 += size2;
  94689. if(size3 < size2)
  94690. return 0;
  94691. return realloc(ptr, size3);
  94692. }
  94693. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  94694. {
  94695. size2 += size1;
  94696. if(size2 < size1)
  94697. return 0;
  94698. size3 += size2;
  94699. if(size3 < size2)
  94700. return 0;
  94701. size4 += size3;
  94702. if(size4 < size3)
  94703. return 0;
  94704. return realloc(ptr, size4);
  94705. }
  94706. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  94707. {
  94708. if(!size1 || !size2)
  94709. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94710. if(size1 > SIZE_MAX / size2)
  94711. return 0;
  94712. return realloc(ptr, size1*size2);
  94713. }
  94714. /* size1 * (size2 + size3) */
  94715. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  94716. {
  94717. if(!size1 || (!size2 && !size3))
  94718. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  94719. size2 += size3;
  94720. if(size2 < size3)
  94721. return 0;
  94722. return safe_realloc_mul_2op_(ptr, size1, size2);
  94723. }
  94724. #endif
  94725. /*** End of inlined file: alloc.h ***/
  94726. /* Things should be fastest when this matches the machine word size */
  94727. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  94728. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  94729. typedef FLAC__uint32 bwword;
  94730. #define FLAC__BYTES_PER_WORD 4
  94731. #define FLAC__BITS_PER_WORD 32
  94732. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  94733. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  94734. #if WORDS_BIGENDIAN
  94735. #define SWAP_BE_WORD_TO_HOST(x) (x)
  94736. #else
  94737. #ifdef _MSC_VER
  94738. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  94739. #else
  94740. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  94741. #endif
  94742. #endif
  94743. /*
  94744. * The default capacity here doesn't matter too much. The buffer always grows
  94745. * to hold whatever is written to it. Usually the encoder will stop adding at
  94746. * a frame or metadata block, then write that out and clear the buffer for the
  94747. * next one.
  94748. */
  94749. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  94750. /* When growing, increment 4K at a time */
  94751. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  94752. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  94753. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  94754. #ifdef min
  94755. #undef min
  94756. #endif
  94757. #define min(x,y) ((x)<(y)?(x):(y))
  94758. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  94759. #ifdef _MSC_VER
  94760. #define FLAC__U64L(x) x
  94761. #else
  94762. #define FLAC__U64L(x) x##LLU
  94763. #endif
  94764. #ifndef FLaC__INLINE
  94765. #define FLaC__INLINE
  94766. #endif
  94767. struct FLAC__BitWriter {
  94768. bwword *buffer;
  94769. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  94770. unsigned capacity; /* capacity of buffer in words */
  94771. unsigned words; /* # of complete words in buffer */
  94772. unsigned bits; /* # of used bits in accum */
  94773. };
  94774. /* * WATCHOUT: The current implementation only grows the buffer. */
  94775. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  94776. {
  94777. unsigned new_capacity;
  94778. bwword *new_buffer;
  94779. FLAC__ASSERT(0 != bw);
  94780. FLAC__ASSERT(0 != bw->buffer);
  94781. /* calculate total words needed to store 'bits_to_add' additional bits */
  94782. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  94783. /* it's possible (due to pessimism in the growth estimation that
  94784. * leads to this call) that we don't actually need to grow
  94785. */
  94786. if(bw->capacity >= new_capacity)
  94787. return true;
  94788. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  94789. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  94790. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94791. /* make sure we got everything right */
  94792. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  94793. FLAC__ASSERT(new_capacity > bw->capacity);
  94794. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  94795. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  94796. if(new_buffer == 0)
  94797. return false;
  94798. bw->buffer = new_buffer;
  94799. bw->capacity = new_capacity;
  94800. return true;
  94801. }
  94802. /***********************************************************************
  94803. *
  94804. * Class constructor/destructor
  94805. *
  94806. ***********************************************************************/
  94807. FLAC__BitWriter *FLAC__bitwriter_new(void)
  94808. {
  94809. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  94810. /* note that calloc() sets all members to 0 for us */
  94811. return bw;
  94812. }
  94813. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  94814. {
  94815. FLAC__ASSERT(0 != bw);
  94816. FLAC__bitwriter_free(bw);
  94817. free(bw);
  94818. }
  94819. /***********************************************************************
  94820. *
  94821. * Public class methods
  94822. *
  94823. ***********************************************************************/
  94824. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  94825. {
  94826. FLAC__ASSERT(0 != bw);
  94827. bw->words = bw->bits = 0;
  94828. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  94829. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  94830. if(bw->buffer == 0)
  94831. return false;
  94832. return true;
  94833. }
  94834. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  94835. {
  94836. FLAC__ASSERT(0 != bw);
  94837. if(0 != bw->buffer)
  94838. free(bw->buffer);
  94839. bw->buffer = 0;
  94840. bw->capacity = 0;
  94841. bw->words = bw->bits = 0;
  94842. }
  94843. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  94844. {
  94845. bw->words = bw->bits = 0;
  94846. }
  94847. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  94848. {
  94849. unsigned i, j;
  94850. if(bw == 0) {
  94851. fprintf(out, "bitwriter is NULL\n");
  94852. }
  94853. else {
  94854. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  94855. for(i = 0; i < bw->words; i++) {
  94856. fprintf(out, "%08X: ", i);
  94857. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  94858. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  94859. fprintf(out, "\n");
  94860. }
  94861. if(bw->bits > 0) {
  94862. fprintf(out, "%08X: ", i);
  94863. for(j = 0; j < bw->bits; j++)
  94864. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  94865. fprintf(out, "\n");
  94866. }
  94867. }
  94868. }
  94869. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  94870. {
  94871. const FLAC__byte *buffer;
  94872. size_t bytes;
  94873. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94874. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94875. return false;
  94876. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  94877. FLAC__bitwriter_release_buffer(bw);
  94878. return true;
  94879. }
  94880. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  94881. {
  94882. const FLAC__byte *buffer;
  94883. size_t bytes;
  94884. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  94885. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  94886. return false;
  94887. *crc = FLAC__crc8(buffer, bytes);
  94888. FLAC__bitwriter_release_buffer(bw);
  94889. return true;
  94890. }
  94891. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  94892. {
  94893. return ((bw->bits & 7) == 0);
  94894. }
  94895. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  94896. {
  94897. return FLAC__TOTAL_BITS(bw);
  94898. }
  94899. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  94900. {
  94901. FLAC__ASSERT((bw->bits & 7) == 0);
  94902. /* double protection */
  94903. if(bw->bits & 7)
  94904. return false;
  94905. /* if we have bits in the accumulator we have to flush those to the buffer first */
  94906. if(bw->bits) {
  94907. FLAC__ASSERT(bw->words <= bw->capacity);
  94908. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  94909. return false;
  94910. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  94911. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  94912. }
  94913. /* now we can just return what we have */
  94914. *buffer = (FLAC__byte*)bw->buffer;
  94915. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  94916. return true;
  94917. }
  94918. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  94919. {
  94920. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  94921. * get-mode' flag could be added everywhere and then cleared here
  94922. */
  94923. (void)bw;
  94924. }
  94925. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  94926. {
  94927. unsigned n;
  94928. FLAC__ASSERT(0 != bw);
  94929. FLAC__ASSERT(0 != bw->buffer);
  94930. if(bits == 0)
  94931. return true;
  94932. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94933. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94934. return false;
  94935. /* first part gets to word alignment */
  94936. if(bw->bits) {
  94937. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  94938. bw->accum <<= n;
  94939. bits -= n;
  94940. bw->bits += n;
  94941. if(bw->bits == FLAC__BITS_PER_WORD) {
  94942. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94943. bw->bits = 0;
  94944. }
  94945. else
  94946. return true;
  94947. }
  94948. /* do whole words */
  94949. while(bits >= FLAC__BITS_PER_WORD) {
  94950. bw->buffer[bw->words++] = 0;
  94951. bits -= FLAC__BITS_PER_WORD;
  94952. }
  94953. /* do any leftovers */
  94954. if(bits > 0) {
  94955. bw->accum = 0;
  94956. bw->bits = bits;
  94957. }
  94958. return true;
  94959. }
  94960. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  94961. {
  94962. register unsigned left;
  94963. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  94964. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  94965. FLAC__ASSERT(0 != bw);
  94966. FLAC__ASSERT(0 != bw->buffer);
  94967. FLAC__ASSERT(bits <= 32);
  94968. if(bits == 0)
  94969. return true;
  94970. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  94971. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  94972. return false;
  94973. left = FLAC__BITS_PER_WORD - bw->bits;
  94974. if(bits < left) {
  94975. bw->accum <<= bits;
  94976. bw->accum |= val;
  94977. bw->bits += bits;
  94978. }
  94979. 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 */
  94980. bw->accum <<= left;
  94981. bw->accum |= val >> (bw->bits = bits - left);
  94982. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  94983. bw->accum = val;
  94984. }
  94985. else {
  94986. bw->accum = val;
  94987. bw->bits = 0;
  94988. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  94989. }
  94990. return true;
  94991. }
  94992. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  94993. {
  94994. /* zero-out unused bits */
  94995. if(bits < 32)
  94996. val &= (~(0xffffffff << bits));
  94997. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  94998. }
  94999. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  95000. {
  95001. /* this could be a little faster but it's not used for much */
  95002. if(bits > 32) {
  95003. return
  95004. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  95005. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  95006. }
  95007. else
  95008. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  95009. }
  95010. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  95011. {
  95012. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  95013. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  95014. return false;
  95015. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  95016. return false;
  95017. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  95018. return false;
  95019. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  95020. return false;
  95021. return true;
  95022. }
  95023. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  95024. {
  95025. unsigned i;
  95026. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  95027. for(i = 0; i < nvals; i++) {
  95028. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  95029. return false;
  95030. }
  95031. return true;
  95032. }
  95033. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  95034. {
  95035. if(val < 32)
  95036. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  95037. else
  95038. return
  95039. FLAC__bitwriter_write_zeroes(bw, val) &&
  95040. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  95041. }
  95042. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  95043. {
  95044. FLAC__uint32 uval;
  95045. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  95046. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95047. uval = (val<<1) ^ (val>>31);
  95048. return 1 + parameter + (uval >> parameter);
  95049. }
  95050. #if 0 /* UNUSED */
  95051. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  95052. {
  95053. unsigned bits, msbs, uval;
  95054. unsigned k;
  95055. FLAC__ASSERT(parameter > 0);
  95056. /* fold signed to unsigned */
  95057. if(val < 0)
  95058. uval = (unsigned)(((-(++val)) << 1) + 1);
  95059. else
  95060. uval = (unsigned)(val << 1);
  95061. k = FLAC__bitmath_ilog2(parameter);
  95062. if(parameter == 1u<<k) {
  95063. FLAC__ASSERT(k <= 30);
  95064. msbs = uval >> k;
  95065. bits = 1 + k + msbs;
  95066. }
  95067. else {
  95068. unsigned q, r, d;
  95069. d = (1 << (k+1)) - parameter;
  95070. q = uval / parameter;
  95071. r = uval - (q * parameter);
  95072. bits = 1 + q + k;
  95073. if(r >= d)
  95074. bits++;
  95075. }
  95076. return bits;
  95077. }
  95078. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  95079. {
  95080. unsigned bits, msbs;
  95081. unsigned k;
  95082. FLAC__ASSERT(parameter > 0);
  95083. k = FLAC__bitmath_ilog2(parameter);
  95084. if(parameter == 1u<<k) {
  95085. FLAC__ASSERT(k <= 30);
  95086. msbs = uval >> k;
  95087. bits = 1 + k + msbs;
  95088. }
  95089. else {
  95090. unsigned q, r, d;
  95091. d = (1 << (k+1)) - parameter;
  95092. q = uval / parameter;
  95093. r = uval - (q * parameter);
  95094. bits = 1 + q + k;
  95095. if(r >= d)
  95096. bits++;
  95097. }
  95098. return bits;
  95099. }
  95100. #endif /* UNUSED */
  95101. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  95102. {
  95103. unsigned total_bits, interesting_bits, msbs;
  95104. FLAC__uint32 uval, pattern;
  95105. FLAC__ASSERT(0 != bw);
  95106. FLAC__ASSERT(0 != bw->buffer);
  95107. FLAC__ASSERT(parameter < 8*sizeof(uval));
  95108. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95109. uval = (val<<1) ^ (val>>31);
  95110. msbs = uval >> parameter;
  95111. interesting_bits = 1 + parameter;
  95112. total_bits = interesting_bits + msbs;
  95113. pattern = 1 << parameter; /* the unary end bit */
  95114. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  95115. if(total_bits <= 32)
  95116. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  95117. else
  95118. return
  95119. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  95120. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  95121. }
  95122. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  95123. {
  95124. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  95125. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  95126. FLAC__uint32 uval;
  95127. unsigned left;
  95128. const unsigned lsbits = 1 + parameter;
  95129. unsigned msbits;
  95130. FLAC__ASSERT(0 != bw);
  95131. FLAC__ASSERT(0 != bw->buffer);
  95132. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  95133. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  95134. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  95135. while(nvals) {
  95136. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  95137. uval = (*vals<<1) ^ (*vals>>31);
  95138. msbits = uval >> parameter;
  95139. #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) */
  95140. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95141. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95142. bw->bits = bw->bits + msbits + lsbits;
  95143. uval |= mask1; /* set stop bit */
  95144. uval &= mask2; /* mask off unused top bits */
  95145. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  95146. bw->accum <<= msbits;
  95147. bw->accum <<= lsbits;
  95148. bw->accum |= uval;
  95149. if(bw->bits == FLAC__BITS_PER_WORD) {
  95150. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95151. bw->bits = 0;
  95152. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  95153. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  95154. FLAC__ASSERT(bw->capacity == bw->words);
  95155. return false;
  95156. }
  95157. }
  95158. }
  95159. else {
  95160. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  95161. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  95162. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  95163. bw->bits = bw->bits + msbits + lsbits;
  95164. uval |= mask1; /* set stop bit */
  95165. uval &= mask2; /* mask off unused top bits */
  95166. bw->accum <<= msbits + lsbits;
  95167. bw->accum |= uval;
  95168. }
  95169. else {
  95170. #endif
  95171. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  95172. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  95173. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  95174. return false;
  95175. if(msbits) {
  95176. /* first part gets to word alignment */
  95177. if(bw->bits) {
  95178. left = FLAC__BITS_PER_WORD - bw->bits;
  95179. if(msbits < left) {
  95180. bw->accum <<= msbits;
  95181. bw->bits += msbits;
  95182. goto break1;
  95183. }
  95184. else {
  95185. bw->accum <<= left;
  95186. msbits -= left;
  95187. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95188. bw->bits = 0;
  95189. }
  95190. }
  95191. /* do whole words */
  95192. while(msbits >= FLAC__BITS_PER_WORD) {
  95193. bw->buffer[bw->words++] = 0;
  95194. msbits -= FLAC__BITS_PER_WORD;
  95195. }
  95196. /* do any leftovers */
  95197. if(msbits > 0) {
  95198. bw->accum = 0;
  95199. bw->bits = msbits;
  95200. }
  95201. }
  95202. break1:
  95203. uval |= mask1; /* set stop bit */
  95204. uval &= mask2; /* mask off unused top bits */
  95205. left = FLAC__BITS_PER_WORD - bw->bits;
  95206. if(lsbits < left) {
  95207. bw->accum <<= lsbits;
  95208. bw->accum |= uval;
  95209. bw->bits += lsbits;
  95210. }
  95211. else {
  95212. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  95213. * be > lsbits (because of previous assertions) so it would have
  95214. * triggered the (lsbits<left) case above.
  95215. */
  95216. FLAC__ASSERT(bw->bits);
  95217. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  95218. bw->accum <<= left;
  95219. bw->accum |= uval >> (bw->bits = lsbits - left);
  95220. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  95221. bw->accum = uval;
  95222. }
  95223. #if 1
  95224. }
  95225. #endif
  95226. vals++;
  95227. nvals--;
  95228. }
  95229. return true;
  95230. }
  95231. #if 0 /* UNUSED */
  95232. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  95233. {
  95234. unsigned total_bits, msbs, uval;
  95235. unsigned k;
  95236. FLAC__ASSERT(0 != bw);
  95237. FLAC__ASSERT(0 != bw->buffer);
  95238. FLAC__ASSERT(parameter > 0);
  95239. /* fold signed to unsigned */
  95240. if(val < 0)
  95241. uval = (unsigned)(((-(++val)) << 1) + 1);
  95242. else
  95243. uval = (unsigned)(val << 1);
  95244. k = FLAC__bitmath_ilog2(parameter);
  95245. if(parameter == 1u<<k) {
  95246. unsigned pattern;
  95247. FLAC__ASSERT(k <= 30);
  95248. msbs = uval >> k;
  95249. total_bits = 1 + k + msbs;
  95250. pattern = 1 << k; /* the unary end bit */
  95251. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95252. if(total_bits <= 32) {
  95253. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95254. return false;
  95255. }
  95256. else {
  95257. /* write the unary MSBs */
  95258. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95259. return false;
  95260. /* write the unary end bit and binary LSBs */
  95261. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95262. return false;
  95263. }
  95264. }
  95265. else {
  95266. unsigned q, r, d;
  95267. d = (1 << (k+1)) - parameter;
  95268. q = uval / parameter;
  95269. r = uval - (q * parameter);
  95270. /* write the unary MSBs */
  95271. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95272. return false;
  95273. /* write the unary end bit */
  95274. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95275. return false;
  95276. /* write the binary LSBs */
  95277. if(r >= d) {
  95278. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95279. return false;
  95280. }
  95281. else {
  95282. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95283. return false;
  95284. }
  95285. }
  95286. return true;
  95287. }
  95288. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  95289. {
  95290. unsigned total_bits, msbs;
  95291. unsigned k;
  95292. FLAC__ASSERT(0 != bw);
  95293. FLAC__ASSERT(0 != bw->buffer);
  95294. FLAC__ASSERT(parameter > 0);
  95295. k = FLAC__bitmath_ilog2(parameter);
  95296. if(parameter == 1u<<k) {
  95297. unsigned pattern;
  95298. FLAC__ASSERT(k <= 30);
  95299. msbs = uval >> k;
  95300. total_bits = 1 + k + msbs;
  95301. pattern = 1 << k; /* the unary end bit */
  95302. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  95303. if(total_bits <= 32) {
  95304. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  95305. return false;
  95306. }
  95307. else {
  95308. /* write the unary MSBs */
  95309. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  95310. return false;
  95311. /* write the unary end bit and binary LSBs */
  95312. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  95313. return false;
  95314. }
  95315. }
  95316. else {
  95317. unsigned q, r, d;
  95318. d = (1 << (k+1)) - parameter;
  95319. q = uval / parameter;
  95320. r = uval - (q * parameter);
  95321. /* write the unary MSBs */
  95322. if(!FLAC__bitwriter_write_zeroes(bw, q))
  95323. return false;
  95324. /* write the unary end bit */
  95325. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  95326. return false;
  95327. /* write the binary LSBs */
  95328. if(r >= d) {
  95329. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  95330. return false;
  95331. }
  95332. else {
  95333. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  95334. return false;
  95335. }
  95336. }
  95337. return true;
  95338. }
  95339. #endif /* UNUSED */
  95340. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  95341. {
  95342. FLAC__bool ok = 1;
  95343. FLAC__ASSERT(0 != bw);
  95344. FLAC__ASSERT(0 != bw->buffer);
  95345. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  95346. if(val < 0x80) {
  95347. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  95348. }
  95349. else if(val < 0x800) {
  95350. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  95351. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95352. }
  95353. else if(val < 0x10000) {
  95354. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  95355. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95356. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95357. }
  95358. else if(val < 0x200000) {
  95359. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 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. else if(val < 0x4000000) {
  95365. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  95366. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95367. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95368. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95369. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95370. }
  95371. else {
  95372. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  95373. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  95374. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  95375. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  95376. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  95377. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  95378. }
  95379. return ok;
  95380. }
  95381. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  95382. {
  95383. FLAC__bool ok = 1;
  95384. FLAC__ASSERT(0 != bw);
  95385. FLAC__ASSERT(0 != bw->buffer);
  95386. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  95387. if(val < 0x80) {
  95388. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  95389. }
  95390. else if(val < 0x800) {
  95391. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  95392. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95393. }
  95394. else if(val < 0x10000) {
  95395. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  95396. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95397. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95398. }
  95399. else if(val < 0x200000) {
  95400. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 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 if(val < 0x4000000) {
  95406. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  95407. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95408. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95409. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95410. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95411. }
  95412. else if(val < 0x80000000) {
  95413. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  95414. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95415. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95416. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95417. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95418. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95419. }
  95420. else {
  95421. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  95422. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  95423. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  95424. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  95425. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  95426. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  95427. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  95428. }
  95429. return ok;
  95430. }
  95431. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  95432. {
  95433. /* 0-pad to byte boundary */
  95434. if(bw->bits & 7u)
  95435. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  95436. else
  95437. return true;
  95438. }
  95439. #endif
  95440. /*** End of inlined file: bitwriter.c ***/
  95441. /*** Start of inlined file: cpu.c ***/
  95442. /*** Start of inlined file: juce_FlacHeader.h ***/
  95443. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95444. // tasks..
  95445. #define VERSION "1.2.1"
  95446. #define FLAC__NO_DLL 1
  95447. #if JUCE_MSVC
  95448. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95449. #endif
  95450. #if JUCE_MAC
  95451. #define FLAC__SYS_DARWIN 1
  95452. #endif
  95453. /*** End of inlined file: juce_FlacHeader.h ***/
  95454. #if JUCE_USE_FLAC
  95455. #if HAVE_CONFIG_H
  95456. # include <config.h>
  95457. #endif
  95458. #include <stdlib.h>
  95459. #include <stdio.h>
  95460. #if defined FLAC__CPU_IA32
  95461. # include <signal.h>
  95462. #elif defined FLAC__CPU_PPC
  95463. # if !defined FLAC__NO_ASM
  95464. # if defined FLAC__SYS_DARWIN
  95465. # include <sys/sysctl.h>
  95466. # include <mach/mach.h>
  95467. # include <mach/mach_host.h>
  95468. # include <mach/host_info.h>
  95469. # include <mach/machine.h>
  95470. # ifndef CPU_SUBTYPE_POWERPC_970
  95471. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  95472. # endif
  95473. # else /* FLAC__SYS_DARWIN */
  95474. # include <signal.h>
  95475. # include <setjmp.h>
  95476. static sigjmp_buf jmpbuf;
  95477. static volatile sig_atomic_t canjump = 0;
  95478. static void sigill_handler (int sig)
  95479. {
  95480. if (!canjump) {
  95481. signal (sig, SIG_DFL);
  95482. raise (sig);
  95483. }
  95484. canjump = 0;
  95485. siglongjmp (jmpbuf, 1);
  95486. }
  95487. # endif /* FLAC__SYS_DARWIN */
  95488. # endif /* FLAC__NO_ASM */
  95489. #endif /* FLAC__CPU_PPC */
  95490. #if defined (__NetBSD__) || defined(__OpenBSD__)
  95491. #include <sys/param.h>
  95492. #include <sys/sysctl.h>
  95493. #include <machine/cpu.h>
  95494. #endif
  95495. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  95496. #include <sys/types.h>
  95497. #include <sys/sysctl.h>
  95498. #endif
  95499. #if defined(__APPLE__)
  95500. /* how to get sysctlbyname()? */
  95501. #endif
  95502. /* these are flags in EDX of CPUID AX=00000001 */
  95503. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  95504. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  95505. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  95506. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  95507. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  95508. /* these are flags in ECX of CPUID AX=00000001 */
  95509. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  95510. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  95511. /* these are flags in EDX of CPUID AX=80000001 */
  95512. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  95513. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  95514. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  95515. /*
  95516. * Extra stuff needed for detection of OS support for SSE on IA-32
  95517. */
  95518. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  95519. # if defined(__linux__)
  95520. /*
  95521. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  95522. * modify the return address to jump over the offending SSE instruction
  95523. * and also the operation following it that indicates the instruction
  95524. * executed successfully. In this way we use no global variables and
  95525. * stay thread-safe.
  95526. *
  95527. * 3 + 3 + 6:
  95528. * 3 bytes for "xorps xmm0,xmm0"
  95529. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  95530. * 6 bytes extra in case our estimate is wrong
  95531. * 12 bytes puts us in the NOP "landing zone"
  95532. */
  95533. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  95534. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95535. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  95536. {
  95537. (void)signal;
  95538. sc.eip += 3 + 3 + 6;
  95539. }
  95540. # else
  95541. # include <sys/ucontext.h>
  95542. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  95543. {
  95544. (void)signal, (void)si;
  95545. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  95546. }
  95547. # endif
  95548. # elif defined(_MSC_VER)
  95549. # include <windows.h>
  95550. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  95551. # ifdef USE_TRY_CATCH_FLAVOR
  95552. # else
  95553. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  95554. {
  95555. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  95556. ep->ContextRecord->Eip += 3 + 3 + 6;
  95557. return EXCEPTION_CONTINUE_EXECUTION;
  95558. }
  95559. return EXCEPTION_CONTINUE_SEARCH;
  95560. }
  95561. # endif
  95562. # endif
  95563. #endif
  95564. void FLAC__cpu_info(FLAC__CPUInfo *info)
  95565. {
  95566. /*
  95567. * IA32-specific
  95568. */
  95569. #ifdef FLAC__CPU_IA32
  95570. info->type = FLAC__CPUINFO_TYPE_IA32;
  95571. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  95572. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  95573. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  95574. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  95575. info->data.ia32.cmov = false;
  95576. info->data.ia32.mmx = false;
  95577. info->data.ia32.fxsr = false;
  95578. info->data.ia32.sse = false;
  95579. info->data.ia32.sse2 = false;
  95580. info->data.ia32.sse3 = false;
  95581. info->data.ia32.ssse3 = false;
  95582. info->data.ia32._3dnow = false;
  95583. info->data.ia32.ext3dnow = false;
  95584. info->data.ia32.extmmx = false;
  95585. if(info->data.ia32.cpuid) {
  95586. /* http://www.sandpile.org/ia32/cpuid.htm */
  95587. FLAC__uint32 flags_edx, flags_ecx;
  95588. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  95589. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  95590. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  95591. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  95592. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  95593. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  95594. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  95595. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  95596. #ifdef FLAC__USE_3DNOW
  95597. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  95598. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  95599. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  95600. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  95601. #else
  95602. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  95603. #endif
  95604. #ifdef DEBUG
  95605. fprintf(stderr, "CPU info (IA-32):\n");
  95606. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  95607. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  95608. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  95609. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  95610. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  95611. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95612. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  95613. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  95614. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  95615. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  95616. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  95617. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  95618. #endif
  95619. /*
  95620. * now have to check for OS support of SSE/SSE2
  95621. */
  95622. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  95623. #if defined FLAC__NO_SSE_OS
  95624. /* assume user knows better than us; turn it off */
  95625. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95626. #elif defined FLAC__SSE_OS
  95627. /* assume user knows better than us; leave as detected above */
  95628. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  95629. int sse = 0;
  95630. size_t len;
  95631. /* at least one of these must work: */
  95632. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  95633. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  95634. if(!sse)
  95635. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95636. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  95637. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  95638. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  95639. size_t len = sizeof(val);
  95640. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95641. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95642. else { /* double-check SSE2 */
  95643. mib[1] = CPU_SSE2;
  95644. len = sizeof(val);
  95645. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  95646. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95647. }
  95648. # else
  95649. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95650. # endif
  95651. #elif defined(__linux__)
  95652. int sse = 0;
  95653. struct sigaction sigill_save;
  95654. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  95655. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  95656. #else
  95657. struct sigaction sigill_sse;
  95658. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  95659. __sigemptyset(&sigill_sse.sa_mask);
  95660. 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 */
  95661. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  95662. #endif
  95663. {
  95664. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  95665. /* see sigill_handler_sse_os() for an explanation of the following: */
  95666. asm volatile (
  95667. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  95668. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  95669. "incl %0\n\t" /* SIGILL handler will jump over this */
  95670. /* landing zone */
  95671. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  95672. "nop\n\t"
  95673. "nop\n\t"
  95674. "nop\n\t"
  95675. "nop\n\t"
  95676. "nop\n\t"
  95677. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  95678. "nop\n\t"
  95679. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  95680. : "=r"(sse)
  95681. : "r"(sse)
  95682. );
  95683. sigaction(SIGILL, &sigill_save, NULL);
  95684. }
  95685. if(!sse)
  95686. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95687. #elif defined(_MSC_VER)
  95688. # ifdef USE_TRY_CATCH_FLAVOR
  95689. _try {
  95690. __asm {
  95691. # if _MSC_VER <= 1200
  95692. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95693. _emit 0x0F
  95694. _emit 0x57
  95695. _emit 0xC0
  95696. # else
  95697. xorps xmm0,xmm0
  95698. # endif
  95699. }
  95700. }
  95701. _except(EXCEPTION_EXECUTE_HANDLER) {
  95702. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  95703. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95704. }
  95705. # else
  95706. int sse = 0;
  95707. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  95708. /* see GCC version above for explanation */
  95709. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  95710. /* http://www.codeproject.com/cpp/gccasm.asp */
  95711. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  95712. __asm {
  95713. # if _MSC_VER <= 1200
  95714. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  95715. _emit 0x0F
  95716. _emit 0x57
  95717. _emit 0xC0
  95718. # else
  95719. xorps xmm0,xmm0
  95720. # endif
  95721. inc sse
  95722. nop
  95723. nop
  95724. nop
  95725. nop
  95726. nop
  95727. nop
  95728. nop
  95729. nop
  95730. nop
  95731. }
  95732. SetUnhandledExceptionFilter(save);
  95733. if(!sse)
  95734. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95735. # endif
  95736. #else
  95737. /* no way to test, disable to be safe */
  95738. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  95739. #endif
  95740. #ifdef DEBUG
  95741. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  95742. #endif
  95743. }
  95744. }
  95745. #else
  95746. info->use_asm = false;
  95747. #endif
  95748. /*
  95749. * PPC-specific
  95750. */
  95751. #elif defined FLAC__CPU_PPC
  95752. info->type = FLAC__CPUINFO_TYPE_PPC;
  95753. # if !defined FLAC__NO_ASM
  95754. info->use_asm = true;
  95755. # ifdef FLAC__USE_ALTIVEC
  95756. # if defined FLAC__SYS_DARWIN
  95757. {
  95758. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  95759. size_t len = sizeof(val);
  95760. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  95761. }
  95762. {
  95763. host_basic_info_data_t hostInfo;
  95764. mach_msg_type_number_t infoCount;
  95765. infoCount = HOST_BASIC_INFO_COUNT;
  95766. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  95767. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  95768. }
  95769. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  95770. {
  95771. /* no Darwin, do it the brute-force way */
  95772. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  95773. info->data.ppc.altivec = 0;
  95774. info->data.ppc.ppc64 = 0;
  95775. signal (SIGILL, sigill_handler);
  95776. canjump = 0;
  95777. if (!sigsetjmp (jmpbuf, 1)) {
  95778. canjump = 1;
  95779. asm volatile (
  95780. "mtspr 256, %0\n\t"
  95781. "vand %%v0, %%v0, %%v0"
  95782. :
  95783. : "r" (-1)
  95784. );
  95785. info->data.ppc.altivec = 1;
  95786. }
  95787. canjump = 0;
  95788. if (!sigsetjmp (jmpbuf, 1)) {
  95789. int x = 0;
  95790. canjump = 1;
  95791. /* PPC64 hardware implements the cntlzd instruction */
  95792. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  95793. info->data.ppc.ppc64 = 1;
  95794. }
  95795. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  95796. }
  95797. # endif
  95798. # else /* !FLAC__USE_ALTIVEC */
  95799. info->data.ppc.altivec = 0;
  95800. info->data.ppc.ppc64 = 0;
  95801. # endif
  95802. # else
  95803. info->use_asm = false;
  95804. # endif
  95805. /*
  95806. * unknown CPI
  95807. */
  95808. #else
  95809. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  95810. info->use_asm = false;
  95811. #endif
  95812. }
  95813. #endif
  95814. /*** End of inlined file: cpu.c ***/
  95815. /*** Start of inlined file: crc.c ***/
  95816. /*** Start of inlined file: juce_FlacHeader.h ***/
  95817. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95818. // tasks..
  95819. #define VERSION "1.2.1"
  95820. #define FLAC__NO_DLL 1
  95821. #if JUCE_MSVC
  95822. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95823. #endif
  95824. #if JUCE_MAC
  95825. #define FLAC__SYS_DARWIN 1
  95826. #endif
  95827. /*** End of inlined file: juce_FlacHeader.h ***/
  95828. #if JUCE_USE_FLAC
  95829. #if HAVE_CONFIG_H
  95830. # include <config.h>
  95831. #endif
  95832. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  95833. FLAC__byte const FLAC__crc8_table[256] = {
  95834. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  95835. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  95836. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  95837. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  95838. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  95839. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  95840. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  95841. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  95842. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  95843. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  95844. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  95845. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  95846. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  95847. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  95848. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  95849. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  95850. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  95851. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  95852. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  95853. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  95854. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  95855. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  95856. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  95857. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  95858. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  95859. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  95860. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  95861. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  95862. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  95863. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  95864. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  95865. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  95866. };
  95867. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  95868. unsigned FLAC__crc16_table[256] = {
  95869. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  95870. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  95871. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  95872. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  95873. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  95874. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  95875. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  95876. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  95877. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  95878. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  95879. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  95880. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  95881. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  95882. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  95883. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  95884. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  95885. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  95886. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  95887. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  95888. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  95889. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  95890. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  95891. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  95892. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  95893. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  95894. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  95895. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  95896. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  95897. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  95898. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  95899. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  95900. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  95901. };
  95902. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  95903. {
  95904. *crc = FLAC__crc8_table[*crc ^ data];
  95905. }
  95906. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  95907. {
  95908. while(len--)
  95909. *crc = FLAC__crc8_table[*crc ^ *data++];
  95910. }
  95911. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  95912. {
  95913. FLAC__uint8 crc = 0;
  95914. while(len--)
  95915. crc = FLAC__crc8_table[crc ^ *data++];
  95916. return crc;
  95917. }
  95918. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  95919. {
  95920. unsigned crc = 0;
  95921. while(len--)
  95922. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  95923. return crc;
  95924. }
  95925. #endif
  95926. /*** End of inlined file: crc.c ***/
  95927. /*** Start of inlined file: fixed.c ***/
  95928. /*** Start of inlined file: juce_FlacHeader.h ***/
  95929. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95930. // tasks..
  95931. #define VERSION "1.2.1"
  95932. #define FLAC__NO_DLL 1
  95933. #if JUCE_MSVC
  95934. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95935. #endif
  95936. #if JUCE_MAC
  95937. #define FLAC__SYS_DARWIN 1
  95938. #endif
  95939. /*** End of inlined file: juce_FlacHeader.h ***/
  95940. #if JUCE_USE_FLAC
  95941. #if HAVE_CONFIG_H
  95942. # include <config.h>
  95943. #endif
  95944. #include <math.h>
  95945. #include <string.h>
  95946. /*** Start of inlined file: fixed.h ***/
  95947. #ifndef FLAC__PRIVATE__FIXED_H
  95948. #define FLAC__PRIVATE__FIXED_H
  95949. #ifdef HAVE_CONFIG_H
  95950. #include <config.h>
  95951. #endif
  95952. /*** Start of inlined file: float.h ***/
  95953. #ifndef FLAC__PRIVATE__FLOAT_H
  95954. #define FLAC__PRIVATE__FLOAT_H
  95955. #ifdef HAVE_CONFIG_H
  95956. #include <config.h>
  95957. #endif
  95958. /*
  95959. * These typedefs make it easier to ensure that integer versions of
  95960. * the library really only contain integer operations. All the code
  95961. * in libFLAC should use FLAC__float and FLAC__double in place of
  95962. * float and double, and be protected by checks of the macro
  95963. * FLAC__INTEGER_ONLY_LIBRARY.
  95964. *
  95965. * FLAC__real is the basic floating point type used in LPC analysis.
  95966. */
  95967. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95968. typedef double FLAC__double;
  95969. typedef float FLAC__float;
  95970. /*
  95971. * WATCHOUT: changing FLAC__real will change the signatures of many
  95972. * functions that have assembly language equivalents and break them.
  95973. */
  95974. typedef float FLAC__real;
  95975. #else
  95976. /*
  95977. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  95978. * for the integer part and lower 16 bits for the fractional part.
  95979. */
  95980. typedef FLAC__int32 FLAC__fixedpoint;
  95981. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  95982. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  95983. extern const FLAC__fixedpoint FLAC__FP_ONE;
  95984. extern const FLAC__fixedpoint FLAC__FP_LN2;
  95985. extern const FLAC__fixedpoint FLAC__FP_E;
  95986. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  95987. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  95988. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  95989. /*
  95990. * FLAC__fixedpoint_log2()
  95991. * --------------------------------------------------------------------
  95992. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  95993. * algorithm by Knuth for x >= 1.0
  95994. *
  95995. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  95996. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  95997. *
  95998. * 'precision' roughly limits the number of iterations that are done;
  95999. * use (unsigned)(-1) for maximum precision.
  96000. *
  96001. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  96002. * function will punt and return 0.
  96003. *
  96004. * The return value will also have 'fracbits' fractional bits.
  96005. */
  96006. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  96007. #endif
  96008. #endif
  96009. /*** End of inlined file: float.h ***/
  96010. /*** Start of inlined file: format.h ***/
  96011. #ifndef FLAC__PRIVATE__FORMAT_H
  96012. #define FLAC__PRIVATE__FORMAT_H
  96013. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  96014. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  96015. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  96016. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  96017. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  96018. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  96019. #endif
  96020. /*** End of inlined file: format.h ***/
  96021. /*
  96022. * FLAC__fixed_compute_best_predictor()
  96023. * --------------------------------------------------------------------
  96024. * Compute the best fixed predictor and the expected bits-per-sample
  96025. * of the residual signal for each order. The _wide() version uses
  96026. * 64-bit integers which is statistically necessary when bits-per-
  96027. * sample + log2(blocksize) > 30
  96028. *
  96029. * IN data[0,data_len-1]
  96030. * IN data_len
  96031. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  96032. */
  96033. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96034. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96035. # ifndef FLAC__NO_ASM
  96036. # ifdef FLAC__CPU_IA32
  96037. # ifdef FLAC__HAS_NASM
  96038. 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]);
  96039. # endif
  96040. # endif
  96041. # endif
  96042. 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]);
  96043. #else
  96044. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  96045. 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]);
  96046. #endif
  96047. /*
  96048. * FLAC__fixed_compute_residual()
  96049. * --------------------------------------------------------------------
  96050. * Compute the residual signal obtained from sutracting the predicted
  96051. * signal from the original.
  96052. *
  96053. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  96054. * IN data_len length of original signal
  96055. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96056. * OUT residual[0,data_len-1] residual signal
  96057. */
  96058. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  96059. /*
  96060. * FLAC__fixed_restore_signal()
  96061. * --------------------------------------------------------------------
  96062. * Restore the original signal by summing the residual and the
  96063. * predictor.
  96064. *
  96065. * IN residual[0,data_len-1] residual signal
  96066. * IN data_len length of original signal
  96067. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  96068. * *** IMPORTANT: the caller must pass in the historical samples:
  96069. * IN data[-order,-1] previously-reconstructed historical samples
  96070. * OUT data[0,data_len-1] original signal
  96071. */
  96072. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  96073. #endif
  96074. /*** End of inlined file: fixed.h ***/
  96075. #ifndef M_LN2
  96076. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  96077. #define M_LN2 0.69314718055994530942
  96078. #endif
  96079. #ifdef min
  96080. #undef min
  96081. #endif
  96082. #define min(x,y) ((x) < (y)? (x) : (y))
  96083. #ifdef local_abs
  96084. #undef local_abs
  96085. #endif
  96086. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  96087. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96088. /* rbps stands for residual bits per sample
  96089. *
  96090. * (ln(2) * err)
  96091. * rbps = log (-----------)
  96092. * 2 ( n )
  96093. */
  96094. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  96095. {
  96096. FLAC__uint32 rbps;
  96097. unsigned bits; /* the number of bits required to represent a number */
  96098. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96099. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96100. FLAC__ASSERT(err > 0);
  96101. FLAC__ASSERT(n > 0);
  96102. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96103. if(err <= n)
  96104. return 0;
  96105. /*
  96106. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96107. * These allow us later to know we won't lose too much precision in the
  96108. * fixed-point division (err<<fracbits)/n.
  96109. */
  96110. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  96111. err <<= fracbits;
  96112. err /= n;
  96113. /* err now holds err/n with fracbits fractional bits */
  96114. /*
  96115. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96116. * our purposes.
  96117. */
  96118. FLAC__ASSERT(err > 0);
  96119. bits = FLAC__bitmath_ilog2(err)+1;
  96120. if(bits > 16) {
  96121. err >>= (bits-16);
  96122. fracbits -= (bits-16);
  96123. }
  96124. rbps = (FLAC__uint32)err;
  96125. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96126. rbps *= FLAC__FP_LN2;
  96127. fracbits += 16;
  96128. FLAC__ASSERT(fracbits >= 0);
  96129. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96130. {
  96131. const int f = fracbits & 3;
  96132. if(f) {
  96133. rbps >>= f;
  96134. fracbits -= f;
  96135. }
  96136. }
  96137. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96138. if(rbps == 0)
  96139. return 0;
  96140. /*
  96141. * The return value must have 16 fractional bits. Since the whole part
  96142. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96143. * must be >= -3, these assertion allows us to be able to shift rbps
  96144. * left if necessary to get 16 fracbits without losing any bits of the
  96145. * whole part of rbps.
  96146. *
  96147. * There is a slight chance due to accumulated error that the whole part
  96148. * will require 6 bits, so we use 6 in the assertion. Really though as
  96149. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96150. */
  96151. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96152. FLAC__ASSERT(fracbits >= -3);
  96153. /* now shift the decimal point into place */
  96154. if(fracbits < 16)
  96155. return rbps << (16-fracbits);
  96156. else if(fracbits > 16)
  96157. return rbps >> (fracbits-16);
  96158. else
  96159. return rbps;
  96160. }
  96161. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  96162. {
  96163. FLAC__uint32 rbps;
  96164. unsigned bits; /* the number of bits required to represent a number */
  96165. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  96166. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  96167. FLAC__ASSERT(err > 0);
  96168. FLAC__ASSERT(n > 0);
  96169. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  96170. if(err <= n)
  96171. return 0;
  96172. /*
  96173. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  96174. * These allow us later to know we won't lose too much precision in the
  96175. * fixed-point division (err<<fracbits)/n.
  96176. */
  96177. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  96178. err <<= fracbits;
  96179. err /= n;
  96180. /* err now holds err/n with fracbits fractional bits */
  96181. /*
  96182. * Whittle err down to 16 bits max. 16 significant bits is enough for
  96183. * our purposes.
  96184. */
  96185. FLAC__ASSERT(err > 0);
  96186. bits = FLAC__bitmath_ilog2_wide(err)+1;
  96187. if(bits > 16) {
  96188. err >>= (bits-16);
  96189. fracbits -= (bits-16);
  96190. }
  96191. rbps = (FLAC__uint32)err;
  96192. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  96193. rbps *= FLAC__FP_LN2;
  96194. fracbits += 16;
  96195. FLAC__ASSERT(fracbits >= 0);
  96196. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  96197. {
  96198. const int f = fracbits & 3;
  96199. if(f) {
  96200. rbps >>= f;
  96201. fracbits -= f;
  96202. }
  96203. }
  96204. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  96205. if(rbps == 0)
  96206. return 0;
  96207. /*
  96208. * The return value must have 16 fractional bits. Since the whole part
  96209. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  96210. * must be >= -3, these assertion allows us to be able to shift rbps
  96211. * left if necessary to get 16 fracbits without losing any bits of the
  96212. * whole part of rbps.
  96213. *
  96214. * There is a slight chance due to accumulated error that the whole part
  96215. * will require 6 bits, so we use 6 in the assertion. Really though as
  96216. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  96217. */
  96218. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  96219. FLAC__ASSERT(fracbits >= -3);
  96220. /* now shift the decimal point into place */
  96221. if(fracbits < 16)
  96222. return rbps << (16-fracbits);
  96223. else if(fracbits > 16)
  96224. return rbps >> (fracbits-16);
  96225. else
  96226. return rbps;
  96227. }
  96228. #endif
  96229. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96230. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96231. #else
  96232. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  96233. #endif
  96234. {
  96235. FLAC__int32 last_error_0 = data[-1];
  96236. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96237. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96238. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96239. FLAC__int32 error, save;
  96240. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96241. unsigned i, order;
  96242. for(i = 0; i < data_len; i++) {
  96243. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96244. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96245. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96246. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96247. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96248. }
  96249. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96250. order = 0;
  96251. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96252. order = 1;
  96253. else if(total_error_2 < min(total_error_3, total_error_4))
  96254. order = 2;
  96255. else if(total_error_3 < total_error_4)
  96256. order = 3;
  96257. else
  96258. order = 4;
  96259. /* Estimate the expected number of bits per residual signal sample. */
  96260. /* 'total_error*' is linearly related to the variance of the residual */
  96261. /* signal, so we use it directly to compute E(|x|) */
  96262. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96263. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96264. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96265. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96266. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96267. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96268. 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);
  96269. 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);
  96270. 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);
  96271. 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);
  96272. 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);
  96273. #else
  96274. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  96275. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  96276. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  96277. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  96278. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  96279. #endif
  96280. return order;
  96281. }
  96282. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96283. 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])
  96284. #else
  96285. 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])
  96286. #endif
  96287. {
  96288. FLAC__int32 last_error_0 = data[-1];
  96289. FLAC__int32 last_error_1 = data[-1] - data[-2];
  96290. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  96291. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  96292. FLAC__int32 error, save;
  96293. /* total_error_* are 64-bits to avoid overflow when encoding
  96294. * erratic signals when the bits-per-sample and blocksize are
  96295. * large.
  96296. */
  96297. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  96298. unsigned i, order;
  96299. for(i = 0; i < data_len; i++) {
  96300. error = data[i] ; total_error_0 += local_abs(error); save = error;
  96301. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  96302. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  96303. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  96304. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  96305. }
  96306. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  96307. order = 0;
  96308. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  96309. order = 1;
  96310. else if(total_error_2 < min(total_error_3, total_error_4))
  96311. order = 2;
  96312. else if(total_error_3 < total_error_4)
  96313. order = 3;
  96314. else
  96315. order = 4;
  96316. /* Estimate the expected number of bits per residual signal sample. */
  96317. /* 'total_error*' is linearly related to the variance of the residual */
  96318. /* signal, so we use it directly to compute E(|x|) */
  96319. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  96320. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  96321. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  96322. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  96323. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  96324. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  96325. #if defined _MSC_VER || defined __MINGW32__
  96326. /* with MSVC you have to spoon feed it the casting */
  96327. 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);
  96328. 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);
  96329. 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);
  96330. 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);
  96331. 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);
  96332. #else
  96333. 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);
  96334. 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);
  96335. 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);
  96336. 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);
  96337. 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);
  96338. #endif
  96339. #else
  96340. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  96341. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  96342. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  96343. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  96344. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  96345. #endif
  96346. return order;
  96347. }
  96348. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  96349. {
  96350. const int idata_len = (int)data_len;
  96351. int i;
  96352. switch(order) {
  96353. case 0:
  96354. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96355. memcpy(residual, data, sizeof(residual[0])*data_len);
  96356. break;
  96357. case 1:
  96358. for(i = 0; i < idata_len; i++)
  96359. residual[i] = data[i] - data[i-1];
  96360. break;
  96361. case 2:
  96362. for(i = 0; i < idata_len; i++)
  96363. #if 1 /* OPT: may be faster with some compilers on some systems */
  96364. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  96365. #else
  96366. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  96367. #endif
  96368. break;
  96369. case 3:
  96370. for(i = 0; i < idata_len; i++)
  96371. #if 1 /* OPT: may be faster with some compilers on some systems */
  96372. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  96373. #else
  96374. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  96375. #endif
  96376. break;
  96377. case 4:
  96378. for(i = 0; i < idata_len; i++)
  96379. #if 1 /* OPT: may be faster with some compilers on some systems */
  96380. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  96381. #else
  96382. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  96383. #endif
  96384. break;
  96385. default:
  96386. FLAC__ASSERT(0);
  96387. }
  96388. }
  96389. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  96390. {
  96391. int i, idata_len = (int)data_len;
  96392. switch(order) {
  96393. case 0:
  96394. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  96395. memcpy(data, residual, sizeof(residual[0])*data_len);
  96396. break;
  96397. case 1:
  96398. for(i = 0; i < idata_len; i++)
  96399. data[i] = residual[i] + data[i-1];
  96400. break;
  96401. case 2:
  96402. for(i = 0; i < idata_len; i++)
  96403. #if 1 /* OPT: may be faster with some compilers on some systems */
  96404. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  96405. #else
  96406. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  96407. #endif
  96408. break;
  96409. case 3:
  96410. for(i = 0; i < idata_len; i++)
  96411. #if 1 /* OPT: may be faster with some compilers on some systems */
  96412. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  96413. #else
  96414. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  96415. #endif
  96416. break;
  96417. case 4:
  96418. for(i = 0; i < idata_len; i++)
  96419. #if 1 /* OPT: may be faster with some compilers on some systems */
  96420. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  96421. #else
  96422. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  96423. #endif
  96424. break;
  96425. default:
  96426. FLAC__ASSERT(0);
  96427. }
  96428. }
  96429. #endif
  96430. /*** End of inlined file: fixed.c ***/
  96431. /*** Start of inlined file: float.c ***/
  96432. /*** Start of inlined file: juce_FlacHeader.h ***/
  96433. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96434. // tasks..
  96435. #define VERSION "1.2.1"
  96436. #define FLAC__NO_DLL 1
  96437. #if JUCE_MSVC
  96438. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96439. #endif
  96440. #if JUCE_MAC
  96441. #define FLAC__SYS_DARWIN 1
  96442. #endif
  96443. /*** End of inlined file: juce_FlacHeader.h ***/
  96444. #if JUCE_USE_FLAC
  96445. #if HAVE_CONFIG_H
  96446. # include <config.h>
  96447. #endif
  96448. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  96449. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96450. #ifdef _MSC_VER
  96451. #define FLAC__U64L(x) x
  96452. #else
  96453. #define FLAC__U64L(x) x##LLU
  96454. #endif
  96455. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  96456. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  96457. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  96458. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  96459. const FLAC__fixedpoint FLAC__FP_E = 178145;
  96460. /* Lookup tables for Knuth's logarithm algorithm */
  96461. #define LOG2_LOOKUP_PRECISION 16
  96462. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  96463. {
  96464. /*
  96465. * 0 fraction bits
  96466. */
  96467. /* undefined */ 0x00000000,
  96468. /* lg(2/1) = */ 0x00000001,
  96469. /* lg(4/3) = */ 0x00000000,
  96470. /* lg(8/7) = */ 0x00000000,
  96471. /* lg(16/15) = */ 0x00000000,
  96472. /* lg(32/31) = */ 0x00000000,
  96473. /* lg(64/63) = */ 0x00000000,
  96474. /* lg(128/127) = */ 0x00000000,
  96475. /* lg(256/255) = */ 0x00000000,
  96476. /* lg(512/511) = */ 0x00000000,
  96477. /* lg(1024/1023) = */ 0x00000000,
  96478. /* lg(2048/2047) = */ 0x00000000,
  96479. /* lg(4096/4095) = */ 0x00000000,
  96480. /* lg(8192/8191) = */ 0x00000000,
  96481. /* lg(16384/16383) = */ 0x00000000,
  96482. /* lg(32768/32767) = */ 0x00000000
  96483. },
  96484. {
  96485. /*
  96486. * 4 fraction bits
  96487. */
  96488. /* undefined */ 0x00000000,
  96489. /* lg(2/1) = */ 0x00000010,
  96490. /* lg(4/3) = */ 0x00000007,
  96491. /* lg(8/7) = */ 0x00000003,
  96492. /* lg(16/15) = */ 0x00000001,
  96493. /* lg(32/31) = */ 0x00000001,
  96494. /* lg(64/63) = */ 0x00000000,
  96495. /* lg(128/127) = */ 0x00000000,
  96496. /* lg(256/255) = */ 0x00000000,
  96497. /* lg(512/511) = */ 0x00000000,
  96498. /* lg(1024/1023) = */ 0x00000000,
  96499. /* lg(2048/2047) = */ 0x00000000,
  96500. /* lg(4096/4095) = */ 0x00000000,
  96501. /* lg(8192/8191) = */ 0x00000000,
  96502. /* lg(16384/16383) = */ 0x00000000,
  96503. /* lg(32768/32767) = */ 0x00000000
  96504. },
  96505. {
  96506. /*
  96507. * 8 fraction bits
  96508. */
  96509. /* undefined */ 0x00000000,
  96510. /* lg(2/1) = */ 0x00000100,
  96511. /* lg(4/3) = */ 0x0000006a,
  96512. /* lg(8/7) = */ 0x00000031,
  96513. /* lg(16/15) = */ 0x00000018,
  96514. /* lg(32/31) = */ 0x0000000c,
  96515. /* lg(64/63) = */ 0x00000006,
  96516. /* lg(128/127) = */ 0x00000003,
  96517. /* lg(256/255) = */ 0x00000001,
  96518. /* lg(512/511) = */ 0x00000001,
  96519. /* lg(1024/1023) = */ 0x00000000,
  96520. /* lg(2048/2047) = */ 0x00000000,
  96521. /* lg(4096/4095) = */ 0x00000000,
  96522. /* lg(8192/8191) = */ 0x00000000,
  96523. /* lg(16384/16383) = */ 0x00000000,
  96524. /* lg(32768/32767) = */ 0x00000000
  96525. },
  96526. {
  96527. /*
  96528. * 12 fraction bits
  96529. */
  96530. /* undefined */ 0x00000000,
  96531. /* lg(2/1) = */ 0x00001000,
  96532. /* lg(4/3) = */ 0x000006a4,
  96533. /* lg(8/7) = */ 0x00000315,
  96534. /* lg(16/15) = */ 0x0000017d,
  96535. /* lg(32/31) = */ 0x000000bc,
  96536. /* lg(64/63) = */ 0x0000005d,
  96537. /* lg(128/127) = */ 0x0000002e,
  96538. /* lg(256/255) = */ 0x00000017,
  96539. /* lg(512/511) = */ 0x0000000c,
  96540. /* lg(1024/1023) = */ 0x00000006,
  96541. /* lg(2048/2047) = */ 0x00000003,
  96542. /* lg(4096/4095) = */ 0x00000001,
  96543. /* lg(8192/8191) = */ 0x00000001,
  96544. /* lg(16384/16383) = */ 0x00000000,
  96545. /* lg(32768/32767) = */ 0x00000000
  96546. },
  96547. {
  96548. /*
  96549. * 16 fraction bits
  96550. */
  96551. /* undefined */ 0x00000000,
  96552. /* lg(2/1) = */ 0x00010000,
  96553. /* lg(4/3) = */ 0x00006a40,
  96554. /* lg(8/7) = */ 0x00003151,
  96555. /* lg(16/15) = */ 0x000017d6,
  96556. /* lg(32/31) = */ 0x00000bba,
  96557. /* lg(64/63) = */ 0x000005d1,
  96558. /* lg(128/127) = */ 0x000002e6,
  96559. /* lg(256/255) = */ 0x00000172,
  96560. /* lg(512/511) = */ 0x000000b9,
  96561. /* lg(1024/1023) = */ 0x0000005c,
  96562. /* lg(2048/2047) = */ 0x0000002e,
  96563. /* lg(4096/4095) = */ 0x00000017,
  96564. /* lg(8192/8191) = */ 0x0000000c,
  96565. /* lg(16384/16383) = */ 0x00000006,
  96566. /* lg(32768/32767) = */ 0x00000003
  96567. },
  96568. {
  96569. /*
  96570. * 20 fraction bits
  96571. */
  96572. /* undefined */ 0x00000000,
  96573. /* lg(2/1) = */ 0x00100000,
  96574. /* lg(4/3) = */ 0x0006a3fe,
  96575. /* lg(8/7) = */ 0x00031513,
  96576. /* lg(16/15) = */ 0x00017d60,
  96577. /* lg(32/31) = */ 0x0000bb9d,
  96578. /* lg(64/63) = */ 0x00005d10,
  96579. /* lg(128/127) = */ 0x00002e59,
  96580. /* lg(256/255) = */ 0x00001721,
  96581. /* lg(512/511) = */ 0x00000b8e,
  96582. /* lg(1024/1023) = */ 0x000005c6,
  96583. /* lg(2048/2047) = */ 0x000002e3,
  96584. /* lg(4096/4095) = */ 0x00000171,
  96585. /* lg(8192/8191) = */ 0x000000b9,
  96586. /* lg(16384/16383) = */ 0x0000005c,
  96587. /* lg(32768/32767) = */ 0x0000002e
  96588. },
  96589. {
  96590. /*
  96591. * 24 fraction bits
  96592. */
  96593. /* undefined */ 0x00000000,
  96594. /* lg(2/1) = */ 0x01000000,
  96595. /* lg(4/3) = */ 0x006a3fe6,
  96596. /* lg(8/7) = */ 0x00315130,
  96597. /* lg(16/15) = */ 0x0017d605,
  96598. /* lg(32/31) = */ 0x000bb9ca,
  96599. /* lg(64/63) = */ 0x0005d0fc,
  96600. /* lg(128/127) = */ 0x0002e58f,
  96601. /* lg(256/255) = */ 0x0001720e,
  96602. /* lg(512/511) = */ 0x0000b8d8,
  96603. /* lg(1024/1023) = */ 0x00005c61,
  96604. /* lg(2048/2047) = */ 0x00002e2d,
  96605. /* lg(4096/4095) = */ 0x00001716,
  96606. /* lg(8192/8191) = */ 0x00000b8b,
  96607. /* lg(16384/16383) = */ 0x000005c5,
  96608. /* lg(32768/32767) = */ 0x000002e3
  96609. },
  96610. {
  96611. /*
  96612. * 28 fraction bits
  96613. */
  96614. /* undefined */ 0x00000000,
  96615. /* lg(2/1) = */ 0x10000000,
  96616. /* lg(4/3) = */ 0x06a3fe5c,
  96617. /* lg(8/7) = */ 0x03151301,
  96618. /* lg(16/15) = */ 0x017d6049,
  96619. /* lg(32/31) = */ 0x00bb9ca6,
  96620. /* lg(64/63) = */ 0x005d0fba,
  96621. /* lg(128/127) = */ 0x002e58f7,
  96622. /* lg(256/255) = */ 0x001720da,
  96623. /* lg(512/511) = */ 0x000b8d87,
  96624. /* lg(1024/1023) = */ 0x0005c60b,
  96625. /* lg(2048/2047) = */ 0x0002e2d7,
  96626. /* lg(4096/4095) = */ 0x00017160,
  96627. /* lg(8192/8191) = */ 0x0000b8ad,
  96628. /* lg(16384/16383) = */ 0x00005c56,
  96629. /* lg(32768/32767) = */ 0x00002e2b
  96630. }
  96631. };
  96632. #if 0
  96633. static const FLAC__uint64 log2_lookup_wide[] = {
  96634. {
  96635. /*
  96636. * 32 fraction bits
  96637. */
  96638. /* undefined */ 0x00000000,
  96639. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  96640. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  96641. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  96642. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  96643. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  96644. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  96645. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  96646. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  96647. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  96648. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  96649. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  96650. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  96651. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  96652. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  96653. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  96654. },
  96655. {
  96656. /*
  96657. * 48 fraction bits
  96658. */
  96659. /* undefined */ 0x00000000,
  96660. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  96661. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  96662. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  96663. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  96664. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  96665. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  96666. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  96667. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  96668. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  96669. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  96670. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  96671. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  96672. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  96673. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  96674. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  96675. }
  96676. };
  96677. #endif
  96678. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  96679. {
  96680. const FLAC__uint32 ONE = (1u << fracbits);
  96681. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  96682. FLAC__ASSERT(fracbits < 32);
  96683. FLAC__ASSERT((fracbits & 0x3) == 0);
  96684. if(x < ONE)
  96685. return 0;
  96686. if(precision > LOG2_LOOKUP_PRECISION)
  96687. precision = LOG2_LOOKUP_PRECISION;
  96688. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  96689. {
  96690. FLAC__uint32 y = 0;
  96691. FLAC__uint32 z = x >> 1, k = 1;
  96692. while (x > ONE && k < precision) {
  96693. if (x - z >= ONE) {
  96694. x -= z;
  96695. z = x >> k;
  96696. y += table[k];
  96697. }
  96698. else {
  96699. z >>= 1;
  96700. k++;
  96701. }
  96702. }
  96703. return y;
  96704. }
  96705. }
  96706. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  96707. #endif
  96708. /*** End of inlined file: float.c ***/
  96709. /*** Start of inlined file: format.c ***/
  96710. /*** Start of inlined file: juce_FlacHeader.h ***/
  96711. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  96712. // tasks..
  96713. #define VERSION "1.2.1"
  96714. #define FLAC__NO_DLL 1
  96715. #if JUCE_MSVC
  96716. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  96717. #endif
  96718. #if JUCE_MAC
  96719. #define FLAC__SYS_DARWIN 1
  96720. #endif
  96721. /*** End of inlined file: juce_FlacHeader.h ***/
  96722. #if JUCE_USE_FLAC
  96723. #if HAVE_CONFIG_H
  96724. # include <config.h>
  96725. #endif
  96726. #include <stdio.h>
  96727. #include <stdlib.h> /* for qsort() */
  96728. #include <string.h> /* for memset() */
  96729. #ifndef FLaC__INLINE
  96730. #define FLaC__INLINE
  96731. #endif
  96732. #ifdef min
  96733. #undef min
  96734. #endif
  96735. #define min(a,b) ((a)<(b)?(a):(b))
  96736. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  96737. #ifdef _MSC_VER
  96738. #define FLAC__U64L(x) x
  96739. #else
  96740. #define FLAC__U64L(x) x##LLU
  96741. #endif
  96742. /* VERSION should come from configure */
  96743. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  96744. ;
  96745. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  96746. /* yet one more hack because of MSVC6: */
  96747. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  96748. #else
  96749. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  96750. #endif
  96751. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  96752. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  96753. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  96754. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  96755. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  96756. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  96757. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  96758. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  96759. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  96760. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  96761. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  96762. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  96763. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  96764. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  96765. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  96766. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  96767. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  96768. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  96769. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  96770. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  96771. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  96772. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  96773. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  96774. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  96775. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  96776. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  96777. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  96778. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  96779. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  96780. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  96781. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  96782. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  96783. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  96784. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  96785. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  96786. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  96787. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  96788. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  96789. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  96790. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  96791. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  96792. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  96793. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  96794. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  96795. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  96796. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  96797. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  96798. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  96799. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  96800. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  96801. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  96802. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  96803. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  96804. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  96805. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  96806. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  96807. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  96808. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  96809. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  96810. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  96811. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  96812. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  96813. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  96814. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  96815. "PARTITIONED_RICE",
  96816. "PARTITIONED_RICE2"
  96817. };
  96818. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  96819. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  96820. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  96821. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  96822. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  96823. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  96824. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  96825. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  96826. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  96827. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  96828. "CONSTANT",
  96829. "VERBATIM",
  96830. "FIXED",
  96831. "LPC"
  96832. };
  96833. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  96834. "INDEPENDENT",
  96835. "LEFT_SIDE",
  96836. "RIGHT_SIDE",
  96837. "MID_SIDE"
  96838. };
  96839. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  96840. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  96841. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  96842. };
  96843. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  96844. "STREAMINFO",
  96845. "PADDING",
  96846. "APPLICATION",
  96847. "SEEKTABLE",
  96848. "VORBIS_COMMENT",
  96849. "CUESHEET",
  96850. "PICTURE"
  96851. };
  96852. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  96853. "Other",
  96854. "32x32 pixels 'file icon' (PNG only)",
  96855. "Other file icon",
  96856. "Cover (front)",
  96857. "Cover (back)",
  96858. "Leaflet page",
  96859. "Media (e.g. label side of CD)",
  96860. "Lead artist/lead performer/soloist",
  96861. "Artist/performer",
  96862. "Conductor",
  96863. "Band/Orchestra",
  96864. "Composer",
  96865. "Lyricist/text writer",
  96866. "Recording Location",
  96867. "During recording",
  96868. "During performance",
  96869. "Movie/video screen capture",
  96870. "A bright coloured fish",
  96871. "Illustration",
  96872. "Band/artist logotype",
  96873. "Publisher/Studio logotype"
  96874. };
  96875. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  96876. {
  96877. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  96878. return false;
  96879. }
  96880. else
  96881. return true;
  96882. }
  96883. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  96884. {
  96885. if(
  96886. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  96887. (
  96888. sample_rate >= (1u << 16) &&
  96889. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  96890. )
  96891. ) {
  96892. return false;
  96893. }
  96894. else
  96895. return true;
  96896. }
  96897. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96898. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  96899. {
  96900. unsigned i;
  96901. FLAC__uint64 prev_sample_number = 0;
  96902. FLAC__bool got_prev = false;
  96903. FLAC__ASSERT(0 != seek_table);
  96904. for(i = 0; i < seek_table->num_points; i++) {
  96905. if(got_prev) {
  96906. if(
  96907. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  96908. seek_table->points[i].sample_number <= prev_sample_number
  96909. )
  96910. return false;
  96911. }
  96912. prev_sample_number = seek_table->points[i].sample_number;
  96913. got_prev = true;
  96914. }
  96915. return true;
  96916. }
  96917. /* used as the sort predicate for qsort() */
  96918. static int JUCE_CDECL seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  96919. {
  96920. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  96921. if(l->sample_number == r->sample_number)
  96922. return 0;
  96923. else if(l->sample_number < r->sample_number)
  96924. return -1;
  96925. else
  96926. return 1;
  96927. }
  96928. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  96929. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  96930. {
  96931. unsigned i, j;
  96932. FLAC__bool first;
  96933. FLAC__ASSERT(0 != seek_table);
  96934. /* sort the seekpoints */
  96935. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (JUCE_CDECL *)(const void *, const void *))seekpoint_compare_);
  96936. /* uniquify the seekpoints */
  96937. first = true;
  96938. for(i = j = 0; i < seek_table->num_points; i++) {
  96939. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  96940. if(!first) {
  96941. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  96942. continue;
  96943. }
  96944. }
  96945. first = false;
  96946. seek_table->points[j++] = seek_table->points[i];
  96947. }
  96948. for(i = j; i < seek_table->num_points; i++) {
  96949. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  96950. seek_table->points[i].stream_offset = 0;
  96951. seek_table->points[i].frame_samples = 0;
  96952. }
  96953. return j;
  96954. }
  96955. /*
  96956. * also disallows non-shortest-form encodings, c.f.
  96957. * http://www.unicode.org/versions/corrigendum1.html
  96958. * and a more clear explanation at the end of this section:
  96959. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  96960. */
  96961. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  96962. {
  96963. FLAC__ASSERT(0 != utf8);
  96964. if ((utf8[0] & 0x80) == 0) {
  96965. return 1;
  96966. }
  96967. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  96968. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  96969. return 0;
  96970. return 2;
  96971. }
  96972. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  96973. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  96974. return 0;
  96975. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  96976. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  96977. return 0;
  96978. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  96979. return 0;
  96980. return 3;
  96981. }
  96982. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  96983. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  96984. return 0;
  96985. return 4;
  96986. }
  96987. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  96988. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  96989. return 0;
  96990. return 5;
  96991. }
  96992. 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) {
  96993. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  96994. return 0;
  96995. return 6;
  96996. }
  96997. else {
  96998. return 0;
  96999. }
  97000. }
  97001. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  97002. {
  97003. char c;
  97004. for(c = *name; c; c = *(++name))
  97005. if(c < 0x20 || c == 0x3d || c > 0x7d)
  97006. return false;
  97007. return true;
  97008. }
  97009. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  97010. {
  97011. if(length == (unsigned)(-1)) {
  97012. while(*value) {
  97013. unsigned n = utf8len_(value);
  97014. if(n == 0)
  97015. return false;
  97016. value += n;
  97017. }
  97018. }
  97019. else {
  97020. const FLAC__byte *end = value + length;
  97021. while(value < end) {
  97022. unsigned n = utf8len_(value);
  97023. if(n == 0)
  97024. return false;
  97025. value += n;
  97026. }
  97027. if(value != end)
  97028. return false;
  97029. }
  97030. return true;
  97031. }
  97032. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  97033. {
  97034. const FLAC__byte *s, *end;
  97035. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  97036. if(*s < 0x20 || *s > 0x7D)
  97037. return false;
  97038. }
  97039. if(s == end)
  97040. return false;
  97041. s++; /* skip '=' */
  97042. while(s < end) {
  97043. unsigned n = utf8len_(s);
  97044. if(n == 0)
  97045. return false;
  97046. s += n;
  97047. }
  97048. if(s != end)
  97049. return false;
  97050. return true;
  97051. }
  97052. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97053. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  97054. {
  97055. unsigned i, j;
  97056. if(check_cd_da_subset) {
  97057. if(cue_sheet->lead_in < 2 * 44100) {
  97058. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  97059. return false;
  97060. }
  97061. if(cue_sheet->lead_in % 588 != 0) {
  97062. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  97063. return false;
  97064. }
  97065. }
  97066. if(cue_sheet->num_tracks == 0) {
  97067. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  97068. return false;
  97069. }
  97070. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  97071. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  97072. return false;
  97073. }
  97074. for(i = 0; i < cue_sheet->num_tracks; i++) {
  97075. if(cue_sheet->tracks[i].number == 0) {
  97076. if(violation) *violation = "cue sheet may not have a track number 0";
  97077. return false;
  97078. }
  97079. if(check_cd_da_subset) {
  97080. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  97081. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  97082. return false;
  97083. }
  97084. }
  97085. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  97086. if(violation) {
  97087. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  97088. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  97089. else
  97090. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  97091. }
  97092. return false;
  97093. }
  97094. if(i < cue_sheet->num_tracks - 1) {
  97095. if(cue_sheet->tracks[i].num_indices == 0) {
  97096. if(violation) *violation = "cue sheet track must have at least one index point";
  97097. return false;
  97098. }
  97099. if(cue_sheet->tracks[i].indices[0].number > 1) {
  97100. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  97101. return false;
  97102. }
  97103. }
  97104. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  97105. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  97106. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  97107. return false;
  97108. }
  97109. if(j > 0) {
  97110. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  97111. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  97112. return false;
  97113. }
  97114. }
  97115. }
  97116. }
  97117. return true;
  97118. }
  97119. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  97120. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  97121. {
  97122. char *p;
  97123. FLAC__byte *b;
  97124. for(p = picture->mime_type; *p; p++) {
  97125. if(*p < 0x20 || *p > 0x7e) {
  97126. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  97127. return false;
  97128. }
  97129. }
  97130. for(b = picture->description; *b; ) {
  97131. unsigned n = utf8len_(b);
  97132. if(n == 0) {
  97133. if(violation) *violation = "description string must be valid UTF-8";
  97134. return false;
  97135. }
  97136. b += n;
  97137. }
  97138. return true;
  97139. }
  97140. /*
  97141. * These routines are private to libFLAC
  97142. */
  97143. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  97144. {
  97145. return
  97146. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  97147. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  97148. blocksize,
  97149. predictor_order
  97150. );
  97151. }
  97152. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  97153. {
  97154. unsigned max_rice_partition_order = 0;
  97155. while(!(blocksize & 1)) {
  97156. max_rice_partition_order++;
  97157. blocksize >>= 1;
  97158. }
  97159. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  97160. }
  97161. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  97162. {
  97163. unsigned max_rice_partition_order = limit;
  97164. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  97165. max_rice_partition_order--;
  97166. FLAC__ASSERT(
  97167. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  97168. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  97169. );
  97170. return max_rice_partition_order;
  97171. }
  97172. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97173. {
  97174. FLAC__ASSERT(0 != object);
  97175. object->parameters = 0;
  97176. object->raw_bits = 0;
  97177. object->capacity_by_order = 0;
  97178. }
  97179. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  97180. {
  97181. FLAC__ASSERT(0 != object);
  97182. if(0 != object->parameters)
  97183. free(object->parameters);
  97184. if(0 != object->raw_bits)
  97185. free(object->raw_bits);
  97186. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  97187. }
  97188. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  97189. {
  97190. FLAC__ASSERT(0 != object);
  97191. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  97192. if(object->capacity_by_order < max_partition_order) {
  97193. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  97194. return false;
  97195. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  97196. return false;
  97197. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  97198. object->capacity_by_order = max_partition_order;
  97199. }
  97200. return true;
  97201. }
  97202. #endif
  97203. /*** End of inlined file: format.c ***/
  97204. /*** Start of inlined file: lpc_flac.c ***/
  97205. /*** Start of inlined file: juce_FlacHeader.h ***/
  97206. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  97207. // tasks..
  97208. #define VERSION "1.2.1"
  97209. #define FLAC__NO_DLL 1
  97210. #if JUCE_MSVC
  97211. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  97212. #endif
  97213. #if JUCE_MAC
  97214. #define FLAC__SYS_DARWIN 1
  97215. #endif
  97216. /*** End of inlined file: juce_FlacHeader.h ***/
  97217. #if JUCE_USE_FLAC
  97218. #if HAVE_CONFIG_H
  97219. # include <config.h>
  97220. #endif
  97221. #include <math.h>
  97222. /*** Start of inlined file: lpc.h ***/
  97223. #ifndef FLAC__PRIVATE__LPC_H
  97224. #define FLAC__PRIVATE__LPC_H
  97225. #ifdef HAVE_CONFIG_H
  97226. #include <config.h>
  97227. #endif
  97228. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97229. /*
  97230. * FLAC__lpc_window_data()
  97231. * --------------------------------------------------------------------
  97232. * Applies the given window to the data.
  97233. * OPT: asm implementation
  97234. *
  97235. * IN in[0,data_len-1]
  97236. * IN window[0,data_len-1]
  97237. * OUT out[0,lag-1]
  97238. * IN data_len
  97239. */
  97240. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  97241. /*
  97242. * FLAC__lpc_compute_autocorrelation()
  97243. * --------------------------------------------------------------------
  97244. * Compute the autocorrelation for lags between 0 and lag-1.
  97245. * Assumes data[] outside of [0,data_len-1] == 0.
  97246. * Asserts that lag > 0.
  97247. *
  97248. * IN data[0,data_len-1]
  97249. * IN data_len
  97250. * IN 0 < lag <= data_len
  97251. * OUT autoc[0,lag-1]
  97252. */
  97253. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97254. #ifndef FLAC__NO_ASM
  97255. # ifdef FLAC__CPU_IA32
  97256. # ifdef FLAC__HAS_NASM
  97257. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97258. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97259. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97260. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97261. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  97262. # endif
  97263. # endif
  97264. #endif
  97265. /*
  97266. * FLAC__lpc_compute_lp_coefficients()
  97267. * --------------------------------------------------------------------
  97268. * Computes LP coefficients for orders 1..max_order.
  97269. * Do not call if autoc[0] == 0.0. This means the signal is zero
  97270. * and there is no point in calculating a predictor.
  97271. *
  97272. * IN autoc[0,max_order] autocorrelation values
  97273. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  97274. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  97275. * *** IMPORTANT:
  97276. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  97277. * OUT error[0,max_order-1] error for each order (more
  97278. * specifically, the variance of
  97279. * the error signal times # of
  97280. * samples in the signal)
  97281. *
  97282. * Example: if max_order is 9, the LP coefficients for order 9 will be
  97283. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  97284. * in lp_coeff[7][0,7], etc.
  97285. */
  97286. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  97287. /*
  97288. * FLAC__lpc_quantize_coefficients()
  97289. * --------------------------------------------------------------------
  97290. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  97291. * must be less than 32 (sizeof(FLAC__int32)*8).
  97292. *
  97293. * IN lp_coeff[0,order-1] LP coefficients
  97294. * IN order LP order
  97295. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  97296. * desired precision (in bits, including sign
  97297. * bit) of largest coefficient
  97298. * OUT qlp_coeff[0,order-1] quantized coefficients
  97299. * OUT shift # of bits to shift right to get approximated
  97300. * LP coefficients. NOTE: could be negative.
  97301. * RETURN 0 => quantization OK
  97302. * 1 => coefficients require too much shifting for *shift to
  97303. * fit in the LPC subframe header. 'shift' is unset.
  97304. * 2 => coefficients are all zero, which is bad. 'shift' is
  97305. * unset.
  97306. */
  97307. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  97308. /*
  97309. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  97310. * --------------------------------------------------------------------
  97311. * Compute the residual signal obtained from sutracting the predicted
  97312. * signal from the original.
  97313. *
  97314. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  97315. * IN data_len length of original signal
  97316. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97317. * IN order > 0 LP order
  97318. * IN lp_quantization quantization of LP coefficients in bits
  97319. * OUT residual[0,data_len-1] residual signal
  97320. */
  97321. 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[]);
  97322. 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[]);
  97323. #ifndef FLAC__NO_ASM
  97324. # ifdef FLAC__CPU_IA32
  97325. # ifdef FLAC__HAS_NASM
  97326. 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[]);
  97327. 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[]);
  97328. # endif
  97329. # endif
  97330. #endif
  97331. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97332. /*
  97333. * FLAC__lpc_restore_signal()
  97334. * --------------------------------------------------------------------
  97335. * Restore the original signal by summing the residual and the
  97336. * predictor.
  97337. *
  97338. * IN residual[0,data_len-1] residual signal
  97339. * IN data_len length of original signal
  97340. * IN qlp_coeff[0,order-1] quantized LP coefficients
  97341. * IN order > 0 LP order
  97342. * IN lp_quantization quantization of LP coefficients in bits
  97343. * *** IMPORTANT: the caller must pass in the historical samples:
  97344. * IN data[-order,-1] previously-reconstructed historical samples
  97345. * OUT data[0,data_len-1] original signal
  97346. */
  97347. 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[]);
  97348. 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[]);
  97349. #ifndef FLAC__NO_ASM
  97350. # ifdef FLAC__CPU_IA32
  97351. # ifdef FLAC__HAS_NASM
  97352. 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[]);
  97353. 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[]);
  97354. # endif /* FLAC__HAS_NASM */
  97355. # elif defined FLAC__CPU_PPC
  97356. 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[]);
  97357. 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[]);
  97358. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  97359. #endif /* FLAC__NO_ASM */
  97360. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97361. /*
  97362. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  97363. * --------------------------------------------------------------------
  97364. * Compute the expected number of bits per residual signal sample
  97365. * based on the LP error (which is related to the residual variance).
  97366. *
  97367. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  97368. * IN total_samples > 0 # of samples in residual signal
  97369. * RETURN expected bits per sample
  97370. */
  97371. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  97372. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  97373. /*
  97374. * FLAC__lpc_compute_best_order()
  97375. * --------------------------------------------------------------------
  97376. * Compute the best order from the array of signal errors returned
  97377. * during coefficient computation.
  97378. *
  97379. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  97380. * IN max_order > 0 max LP order
  97381. * IN total_samples > 0 # of samples in residual signal
  97382. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  97383. * (includes warmup sample size and quantized LP coefficient)
  97384. * RETURN [1,max_order] best order
  97385. */
  97386. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  97387. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  97388. #endif
  97389. /*** End of inlined file: lpc.h ***/
  97390. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  97391. #include <stdio.h>
  97392. #endif
  97393. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  97394. #ifndef M_LN2
  97395. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  97396. #define M_LN2 0.69314718055994530942
  97397. #endif
  97398. /* OPT: #undef'ing this may improve the speed on some architectures */
  97399. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  97400. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  97401. {
  97402. unsigned i;
  97403. for(i = 0; i < data_len; i++)
  97404. out[i] = in[i] * window[i];
  97405. }
  97406. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  97407. {
  97408. /* a readable, but slower, version */
  97409. #if 0
  97410. FLAC__real d;
  97411. unsigned i;
  97412. FLAC__ASSERT(lag > 0);
  97413. FLAC__ASSERT(lag <= data_len);
  97414. /*
  97415. * Technically we should subtract the mean first like so:
  97416. * for(i = 0; i < data_len; i++)
  97417. * data[i] -= mean;
  97418. * but it appears not to make enough of a difference to matter, and
  97419. * most signals are already closely centered around zero
  97420. */
  97421. while(lag--) {
  97422. for(i = lag, d = 0.0; i < data_len; i++)
  97423. d += data[i] * data[i - lag];
  97424. autoc[lag] = d;
  97425. }
  97426. #endif
  97427. /*
  97428. * this version tends to run faster because of better data locality
  97429. * ('data_len' is usually much larger than 'lag')
  97430. */
  97431. FLAC__real d;
  97432. unsigned sample, coeff;
  97433. const unsigned limit = data_len - lag;
  97434. FLAC__ASSERT(lag > 0);
  97435. FLAC__ASSERT(lag <= data_len);
  97436. for(coeff = 0; coeff < lag; coeff++)
  97437. autoc[coeff] = 0.0;
  97438. for(sample = 0; sample <= limit; sample++) {
  97439. d = data[sample];
  97440. for(coeff = 0; coeff < lag; coeff++)
  97441. autoc[coeff] += d * data[sample+coeff];
  97442. }
  97443. for(; sample < data_len; sample++) {
  97444. d = data[sample];
  97445. for(coeff = 0; coeff < data_len - sample; coeff++)
  97446. autoc[coeff] += d * data[sample+coeff];
  97447. }
  97448. }
  97449. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  97450. {
  97451. unsigned i, j;
  97452. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  97453. FLAC__ASSERT(0 != max_order);
  97454. FLAC__ASSERT(0 < *max_order);
  97455. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  97456. FLAC__ASSERT(autoc[0] != 0.0);
  97457. err = autoc[0];
  97458. for(i = 0; i < *max_order; i++) {
  97459. /* Sum up this iteration's reflection coefficient. */
  97460. r = -autoc[i+1];
  97461. for(j = 0; j < i; j++)
  97462. r -= lpc[j] * autoc[i-j];
  97463. ref[i] = (r/=err);
  97464. /* Update LPC coefficients and total error. */
  97465. lpc[i]=r;
  97466. for(j = 0; j < (i>>1); j++) {
  97467. FLAC__double tmp = lpc[j];
  97468. lpc[j] += r * lpc[i-1-j];
  97469. lpc[i-1-j] += r * tmp;
  97470. }
  97471. if(i & 1)
  97472. lpc[j] += lpc[j] * r;
  97473. err *= (1.0 - r * r);
  97474. /* save this order */
  97475. for(j = 0; j <= i; j++)
  97476. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  97477. error[i] = err;
  97478. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  97479. if(err == 0.0) {
  97480. *max_order = i+1;
  97481. return;
  97482. }
  97483. }
  97484. }
  97485. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  97486. {
  97487. unsigned i;
  97488. FLAC__double cmax;
  97489. FLAC__int32 qmax, qmin;
  97490. FLAC__ASSERT(precision > 0);
  97491. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  97492. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  97493. precision--;
  97494. qmax = 1 << precision;
  97495. qmin = -qmax;
  97496. qmax--;
  97497. /* calc cmax = max( |lp_coeff[i]| ) */
  97498. cmax = 0.0;
  97499. for(i = 0; i < order; i++) {
  97500. const FLAC__double d = fabs(lp_coeff[i]);
  97501. if(d > cmax)
  97502. cmax = d;
  97503. }
  97504. if(cmax <= 0.0) {
  97505. /* => coefficients are all 0, which means our constant-detect didn't work */
  97506. return 2;
  97507. }
  97508. else {
  97509. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  97510. const int min_shiftlimit = -max_shiftlimit - 1;
  97511. int log2cmax;
  97512. (void)frexp(cmax, &log2cmax);
  97513. log2cmax--;
  97514. *shift = (int)precision - log2cmax - 1;
  97515. if(*shift > max_shiftlimit)
  97516. *shift = max_shiftlimit;
  97517. else if(*shift < min_shiftlimit)
  97518. return 1;
  97519. }
  97520. if(*shift >= 0) {
  97521. FLAC__double error = 0.0;
  97522. FLAC__int32 q;
  97523. for(i = 0; i < order; i++) {
  97524. error += lp_coeff[i] * (1 << *shift);
  97525. #if 1 /* unfortunately lround() is C99 */
  97526. if(error >= 0.0)
  97527. q = (FLAC__int32)(error + 0.5);
  97528. else
  97529. q = (FLAC__int32)(error - 0.5);
  97530. #else
  97531. q = lround(error);
  97532. #endif
  97533. #ifdef FLAC__OVERFLOW_DETECT
  97534. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97535. 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]);
  97536. else if(q < qmin)
  97537. 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]);
  97538. #endif
  97539. if(q > qmax)
  97540. q = qmax;
  97541. else if(q < qmin)
  97542. q = qmin;
  97543. error -= q;
  97544. qlp_coeff[i] = q;
  97545. }
  97546. }
  97547. /* negative shift is very rare but due to design flaw, negative shift is
  97548. * a NOP in the decoder, so it must be handled specially by scaling down
  97549. * coeffs
  97550. */
  97551. else {
  97552. const int nshift = -(*shift);
  97553. FLAC__double error = 0.0;
  97554. FLAC__int32 q;
  97555. #ifdef DEBUG
  97556. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  97557. #endif
  97558. for(i = 0; i < order; i++) {
  97559. error += lp_coeff[i] / (1 << nshift);
  97560. #if 1 /* unfortunately lround() is C99 */
  97561. if(error >= 0.0)
  97562. q = (FLAC__int32)(error + 0.5);
  97563. else
  97564. q = (FLAC__int32)(error - 0.5);
  97565. #else
  97566. q = lround(error);
  97567. #endif
  97568. #ifdef FLAC__OVERFLOW_DETECT
  97569. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  97570. 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]);
  97571. else if(q < qmin)
  97572. 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]);
  97573. #endif
  97574. if(q > qmax)
  97575. q = qmax;
  97576. else if(q < qmin)
  97577. q = qmin;
  97578. error -= q;
  97579. qlp_coeff[i] = q;
  97580. }
  97581. *shift = 0;
  97582. }
  97583. return 0;
  97584. }
  97585. 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[])
  97586. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97587. {
  97588. FLAC__int64 sumo;
  97589. unsigned i, j;
  97590. FLAC__int32 sum;
  97591. const FLAC__int32 *history;
  97592. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97593. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97594. for(i=0;i<order;i++)
  97595. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97596. fprintf(stderr,"\n");
  97597. #endif
  97598. FLAC__ASSERT(order > 0);
  97599. for(i = 0; i < data_len; i++) {
  97600. sumo = 0;
  97601. sum = 0;
  97602. history = data;
  97603. for(j = 0; j < order; j++) {
  97604. sum += qlp_coeff[j] * (*(--history));
  97605. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  97606. #if defined _MSC_VER
  97607. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  97608. 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);
  97609. #else
  97610. if(sumo > 2147483647ll || sumo < -2147483648ll)
  97611. 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);
  97612. #endif
  97613. }
  97614. *(residual++) = *(data++) - (sum >> lp_quantization);
  97615. }
  97616. /* Here's a slower but clearer version:
  97617. for(i = 0; i < data_len; i++) {
  97618. sum = 0;
  97619. for(j = 0; j < order; j++)
  97620. sum += qlp_coeff[j] * data[i-j-1];
  97621. residual[i] = data[i] - (sum >> lp_quantization);
  97622. }
  97623. */
  97624. }
  97625. #else /* fully unrolled version for normal use */
  97626. {
  97627. int i;
  97628. FLAC__int32 sum;
  97629. FLAC__ASSERT(order > 0);
  97630. FLAC__ASSERT(order <= 32);
  97631. /*
  97632. * We do unique versions up to 12th order since that's the subset limit.
  97633. * Also they are roughly ordered to match frequency of occurrence to
  97634. * minimize branching.
  97635. */
  97636. if(order <= 12) {
  97637. if(order > 8) {
  97638. if(order > 10) {
  97639. if(order == 12) {
  97640. for(i = 0; i < (int)data_len; i++) {
  97641. sum = 0;
  97642. sum += qlp_coeff[11] * data[i-12];
  97643. sum += qlp_coeff[10] * data[i-11];
  97644. sum += qlp_coeff[9] * data[i-10];
  97645. sum += qlp_coeff[8] * data[i-9];
  97646. sum += qlp_coeff[7] * data[i-8];
  97647. sum += qlp_coeff[6] * data[i-7];
  97648. sum += qlp_coeff[5] * data[i-6];
  97649. sum += qlp_coeff[4] * data[i-5];
  97650. sum += qlp_coeff[3] * data[i-4];
  97651. sum += qlp_coeff[2] * data[i-3];
  97652. sum += qlp_coeff[1] * data[i-2];
  97653. sum += qlp_coeff[0] * data[i-1];
  97654. residual[i] = data[i] - (sum >> lp_quantization);
  97655. }
  97656. }
  97657. else { /* order == 11 */
  97658. for(i = 0; i < (int)data_len; i++) {
  97659. sum = 0;
  97660. sum += qlp_coeff[10] * data[i-11];
  97661. sum += qlp_coeff[9] * data[i-10];
  97662. sum += qlp_coeff[8] * data[i-9];
  97663. sum += qlp_coeff[7] * data[i-8];
  97664. sum += qlp_coeff[6] * data[i-7];
  97665. sum += qlp_coeff[5] * data[i-6];
  97666. sum += qlp_coeff[4] * data[i-5];
  97667. sum += qlp_coeff[3] * data[i-4];
  97668. sum += qlp_coeff[2] * data[i-3];
  97669. sum += qlp_coeff[1] * data[i-2];
  97670. sum += qlp_coeff[0] * data[i-1];
  97671. residual[i] = data[i] - (sum >> lp_quantization);
  97672. }
  97673. }
  97674. }
  97675. else {
  97676. if(order == 10) {
  97677. for(i = 0; i < (int)data_len; i++) {
  97678. sum = 0;
  97679. sum += qlp_coeff[9] * data[i-10];
  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. else { /* order == 9 */
  97693. for(i = 0; i < (int)data_len; i++) {
  97694. sum = 0;
  97695. sum += qlp_coeff[8] * data[i-9];
  97696. sum += qlp_coeff[7] * data[i-8];
  97697. sum += qlp_coeff[6] * data[i-7];
  97698. sum += qlp_coeff[5] * data[i-6];
  97699. sum += qlp_coeff[4] * data[i-5];
  97700. sum += qlp_coeff[3] * data[i-4];
  97701. sum += qlp_coeff[2] * data[i-3];
  97702. sum += qlp_coeff[1] * data[i-2];
  97703. sum += qlp_coeff[0] * data[i-1];
  97704. residual[i] = data[i] - (sum >> lp_quantization);
  97705. }
  97706. }
  97707. }
  97708. }
  97709. else if(order > 4) {
  97710. if(order > 6) {
  97711. if(order == 8) {
  97712. for(i = 0; i < (int)data_len; i++) {
  97713. sum = 0;
  97714. sum += qlp_coeff[7] * data[i-8];
  97715. sum += qlp_coeff[6] * data[i-7];
  97716. sum += qlp_coeff[5] * data[i-6];
  97717. sum += qlp_coeff[4] * data[i-5];
  97718. sum += qlp_coeff[3] * data[i-4];
  97719. sum += qlp_coeff[2] * data[i-3];
  97720. sum += qlp_coeff[1] * data[i-2];
  97721. sum += qlp_coeff[0] * data[i-1];
  97722. residual[i] = data[i] - (sum >> lp_quantization);
  97723. }
  97724. }
  97725. else { /* order == 7 */
  97726. for(i = 0; i < (int)data_len; i++) {
  97727. sum = 0;
  97728. sum += qlp_coeff[6] * data[i-7];
  97729. sum += qlp_coeff[5] * data[i-6];
  97730. sum += qlp_coeff[4] * data[i-5];
  97731. sum += qlp_coeff[3] * data[i-4];
  97732. sum += qlp_coeff[2] * data[i-3];
  97733. sum += qlp_coeff[1] * data[i-2];
  97734. sum += qlp_coeff[0] * data[i-1];
  97735. residual[i] = data[i] - (sum >> lp_quantization);
  97736. }
  97737. }
  97738. }
  97739. else {
  97740. if(order == 6) {
  97741. for(i = 0; i < (int)data_len; i++) {
  97742. sum = 0;
  97743. sum += qlp_coeff[5] * data[i-6];
  97744. sum += qlp_coeff[4] * data[i-5];
  97745. sum += qlp_coeff[3] * data[i-4];
  97746. sum += qlp_coeff[2] * data[i-3];
  97747. sum += qlp_coeff[1] * data[i-2];
  97748. sum += qlp_coeff[0] * data[i-1];
  97749. residual[i] = data[i] - (sum >> lp_quantization);
  97750. }
  97751. }
  97752. else { /* order == 5 */
  97753. for(i = 0; i < (int)data_len; i++) {
  97754. sum = 0;
  97755. sum += qlp_coeff[4] * data[i-5];
  97756. sum += qlp_coeff[3] * data[i-4];
  97757. sum += qlp_coeff[2] * data[i-3];
  97758. sum += qlp_coeff[1] * data[i-2];
  97759. sum += qlp_coeff[0] * data[i-1];
  97760. residual[i] = data[i] - (sum >> lp_quantization);
  97761. }
  97762. }
  97763. }
  97764. }
  97765. else {
  97766. if(order > 2) {
  97767. if(order == 4) {
  97768. for(i = 0; i < (int)data_len; i++) {
  97769. sum = 0;
  97770. sum += qlp_coeff[3] * data[i-4];
  97771. sum += qlp_coeff[2] * data[i-3];
  97772. sum += qlp_coeff[1] * data[i-2];
  97773. sum += qlp_coeff[0] * data[i-1];
  97774. residual[i] = data[i] - (sum >> lp_quantization);
  97775. }
  97776. }
  97777. else { /* order == 3 */
  97778. for(i = 0; i < (int)data_len; i++) {
  97779. sum = 0;
  97780. sum += qlp_coeff[2] * data[i-3];
  97781. sum += qlp_coeff[1] * data[i-2];
  97782. sum += qlp_coeff[0] * data[i-1];
  97783. residual[i] = data[i] - (sum >> lp_quantization);
  97784. }
  97785. }
  97786. }
  97787. else {
  97788. if(order == 2) {
  97789. for(i = 0; i < (int)data_len; i++) {
  97790. sum = 0;
  97791. sum += qlp_coeff[1] * data[i-2];
  97792. sum += qlp_coeff[0] * data[i-1];
  97793. residual[i] = data[i] - (sum >> lp_quantization);
  97794. }
  97795. }
  97796. else { /* order == 1 */
  97797. for(i = 0; i < (int)data_len; i++)
  97798. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  97799. }
  97800. }
  97801. }
  97802. }
  97803. else { /* order > 12 */
  97804. for(i = 0; i < (int)data_len; i++) {
  97805. sum = 0;
  97806. switch(order) {
  97807. case 32: sum += qlp_coeff[31] * data[i-32];
  97808. case 31: sum += qlp_coeff[30] * data[i-31];
  97809. case 30: sum += qlp_coeff[29] * data[i-30];
  97810. case 29: sum += qlp_coeff[28] * data[i-29];
  97811. case 28: sum += qlp_coeff[27] * data[i-28];
  97812. case 27: sum += qlp_coeff[26] * data[i-27];
  97813. case 26: sum += qlp_coeff[25] * data[i-26];
  97814. case 25: sum += qlp_coeff[24] * data[i-25];
  97815. case 24: sum += qlp_coeff[23] * data[i-24];
  97816. case 23: sum += qlp_coeff[22] * data[i-23];
  97817. case 22: sum += qlp_coeff[21] * data[i-22];
  97818. case 21: sum += qlp_coeff[20] * data[i-21];
  97819. case 20: sum += qlp_coeff[19] * data[i-20];
  97820. case 19: sum += qlp_coeff[18] * data[i-19];
  97821. case 18: sum += qlp_coeff[17] * data[i-18];
  97822. case 17: sum += qlp_coeff[16] * data[i-17];
  97823. case 16: sum += qlp_coeff[15] * data[i-16];
  97824. case 15: sum += qlp_coeff[14] * data[i-15];
  97825. case 14: sum += qlp_coeff[13] * data[i-14];
  97826. case 13: sum += qlp_coeff[12] * data[i-13];
  97827. sum += qlp_coeff[11] * data[i-12];
  97828. sum += qlp_coeff[10] * data[i-11];
  97829. sum += qlp_coeff[ 9] * data[i-10];
  97830. sum += qlp_coeff[ 8] * data[i- 9];
  97831. sum += qlp_coeff[ 7] * data[i- 8];
  97832. sum += qlp_coeff[ 6] * data[i- 7];
  97833. sum += qlp_coeff[ 5] * data[i- 6];
  97834. sum += qlp_coeff[ 4] * data[i- 5];
  97835. sum += qlp_coeff[ 3] * data[i- 4];
  97836. sum += qlp_coeff[ 2] * data[i- 3];
  97837. sum += qlp_coeff[ 1] * data[i- 2];
  97838. sum += qlp_coeff[ 0] * data[i- 1];
  97839. }
  97840. residual[i] = data[i] - (sum >> lp_quantization);
  97841. }
  97842. }
  97843. }
  97844. #endif
  97845. 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[])
  97846. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  97847. {
  97848. unsigned i, j;
  97849. FLAC__int64 sum;
  97850. const FLAC__int32 *history;
  97851. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  97852. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  97853. for(i=0;i<order;i++)
  97854. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  97855. fprintf(stderr,"\n");
  97856. #endif
  97857. FLAC__ASSERT(order > 0);
  97858. for(i = 0; i < data_len; i++) {
  97859. sum = 0;
  97860. history = data;
  97861. for(j = 0; j < order; j++)
  97862. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  97863. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  97864. #if defined _MSC_VER
  97865. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  97866. #else
  97867. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  97868. #endif
  97869. break;
  97870. }
  97871. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  97872. #if defined _MSC_VER
  97873. 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));
  97874. #else
  97875. 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)));
  97876. #endif
  97877. break;
  97878. }
  97879. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  97880. }
  97881. }
  97882. #else /* fully unrolled version for normal use */
  97883. {
  97884. int i;
  97885. FLAC__int64 sum;
  97886. FLAC__ASSERT(order > 0);
  97887. FLAC__ASSERT(order <= 32);
  97888. /*
  97889. * We do unique versions up to 12th order since that's the subset limit.
  97890. * Also they are roughly ordered to match frequency of occurrence to
  97891. * minimize branching.
  97892. */
  97893. if(order <= 12) {
  97894. if(order > 8) {
  97895. if(order > 10) {
  97896. if(order == 12) {
  97897. for(i = 0; i < (int)data_len; i++) {
  97898. sum = 0;
  97899. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  97900. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97901. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97902. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97903. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97904. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97905. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97906. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97907. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97908. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97909. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97910. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97911. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97912. }
  97913. }
  97914. else { /* order == 11 */
  97915. for(i = 0; i < (int)data_len; i++) {
  97916. sum = 0;
  97917. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  97918. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  97919. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97920. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97921. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97922. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97923. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97924. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97925. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97926. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97927. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97928. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97929. }
  97930. }
  97931. }
  97932. else {
  97933. if(order == 10) {
  97934. for(i = 0; i < (int)data_len; i++) {
  97935. sum = 0;
  97936. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  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. else { /* order == 9 */
  97950. for(i = 0; i < (int)data_len; i++) {
  97951. sum = 0;
  97952. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  97953. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97954. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97955. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97956. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97957. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97958. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97959. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97960. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97961. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97962. }
  97963. }
  97964. }
  97965. }
  97966. else if(order > 4) {
  97967. if(order > 6) {
  97968. if(order == 8) {
  97969. for(i = 0; i < (int)data_len; i++) {
  97970. sum = 0;
  97971. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  97972. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97973. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97974. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97975. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97976. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97977. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97978. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97979. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97980. }
  97981. }
  97982. else { /* order == 7 */
  97983. for(i = 0; i < (int)data_len; i++) {
  97984. sum = 0;
  97985. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  97986. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  97987. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  97988. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  97989. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  97990. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  97991. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  97992. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  97993. }
  97994. }
  97995. }
  97996. else {
  97997. if(order == 6) {
  97998. for(i = 0; i < (int)data_len; i++) {
  97999. sum = 0;
  98000. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98001. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98002. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98003. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98004. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98005. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98006. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98007. }
  98008. }
  98009. else { /* order == 5 */
  98010. for(i = 0; i < (int)data_len; i++) {
  98011. sum = 0;
  98012. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98013. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98014. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98015. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98016. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98017. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98018. }
  98019. }
  98020. }
  98021. }
  98022. else {
  98023. if(order > 2) {
  98024. if(order == 4) {
  98025. for(i = 0; i < (int)data_len; i++) {
  98026. sum = 0;
  98027. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98028. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98029. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98030. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98031. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98032. }
  98033. }
  98034. else { /* order == 3 */
  98035. for(i = 0; i < (int)data_len; i++) {
  98036. sum = 0;
  98037. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98038. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98039. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98040. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98041. }
  98042. }
  98043. }
  98044. else {
  98045. if(order == 2) {
  98046. for(i = 0; i < (int)data_len; i++) {
  98047. sum = 0;
  98048. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98049. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98050. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98051. }
  98052. }
  98053. else { /* order == 1 */
  98054. for(i = 0; i < (int)data_len; i++)
  98055. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98056. }
  98057. }
  98058. }
  98059. }
  98060. else { /* order > 12 */
  98061. for(i = 0; i < (int)data_len; i++) {
  98062. sum = 0;
  98063. switch(order) {
  98064. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98065. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98066. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98067. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98068. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98069. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98070. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98071. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98072. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98073. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98074. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98075. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98076. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98077. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98078. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98079. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98080. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98081. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98082. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98083. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98084. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98085. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98086. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98087. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98088. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98089. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98090. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98091. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98092. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98093. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98094. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98095. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98096. }
  98097. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  98098. }
  98099. }
  98100. }
  98101. #endif
  98102. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98103. 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[])
  98104. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98105. {
  98106. FLAC__int64 sumo;
  98107. unsigned i, j;
  98108. FLAC__int32 sum;
  98109. const FLAC__int32 *r = residual, *history;
  98110. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98111. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98112. for(i=0;i<order;i++)
  98113. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98114. fprintf(stderr,"\n");
  98115. #endif
  98116. FLAC__ASSERT(order > 0);
  98117. for(i = 0; i < data_len; i++) {
  98118. sumo = 0;
  98119. sum = 0;
  98120. history = data;
  98121. for(j = 0; j < order; j++) {
  98122. sum += qlp_coeff[j] * (*(--history));
  98123. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  98124. #if defined _MSC_VER
  98125. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  98126. 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);
  98127. #else
  98128. if(sumo > 2147483647ll || sumo < -2147483648ll)
  98129. 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);
  98130. #endif
  98131. }
  98132. *(data++) = *(r++) + (sum >> lp_quantization);
  98133. }
  98134. /* Here's a slower but clearer version:
  98135. for(i = 0; i < data_len; i++) {
  98136. sum = 0;
  98137. for(j = 0; j < order; j++)
  98138. sum += qlp_coeff[j] * data[i-j-1];
  98139. data[i] = residual[i] + (sum >> lp_quantization);
  98140. }
  98141. */
  98142. }
  98143. #else /* fully unrolled version for normal use */
  98144. {
  98145. int i;
  98146. FLAC__int32 sum;
  98147. FLAC__ASSERT(order > 0);
  98148. FLAC__ASSERT(order <= 32);
  98149. /*
  98150. * We do unique versions up to 12th order since that's the subset limit.
  98151. * Also they are roughly ordered to match frequency of occurrence to
  98152. * minimize branching.
  98153. */
  98154. if(order <= 12) {
  98155. if(order > 8) {
  98156. if(order > 10) {
  98157. if(order == 12) {
  98158. for(i = 0; i < (int)data_len; i++) {
  98159. sum = 0;
  98160. sum += qlp_coeff[11] * data[i-12];
  98161. sum += qlp_coeff[10] * data[i-11];
  98162. sum += qlp_coeff[9] * data[i-10];
  98163. sum += qlp_coeff[8] * data[i-9];
  98164. sum += qlp_coeff[7] * data[i-8];
  98165. sum += qlp_coeff[6] * data[i-7];
  98166. sum += qlp_coeff[5] * data[i-6];
  98167. sum += qlp_coeff[4] * data[i-5];
  98168. sum += qlp_coeff[3] * data[i-4];
  98169. sum += qlp_coeff[2] * data[i-3];
  98170. sum += qlp_coeff[1] * data[i-2];
  98171. sum += qlp_coeff[0] * data[i-1];
  98172. data[i] = residual[i] + (sum >> lp_quantization);
  98173. }
  98174. }
  98175. else { /* order == 11 */
  98176. for(i = 0; i < (int)data_len; i++) {
  98177. sum = 0;
  98178. sum += qlp_coeff[10] * data[i-11];
  98179. sum += qlp_coeff[9] * data[i-10];
  98180. sum += qlp_coeff[8] * data[i-9];
  98181. sum += qlp_coeff[7] * data[i-8];
  98182. sum += qlp_coeff[6] * data[i-7];
  98183. sum += qlp_coeff[5] * data[i-6];
  98184. sum += qlp_coeff[4] * data[i-5];
  98185. sum += qlp_coeff[3] * data[i-4];
  98186. sum += qlp_coeff[2] * data[i-3];
  98187. sum += qlp_coeff[1] * data[i-2];
  98188. sum += qlp_coeff[0] * data[i-1];
  98189. data[i] = residual[i] + (sum >> lp_quantization);
  98190. }
  98191. }
  98192. }
  98193. else {
  98194. if(order == 10) {
  98195. for(i = 0; i < (int)data_len; i++) {
  98196. sum = 0;
  98197. sum += qlp_coeff[9] * data[i-10];
  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. else { /* order == 9 */
  98211. for(i = 0; i < (int)data_len; i++) {
  98212. sum = 0;
  98213. sum += qlp_coeff[8] * data[i-9];
  98214. sum += qlp_coeff[7] * data[i-8];
  98215. sum += qlp_coeff[6] * data[i-7];
  98216. sum += qlp_coeff[5] * data[i-6];
  98217. sum += qlp_coeff[4] * data[i-5];
  98218. sum += qlp_coeff[3] * data[i-4];
  98219. sum += qlp_coeff[2] * data[i-3];
  98220. sum += qlp_coeff[1] * data[i-2];
  98221. sum += qlp_coeff[0] * data[i-1];
  98222. data[i] = residual[i] + (sum >> lp_quantization);
  98223. }
  98224. }
  98225. }
  98226. }
  98227. else if(order > 4) {
  98228. if(order > 6) {
  98229. if(order == 8) {
  98230. for(i = 0; i < (int)data_len; i++) {
  98231. sum = 0;
  98232. sum += qlp_coeff[7] * data[i-8];
  98233. sum += qlp_coeff[6] * data[i-7];
  98234. sum += qlp_coeff[5] * data[i-6];
  98235. sum += qlp_coeff[4] * data[i-5];
  98236. sum += qlp_coeff[3] * data[i-4];
  98237. sum += qlp_coeff[2] * data[i-3];
  98238. sum += qlp_coeff[1] * data[i-2];
  98239. sum += qlp_coeff[0] * data[i-1];
  98240. data[i] = residual[i] + (sum >> lp_quantization);
  98241. }
  98242. }
  98243. else { /* order == 7 */
  98244. for(i = 0; i < (int)data_len; i++) {
  98245. sum = 0;
  98246. sum += qlp_coeff[6] * data[i-7];
  98247. sum += qlp_coeff[5] * data[i-6];
  98248. sum += qlp_coeff[4] * data[i-5];
  98249. sum += qlp_coeff[3] * data[i-4];
  98250. sum += qlp_coeff[2] * data[i-3];
  98251. sum += qlp_coeff[1] * data[i-2];
  98252. sum += qlp_coeff[0] * data[i-1];
  98253. data[i] = residual[i] + (sum >> lp_quantization);
  98254. }
  98255. }
  98256. }
  98257. else {
  98258. if(order == 6) {
  98259. for(i = 0; i < (int)data_len; i++) {
  98260. sum = 0;
  98261. sum += qlp_coeff[5] * data[i-6];
  98262. sum += qlp_coeff[4] * data[i-5];
  98263. sum += qlp_coeff[3] * data[i-4];
  98264. sum += qlp_coeff[2] * data[i-3];
  98265. sum += qlp_coeff[1] * data[i-2];
  98266. sum += qlp_coeff[0] * data[i-1];
  98267. data[i] = residual[i] + (sum >> lp_quantization);
  98268. }
  98269. }
  98270. else { /* order == 5 */
  98271. for(i = 0; i < (int)data_len; i++) {
  98272. sum = 0;
  98273. sum += qlp_coeff[4] * data[i-5];
  98274. sum += qlp_coeff[3] * data[i-4];
  98275. sum += qlp_coeff[2] * data[i-3];
  98276. sum += qlp_coeff[1] * data[i-2];
  98277. sum += qlp_coeff[0] * data[i-1];
  98278. data[i] = residual[i] + (sum >> lp_quantization);
  98279. }
  98280. }
  98281. }
  98282. }
  98283. else {
  98284. if(order > 2) {
  98285. if(order == 4) {
  98286. for(i = 0; i < (int)data_len; i++) {
  98287. sum = 0;
  98288. sum += qlp_coeff[3] * data[i-4];
  98289. sum += qlp_coeff[2] * data[i-3];
  98290. sum += qlp_coeff[1] * data[i-2];
  98291. sum += qlp_coeff[0] * data[i-1];
  98292. data[i] = residual[i] + (sum >> lp_quantization);
  98293. }
  98294. }
  98295. else { /* order == 3 */
  98296. for(i = 0; i < (int)data_len; i++) {
  98297. sum = 0;
  98298. sum += qlp_coeff[2] * data[i-3];
  98299. sum += qlp_coeff[1] * data[i-2];
  98300. sum += qlp_coeff[0] * data[i-1];
  98301. data[i] = residual[i] + (sum >> lp_quantization);
  98302. }
  98303. }
  98304. }
  98305. else {
  98306. if(order == 2) {
  98307. for(i = 0; i < (int)data_len; i++) {
  98308. sum = 0;
  98309. sum += qlp_coeff[1] * data[i-2];
  98310. sum += qlp_coeff[0] * data[i-1];
  98311. data[i] = residual[i] + (sum >> lp_quantization);
  98312. }
  98313. }
  98314. else { /* order == 1 */
  98315. for(i = 0; i < (int)data_len; i++)
  98316. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  98317. }
  98318. }
  98319. }
  98320. }
  98321. else { /* order > 12 */
  98322. for(i = 0; i < (int)data_len; i++) {
  98323. sum = 0;
  98324. switch(order) {
  98325. case 32: sum += qlp_coeff[31] * data[i-32];
  98326. case 31: sum += qlp_coeff[30] * data[i-31];
  98327. case 30: sum += qlp_coeff[29] * data[i-30];
  98328. case 29: sum += qlp_coeff[28] * data[i-29];
  98329. case 28: sum += qlp_coeff[27] * data[i-28];
  98330. case 27: sum += qlp_coeff[26] * data[i-27];
  98331. case 26: sum += qlp_coeff[25] * data[i-26];
  98332. case 25: sum += qlp_coeff[24] * data[i-25];
  98333. case 24: sum += qlp_coeff[23] * data[i-24];
  98334. case 23: sum += qlp_coeff[22] * data[i-23];
  98335. case 22: sum += qlp_coeff[21] * data[i-22];
  98336. case 21: sum += qlp_coeff[20] * data[i-21];
  98337. case 20: sum += qlp_coeff[19] * data[i-20];
  98338. case 19: sum += qlp_coeff[18] * data[i-19];
  98339. case 18: sum += qlp_coeff[17] * data[i-18];
  98340. case 17: sum += qlp_coeff[16] * data[i-17];
  98341. case 16: sum += qlp_coeff[15] * data[i-16];
  98342. case 15: sum += qlp_coeff[14] * data[i-15];
  98343. case 14: sum += qlp_coeff[13] * data[i-14];
  98344. case 13: sum += qlp_coeff[12] * data[i-13];
  98345. sum += qlp_coeff[11] * data[i-12];
  98346. sum += qlp_coeff[10] * data[i-11];
  98347. sum += qlp_coeff[ 9] * data[i-10];
  98348. sum += qlp_coeff[ 8] * data[i- 9];
  98349. sum += qlp_coeff[ 7] * data[i- 8];
  98350. sum += qlp_coeff[ 6] * data[i- 7];
  98351. sum += qlp_coeff[ 5] * data[i- 6];
  98352. sum += qlp_coeff[ 4] * data[i- 5];
  98353. sum += qlp_coeff[ 3] * data[i- 4];
  98354. sum += qlp_coeff[ 2] * data[i- 3];
  98355. sum += qlp_coeff[ 1] * data[i- 2];
  98356. sum += qlp_coeff[ 0] * data[i- 1];
  98357. }
  98358. data[i] = residual[i] + (sum >> lp_quantization);
  98359. }
  98360. }
  98361. }
  98362. #endif
  98363. 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[])
  98364. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  98365. {
  98366. unsigned i, j;
  98367. FLAC__int64 sum;
  98368. const FLAC__int32 *r = residual, *history;
  98369. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  98370. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  98371. for(i=0;i<order;i++)
  98372. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  98373. fprintf(stderr,"\n");
  98374. #endif
  98375. FLAC__ASSERT(order > 0);
  98376. for(i = 0; i < data_len; i++) {
  98377. sum = 0;
  98378. history = data;
  98379. for(j = 0; j < order; j++)
  98380. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  98381. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  98382. #ifdef _MSC_VER
  98383. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  98384. #else
  98385. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  98386. #endif
  98387. break;
  98388. }
  98389. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  98390. #ifdef _MSC_VER
  98391. 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));
  98392. #else
  98393. 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)));
  98394. #endif
  98395. break;
  98396. }
  98397. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  98398. }
  98399. }
  98400. #else /* fully unrolled version for normal use */
  98401. {
  98402. int i;
  98403. FLAC__int64 sum;
  98404. FLAC__ASSERT(order > 0);
  98405. FLAC__ASSERT(order <= 32);
  98406. /*
  98407. * We do unique versions up to 12th order since that's the subset limit.
  98408. * Also they are roughly ordered to match frequency of occurrence to
  98409. * minimize branching.
  98410. */
  98411. if(order <= 12) {
  98412. if(order > 8) {
  98413. if(order > 10) {
  98414. if(order == 12) {
  98415. for(i = 0; i < (int)data_len; i++) {
  98416. sum = 0;
  98417. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98418. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98419. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98420. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98421. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98422. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98423. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98424. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98425. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98426. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98427. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98428. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98429. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98430. }
  98431. }
  98432. else { /* order == 11 */
  98433. for(i = 0; i < (int)data_len; i++) {
  98434. sum = 0;
  98435. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98436. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  98437. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98438. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98439. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98440. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98441. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98442. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98443. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98444. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98445. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98446. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98447. }
  98448. }
  98449. }
  98450. else {
  98451. if(order == 10) {
  98452. for(i = 0; i < (int)data_len; i++) {
  98453. sum = 0;
  98454. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  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. else { /* order == 9 */
  98468. for(i = 0; i < (int)data_len; i++) {
  98469. sum = 0;
  98470. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  98471. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98472. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98473. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98474. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98475. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98476. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98477. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98478. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98479. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98480. }
  98481. }
  98482. }
  98483. }
  98484. else if(order > 4) {
  98485. if(order > 6) {
  98486. if(order == 8) {
  98487. for(i = 0; i < (int)data_len; i++) {
  98488. sum = 0;
  98489. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  98490. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98491. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98492. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98493. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98494. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98495. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98496. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98497. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98498. }
  98499. }
  98500. else { /* order == 7 */
  98501. for(i = 0; i < (int)data_len; i++) {
  98502. sum = 0;
  98503. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  98504. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98505. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98506. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98507. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98508. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98509. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98510. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98511. }
  98512. }
  98513. }
  98514. else {
  98515. if(order == 6) {
  98516. for(i = 0; i < (int)data_len; i++) {
  98517. sum = 0;
  98518. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  98519. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98520. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98521. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98522. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98523. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98524. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98525. }
  98526. }
  98527. else { /* order == 5 */
  98528. for(i = 0; i < (int)data_len; i++) {
  98529. sum = 0;
  98530. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  98531. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98532. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98533. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98534. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98535. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98536. }
  98537. }
  98538. }
  98539. }
  98540. else {
  98541. if(order > 2) {
  98542. if(order == 4) {
  98543. for(i = 0; i < (int)data_len; i++) {
  98544. sum = 0;
  98545. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  98546. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98547. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98548. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98549. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98550. }
  98551. }
  98552. else { /* order == 3 */
  98553. for(i = 0; i < (int)data_len; i++) {
  98554. sum = 0;
  98555. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  98556. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98557. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98558. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98559. }
  98560. }
  98561. }
  98562. else {
  98563. if(order == 2) {
  98564. for(i = 0; i < (int)data_len; i++) {
  98565. sum = 0;
  98566. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  98567. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  98568. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98569. }
  98570. }
  98571. else { /* order == 1 */
  98572. for(i = 0; i < (int)data_len; i++)
  98573. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  98574. }
  98575. }
  98576. }
  98577. }
  98578. else { /* order > 12 */
  98579. for(i = 0; i < (int)data_len; i++) {
  98580. sum = 0;
  98581. switch(order) {
  98582. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  98583. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  98584. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  98585. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  98586. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  98587. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  98588. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  98589. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  98590. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  98591. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  98592. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  98593. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  98594. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  98595. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  98596. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  98597. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  98598. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  98599. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  98600. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  98601. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  98602. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  98603. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  98604. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  98605. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  98606. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  98607. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  98608. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  98609. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  98610. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  98611. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  98612. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  98613. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  98614. }
  98615. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  98616. }
  98617. }
  98618. }
  98619. #endif
  98620. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98621. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  98622. {
  98623. FLAC__double error_scale;
  98624. FLAC__ASSERT(total_samples > 0);
  98625. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98626. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  98627. }
  98628. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  98629. {
  98630. if(lpc_error > 0.0) {
  98631. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  98632. if(bps >= 0.0)
  98633. return bps;
  98634. else
  98635. return 0.0;
  98636. }
  98637. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  98638. return 1e32;
  98639. }
  98640. else {
  98641. return 0.0;
  98642. }
  98643. }
  98644. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  98645. {
  98646. 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 */
  98647. FLAC__double bits, best_bits, error_scale;
  98648. FLAC__ASSERT(max_order > 0);
  98649. FLAC__ASSERT(total_samples > 0);
  98650. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  98651. best_index = 0;
  98652. best_bits = (unsigned)(-1);
  98653. for(index = 0, order = 1; index < max_order; index++, order++) {
  98654. 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);
  98655. if(bits < best_bits) {
  98656. best_index = index;
  98657. best_bits = bits;
  98658. }
  98659. }
  98660. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  98661. }
  98662. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98663. #endif
  98664. /*** End of inlined file: lpc_flac.c ***/
  98665. /*** Start of inlined file: md5.c ***/
  98666. /*** Start of inlined file: juce_FlacHeader.h ***/
  98667. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98668. // tasks..
  98669. #define VERSION "1.2.1"
  98670. #define FLAC__NO_DLL 1
  98671. #if JUCE_MSVC
  98672. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98673. #endif
  98674. #if JUCE_MAC
  98675. #define FLAC__SYS_DARWIN 1
  98676. #endif
  98677. /*** End of inlined file: juce_FlacHeader.h ***/
  98678. #if JUCE_USE_FLAC
  98679. #if HAVE_CONFIG_H
  98680. # include <config.h>
  98681. #endif
  98682. #include <stdlib.h> /* for malloc() */
  98683. #include <string.h> /* for memcpy() */
  98684. /*** Start of inlined file: md5.h ***/
  98685. #ifndef FLAC__PRIVATE__MD5_H
  98686. #define FLAC__PRIVATE__MD5_H
  98687. /*
  98688. * This is the header file for the MD5 message-digest algorithm.
  98689. * The algorithm is due to Ron Rivest. This code was
  98690. * written by Colin Plumb in 1993, no copyright is claimed.
  98691. * This code is in the public domain; do with it what you wish.
  98692. *
  98693. * Equivalent code is available from RSA Data Security, Inc.
  98694. * This code has been tested against that, and is equivalent,
  98695. * except that you don't need to include two pages of legalese
  98696. * with every copy.
  98697. *
  98698. * To compute the message digest of a chunk of bytes, declare an
  98699. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98700. * needed on buffers full of bytes, and then call MD5Final, which
  98701. * will fill a supplied 16-byte array with the digest.
  98702. *
  98703. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  98704. * header definitions; now uses stuff from dpkg's config.h
  98705. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98706. * Still in the public domain.
  98707. *
  98708. * Josh Coalson: made some changes to integrate with libFLAC.
  98709. * Still in the public domain, with no warranty.
  98710. */
  98711. typedef struct {
  98712. FLAC__uint32 in[16];
  98713. FLAC__uint32 buf[4];
  98714. FLAC__uint32 bytes[2];
  98715. FLAC__byte *internal_buf;
  98716. size_t capacity;
  98717. } FLAC__MD5Context;
  98718. void FLAC__MD5Init(FLAC__MD5Context *context);
  98719. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  98720. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  98721. #endif
  98722. /*** End of inlined file: md5.h ***/
  98723. #ifndef FLaC__INLINE
  98724. #define FLaC__INLINE
  98725. #endif
  98726. /*
  98727. * This code implements the MD5 message-digest algorithm.
  98728. * The algorithm is due to Ron Rivest. This code was
  98729. * written by Colin Plumb in 1993, no copyright is claimed.
  98730. * This code is in the public domain; do with it what you wish.
  98731. *
  98732. * Equivalent code is available from RSA Data Security, Inc.
  98733. * This code has been tested against that, and is equivalent,
  98734. * except that you don't need to include two pages of legalese
  98735. * with every copy.
  98736. *
  98737. * To compute the message digest of a chunk of bytes, declare an
  98738. * MD5Context structure, pass it to MD5Init, call MD5Update as
  98739. * needed on buffers full of bytes, and then call MD5Final, which
  98740. * will fill a supplied 16-byte array with the digest.
  98741. *
  98742. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  98743. * definitions; now uses stuff from dpkg's config.h.
  98744. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  98745. * Still in the public domain.
  98746. *
  98747. * Josh Coalson: made some changes to integrate with libFLAC.
  98748. * Still in the public domain.
  98749. */
  98750. /* The four core functions - F1 is optimized somewhat */
  98751. /* #define F1(x, y, z) (x & y | ~x & z) */
  98752. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  98753. #define F2(x, y, z) F1(z, x, y)
  98754. #define F3(x, y, z) (x ^ y ^ z)
  98755. #define F4(x, y, z) (y ^ (x | ~z))
  98756. /* This is the central step in the MD5 algorithm. */
  98757. #define MD5STEP(f,w,x,y,z,in,s) \
  98758. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  98759. /*
  98760. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  98761. * reflect the addition of 16 longwords of new data. MD5Update blocks
  98762. * the data and converts bytes into longwords for this routine.
  98763. */
  98764. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  98765. {
  98766. register FLAC__uint32 a, b, c, d;
  98767. a = buf[0];
  98768. b = buf[1];
  98769. c = buf[2];
  98770. d = buf[3];
  98771. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  98772. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  98773. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  98774. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  98775. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  98776. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  98777. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  98778. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  98779. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  98780. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  98781. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  98782. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  98783. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  98784. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  98785. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  98786. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  98787. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  98788. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  98789. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  98790. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  98791. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  98792. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  98793. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  98794. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  98795. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  98796. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  98797. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  98798. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  98799. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  98800. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  98801. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  98802. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  98803. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  98804. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  98805. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  98806. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  98807. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  98808. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  98809. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  98810. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  98811. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  98812. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  98813. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  98814. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  98815. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  98816. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  98817. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  98818. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  98819. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  98820. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  98821. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  98822. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  98823. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  98824. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  98825. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  98826. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  98827. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  98828. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  98829. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  98830. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  98831. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  98832. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  98833. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  98834. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  98835. buf[0] += a;
  98836. buf[1] += b;
  98837. buf[2] += c;
  98838. buf[3] += d;
  98839. }
  98840. #if WORDS_BIGENDIAN
  98841. //@@@@@@ OPT: use bswap/intrinsics
  98842. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  98843. {
  98844. register FLAC__uint32 x;
  98845. do {
  98846. x = *buf;
  98847. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  98848. *buf++ = (x >> 16) | (x << 16);
  98849. } while (--words);
  98850. }
  98851. static void byteSwapX16(FLAC__uint32 *buf)
  98852. {
  98853. register FLAC__uint32 x;
  98854. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98855. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98856. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98857. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98858. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98859. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98860. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98861. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98862. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98863. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98864. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98865. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98866. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98867. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98868. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  98869. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  98870. }
  98871. #else
  98872. #define byteSwap(buf, words)
  98873. #define byteSwapX16(buf)
  98874. #endif
  98875. /*
  98876. * Update context to reflect the concatenation of another buffer full
  98877. * of bytes.
  98878. */
  98879. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  98880. {
  98881. FLAC__uint32 t;
  98882. /* Update byte count */
  98883. t = ctx->bytes[0];
  98884. if ((ctx->bytes[0] = t + len) < t)
  98885. ctx->bytes[1]++; /* Carry from low to high */
  98886. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  98887. if (t > len) {
  98888. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  98889. return;
  98890. }
  98891. /* First chunk is an odd size */
  98892. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  98893. byteSwapX16(ctx->in);
  98894. FLAC__MD5Transform(ctx->buf, ctx->in);
  98895. buf += t;
  98896. len -= t;
  98897. /* Process data in 64-byte chunks */
  98898. while (len >= 64) {
  98899. memcpy(ctx->in, buf, 64);
  98900. byteSwapX16(ctx->in);
  98901. FLAC__MD5Transform(ctx->buf, ctx->in);
  98902. buf += 64;
  98903. len -= 64;
  98904. }
  98905. /* Handle any remaining bytes of data. */
  98906. memcpy(ctx->in, buf, len);
  98907. }
  98908. /*
  98909. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  98910. * initialization constants.
  98911. */
  98912. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  98913. {
  98914. ctx->buf[0] = 0x67452301;
  98915. ctx->buf[1] = 0xefcdab89;
  98916. ctx->buf[2] = 0x98badcfe;
  98917. ctx->buf[3] = 0x10325476;
  98918. ctx->bytes[0] = 0;
  98919. ctx->bytes[1] = 0;
  98920. ctx->internal_buf = 0;
  98921. ctx->capacity = 0;
  98922. }
  98923. /*
  98924. * Final wrapup - pad to 64-byte boundary with the bit pattern
  98925. * 1 0* (64-bit count of bits processed, MSB-first)
  98926. */
  98927. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  98928. {
  98929. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  98930. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  98931. /* Set the first char of padding to 0x80. There is always room. */
  98932. *p++ = 0x80;
  98933. /* Bytes of padding needed to make 56 bytes (-8..55) */
  98934. count = 56 - 1 - count;
  98935. if (count < 0) { /* Padding forces an extra block */
  98936. memset(p, 0, count + 8);
  98937. byteSwapX16(ctx->in);
  98938. FLAC__MD5Transform(ctx->buf, ctx->in);
  98939. p = (FLAC__byte *)ctx->in;
  98940. count = 56;
  98941. }
  98942. memset(p, 0, count);
  98943. byteSwap(ctx->in, 14);
  98944. /* Append length in bits and transform */
  98945. ctx->in[14] = ctx->bytes[0] << 3;
  98946. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  98947. FLAC__MD5Transform(ctx->buf, ctx->in);
  98948. byteSwap(ctx->buf, 4);
  98949. memcpy(digest, ctx->buf, 16);
  98950. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  98951. if(0 != ctx->internal_buf) {
  98952. free(ctx->internal_buf);
  98953. ctx->internal_buf = 0;
  98954. ctx->capacity = 0;
  98955. }
  98956. }
  98957. /*
  98958. * Convert the incoming audio signal to a byte stream
  98959. */
  98960. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  98961. {
  98962. unsigned channel, sample;
  98963. register FLAC__int32 a_word;
  98964. register FLAC__byte *buf_ = buf;
  98965. #if WORDS_BIGENDIAN
  98966. #else
  98967. if(channels == 2 && bytes_per_sample == 2) {
  98968. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  98969. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  98970. for(sample = 0; sample < samples; sample++, buf1_+=2)
  98971. *buf1_ = (FLAC__int16)signal[1][sample];
  98972. }
  98973. else if(channels == 1 && bytes_per_sample == 2) {
  98974. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  98975. for(sample = 0; sample < samples; sample++)
  98976. *buf1_++ = (FLAC__int16)signal[0][sample];
  98977. }
  98978. else
  98979. #endif
  98980. if(bytes_per_sample == 2) {
  98981. if(channels == 2) {
  98982. for(sample = 0; sample < samples; sample++) {
  98983. a_word = signal[0][sample];
  98984. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98985. *buf_++ = (FLAC__byte)a_word;
  98986. a_word = signal[1][sample];
  98987. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98988. *buf_++ = (FLAC__byte)a_word;
  98989. }
  98990. }
  98991. else if(channels == 1) {
  98992. for(sample = 0; sample < samples; sample++) {
  98993. a_word = signal[0][sample];
  98994. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  98995. *buf_++ = (FLAC__byte)a_word;
  98996. }
  98997. }
  98998. else {
  98999. for(sample = 0; sample < samples; sample++) {
  99000. for(channel = 0; channel < channels; channel++) {
  99001. a_word = signal[channel][sample];
  99002. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99003. *buf_++ = (FLAC__byte)a_word;
  99004. }
  99005. }
  99006. }
  99007. }
  99008. else if(bytes_per_sample == 3) {
  99009. if(channels == 2) {
  99010. for(sample = 0; sample < samples; sample++) {
  99011. a_word = signal[0][sample];
  99012. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99013. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99014. *buf_++ = (FLAC__byte)a_word;
  99015. a_word = signal[1][sample];
  99016. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99017. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99018. *buf_++ = (FLAC__byte)a_word;
  99019. }
  99020. }
  99021. else if(channels == 1) {
  99022. for(sample = 0; sample < samples; sample++) {
  99023. a_word = signal[0][sample];
  99024. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99025. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99026. *buf_++ = (FLAC__byte)a_word;
  99027. }
  99028. }
  99029. else {
  99030. for(sample = 0; sample < samples; sample++) {
  99031. for(channel = 0; channel < channels; channel++) {
  99032. a_word = signal[channel][sample];
  99033. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99034. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99035. *buf_++ = (FLAC__byte)a_word;
  99036. }
  99037. }
  99038. }
  99039. }
  99040. else if(bytes_per_sample == 1) {
  99041. if(channels == 2) {
  99042. for(sample = 0; sample < samples; sample++) {
  99043. a_word = signal[0][sample];
  99044. *buf_++ = (FLAC__byte)a_word;
  99045. a_word = signal[1][sample];
  99046. *buf_++ = (FLAC__byte)a_word;
  99047. }
  99048. }
  99049. else if(channels == 1) {
  99050. for(sample = 0; sample < samples; sample++) {
  99051. a_word = signal[0][sample];
  99052. *buf_++ = (FLAC__byte)a_word;
  99053. }
  99054. }
  99055. else {
  99056. for(sample = 0; sample < samples; sample++) {
  99057. for(channel = 0; channel < channels; channel++) {
  99058. a_word = signal[channel][sample];
  99059. *buf_++ = (FLAC__byte)a_word;
  99060. }
  99061. }
  99062. }
  99063. }
  99064. else { /* bytes_per_sample == 4, maybe optimize more later */
  99065. for(sample = 0; sample < samples; sample++) {
  99066. for(channel = 0; channel < channels; channel++) {
  99067. a_word = signal[channel][sample];
  99068. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99069. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99070. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  99071. *buf_++ = (FLAC__byte)a_word;
  99072. }
  99073. }
  99074. }
  99075. }
  99076. /*
  99077. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  99078. */
  99079. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  99080. {
  99081. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  99082. /* overflow check */
  99083. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  99084. return false;
  99085. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  99086. return false;
  99087. if(ctx->capacity < bytes_needed) {
  99088. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  99089. if(0 == tmp) {
  99090. free(ctx->internal_buf);
  99091. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  99092. return false;
  99093. }
  99094. ctx->internal_buf = tmp;
  99095. ctx->capacity = bytes_needed;
  99096. }
  99097. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  99098. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  99099. return true;
  99100. }
  99101. #endif
  99102. /*** End of inlined file: md5.c ***/
  99103. /*** Start of inlined file: memory.c ***/
  99104. /*** Start of inlined file: juce_FlacHeader.h ***/
  99105. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99106. // tasks..
  99107. #define VERSION "1.2.1"
  99108. #define FLAC__NO_DLL 1
  99109. #if JUCE_MSVC
  99110. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99111. #endif
  99112. #if JUCE_MAC
  99113. #define FLAC__SYS_DARWIN 1
  99114. #endif
  99115. /*** End of inlined file: juce_FlacHeader.h ***/
  99116. #if JUCE_USE_FLAC
  99117. #if HAVE_CONFIG_H
  99118. # include <config.h>
  99119. #endif
  99120. /*** Start of inlined file: memory.h ***/
  99121. #ifndef FLAC__PRIVATE__MEMORY_H
  99122. #define FLAC__PRIVATE__MEMORY_H
  99123. #ifdef HAVE_CONFIG_H
  99124. #include <config.h>
  99125. #endif
  99126. #include <stdlib.h> /* for size_t */
  99127. /* Returns the unaligned address returned by malloc.
  99128. * Use free() on this address to deallocate.
  99129. */
  99130. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  99131. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  99132. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  99133. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  99134. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  99135. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99136. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  99137. #endif
  99138. #endif
  99139. /*** End of inlined file: memory.h ***/
  99140. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  99141. {
  99142. void *x;
  99143. FLAC__ASSERT(0 != aligned_address);
  99144. #ifdef FLAC__ALIGN_MALLOC_DATA
  99145. /* align on 32-byte (256-bit) boundary */
  99146. x = safe_malloc_add_2op_(bytes, /*+*/31);
  99147. #ifdef SIZEOF_VOIDP
  99148. #if SIZEOF_VOIDP == 4
  99149. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  99150. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99151. #elif SIZEOF_VOIDP == 8
  99152. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99153. #else
  99154. # error Unsupported sizeof(void*)
  99155. #endif
  99156. #else
  99157. /* there's got to be a better way to do this right for all archs */
  99158. if(sizeof(void*) == sizeof(unsigned))
  99159. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  99160. else if(sizeof(void*) == sizeof(FLAC__uint64))
  99161. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  99162. else
  99163. return 0;
  99164. #endif
  99165. #else
  99166. x = safe_malloc_(bytes);
  99167. *aligned_address = x;
  99168. #endif
  99169. return x;
  99170. }
  99171. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  99172. {
  99173. FLAC__int32 *pu; /* unaligned pointer */
  99174. union { /* union needed to comply with C99 pointer aliasing rules */
  99175. FLAC__int32 *pa; /* aligned pointer */
  99176. void *pv; /* aligned pointer alias */
  99177. } u;
  99178. FLAC__ASSERT(elements > 0);
  99179. FLAC__ASSERT(0 != unaligned_pointer);
  99180. FLAC__ASSERT(0 != aligned_pointer);
  99181. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99182. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  99183. if(0 == pu) {
  99184. return false;
  99185. }
  99186. else {
  99187. if(*unaligned_pointer != 0)
  99188. free(*unaligned_pointer);
  99189. *unaligned_pointer = pu;
  99190. *aligned_pointer = u.pa;
  99191. return true;
  99192. }
  99193. }
  99194. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  99195. {
  99196. FLAC__uint32 *pu; /* unaligned pointer */
  99197. union { /* union needed to comply with C99 pointer aliasing rules */
  99198. FLAC__uint32 *pa; /* aligned pointer */
  99199. void *pv; /* aligned pointer alias */
  99200. } u;
  99201. FLAC__ASSERT(elements > 0);
  99202. FLAC__ASSERT(0 != unaligned_pointer);
  99203. FLAC__ASSERT(0 != aligned_pointer);
  99204. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99205. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99206. if(0 == pu) {
  99207. return false;
  99208. }
  99209. else {
  99210. if(*unaligned_pointer != 0)
  99211. free(*unaligned_pointer);
  99212. *unaligned_pointer = pu;
  99213. *aligned_pointer = u.pa;
  99214. return true;
  99215. }
  99216. }
  99217. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  99218. {
  99219. FLAC__uint64 *pu; /* unaligned pointer */
  99220. union { /* union needed to comply with C99 pointer aliasing rules */
  99221. FLAC__uint64 *pa; /* aligned pointer */
  99222. void *pv; /* aligned pointer alias */
  99223. } u;
  99224. FLAC__ASSERT(elements > 0);
  99225. FLAC__ASSERT(0 != unaligned_pointer);
  99226. FLAC__ASSERT(0 != aligned_pointer);
  99227. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99228. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99229. if(0 == pu) {
  99230. return false;
  99231. }
  99232. else {
  99233. if(*unaligned_pointer != 0)
  99234. free(*unaligned_pointer);
  99235. *unaligned_pointer = pu;
  99236. *aligned_pointer = u.pa;
  99237. return true;
  99238. }
  99239. }
  99240. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  99241. {
  99242. unsigned *pu; /* unaligned pointer */
  99243. union { /* union needed to comply with C99 pointer aliasing rules */
  99244. unsigned *pa; /* aligned pointer */
  99245. void *pv; /* aligned pointer alias */
  99246. } u;
  99247. FLAC__ASSERT(elements > 0);
  99248. FLAC__ASSERT(0 != unaligned_pointer);
  99249. FLAC__ASSERT(0 != aligned_pointer);
  99250. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99251. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99252. if(0 == pu) {
  99253. return false;
  99254. }
  99255. else {
  99256. if(*unaligned_pointer != 0)
  99257. free(*unaligned_pointer);
  99258. *unaligned_pointer = pu;
  99259. *aligned_pointer = u.pa;
  99260. return true;
  99261. }
  99262. }
  99263. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99264. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  99265. {
  99266. FLAC__real *pu; /* unaligned pointer */
  99267. union { /* union needed to comply with C99 pointer aliasing rules */
  99268. FLAC__real *pa; /* aligned pointer */
  99269. void *pv; /* aligned pointer alias */
  99270. } u;
  99271. FLAC__ASSERT(elements > 0);
  99272. FLAC__ASSERT(0 != unaligned_pointer);
  99273. FLAC__ASSERT(0 != aligned_pointer);
  99274. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  99275. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  99276. if(0 == pu) {
  99277. return false;
  99278. }
  99279. else {
  99280. if(*unaligned_pointer != 0)
  99281. free(*unaligned_pointer);
  99282. *unaligned_pointer = pu;
  99283. *aligned_pointer = u.pa;
  99284. return true;
  99285. }
  99286. }
  99287. #endif
  99288. #endif
  99289. /*** End of inlined file: memory.c ***/
  99290. /*** Start of inlined file: stream_decoder.c ***/
  99291. /*** Start of inlined file: juce_FlacHeader.h ***/
  99292. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  99293. // tasks..
  99294. #define VERSION "1.2.1"
  99295. #define FLAC__NO_DLL 1
  99296. #if JUCE_MSVC
  99297. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  99298. #endif
  99299. #if JUCE_MAC
  99300. #define FLAC__SYS_DARWIN 1
  99301. #endif
  99302. /*** End of inlined file: juce_FlacHeader.h ***/
  99303. #if JUCE_USE_FLAC
  99304. #if HAVE_CONFIG_H
  99305. # include <config.h>
  99306. #endif
  99307. #if defined _MSC_VER || defined __MINGW32__
  99308. #include <io.h> /* for _setmode() */
  99309. #include <fcntl.h> /* for _O_BINARY */
  99310. #endif
  99311. #if defined __CYGWIN__ || defined __EMX__
  99312. #include <io.h> /* for setmode(), O_BINARY */
  99313. #include <fcntl.h> /* for _O_BINARY */
  99314. #endif
  99315. #include <stdio.h>
  99316. #include <stdlib.h> /* for malloc() */
  99317. #include <string.h> /* for memset/memcpy() */
  99318. #include <sys/stat.h> /* for stat() */
  99319. #include <sys/types.h> /* for off_t */
  99320. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  99321. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  99322. #define fseeko fseek
  99323. #define ftello ftell
  99324. #endif
  99325. #endif
  99326. /*** Start of inlined file: stream_decoder.h ***/
  99327. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  99328. #define FLAC__PROTECTED__STREAM_DECODER_H
  99329. #if FLAC__HAS_OGG
  99330. #include "include/private/ogg_decoder_aspect.h"
  99331. #endif
  99332. typedef struct FLAC__StreamDecoderProtected {
  99333. FLAC__StreamDecoderState state;
  99334. unsigned channels;
  99335. FLAC__ChannelAssignment channel_assignment;
  99336. unsigned bits_per_sample;
  99337. unsigned sample_rate; /* in Hz */
  99338. unsigned blocksize; /* in samples (per channel) */
  99339. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  99340. #if FLAC__HAS_OGG
  99341. FLAC__OggDecoderAspect ogg_decoder_aspect;
  99342. #endif
  99343. } FLAC__StreamDecoderProtected;
  99344. /*
  99345. * return the number of input bytes consumed
  99346. */
  99347. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  99348. #endif
  99349. /*** End of inlined file: stream_decoder.h ***/
  99350. #ifdef max
  99351. #undef max
  99352. #endif
  99353. #define max(a,b) ((a)>(b)?(a):(b))
  99354. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  99355. #ifdef _MSC_VER
  99356. #define FLAC__U64L(x) x
  99357. #else
  99358. #define FLAC__U64L(x) x##LLU
  99359. #endif
  99360. /* technically this should be in an "export.c" but this is convenient enough */
  99361. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  99362. #if FLAC__HAS_OGG
  99363. 1
  99364. #else
  99365. 0
  99366. #endif
  99367. ;
  99368. /***********************************************************************
  99369. *
  99370. * Private static data
  99371. *
  99372. ***********************************************************************/
  99373. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  99374. /***********************************************************************
  99375. *
  99376. * Private class method prototypes
  99377. *
  99378. ***********************************************************************/
  99379. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  99380. static FILE *get_binary_stdin_(void);
  99381. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  99382. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  99383. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  99384. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  99385. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99386. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  99387. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  99388. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  99389. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  99390. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  99391. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  99392. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  99393. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  99394. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99395. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99396. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99397. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  99398. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  99399. 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);
  99400. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  99401. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  99402. #if FLAC__HAS_OGG
  99403. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  99404. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99405. #endif
  99406. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  99407. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  99408. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99409. #if FLAC__HAS_OGG
  99410. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  99411. #endif
  99412. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  99413. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  99414. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  99415. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  99416. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  99417. /***********************************************************************
  99418. *
  99419. * Private class data
  99420. *
  99421. ***********************************************************************/
  99422. typedef struct FLAC__StreamDecoderPrivate {
  99423. #if FLAC__HAS_OGG
  99424. FLAC__bool is_ogg;
  99425. #endif
  99426. FLAC__StreamDecoderReadCallback read_callback;
  99427. FLAC__StreamDecoderSeekCallback seek_callback;
  99428. FLAC__StreamDecoderTellCallback tell_callback;
  99429. FLAC__StreamDecoderLengthCallback length_callback;
  99430. FLAC__StreamDecoderEofCallback eof_callback;
  99431. FLAC__StreamDecoderWriteCallback write_callback;
  99432. FLAC__StreamDecoderMetadataCallback metadata_callback;
  99433. FLAC__StreamDecoderErrorCallback error_callback;
  99434. /* generic 32-bit datapath: */
  99435. 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[]);
  99436. /* generic 64-bit datapath: */
  99437. 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[]);
  99438. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  99439. 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[]);
  99440. /* 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: */
  99441. 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[]);
  99442. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  99443. void *client_data;
  99444. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  99445. FLAC__BitReader *input;
  99446. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  99447. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  99448. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  99449. unsigned output_capacity, output_channels;
  99450. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  99451. FLAC__uint64 samples_decoded;
  99452. FLAC__bool has_stream_info, has_seek_table;
  99453. FLAC__StreamMetadata stream_info;
  99454. FLAC__StreamMetadata seek_table;
  99455. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  99456. FLAC__byte *metadata_filter_ids;
  99457. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  99458. FLAC__Frame frame;
  99459. FLAC__bool cached; /* true if there is a byte in lookahead */
  99460. FLAC__CPUInfo cpuinfo;
  99461. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  99462. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  99463. /* unaligned (original) pointers to allocated data */
  99464. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  99465. 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 */
  99466. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  99467. FLAC__bool is_seeking;
  99468. FLAC__MD5Context md5context;
  99469. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  99470. /* (the rest of these are only used for seeking) */
  99471. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  99472. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  99473. FLAC__uint64 target_sample;
  99474. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  99475. #if FLAC__HAS_OGG
  99476. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  99477. #endif
  99478. } FLAC__StreamDecoderPrivate;
  99479. /***********************************************************************
  99480. *
  99481. * Public static class data
  99482. *
  99483. ***********************************************************************/
  99484. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  99485. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  99486. "FLAC__STREAM_DECODER_READ_METADATA",
  99487. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  99488. "FLAC__STREAM_DECODER_READ_FRAME",
  99489. "FLAC__STREAM_DECODER_END_OF_STREAM",
  99490. "FLAC__STREAM_DECODER_OGG_ERROR",
  99491. "FLAC__STREAM_DECODER_SEEK_ERROR",
  99492. "FLAC__STREAM_DECODER_ABORTED",
  99493. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  99494. "FLAC__STREAM_DECODER_UNINITIALIZED"
  99495. };
  99496. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  99497. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  99498. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99499. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  99500. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  99501. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  99502. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  99503. };
  99504. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  99505. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  99506. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  99507. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  99508. };
  99509. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  99510. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  99511. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  99512. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  99513. };
  99514. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  99515. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  99516. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  99517. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  99518. };
  99519. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  99520. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  99521. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  99522. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  99523. };
  99524. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  99525. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  99526. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  99527. };
  99528. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  99529. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  99530. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  99531. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  99532. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  99533. };
  99534. /***********************************************************************
  99535. *
  99536. * Class constructor/destructor
  99537. *
  99538. ***********************************************************************/
  99539. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  99540. {
  99541. FLAC__StreamDecoder *decoder;
  99542. unsigned i;
  99543. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99544. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  99545. if(decoder == 0) {
  99546. return 0;
  99547. }
  99548. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  99549. if(decoder->protected_ == 0) {
  99550. free(decoder);
  99551. return 0;
  99552. }
  99553. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  99554. if(decoder->private_ == 0) {
  99555. free(decoder->protected_);
  99556. free(decoder);
  99557. return 0;
  99558. }
  99559. decoder->private_->input = FLAC__bitreader_new();
  99560. if(decoder->private_->input == 0) {
  99561. free(decoder->private_);
  99562. free(decoder->protected_);
  99563. free(decoder);
  99564. return 0;
  99565. }
  99566. decoder->private_->metadata_filter_ids_capacity = 16;
  99567. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  99568. FLAC__bitreader_delete(decoder->private_->input);
  99569. free(decoder->private_);
  99570. free(decoder->protected_);
  99571. free(decoder);
  99572. return 0;
  99573. }
  99574. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99575. decoder->private_->output[i] = 0;
  99576. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99577. }
  99578. decoder->private_->output_capacity = 0;
  99579. decoder->private_->output_channels = 0;
  99580. decoder->private_->has_seek_table = false;
  99581. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99582. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  99583. decoder->private_->file = 0;
  99584. set_defaults_dec(decoder);
  99585. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99586. return decoder;
  99587. }
  99588. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  99589. {
  99590. unsigned i;
  99591. FLAC__ASSERT(0 != decoder);
  99592. FLAC__ASSERT(0 != decoder->protected_);
  99593. FLAC__ASSERT(0 != decoder->private_);
  99594. FLAC__ASSERT(0 != decoder->private_->input);
  99595. (void)FLAC__stream_decoder_finish(decoder);
  99596. if(0 != decoder->private_->metadata_filter_ids)
  99597. free(decoder->private_->metadata_filter_ids);
  99598. FLAC__bitreader_delete(decoder->private_->input);
  99599. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  99600. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  99601. free(decoder->private_);
  99602. free(decoder->protected_);
  99603. free(decoder);
  99604. }
  99605. /***********************************************************************
  99606. *
  99607. * Public class methods
  99608. *
  99609. ***********************************************************************/
  99610. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  99611. FLAC__StreamDecoder *decoder,
  99612. FLAC__StreamDecoderReadCallback read_callback,
  99613. FLAC__StreamDecoderSeekCallback seek_callback,
  99614. FLAC__StreamDecoderTellCallback tell_callback,
  99615. FLAC__StreamDecoderLengthCallback length_callback,
  99616. FLAC__StreamDecoderEofCallback eof_callback,
  99617. FLAC__StreamDecoderWriteCallback write_callback,
  99618. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99619. FLAC__StreamDecoderErrorCallback error_callback,
  99620. void *client_data,
  99621. FLAC__bool is_ogg
  99622. )
  99623. {
  99624. FLAC__ASSERT(0 != decoder);
  99625. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99626. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  99627. #if !FLAC__HAS_OGG
  99628. if(is_ogg)
  99629. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99630. #endif
  99631. if(
  99632. 0 == read_callback ||
  99633. 0 == write_callback ||
  99634. 0 == error_callback ||
  99635. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  99636. )
  99637. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  99638. #if FLAC__HAS_OGG
  99639. decoder->private_->is_ogg = is_ogg;
  99640. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  99641. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  99642. #endif
  99643. /*
  99644. * get the CPU info and set the function pointers
  99645. */
  99646. FLAC__cpu_info(&decoder->private_->cpuinfo);
  99647. /* first default to the non-asm routines */
  99648. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  99649. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  99650. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  99651. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  99652. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  99653. /* now override with asm where appropriate */
  99654. #ifndef FLAC__NO_ASM
  99655. if(decoder->private_->cpuinfo.use_asm) {
  99656. #ifdef FLAC__CPU_IA32
  99657. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99658. #ifdef FLAC__HAS_NASM
  99659. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  99660. if(decoder->private_->cpuinfo.data.ia32.bswap)
  99661. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  99662. #endif
  99663. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  99664. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99665. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99666. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  99667. }
  99668. else {
  99669. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  99670. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  99671. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  99672. }
  99673. #endif
  99674. #elif defined FLAC__CPU_PPC
  99675. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  99676. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  99677. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  99678. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  99679. }
  99680. #endif
  99681. }
  99682. #endif
  99683. /* from here on, errors are fatal */
  99684. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  99685. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99686. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99687. }
  99688. decoder->private_->read_callback = read_callback;
  99689. decoder->private_->seek_callback = seek_callback;
  99690. decoder->private_->tell_callback = tell_callback;
  99691. decoder->private_->length_callback = length_callback;
  99692. decoder->private_->eof_callback = eof_callback;
  99693. decoder->private_->write_callback = write_callback;
  99694. decoder->private_->metadata_callback = metadata_callback;
  99695. decoder->private_->error_callback = error_callback;
  99696. decoder->private_->client_data = client_data;
  99697. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  99698. decoder->private_->samples_decoded = 0;
  99699. decoder->private_->has_stream_info = false;
  99700. decoder->private_->cached = false;
  99701. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  99702. decoder->private_->is_seeking = false;
  99703. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  99704. if(!FLAC__stream_decoder_reset(decoder)) {
  99705. /* above call sets the state for us */
  99706. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  99707. }
  99708. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  99709. }
  99710. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  99711. FLAC__StreamDecoder *decoder,
  99712. FLAC__StreamDecoderReadCallback read_callback,
  99713. FLAC__StreamDecoderSeekCallback seek_callback,
  99714. FLAC__StreamDecoderTellCallback tell_callback,
  99715. FLAC__StreamDecoderLengthCallback length_callback,
  99716. FLAC__StreamDecoderEofCallback eof_callback,
  99717. FLAC__StreamDecoderWriteCallback write_callback,
  99718. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99719. FLAC__StreamDecoderErrorCallback error_callback,
  99720. void *client_data
  99721. )
  99722. {
  99723. return init_stream_internal_dec(
  99724. decoder,
  99725. read_callback,
  99726. seek_callback,
  99727. tell_callback,
  99728. length_callback,
  99729. eof_callback,
  99730. write_callback,
  99731. metadata_callback,
  99732. error_callback,
  99733. client_data,
  99734. /*is_ogg=*/false
  99735. );
  99736. }
  99737. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  99738. FLAC__StreamDecoder *decoder,
  99739. FLAC__StreamDecoderReadCallback read_callback,
  99740. FLAC__StreamDecoderSeekCallback seek_callback,
  99741. FLAC__StreamDecoderTellCallback tell_callback,
  99742. FLAC__StreamDecoderLengthCallback length_callback,
  99743. FLAC__StreamDecoderEofCallback eof_callback,
  99744. FLAC__StreamDecoderWriteCallback write_callback,
  99745. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99746. FLAC__StreamDecoderErrorCallback error_callback,
  99747. void *client_data
  99748. )
  99749. {
  99750. return init_stream_internal_dec(
  99751. decoder,
  99752. read_callback,
  99753. seek_callback,
  99754. tell_callback,
  99755. length_callback,
  99756. eof_callback,
  99757. write_callback,
  99758. metadata_callback,
  99759. error_callback,
  99760. client_data,
  99761. /*is_ogg=*/true
  99762. );
  99763. }
  99764. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  99765. FLAC__StreamDecoder *decoder,
  99766. FILE *file,
  99767. FLAC__StreamDecoderWriteCallback write_callback,
  99768. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99769. FLAC__StreamDecoderErrorCallback error_callback,
  99770. void *client_data,
  99771. FLAC__bool is_ogg
  99772. )
  99773. {
  99774. FLAC__ASSERT(0 != decoder);
  99775. FLAC__ASSERT(0 != file);
  99776. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99777. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99778. if(0 == write_callback || 0 == error_callback)
  99779. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99780. /*
  99781. * To make sure that our file does not go unclosed after an error, we
  99782. * must assign the FILE pointer before any further error can occur in
  99783. * this routine.
  99784. */
  99785. if(file == stdin)
  99786. file = get_binary_stdin_(); /* just to be safe */
  99787. decoder->private_->file = file;
  99788. return init_stream_internal_dec(
  99789. decoder,
  99790. file_read_callback_dec,
  99791. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  99792. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  99793. decoder->private_->file == stdin? 0: file_length_callback_,
  99794. file_eof_callback_,
  99795. write_callback,
  99796. metadata_callback,
  99797. error_callback,
  99798. client_data,
  99799. is_ogg
  99800. );
  99801. }
  99802. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  99803. FLAC__StreamDecoder *decoder,
  99804. FILE *file,
  99805. FLAC__StreamDecoderWriteCallback write_callback,
  99806. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99807. FLAC__StreamDecoderErrorCallback error_callback,
  99808. void *client_data
  99809. )
  99810. {
  99811. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99812. }
  99813. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  99814. FLAC__StreamDecoder *decoder,
  99815. FILE *file,
  99816. FLAC__StreamDecoderWriteCallback write_callback,
  99817. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99818. FLAC__StreamDecoderErrorCallback error_callback,
  99819. void *client_data
  99820. )
  99821. {
  99822. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99823. }
  99824. static FLAC__StreamDecoderInitStatus init_file_internal_(
  99825. FLAC__StreamDecoder *decoder,
  99826. const char *filename,
  99827. FLAC__StreamDecoderWriteCallback write_callback,
  99828. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99829. FLAC__StreamDecoderErrorCallback error_callback,
  99830. void *client_data,
  99831. FLAC__bool is_ogg
  99832. )
  99833. {
  99834. FILE *file;
  99835. FLAC__ASSERT(0 != decoder);
  99836. /*
  99837. * To make sure that our file does not go unclosed after an error, we
  99838. * have to do the same entrance checks here that are later performed
  99839. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  99840. */
  99841. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99842. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  99843. if(0 == write_callback || 0 == error_callback)
  99844. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  99845. file = filename? fopen(filename, "rb") : stdin;
  99846. if(0 == file)
  99847. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  99848. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  99849. }
  99850. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  99851. FLAC__StreamDecoder *decoder,
  99852. const char *filename,
  99853. FLAC__StreamDecoderWriteCallback write_callback,
  99854. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99855. FLAC__StreamDecoderErrorCallback error_callback,
  99856. void *client_data
  99857. )
  99858. {
  99859. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  99860. }
  99861. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  99862. FLAC__StreamDecoder *decoder,
  99863. const char *filename,
  99864. FLAC__StreamDecoderWriteCallback write_callback,
  99865. FLAC__StreamDecoderMetadataCallback metadata_callback,
  99866. FLAC__StreamDecoderErrorCallback error_callback,
  99867. void *client_data
  99868. )
  99869. {
  99870. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  99871. }
  99872. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  99873. {
  99874. FLAC__bool md5_failed = false;
  99875. unsigned i;
  99876. FLAC__ASSERT(0 != decoder);
  99877. FLAC__ASSERT(0 != decoder->private_);
  99878. FLAC__ASSERT(0 != decoder->protected_);
  99879. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  99880. return true;
  99881. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  99882. * always call FLAC__MD5Final()
  99883. */
  99884. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  99885. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  99886. free(decoder->private_->seek_table.data.seek_table.points);
  99887. decoder->private_->seek_table.data.seek_table.points = 0;
  99888. decoder->private_->has_seek_table = false;
  99889. }
  99890. FLAC__bitreader_free(decoder->private_->input);
  99891. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99892. /* WATCHOUT:
  99893. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  99894. * output arrays have a buffer of up to 3 zeroes in front
  99895. * (at negative indices) for alignment purposes; we use 4
  99896. * to keep the data well-aligned.
  99897. */
  99898. if(0 != decoder->private_->output[i]) {
  99899. free(decoder->private_->output[i]-4);
  99900. decoder->private_->output[i] = 0;
  99901. }
  99902. if(0 != decoder->private_->residual_unaligned[i]) {
  99903. free(decoder->private_->residual_unaligned[i]);
  99904. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  99905. }
  99906. }
  99907. decoder->private_->output_capacity = 0;
  99908. decoder->private_->output_channels = 0;
  99909. #if FLAC__HAS_OGG
  99910. if(decoder->private_->is_ogg)
  99911. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  99912. #endif
  99913. if(0 != decoder->private_->file) {
  99914. if(decoder->private_->file != stdin)
  99915. fclose(decoder->private_->file);
  99916. decoder->private_->file = 0;
  99917. }
  99918. if(decoder->private_->do_md5_checking) {
  99919. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  99920. md5_failed = true;
  99921. }
  99922. decoder->private_->is_seeking = false;
  99923. set_defaults_dec(decoder);
  99924. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  99925. return !md5_failed;
  99926. }
  99927. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  99928. {
  99929. FLAC__ASSERT(0 != decoder);
  99930. FLAC__ASSERT(0 != decoder->private_);
  99931. FLAC__ASSERT(0 != decoder->protected_);
  99932. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99933. return false;
  99934. #if FLAC__HAS_OGG
  99935. /* can't check decoder->private_->is_ogg since that's not set until init time */
  99936. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  99937. return true;
  99938. #else
  99939. (void)value;
  99940. return false;
  99941. #endif
  99942. }
  99943. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  99944. {
  99945. FLAC__ASSERT(0 != decoder);
  99946. FLAC__ASSERT(0 != decoder->protected_);
  99947. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99948. return false;
  99949. decoder->protected_->md5_checking = value;
  99950. return true;
  99951. }
  99952. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  99953. {
  99954. FLAC__ASSERT(0 != decoder);
  99955. FLAC__ASSERT(0 != decoder->private_);
  99956. FLAC__ASSERT(0 != decoder->protected_);
  99957. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  99958. /* double protection */
  99959. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  99960. return false;
  99961. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99962. return false;
  99963. decoder->private_->metadata_filter[type] = true;
  99964. if(type == FLAC__METADATA_TYPE_APPLICATION)
  99965. decoder->private_->metadata_filter_ids_count = 0;
  99966. return true;
  99967. }
  99968. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  99969. {
  99970. FLAC__ASSERT(0 != decoder);
  99971. FLAC__ASSERT(0 != decoder->private_);
  99972. FLAC__ASSERT(0 != decoder->protected_);
  99973. FLAC__ASSERT(0 != id);
  99974. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99975. return false;
  99976. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  99977. return true;
  99978. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  99979. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  99980. 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))) {
  99981. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  99982. return false;
  99983. }
  99984. decoder->private_->metadata_filter_ids_capacity *= 2;
  99985. }
  99986. 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));
  99987. decoder->private_->metadata_filter_ids_count++;
  99988. return true;
  99989. }
  99990. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  99991. {
  99992. unsigned i;
  99993. FLAC__ASSERT(0 != decoder);
  99994. FLAC__ASSERT(0 != decoder->private_);
  99995. FLAC__ASSERT(0 != decoder->protected_);
  99996. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  99997. return false;
  99998. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  99999. decoder->private_->metadata_filter[i] = true;
  100000. decoder->private_->metadata_filter_ids_count = 0;
  100001. return true;
  100002. }
  100003. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  100004. {
  100005. FLAC__ASSERT(0 != decoder);
  100006. FLAC__ASSERT(0 != decoder->private_);
  100007. FLAC__ASSERT(0 != decoder->protected_);
  100008. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  100009. /* double protection */
  100010. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  100011. return false;
  100012. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100013. return false;
  100014. decoder->private_->metadata_filter[type] = false;
  100015. if(type == FLAC__METADATA_TYPE_APPLICATION)
  100016. decoder->private_->metadata_filter_ids_count = 0;
  100017. return true;
  100018. }
  100019. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  100020. {
  100021. FLAC__ASSERT(0 != decoder);
  100022. FLAC__ASSERT(0 != decoder->private_);
  100023. FLAC__ASSERT(0 != decoder->protected_);
  100024. FLAC__ASSERT(0 != id);
  100025. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100026. return false;
  100027. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  100028. return true;
  100029. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  100030. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  100031. 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))) {
  100032. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100033. return false;
  100034. }
  100035. decoder->private_->metadata_filter_ids_capacity *= 2;
  100036. }
  100037. 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));
  100038. decoder->private_->metadata_filter_ids_count++;
  100039. return true;
  100040. }
  100041. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  100042. {
  100043. FLAC__ASSERT(0 != decoder);
  100044. FLAC__ASSERT(0 != decoder->private_);
  100045. FLAC__ASSERT(0 != decoder->protected_);
  100046. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  100047. return false;
  100048. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100049. decoder->private_->metadata_filter_ids_count = 0;
  100050. return true;
  100051. }
  100052. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  100053. {
  100054. FLAC__ASSERT(0 != decoder);
  100055. FLAC__ASSERT(0 != decoder->protected_);
  100056. return decoder->protected_->state;
  100057. }
  100058. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  100059. {
  100060. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  100061. }
  100062. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  100063. {
  100064. FLAC__ASSERT(0 != decoder);
  100065. FLAC__ASSERT(0 != decoder->protected_);
  100066. return decoder->protected_->md5_checking;
  100067. }
  100068. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  100069. {
  100070. FLAC__ASSERT(0 != decoder);
  100071. FLAC__ASSERT(0 != decoder->protected_);
  100072. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  100073. }
  100074. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  100075. {
  100076. FLAC__ASSERT(0 != decoder);
  100077. FLAC__ASSERT(0 != decoder->protected_);
  100078. return decoder->protected_->channels;
  100079. }
  100080. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  100081. {
  100082. FLAC__ASSERT(0 != decoder);
  100083. FLAC__ASSERT(0 != decoder->protected_);
  100084. return decoder->protected_->channel_assignment;
  100085. }
  100086. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  100087. {
  100088. FLAC__ASSERT(0 != decoder);
  100089. FLAC__ASSERT(0 != decoder->protected_);
  100090. return decoder->protected_->bits_per_sample;
  100091. }
  100092. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  100093. {
  100094. FLAC__ASSERT(0 != decoder);
  100095. FLAC__ASSERT(0 != decoder->protected_);
  100096. return decoder->protected_->sample_rate;
  100097. }
  100098. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  100099. {
  100100. FLAC__ASSERT(0 != decoder);
  100101. FLAC__ASSERT(0 != decoder->protected_);
  100102. return decoder->protected_->blocksize;
  100103. }
  100104. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  100105. {
  100106. FLAC__ASSERT(0 != decoder);
  100107. FLAC__ASSERT(0 != decoder->private_);
  100108. FLAC__ASSERT(0 != position);
  100109. #if FLAC__HAS_OGG
  100110. if(decoder->private_->is_ogg)
  100111. return false;
  100112. #endif
  100113. if(0 == decoder->private_->tell_callback)
  100114. return false;
  100115. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  100116. return false;
  100117. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  100118. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  100119. return false;
  100120. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  100121. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  100122. return true;
  100123. }
  100124. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  100125. {
  100126. FLAC__ASSERT(0 != decoder);
  100127. FLAC__ASSERT(0 != decoder->private_);
  100128. FLAC__ASSERT(0 != decoder->protected_);
  100129. decoder->private_->samples_decoded = 0;
  100130. decoder->private_->do_md5_checking = false;
  100131. #if FLAC__HAS_OGG
  100132. if(decoder->private_->is_ogg)
  100133. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  100134. #endif
  100135. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  100136. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100137. return false;
  100138. }
  100139. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100140. return true;
  100141. }
  100142. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  100143. {
  100144. FLAC__ASSERT(0 != decoder);
  100145. FLAC__ASSERT(0 != decoder->private_);
  100146. FLAC__ASSERT(0 != decoder->protected_);
  100147. if(!FLAC__stream_decoder_flush(decoder)) {
  100148. /* above call sets the state for us */
  100149. return false;
  100150. }
  100151. #if FLAC__HAS_OGG
  100152. /*@@@ could go in !internal_reset_hack block below */
  100153. if(decoder->private_->is_ogg)
  100154. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  100155. #endif
  100156. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  100157. * (internal_reset_hack) don't try to rewind since we are already at
  100158. * the beginning of the stream and don't want to fail if the input is
  100159. * not seekable.
  100160. */
  100161. if(!decoder->private_->internal_reset_hack) {
  100162. if(decoder->private_->file == stdin)
  100163. return false; /* can't rewind stdin, reset fails */
  100164. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  100165. return false; /* seekable and seek fails, reset fails */
  100166. }
  100167. else
  100168. decoder->private_->internal_reset_hack = false;
  100169. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  100170. decoder->private_->has_stream_info = false;
  100171. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  100172. free(decoder->private_->seek_table.data.seek_table.points);
  100173. decoder->private_->seek_table.data.seek_table.points = 0;
  100174. decoder->private_->has_seek_table = false;
  100175. }
  100176. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  100177. /*
  100178. * This goes in reset() and not flush() because according to the spec, a
  100179. * fixed-blocksize stream must stay that way through the whole stream.
  100180. */
  100181. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  100182. /* We initialize the FLAC__MD5Context even though we may never use it. This
  100183. * is because md5 checking may be turned on to start and then turned off if
  100184. * a seek occurs. So we init the context here and finalize it in
  100185. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  100186. * properly.
  100187. */
  100188. FLAC__MD5Init(&decoder->private_->md5context);
  100189. decoder->private_->first_frame_offset = 0;
  100190. decoder->private_->unparseable_frame_count = 0;
  100191. return true;
  100192. }
  100193. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  100194. {
  100195. FLAC__bool got_a_frame;
  100196. FLAC__ASSERT(0 != decoder);
  100197. FLAC__ASSERT(0 != decoder->protected_);
  100198. while(1) {
  100199. switch(decoder->protected_->state) {
  100200. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100201. if(!find_metadata_(decoder))
  100202. return false; /* above function sets the status for us */
  100203. break;
  100204. case FLAC__STREAM_DECODER_READ_METADATA:
  100205. if(!read_metadata_(decoder))
  100206. return false; /* above function sets the status for us */
  100207. else
  100208. return true;
  100209. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100210. if(!frame_sync_(decoder))
  100211. return true; /* above function sets the status for us */
  100212. break;
  100213. case FLAC__STREAM_DECODER_READ_FRAME:
  100214. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  100215. return false; /* above function sets the status for us */
  100216. if(got_a_frame)
  100217. return true; /* above function sets the status for us */
  100218. break;
  100219. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100220. case FLAC__STREAM_DECODER_ABORTED:
  100221. return true;
  100222. default:
  100223. FLAC__ASSERT(0);
  100224. return false;
  100225. }
  100226. }
  100227. }
  100228. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  100229. {
  100230. FLAC__ASSERT(0 != decoder);
  100231. FLAC__ASSERT(0 != decoder->protected_);
  100232. while(1) {
  100233. switch(decoder->protected_->state) {
  100234. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100235. if(!find_metadata_(decoder))
  100236. return false; /* above function sets the status for us */
  100237. break;
  100238. case FLAC__STREAM_DECODER_READ_METADATA:
  100239. if(!read_metadata_(decoder))
  100240. return false; /* above function sets the status for us */
  100241. break;
  100242. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100243. case FLAC__STREAM_DECODER_READ_FRAME:
  100244. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100245. case FLAC__STREAM_DECODER_ABORTED:
  100246. return true;
  100247. default:
  100248. FLAC__ASSERT(0);
  100249. return false;
  100250. }
  100251. }
  100252. }
  100253. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  100254. {
  100255. FLAC__bool dummy;
  100256. FLAC__ASSERT(0 != decoder);
  100257. FLAC__ASSERT(0 != decoder->protected_);
  100258. while(1) {
  100259. switch(decoder->protected_->state) {
  100260. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100261. if(!find_metadata_(decoder))
  100262. return false; /* above function sets the status for us */
  100263. break;
  100264. case FLAC__STREAM_DECODER_READ_METADATA:
  100265. if(!read_metadata_(decoder))
  100266. return false; /* above function sets the status for us */
  100267. break;
  100268. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100269. if(!frame_sync_(decoder))
  100270. return true; /* above function sets the status for us */
  100271. break;
  100272. case FLAC__STREAM_DECODER_READ_FRAME:
  100273. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  100274. return false; /* above function sets the status for us */
  100275. break;
  100276. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100277. case FLAC__STREAM_DECODER_ABORTED:
  100278. return true;
  100279. default:
  100280. FLAC__ASSERT(0);
  100281. return false;
  100282. }
  100283. }
  100284. }
  100285. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  100286. {
  100287. FLAC__bool got_a_frame;
  100288. FLAC__ASSERT(0 != decoder);
  100289. FLAC__ASSERT(0 != decoder->protected_);
  100290. while(1) {
  100291. switch(decoder->protected_->state) {
  100292. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  100293. case FLAC__STREAM_DECODER_READ_METADATA:
  100294. return false; /* above function sets the status for us */
  100295. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  100296. if(!frame_sync_(decoder))
  100297. return true; /* above function sets the status for us */
  100298. break;
  100299. case FLAC__STREAM_DECODER_READ_FRAME:
  100300. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  100301. return false; /* above function sets the status for us */
  100302. if(got_a_frame)
  100303. return true; /* above function sets the status for us */
  100304. break;
  100305. case FLAC__STREAM_DECODER_END_OF_STREAM:
  100306. case FLAC__STREAM_DECODER_ABORTED:
  100307. return true;
  100308. default:
  100309. FLAC__ASSERT(0);
  100310. return false;
  100311. }
  100312. }
  100313. }
  100314. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  100315. {
  100316. FLAC__uint64 length;
  100317. FLAC__ASSERT(0 != decoder);
  100318. if(
  100319. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  100320. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  100321. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  100322. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  100323. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  100324. )
  100325. return false;
  100326. if(0 == decoder->private_->seek_callback)
  100327. return false;
  100328. FLAC__ASSERT(decoder->private_->seek_callback);
  100329. FLAC__ASSERT(decoder->private_->tell_callback);
  100330. FLAC__ASSERT(decoder->private_->length_callback);
  100331. FLAC__ASSERT(decoder->private_->eof_callback);
  100332. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  100333. return false;
  100334. decoder->private_->is_seeking = true;
  100335. /* turn off md5 checking if a seek is attempted */
  100336. decoder->private_->do_md5_checking = false;
  100337. /* 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) */
  100338. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  100339. decoder->private_->is_seeking = false;
  100340. return false;
  100341. }
  100342. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  100343. if(
  100344. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  100345. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  100346. ) {
  100347. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  100348. /* above call sets the state for us */
  100349. decoder->private_->is_seeking = false;
  100350. return false;
  100351. }
  100352. /* check this again in case we didn't know total_samples the first time */
  100353. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100354. decoder->private_->is_seeking = false;
  100355. return false;
  100356. }
  100357. }
  100358. {
  100359. const FLAC__bool ok =
  100360. #if FLAC__HAS_OGG
  100361. decoder->private_->is_ogg?
  100362. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  100363. #endif
  100364. seek_to_absolute_sample_(decoder, length, sample)
  100365. ;
  100366. decoder->private_->is_seeking = false;
  100367. return ok;
  100368. }
  100369. }
  100370. /***********************************************************************
  100371. *
  100372. * Protected class methods
  100373. *
  100374. ***********************************************************************/
  100375. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  100376. {
  100377. FLAC__ASSERT(0 != decoder);
  100378. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100379. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  100380. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  100381. }
  100382. /***********************************************************************
  100383. *
  100384. * Private class methods
  100385. *
  100386. ***********************************************************************/
  100387. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  100388. {
  100389. #if FLAC__HAS_OGG
  100390. decoder->private_->is_ogg = false;
  100391. #endif
  100392. decoder->private_->read_callback = 0;
  100393. decoder->private_->seek_callback = 0;
  100394. decoder->private_->tell_callback = 0;
  100395. decoder->private_->length_callback = 0;
  100396. decoder->private_->eof_callback = 0;
  100397. decoder->private_->write_callback = 0;
  100398. decoder->private_->metadata_callback = 0;
  100399. decoder->private_->error_callback = 0;
  100400. decoder->private_->client_data = 0;
  100401. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  100402. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  100403. decoder->private_->metadata_filter_ids_count = 0;
  100404. decoder->protected_->md5_checking = false;
  100405. #if FLAC__HAS_OGG
  100406. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  100407. #endif
  100408. }
  100409. /*
  100410. * This will forcibly set stdin to binary mode (for OSes that require it)
  100411. */
  100412. FILE *get_binary_stdin_(void)
  100413. {
  100414. /* if something breaks here it is probably due to the presence or
  100415. * absence of an underscore before the identifiers 'setmode',
  100416. * 'fileno', and/or 'O_BINARY'; check your system header files.
  100417. */
  100418. #if defined _MSC_VER || defined __MINGW32__
  100419. _setmode(_fileno(stdin), _O_BINARY);
  100420. #elif defined __CYGWIN__
  100421. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  100422. setmode(_fileno(stdin), _O_BINARY);
  100423. #elif defined __EMX__
  100424. setmode(fileno(stdin), O_BINARY);
  100425. #endif
  100426. return stdin;
  100427. }
  100428. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  100429. {
  100430. unsigned i;
  100431. FLAC__int32 *tmp;
  100432. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  100433. return true;
  100434. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  100435. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  100436. if(0 != decoder->private_->output[i]) {
  100437. free(decoder->private_->output[i]-4);
  100438. decoder->private_->output[i] = 0;
  100439. }
  100440. if(0 != decoder->private_->residual_unaligned[i]) {
  100441. free(decoder->private_->residual_unaligned[i]);
  100442. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  100443. }
  100444. }
  100445. for(i = 0; i < channels; i++) {
  100446. /* WATCHOUT:
  100447. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  100448. * output arrays have a buffer of up to 3 zeroes in front
  100449. * (at negative indices) for alignment purposes; we use 4
  100450. * to keep the data well-aligned.
  100451. */
  100452. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  100453. if(tmp == 0) {
  100454. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100455. return false;
  100456. }
  100457. memset(tmp, 0, sizeof(FLAC__int32)*4);
  100458. decoder->private_->output[i] = tmp + 4;
  100459. /* WATCHOUT:
  100460. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  100461. */
  100462. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  100463. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100464. return false;
  100465. }
  100466. }
  100467. decoder->private_->output_capacity = size;
  100468. decoder->private_->output_channels = channels;
  100469. return true;
  100470. }
  100471. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  100472. {
  100473. size_t i;
  100474. FLAC__ASSERT(0 != decoder);
  100475. FLAC__ASSERT(0 != decoder->private_);
  100476. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  100477. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  100478. return true;
  100479. return false;
  100480. }
  100481. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  100482. {
  100483. FLAC__uint32 x;
  100484. unsigned i, id_;
  100485. FLAC__bool first = true;
  100486. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100487. for(i = id_ = 0; i < 4; ) {
  100488. if(decoder->private_->cached) {
  100489. x = (FLAC__uint32)decoder->private_->lookahead;
  100490. decoder->private_->cached = false;
  100491. }
  100492. else {
  100493. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100494. return false; /* read_callback_ sets the state for us */
  100495. }
  100496. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  100497. first = true;
  100498. i++;
  100499. id_ = 0;
  100500. continue;
  100501. }
  100502. if(x == ID3V2_TAG_[id_]) {
  100503. id_++;
  100504. i = 0;
  100505. if(id_ == 3) {
  100506. if(!skip_id3v2_tag_(decoder))
  100507. return false; /* skip_id3v2_tag_ sets the state for us */
  100508. }
  100509. continue;
  100510. }
  100511. id_ = 0;
  100512. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100513. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  100514. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100515. return false; /* read_callback_ sets the state for us */
  100516. /* 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 */
  100517. /* else we have to check if the second byte is the end of a sync code */
  100518. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  100519. decoder->private_->lookahead = (FLAC__byte)x;
  100520. decoder->private_->cached = true;
  100521. }
  100522. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  100523. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  100524. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  100525. return true;
  100526. }
  100527. }
  100528. i = 0;
  100529. if(first) {
  100530. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  100531. first = false;
  100532. }
  100533. }
  100534. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  100535. return true;
  100536. }
  100537. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  100538. {
  100539. FLAC__bool is_last;
  100540. FLAC__uint32 i, x, type, length;
  100541. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100542. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  100543. return false; /* read_callback_ sets the state for us */
  100544. is_last = x? true : false;
  100545. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  100546. return false; /* read_callback_ sets the state for us */
  100547. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  100548. return false; /* read_callback_ sets the state for us */
  100549. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  100550. if(!read_metadata_streaminfo_(decoder, is_last, length))
  100551. return false;
  100552. decoder->private_->has_stream_info = true;
  100553. 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))
  100554. decoder->private_->do_md5_checking = false;
  100555. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  100556. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  100557. }
  100558. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  100559. if(!read_metadata_seektable_(decoder, is_last, length))
  100560. return false;
  100561. decoder->private_->has_seek_table = true;
  100562. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  100563. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  100564. }
  100565. else {
  100566. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  100567. unsigned real_length = length;
  100568. FLAC__StreamMetadata block;
  100569. block.is_last = is_last;
  100570. block.type = (FLAC__MetadataType)type;
  100571. block.length = length;
  100572. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  100573. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  100574. return false; /* read_callback_ sets the state for us */
  100575. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  100576. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  100577. return false;
  100578. }
  100579. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  100580. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  100581. skip_it = !skip_it;
  100582. }
  100583. if(skip_it) {
  100584. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100585. return false; /* read_callback_ sets the state for us */
  100586. }
  100587. else {
  100588. switch(type) {
  100589. case FLAC__METADATA_TYPE_PADDING:
  100590. /* skip the padding bytes */
  100591. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  100592. return false; /* read_callback_ sets the state for us */
  100593. break;
  100594. case FLAC__METADATA_TYPE_APPLICATION:
  100595. /* remember, we read the ID already */
  100596. if(real_length > 0) {
  100597. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  100598. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100599. return false;
  100600. }
  100601. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  100602. return false; /* read_callback_ sets the state for us */
  100603. }
  100604. else
  100605. block.data.application.data = 0;
  100606. break;
  100607. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100608. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  100609. return false;
  100610. break;
  100611. case FLAC__METADATA_TYPE_CUESHEET:
  100612. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  100613. return false;
  100614. break;
  100615. case FLAC__METADATA_TYPE_PICTURE:
  100616. if(!read_metadata_picture_(decoder, &block.data.picture))
  100617. return false;
  100618. break;
  100619. case FLAC__METADATA_TYPE_STREAMINFO:
  100620. case FLAC__METADATA_TYPE_SEEKTABLE:
  100621. FLAC__ASSERT(0);
  100622. break;
  100623. default:
  100624. if(real_length > 0) {
  100625. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  100626. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100627. return false;
  100628. }
  100629. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  100630. return false; /* read_callback_ sets the state for us */
  100631. }
  100632. else
  100633. block.data.unknown.data = 0;
  100634. break;
  100635. }
  100636. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  100637. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  100638. /* now we have to free any malloc()ed data in the block */
  100639. switch(type) {
  100640. case FLAC__METADATA_TYPE_PADDING:
  100641. break;
  100642. case FLAC__METADATA_TYPE_APPLICATION:
  100643. if(0 != block.data.application.data)
  100644. free(block.data.application.data);
  100645. break;
  100646. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  100647. if(0 != block.data.vorbis_comment.vendor_string.entry)
  100648. free(block.data.vorbis_comment.vendor_string.entry);
  100649. if(block.data.vorbis_comment.num_comments > 0)
  100650. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  100651. if(0 != block.data.vorbis_comment.comments[i].entry)
  100652. free(block.data.vorbis_comment.comments[i].entry);
  100653. if(0 != block.data.vorbis_comment.comments)
  100654. free(block.data.vorbis_comment.comments);
  100655. break;
  100656. case FLAC__METADATA_TYPE_CUESHEET:
  100657. if(block.data.cue_sheet.num_tracks > 0)
  100658. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  100659. if(0 != block.data.cue_sheet.tracks[i].indices)
  100660. free(block.data.cue_sheet.tracks[i].indices);
  100661. if(0 != block.data.cue_sheet.tracks)
  100662. free(block.data.cue_sheet.tracks);
  100663. break;
  100664. case FLAC__METADATA_TYPE_PICTURE:
  100665. if(0 != block.data.picture.mime_type)
  100666. free(block.data.picture.mime_type);
  100667. if(0 != block.data.picture.description)
  100668. free(block.data.picture.description);
  100669. if(0 != block.data.picture.data)
  100670. free(block.data.picture.data);
  100671. break;
  100672. case FLAC__METADATA_TYPE_STREAMINFO:
  100673. case FLAC__METADATA_TYPE_SEEKTABLE:
  100674. FLAC__ASSERT(0);
  100675. default:
  100676. if(0 != block.data.unknown.data)
  100677. free(block.data.unknown.data);
  100678. break;
  100679. }
  100680. }
  100681. }
  100682. if(is_last) {
  100683. /* if this fails, it's OK, it's just a hint for the seek routine */
  100684. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  100685. decoder->private_->first_frame_offset = 0;
  100686. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  100687. }
  100688. return true;
  100689. }
  100690. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100691. {
  100692. FLAC__uint32 x;
  100693. unsigned bits, used_bits = 0;
  100694. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100695. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  100696. decoder->private_->stream_info.is_last = is_last;
  100697. decoder->private_->stream_info.length = length;
  100698. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  100699. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  100700. return false; /* read_callback_ sets the state for us */
  100701. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  100702. used_bits += bits;
  100703. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  100704. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  100705. return false; /* read_callback_ sets the state for us */
  100706. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  100707. used_bits += bits;
  100708. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  100709. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  100710. return false; /* read_callback_ sets the state for us */
  100711. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  100712. used_bits += bits;
  100713. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  100714. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  100715. return false; /* read_callback_ sets the state for us */
  100716. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  100717. used_bits += bits;
  100718. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  100719. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  100720. return false; /* read_callback_ sets the state for us */
  100721. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  100722. used_bits += bits;
  100723. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  100724. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  100725. return false; /* read_callback_ sets the state for us */
  100726. decoder->private_->stream_info.data.stream_info.channels = x+1;
  100727. used_bits += bits;
  100728. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  100729. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  100730. return false; /* read_callback_ sets the state for us */
  100731. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  100732. used_bits += bits;
  100733. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  100734. 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))
  100735. return false; /* read_callback_ sets the state for us */
  100736. used_bits += bits;
  100737. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  100738. return false; /* read_callback_ sets the state for us */
  100739. used_bits += 16*8;
  100740. /* skip the rest of the block */
  100741. FLAC__ASSERT(used_bits % 8 == 0);
  100742. length -= (used_bits / 8);
  100743. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100744. return false; /* read_callback_ sets the state for us */
  100745. return true;
  100746. }
  100747. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  100748. {
  100749. FLAC__uint32 i, x;
  100750. FLAC__uint64 xx;
  100751. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100752. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  100753. decoder->private_->seek_table.is_last = is_last;
  100754. decoder->private_->seek_table.length = length;
  100755. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  100756. /* use realloc since we may pass through here several times (e.g. after seeking) */
  100757. 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)))) {
  100758. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100759. return false;
  100760. }
  100761. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  100762. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  100763. return false; /* read_callback_ sets the state for us */
  100764. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  100765. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  100766. return false; /* read_callback_ sets the state for us */
  100767. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  100768. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  100769. return false; /* read_callback_ sets the state for us */
  100770. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  100771. }
  100772. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  100773. /* if there is a partial point left, skip over it */
  100774. if(length > 0) {
  100775. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  100776. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  100777. return false; /* read_callback_ sets the state for us */
  100778. }
  100779. return true;
  100780. }
  100781. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  100782. {
  100783. FLAC__uint32 i;
  100784. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100785. /* read vendor string */
  100786. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100787. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  100788. return false; /* read_callback_ sets the state for us */
  100789. if(obj->vendor_string.length > 0) {
  100790. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  100791. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100792. return false;
  100793. }
  100794. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  100795. return false; /* read_callback_ sets the state for us */
  100796. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  100797. }
  100798. else
  100799. obj->vendor_string.entry = 0;
  100800. /* read num comments */
  100801. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  100802. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  100803. return false; /* read_callback_ sets the state for us */
  100804. /* read comments */
  100805. if(obj->num_comments > 0) {
  100806. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  100807. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100808. return false;
  100809. }
  100810. for(i = 0; i < obj->num_comments; i++) {
  100811. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  100812. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  100813. return false; /* read_callback_ sets the state for us */
  100814. if(obj->comments[i].length > 0) {
  100815. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  100816. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100817. return false;
  100818. }
  100819. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  100820. return false; /* read_callback_ sets the state for us */
  100821. obj->comments[i].entry[obj->comments[i].length] = '\0';
  100822. }
  100823. else
  100824. obj->comments[i].entry = 0;
  100825. }
  100826. }
  100827. else {
  100828. obj->comments = 0;
  100829. }
  100830. return true;
  100831. }
  100832. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  100833. {
  100834. FLAC__uint32 i, j, x;
  100835. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100836. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  100837. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  100838. 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))
  100839. return false; /* read_callback_ sets the state for us */
  100840. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  100841. return false; /* read_callback_ sets the state for us */
  100842. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  100843. return false; /* read_callback_ sets the state for us */
  100844. obj->is_cd = x? true : false;
  100845. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  100846. return false; /* read_callback_ sets the state for us */
  100847. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  100848. return false; /* read_callback_ sets the state for us */
  100849. obj->num_tracks = x;
  100850. if(obj->num_tracks > 0) {
  100851. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  100852. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100853. return false;
  100854. }
  100855. for(i = 0; i < obj->num_tracks; i++) {
  100856. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  100857. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  100858. return false; /* read_callback_ sets the state for us */
  100859. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  100860. return false; /* read_callback_ sets the state for us */
  100861. track->number = (FLAC__byte)x;
  100862. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  100863. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  100864. return false; /* read_callback_ sets the state for us */
  100865. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  100866. return false; /* read_callback_ sets the state for us */
  100867. track->type = x;
  100868. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  100869. return false; /* read_callback_ sets the state for us */
  100870. track->pre_emphasis = x;
  100871. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  100872. return false; /* read_callback_ sets the state for us */
  100873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  100874. return false; /* read_callback_ sets the state for us */
  100875. track->num_indices = (FLAC__byte)x;
  100876. if(track->num_indices > 0) {
  100877. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  100878. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100879. return false;
  100880. }
  100881. for(j = 0; j < track->num_indices; j++) {
  100882. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  100883. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  100884. return false; /* read_callback_ sets the state for us */
  100885. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  100886. return false; /* read_callback_ sets the state for us */
  100887. index->number = (FLAC__byte)x;
  100888. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  100889. return false; /* read_callback_ sets the state for us */
  100890. }
  100891. }
  100892. }
  100893. }
  100894. return true;
  100895. }
  100896. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  100897. {
  100898. FLAC__uint32 x;
  100899. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  100900. /* read type */
  100901. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  100902. return false; /* read_callback_ sets the state for us */
  100903. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  100904. /* read MIME type */
  100905. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  100906. return false; /* read_callback_ sets the state for us */
  100907. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  100908. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100909. return false;
  100910. }
  100911. if(x > 0) {
  100912. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  100913. return false; /* read_callback_ sets the state for us */
  100914. }
  100915. obj->mime_type[x] = '\0';
  100916. /* read description */
  100917. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  100918. return false; /* read_callback_ sets the state for us */
  100919. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  100920. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100921. return false;
  100922. }
  100923. if(x > 0) {
  100924. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  100925. return false; /* read_callback_ sets the state for us */
  100926. }
  100927. obj->description[x] = '\0';
  100928. /* read width */
  100929. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  100930. return false; /* read_callback_ sets the state for us */
  100931. /* read height */
  100932. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  100933. return false; /* read_callback_ sets the state for us */
  100934. /* read depth */
  100935. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  100936. return false; /* read_callback_ sets the state for us */
  100937. /* read colors */
  100938. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  100939. return false; /* read_callback_ sets the state for us */
  100940. /* read data */
  100941. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  100942. return false; /* read_callback_ sets the state for us */
  100943. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  100944. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  100945. return false;
  100946. }
  100947. if(obj->data_length > 0) {
  100948. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  100949. return false; /* read_callback_ sets the state for us */
  100950. }
  100951. return true;
  100952. }
  100953. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  100954. {
  100955. FLAC__uint32 x;
  100956. unsigned i, skip;
  100957. /* skip the version and flags bytes */
  100958. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  100959. return false; /* read_callback_ sets the state for us */
  100960. /* get the size (in bytes) to skip */
  100961. skip = 0;
  100962. for(i = 0; i < 4; i++) {
  100963. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100964. return false; /* read_callback_ sets the state for us */
  100965. skip <<= 7;
  100966. skip |= (x & 0x7f);
  100967. }
  100968. /* skip the rest of the tag */
  100969. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  100970. return false; /* read_callback_ sets the state for us */
  100971. return true;
  100972. }
  100973. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  100974. {
  100975. FLAC__uint32 x;
  100976. FLAC__bool first = true;
  100977. /* If we know the total number of samples in the stream, stop if we've read that many. */
  100978. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  100979. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  100980. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  100981. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  100982. return true;
  100983. }
  100984. }
  100985. /* make sure we're byte aligned */
  100986. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  100987. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  100988. return false; /* read_callback_ sets the state for us */
  100989. }
  100990. while(1) {
  100991. if(decoder->private_->cached) {
  100992. x = (FLAC__uint32)decoder->private_->lookahead;
  100993. decoder->private_->cached = false;
  100994. }
  100995. else {
  100996. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  100997. return false; /* read_callback_ sets the state for us */
  100998. }
  100999. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101000. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  101001. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101002. return false; /* read_callback_ sets the state for us */
  101003. /* 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 */
  101004. /* else we have to check if the second byte is the end of a sync code */
  101005. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101006. decoder->private_->lookahead = (FLAC__byte)x;
  101007. decoder->private_->cached = true;
  101008. }
  101009. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  101010. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  101011. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  101012. return true;
  101013. }
  101014. }
  101015. if(first) {
  101016. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101017. first = false;
  101018. }
  101019. }
  101020. return true;
  101021. }
  101022. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  101023. {
  101024. unsigned channel;
  101025. unsigned i;
  101026. FLAC__int32 mid, side;
  101027. unsigned frame_crc; /* the one we calculate from the input stream */
  101028. FLAC__uint32 x;
  101029. *got_a_frame = false;
  101030. /* init the CRC */
  101031. frame_crc = 0;
  101032. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  101033. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  101034. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  101035. if(!read_frame_header_(decoder))
  101036. return false;
  101037. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  101038. return true;
  101039. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  101040. return false;
  101041. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101042. /*
  101043. * first figure the correct bits-per-sample of the subframe
  101044. */
  101045. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  101046. switch(decoder->private_->frame.header.channel_assignment) {
  101047. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101048. /* no adjustment needed */
  101049. break;
  101050. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101051. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101052. if(channel == 1)
  101053. bps++;
  101054. break;
  101055. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101056. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101057. if(channel == 0)
  101058. bps++;
  101059. break;
  101060. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101061. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101062. if(channel == 1)
  101063. bps++;
  101064. break;
  101065. default:
  101066. FLAC__ASSERT(0);
  101067. }
  101068. /*
  101069. * now read it
  101070. */
  101071. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  101072. return false;
  101073. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101074. return true;
  101075. }
  101076. if(!read_zero_padding_(decoder))
  101077. return false;
  101078. 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) */
  101079. return true;
  101080. /*
  101081. * Read the frame CRC-16 from the footer and check
  101082. */
  101083. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  101084. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  101085. return false; /* read_callback_ sets the state for us */
  101086. if(frame_crc == x) {
  101087. if(do_full_decode) {
  101088. /* Undo any special channel coding */
  101089. switch(decoder->private_->frame.header.channel_assignment) {
  101090. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101091. /* do nothing */
  101092. break;
  101093. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101094. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101095. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101096. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  101097. break;
  101098. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101099. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101100. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101101. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  101102. break;
  101103. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101104. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  101105. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101106. #if 1
  101107. mid = decoder->private_->output[0][i];
  101108. side = decoder->private_->output[1][i];
  101109. mid <<= 1;
  101110. mid |= (side & 1); /* i.e. if 'side' is odd... */
  101111. decoder->private_->output[0][i] = (mid + side) >> 1;
  101112. decoder->private_->output[1][i] = (mid - side) >> 1;
  101113. #else
  101114. /* OPT: without 'side' temp variable */
  101115. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  101116. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  101117. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  101118. #endif
  101119. }
  101120. break;
  101121. default:
  101122. FLAC__ASSERT(0);
  101123. break;
  101124. }
  101125. }
  101126. }
  101127. else {
  101128. /* Bad frame, emit error and zero the output signal */
  101129. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  101130. if(do_full_decode) {
  101131. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  101132. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101133. }
  101134. }
  101135. }
  101136. *got_a_frame = true;
  101137. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  101138. if(decoder->private_->next_fixed_block_size)
  101139. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  101140. /* put the latest values into the public section of the decoder instance */
  101141. decoder->protected_->channels = decoder->private_->frame.header.channels;
  101142. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  101143. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  101144. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  101145. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  101146. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101147. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  101148. /* write it */
  101149. if(do_full_decode) {
  101150. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  101151. return false;
  101152. }
  101153. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101154. return true;
  101155. }
  101156. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  101157. {
  101158. FLAC__uint32 x;
  101159. FLAC__uint64 xx;
  101160. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  101161. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  101162. unsigned raw_header_len;
  101163. FLAC__bool is_unparseable = false;
  101164. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  101165. /* init the raw header with the saved bits from synchronization */
  101166. raw_header[0] = decoder->private_->header_warmup[0];
  101167. raw_header[1] = decoder->private_->header_warmup[1];
  101168. raw_header_len = 2;
  101169. /* check to make sure that reserved bit is 0 */
  101170. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  101171. is_unparseable = true;
  101172. /*
  101173. * Note that along the way as we read the header, we look for a sync
  101174. * code inside. If we find one it would indicate that our original
  101175. * sync was bad since there cannot be a sync code in a valid header.
  101176. *
  101177. * Three kinds of things can go wrong when reading the frame header:
  101178. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  101179. * If we don't find a sync code, it can end up looking like we read
  101180. * a valid but unparseable header, until getting to the frame header
  101181. * CRC. Even then we could get a false positive on the CRC.
  101182. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  101183. * future encoder).
  101184. * 3) We may be on a damaged frame which appears valid but unparseable.
  101185. *
  101186. * For all these reasons, we try and read a complete frame header as
  101187. * long as it seems valid, even if unparseable, up until the frame
  101188. * header CRC.
  101189. */
  101190. /*
  101191. * read in the raw header as bytes so we can CRC it, and parse it on the way
  101192. */
  101193. for(i = 0; i < 2; i++) {
  101194. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101195. return false; /* read_callback_ sets the state for us */
  101196. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  101197. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  101198. decoder->private_->lookahead = (FLAC__byte)x;
  101199. decoder->private_->cached = true;
  101200. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101201. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101202. return true;
  101203. }
  101204. raw_header[raw_header_len++] = (FLAC__byte)x;
  101205. }
  101206. switch(x = raw_header[2] >> 4) {
  101207. case 0:
  101208. is_unparseable = true;
  101209. break;
  101210. case 1:
  101211. decoder->private_->frame.header.blocksize = 192;
  101212. break;
  101213. case 2:
  101214. case 3:
  101215. case 4:
  101216. case 5:
  101217. decoder->private_->frame.header.blocksize = 576 << (x-2);
  101218. break;
  101219. case 6:
  101220. case 7:
  101221. blocksize_hint = x;
  101222. break;
  101223. case 8:
  101224. case 9:
  101225. case 10:
  101226. case 11:
  101227. case 12:
  101228. case 13:
  101229. case 14:
  101230. case 15:
  101231. decoder->private_->frame.header.blocksize = 256 << (x-8);
  101232. break;
  101233. default:
  101234. FLAC__ASSERT(0);
  101235. break;
  101236. }
  101237. switch(x = raw_header[2] & 0x0f) {
  101238. case 0:
  101239. if(decoder->private_->has_stream_info)
  101240. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  101241. else
  101242. is_unparseable = true;
  101243. break;
  101244. case 1:
  101245. decoder->private_->frame.header.sample_rate = 88200;
  101246. break;
  101247. case 2:
  101248. decoder->private_->frame.header.sample_rate = 176400;
  101249. break;
  101250. case 3:
  101251. decoder->private_->frame.header.sample_rate = 192000;
  101252. break;
  101253. case 4:
  101254. decoder->private_->frame.header.sample_rate = 8000;
  101255. break;
  101256. case 5:
  101257. decoder->private_->frame.header.sample_rate = 16000;
  101258. break;
  101259. case 6:
  101260. decoder->private_->frame.header.sample_rate = 22050;
  101261. break;
  101262. case 7:
  101263. decoder->private_->frame.header.sample_rate = 24000;
  101264. break;
  101265. case 8:
  101266. decoder->private_->frame.header.sample_rate = 32000;
  101267. break;
  101268. case 9:
  101269. decoder->private_->frame.header.sample_rate = 44100;
  101270. break;
  101271. case 10:
  101272. decoder->private_->frame.header.sample_rate = 48000;
  101273. break;
  101274. case 11:
  101275. decoder->private_->frame.header.sample_rate = 96000;
  101276. break;
  101277. case 12:
  101278. case 13:
  101279. case 14:
  101280. sample_rate_hint = x;
  101281. break;
  101282. case 15:
  101283. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101284. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101285. return true;
  101286. default:
  101287. FLAC__ASSERT(0);
  101288. }
  101289. x = (unsigned)(raw_header[3] >> 4);
  101290. if(x & 8) {
  101291. decoder->private_->frame.header.channels = 2;
  101292. switch(x & 7) {
  101293. case 0:
  101294. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  101295. break;
  101296. case 1:
  101297. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  101298. break;
  101299. case 2:
  101300. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  101301. break;
  101302. default:
  101303. is_unparseable = true;
  101304. break;
  101305. }
  101306. }
  101307. else {
  101308. decoder->private_->frame.header.channels = (unsigned)x + 1;
  101309. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101310. }
  101311. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  101312. case 0:
  101313. if(decoder->private_->has_stream_info)
  101314. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101315. else
  101316. is_unparseable = true;
  101317. break;
  101318. case 1:
  101319. decoder->private_->frame.header.bits_per_sample = 8;
  101320. break;
  101321. case 2:
  101322. decoder->private_->frame.header.bits_per_sample = 12;
  101323. break;
  101324. case 4:
  101325. decoder->private_->frame.header.bits_per_sample = 16;
  101326. break;
  101327. case 5:
  101328. decoder->private_->frame.header.bits_per_sample = 20;
  101329. break;
  101330. case 6:
  101331. decoder->private_->frame.header.bits_per_sample = 24;
  101332. break;
  101333. case 3:
  101334. case 7:
  101335. is_unparseable = true;
  101336. break;
  101337. default:
  101338. FLAC__ASSERT(0);
  101339. break;
  101340. }
  101341. /* check to make sure that reserved bit is 0 */
  101342. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  101343. is_unparseable = true;
  101344. /* read the frame's starting sample number (or frame number as the case may be) */
  101345. if(
  101346. raw_header[1] & 0x01 ||
  101347. /*@@@ 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 */
  101348. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  101349. ) { /* variable blocksize */
  101350. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  101351. return false; /* read_callback_ sets the state for us */
  101352. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  101353. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101354. decoder->private_->cached = true;
  101355. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101356. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101357. return true;
  101358. }
  101359. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101360. decoder->private_->frame.header.number.sample_number = xx;
  101361. }
  101362. else { /* fixed blocksize */
  101363. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  101364. return false; /* read_callback_ sets the state for us */
  101365. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  101366. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  101367. decoder->private_->cached = true;
  101368. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101369. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101370. return true;
  101371. }
  101372. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101373. decoder->private_->frame.header.number.frame_number = x;
  101374. }
  101375. if(blocksize_hint) {
  101376. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101377. return false; /* read_callback_ sets the state for us */
  101378. raw_header[raw_header_len++] = (FLAC__byte)x;
  101379. if(blocksize_hint == 7) {
  101380. FLAC__uint32 _x;
  101381. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101382. return false; /* read_callback_ sets the state for us */
  101383. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101384. x = (x << 8) | _x;
  101385. }
  101386. decoder->private_->frame.header.blocksize = x+1;
  101387. }
  101388. if(sample_rate_hint) {
  101389. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101390. return false; /* read_callback_ sets the state for us */
  101391. raw_header[raw_header_len++] = (FLAC__byte)x;
  101392. if(sample_rate_hint != 12) {
  101393. FLAC__uint32 _x;
  101394. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  101395. return false; /* read_callback_ sets the state for us */
  101396. raw_header[raw_header_len++] = (FLAC__byte)_x;
  101397. x = (x << 8) | _x;
  101398. }
  101399. if(sample_rate_hint == 12)
  101400. decoder->private_->frame.header.sample_rate = x*1000;
  101401. else if(sample_rate_hint == 13)
  101402. decoder->private_->frame.header.sample_rate = x;
  101403. else
  101404. decoder->private_->frame.header.sample_rate = x*10;
  101405. }
  101406. /* read the CRC-8 byte */
  101407. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  101408. return false; /* read_callback_ sets the state for us */
  101409. crc8 = (FLAC__byte)x;
  101410. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  101411. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  101412. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101413. return true;
  101414. }
  101415. /* calculate the sample number from the frame number if needed */
  101416. decoder->private_->next_fixed_block_size = 0;
  101417. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  101418. x = decoder->private_->frame.header.number.frame_number;
  101419. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  101420. if(decoder->private_->fixed_block_size)
  101421. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  101422. else if(decoder->private_->has_stream_info) {
  101423. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  101424. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  101425. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101426. }
  101427. else
  101428. is_unparseable = true;
  101429. }
  101430. else if(x == 0) {
  101431. decoder->private_->frame.header.number.sample_number = 0;
  101432. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  101433. }
  101434. else {
  101435. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  101436. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  101437. }
  101438. }
  101439. if(is_unparseable) {
  101440. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101441. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101442. return true;
  101443. }
  101444. return true;
  101445. }
  101446. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101447. {
  101448. FLAC__uint32 x;
  101449. FLAC__bool wasted_bits;
  101450. unsigned i;
  101451. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  101452. return false; /* read_callback_ sets the state for us */
  101453. wasted_bits = (x & 1);
  101454. x &= 0xfe;
  101455. if(wasted_bits) {
  101456. unsigned u;
  101457. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  101458. return false; /* read_callback_ sets the state for us */
  101459. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  101460. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  101461. }
  101462. else
  101463. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  101464. /*
  101465. * Lots of magic numbers here
  101466. */
  101467. if(x & 0x80) {
  101468. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101469. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101470. return true;
  101471. }
  101472. else if(x == 0) {
  101473. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  101474. return false;
  101475. }
  101476. else if(x == 2) {
  101477. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  101478. return false;
  101479. }
  101480. else if(x < 16) {
  101481. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101482. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101483. return true;
  101484. }
  101485. else if(x <= 24) {
  101486. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  101487. return false;
  101488. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101489. return true;
  101490. }
  101491. else if(x < 64) {
  101492. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101493. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101494. return true;
  101495. }
  101496. else {
  101497. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  101498. return false;
  101499. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  101500. return true;
  101501. }
  101502. if(wasted_bits && do_full_decode) {
  101503. x = decoder->private_->frame.subframes[channel].wasted_bits;
  101504. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101505. decoder->private_->output[channel][i] <<= x;
  101506. }
  101507. return true;
  101508. }
  101509. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101510. {
  101511. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  101512. FLAC__int32 x;
  101513. unsigned i;
  101514. FLAC__int32 *output = decoder->private_->output[channel];
  101515. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101516. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101517. return false; /* read_callback_ sets the state for us */
  101518. subframe->value = x;
  101519. /* decode the subframe */
  101520. if(do_full_decode) {
  101521. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  101522. output[i] = x;
  101523. }
  101524. return true;
  101525. }
  101526. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101527. {
  101528. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  101529. FLAC__int32 i32;
  101530. FLAC__uint32 u32;
  101531. unsigned u;
  101532. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  101533. subframe->residual = decoder->private_->residual[channel];
  101534. subframe->order = order;
  101535. /* read warm-up samples */
  101536. for(u = 0; u < order; u++) {
  101537. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101538. return false; /* read_callback_ sets the state for us */
  101539. subframe->warmup[u] = i32;
  101540. }
  101541. /* read entropy coding method info */
  101542. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101543. return false; /* read_callback_ sets the state for us */
  101544. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101545. switch(subframe->entropy_coding_method.type) {
  101546. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101547. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101548. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101549. return false; /* read_callback_ sets the state for us */
  101550. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101551. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101552. break;
  101553. default:
  101554. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101555. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101556. return true;
  101557. }
  101558. /* read residual */
  101559. switch(subframe->entropy_coding_method.type) {
  101560. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101561. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101562. 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))
  101563. return false;
  101564. break;
  101565. default:
  101566. FLAC__ASSERT(0);
  101567. }
  101568. /* decode the subframe */
  101569. if(do_full_decode) {
  101570. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101571. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  101572. }
  101573. return true;
  101574. }
  101575. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  101576. {
  101577. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  101578. FLAC__int32 i32;
  101579. FLAC__uint32 u32;
  101580. unsigned u;
  101581. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  101582. subframe->residual = decoder->private_->residual[channel];
  101583. subframe->order = order;
  101584. /* read warm-up samples */
  101585. for(u = 0; u < order; u++) {
  101586. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  101587. return false; /* read_callback_ sets the state for us */
  101588. subframe->warmup[u] = i32;
  101589. }
  101590. /* read qlp coeff precision */
  101591. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  101592. return false; /* read_callback_ sets the state for us */
  101593. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  101594. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101595. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101596. return true;
  101597. }
  101598. subframe->qlp_coeff_precision = u32+1;
  101599. /* read qlp shift */
  101600. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  101601. return false; /* read_callback_ sets the state for us */
  101602. subframe->quantization_level = i32;
  101603. /* read quantized lp coefficiencts */
  101604. for(u = 0; u < order; u++) {
  101605. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  101606. return false; /* read_callback_ sets the state for us */
  101607. subframe->qlp_coeff[u] = i32;
  101608. }
  101609. /* read entropy coding method info */
  101610. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  101611. return false; /* read_callback_ sets the state for us */
  101612. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  101613. switch(subframe->entropy_coding_method.type) {
  101614. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101615. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101616. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  101617. return false; /* read_callback_ sets the state for us */
  101618. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  101619. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  101620. break;
  101621. default:
  101622. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  101623. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101624. return true;
  101625. }
  101626. /* read residual */
  101627. switch(subframe->entropy_coding_method.type) {
  101628. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  101629. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  101630. 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))
  101631. return false;
  101632. break;
  101633. default:
  101634. FLAC__ASSERT(0);
  101635. }
  101636. /* decode the subframe */
  101637. if(do_full_decode) {
  101638. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  101639. /*@@@@@@ technically not pessimistic enough, should be more like
  101640. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  101641. */
  101642. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101643. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  101644. if(order <= 8)
  101645. 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);
  101646. else
  101647. 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);
  101648. }
  101649. else
  101650. 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);
  101651. else
  101652. 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);
  101653. }
  101654. return true;
  101655. }
  101656. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  101657. {
  101658. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  101659. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  101660. unsigned i;
  101661. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  101662. subframe->data = residual;
  101663. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  101664. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  101665. return false; /* read_callback_ sets the state for us */
  101666. residual[i] = x;
  101667. }
  101668. /* decode the subframe */
  101669. if(do_full_decode)
  101670. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  101671. return true;
  101672. }
  101673. 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)
  101674. {
  101675. FLAC__uint32 rice_parameter;
  101676. int i;
  101677. unsigned partition, sample, u;
  101678. const unsigned partitions = 1u << partition_order;
  101679. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  101680. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  101681. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  101682. /* sanity checks */
  101683. if(partition_order == 0) {
  101684. if(decoder->private_->frame.header.blocksize < predictor_order) {
  101685. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101686. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101687. return true;
  101688. }
  101689. }
  101690. else {
  101691. if(partition_samples < predictor_order) {
  101692. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101693. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101694. return true;
  101695. }
  101696. }
  101697. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  101698. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  101699. return false;
  101700. }
  101701. sample = 0;
  101702. for(partition = 0; partition < partitions; partition++) {
  101703. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  101704. return false; /* read_callback_ sets the state for us */
  101705. partitioned_rice_contents->parameters[partition] = rice_parameter;
  101706. if(rice_parameter < pesc) {
  101707. partitioned_rice_contents->raw_bits[partition] = 0;
  101708. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  101709. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  101710. return false; /* read_callback_ sets the state for us */
  101711. sample += u;
  101712. }
  101713. else {
  101714. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  101715. return false; /* read_callback_ sets the state for us */
  101716. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  101717. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  101718. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  101719. return false; /* read_callback_ sets the state for us */
  101720. residual[sample] = i;
  101721. }
  101722. }
  101723. }
  101724. return true;
  101725. }
  101726. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  101727. {
  101728. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  101729. FLAC__uint32 zero = 0;
  101730. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  101731. return false; /* read_callback_ sets the state for us */
  101732. if(zero != 0) {
  101733. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  101734. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  101735. }
  101736. }
  101737. return true;
  101738. }
  101739. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  101740. {
  101741. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  101742. if(
  101743. #if FLAC__HAS_OGG
  101744. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101745. !decoder->private_->is_ogg &&
  101746. #endif
  101747. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101748. ) {
  101749. *bytes = 0;
  101750. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101751. return false;
  101752. }
  101753. else if(*bytes > 0) {
  101754. /* While seeking, it is possible for our seek to land in the
  101755. * middle of audio data that looks exactly like a frame header
  101756. * from a future version of an encoder. When that happens, our
  101757. * error callback will get an
  101758. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  101759. * unparseable_frame_count. But there is a remote possibility
  101760. * that it is properly synced at such a "future-codec frame",
  101761. * so to make sure, we wait to see many "unparseable" errors in
  101762. * a row before bailing out.
  101763. */
  101764. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  101765. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101766. return false;
  101767. }
  101768. else {
  101769. const FLAC__StreamDecoderReadStatus status =
  101770. #if FLAC__HAS_OGG
  101771. decoder->private_->is_ogg?
  101772. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  101773. #endif
  101774. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  101775. ;
  101776. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  101777. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101778. return false;
  101779. }
  101780. else if(*bytes == 0) {
  101781. if(
  101782. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  101783. (
  101784. #if FLAC__HAS_OGG
  101785. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  101786. !decoder->private_->is_ogg &&
  101787. #endif
  101788. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  101789. )
  101790. ) {
  101791. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  101792. return false;
  101793. }
  101794. else
  101795. return true;
  101796. }
  101797. else
  101798. return true;
  101799. }
  101800. }
  101801. else {
  101802. /* abort to avoid a deadlock */
  101803. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  101804. return false;
  101805. }
  101806. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  101807. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  101808. * and at the same time hit the end of the stream (for example, seeking
  101809. * to a point that is after the beginning of the last Ogg page). There
  101810. * is no way to report an Ogg sync loss through the callbacks (see note
  101811. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  101812. * So to keep the decoder from stopping at this point we gate the call
  101813. * to the eof_callback and let the Ogg decoder aspect set the
  101814. * end-of-stream state when it is needed.
  101815. */
  101816. }
  101817. #if FLAC__HAS_OGG
  101818. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  101819. {
  101820. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  101821. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  101822. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101823. /* we don't really have a way to handle lost sync via read
  101824. * callback so we'll let it pass and let the underlying
  101825. * FLAC decoder catch the error
  101826. */
  101827. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  101828. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  101829. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  101830. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  101831. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  101832. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  101833. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  101834. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  101835. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  101836. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101837. default:
  101838. FLAC__ASSERT(0);
  101839. /* double protection */
  101840. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  101841. }
  101842. }
  101843. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  101844. {
  101845. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  101846. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  101847. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  101848. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  101849. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  101850. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  101851. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  101852. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101853. default:
  101854. /* double protection: */
  101855. FLAC__ASSERT(0);
  101856. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  101857. }
  101858. }
  101859. #endif
  101860. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  101861. {
  101862. if(decoder->private_->is_seeking) {
  101863. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  101864. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  101865. FLAC__uint64 target_sample = decoder->private_->target_sample;
  101866. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  101867. #if FLAC__HAS_OGG
  101868. decoder->private_->got_a_frame = true;
  101869. #endif
  101870. decoder->private_->last_frame = *frame; /* save the frame */
  101871. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  101872. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  101873. /* kick out of seek mode */
  101874. decoder->private_->is_seeking = false;
  101875. /* shift out the samples before target_sample */
  101876. if(delta > 0) {
  101877. unsigned channel;
  101878. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  101879. for(channel = 0; channel < frame->header.channels; channel++)
  101880. newbuffer[channel] = buffer[channel] + delta;
  101881. decoder->private_->last_frame.header.blocksize -= delta;
  101882. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  101883. /* write the relevant samples */
  101884. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  101885. }
  101886. else {
  101887. /* write the relevant samples */
  101888. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101889. }
  101890. }
  101891. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  101892. }
  101893. /*
  101894. * If we never got STREAMINFO, turn off MD5 checking to save
  101895. * cycles since we don't have a sum to compare to anyway
  101896. */
  101897. if(!decoder->private_->has_stream_info)
  101898. decoder->private_->do_md5_checking = false;
  101899. if(decoder->private_->do_md5_checking) {
  101900. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  101901. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  101902. }
  101903. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  101904. }
  101905. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  101906. {
  101907. if(!decoder->private_->is_seeking)
  101908. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  101909. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  101910. decoder->private_->unparseable_frame_count++;
  101911. }
  101912. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  101913. {
  101914. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  101915. FLAC__int64 pos = -1;
  101916. int i;
  101917. unsigned approx_bytes_per_frame;
  101918. FLAC__bool first_seek = true;
  101919. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  101920. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  101921. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  101922. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  101923. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  101924. /* take these from the current frame in case they've changed mid-stream */
  101925. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  101926. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  101927. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  101928. /* use values from stream info if we didn't decode a frame */
  101929. if(channels == 0)
  101930. channels = decoder->private_->stream_info.data.stream_info.channels;
  101931. if(bps == 0)
  101932. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  101933. /* we are just guessing here */
  101934. if(max_framesize > 0)
  101935. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  101936. /*
  101937. * Check if it's a known fixed-blocksize stream. Note that though
  101938. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  101939. * never get a STREAMINFO block when decoding so the value of
  101940. * min_blocksize might be zero.
  101941. */
  101942. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  101943. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  101944. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  101945. }
  101946. else
  101947. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  101948. /*
  101949. * First, we set an upper and lower bound on where in the
  101950. * stream we will search. For now we assume the worst case
  101951. * scenario, which is our best guess at the beginning of
  101952. * the first frame and end of the stream.
  101953. */
  101954. lower_bound = first_frame_offset;
  101955. lower_bound_sample = 0;
  101956. upper_bound = stream_length;
  101957. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  101958. /*
  101959. * Now we refine the bounds if we have a seektable with
  101960. * suitable points. Note that according to the spec they
  101961. * must be ordered by ascending sample number.
  101962. *
  101963. * Note: to protect against invalid seek tables we will ignore points
  101964. * that have frame_samples==0 or sample_number>=total_samples
  101965. */
  101966. if(seek_table) {
  101967. FLAC__uint64 new_lower_bound = lower_bound;
  101968. FLAC__uint64 new_upper_bound = upper_bound;
  101969. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  101970. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  101971. /* find the closest seek point <= target_sample, if it exists */
  101972. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  101973. if(
  101974. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101975. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101976. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101977. seek_table->points[i].sample_number <= target_sample
  101978. )
  101979. break;
  101980. }
  101981. if(i >= 0) { /* i.e. we found a suitable seek point... */
  101982. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101983. new_lower_bound_sample = seek_table->points[i].sample_number;
  101984. }
  101985. /* find the closest seek point > target_sample, if it exists */
  101986. for(i = 0; i < (int)seek_table->num_points; i++) {
  101987. if(
  101988. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  101989. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  101990. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  101991. seek_table->points[i].sample_number > target_sample
  101992. )
  101993. break;
  101994. }
  101995. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  101996. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  101997. new_upper_bound_sample = seek_table->points[i].sample_number;
  101998. }
  101999. /* final protection against unsorted seek tables; keep original values if bogus */
  102000. if(new_upper_bound >= new_lower_bound) {
  102001. lower_bound = new_lower_bound;
  102002. upper_bound = new_upper_bound;
  102003. lower_bound_sample = new_lower_bound_sample;
  102004. upper_bound_sample = new_upper_bound_sample;
  102005. }
  102006. }
  102007. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  102008. /* there are 2 insidious ways that the following equality occurs, which
  102009. * we need to fix:
  102010. * 1) total_samples is 0 (unknown) and target_sample is 0
  102011. * 2) total_samples is 0 (unknown) and target_sample happens to be
  102012. * exactly equal to the last seek point in the seek table; this
  102013. * means there is no seek point above it, and upper_bound_samples
  102014. * remains equal to the estimate (of target_samples) we made above
  102015. * in either case it does not hurt to move upper_bound_sample up by 1
  102016. */
  102017. if(upper_bound_sample == lower_bound_sample)
  102018. upper_bound_sample++;
  102019. decoder->private_->target_sample = target_sample;
  102020. while(1) {
  102021. /* check if the bounds are still ok */
  102022. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  102023. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102024. return false;
  102025. }
  102026. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102027. #if defined _MSC_VER || defined __MINGW32__
  102028. /* with VC++ you have to spoon feed it the casting */
  102029. 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;
  102030. #else
  102031. 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;
  102032. #endif
  102033. #else
  102034. /* a little less accurate: */
  102035. if(upper_bound - lower_bound < 0xffffffff)
  102036. 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;
  102037. else /* @@@ WATCHOUT, ~2TB limit */
  102038. 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;
  102039. #endif
  102040. if(pos >= (FLAC__int64)upper_bound)
  102041. pos = (FLAC__int64)upper_bound - 1;
  102042. if(pos < (FLAC__int64)lower_bound)
  102043. pos = (FLAC__int64)lower_bound;
  102044. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102045. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102046. return false;
  102047. }
  102048. if(!FLAC__stream_decoder_flush(decoder)) {
  102049. /* above call sets the state for us */
  102050. return false;
  102051. }
  102052. /* Now we need to get a frame. First we need to reset our
  102053. * unparseable_frame_count; if we get too many unparseable
  102054. * frames in a row, the read callback will return
  102055. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  102056. * FLAC__stream_decoder_process_single() to return false.
  102057. */
  102058. decoder->private_->unparseable_frame_count = 0;
  102059. if(!FLAC__stream_decoder_process_single(decoder)) {
  102060. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102061. return false;
  102062. }
  102063. /* our write callback will change the state when it gets to the target frame */
  102064. /* 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 */
  102065. #if 0
  102066. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  102067. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  102068. break;
  102069. #endif
  102070. if(!decoder->private_->is_seeking)
  102071. break;
  102072. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102073. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102074. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  102075. if (pos == (FLAC__int64)lower_bound) {
  102076. /* can't move back any more than the first frame, something is fatally wrong */
  102077. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102078. return false;
  102079. }
  102080. /* our last move backwards wasn't big enough, try again */
  102081. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  102082. continue;
  102083. }
  102084. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  102085. first_seek = false;
  102086. /* make sure we are not seeking in corrupted stream */
  102087. if (this_frame_sample < lower_bound_sample) {
  102088. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102089. return false;
  102090. }
  102091. /* we need to narrow the search */
  102092. if(target_sample < this_frame_sample) {
  102093. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102094. /*@@@@@@ what will decode position be if at end of stream? */
  102095. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  102096. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102097. return false;
  102098. }
  102099. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  102100. }
  102101. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  102102. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  102103. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  102104. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102105. return false;
  102106. }
  102107. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  102108. }
  102109. }
  102110. return true;
  102111. }
  102112. #if FLAC__HAS_OGG
  102113. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  102114. {
  102115. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  102116. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  102117. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  102118. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  102119. FLAC__bool did_a_seek;
  102120. unsigned iteration = 0;
  102121. /* In the first iterations, we will calculate the target byte position
  102122. * by the distance from the target sample to left_sample and
  102123. * right_sample (let's call it "proportional search"). After that, we
  102124. * will switch to binary search.
  102125. */
  102126. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  102127. /* We will switch to a linear search once our current sample is less
  102128. * than this number of samples ahead of the target sample
  102129. */
  102130. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  102131. /* If the total number of samples is unknown, use a large value, and
  102132. * force binary search immediately.
  102133. */
  102134. if(right_sample == 0) {
  102135. right_sample = (FLAC__uint64)(-1);
  102136. BINARY_SEARCH_AFTER_ITERATION = 0;
  102137. }
  102138. decoder->private_->target_sample = target_sample;
  102139. for( ; ; iteration++) {
  102140. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  102141. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  102142. pos = (right_pos + left_pos) / 2;
  102143. }
  102144. else {
  102145. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102146. #if defined _MSC_VER || defined __MINGW32__
  102147. /* with MSVC you have to spoon feed it the casting */
  102148. 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));
  102149. #else
  102150. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  102151. #endif
  102152. #else
  102153. /* a little less accurate: */
  102154. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  102155. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  102156. else /* @@@ WATCHOUT, ~2TB limit */
  102157. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  102158. #endif
  102159. /* @@@ TODO: might want to limit pos to some distance
  102160. * before EOF, to make sure we land before the last frame,
  102161. * thereby getting a this_frame_sample and so having a better
  102162. * estimate.
  102163. */
  102164. }
  102165. /* physical seek */
  102166. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  102167. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102168. return false;
  102169. }
  102170. if(!FLAC__stream_decoder_flush(decoder)) {
  102171. /* above call sets the state for us */
  102172. return false;
  102173. }
  102174. did_a_seek = true;
  102175. }
  102176. else
  102177. did_a_seek = false;
  102178. decoder->private_->got_a_frame = false;
  102179. if(!FLAC__stream_decoder_process_single(decoder)) {
  102180. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102181. return false;
  102182. }
  102183. if(!decoder->private_->got_a_frame) {
  102184. if(did_a_seek) {
  102185. /* this can happen if we seek to a point after the last frame; we drop
  102186. * to binary search right away in this case to avoid any wasted
  102187. * iterations of proportional search.
  102188. */
  102189. right_pos = pos;
  102190. BINARY_SEARCH_AFTER_ITERATION = 0;
  102191. }
  102192. else {
  102193. /* this can probably only happen if total_samples is unknown and the
  102194. * target_sample is past the end of the stream
  102195. */
  102196. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102197. return false;
  102198. }
  102199. }
  102200. /* our write callback will change the state when it gets to the target frame */
  102201. else if(!decoder->private_->is_seeking) {
  102202. break;
  102203. }
  102204. else {
  102205. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  102206. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102207. if (did_a_seek) {
  102208. if (this_frame_sample <= target_sample) {
  102209. /* The 'equal' case should not happen, since
  102210. * FLAC__stream_decoder_process_single()
  102211. * should recognize that it has hit the
  102212. * target sample and we would exit through
  102213. * the 'break' above.
  102214. */
  102215. FLAC__ASSERT(this_frame_sample != target_sample);
  102216. left_sample = this_frame_sample;
  102217. /* sanity check to avoid infinite loop */
  102218. if (left_pos == pos) {
  102219. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102220. return false;
  102221. }
  102222. left_pos = pos;
  102223. }
  102224. else if(this_frame_sample > target_sample) {
  102225. right_sample = this_frame_sample;
  102226. /* sanity check to avoid infinite loop */
  102227. if (right_pos == pos) {
  102228. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  102229. return false;
  102230. }
  102231. right_pos = pos;
  102232. }
  102233. }
  102234. }
  102235. }
  102236. return true;
  102237. }
  102238. #endif
  102239. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102240. {
  102241. (void)client_data;
  102242. if(*bytes > 0) {
  102243. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  102244. if(ferror(decoder->private_->file))
  102245. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102246. else if(*bytes == 0)
  102247. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  102248. else
  102249. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102250. }
  102251. else
  102252. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  102253. }
  102254. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102255. {
  102256. (void)client_data;
  102257. if(decoder->private_->file == stdin)
  102258. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  102259. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102260. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  102261. else
  102262. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  102263. }
  102264. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102265. {
  102266. off_t pos;
  102267. (void)client_data;
  102268. if(decoder->private_->file == stdin)
  102269. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  102270. else if((pos = ftello(decoder->private_->file)) < 0)
  102271. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  102272. else {
  102273. *absolute_byte_offset = (FLAC__uint64)pos;
  102274. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  102275. }
  102276. }
  102277. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  102278. {
  102279. struct stat filestats;
  102280. (void)client_data;
  102281. if(decoder->private_->file == stdin)
  102282. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  102283. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  102284. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  102285. else {
  102286. *stream_length = (FLAC__uint64)filestats.st_size;
  102287. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  102288. }
  102289. }
  102290. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  102291. {
  102292. (void)client_data;
  102293. return feof(decoder->private_->file)? true : false;
  102294. }
  102295. #endif
  102296. /*** End of inlined file: stream_decoder.c ***/
  102297. /*** Start of inlined file: stream_encoder.c ***/
  102298. /*** Start of inlined file: juce_FlacHeader.h ***/
  102299. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102300. // tasks..
  102301. #define VERSION "1.2.1"
  102302. #define FLAC__NO_DLL 1
  102303. #if JUCE_MSVC
  102304. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102305. #endif
  102306. #if JUCE_MAC
  102307. #define FLAC__SYS_DARWIN 1
  102308. #endif
  102309. /*** End of inlined file: juce_FlacHeader.h ***/
  102310. #if JUCE_USE_FLAC
  102311. #if HAVE_CONFIG_H
  102312. # include <config.h>
  102313. #endif
  102314. #if defined _MSC_VER || defined __MINGW32__
  102315. #include <io.h> /* for _setmode() */
  102316. #include <fcntl.h> /* for _O_BINARY */
  102317. #endif
  102318. #if defined __CYGWIN__ || defined __EMX__
  102319. #include <io.h> /* for setmode(), O_BINARY */
  102320. #include <fcntl.h> /* for _O_BINARY */
  102321. #endif
  102322. #include <limits.h>
  102323. #include <stdio.h>
  102324. #include <stdlib.h> /* for malloc() */
  102325. #include <string.h> /* for memcpy() */
  102326. #include <sys/types.h> /* for off_t */
  102327. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  102328. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  102329. #define fseeko fseek
  102330. #define ftello ftell
  102331. #endif
  102332. #endif
  102333. /*** Start of inlined file: stream_encoder.h ***/
  102334. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  102335. #define FLAC__PROTECTED__STREAM_ENCODER_H
  102336. #if FLAC__HAS_OGG
  102337. #include "private/ogg_encoder_aspect.h"
  102338. #endif
  102339. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102340. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  102341. typedef enum {
  102342. FLAC__APODIZATION_BARTLETT,
  102343. FLAC__APODIZATION_BARTLETT_HANN,
  102344. FLAC__APODIZATION_BLACKMAN,
  102345. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  102346. FLAC__APODIZATION_CONNES,
  102347. FLAC__APODIZATION_FLATTOP,
  102348. FLAC__APODIZATION_GAUSS,
  102349. FLAC__APODIZATION_HAMMING,
  102350. FLAC__APODIZATION_HANN,
  102351. FLAC__APODIZATION_KAISER_BESSEL,
  102352. FLAC__APODIZATION_NUTTALL,
  102353. FLAC__APODIZATION_RECTANGLE,
  102354. FLAC__APODIZATION_TRIANGLE,
  102355. FLAC__APODIZATION_TUKEY,
  102356. FLAC__APODIZATION_WELCH
  102357. } FLAC__ApodizationFunction;
  102358. typedef struct {
  102359. FLAC__ApodizationFunction type;
  102360. union {
  102361. struct {
  102362. FLAC__real stddev;
  102363. } gauss;
  102364. struct {
  102365. FLAC__real p;
  102366. } tukey;
  102367. } parameters;
  102368. } FLAC__ApodizationSpecification;
  102369. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102370. typedef struct FLAC__StreamEncoderProtected {
  102371. FLAC__StreamEncoderState state;
  102372. FLAC__bool verify;
  102373. FLAC__bool streamable_subset;
  102374. FLAC__bool do_md5;
  102375. FLAC__bool do_mid_side_stereo;
  102376. FLAC__bool loose_mid_side_stereo;
  102377. unsigned channels;
  102378. unsigned bits_per_sample;
  102379. unsigned sample_rate;
  102380. unsigned blocksize;
  102381. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102382. unsigned num_apodizations;
  102383. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  102384. #endif
  102385. unsigned max_lpc_order;
  102386. unsigned qlp_coeff_precision;
  102387. FLAC__bool do_qlp_coeff_prec_search;
  102388. FLAC__bool do_exhaustive_model_search;
  102389. FLAC__bool do_escape_coding;
  102390. unsigned min_residual_partition_order;
  102391. unsigned max_residual_partition_order;
  102392. unsigned rice_parameter_search_dist;
  102393. FLAC__uint64 total_samples_estimate;
  102394. FLAC__StreamMetadata **metadata;
  102395. unsigned num_metadata_blocks;
  102396. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  102397. #if FLAC__HAS_OGG
  102398. FLAC__OggEncoderAspect ogg_encoder_aspect;
  102399. #endif
  102400. } FLAC__StreamEncoderProtected;
  102401. #endif
  102402. /*** End of inlined file: stream_encoder.h ***/
  102403. #if FLAC__HAS_OGG
  102404. #include "include/private/ogg_helper.h"
  102405. #include "include/private/ogg_mapping.h"
  102406. #endif
  102407. /*** Start of inlined file: stream_encoder_framing.h ***/
  102408. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102409. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  102410. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  102411. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  102412. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102413. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102414. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102415. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  102416. #endif
  102417. /*** End of inlined file: stream_encoder_framing.h ***/
  102418. /*** Start of inlined file: window.h ***/
  102419. #ifndef FLAC__PRIVATE__WINDOW_H
  102420. #define FLAC__PRIVATE__WINDOW_H
  102421. #ifdef HAVE_CONFIG_H
  102422. #include <config.h>
  102423. #endif
  102424. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102425. /*
  102426. * FLAC__window_*()
  102427. * --------------------------------------------------------------------
  102428. * Calculates window coefficients according to different apodization
  102429. * functions.
  102430. *
  102431. * OUT window[0,L-1]
  102432. * IN L (number of points in window)
  102433. */
  102434. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  102435. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  102436. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  102437. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  102438. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  102439. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  102440. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  102441. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  102442. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  102443. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  102444. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  102445. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  102446. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  102447. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  102448. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  102449. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  102450. #endif
  102451. /*** End of inlined file: window.h ***/
  102452. #ifndef FLaC__INLINE
  102453. #define FLaC__INLINE
  102454. #endif
  102455. #ifdef min
  102456. #undef min
  102457. #endif
  102458. #define min(x,y) ((x)<(y)?(x):(y))
  102459. #ifdef max
  102460. #undef max
  102461. #endif
  102462. #define max(x,y) ((x)>(y)?(x):(y))
  102463. /* Exact Rice codeword length calculation is off by default. The simple
  102464. * (and fast) estimation (of how many bits a residual value will be
  102465. * encoded with) in this encoder is very good, almost always yielding
  102466. * compression within 0.1% of exact calculation.
  102467. */
  102468. #undef EXACT_RICE_BITS_CALCULATION
  102469. /* Rice parameter searching is off by default. The simple (and fast)
  102470. * parameter estimation in this encoder is very good, almost always
  102471. * yielding compression within 0.1% of the optimal parameters.
  102472. */
  102473. #undef ENABLE_RICE_PARAMETER_SEARCH
  102474. typedef struct {
  102475. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  102476. unsigned size; /* of each data[] in samples */
  102477. unsigned tail;
  102478. } verify_input_fifo;
  102479. typedef struct {
  102480. const FLAC__byte *data;
  102481. unsigned capacity;
  102482. unsigned bytes;
  102483. } verify_output;
  102484. typedef enum {
  102485. ENCODER_IN_MAGIC = 0,
  102486. ENCODER_IN_METADATA = 1,
  102487. ENCODER_IN_AUDIO = 2
  102488. } EncoderStateHint;
  102489. static struct CompressionLevels {
  102490. FLAC__bool do_mid_side_stereo;
  102491. FLAC__bool loose_mid_side_stereo;
  102492. unsigned max_lpc_order;
  102493. unsigned qlp_coeff_precision;
  102494. FLAC__bool do_qlp_coeff_prec_search;
  102495. FLAC__bool do_escape_coding;
  102496. FLAC__bool do_exhaustive_model_search;
  102497. unsigned min_residual_partition_order;
  102498. unsigned max_residual_partition_order;
  102499. unsigned rice_parameter_search_dist;
  102500. } compression_levels_[] = {
  102501. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  102502. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  102503. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  102504. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  102505. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  102506. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  102507. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  102508. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  102509. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  102510. };
  102511. /***********************************************************************
  102512. *
  102513. * Private class method prototypes
  102514. *
  102515. ***********************************************************************/
  102516. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  102517. static void free_(FLAC__StreamEncoder *encoder);
  102518. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  102519. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  102520. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  102521. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  102522. #if FLAC__HAS_OGG
  102523. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  102524. #endif
  102525. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  102526. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  102527. static FLAC__bool process_subframe_(
  102528. FLAC__StreamEncoder *encoder,
  102529. unsigned min_partition_order,
  102530. unsigned max_partition_order,
  102531. const FLAC__FrameHeader *frame_header,
  102532. unsigned subframe_bps,
  102533. const FLAC__int32 integer_signal[],
  102534. FLAC__Subframe *subframe[2],
  102535. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  102536. FLAC__int32 *residual[2],
  102537. unsigned *best_subframe,
  102538. unsigned *best_bits
  102539. );
  102540. static FLAC__bool add_subframe_(
  102541. FLAC__StreamEncoder *encoder,
  102542. unsigned blocksize,
  102543. unsigned subframe_bps,
  102544. const FLAC__Subframe *subframe,
  102545. FLAC__BitWriter *frame
  102546. );
  102547. static unsigned evaluate_constant_subframe_(
  102548. FLAC__StreamEncoder *encoder,
  102549. const FLAC__int32 signal,
  102550. unsigned blocksize,
  102551. unsigned subframe_bps,
  102552. FLAC__Subframe *subframe
  102553. );
  102554. static unsigned evaluate_fixed_subframe_(
  102555. FLAC__StreamEncoder *encoder,
  102556. const FLAC__int32 signal[],
  102557. FLAC__int32 residual[],
  102558. FLAC__uint64 abs_residual_partition_sums[],
  102559. unsigned raw_bits_per_partition[],
  102560. unsigned blocksize,
  102561. unsigned subframe_bps,
  102562. unsigned order,
  102563. unsigned rice_parameter,
  102564. unsigned rice_parameter_limit,
  102565. unsigned min_partition_order,
  102566. unsigned max_partition_order,
  102567. FLAC__bool do_escape_coding,
  102568. unsigned rice_parameter_search_dist,
  102569. FLAC__Subframe *subframe,
  102570. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102571. );
  102572. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102573. static unsigned evaluate_lpc_subframe_(
  102574. FLAC__StreamEncoder *encoder,
  102575. const FLAC__int32 signal[],
  102576. FLAC__int32 residual[],
  102577. FLAC__uint64 abs_residual_partition_sums[],
  102578. unsigned raw_bits_per_partition[],
  102579. const FLAC__real lp_coeff[],
  102580. unsigned blocksize,
  102581. unsigned subframe_bps,
  102582. unsigned order,
  102583. unsigned qlp_coeff_precision,
  102584. unsigned rice_parameter,
  102585. unsigned rice_parameter_limit,
  102586. unsigned min_partition_order,
  102587. unsigned max_partition_order,
  102588. FLAC__bool do_escape_coding,
  102589. unsigned rice_parameter_search_dist,
  102590. FLAC__Subframe *subframe,
  102591. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  102592. );
  102593. #endif
  102594. static unsigned evaluate_verbatim_subframe_(
  102595. FLAC__StreamEncoder *encoder,
  102596. const FLAC__int32 signal[],
  102597. unsigned blocksize,
  102598. unsigned subframe_bps,
  102599. FLAC__Subframe *subframe
  102600. );
  102601. static unsigned find_best_partition_order_(
  102602. struct FLAC__StreamEncoderPrivate *private_,
  102603. const FLAC__int32 residual[],
  102604. FLAC__uint64 abs_residual_partition_sums[],
  102605. unsigned raw_bits_per_partition[],
  102606. unsigned residual_samples,
  102607. unsigned predictor_order,
  102608. unsigned rice_parameter,
  102609. unsigned rice_parameter_limit,
  102610. unsigned min_partition_order,
  102611. unsigned max_partition_order,
  102612. unsigned bps,
  102613. FLAC__bool do_escape_coding,
  102614. unsigned rice_parameter_search_dist,
  102615. FLAC__EntropyCodingMethod *best_ecm
  102616. );
  102617. static void precompute_partition_info_sums_(
  102618. const FLAC__int32 residual[],
  102619. FLAC__uint64 abs_residual_partition_sums[],
  102620. unsigned residual_samples,
  102621. unsigned predictor_order,
  102622. unsigned min_partition_order,
  102623. unsigned max_partition_order,
  102624. unsigned bps
  102625. );
  102626. static void precompute_partition_info_escapes_(
  102627. const FLAC__int32 residual[],
  102628. unsigned raw_bits_per_partition[],
  102629. unsigned residual_samples,
  102630. unsigned predictor_order,
  102631. unsigned min_partition_order,
  102632. unsigned max_partition_order
  102633. );
  102634. static FLAC__bool set_partitioned_rice_(
  102635. #ifdef EXACT_RICE_BITS_CALCULATION
  102636. const FLAC__int32 residual[],
  102637. #endif
  102638. const FLAC__uint64 abs_residual_partition_sums[],
  102639. const unsigned raw_bits_per_partition[],
  102640. const unsigned residual_samples,
  102641. const unsigned predictor_order,
  102642. const unsigned suggested_rice_parameter,
  102643. const unsigned rice_parameter_limit,
  102644. const unsigned rice_parameter_search_dist,
  102645. const unsigned partition_order,
  102646. const FLAC__bool search_for_escapes,
  102647. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102648. unsigned *bits
  102649. );
  102650. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  102651. /* verify-related routines: */
  102652. static void append_to_verify_fifo_(
  102653. verify_input_fifo *fifo,
  102654. const FLAC__int32 * const input[],
  102655. unsigned input_offset,
  102656. unsigned channels,
  102657. unsigned wide_samples
  102658. );
  102659. static void append_to_verify_fifo_interleaved_(
  102660. verify_input_fifo *fifo,
  102661. const FLAC__int32 input[],
  102662. unsigned input_offset,
  102663. unsigned channels,
  102664. unsigned wide_samples
  102665. );
  102666. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102667. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  102668. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  102669. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  102670. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  102671. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  102672. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  102673. 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);
  102674. static FILE *get_binary_stdout_(void);
  102675. /***********************************************************************
  102676. *
  102677. * Private class data
  102678. *
  102679. ***********************************************************************/
  102680. typedef struct FLAC__StreamEncoderPrivate {
  102681. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  102682. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  102683. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  102684. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102685. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  102686. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  102687. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  102688. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  102689. #endif
  102690. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  102691. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  102692. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  102693. FLAC__int32 *residual_workspace_mid_side[2][2];
  102694. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  102695. FLAC__Subframe subframe_workspace_mid_side[2][2];
  102696. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102697. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  102698. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  102699. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  102700. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  102701. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  102702. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  102703. unsigned best_subframe_mid_side[2];
  102704. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  102705. unsigned best_subframe_bits_mid_side[2];
  102706. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  102707. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  102708. FLAC__BitWriter *frame; /* the current frame being worked on */
  102709. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  102710. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  102711. FLAC__ChannelAssignment last_channel_assignment;
  102712. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  102713. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  102714. unsigned current_sample_number;
  102715. unsigned current_frame_number;
  102716. FLAC__MD5Context md5context;
  102717. FLAC__CPUInfo cpuinfo;
  102718. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102719. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102720. #else
  102721. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  102722. #endif
  102723. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102724. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  102725. 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[]);
  102726. 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[]);
  102727. 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[]);
  102728. #endif
  102729. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  102730. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  102731. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  102732. FLAC__bool disable_constant_subframes;
  102733. FLAC__bool disable_fixed_subframes;
  102734. FLAC__bool disable_verbatim_subframes;
  102735. #if FLAC__HAS_OGG
  102736. FLAC__bool is_ogg;
  102737. #endif
  102738. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  102739. FLAC__StreamEncoderSeekCallback seek_callback;
  102740. FLAC__StreamEncoderTellCallback tell_callback;
  102741. FLAC__StreamEncoderWriteCallback write_callback;
  102742. FLAC__StreamEncoderMetadataCallback metadata_callback;
  102743. FLAC__StreamEncoderProgressCallback progress_callback;
  102744. void *client_data;
  102745. unsigned first_seekpoint_to_check;
  102746. FILE *file; /* only used when encoding to a file */
  102747. FLAC__uint64 bytes_written;
  102748. FLAC__uint64 samples_written;
  102749. unsigned frames_written;
  102750. unsigned total_frames_estimate;
  102751. /* unaligned (original) pointers to allocated data */
  102752. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  102753. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  102754. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102755. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  102756. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  102757. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  102758. FLAC__real *windowed_signal_unaligned;
  102759. #endif
  102760. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  102761. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  102762. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  102763. unsigned *raw_bits_per_partition_unaligned;
  102764. /*
  102765. * These fields have been moved here from private function local
  102766. * declarations merely to save stack space during encoding.
  102767. */
  102768. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  102769. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  102770. #endif
  102771. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  102772. /*
  102773. * The data for the verify section
  102774. */
  102775. struct {
  102776. FLAC__StreamDecoder *decoder;
  102777. EncoderStateHint state_hint;
  102778. FLAC__bool needs_magic_hack;
  102779. verify_input_fifo input_fifo;
  102780. verify_output output;
  102781. struct {
  102782. FLAC__uint64 absolute_sample;
  102783. unsigned frame_number;
  102784. unsigned channel;
  102785. unsigned sample;
  102786. FLAC__int32 expected;
  102787. FLAC__int32 got;
  102788. } error_stats;
  102789. } verify;
  102790. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  102791. } FLAC__StreamEncoderPrivate;
  102792. /***********************************************************************
  102793. *
  102794. * Public static class data
  102795. *
  102796. ***********************************************************************/
  102797. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  102798. "FLAC__STREAM_ENCODER_OK",
  102799. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  102800. "FLAC__STREAM_ENCODER_OGG_ERROR",
  102801. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  102802. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  102803. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  102804. "FLAC__STREAM_ENCODER_IO_ERROR",
  102805. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  102806. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  102807. };
  102808. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  102809. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  102810. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  102811. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  102812. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  102813. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  102814. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  102815. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  102816. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  102817. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  102818. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  102819. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  102820. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  102821. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  102822. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  102823. };
  102824. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  102825. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  102826. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  102827. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  102828. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  102829. };
  102830. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  102831. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  102832. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  102833. };
  102834. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  102835. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  102836. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  102837. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  102838. };
  102839. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  102840. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  102841. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  102842. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  102843. };
  102844. /* Number of samples that will be overread to watch for end of stream. By
  102845. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  102846. * always try to read blocksize+1 samples before encoding a block, so that
  102847. * even if the stream has a total sample count that is an integral multiple
  102848. * of the blocksize, we will still notice when we are encoding the last
  102849. * block. This is needed, for example, to correctly set the end-of-stream
  102850. * marker in Ogg FLAC.
  102851. *
  102852. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  102853. * not really any reason to change it.
  102854. */
  102855. static const unsigned OVERREAD_ = 1;
  102856. /***********************************************************************
  102857. *
  102858. * Class constructor/destructor
  102859. *
  102860. */
  102861. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  102862. {
  102863. FLAC__StreamEncoder *encoder;
  102864. unsigned i;
  102865. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  102866. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  102867. if(encoder == 0) {
  102868. return 0;
  102869. }
  102870. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  102871. if(encoder->protected_ == 0) {
  102872. free(encoder);
  102873. return 0;
  102874. }
  102875. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  102876. if(encoder->private_ == 0) {
  102877. free(encoder->protected_);
  102878. free(encoder);
  102879. return 0;
  102880. }
  102881. encoder->private_->frame = FLAC__bitwriter_new();
  102882. if(encoder->private_->frame == 0) {
  102883. free(encoder->private_);
  102884. free(encoder->protected_);
  102885. free(encoder);
  102886. return 0;
  102887. }
  102888. encoder->private_->file = 0;
  102889. set_defaults_enc(encoder);
  102890. encoder->private_->is_being_deleted = false;
  102891. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102892. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  102893. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  102894. }
  102895. for(i = 0; i < 2; i++) {
  102896. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  102897. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  102898. }
  102899. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102900. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  102901. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  102902. }
  102903. for(i = 0; i < 2; i++) {
  102904. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  102905. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  102906. }
  102907. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102908. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102909. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102910. }
  102911. for(i = 0; i < 2; i++) {
  102912. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102913. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102914. }
  102915. for(i = 0; i < 2; i++)
  102916. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  102917. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  102918. return encoder;
  102919. }
  102920. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  102921. {
  102922. unsigned i;
  102923. FLAC__ASSERT(0 != encoder);
  102924. FLAC__ASSERT(0 != encoder->protected_);
  102925. FLAC__ASSERT(0 != encoder->private_);
  102926. FLAC__ASSERT(0 != encoder->private_->frame);
  102927. encoder->private_->is_being_deleted = true;
  102928. (void)FLAC__stream_encoder_finish(encoder);
  102929. if(0 != encoder->private_->verify.decoder)
  102930. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  102931. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  102932. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  102933. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  102934. }
  102935. for(i = 0; i < 2; i++) {
  102936. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  102937. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  102938. }
  102939. for(i = 0; i < 2; i++)
  102940. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  102941. FLAC__bitwriter_delete(encoder->private_->frame);
  102942. free(encoder->private_);
  102943. free(encoder->protected_);
  102944. free(encoder);
  102945. }
  102946. /***********************************************************************
  102947. *
  102948. * Public class methods
  102949. *
  102950. ***********************************************************************/
  102951. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  102952. FLAC__StreamEncoder *encoder,
  102953. FLAC__StreamEncoderReadCallback read_callback,
  102954. FLAC__StreamEncoderWriteCallback write_callback,
  102955. FLAC__StreamEncoderSeekCallback seek_callback,
  102956. FLAC__StreamEncoderTellCallback tell_callback,
  102957. FLAC__StreamEncoderMetadataCallback metadata_callback,
  102958. void *client_data,
  102959. FLAC__bool is_ogg
  102960. )
  102961. {
  102962. unsigned i;
  102963. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  102964. FLAC__ASSERT(0 != encoder);
  102965. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  102966. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  102967. #if !FLAC__HAS_OGG
  102968. if(is_ogg)
  102969. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  102970. #endif
  102971. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  102972. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  102973. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  102974. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  102975. if(encoder->protected_->channels != 2) {
  102976. encoder->protected_->do_mid_side_stereo = false;
  102977. encoder->protected_->loose_mid_side_stereo = false;
  102978. }
  102979. else if(!encoder->protected_->do_mid_side_stereo)
  102980. encoder->protected_->loose_mid_side_stereo = false;
  102981. if(encoder->protected_->bits_per_sample >= 32)
  102982. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  102983. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  102984. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  102985. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  102986. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  102987. if(encoder->protected_->blocksize == 0) {
  102988. if(encoder->protected_->max_lpc_order == 0)
  102989. encoder->protected_->blocksize = 1152;
  102990. else
  102991. encoder->protected_->blocksize = 4096;
  102992. }
  102993. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  102994. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  102995. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  102996. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  102997. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  102998. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  102999. if(encoder->protected_->qlp_coeff_precision == 0) {
  103000. if(encoder->protected_->bits_per_sample < 16) {
  103001. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  103002. /* @@@ until then we'll make a guess */
  103003. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  103004. }
  103005. else if(encoder->protected_->bits_per_sample == 16) {
  103006. if(encoder->protected_->blocksize <= 192)
  103007. encoder->protected_->qlp_coeff_precision = 7;
  103008. else if(encoder->protected_->blocksize <= 384)
  103009. encoder->protected_->qlp_coeff_precision = 8;
  103010. else if(encoder->protected_->blocksize <= 576)
  103011. encoder->protected_->qlp_coeff_precision = 9;
  103012. else if(encoder->protected_->blocksize <= 1152)
  103013. encoder->protected_->qlp_coeff_precision = 10;
  103014. else if(encoder->protected_->blocksize <= 2304)
  103015. encoder->protected_->qlp_coeff_precision = 11;
  103016. else if(encoder->protected_->blocksize <= 4608)
  103017. encoder->protected_->qlp_coeff_precision = 12;
  103018. else
  103019. encoder->protected_->qlp_coeff_precision = 13;
  103020. }
  103021. else {
  103022. if(encoder->protected_->blocksize <= 384)
  103023. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  103024. else if(encoder->protected_->blocksize <= 1152)
  103025. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  103026. else
  103027. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  103028. }
  103029. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  103030. }
  103031. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  103032. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  103033. if(encoder->protected_->streamable_subset) {
  103034. if(
  103035. encoder->protected_->blocksize != 192 &&
  103036. encoder->protected_->blocksize != 576 &&
  103037. encoder->protected_->blocksize != 1152 &&
  103038. encoder->protected_->blocksize != 2304 &&
  103039. encoder->protected_->blocksize != 4608 &&
  103040. encoder->protected_->blocksize != 256 &&
  103041. encoder->protected_->blocksize != 512 &&
  103042. encoder->protected_->blocksize != 1024 &&
  103043. encoder->protected_->blocksize != 2048 &&
  103044. encoder->protected_->blocksize != 4096 &&
  103045. encoder->protected_->blocksize != 8192 &&
  103046. encoder->protected_->blocksize != 16384
  103047. )
  103048. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103049. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  103050. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103051. if(
  103052. encoder->protected_->bits_per_sample != 8 &&
  103053. encoder->protected_->bits_per_sample != 12 &&
  103054. encoder->protected_->bits_per_sample != 16 &&
  103055. encoder->protected_->bits_per_sample != 20 &&
  103056. encoder->protected_->bits_per_sample != 24
  103057. )
  103058. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103059. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  103060. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103061. if(
  103062. encoder->protected_->sample_rate <= 48000 &&
  103063. (
  103064. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  103065. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  103066. )
  103067. ) {
  103068. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  103069. }
  103070. }
  103071. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103072. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  103073. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  103074. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  103075. #if FLAC__HAS_OGG
  103076. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  103077. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  103078. unsigned i;
  103079. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  103080. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103081. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  103082. for( ; i > 0; i--)
  103083. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  103084. encoder->protected_->metadata[0] = vc;
  103085. break;
  103086. }
  103087. }
  103088. }
  103089. #endif
  103090. /* keep track of any SEEKTABLE block */
  103091. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  103092. unsigned i;
  103093. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103094. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103095. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  103096. break; /* take only the first one */
  103097. }
  103098. }
  103099. }
  103100. /* validate metadata */
  103101. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  103102. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103103. metadata_has_seektable = false;
  103104. metadata_has_vorbis_comment = false;
  103105. metadata_picture_has_type1 = false;
  103106. metadata_picture_has_type2 = false;
  103107. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103108. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  103109. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  103110. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103111. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  103112. if(metadata_has_seektable) /* only one is allowed */
  103113. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103114. metadata_has_seektable = true;
  103115. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  103116. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103117. }
  103118. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  103119. if(metadata_has_vorbis_comment) /* only one is allowed */
  103120. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103121. metadata_has_vorbis_comment = true;
  103122. }
  103123. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  103124. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  103125. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103126. }
  103127. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  103128. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  103129. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103130. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  103131. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  103132. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103133. metadata_picture_has_type1 = true;
  103134. /* standard icon must be 32x32 pixel PNG */
  103135. if(
  103136. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  103137. (
  103138. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  103139. m->data.picture.width != 32 ||
  103140. m->data.picture.height != 32
  103141. )
  103142. )
  103143. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103144. }
  103145. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  103146. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  103147. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  103148. metadata_picture_has_type2 = true;
  103149. }
  103150. }
  103151. }
  103152. encoder->private_->input_capacity = 0;
  103153. for(i = 0; i < encoder->protected_->channels; i++) {
  103154. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  103155. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103156. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  103157. #endif
  103158. }
  103159. for(i = 0; i < 2; i++) {
  103160. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  103161. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103162. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  103163. #endif
  103164. }
  103165. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103166. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  103167. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  103168. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  103169. #endif
  103170. for(i = 0; i < encoder->protected_->channels; i++) {
  103171. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  103172. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  103173. encoder->private_->best_subframe[i] = 0;
  103174. }
  103175. for(i = 0; i < 2; i++) {
  103176. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  103177. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  103178. encoder->private_->best_subframe_mid_side[i] = 0;
  103179. }
  103180. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  103181. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  103182. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103183. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  103184. #else
  103185. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  103186. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  103187. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  103188. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  103189. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  103190. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  103191. 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);
  103192. #endif
  103193. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  103194. encoder->private_->loose_mid_side_stereo_frames = 1;
  103195. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  103196. encoder->private_->current_sample_number = 0;
  103197. encoder->private_->current_frame_number = 0;
  103198. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  103199. 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? */
  103200. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  103201. /*
  103202. * get the CPU info and set the function pointers
  103203. */
  103204. FLAC__cpu_info(&encoder->private_->cpuinfo);
  103205. /* first default to the non-asm routines */
  103206. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103207. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  103208. #endif
  103209. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  103210. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103211. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103212. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  103213. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  103214. #endif
  103215. /* now override with asm where appropriate */
  103216. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103217. # ifndef FLAC__NO_ASM
  103218. if(encoder->private_->cpuinfo.use_asm) {
  103219. # ifdef FLAC__CPU_IA32
  103220. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  103221. # ifdef FLAC__HAS_NASM
  103222. if(encoder->private_->cpuinfo.data.ia32.sse) {
  103223. if(encoder->protected_->max_lpc_order < 4)
  103224. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  103225. else if(encoder->protected_->max_lpc_order < 8)
  103226. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  103227. else if(encoder->protected_->max_lpc_order < 12)
  103228. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  103229. else
  103230. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103231. }
  103232. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  103233. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  103234. else
  103235. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  103236. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  103237. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103238. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  103239. }
  103240. else {
  103241. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103242. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  103243. }
  103244. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  103245. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  103246. # endif /* FLAC__HAS_NASM */
  103247. # endif /* FLAC__CPU_IA32 */
  103248. }
  103249. # endif /* !FLAC__NO_ASM */
  103250. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  103251. /* finally override based on wide-ness if necessary */
  103252. if(encoder->private_->use_wide_by_block) {
  103253. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  103254. }
  103255. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  103256. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  103257. #if FLAC__HAS_OGG
  103258. encoder->private_->is_ogg = is_ogg;
  103259. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  103260. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  103261. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103262. }
  103263. #endif
  103264. encoder->private_->read_callback = read_callback;
  103265. encoder->private_->write_callback = write_callback;
  103266. encoder->private_->seek_callback = seek_callback;
  103267. encoder->private_->tell_callback = tell_callback;
  103268. encoder->private_->metadata_callback = metadata_callback;
  103269. encoder->private_->client_data = client_data;
  103270. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  103271. /* the above function sets the state for us in case of an error */
  103272. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103273. }
  103274. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  103275. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103276. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103277. }
  103278. /*
  103279. * Set up the verify stuff if necessary
  103280. */
  103281. if(encoder->protected_->verify) {
  103282. /*
  103283. * First, set up the fifo which will hold the
  103284. * original signal to compare against
  103285. */
  103286. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  103287. for(i = 0; i < encoder->protected_->channels; i++) {
  103288. 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))) {
  103289. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  103290. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103291. }
  103292. }
  103293. encoder->private_->verify.input_fifo.tail = 0;
  103294. /*
  103295. * Now set up a stream decoder for verification
  103296. */
  103297. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  103298. if(0 == encoder->private_->verify.decoder) {
  103299. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103300. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103301. }
  103302. 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) {
  103303. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  103304. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103305. }
  103306. }
  103307. encoder->private_->verify.error_stats.absolute_sample = 0;
  103308. encoder->private_->verify.error_stats.frame_number = 0;
  103309. encoder->private_->verify.error_stats.channel = 0;
  103310. encoder->private_->verify.error_stats.sample = 0;
  103311. encoder->private_->verify.error_stats.expected = 0;
  103312. encoder->private_->verify.error_stats.got = 0;
  103313. /*
  103314. * These must be done before we write any metadata, because that
  103315. * calls the write_callback, which uses these values.
  103316. */
  103317. encoder->private_->first_seekpoint_to_check = 0;
  103318. encoder->private_->samples_written = 0;
  103319. encoder->protected_->streaminfo_offset = 0;
  103320. encoder->protected_->seektable_offset = 0;
  103321. encoder->protected_->audio_offset = 0;
  103322. /*
  103323. * write the stream header
  103324. */
  103325. if(encoder->protected_->verify)
  103326. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  103327. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  103328. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103329. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103330. }
  103331. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103332. /* the above function sets the state for us in case of an error */
  103333. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103334. }
  103335. /*
  103336. * write the STREAMINFO metadata block
  103337. */
  103338. if(encoder->protected_->verify)
  103339. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  103340. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  103341. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  103342. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  103343. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  103344. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  103345. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  103346. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  103347. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  103348. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  103349. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  103350. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  103351. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  103352. if(encoder->protected_->do_md5)
  103353. FLAC__MD5Init(&encoder->private_->md5context);
  103354. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  103355. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103356. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103357. }
  103358. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103359. /* the above function sets the state for us in case of an error */
  103360. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103361. }
  103362. /*
  103363. * Now that the STREAMINFO block is written, we can init this to an
  103364. * absurdly-high value...
  103365. */
  103366. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  103367. /* ... and clear this to 0 */
  103368. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  103369. /*
  103370. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  103371. * if not, we will write an empty one (FLAC__add_metadata_block()
  103372. * automatically supplies the vendor string).
  103373. *
  103374. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  103375. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  103376. * true it will have already insured that the metadata list is properly
  103377. * ordered.)
  103378. */
  103379. if(!metadata_has_vorbis_comment) {
  103380. FLAC__StreamMetadata vorbis_comment;
  103381. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  103382. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  103383. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  103384. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  103385. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  103386. vorbis_comment.data.vorbis_comment.num_comments = 0;
  103387. vorbis_comment.data.vorbis_comment.comments = 0;
  103388. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  103389. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103390. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103391. }
  103392. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103393. /* the above function sets the state for us in case of an error */
  103394. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103395. }
  103396. }
  103397. /*
  103398. * write the user's metadata blocks
  103399. */
  103400. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  103401. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  103402. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  103403. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  103404. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103405. }
  103406. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  103407. /* the above function sets the state for us in case of an error */
  103408. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103409. }
  103410. }
  103411. /* now that all the metadata is written, we save the stream offset */
  103412. 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 */
  103413. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  103414. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103415. }
  103416. if(encoder->protected_->verify)
  103417. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  103418. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103419. }
  103420. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  103421. FLAC__StreamEncoder *encoder,
  103422. FLAC__StreamEncoderWriteCallback write_callback,
  103423. FLAC__StreamEncoderSeekCallback seek_callback,
  103424. FLAC__StreamEncoderTellCallback tell_callback,
  103425. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103426. void *client_data
  103427. )
  103428. {
  103429. return init_stream_internal_enc(
  103430. encoder,
  103431. /*read_callback=*/0,
  103432. write_callback,
  103433. seek_callback,
  103434. tell_callback,
  103435. metadata_callback,
  103436. client_data,
  103437. /*is_ogg=*/false
  103438. );
  103439. }
  103440. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  103441. FLAC__StreamEncoder *encoder,
  103442. FLAC__StreamEncoderReadCallback read_callback,
  103443. FLAC__StreamEncoderWriteCallback write_callback,
  103444. FLAC__StreamEncoderSeekCallback seek_callback,
  103445. FLAC__StreamEncoderTellCallback tell_callback,
  103446. FLAC__StreamEncoderMetadataCallback metadata_callback,
  103447. void *client_data
  103448. )
  103449. {
  103450. return init_stream_internal_enc(
  103451. encoder,
  103452. read_callback,
  103453. write_callback,
  103454. seek_callback,
  103455. tell_callback,
  103456. metadata_callback,
  103457. client_data,
  103458. /*is_ogg=*/true
  103459. );
  103460. }
  103461. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  103462. FLAC__StreamEncoder *encoder,
  103463. FILE *file,
  103464. FLAC__StreamEncoderProgressCallback progress_callback,
  103465. void *client_data,
  103466. FLAC__bool is_ogg
  103467. )
  103468. {
  103469. FLAC__StreamEncoderInitStatus init_status;
  103470. FLAC__ASSERT(0 != encoder);
  103471. FLAC__ASSERT(0 != file);
  103472. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103473. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103474. /* double protection */
  103475. if(file == 0) {
  103476. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103477. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103478. }
  103479. /*
  103480. * To make sure that our file does not go unclosed after an error, we
  103481. * must assign the FILE pointer before any further error can occur in
  103482. * this routine.
  103483. */
  103484. if(file == stdout)
  103485. file = get_binary_stdout_(); /* just to be safe */
  103486. encoder->private_->file = file;
  103487. encoder->private_->progress_callback = progress_callback;
  103488. encoder->private_->bytes_written = 0;
  103489. encoder->private_->samples_written = 0;
  103490. encoder->private_->frames_written = 0;
  103491. init_status = init_stream_internal_enc(
  103492. encoder,
  103493. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  103494. file_write_callback_,
  103495. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  103496. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  103497. /*metadata_callback=*/0,
  103498. client_data,
  103499. is_ogg
  103500. );
  103501. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  103502. /* the above function sets the state for us in case of an error */
  103503. return init_status;
  103504. }
  103505. {
  103506. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  103507. FLAC__ASSERT(blocksize != 0);
  103508. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  103509. }
  103510. return init_status;
  103511. }
  103512. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  103513. FLAC__StreamEncoder *encoder,
  103514. FILE *file,
  103515. FLAC__StreamEncoderProgressCallback progress_callback,
  103516. void *client_data
  103517. )
  103518. {
  103519. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  103520. }
  103521. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  103522. FLAC__StreamEncoder *encoder,
  103523. FILE *file,
  103524. FLAC__StreamEncoderProgressCallback progress_callback,
  103525. void *client_data
  103526. )
  103527. {
  103528. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  103529. }
  103530. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  103531. FLAC__StreamEncoder *encoder,
  103532. const char *filename,
  103533. FLAC__StreamEncoderProgressCallback progress_callback,
  103534. void *client_data,
  103535. FLAC__bool is_ogg
  103536. )
  103537. {
  103538. FILE *file;
  103539. FLAC__ASSERT(0 != encoder);
  103540. /*
  103541. * To make sure that our file does not go unclosed after an error, we
  103542. * have to do the same entrance checks here that are later performed
  103543. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  103544. */
  103545. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103546. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  103547. file = filename? fopen(filename, "w+b") : stdout;
  103548. if(file == 0) {
  103549. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  103550. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  103551. }
  103552. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  103553. }
  103554. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  103555. FLAC__StreamEncoder *encoder,
  103556. const char *filename,
  103557. FLAC__StreamEncoderProgressCallback progress_callback,
  103558. void *client_data
  103559. )
  103560. {
  103561. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  103562. }
  103563. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  103564. FLAC__StreamEncoder *encoder,
  103565. const char *filename,
  103566. FLAC__StreamEncoderProgressCallback progress_callback,
  103567. void *client_data
  103568. )
  103569. {
  103570. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  103571. }
  103572. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  103573. {
  103574. FLAC__bool error = false;
  103575. FLAC__ASSERT(0 != encoder);
  103576. FLAC__ASSERT(0 != encoder->private_);
  103577. FLAC__ASSERT(0 != encoder->protected_);
  103578. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  103579. return true;
  103580. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  103581. if(encoder->private_->current_sample_number != 0) {
  103582. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  103583. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  103584. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  103585. error = true;
  103586. }
  103587. }
  103588. if(encoder->protected_->do_md5)
  103589. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  103590. if(!encoder->private_->is_being_deleted) {
  103591. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  103592. if(encoder->private_->seek_callback) {
  103593. #if FLAC__HAS_OGG
  103594. if(encoder->private_->is_ogg)
  103595. update_ogg_metadata_(encoder);
  103596. else
  103597. #endif
  103598. update_metadata_(encoder);
  103599. /* check if an error occurred while updating metadata */
  103600. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  103601. error = true;
  103602. }
  103603. if(encoder->private_->metadata_callback)
  103604. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  103605. }
  103606. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  103607. if(!error)
  103608. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  103609. error = true;
  103610. }
  103611. }
  103612. if(0 != encoder->private_->file) {
  103613. if(encoder->private_->file != stdout)
  103614. fclose(encoder->private_->file);
  103615. encoder->private_->file = 0;
  103616. }
  103617. #if FLAC__HAS_OGG
  103618. if(encoder->private_->is_ogg)
  103619. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  103620. #endif
  103621. free_(encoder);
  103622. set_defaults_enc(encoder);
  103623. if(!error)
  103624. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  103625. return !error;
  103626. }
  103627. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  103628. {
  103629. FLAC__ASSERT(0 != encoder);
  103630. FLAC__ASSERT(0 != encoder->private_);
  103631. FLAC__ASSERT(0 != encoder->protected_);
  103632. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103633. return false;
  103634. #if FLAC__HAS_OGG
  103635. /* can't check encoder->private_->is_ogg since that's not set until init time */
  103636. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  103637. return true;
  103638. #else
  103639. (void)value;
  103640. return false;
  103641. #endif
  103642. }
  103643. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103644. {
  103645. FLAC__ASSERT(0 != encoder);
  103646. FLAC__ASSERT(0 != encoder->private_);
  103647. FLAC__ASSERT(0 != encoder->protected_);
  103648. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103649. return false;
  103650. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  103651. encoder->protected_->verify = value;
  103652. #endif
  103653. return true;
  103654. }
  103655. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103656. {
  103657. FLAC__ASSERT(0 != encoder);
  103658. FLAC__ASSERT(0 != encoder->private_);
  103659. FLAC__ASSERT(0 != encoder->protected_);
  103660. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103661. return false;
  103662. encoder->protected_->streamable_subset = value;
  103663. return true;
  103664. }
  103665. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103666. {
  103667. FLAC__ASSERT(0 != encoder);
  103668. FLAC__ASSERT(0 != encoder->private_);
  103669. FLAC__ASSERT(0 != encoder->protected_);
  103670. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103671. return false;
  103672. encoder->protected_->do_md5 = value;
  103673. return true;
  103674. }
  103675. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  103676. {
  103677. FLAC__ASSERT(0 != encoder);
  103678. FLAC__ASSERT(0 != encoder->private_);
  103679. FLAC__ASSERT(0 != encoder->protected_);
  103680. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103681. return false;
  103682. encoder->protected_->channels = value;
  103683. return true;
  103684. }
  103685. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  103686. {
  103687. FLAC__ASSERT(0 != encoder);
  103688. FLAC__ASSERT(0 != encoder->private_);
  103689. FLAC__ASSERT(0 != encoder->protected_);
  103690. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103691. return false;
  103692. encoder->protected_->bits_per_sample = value;
  103693. return true;
  103694. }
  103695. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  103696. {
  103697. FLAC__ASSERT(0 != encoder);
  103698. FLAC__ASSERT(0 != encoder->private_);
  103699. FLAC__ASSERT(0 != encoder->protected_);
  103700. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103701. return false;
  103702. encoder->protected_->sample_rate = value;
  103703. return true;
  103704. }
  103705. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  103706. {
  103707. FLAC__bool ok = true;
  103708. FLAC__ASSERT(0 != encoder);
  103709. FLAC__ASSERT(0 != encoder->private_);
  103710. FLAC__ASSERT(0 != encoder->protected_);
  103711. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103712. return false;
  103713. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  103714. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  103715. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  103716. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  103717. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103718. #if 0
  103719. /* was: */
  103720. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  103721. /* but it's too hard to specify the string in a locale-specific way */
  103722. #else
  103723. encoder->protected_->num_apodizations = 1;
  103724. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103725. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103726. #endif
  103727. #endif
  103728. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  103729. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  103730. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  103731. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  103732. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  103733. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  103734. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  103735. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  103736. return ok;
  103737. }
  103738. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  103739. {
  103740. FLAC__ASSERT(0 != encoder);
  103741. FLAC__ASSERT(0 != encoder->private_);
  103742. FLAC__ASSERT(0 != encoder->protected_);
  103743. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103744. return false;
  103745. encoder->protected_->blocksize = value;
  103746. return true;
  103747. }
  103748. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103749. {
  103750. FLAC__ASSERT(0 != encoder);
  103751. FLAC__ASSERT(0 != encoder->private_);
  103752. FLAC__ASSERT(0 != encoder->protected_);
  103753. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103754. return false;
  103755. encoder->protected_->do_mid_side_stereo = value;
  103756. return true;
  103757. }
  103758. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103759. {
  103760. FLAC__ASSERT(0 != encoder);
  103761. FLAC__ASSERT(0 != encoder->private_);
  103762. FLAC__ASSERT(0 != encoder->protected_);
  103763. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103764. return false;
  103765. encoder->protected_->loose_mid_side_stereo = value;
  103766. return true;
  103767. }
  103768. /*@@@@add to tests*/
  103769. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  103770. {
  103771. FLAC__ASSERT(0 != encoder);
  103772. FLAC__ASSERT(0 != encoder->private_);
  103773. FLAC__ASSERT(0 != encoder->protected_);
  103774. FLAC__ASSERT(0 != specification);
  103775. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103776. return false;
  103777. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  103778. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  103779. #else
  103780. encoder->protected_->num_apodizations = 0;
  103781. while(1) {
  103782. const char *s = strchr(specification, ';');
  103783. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  103784. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  103785. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  103786. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  103787. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  103788. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  103789. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  103790. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  103791. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  103792. else if(n==6 && 0 == strncmp("connes" , specification, n))
  103793. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  103794. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  103795. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  103796. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  103797. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  103798. if (stddev > 0.0 && stddev <= 0.5) {
  103799. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  103800. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  103801. }
  103802. }
  103803. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  103804. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  103805. else if(n==4 && 0 == strncmp("hann" , specification, n))
  103806. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  103807. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  103808. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  103809. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  103810. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  103811. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  103812. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  103813. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  103814. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  103815. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  103816. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  103817. if (p >= 0.0 && p <= 1.0) {
  103818. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  103819. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  103820. }
  103821. }
  103822. else if(n==5 && 0 == strncmp("welch" , specification, n))
  103823. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  103824. if (encoder->protected_->num_apodizations == 32)
  103825. break;
  103826. if (s)
  103827. specification = s+1;
  103828. else
  103829. break;
  103830. }
  103831. if(encoder->protected_->num_apodizations == 0) {
  103832. encoder->protected_->num_apodizations = 1;
  103833. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  103834. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  103835. }
  103836. #endif
  103837. return true;
  103838. }
  103839. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  103840. {
  103841. FLAC__ASSERT(0 != encoder);
  103842. FLAC__ASSERT(0 != encoder->private_);
  103843. FLAC__ASSERT(0 != encoder->protected_);
  103844. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103845. return false;
  103846. encoder->protected_->max_lpc_order = value;
  103847. return true;
  103848. }
  103849. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  103850. {
  103851. FLAC__ASSERT(0 != encoder);
  103852. FLAC__ASSERT(0 != encoder->private_);
  103853. FLAC__ASSERT(0 != encoder->protected_);
  103854. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103855. return false;
  103856. encoder->protected_->qlp_coeff_precision = value;
  103857. return true;
  103858. }
  103859. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103860. {
  103861. FLAC__ASSERT(0 != encoder);
  103862. FLAC__ASSERT(0 != encoder->private_);
  103863. FLAC__ASSERT(0 != encoder->protected_);
  103864. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103865. return false;
  103866. encoder->protected_->do_qlp_coeff_prec_search = value;
  103867. return true;
  103868. }
  103869. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(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. #if 0
  103877. /*@@@ deprecated: */
  103878. encoder->protected_->do_escape_coding = value;
  103879. #else
  103880. (void)value;
  103881. #endif
  103882. return true;
  103883. }
  103884. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103885. {
  103886. FLAC__ASSERT(0 != encoder);
  103887. FLAC__ASSERT(0 != encoder->private_);
  103888. FLAC__ASSERT(0 != encoder->protected_);
  103889. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103890. return false;
  103891. encoder->protected_->do_exhaustive_model_search = value;
  103892. return true;
  103893. }
  103894. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103895. {
  103896. FLAC__ASSERT(0 != encoder);
  103897. FLAC__ASSERT(0 != encoder->private_);
  103898. FLAC__ASSERT(0 != encoder->protected_);
  103899. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103900. return false;
  103901. encoder->protected_->min_residual_partition_order = value;
  103902. return true;
  103903. }
  103904. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  103905. {
  103906. FLAC__ASSERT(0 != encoder);
  103907. FLAC__ASSERT(0 != encoder->private_);
  103908. FLAC__ASSERT(0 != encoder->protected_);
  103909. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103910. return false;
  103911. encoder->protected_->max_residual_partition_order = value;
  103912. return true;
  103913. }
  103914. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned 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. #if 0
  103922. /*@@@ deprecated: */
  103923. encoder->protected_->rice_parameter_search_dist = value;
  103924. #else
  103925. (void)value;
  103926. #endif
  103927. return true;
  103928. }
  103929. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  103930. {
  103931. FLAC__ASSERT(0 != encoder);
  103932. FLAC__ASSERT(0 != encoder->private_);
  103933. FLAC__ASSERT(0 != encoder->protected_);
  103934. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103935. return false;
  103936. encoder->protected_->total_samples_estimate = value;
  103937. return true;
  103938. }
  103939. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  103940. {
  103941. FLAC__ASSERT(0 != encoder);
  103942. FLAC__ASSERT(0 != encoder->private_);
  103943. FLAC__ASSERT(0 != encoder->protected_);
  103944. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103945. return false;
  103946. if(0 == metadata)
  103947. num_blocks = 0;
  103948. if(0 == num_blocks)
  103949. metadata = 0;
  103950. /* realloc() does not do exactly what we want so... */
  103951. if(encoder->protected_->metadata) {
  103952. free(encoder->protected_->metadata);
  103953. encoder->protected_->metadata = 0;
  103954. encoder->protected_->num_metadata_blocks = 0;
  103955. }
  103956. if(num_blocks) {
  103957. FLAC__StreamMetadata **m;
  103958. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  103959. return false;
  103960. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  103961. encoder->protected_->metadata = m;
  103962. encoder->protected_->num_metadata_blocks = num_blocks;
  103963. }
  103964. #if FLAC__HAS_OGG
  103965. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  103966. return false;
  103967. #endif
  103968. return true;
  103969. }
  103970. /*
  103971. * These three functions are not static, but not publically exposed in
  103972. * include/FLAC/ either. They are used by the test suite.
  103973. */
  103974. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103975. {
  103976. FLAC__ASSERT(0 != encoder);
  103977. FLAC__ASSERT(0 != encoder->private_);
  103978. FLAC__ASSERT(0 != encoder->protected_);
  103979. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103980. return false;
  103981. encoder->private_->disable_constant_subframes = value;
  103982. return true;
  103983. }
  103984. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103985. {
  103986. FLAC__ASSERT(0 != encoder);
  103987. FLAC__ASSERT(0 != encoder->private_);
  103988. FLAC__ASSERT(0 != encoder->protected_);
  103989. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  103990. return false;
  103991. encoder->private_->disable_fixed_subframes = value;
  103992. return true;
  103993. }
  103994. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  103995. {
  103996. FLAC__ASSERT(0 != encoder);
  103997. FLAC__ASSERT(0 != encoder->private_);
  103998. FLAC__ASSERT(0 != encoder->protected_);
  103999. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  104000. return false;
  104001. encoder->private_->disable_verbatim_subframes = value;
  104002. return true;
  104003. }
  104004. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  104005. {
  104006. FLAC__ASSERT(0 != encoder);
  104007. FLAC__ASSERT(0 != encoder->private_);
  104008. FLAC__ASSERT(0 != encoder->protected_);
  104009. return encoder->protected_->state;
  104010. }
  104011. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  104012. {
  104013. FLAC__ASSERT(0 != encoder);
  104014. FLAC__ASSERT(0 != encoder->private_);
  104015. FLAC__ASSERT(0 != encoder->protected_);
  104016. if(encoder->protected_->verify)
  104017. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  104018. else
  104019. return FLAC__STREAM_DECODER_UNINITIALIZED;
  104020. }
  104021. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  104022. {
  104023. FLAC__ASSERT(0 != encoder);
  104024. FLAC__ASSERT(0 != encoder->private_);
  104025. FLAC__ASSERT(0 != encoder->protected_);
  104026. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  104027. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  104028. else
  104029. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  104030. }
  104031. 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)
  104032. {
  104033. FLAC__ASSERT(0 != encoder);
  104034. FLAC__ASSERT(0 != encoder->private_);
  104035. FLAC__ASSERT(0 != encoder->protected_);
  104036. if(0 != absolute_sample)
  104037. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  104038. if(0 != frame_number)
  104039. *frame_number = encoder->private_->verify.error_stats.frame_number;
  104040. if(0 != channel)
  104041. *channel = encoder->private_->verify.error_stats.channel;
  104042. if(0 != sample)
  104043. *sample = encoder->private_->verify.error_stats.sample;
  104044. if(0 != expected)
  104045. *expected = encoder->private_->verify.error_stats.expected;
  104046. if(0 != got)
  104047. *got = encoder->private_->verify.error_stats.got;
  104048. }
  104049. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  104050. {
  104051. FLAC__ASSERT(0 != encoder);
  104052. FLAC__ASSERT(0 != encoder->private_);
  104053. FLAC__ASSERT(0 != encoder->protected_);
  104054. return encoder->protected_->verify;
  104055. }
  104056. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  104057. {
  104058. FLAC__ASSERT(0 != encoder);
  104059. FLAC__ASSERT(0 != encoder->private_);
  104060. FLAC__ASSERT(0 != encoder->protected_);
  104061. return encoder->protected_->streamable_subset;
  104062. }
  104063. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  104064. {
  104065. FLAC__ASSERT(0 != encoder);
  104066. FLAC__ASSERT(0 != encoder->private_);
  104067. FLAC__ASSERT(0 != encoder->protected_);
  104068. return encoder->protected_->do_md5;
  104069. }
  104070. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  104071. {
  104072. FLAC__ASSERT(0 != encoder);
  104073. FLAC__ASSERT(0 != encoder->private_);
  104074. FLAC__ASSERT(0 != encoder->protected_);
  104075. return encoder->protected_->channels;
  104076. }
  104077. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  104078. {
  104079. FLAC__ASSERT(0 != encoder);
  104080. FLAC__ASSERT(0 != encoder->private_);
  104081. FLAC__ASSERT(0 != encoder->protected_);
  104082. return encoder->protected_->bits_per_sample;
  104083. }
  104084. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  104085. {
  104086. FLAC__ASSERT(0 != encoder);
  104087. FLAC__ASSERT(0 != encoder->private_);
  104088. FLAC__ASSERT(0 != encoder->protected_);
  104089. return encoder->protected_->sample_rate;
  104090. }
  104091. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  104092. {
  104093. FLAC__ASSERT(0 != encoder);
  104094. FLAC__ASSERT(0 != encoder->private_);
  104095. FLAC__ASSERT(0 != encoder->protected_);
  104096. return encoder->protected_->blocksize;
  104097. }
  104098. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104099. {
  104100. FLAC__ASSERT(0 != encoder);
  104101. FLAC__ASSERT(0 != encoder->private_);
  104102. FLAC__ASSERT(0 != encoder->protected_);
  104103. return encoder->protected_->do_mid_side_stereo;
  104104. }
  104105. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  104106. {
  104107. FLAC__ASSERT(0 != encoder);
  104108. FLAC__ASSERT(0 != encoder->private_);
  104109. FLAC__ASSERT(0 != encoder->protected_);
  104110. return encoder->protected_->loose_mid_side_stereo;
  104111. }
  104112. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  104113. {
  104114. FLAC__ASSERT(0 != encoder);
  104115. FLAC__ASSERT(0 != encoder->private_);
  104116. FLAC__ASSERT(0 != encoder->protected_);
  104117. return encoder->protected_->max_lpc_order;
  104118. }
  104119. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  104120. {
  104121. FLAC__ASSERT(0 != encoder);
  104122. FLAC__ASSERT(0 != encoder->private_);
  104123. FLAC__ASSERT(0 != encoder->protected_);
  104124. return encoder->protected_->qlp_coeff_precision;
  104125. }
  104126. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  104127. {
  104128. FLAC__ASSERT(0 != encoder);
  104129. FLAC__ASSERT(0 != encoder->private_);
  104130. FLAC__ASSERT(0 != encoder->protected_);
  104131. return encoder->protected_->do_qlp_coeff_prec_search;
  104132. }
  104133. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  104134. {
  104135. FLAC__ASSERT(0 != encoder);
  104136. FLAC__ASSERT(0 != encoder->private_);
  104137. FLAC__ASSERT(0 != encoder->protected_);
  104138. return encoder->protected_->do_escape_coding;
  104139. }
  104140. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  104141. {
  104142. FLAC__ASSERT(0 != encoder);
  104143. FLAC__ASSERT(0 != encoder->private_);
  104144. FLAC__ASSERT(0 != encoder->protected_);
  104145. return encoder->protected_->do_exhaustive_model_search;
  104146. }
  104147. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104148. {
  104149. FLAC__ASSERT(0 != encoder);
  104150. FLAC__ASSERT(0 != encoder->private_);
  104151. FLAC__ASSERT(0 != encoder->protected_);
  104152. return encoder->protected_->min_residual_partition_order;
  104153. }
  104154. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  104155. {
  104156. FLAC__ASSERT(0 != encoder);
  104157. FLAC__ASSERT(0 != encoder->private_);
  104158. FLAC__ASSERT(0 != encoder->protected_);
  104159. return encoder->protected_->max_residual_partition_order;
  104160. }
  104161. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  104162. {
  104163. FLAC__ASSERT(0 != encoder);
  104164. FLAC__ASSERT(0 != encoder->private_);
  104165. FLAC__ASSERT(0 != encoder->protected_);
  104166. return encoder->protected_->rice_parameter_search_dist;
  104167. }
  104168. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  104169. {
  104170. FLAC__ASSERT(0 != encoder);
  104171. FLAC__ASSERT(0 != encoder->private_);
  104172. FLAC__ASSERT(0 != encoder->protected_);
  104173. return encoder->protected_->total_samples_estimate;
  104174. }
  104175. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  104176. {
  104177. unsigned i, j = 0, channel;
  104178. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104179. FLAC__ASSERT(0 != encoder);
  104180. FLAC__ASSERT(0 != encoder->private_);
  104181. FLAC__ASSERT(0 != encoder->protected_);
  104182. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104183. do {
  104184. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  104185. if(encoder->protected_->verify)
  104186. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  104187. for(channel = 0; channel < channels; channel++)
  104188. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  104189. if(encoder->protected_->do_mid_side_stereo) {
  104190. FLAC__ASSERT(channels == 2);
  104191. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104192. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104193. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  104194. 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' ! */
  104195. }
  104196. }
  104197. else
  104198. j += n;
  104199. encoder->private_->current_sample_number += n;
  104200. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104201. if(encoder->private_->current_sample_number > blocksize) {
  104202. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  104203. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104204. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104205. return false;
  104206. /* move unprocessed overread samples to beginnings of arrays */
  104207. for(channel = 0; channel < channels; channel++)
  104208. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104209. if(encoder->protected_->do_mid_side_stereo) {
  104210. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104211. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104212. }
  104213. encoder->private_->current_sample_number = 1;
  104214. }
  104215. } while(j < samples);
  104216. return true;
  104217. }
  104218. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  104219. {
  104220. unsigned i, j, k, channel;
  104221. FLAC__int32 x, mid, side;
  104222. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  104223. FLAC__ASSERT(0 != encoder);
  104224. FLAC__ASSERT(0 != encoder->private_);
  104225. FLAC__ASSERT(0 != encoder->protected_);
  104226. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104227. j = k = 0;
  104228. /*
  104229. * we have several flavors of the same basic loop, optimized for
  104230. * different conditions:
  104231. */
  104232. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  104233. /*
  104234. * stereo coding: unroll channel loop
  104235. */
  104236. do {
  104237. if(encoder->protected_->verify)
  104238. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104239. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104240. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104241. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  104242. x = buffer[k++];
  104243. encoder->private_->integer_signal[1][i] = x;
  104244. mid += x;
  104245. side -= x;
  104246. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  104247. encoder->private_->integer_signal_mid_side[1][i] = side;
  104248. encoder->private_->integer_signal_mid_side[0][i] = mid;
  104249. }
  104250. encoder->private_->current_sample_number = i;
  104251. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104252. if(i > blocksize) {
  104253. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104254. return false;
  104255. /* move unprocessed overread samples to beginnings of arrays */
  104256. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104257. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104258. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  104259. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  104260. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  104261. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  104262. encoder->private_->current_sample_number = 1;
  104263. }
  104264. } while(j < samples);
  104265. }
  104266. else {
  104267. /*
  104268. * independent channel coding: buffer each channel in inner loop
  104269. */
  104270. do {
  104271. if(encoder->protected_->verify)
  104272. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  104273. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  104274. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  104275. for(channel = 0; channel < channels; channel++)
  104276. encoder->private_->integer_signal[channel][i] = buffer[k++];
  104277. }
  104278. encoder->private_->current_sample_number = i;
  104279. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  104280. if(i > blocksize) {
  104281. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  104282. return false;
  104283. /* move unprocessed overread samples to beginnings of arrays */
  104284. FLAC__ASSERT(i == blocksize+OVERREAD_);
  104285. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  104286. for(channel = 0; channel < channels; channel++)
  104287. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  104288. encoder->private_->current_sample_number = 1;
  104289. }
  104290. } while(j < samples);
  104291. }
  104292. return true;
  104293. }
  104294. /***********************************************************************
  104295. *
  104296. * Private class methods
  104297. *
  104298. ***********************************************************************/
  104299. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  104300. {
  104301. FLAC__ASSERT(0 != encoder);
  104302. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  104303. encoder->protected_->verify = true;
  104304. #else
  104305. encoder->protected_->verify = false;
  104306. #endif
  104307. encoder->protected_->streamable_subset = true;
  104308. encoder->protected_->do_md5 = true;
  104309. encoder->protected_->do_mid_side_stereo = false;
  104310. encoder->protected_->loose_mid_side_stereo = false;
  104311. encoder->protected_->channels = 2;
  104312. encoder->protected_->bits_per_sample = 16;
  104313. encoder->protected_->sample_rate = 44100;
  104314. encoder->protected_->blocksize = 0;
  104315. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104316. encoder->protected_->num_apodizations = 1;
  104317. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  104318. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  104319. #endif
  104320. encoder->protected_->max_lpc_order = 0;
  104321. encoder->protected_->qlp_coeff_precision = 0;
  104322. encoder->protected_->do_qlp_coeff_prec_search = false;
  104323. encoder->protected_->do_exhaustive_model_search = false;
  104324. encoder->protected_->do_escape_coding = false;
  104325. encoder->protected_->min_residual_partition_order = 0;
  104326. encoder->protected_->max_residual_partition_order = 0;
  104327. encoder->protected_->rice_parameter_search_dist = 0;
  104328. encoder->protected_->total_samples_estimate = 0;
  104329. encoder->protected_->metadata = 0;
  104330. encoder->protected_->num_metadata_blocks = 0;
  104331. encoder->private_->seek_table = 0;
  104332. encoder->private_->disable_constant_subframes = false;
  104333. encoder->private_->disable_fixed_subframes = false;
  104334. encoder->private_->disable_verbatim_subframes = false;
  104335. #if FLAC__HAS_OGG
  104336. encoder->private_->is_ogg = false;
  104337. #endif
  104338. encoder->private_->read_callback = 0;
  104339. encoder->private_->write_callback = 0;
  104340. encoder->private_->seek_callback = 0;
  104341. encoder->private_->tell_callback = 0;
  104342. encoder->private_->metadata_callback = 0;
  104343. encoder->private_->progress_callback = 0;
  104344. encoder->private_->client_data = 0;
  104345. #if FLAC__HAS_OGG
  104346. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  104347. #endif
  104348. }
  104349. void free_(FLAC__StreamEncoder *encoder)
  104350. {
  104351. unsigned i, channel;
  104352. FLAC__ASSERT(0 != encoder);
  104353. if(encoder->protected_->metadata) {
  104354. free(encoder->protected_->metadata);
  104355. encoder->protected_->metadata = 0;
  104356. encoder->protected_->num_metadata_blocks = 0;
  104357. }
  104358. for(i = 0; i < encoder->protected_->channels; i++) {
  104359. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  104360. free(encoder->private_->integer_signal_unaligned[i]);
  104361. encoder->private_->integer_signal_unaligned[i] = 0;
  104362. }
  104363. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104364. if(0 != encoder->private_->real_signal_unaligned[i]) {
  104365. free(encoder->private_->real_signal_unaligned[i]);
  104366. encoder->private_->real_signal_unaligned[i] = 0;
  104367. }
  104368. #endif
  104369. }
  104370. for(i = 0; i < 2; i++) {
  104371. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  104372. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  104373. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  104374. }
  104375. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104376. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  104377. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  104378. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  104379. }
  104380. #endif
  104381. }
  104382. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104383. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  104384. if(0 != encoder->private_->window_unaligned[i]) {
  104385. free(encoder->private_->window_unaligned[i]);
  104386. encoder->private_->window_unaligned[i] = 0;
  104387. }
  104388. }
  104389. if(0 != encoder->private_->windowed_signal_unaligned) {
  104390. free(encoder->private_->windowed_signal_unaligned);
  104391. encoder->private_->windowed_signal_unaligned = 0;
  104392. }
  104393. #endif
  104394. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  104395. for(i = 0; i < 2; i++) {
  104396. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  104397. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  104398. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  104399. }
  104400. }
  104401. }
  104402. for(channel = 0; channel < 2; channel++) {
  104403. for(i = 0; i < 2; i++) {
  104404. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  104405. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  104406. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  104407. }
  104408. }
  104409. }
  104410. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  104411. free(encoder->private_->abs_residual_partition_sums_unaligned);
  104412. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  104413. }
  104414. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  104415. free(encoder->private_->raw_bits_per_partition_unaligned);
  104416. encoder->private_->raw_bits_per_partition_unaligned = 0;
  104417. }
  104418. if(encoder->protected_->verify) {
  104419. for(i = 0; i < encoder->protected_->channels; i++) {
  104420. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  104421. free(encoder->private_->verify.input_fifo.data[i]);
  104422. encoder->private_->verify.input_fifo.data[i] = 0;
  104423. }
  104424. }
  104425. }
  104426. FLAC__bitwriter_free(encoder->private_->frame);
  104427. }
  104428. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  104429. {
  104430. FLAC__bool ok;
  104431. unsigned i, channel;
  104432. FLAC__ASSERT(new_blocksize > 0);
  104433. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104434. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  104435. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  104436. if(new_blocksize <= encoder->private_->input_capacity)
  104437. return true;
  104438. ok = true;
  104439. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  104440. * requires that the input arrays (in our case the integer signals)
  104441. * have a buffer of up to 3 zeroes in front (at negative indices) for
  104442. * alignment purposes; we use 4 in front to keep the data well-aligned.
  104443. */
  104444. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  104445. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  104446. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  104447. encoder->private_->integer_signal[i] += 4;
  104448. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104449. #if 0 /* @@@ currently unused */
  104450. if(encoder->protected_->max_lpc_order > 0)
  104451. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  104452. #endif
  104453. #endif
  104454. }
  104455. for(i = 0; ok && i < 2; i++) {
  104456. 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]);
  104457. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  104458. encoder->private_->integer_signal_mid_side[i] += 4;
  104459. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104460. #if 0 /* @@@ currently unused */
  104461. if(encoder->protected_->max_lpc_order > 0)
  104462. 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]);
  104463. #endif
  104464. #endif
  104465. }
  104466. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104467. if(ok && encoder->protected_->max_lpc_order > 0) {
  104468. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  104469. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  104470. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  104471. }
  104472. #endif
  104473. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  104474. for(i = 0; ok && i < 2; i++) {
  104475. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  104476. }
  104477. }
  104478. for(channel = 0; ok && channel < 2; channel++) {
  104479. for(i = 0; ok && i < 2; i++) {
  104480. 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]);
  104481. }
  104482. }
  104483. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  104484. /*@@@ 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) */
  104485. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  104486. if(encoder->protected_->do_escape_coding)
  104487. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  104488. /* now adjust the windows if the blocksize has changed */
  104489. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  104490. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  104491. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  104492. switch(encoder->protected_->apodizations[i].type) {
  104493. case FLAC__APODIZATION_BARTLETT:
  104494. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  104495. break;
  104496. case FLAC__APODIZATION_BARTLETT_HANN:
  104497. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  104498. break;
  104499. case FLAC__APODIZATION_BLACKMAN:
  104500. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  104501. break;
  104502. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  104503. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  104504. break;
  104505. case FLAC__APODIZATION_CONNES:
  104506. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  104507. break;
  104508. case FLAC__APODIZATION_FLATTOP:
  104509. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  104510. break;
  104511. case FLAC__APODIZATION_GAUSS:
  104512. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  104513. break;
  104514. case FLAC__APODIZATION_HAMMING:
  104515. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  104516. break;
  104517. case FLAC__APODIZATION_HANN:
  104518. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104519. break;
  104520. case FLAC__APODIZATION_KAISER_BESSEL:
  104521. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  104522. break;
  104523. case FLAC__APODIZATION_NUTTALL:
  104524. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  104525. break;
  104526. case FLAC__APODIZATION_RECTANGLE:
  104527. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  104528. break;
  104529. case FLAC__APODIZATION_TRIANGLE:
  104530. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  104531. break;
  104532. case FLAC__APODIZATION_TUKEY:
  104533. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  104534. break;
  104535. case FLAC__APODIZATION_WELCH:
  104536. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  104537. break;
  104538. default:
  104539. FLAC__ASSERT(0);
  104540. /* double protection */
  104541. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  104542. break;
  104543. }
  104544. }
  104545. }
  104546. #endif
  104547. if(ok)
  104548. encoder->private_->input_capacity = new_blocksize;
  104549. else
  104550. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104551. return ok;
  104552. }
  104553. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  104554. {
  104555. const FLAC__byte *buffer;
  104556. size_t bytes;
  104557. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  104558. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  104559. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104560. return false;
  104561. }
  104562. if(encoder->protected_->verify) {
  104563. encoder->private_->verify.output.data = buffer;
  104564. encoder->private_->verify.output.bytes = bytes;
  104565. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  104566. encoder->private_->verify.needs_magic_hack = true;
  104567. }
  104568. else {
  104569. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  104570. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104571. FLAC__bitwriter_clear(encoder->private_->frame);
  104572. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  104573. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  104574. return false;
  104575. }
  104576. }
  104577. }
  104578. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104579. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104580. FLAC__bitwriter_clear(encoder->private_->frame);
  104581. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104582. return false;
  104583. }
  104584. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  104585. FLAC__bitwriter_clear(encoder->private_->frame);
  104586. if(samples > 0) {
  104587. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  104588. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  104589. }
  104590. return true;
  104591. }
  104592. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  104593. {
  104594. FLAC__StreamEncoderWriteStatus status;
  104595. FLAC__uint64 output_position = 0;
  104596. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  104597. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  104598. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104599. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  104600. }
  104601. /*
  104602. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  104603. */
  104604. if(samples == 0) {
  104605. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  104606. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  104607. encoder->protected_->streaminfo_offset = output_position;
  104608. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  104609. encoder->protected_->seektable_offset = output_position;
  104610. }
  104611. /*
  104612. * Mark the current seek point if hit (if audio_offset == 0 that
  104613. * means we're still writing metadata and haven't hit the first
  104614. * frame yet)
  104615. */
  104616. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  104617. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  104618. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  104619. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  104620. FLAC__uint64 test_sample;
  104621. unsigned i;
  104622. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  104623. test_sample = encoder->private_->seek_table->points[i].sample_number;
  104624. if(test_sample > frame_last_sample) {
  104625. break;
  104626. }
  104627. else if(test_sample >= frame_first_sample) {
  104628. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  104629. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  104630. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  104631. encoder->private_->first_seekpoint_to_check++;
  104632. /* DO NOT: "break;" and here's why:
  104633. * The seektable template may contain more than one target
  104634. * sample for any given frame; we will keep looping, generating
  104635. * duplicate seekpoints for them, and we'll clean it up later,
  104636. * just before writing the seektable back to the metadata.
  104637. */
  104638. }
  104639. else {
  104640. encoder->private_->first_seekpoint_to_check++;
  104641. }
  104642. }
  104643. }
  104644. #if FLAC__HAS_OGG
  104645. if(encoder->private_->is_ogg) {
  104646. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  104647. &encoder->protected_->ogg_encoder_aspect,
  104648. buffer,
  104649. bytes,
  104650. samples,
  104651. encoder->private_->current_frame_number,
  104652. is_last_block,
  104653. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  104654. encoder,
  104655. encoder->private_->client_data
  104656. );
  104657. }
  104658. else
  104659. #endif
  104660. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  104661. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104662. encoder->private_->bytes_written += bytes;
  104663. encoder->private_->samples_written += samples;
  104664. /* we keep a high watermark on the number of frames written because
  104665. * when the encoder goes back to write metadata, 'current_frame'
  104666. * will drop back to 0.
  104667. */
  104668. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  104669. }
  104670. else
  104671. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104672. return status;
  104673. }
  104674. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104675. void update_metadata_(const FLAC__StreamEncoder *encoder)
  104676. {
  104677. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104678. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104679. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104680. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104681. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104682. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  104683. FLAC__StreamEncoderSeekStatus seek_status;
  104684. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104685. /* All this is based on intimate knowledge of the stream header
  104686. * layout, but a change to the header format that would break this
  104687. * would also break all streams encoded in the previous format.
  104688. */
  104689. /*
  104690. * Write MD5 signature
  104691. */
  104692. {
  104693. const unsigned md5_offset =
  104694. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104695. (
  104696. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104697. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104698. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104699. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104700. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104701. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104702. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104703. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104704. ) / 8;
  104705. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  104706. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104707. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104708. return;
  104709. }
  104710. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104711. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104712. return;
  104713. }
  104714. }
  104715. /*
  104716. * Write total samples
  104717. */
  104718. {
  104719. const unsigned total_samples_byte_offset =
  104720. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104721. (
  104722. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104723. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104724. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104725. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104726. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104727. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104728. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104729. - 4
  104730. ) / 8;
  104731. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  104732. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104733. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104734. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104735. b[4] = (FLAC__byte)(samples & 0xFF);
  104736. 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) {
  104737. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104738. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104739. return;
  104740. }
  104741. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104742. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104743. return;
  104744. }
  104745. }
  104746. /*
  104747. * Write min/max framesize
  104748. */
  104749. {
  104750. const unsigned min_framesize_offset =
  104751. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104752. (
  104753. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104754. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104755. ) / 8;
  104756. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104757. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104758. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104759. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104760. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104761. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104762. 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) {
  104763. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104764. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104765. return;
  104766. }
  104767. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104768. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104769. return;
  104770. }
  104771. }
  104772. /*
  104773. * Write seektable
  104774. */
  104775. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104776. unsigned i;
  104777. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104778. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104779. 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) {
  104780. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  104781. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104782. return;
  104783. }
  104784. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  104785. FLAC__uint64 xx;
  104786. unsigned x;
  104787. xx = encoder->private_->seek_table->points[i].sample_number;
  104788. b[7] = (FLAC__byte)xx; xx >>= 8;
  104789. b[6] = (FLAC__byte)xx; xx >>= 8;
  104790. b[5] = (FLAC__byte)xx; xx >>= 8;
  104791. b[4] = (FLAC__byte)xx; xx >>= 8;
  104792. b[3] = (FLAC__byte)xx; xx >>= 8;
  104793. b[2] = (FLAC__byte)xx; xx >>= 8;
  104794. b[1] = (FLAC__byte)xx; xx >>= 8;
  104795. b[0] = (FLAC__byte)xx; xx >>= 8;
  104796. xx = encoder->private_->seek_table->points[i].stream_offset;
  104797. b[15] = (FLAC__byte)xx; xx >>= 8;
  104798. b[14] = (FLAC__byte)xx; xx >>= 8;
  104799. b[13] = (FLAC__byte)xx; xx >>= 8;
  104800. b[12] = (FLAC__byte)xx; xx >>= 8;
  104801. b[11] = (FLAC__byte)xx; xx >>= 8;
  104802. b[10] = (FLAC__byte)xx; xx >>= 8;
  104803. b[9] = (FLAC__byte)xx; xx >>= 8;
  104804. b[8] = (FLAC__byte)xx; xx >>= 8;
  104805. x = encoder->private_->seek_table->points[i].frame_samples;
  104806. b[17] = (FLAC__byte)x; x >>= 8;
  104807. b[16] = (FLAC__byte)x; x >>= 8;
  104808. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  104809. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  104810. return;
  104811. }
  104812. }
  104813. }
  104814. }
  104815. #if FLAC__HAS_OGG
  104816. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  104817. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  104818. {
  104819. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  104820. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  104821. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  104822. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  104823. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  104824. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  104825. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  104826. FLAC__STREAM_SYNC_LENGTH
  104827. ;
  104828. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  104829. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  104830. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  104831. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  104832. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  104833. ogg_page page;
  104834. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  104835. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  104836. /* Pre-check that client supports seeking, since we don't want the
  104837. * ogg_helper code to ever have to deal with this condition.
  104838. */
  104839. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  104840. return;
  104841. /* All this is based on intimate knowledge of the stream header
  104842. * layout, but a change to the header format that would break this
  104843. * would also break all streams encoded in the previous format.
  104844. */
  104845. /**
  104846. ** Write STREAMINFO stats
  104847. **/
  104848. simple_ogg_page__init(&page);
  104849. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104850. simple_ogg_page__clear(&page);
  104851. return; /* state already set */
  104852. }
  104853. /*
  104854. * Write MD5 signature
  104855. */
  104856. {
  104857. const unsigned md5_offset =
  104858. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104859. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104860. (
  104861. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104862. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104863. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104864. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104865. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104866. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104867. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  104868. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  104869. ) / 8;
  104870. if(md5_offset + 16 > (unsigned)page.body_len) {
  104871. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104872. simple_ogg_page__clear(&page);
  104873. return;
  104874. }
  104875. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  104876. }
  104877. /*
  104878. * Write total samples
  104879. */
  104880. {
  104881. const unsigned total_samples_byte_offset =
  104882. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104883. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104884. (
  104885. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104886. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  104887. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  104888. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  104889. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  104890. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  104891. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  104892. - 4
  104893. ) / 8;
  104894. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  104895. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104896. simple_ogg_page__clear(&page);
  104897. return;
  104898. }
  104899. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  104900. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  104901. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  104902. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  104903. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  104904. b[4] = (FLAC__byte)(samples & 0xFF);
  104905. memcpy(page.body + total_samples_byte_offset, b, 5);
  104906. }
  104907. /*
  104908. * Write min/max framesize
  104909. */
  104910. {
  104911. const unsigned min_framesize_offset =
  104912. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  104913. FLAC__STREAM_METADATA_HEADER_LENGTH +
  104914. (
  104915. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  104916. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  104917. ) / 8;
  104918. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  104919. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104920. simple_ogg_page__clear(&page);
  104921. return;
  104922. }
  104923. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  104924. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  104925. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  104926. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  104927. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  104928. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  104929. memcpy(page.body + min_framesize_offset, b, 6);
  104930. }
  104931. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104932. simple_ogg_page__clear(&page);
  104933. return; /* state already set */
  104934. }
  104935. simple_ogg_page__clear(&page);
  104936. /*
  104937. * Write seektable
  104938. */
  104939. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  104940. unsigned i;
  104941. FLAC__byte *p;
  104942. FLAC__format_seektable_sort(encoder->private_->seek_table);
  104943. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  104944. simple_ogg_page__init(&page);
  104945. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  104946. simple_ogg_page__clear(&page);
  104947. return; /* state already set */
  104948. }
  104949. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  104950. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  104951. simple_ogg_page__clear(&page);
  104952. return;
  104953. }
  104954. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  104955. FLAC__uint64 xx;
  104956. unsigned x;
  104957. xx = encoder->private_->seek_table->points[i].sample_number;
  104958. b[7] = (FLAC__byte)xx; xx >>= 8;
  104959. b[6] = (FLAC__byte)xx; xx >>= 8;
  104960. b[5] = (FLAC__byte)xx; xx >>= 8;
  104961. b[4] = (FLAC__byte)xx; xx >>= 8;
  104962. b[3] = (FLAC__byte)xx; xx >>= 8;
  104963. b[2] = (FLAC__byte)xx; xx >>= 8;
  104964. b[1] = (FLAC__byte)xx; xx >>= 8;
  104965. b[0] = (FLAC__byte)xx; xx >>= 8;
  104966. xx = encoder->private_->seek_table->points[i].stream_offset;
  104967. b[15] = (FLAC__byte)xx; xx >>= 8;
  104968. b[14] = (FLAC__byte)xx; xx >>= 8;
  104969. b[13] = (FLAC__byte)xx; xx >>= 8;
  104970. b[12] = (FLAC__byte)xx; xx >>= 8;
  104971. b[11] = (FLAC__byte)xx; xx >>= 8;
  104972. b[10] = (FLAC__byte)xx; xx >>= 8;
  104973. b[9] = (FLAC__byte)xx; xx >>= 8;
  104974. b[8] = (FLAC__byte)xx; xx >>= 8;
  104975. x = encoder->private_->seek_table->points[i].frame_samples;
  104976. b[17] = (FLAC__byte)x; x >>= 8;
  104977. b[16] = (FLAC__byte)x; x >>= 8;
  104978. memcpy(p, b, 18);
  104979. }
  104980. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  104981. simple_ogg_page__clear(&page);
  104982. return; /* state already set */
  104983. }
  104984. simple_ogg_page__clear(&page);
  104985. }
  104986. }
  104987. #endif
  104988. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  104989. {
  104990. FLAC__uint16 crc;
  104991. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  104992. /*
  104993. * Accumulate raw signal to the MD5 signature
  104994. */
  104995. 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)) {
  104996. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  104997. return false;
  104998. }
  104999. /*
  105000. * Process the frame header and subframes into the frame bitbuffer
  105001. */
  105002. if(!process_subframes_(encoder, is_fractional_block)) {
  105003. /* the above function sets the state for us in case of an error */
  105004. return false;
  105005. }
  105006. /*
  105007. * Zero-pad the frame to a byte_boundary
  105008. */
  105009. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  105010. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  105011. return false;
  105012. }
  105013. /*
  105014. * CRC-16 the whole thing
  105015. */
  105016. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  105017. if(
  105018. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  105019. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  105020. ) {
  105021. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  105022. return false;
  105023. }
  105024. /*
  105025. * Write it
  105026. */
  105027. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  105028. /* the above function sets the state for us in case of an error */
  105029. return false;
  105030. }
  105031. /*
  105032. * Get ready for the next frame
  105033. */
  105034. encoder->private_->current_sample_number = 0;
  105035. encoder->private_->current_frame_number++;
  105036. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  105037. return true;
  105038. }
  105039. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  105040. {
  105041. FLAC__FrameHeader frame_header;
  105042. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  105043. FLAC__bool do_independent, do_mid_side;
  105044. /*
  105045. * Calculate the min,max Rice partition orders
  105046. */
  105047. if(is_fractional_block) {
  105048. max_partition_order = 0;
  105049. }
  105050. else {
  105051. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  105052. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  105053. }
  105054. min_partition_order = min(min_partition_order, max_partition_order);
  105055. /*
  105056. * Setup the frame
  105057. */
  105058. frame_header.blocksize = encoder->protected_->blocksize;
  105059. frame_header.sample_rate = encoder->protected_->sample_rate;
  105060. frame_header.channels = encoder->protected_->channels;
  105061. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  105062. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  105063. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  105064. frame_header.number.frame_number = encoder->private_->current_frame_number;
  105065. /*
  105066. * Figure out what channel assignments to try
  105067. */
  105068. if(encoder->protected_->do_mid_side_stereo) {
  105069. if(encoder->protected_->loose_mid_side_stereo) {
  105070. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  105071. do_independent = true;
  105072. do_mid_side = true;
  105073. }
  105074. else {
  105075. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  105076. do_mid_side = !do_independent;
  105077. }
  105078. }
  105079. else {
  105080. do_independent = true;
  105081. do_mid_side = true;
  105082. }
  105083. }
  105084. else {
  105085. do_independent = true;
  105086. do_mid_side = false;
  105087. }
  105088. FLAC__ASSERT(do_independent || do_mid_side);
  105089. /*
  105090. * Check for wasted bits; set effective bps for each subframe
  105091. */
  105092. if(do_independent) {
  105093. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105094. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  105095. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  105096. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  105097. }
  105098. }
  105099. if(do_mid_side) {
  105100. FLAC__ASSERT(encoder->protected_->channels == 2);
  105101. for(channel = 0; channel < 2; channel++) {
  105102. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  105103. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  105104. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  105105. }
  105106. }
  105107. /*
  105108. * First do a normal encoding pass of each independent channel
  105109. */
  105110. if(do_independent) {
  105111. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105112. if(!
  105113. process_subframe_(
  105114. encoder,
  105115. min_partition_order,
  105116. max_partition_order,
  105117. &frame_header,
  105118. encoder->private_->subframe_bps[channel],
  105119. encoder->private_->integer_signal[channel],
  105120. encoder->private_->subframe_workspace_ptr[channel],
  105121. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  105122. encoder->private_->residual_workspace[channel],
  105123. encoder->private_->best_subframe+channel,
  105124. encoder->private_->best_subframe_bits+channel
  105125. )
  105126. )
  105127. return false;
  105128. }
  105129. }
  105130. /*
  105131. * Now do mid and side channels if requested
  105132. */
  105133. if(do_mid_side) {
  105134. FLAC__ASSERT(encoder->protected_->channels == 2);
  105135. for(channel = 0; channel < 2; channel++) {
  105136. if(!
  105137. process_subframe_(
  105138. encoder,
  105139. min_partition_order,
  105140. max_partition_order,
  105141. &frame_header,
  105142. encoder->private_->subframe_bps_mid_side[channel],
  105143. encoder->private_->integer_signal_mid_side[channel],
  105144. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  105145. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  105146. encoder->private_->residual_workspace_mid_side[channel],
  105147. encoder->private_->best_subframe_mid_side+channel,
  105148. encoder->private_->best_subframe_bits_mid_side+channel
  105149. )
  105150. )
  105151. return false;
  105152. }
  105153. }
  105154. /*
  105155. * Compose the frame bitbuffer
  105156. */
  105157. if(do_mid_side) {
  105158. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  105159. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  105160. FLAC__ChannelAssignment channel_assignment;
  105161. FLAC__ASSERT(encoder->protected_->channels == 2);
  105162. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  105163. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  105164. }
  105165. else {
  105166. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  105167. unsigned min_bits;
  105168. int ca;
  105169. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  105170. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  105171. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  105172. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  105173. FLAC__ASSERT(do_independent && do_mid_side);
  105174. /* We have to figure out which channel assignent results in the smallest frame */
  105175. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  105176. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  105177. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  105178. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  105179. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  105180. min_bits = bits[channel_assignment];
  105181. for(ca = 1; ca <= 3; ca++) {
  105182. if(bits[ca] < min_bits) {
  105183. min_bits = bits[ca];
  105184. channel_assignment = (FLAC__ChannelAssignment)ca;
  105185. }
  105186. }
  105187. }
  105188. frame_header.channel_assignment = channel_assignment;
  105189. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105190. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105191. return false;
  105192. }
  105193. switch(channel_assignment) {
  105194. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105195. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105196. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105197. break;
  105198. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105199. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  105200. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105201. break;
  105202. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105203. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105204. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  105205. break;
  105206. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105207. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  105208. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  105209. break;
  105210. default:
  105211. FLAC__ASSERT(0);
  105212. }
  105213. switch(channel_assignment) {
  105214. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  105215. left_bps = encoder->private_->subframe_bps [0];
  105216. right_bps = encoder->private_->subframe_bps [1];
  105217. break;
  105218. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  105219. left_bps = encoder->private_->subframe_bps [0];
  105220. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105221. break;
  105222. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  105223. left_bps = encoder->private_->subframe_bps_mid_side[1];
  105224. right_bps = encoder->private_->subframe_bps [1];
  105225. break;
  105226. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  105227. left_bps = encoder->private_->subframe_bps_mid_side[0];
  105228. right_bps = encoder->private_->subframe_bps_mid_side[1];
  105229. break;
  105230. default:
  105231. FLAC__ASSERT(0);
  105232. }
  105233. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  105234. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  105235. return false;
  105236. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  105237. return false;
  105238. }
  105239. else {
  105240. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  105241. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105242. return false;
  105243. }
  105244. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  105245. 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)) {
  105246. /* the above function sets the state for us in case of an error */
  105247. return false;
  105248. }
  105249. }
  105250. }
  105251. if(encoder->protected_->loose_mid_side_stereo) {
  105252. encoder->private_->loose_mid_side_stereo_frame_count++;
  105253. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  105254. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  105255. }
  105256. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  105257. return true;
  105258. }
  105259. FLAC__bool process_subframe_(
  105260. FLAC__StreamEncoder *encoder,
  105261. unsigned min_partition_order,
  105262. unsigned max_partition_order,
  105263. const FLAC__FrameHeader *frame_header,
  105264. unsigned subframe_bps,
  105265. const FLAC__int32 integer_signal[],
  105266. FLAC__Subframe *subframe[2],
  105267. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  105268. FLAC__int32 *residual[2],
  105269. unsigned *best_subframe,
  105270. unsigned *best_bits
  105271. )
  105272. {
  105273. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105274. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105275. #else
  105276. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  105277. #endif
  105278. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105279. FLAC__double lpc_residual_bits_per_sample;
  105280. 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 */
  105281. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  105282. unsigned min_lpc_order, max_lpc_order, lpc_order;
  105283. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  105284. #endif
  105285. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  105286. unsigned rice_parameter;
  105287. unsigned _candidate_bits, _best_bits;
  105288. unsigned _best_subframe;
  105289. /* only use RICE2 partitions if stream bps > 16 */
  105290. 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;
  105291. FLAC__ASSERT(frame_header->blocksize > 0);
  105292. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  105293. _best_subframe = 0;
  105294. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  105295. _best_bits = UINT_MAX;
  105296. else
  105297. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105298. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  105299. unsigned signal_is_constant = false;
  105300. 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);
  105301. /* check for constant subframe */
  105302. if(
  105303. !encoder->private_->disable_constant_subframes &&
  105304. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105305. fixed_residual_bits_per_sample[1] == 0.0
  105306. #else
  105307. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  105308. #endif
  105309. ) {
  105310. /* the above means it's possible all samples are the same value; now double-check it: */
  105311. unsigned i;
  105312. signal_is_constant = true;
  105313. for(i = 1; i < frame_header->blocksize; i++) {
  105314. if(integer_signal[0] != integer_signal[i]) {
  105315. signal_is_constant = false;
  105316. break;
  105317. }
  105318. }
  105319. }
  105320. if(signal_is_constant) {
  105321. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  105322. if(_candidate_bits < _best_bits) {
  105323. _best_subframe = !_best_subframe;
  105324. _best_bits = _candidate_bits;
  105325. }
  105326. }
  105327. else {
  105328. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  105329. /* encode fixed */
  105330. if(encoder->protected_->do_exhaustive_model_search) {
  105331. min_fixed_order = 0;
  105332. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  105333. }
  105334. else {
  105335. min_fixed_order = max_fixed_order = guess_fixed_order;
  105336. }
  105337. if(max_fixed_order >= frame_header->blocksize)
  105338. max_fixed_order = frame_header->blocksize - 1;
  105339. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  105340. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105341. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  105342. continue; /* don't even try */
  105343. 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 */
  105344. #else
  105345. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  105346. continue; /* don't even try */
  105347. 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 */
  105348. #endif
  105349. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105350. if(rice_parameter >= rice_parameter_limit) {
  105351. #ifdef DEBUG_VERBOSE
  105352. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  105353. #endif
  105354. rice_parameter = rice_parameter_limit - 1;
  105355. }
  105356. _candidate_bits =
  105357. evaluate_fixed_subframe_(
  105358. encoder,
  105359. integer_signal,
  105360. residual[!_best_subframe],
  105361. encoder->private_->abs_residual_partition_sums,
  105362. encoder->private_->raw_bits_per_partition,
  105363. frame_header->blocksize,
  105364. subframe_bps,
  105365. fixed_order,
  105366. rice_parameter,
  105367. rice_parameter_limit,
  105368. min_partition_order,
  105369. max_partition_order,
  105370. encoder->protected_->do_escape_coding,
  105371. encoder->protected_->rice_parameter_search_dist,
  105372. subframe[!_best_subframe],
  105373. partitioned_rice_contents[!_best_subframe]
  105374. );
  105375. if(_candidate_bits < _best_bits) {
  105376. _best_subframe = !_best_subframe;
  105377. _best_bits = _candidate_bits;
  105378. }
  105379. }
  105380. }
  105381. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105382. /* encode lpc */
  105383. if(encoder->protected_->max_lpc_order > 0) {
  105384. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  105385. max_lpc_order = frame_header->blocksize-1;
  105386. else
  105387. max_lpc_order = encoder->protected_->max_lpc_order;
  105388. if(max_lpc_order > 0) {
  105389. unsigned a;
  105390. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  105391. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  105392. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  105393. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  105394. if(autoc[0] != 0.0) {
  105395. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  105396. if(encoder->protected_->do_exhaustive_model_search) {
  105397. min_lpc_order = 1;
  105398. }
  105399. else {
  105400. const unsigned guess_lpc_order =
  105401. FLAC__lpc_compute_best_order(
  105402. lpc_error,
  105403. max_lpc_order,
  105404. frame_header->blocksize,
  105405. subframe_bps + (
  105406. encoder->protected_->do_qlp_coeff_prec_search?
  105407. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  105408. encoder->protected_->qlp_coeff_precision
  105409. )
  105410. );
  105411. min_lpc_order = max_lpc_order = guess_lpc_order;
  105412. }
  105413. if(max_lpc_order >= frame_header->blocksize)
  105414. max_lpc_order = frame_header->blocksize - 1;
  105415. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  105416. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  105417. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  105418. continue; /* don't even try */
  105419. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  105420. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  105421. if(rice_parameter >= rice_parameter_limit) {
  105422. #ifdef DEBUG_VERBOSE
  105423. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  105424. #endif
  105425. rice_parameter = rice_parameter_limit - 1;
  105426. }
  105427. if(encoder->protected_->do_qlp_coeff_prec_search) {
  105428. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  105429. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  105430. if(subframe_bps <= 17) {
  105431. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  105432. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  105433. }
  105434. else
  105435. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  105436. }
  105437. else {
  105438. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  105439. }
  105440. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  105441. _candidate_bits =
  105442. evaluate_lpc_subframe_(
  105443. encoder,
  105444. integer_signal,
  105445. residual[!_best_subframe],
  105446. encoder->private_->abs_residual_partition_sums,
  105447. encoder->private_->raw_bits_per_partition,
  105448. encoder->private_->lp_coeff[lpc_order-1],
  105449. frame_header->blocksize,
  105450. subframe_bps,
  105451. lpc_order,
  105452. qlp_coeff_precision,
  105453. rice_parameter,
  105454. rice_parameter_limit,
  105455. min_partition_order,
  105456. max_partition_order,
  105457. encoder->protected_->do_escape_coding,
  105458. encoder->protected_->rice_parameter_search_dist,
  105459. subframe[!_best_subframe],
  105460. partitioned_rice_contents[!_best_subframe]
  105461. );
  105462. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  105463. if(_candidate_bits < _best_bits) {
  105464. _best_subframe = !_best_subframe;
  105465. _best_bits = _candidate_bits;
  105466. }
  105467. }
  105468. }
  105469. }
  105470. }
  105471. }
  105472. }
  105473. }
  105474. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  105475. }
  105476. }
  105477. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  105478. if(_best_bits == UINT_MAX) {
  105479. FLAC__ASSERT(_best_subframe == 0);
  105480. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  105481. }
  105482. *best_subframe = _best_subframe;
  105483. *best_bits = _best_bits;
  105484. return true;
  105485. }
  105486. FLAC__bool add_subframe_(
  105487. FLAC__StreamEncoder *encoder,
  105488. unsigned blocksize,
  105489. unsigned subframe_bps,
  105490. const FLAC__Subframe *subframe,
  105491. FLAC__BitWriter *frame
  105492. )
  105493. {
  105494. switch(subframe->type) {
  105495. case FLAC__SUBFRAME_TYPE_CONSTANT:
  105496. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  105497. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105498. return false;
  105499. }
  105500. break;
  105501. case FLAC__SUBFRAME_TYPE_FIXED:
  105502. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  105503. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105504. return false;
  105505. }
  105506. break;
  105507. case FLAC__SUBFRAME_TYPE_LPC:
  105508. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  105509. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105510. return false;
  105511. }
  105512. break;
  105513. case FLAC__SUBFRAME_TYPE_VERBATIM:
  105514. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  105515. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  105516. return false;
  105517. }
  105518. break;
  105519. default:
  105520. FLAC__ASSERT(0);
  105521. }
  105522. return true;
  105523. }
  105524. #define SPOTCHECK_ESTIMATE 0
  105525. #if SPOTCHECK_ESTIMATE
  105526. static void spotcheck_subframe_estimate_(
  105527. FLAC__StreamEncoder *encoder,
  105528. unsigned blocksize,
  105529. unsigned subframe_bps,
  105530. const FLAC__Subframe *subframe,
  105531. unsigned estimate
  105532. )
  105533. {
  105534. FLAC__bool ret;
  105535. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  105536. if(frame == 0) {
  105537. fprintf(stderr, "EST: can't allocate frame\n");
  105538. return;
  105539. }
  105540. if(!FLAC__bitwriter_init(frame)) {
  105541. fprintf(stderr, "EST: can't init frame\n");
  105542. return;
  105543. }
  105544. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  105545. FLAC__ASSERT(ret);
  105546. {
  105547. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  105548. if(estimate != actual)
  105549. 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);
  105550. }
  105551. FLAC__bitwriter_delete(frame);
  105552. }
  105553. #endif
  105554. unsigned evaluate_constant_subframe_(
  105555. FLAC__StreamEncoder *encoder,
  105556. const FLAC__int32 signal,
  105557. unsigned blocksize,
  105558. unsigned subframe_bps,
  105559. FLAC__Subframe *subframe
  105560. )
  105561. {
  105562. unsigned estimate;
  105563. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  105564. subframe->data.constant.value = signal;
  105565. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  105566. #if SPOTCHECK_ESTIMATE
  105567. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105568. #else
  105569. (void)encoder, (void)blocksize;
  105570. #endif
  105571. return estimate;
  105572. }
  105573. unsigned evaluate_fixed_subframe_(
  105574. FLAC__StreamEncoder *encoder,
  105575. const FLAC__int32 signal[],
  105576. FLAC__int32 residual[],
  105577. FLAC__uint64 abs_residual_partition_sums[],
  105578. unsigned raw_bits_per_partition[],
  105579. unsigned blocksize,
  105580. unsigned subframe_bps,
  105581. unsigned order,
  105582. unsigned rice_parameter,
  105583. unsigned rice_parameter_limit,
  105584. unsigned min_partition_order,
  105585. unsigned max_partition_order,
  105586. FLAC__bool do_escape_coding,
  105587. unsigned rice_parameter_search_dist,
  105588. FLAC__Subframe *subframe,
  105589. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105590. )
  105591. {
  105592. unsigned i, residual_bits, estimate;
  105593. const unsigned residual_samples = blocksize - order;
  105594. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  105595. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  105596. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105597. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105598. subframe->data.fixed.residual = residual;
  105599. residual_bits =
  105600. find_best_partition_order_(
  105601. encoder->private_,
  105602. residual,
  105603. abs_residual_partition_sums,
  105604. raw_bits_per_partition,
  105605. residual_samples,
  105606. order,
  105607. rice_parameter,
  105608. rice_parameter_limit,
  105609. min_partition_order,
  105610. max_partition_order,
  105611. subframe_bps,
  105612. do_escape_coding,
  105613. rice_parameter_search_dist,
  105614. &subframe->data.fixed.entropy_coding_method
  105615. );
  105616. subframe->data.fixed.order = order;
  105617. for(i = 0; i < order; i++)
  105618. subframe->data.fixed.warmup[i] = signal[i];
  105619. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  105620. #if SPOTCHECK_ESTIMATE
  105621. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105622. #endif
  105623. return estimate;
  105624. }
  105625. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  105626. unsigned evaluate_lpc_subframe_(
  105627. FLAC__StreamEncoder *encoder,
  105628. const FLAC__int32 signal[],
  105629. FLAC__int32 residual[],
  105630. FLAC__uint64 abs_residual_partition_sums[],
  105631. unsigned raw_bits_per_partition[],
  105632. const FLAC__real lp_coeff[],
  105633. unsigned blocksize,
  105634. unsigned subframe_bps,
  105635. unsigned order,
  105636. unsigned qlp_coeff_precision,
  105637. unsigned rice_parameter,
  105638. unsigned rice_parameter_limit,
  105639. unsigned min_partition_order,
  105640. unsigned max_partition_order,
  105641. FLAC__bool do_escape_coding,
  105642. unsigned rice_parameter_search_dist,
  105643. FLAC__Subframe *subframe,
  105644. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  105645. )
  105646. {
  105647. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  105648. unsigned i, residual_bits, estimate;
  105649. int quantization, ret;
  105650. const unsigned residual_samples = blocksize - order;
  105651. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  105652. if(subframe_bps <= 16) {
  105653. FLAC__ASSERT(order > 0);
  105654. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  105655. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  105656. }
  105657. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  105658. if(ret != 0)
  105659. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  105660. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  105661. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  105662. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105663. else
  105664. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105665. else
  105666. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  105667. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  105668. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  105669. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  105670. subframe->data.lpc.residual = residual;
  105671. residual_bits =
  105672. find_best_partition_order_(
  105673. encoder->private_,
  105674. residual,
  105675. abs_residual_partition_sums,
  105676. raw_bits_per_partition,
  105677. residual_samples,
  105678. order,
  105679. rice_parameter,
  105680. rice_parameter_limit,
  105681. min_partition_order,
  105682. max_partition_order,
  105683. subframe_bps,
  105684. do_escape_coding,
  105685. rice_parameter_search_dist,
  105686. &subframe->data.lpc.entropy_coding_method
  105687. );
  105688. subframe->data.lpc.order = order;
  105689. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  105690. subframe->data.lpc.quantization_level = quantization;
  105691. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  105692. for(i = 0; i < order; i++)
  105693. subframe->data.lpc.warmup[i] = signal[i];
  105694. 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;
  105695. #if SPOTCHECK_ESTIMATE
  105696. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105697. #endif
  105698. return estimate;
  105699. }
  105700. #endif
  105701. unsigned evaluate_verbatim_subframe_(
  105702. FLAC__StreamEncoder *encoder,
  105703. const FLAC__int32 signal[],
  105704. unsigned blocksize,
  105705. unsigned subframe_bps,
  105706. FLAC__Subframe *subframe
  105707. )
  105708. {
  105709. unsigned estimate;
  105710. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  105711. subframe->data.verbatim.data = signal;
  105712. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  105713. #if SPOTCHECK_ESTIMATE
  105714. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  105715. #else
  105716. (void)encoder;
  105717. #endif
  105718. return estimate;
  105719. }
  105720. unsigned find_best_partition_order_(
  105721. FLAC__StreamEncoderPrivate *private_,
  105722. const FLAC__int32 residual[],
  105723. FLAC__uint64 abs_residual_partition_sums[],
  105724. unsigned raw_bits_per_partition[],
  105725. unsigned residual_samples,
  105726. unsigned predictor_order,
  105727. unsigned rice_parameter,
  105728. unsigned rice_parameter_limit,
  105729. unsigned min_partition_order,
  105730. unsigned max_partition_order,
  105731. unsigned bps,
  105732. FLAC__bool do_escape_coding,
  105733. unsigned rice_parameter_search_dist,
  105734. FLAC__EntropyCodingMethod *best_ecm
  105735. )
  105736. {
  105737. unsigned residual_bits, best_residual_bits = 0;
  105738. unsigned best_parameters_index = 0;
  105739. unsigned best_partition_order = 0;
  105740. const unsigned blocksize = residual_samples + predictor_order;
  105741. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  105742. min_partition_order = min(min_partition_order, max_partition_order);
  105743. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  105744. if(do_escape_coding)
  105745. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  105746. {
  105747. int partition_order;
  105748. unsigned sum;
  105749. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  105750. if(!
  105751. set_partitioned_rice_(
  105752. #ifdef EXACT_RICE_BITS_CALCULATION
  105753. residual,
  105754. #endif
  105755. abs_residual_partition_sums+sum,
  105756. raw_bits_per_partition+sum,
  105757. residual_samples,
  105758. predictor_order,
  105759. rice_parameter,
  105760. rice_parameter_limit,
  105761. rice_parameter_search_dist,
  105762. (unsigned)partition_order,
  105763. do_escape_coding,
  105764. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  105765. &residual_bits
  105766. )
  105767. )
  105768. {
  105769. FLAC__ASSERT(best_residual_bits != 0);
  105770. break;
  105771. }
  105772. sum += 1u << partition_order;
  105773. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  105774. best_residual_bits = residual_bits;
  105775. best_parameters_index = !best_parameters_index;
  105776. best_partition_order = partition_order;
  105777. }
  105778. }
  105779. }
  105780. best_ecm->data.partitioned_rice.order = best_partition_order;
  105781. {
  105782. /*
  105783. * We are allowed to de-const the pointer based on our special
  105784. * knowledge; it is const to the outside world.
  105785. */
  105786. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  105787. unsigned partition;
  105788. /* save best parameters and raw_bits */
  105789. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  105790. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  105791. if(do_escape_coding)
  105792. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  105793. /*
  105794. * Now need to check if the type should be changed to
  105795. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  105796. * size of the rice parameters.
  105797. */
  105798. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  105799. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  105800. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  105801. break;
  105802. }
  105803. }
  105804. }
  105805. return best_residual_bits;
  105806. }
  105807. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105808. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  105809. const FLAC__int32 residual[],
  105810. FLAC__uint64 abs_residual_partition_sums[],
  105811. unsigned blocksize,
  105812. unsigned predictor_order,
  105813. unsigned min_partition_order,
  105814. unsigned max_partition_order
  105815. );
  105816. #endif
  105817. void precompute_partition_info_sums_(
  105818. const FLAC__int32 residual[],
  105819. FLAC__uint64 abs_residual_partition_sums[],
  105820. unsigned residual_samples,
  105821. unsigned predictor_order,
  105822. unsigned min_partition_order,
  105823. unsigned max_partition_order,
  105824. unsigned bps
  105825. )
  105826. {
  105827. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  105828. unsigned partitions = 1u << max_partition_order;
  105829. FLAC__ASSERT(default_partition_samples > predictor_order);
  105830. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  105831. /* slightly pessimistic but still catches all common cases */
  105832. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105833. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105834. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  105835. return;
  105836. }
  105837. #endif
  105838. /* first do max_partition_order */
  105839. {
  105840. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  105841. /* slightly pessimistic but still catches all common cases */
  105842. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  105843. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  105844. FLAC__uint32 abs_residual_partition_sum;
  105845. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105846. end += default_partition_samples;
  105847. abs_residual_partition_sum = 0;
  105848. for( ; residual_sample < end; residual_sample++)
  105849. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105850. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105851. }
  105852. }
  105853. else { /* have to pessimistically use 64 bits for accumulator */
  105854. FLAC__uint64 abs_residual_partition_sum;
  105855. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105856. end += default_partition_samples;
  105857. abs_residual_partition_sum = 0;
  105858. for( ; residual_sample < end; residual_sample++)
  105859. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  105860. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  105861. }
  105862. }
  105863. }
  105864. /* now merge partitions for lower orders */
  105865. {
  105866. unsigned from_partition = 0, to_partition = partitions;
  105867. int partition_order;
  105868. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  105869. unsigned i;
  105870. partitions >>= 1;
  105871. for(i = 0; i < partitions; i++) {
  105872. abs_residual_partition_sums[to_partition++] =
  105873. abs_residual_partition_sums[from_partition ] +
  105874. abs_residual_partition_sums[from_partition+1];
  105875. from_partition += 2;
  105876. }
  105877. }
  105878. }
  105879. }
  105880. void precompute_partition_info_escapes_(
  105881. const FLAC__int32 residual[],
  105882. unsigned raw_bits_per_partition[],
  105883. unsigned residual_samples,
  105884. unsigned predictor_order,
  105885. unsigned min_partition_order,
  105886. unsigned max_partition_order
  105887. )
  105888. {
  105889. int partition_order;
  105890. unsigned from_partition, to_partition = 0;
  105891. const unsigned blocksize = residual_samples + predictor_order;
  105892. /* first do max_partition_order */
  105893. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  105894. FLAC__int32 r;
  105895. FLAC__uint32 rmax;
  105896. unsigned partition, partition_sample, partition_samples, residual_sample;
  105897. const unsigned partitions = 1u << partition_order;
  105898. const unsigned default_partition_samples = blocksize >> partition_order;
  105899. FLAC__ASSERT(default_partition_samples > predictor_order);
  105900. for(partition = residual_sample = 0; partition < partitions; partition++) {
  105901. partition_samples = default_partition_samples;
  105902. if(partition == 0)
  105903. partition_samples -= predictor_order;
  105904. rmax = 0;
  105905. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  105906. r = residual[residual_sample++];
  105907. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  105908. if(r < 0)
  105909. rmax |= ~r;
  105910. else
  105911. rmax |= r;
  105912. }
  105913. /* now we know all residual values are in the range [-rmax-1,rmax] */
  105914. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  105915. }
  105916. to_partition = partitions;
  105917. break; /*@@@ yuck, should remove the 'for' loop instead */
  105918. }
  105919. /* now merge partitions for lower orders */
  105920. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  105921. unsigned m;
  105922. unsigned i;
  105923. const unsigned partitions = 1u << partition_order;
  105924. for(i = 0; i < partitions; i++) {
  105925. m = raw_bits_per_partition[from_partition];
  105926. from_partition++;
  105927. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  105928. from_partition++;
  105929. to_partition++;
  105930. }
  105931. }
  105932. }
  105933. #ifdef EXACT_RICE_BITS_CALCULATION
  105934. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105935. const unsigned rice_parameter,
  105936. const unsigned partition_samples,
  105937. const FLAC__int32 *residual
  105938. )
  105939. {
  105940. unsigned i, partition_bits =
  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. for(i = 0; i < partition_samples; i++)
  105945. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  105946. return partition_bits;
  105947. }
  105948. #else
  105949. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  105950. const unsigned rice_parameter,
  105951. const unsigned partition_samples,
  105952. const FLAC__uint64 abs_residual_partition_sum
  105953. )
  105954. {
  105955. return
  105956. 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 */
  105957. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  105958. (
  105959. rice_parameter?
  105960. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  105961. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  105962. )
  105963. - (partition_samples >> 1)
  105964. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  105965. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  105966. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  105967. * So the subtraction term tries to guess how many extra bits were contributed.
  105968. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  105969. */
  105970. ;
  105971. }
  105972. #endif
  105973. FLAC__bool set_partitioned_rice_(
  105974. #ifdef EXACT_RICE_BITS_CALCULATION
  105975. const FLAC__int32 residual[],
  105976. #endif
  105977. const FLAC__uint64 abs_residual_partition_sums[],
  105978. const unsigned raw_bits_per_partition[],
  105979. const unsigned residual_samples,
  105980. const unsigned predictor_order,
  105981. const unsigned suggested_rice_parameter,
  105982. const unsigned rice_parameter_limit,
  105983. const unsigned rice_parameter_search_dist,
  105984. const unsigned partition_order,
  105985. const FLAC__bool search_for_escapes,
  105986. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  105987. unsigned *bits
  105988. )
  105989. {
  105990. unsigned rice_parameter, partition_bits;
  105991. unsigned best_partition_bits, best_rice_parameter = 0;
  105992. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  105993. unsigned *parameters, *raw_bits;
  105994. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  105995. unsigned min_rice_parameter, max_rice_parameter;
  105996. #else
  105997. (void)rice_parameter_search_dist;
  105998. #endif
  105999. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  106000. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  106001. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  106002. parameters = partitioned_rice_contents->parameters;
  106003. raw_bits = partitioned_rice_contents->raw_bits;
  106004. if(partition_order == 0) {
  106005. best_partition_bits = (unsigned)(-1);
  106006. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106007. if(rice_parameter_search_dist) {
  106008. if(suggested_rice_parameter < rice_parameter_search_dist)
  106009. min_rice_parameter = 0;
  106010. else
  106011. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  106012. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  106013. if(max_rice_parameter >= rice_parameter_limit) {
  106014. #ifdef DEBUG_VERBOSE
  106015. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  106016. #endif
  106017. max_rice_parameter = rice_parameter_limit - 1;
  106018. }
  106019. }
  106020. else
  106021. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  106022. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106023. #else
  106024. rice_parameter = suggested_rice_parameter;
  106025. #endif
  106026. #ifdef EXACT_RICE_BITS_CALCULATION
  106027. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  106028. #else
  106029. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  106030. #endif
  106031. if(partition_bits < best_partition_bits) {
  106032. best_rice_parameter = rice_parameter;
  106033. best_partition_bits = partition_bits;
  106034. }
  106035. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106036. }
  106037. #endif
  106038. if(search_for_escapes) {
  106039. 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;
  106040. if(partition_bits <= best_partition_bits) {
  106041. raw_bits[0] = raw_bits_per_partition[0];
  106042. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106043. best_partition_bits = partition_bits;
  106044. }
  106045. else
  106046. raw_bits[0] = 0;
  106047. }
  106048. parameters[0] = best_rice_parameter;
  106049. bits_ += best_partition_bits;
  106050. }
  106051. else {
  106052. unsigned partition, residual_sample;
  106053. unsigned partition_samples;
  106054. FLAC__uint64 mean, k;
  106055. const unsigned partitions = 1u << partition_order;
  106056. for(partition = residual_sample = 0; partition < partitions; partition++) {
  106057. partition_samples = (residual_samples+predictor_order) >> partition_order;
  106058. if(partition == 0) {
  106059. if(partition_samples <= predictor_order)
  106060. return false;
  106061. else
  106062. partition_samples -= predictor_order;
  106063. }
  106064. mean = abs_residual_partition_sums[partition];
  106065. /* we are basically calculating the size in bits of the
  106066. * average residual magnitude in the partition:
  106067. * rice_parameter = floor(log2(mean/partition_samples))
  106068. * 'mean' is not a good name for the variable, it is
  106069. * actually the sum of magnitudes of all residual values
  106070. * in the partition, so the actual mean is
  106071. * mean/partition_samples
  106072. */
  106073. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  106074. ;
  106075. if(rice_parameter >= rice_parameter_limit) {
  106076. #ifdef DEBUG_VERBOSE
  106077. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  106078. #endif
  106079. rice_parameter = rice_parameter_limit - 1;
  106080. }
  106081. best_partition_bits = (unsigned)(-1);
  106082. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106083. if(rice_parameter_search_dist) {
  106084. if(rice_parameter < rice_parameter_search_dist)
  106085. min_rice_parameter = 0;
  106086. else
  106087. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  106088. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  106089. if(max_rice_parameter >= rice_parameter_limit) {
  106090. #ifdef DEBUG_VERBOSE
  106091. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  106092. #endif
  106093. max_rice_parameter = rice_parameter_limit - 1;
  106094. }
  106095. }
  106096. else
  106097. min_rice_parameter = max_rice_parameter = rice_parameter;
  106098. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  106099. #endif
  106100. #ifdef EXACT_RICE_BITS_CALCULATION
  106101. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  106102. #else
  106103. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  106104. #endif
  106105. if(partition_bits < best_partition_bits) {
  106106. best_rice_parameter = rice_parameter;
  106107. best_partition_bits = partition_bits;
  106108. }
  106109. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  106110. }
  106111. #endif
  106112. if(search_for_escapes) {
  106113. 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;
  106114. if(partition_bits <= best_partition_bits) {
  106115. raw_bits[partition] = raw_bits_per_partition[partition];
  106116. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  106117. best_partition_bits = partition_bits;
  106118. }
  106119. else
  106120. raw_bits[partition] = 0;
  106121. }
  106122. parameters[partition] = best_rice_parameter;
  106123. bits_ += best_partition_bits;
  106124. residual_sample += partition_samples;
  106125. }
  106126. }
  106127. *bits = bits_;
  106128. return true;
  106129. }
  106130. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  106131. {
  106132. unsigned i, shift;
  106133. FLAC__int32 x = 0;
  106134. for(i = 0; i < samples && !(x&1); i++)
  106135. x |= signal[i];
  106136. if(x == 0) {
  106137. shift = 0;
  106138. }
  106139. else {
  106140. for(shift = 0; !(x&1); shift++)
  106141. x >>= 1;
  106142. }
  106143. if(shift > 0) {
  106144. for(i = 0; i < samples; i++)
  106145. signal[i] >>= shift;
  106146. }
  106147. return shift;
  106148. }
  106149. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106150. {
  106151. unsigned channel;
  106152. for(channel = 0; channel < channels; channel++)
  106153. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  106154. fifo->tail += wide_samples;
  106155. FLAC__ASSERT(fifo->tail <= fifo->size);
  106156. }
  106157. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  106158. {
  106159. unsigned channel;
  106160. unsigned sample, wide_sample;
  106161. unsigned tail = fifo->tail;
  106162. sample = input_offset * channels;
  106163. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  106164. for(channel = 0; channel < channels; channel++)
  106165. fifo->data[channel][tail] = input[sample++];
  106166. tail++;
  106167. }
  106168. fifo->tail = tail;
  106169. FLAC__ASSERT(fifo->tail <= fifo->size);
  106170. }
  106171. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106172. {
  106173. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106174. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  106175. (void)decoder;
  106176. if(encoder->private_->verify.needs_magic_hack) {
  106177. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  106178. *bytes = FLAC__STREAM_SYNC_LENGTH;
  106179. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  106180. encoder->private_->verify.needs_magic_hack = false;
  106181. }
  106182. else {
  106183. if(encoded_bytes == 0) {
  106184. /*
  106185. * If we get here, a FIFO underflow has occurred,
  106186. * which means there is a bug somewhere.
  106187. */
  106188. FLAC__ASSERT(0);
  106189. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  106190. }
  106191. else if(encoded_bytes < *bytes)
  106192. *bytes = encoded_bytes;
  106193. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  106194. encoder->private_->verify.output.data += *bytes;
  106195. encoder->private_->verify.output.bytes -= *bytes;
  106196. }
  106197. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  106198. }
  106199. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  106200. {
  106201. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  106202. unsigned channel;
  106203. const unsigned channels = frame->header.channels;
  106204. const unsigned blocksize = frame->header.blocksize;
  106205. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  106206. (void)decoder;
  106207. for(channel = 0; channel < channels; channel++) {
  106208. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  106209. unsigned i, sample = 0;
  106210. FLAC__int32 expect = 0, got = 0;
  106211. for(i = 0; i < blocksize; i++) {
  106212. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  106213. sample = i;
  106214. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  106215. got = (FLAC__int32)buffer[channel][i];
  106216. break;
  106217. }
  106218. }
  106219. FLAC__ASSERT(i < blocksize);
  106220. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  106221. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  106222. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  106223. encoder->private_->verify.error_stats.channel = channel;
  106224. encoder->private_->verify.error_stats.sample = sample;
  106225. encoder->private_->verify.error_stats.expected = expect;
  106226. encoder->private_->verify.error_stats.got = got;
  106227. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  106228. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  106229. }
  106230. }
  106231. /* dequeue the frame from the fifo */
  106232. encoder->private_->verify.input_fifo.tail -= blocksize;
  106233. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  106234. for(channel = 0; channel < channels; channel++)
  106235. 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]));
  106236. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  106237. }
  106238. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  106239. {
  106240. (void)decoder, (void)metadata, (void)client_data;
  106241. }
  106242. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  106243. {
  106244. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  106245. (void)decoder, (void)status;
  106246. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  106247. }
  106248. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  106249. {
  106250. (void)client_data;
  106251. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  106252. if (*bytes == 0) {
  106253. if (feof(encoder->private_->file))
  106254. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  106255. else if (ferror(encoder->private_->file))
  106256. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  106257. }
  106258. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  106259. }
  106260. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  106261. {
  106262. (void)client_data;
  106263. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  106264. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  106265. else
  106266. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  106267. }
  106268. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  106269. {
  106270. off_t offset;
  106271. (void)client_data;
  106272. offset = ftello(encoder->private_->file);
  106273. if(offset < 0) {
  106274. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  106275. }
  106276. else {
  106277. *absolute_byte_offset = (FLAC__uint64)offset;
  106278. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  106279. }
  106280. }
  106281. #ifdef FLAC__VALGRIND_TESTING
  106282. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  106283. {
  106284. size_t ret = fwrite(ptr, size, nmemb, stream);
  106285. if(!ferror(stream))
  106286. fflush(stream);
  106287. return ret;
  106288. }
  106289. #else
  106290. #define local__fwrite fwrite
  106291. #endif
  106292. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  106293. {
  106294. (void)client_data, (void)current_frame;
  106295. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  106296. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  106297. #if FLAC__HAS_OGG
  106298. /* We would like to be able to use 'samples > 0' in the
  106299. * clause here but currently because of the nature of our
  106300. * Ogg writing implementation, 'samples' is always 0 (see
  106301. * ogg_encoder_aspect.c). The downside is extra progress
  106302. * callbacks.
  106303. */
  106304. encoder->private_->is_ogg? true :
  106305. #endif
  106306. samples > 0
  106307. );
  106308. if(call_it) {
  106309. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  106310. * because at this point in the callback chain, the stats
  106311. * have not been updated. Only after we return and control
  106312. * gets back to write_frame_() are the stats updated
  106313. */
  106314. 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);
  106315. }
  106316. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  106317. }
  106318. else
  106319. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  106320. }
  106321. /*
  106322. * This will forcibly set stdout to binary mode (for OSes that require it)
  106323. */
  106324. FILE *get_binary_stdout_(void)
  106325. {
  106326. /* if something breaks here it is probably due to the presence or
  106327. * absence of an underscore before the identifiers 'setmode',
  106328. * 'fileno', and/or 'O_BINARY'; check your system header files.
  106329. */
  106330. #if defined _MSC_VER || defined __MINGW32__
  106331. _setmode(_fileno(stdout), _O_BINARY);
  106332. #elif defined __CYGWIN__
  106333. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  106334. setmode(_fileno(stdout), _O_BINARY);
  106335. #elif defined __EMX__
  106336. setmode(fileno(stdout), O_BINARY);
  106337. #endif
  106338. return stdout;
  106339. }
  106340. #endif
  106341. /*** End of inlined file: stream_encoder.c ***/
  106342. /*** Start of inlined file: stream_encoder_framing.c ***/
  106343. /*** Start of inlined file: juce_FlacHeader.h ***/
  106344. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106345. // tasks..
  106346. #define VERSION "1.2.1"
  106347. #define FLAC__NO_DLL 1
  106348. #if JUCE_MSVC
  106349. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106350. #endif
  106351. #if JUCE_MAC
  106352. #define FLAC__SYS_DARWIN 1
  106353. #endif
  106354. /*** End of inlined file: juce_FlacHeader.h ***/
  106355. #if JUCE_USE_FLAC
  106356. #if HAVE_CONFIG_H
  106357. # include <config.h>
  106358. #endif
  106359. #include <stdio.h>
  106360. #include <string.h> /* for strlen() */
  106361. #ifdef max
  106362. #undef max
  106363. #endif
  106364. #define max(x,y) ((x)>(y)?(x):(y))
  106365. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  106366. 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);
  106367. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  106368. {
  106369. unsigned i, j;
  106370. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  106371. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  106372. return false;
  106373. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  106374. return false;
  106375. /*
  106376. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  106377. */
  106378. i = metadata->length;
  106379. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  106380. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  106381. i -= metadata->data.vorbis_comment.vendor_string.length;
  106382. i += vendor_string_length;
  106383. }
  106384. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  106385. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  106386. return false;
  106387. switch(metadata->type) {
  106388. case FLAC__METADATA_TYPE_STREAMINFO:
  106389. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  106390. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  106391. return false;
  106392. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  106393. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  106394. return false;
  106395. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  106396. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  106397. return false;
  106398. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  106399. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  106400. return false;
  106401. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  106402. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  106403. return false;
  106404. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  106405. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  106406. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  106407. return false;
  106408. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  106409. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106410. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  106411. return false;
  106412. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  106413. return false;
  106414. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  106415. return false;
  106416. break;
  106417. case FLAC__METADATA_TYPE_PADDING:
  106418. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  106419. return false;
  106420. break;
  106421. case FLAC__METADATA_TYPE_APPLICATION:
  106422. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  106423. return false;
  106424. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  106425. return false;
  106426. break;
  106427. case FLAC__METADATA_TYPE_SEEKTABLE:
  106428. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  106429. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  106430. return false;
  106431. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  106432. return false;
  106433. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  106434. return false;
  106435. }
  106436. break;
  106437. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  106438. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  106439. return false;
  106440. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  106441. return false;
  106442. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  106443. return false;
  106444. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  106445. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  106446. return false;
  106447. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  106448. return false;
  106449. }
  106450. break;
  106451. case FLAC__METADATA_TYPE_CUESHEET:
  106452. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  106453. 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))
  106454. return false;
  106455. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  106456. return false;
  106457. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  106458. return false;
  106459. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  106460. return false;
  106461. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  106462. return false;
  106463. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  106464. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  106465. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  106466. return false;
  106467. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  106468. return false;
  106469. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  106470. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  106471. return false;
  106472. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  106473. return false;
  106474. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  106475. return false;
  106476. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  106477. return false;
  106478. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  106479. return false;
  106480. for(j = 0; j < track->num_indices; j++) {
  106481. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  106482. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  106483. return false;
  106484. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  106485. return false;
  106486. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  106487. return false;
  106488. }
  106489. }
  106490. break;
  106491. case FLAC__METADATA_TYPE_PICTURE:
  106492. {
  106493. size_t len;
  106494. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  106495. return false;
  106496. len = strlen(metadata->data.picture.mime_type);
  106497. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  106498. return false;
  106499. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  106500. return false;
  106501. len = strlen((const char *)metadata->data.picture.description);
  106502. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  106503. return false;
  106504. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  106505. return false;
  106506. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  106507. return false;
  106508. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  106509. return false;
  106510. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  106511. return false;
  106512. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  106513. return false;
  106514. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  106515. return false;
  106516. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  106517. return false;
  106518. }
  106519. break;
  106520. default:
  106521. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  106522. return false;
  106523. break;
  106524. }
  106525. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106526. return true;
  106527. }
  106528. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  106529. {
  106530. unsigned u, blocksize_hint, sample_rate_hint;
  106531. FLAC__byte crc;
  106532. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  106533. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  106534. return false;
  106535. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  106536. return false;
  106537. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  106538. return false;
  106539. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  106540. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  106541. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  106542. blocksize_hint = 0;
  106543. switch(header->blocksize) {
  106544. case 192: u = 1; break;
  106545. case 576: u = 2; break;
  106546. case 1152: u = 3; break;
  106547. case 2304: u = 4; break;
  106548. case 4608: u = 5; break;
  106549. case 256: u = 8; break;
  106550. case 512: u = 9; break;
  106551. case 1024: u = 10; break;
  106552. case 2048: u = 11; break;
  106553. case 4096: u = 12; break;
  106554. case 8192: u = 13; break;
  106555. case 16384: u = 14; break;
  106556. case 32768: u = 15; break;
  106557. default:
  106558. if(header->blocksize <= 0x100)
  106559. blocksize_hint = u = 6;
  106560. else
  106561. blocksize_hint = u = 7;
  106562. break;
  106563. }
  106564. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  106565. return false;
  106566. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  106567. sample_rate_hint = 0;
  106568. switch(header->sample_rate) {
  106569. case 88200: u = 1; break;
  106570. case 176400: u = 2; break;
  106571. case 192000: u = 3; break;
  106572. case 8000: u = 4; break;
  106573. case 16000: u = 5; break;
  106574. case 22050: u = 6; break;
  106575. case 24000: u = 7; break;
  106576. case 32000: u = 8; break;
  106577. case 44100: u = 9; break;
  106578. case 48000: u = 10; break;
  106579. case 96000: u = 11; break;
  106580. default:
  106581. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  106582. sample_rate_hint = u = 12;
  106583. else if(header->sample_rate % 10 == 0)
  106584. sample_rate_hint = u = 14;
  106585. else if(header->sample_rate <= 0xffff)
  106586. sample_rate_hint = u = 13;
  106587. else
  106588. u = 0;
  106589. break;
  106590. }
  106591. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  106592. return false;
  106593. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  106594. switch(header->channel_assignment) {
  106595. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  106596. u = header->channels - 1;
  106597. break;
  106598. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  106599. FLAC__ASSERT(header->channels == 2);
  106600. u = 8;
  106601. break;
  106602. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  106603. FLAC__ASSERT(header->channels == 2);
  106604. u = 9;
  106605. break;
  106606. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  106607. FLAC__ASSERT(header->channels == 2);
  106608. u = 10;
  106609. break;
  106610. default:
  106611. FLAC__ASSERT(0);
  106612. }
  106613. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  106614. return false;
  106615. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  106616. switch(header->bits_per_sample) {
  106617. case 8 : u = 1; break;
  106618. case 12: u = 2; break;
  106619. case 16: u = 4; break;
  106620. case 20: u = 5; break;
  106621. case 24: u = 6; break;
  106622. default: u = 0; break;
  106623. }
  106624. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  106625. return false;
  106626. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  106627. return false;
  106628. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  106629. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  106630. return false;
  106631. }
  106632. else {
  106633. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  106634. return false;
  106635. }
  106636. if(blocksize_hint)
  106637. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  106638. return false;
  106639. switch(sample_rate_hint) {
  106640. case 12:
  106641. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  106642. return false;
  106643. break;
  106644. case 13:
  106645. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  106646. return false;
  106647. break;
  106648. case 14:
  106649. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  106650. return false;
  106651. break;
  106652. }
  106653. /* write the CRC */
  106654. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  106655. return false;
  106656. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  106657. return false;
  106658. return true;
  106659. }
  106660. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106661. {
  106662. FLAC__bool ok;
  106663. ok =
  106664. 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) &&
  106665. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  106666. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  106667. ;
  106668. return ok;
  106669. }
  106670. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106671. {
  106672. unsigned i;
  106673. 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))
  106674. return false;
  106675. if(wasted_bits)
  106676. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106677. return false;
  106678. for(i = 0; i < subframe->order; i++)
  106679. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106680. return false;
  106681. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106682. return false;
  106683. switch(subframe->entropy_coding_method.type) {
  106684. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106685. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106686. if(!add_residual_partitioned_rice_(
  106687. bw,
  106688. subframe->residual,
  106689. residual_samples,
  106690. subframe->order,
  106691. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106692. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106693. subframe->entropy_coding_method.data.partitioned_rice.order,
  106694. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106695. ))
  106696. return false;
  106697. break;
  106698. default:
  106699. FLAC__ASSERT(0);
  106700. }
  106701. return true;
  106702. }
  106703. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106704. {
  106705. unsigned i;
  106706. 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))
  106707. return false;
  106708. if(wasted_bits)
  106709. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106710. return false;
  106711. for(i = 0; i < subframe->order; i++)
  106712. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  106713. return false;
  106714. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  106715. return false;
  106716. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  106717. return false;
  106718. for(i = 0; i < subframe->order; i++)
  106719. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  106720. return false;
  106721. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  106722. return false;
  106723. switch(subframe->entropy_coding_method.type) {
  106724. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106725. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106726. if(!add_residual_partitioned_rice_(
  106727. bw,
  106728. subframe->residual,
  106729. residual_samples,
  106730. subframe->order,
  106731. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  106732. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  106733. subframe->entropy_coding_method.data.partitioned_rice.order,
  106734. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  106735. ))
  106736. return false;
  106737. break;
  106738. default:
  106739. FLAC__ASSERT(0);
  106740. }
  106741. return true;
  106742. }
  106743. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  106744. {
  106745. unsigned i;
  106746. const FLAC__int32 *signal = subframe->data;
  106747. 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))
  106748. return false;
  106749. if(wasted_bits)
  106750. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  106751. return false;
  106752. for(i = 0; i < samples; i++)
  106753. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  106754. return false;
  106755. return true;
  106756. }
  106757. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  106758. {
  106759. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  106760. return false;
  106761. switch(method->type) {
  106762. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  106763. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  106764. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  106765. return false;
  106766. break;
  106767. default:
  106768. FLAC__ASSERT(0);
  106769. }
  106770. return true;
  106771. }
  106772. 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)
  106773. {
  106774. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  106775. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  106776. if(partition_order == 0) {
  106777. unsigned i;
  106778. if(raw_bits[0] == 0) {
  106779. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  106780. return false;
  106781. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  106782. return false;
  106783. }
  106784. else {
  106785. FLAC__ASSERT(rice_parameters[0] == 0);
  106786. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106787. return false;
  106788. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106789. return false;
  106790. for(i = 0; i < residual_samples; i++) {
  106791. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  106792. return false;
  106793. }
  106794. }
  106795. return true;
  106796. }
  106797. else {
  106798. unsigned i, j, k = 0, k_last = 0;
  106799. unsigned partition_samples;
  106800. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  106801. for(i = 0; i < (1u<<partition_order); i++) {
  106802. partition_samples = default_partition_samples;
  106803. if(i == 0)
  106804. partition_samples -= predictor_order;
  106805. k += partition_samples;
  106806. if(raw_bits[i] == 0) {
  106807. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  106808. return false;
  106809. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  106810. return false;
  106811. }
  106812. else {
  106813. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  106814. return false;
  106815. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  106816. return false;
  106817. for(j = k_last; j < k; j++) {
  106818. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  106819. return false;
  106820. }
  106821. }
  106822. k_last = k;
  106823. }
  106824. return true;
  106825. }
  106826. }
  106827. #endif
  106828. /*** End of inlined file: stream_encoder_framing.c ***/
  106829. /*** Start of inlined file: window_flac.c ***/
  106830. /*** Start of inlined file: juce_FlacHeader.h ***/
  106831. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  106832. // tasks..
  106833. #define VERSION "1.2.1"
  106834. #define FLAC__NO_DLL 1
  106835. #if JUCE_MSVC
  106836. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  106837. #endif
  106838. #if JUCE_MAC
  106839. #define FLAC__SYS_DARWIN 1
  106840. #endif
  106841. /*** End of inlined file: juce_FlacHeader.h ***/
  106842. #if JUCE_USE_FLAC
  106843. #if HAVE_CONFIG_H
  106844. # include <config.h>
  106845. #endif
  106846. #include <math.h>
  106847. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  106848. #ifndef M_PI
  106849. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  106850. #define M_PI 3.14159265358979323846
  106851. #endif
  106852. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  106853. {
  106854. const FLAC__int32 N = L - 1;
  106855. FLAC__int32 n;
  106856. if (L & 1) {
  106857. for (n = 0; n <= N/2; n++)
  106858. window[n] = 2.0f * n / (float)N;
  106859. for (; n <= N; n++)
  106860. window[n] = 2.0f - 2.0f * n / (float)N;
  106861. }
  106862. else {
  106863. for (n = 0; n <= L/2-1; n++)
  106864. window[n] = 2.0f * n / (float)N;
  106865. for (; n <= N; n++)
  106866. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  106867. }
  106868. }
  106869. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  106870. {
  106871. const FLAC__int32 N = L - 1;
  106872. FLAC__int32 n;
  106873. for (n = 0; n < L; n++)
  106874. 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)));
  106875. }
  106876. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  106877. {
  106878. const FLAC__int32 N = L - 1;
  106879. FLAC__int32 n;
  106880. for (n = 0; n < L; n++)
  106881. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  106882. }
  106883. /* 4-term -92dB side-lobe */
  106884. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  106885. {
  106886. const FLAC__int32 N = L - 1;
  106887. FLAC__int32 n;
  106888. for (n = 0; n <= N; n++)
  106889. 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));
  106890. }
  106891. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  106892. {
  106893. const FLAC__int32 N = L - 1;
  106894. const double N2 = (double)N / 2.;
  106895. FLAC__int32 n;
  106896. for (n = 0; n <= N; n++) {
  106897. double k = ((double)n - N2) / N2;
  106898. k = 1.0f - k * k;
  106899. window[n] = (FLAC__real)(k * k);
  106900. }
  106901. }
  106902. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  106903. {
  106904. const FLAC__int32 N = L - 1;
  106905. FLAC__int32 n;
  106906. for (n = 0; n < L; n++)
  106907. 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));
  106908. }
  106909. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  106910. {
  106911. const FLAC__int32 N = L - 1;
  106912. const double N2 = (double)N / 2.;
  106913. FLAC__int32 n;
  106914. for (n = 0; n <= N; n++) {
  106915. const double k = ((double)n - N2) / (stddev * N2);
  106916. window[n] = (FLAC__real)exp(-0.5f * k * k);
  106917. }
  106918. }
  106919. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  106920. {
  106921. const FLAC__int32 N = L - 1;
  106922. FLAC__int32 n;
  106923. for (n = 0; n < L; n++)
  106924. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  106925. }
  106926. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  106927. {
  106928. const FLAC__int32 N = L - 1;
  106929. FLAC__int32 n;
  106930. for (n = 0; n < L; n++)
  106931. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  106932. }
  106933. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  106934. {
  106935. const FLAC__int32 N = L - 1;
  106936. FLAC__int32 n;
  106937. for (n = 0; n < L; n++)
  106938. 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));
  106939. }
  106940. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  106941. {
  106942. const FLAC__int32 N = L - 1;
  106943. FLAC__int32 n;
  106944. for (n = 0; n < L; n++)
  106945. 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));
  106946. }
  106947. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  106948. {
  106949. FLAC__int32 n;
  106950. for (n = 0; n < L; n++)
  106951. window[n] = 1.0f;
  106952. }
  106953. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  106954. {
  106955. FLAC__int32 n;
  106956. if (L & 1) {
  106957. for (n = 1; n <= L+1/2; n++)
  106958. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  106959. for (; n <= L; n++)
  106960. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  106961. }
  106962. else {
  106963. for (n = 1; n <= L/2; n++)
  106964. window[n-1] = 2.0f * n / (float)L;
  106965. for (; n <= L; n++)
  106966. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  106967. }
  106968. }
  106969. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  106970. {
  106971. if (p <= 0.0)
  106972. FLAC__window_rectangle(window, L);
  106973. else if (p >= 1.0)
  106974. FLAC__window_hann(window, L);
  106975. else {
  106976. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  106977. FLAC__int32 n;
  106978. /* start with rectangle... */
  106979. FLAC__window_rectangle(window, L);
  106980. /* ...replace ends with hann */
  106981. if (Np > 0) {
  106982. for (n = 0; n <= Np; n++) {
  106983. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  106984. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  106985. }
  106986. }
  106987. }
  106988. }
  106989. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  106990. {
  106991. const FLAC__int32 N = L - 1;
  106992. const double N2 = (double)N / 2.;
  106993. FLAC__int32 n;
  106994. for (n = 0; n <= N; n++) {
  106995. const double k = ((double)n - N2) / N2;
  106996. window[n] = (FLAC__real)(1.0f - k * k);
  106997. }
  106998. }
  106999. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  107000. #endif
  107001. /*** End of inlined file: window_flac.c ***/
  107002. #else
  107003. #include <FLAC/all.h>
  107004. #endif
  107005. }
  107006. #undef max
  107007. #undef min
  107008. BEGIN_JUCE_NAMESPACE
  107009. static const char* const flacFormatName = "FLAC file";
  107010. static const char* const flacExtensions[] = { ".flac", 0 };
  107011. class FlacReader : public AudioFormatReader
  107012. {
  107013. public:
  107014. FlacReader (InputStream* const in)
  107015. : AudioFormatReader (in, TRANS (flacFormatName)),
  107016. reservoir (2, 0),
  107017. reservoirStart (0),
  107018. samplesInReservoir (0),
  107019. scanningForLength (false)
  107020. {
  107021. using namespace FlacNamespace;
  107022. lengthInSamples = 0;
  107023. decoder = FLAC__stream_decoder_new();
  107024. ok = FLAC__stream_decoder_init_stream (decoder,
  107025. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  107026. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  107027. this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  107028. if (ok)
  107029. {
  107030. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107031. if (lengthInSamples == 0 && sampleRate > 0)
  107032. {
  107033. // the length hasn't been stored in the metadata, so we'll need to
  107034. // work it out the length the hard way, by scanning the whole file..
  107035. scanningForLength = true;
  107036. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  107037. scanningForLength = false;
  107038. const int64 tempLength = lengthInSamples;
  107039. FLAC__stream_decoder_reset (decoder);
  107040. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  107041. lengthInSamples = tempLength;
  107042. }
  107043. }
  107044. }
  107045. ~FlacReader()
  107046. {
  107047. FlacNamespace::FLAC__stream_decoder_delete (decoder);
  107048. }
  107049. void useMetadata (const FlacNamespace::FLAC__StreamMetadata_StreamInfo& info)
  107050. {
  107051. sampleRate = info.sample_rate;
  107052. bitsPerSample = info.bits_per_sample;
  107053. lengthInSamples = (unsigned int) info.total_samples;
  107054. numChannels = info.channels;
  107055. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  107056. }
  107057. // returns the number of samples read
  107058. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  107059. int64 startSampleInFile, int numSamples)
  107060. {
  107061. using namespace FlacNamespace;
  107062. if (! ok)
  107063. return false;
  107064. while (numSamples > 0)
  107065. {
  107066. if (startSampleInFile >= reservoirStart
  107067. && startSampleInFile < reservoirStart + samplesInReservoir)
  107068. {
  107069. const int num = (int) jmin ((int64) numSamples,
  107070. reservoirStart + samplesInReservoir - startSampleInFile);
  107071. jassert (num > 0);
  107072. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  107073. if (destSamples[i] != 0)
  107074. memcpy (destSamples[i] + startOffsetInDestBuffer,
  107075. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  107076. sizeof (int) * num);
  107077. startOffsetInDestBuffer += num;
  107078. startSampleInFile += num;
  107079. numSamples -= num;
  107080. }
  107081. else
  107082. {
  107083. if (startSampleInFile >= (int) lengthInSamples)
  107084. {
  107085. samplesInReservoir = 0;
  107086. }
  107087. else if (startSampleInFile < reservoirStart
  107088. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  107089. {
  107090. // had some problems with flac crashing if the read pos is aligned more
  107091. // accurately than this. Probably fixed in newer versions of the library, though.
  107092. reservoirStart = (int) (startSampleInFile & ~511);
  107093. samplesInReservoir = 0;
  107094. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  107095. }
  107096. else
  107097. {
  107098. reservoirStart += samplesInReservoir;
  107099. samplesInReservoir = 0;
  107100. FLAC__stream_decoder_process_single (decoder);
  107101. }
  107102. if (samplesInReservoir == 0)
  107103. break;
  107104. }
  107105. }
  107106. if (numSamples > 0)
  107107. {
  107108. for (int i = numDestChannels; --i >= 0;)
  107109. if (destSamples[i] != 0)
  107110. zeromem (destSamples[i] + startOffsetInDestBuffer,
  107111. sizeof (int) * numSamples);
  107112. }
  107113. return true;
  107114. }
  107115. void useSamples (const FlacNamespace::FLAC__int32* const buffer[], int numSamples)
  107116. {
  107117. if (scanningForLength)
  107118. {
  107119. lengthInSamples += numSamples;
  107120. }
  107121. else
  107122. {
  107123. if (numSamples > reservoir.getNumSamples())
  107124. reservoir.setSize (numChannels, numSamples, false, false, true);
  107125. const int bitsToShift = 32 - bitsPerSample;
  107126. for (int i = 0; i < (int) numChannels; ++i)
  107127. {
  107128. const FlacNamespace::FLAC__int32* src = buffer[i];
  107129. int n = i;
  107130. while (src == 0 && n > 0)
  107131. src = buffer [--n];
  107132. if (src != 0)
  107133. {
  107134. int* dest = reinterpret_cast<int*> (reservoir.getSampleData(i));
  107135. for (int j = 0; j < numSamples; ++j)
  107136. dest[j] = src[j] << bitsToShift;
  107137. }
  107138. }
  107139. samplesInReservoir = numSamples;
  107140. }
  107141. }
  107142. static FlacNamespace::FLAC__StreamDecoderReadStatus readCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__byte buffer[], size_t* bytes, void* client_data)
  107143. {
  107144. using namespace FlacNamespace;
  107145. *bytes = (size_t) static_cast <const FlacReader*> (client_data)->input->read (buffer, (int) *bytes);
  107146. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  107147. }
  107148. static FlacNamespace::FLAC__StreamDecoderSeekStatus seekCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64 absolute_byte_offset, void* client_data)
  107149. {
  107150. using namespace FlacNamespace;
  107151. static_cast <const FlacReader*> (client_data)->input->setPosition ((int) absolute_byte_offset);
  107152. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  107153. }
  107154. static FlacNamespace::FLAC__StreamDecoderTellStatus tellCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107155. {
  107156. using namespace FlacNamespace;
  107157. *absolute_byte_offset = static_cast <const FlacReader*> (client_data)->input->getPosition();
  107158. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  107159. }
  107160. static FlacNamespace::FLAC__StreamDecoderLengthStatus lengthCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__uint64* stream_length, void* client_data)
  107161. {
  107162. using namespace FlacNamespace;
  107163. *stream_length = static_cast <const FlacReader*> (client_data)->input->getTotalLength();
  107164. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  107165. }
  107166. static FlacNamespace::FLAC__bool eofCallback_ (const FlacNamespace::FLAC__StreamDecoder*, void* client_data)
  107167. {
  107168. return static_cast <const FlacReader*> (client_data)->input->isExhausted();
  107169. }
  107170. static FlacNamespace::FLAC__StreamDecoderWriteStatus writeCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107171. const FlacNamespace::FLAC__Frame* frame,
  107172. const FlacNamespace::FLAC__int32* const buffer[],
  107173. void* client_data)
  107174. {
  107175. using namespace FlacNamespace;
  107176. static_cast <FlacReader*> (client_data)->useSamples (buffer, frame->header.blocksize);
  107177. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  107178. }
  107179. static void metadataCallback_ (const FlacNamespace::FLAC__StreamDecoder*,
  107180. const FlacNamespace::FLAC__StreamMetadata* metadata,
  107181. void* client_data)
  107182. {
  107183. static_cast <FlacReader*> (client_data)->useMetadata (metadata->data.stream_info);
  107184. }
  107185. static void errorCallback_ (const FlacNamespace::FLAC__StreamDecoder*, FlacNamespace::FLAC__StreamDecoderErrorStatus, void*)
  107186. {
  107187. }
  107188. juce_UseDebuggingNewOperator
  107189. private:
  107190. FlacNamespace::FLAC__StreamDecoder* decoder;
  107191. AudioSampleBuffer reservoir;
  107192. int reservoirStart, samplesInReservoir;
  107193. bool ok, scanningForLength;
  107194. FlacReader (const FlacReader&);
  107195. FlacReader& operator= (const FlacReader&);
  107196. };
  107197. class FlacWriter : public AudioFormatWriter
  107198. {
  107199. public:
  107200. FlacWriter (OutputStream* const out, double sampleRate_,
  107201. int numChannels_, int bitsPerSample_, int qualityOptionIndex)
  107202. : AudioFormatWriter (out, TRANS (flacFormatName),
  107203. sampleRate_, numChannels_, bitsPerSample_)
  107204. {
  107205. using namespace FlacNamespace;
  107206. encoder = FLAC__stream_encoder_new();
  107207. if (qualityOptionIndex > 0)
  107208. FLAC__stream_encoder_set_compression_level (encoder, jmin (8, qualityOptionIndex));
  107209. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  107210. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  107211. FLAC__stream_encoder_set_channels (encoder, numChannels);
  107212. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin ((unsigned int) 24, bitsPerSample));
  107213. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  107214. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  107215. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  107216. ok = FLAC__stream_encoder_init_stream (encoder,
  107217. encodeWriteCallback, encodeSeekCallback,
  107218. encodeTellCallback, encodeMetadataCallback,
  107219. this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  107220. }
  107221. ~FlacWriter()
  107222. {
  107223. if (ok)
  107224. {
  107225. FlacNamespace::FLAC__stream_encoder_finish (encoder);
  107226. output->flush();
  107227. }
  107228. else
  107229. {
  107230. output = 0; // to stop the base class deleting this, as it needs to be returned
  107231. // to the caller of createWriter()
  107232. }
  107233. FlacNamespace::FLAC__stream_encoder_delete (encoder);
  107234. }
  107235. bool write (const int** samplesToWrite, int numSamples)
  107236. {
  107237. using namespace FlacNamespace;
  107238. if (! ok)
  107239. return false;
  107240. int* buf[3];
  107241. const int bitsToShift = 32 - bitsPerSample;
  107242. if (bitsToShift > 0)
  107243. {
  107244. const int numChannelsToWrite = (samplesToWrite[1] == 0) ? 1 : 2;
  107245. HeapBlock<int> temp (numSamples * numChannelsToWrite);
  107246. buf[0] = temp.getData();
  107247. buf[1] = temp.getData() + numSamples;
  107248. buf[2] = 0;
  107249. for (int i = numChannelsToWrite; --i >= 0;)
  107250. {
  107251. if (samplesToWrite[i] != 0)
  107252. {
  107253. for (int j = 0; j < numSamples; ++j)
  107254. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  107255. }
  107256. }
  107257. samplesToWrite = const_cast<const int**> (buf);
  107258. }
  107259. return FLAC__stream_encoder_process (encoder,
  107260. (const FLAC__int32**) samplesToWrite,
  107261. numSamples) != 0;
  107262. }
  107263. bool writeData (const void* const data, const int size) const
  107264. {
  107265. return output->write (data, size);
  107266. }
  107267. static void packUint32 (FlacNamespace::FLAC__uint32 val, FlacNamespace::FLAC__byte* b, const int bytes)
  107268. {
  107269. using namespace FlacNamespace;
  107270. b += bytes;
  107271. for (int i = 0; i < bytes; ++i)
  107272. {
  107273. *(--b) = (FLAC__byte) (val & 0xff);
  107274. val >>= 8;
  107275. }
  107276. }
  107277. void writeMetaData (const FlacNamespace::FLAC__StreamMetadata* metadata)
  107278. {
  107279. using namespace FlacNamespace;
  107280. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  107281. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  107282. const unsigned int channelsMinus1 = info.channels - 1;
  107283. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  107284. packUint32 (info.min_blocksize, buffer, 2);
  107285. packUint32 (info.max_blocksize, buffer + 2, 2);
  107286. packUint32 (info.min_framesize, buffer + 4, 3);
  107287. packUint32 (info.max_framesize, buffer + 7, 3);
  107288. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  107289. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  107290. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  107291. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  107292. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  107293. memcpy (buffer + 18, info.md5sum, 16);
  107294. const bool seekOk = output->setPosition (4);
  107295. (void) seekOk;
  107296. // if this fails, you've given it an output stream that can't seek! It needs
  107297. // to be able to seek back to write the header
  107298. jassert (seekOk);
  107299. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107300. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  107301. }
  107302. static FlacNamespace::FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FlacNamespace::FLAC__StreamEncoder*,
  107303. const FlacNamespace::FLAC__byte buffer[],
  107304. size_t bytes,
  107305. unsigned int /*samples*/,
  107306. unsigned int /*current_frame*/,
  107307. void* client_data)
  107308. {
  107309. using namespace FlacNamespace;
  107310. return static_cast <FlacWriter*> (client_data)->writeData (buffer, (int) bytes)
  107311. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  107312. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  107313. }
  107314. static FlacNamespace::FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64, void*)
  107315. {
  107316. using namespace FlacNamespace;
  107317. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  107318. }
  107319. static FlacNamespace::FLAC__StreamEncoderTellStatus encodeTellCallback (const FlacNamespace::FLAC__StreamEncoder*, FlacNamespace::FLAC__uint64* absolute_byte_offset, void* client_data)
  107320. {
  107321. using namespace FlacNamespace;
  107322. if (client_data == 0)
  107323. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  107324. *absolute_byte_offset = (FLAC__uint64) static_cast <FlacWriter*> (client_data)->output->getPosition();
  107325. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  107326. }
  107327. static void encodeMetadataCallback (const FlacNamespace::FLAC__StreamEncoder*, const FlacNamespace::FLAC__StreamMetadata* metadata, void* client_data)
  107328. {
  107329. static_cast <FlacWriter*> (client_data)->writeMetaData (metadata);
  107330. }
  107331. juce_UseDebuggingNewOperator
  107332. bool ok;
  107333. private:
  107334. FlacNamespace::FLAC__StreamEncoder* encoder;
  107335. FlacWriter (const FlacWriter&);
  107336. FlacWriter& operator= (const FlacWriter&);
  107337. };
  107338. FlacAudioFormat::FlacAudioFormat()
  107339. : AudioFormat (TRANS (flacFormatName), StringArray (flacExtensions))
  107340. {
  107341. }
  107342. FlacAudioFormat::~FlacAudioFormat()
  107343. {
  107344. }
  107345. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  107346. {
  107347. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  107348. return Array <int> (rates);
  107349. }
  107350. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  107351. {
  107352. const int depths[] = { 16, 24, 0 };
  107353. return Array <int> (depths);
  107354. }
  107355. bool FlacAudioFormat::canDoStereo() { return true; }
  107356. bool FlacAudioFormat::canDoMono() { return true; }
  107357. bool FlacAudioFormat::isCompressed() { return true; }
  107358. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  107359. const bool deleteStreamIfOpeningFails)
  107360. {
  107361. ScopedPointer<FlacReader> r (new FlacReader (in));
  107362. if (r->sampleRate != 0)
  107363. return r.release();
  107364. if (! deleteStreamIfOpeningFails)
  107365. r->input = 0;
  107366. return 0;
  107367. }
  107368. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  107369. double sampleRate,
  107370. unsigned int numberOfChannels,
  107371. int bitsPerSample,
  107372. const StringPairArray& /*metadataValues*/,
  107373. int qualityOptionIndex)
  107374. {
  107375. if (getPossibleBitDepths().contains (bitsPerSample))
  107376. {
  107377. ScopedPointer<FlacWriter> w (new FlacWriter (out, sampleRate, numberOfChannels, bitsPerSample, qualityOptionIndex));
  107378. if (w->ok)
  107379. return w.release();
  107380. }
  107381. return 0;
  107382. }
  107383. END_JUCE_NAMESPACE
  107384. #endif
  107385. /*** End of inlined file: juce_FlacAudioFormat.cpp ***/
  107386. /*** Start of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  107387. #if JUCE_USE_OGGVORBIS
  107388. #if JUCE_MAC
  107389. #define __MACOSX__ 1
  107390. #endif
  107391. namespace OggVorbisNamespace
  107392. {
  107393. #if JUCE_INCLUDE_OGGVORBIS_CODE
  107394. /*** Start of inlined file: vorbisenc.h ***/
  107395. #ifndef _OV_ENC_H_
  107396. #define _OV_ENC_H_
  107397. #ifdef __cplusplus
  107398. extern "C"
  107399. {
  107400. #endif /* __cplusplus */
  107401. /*** Start of inlined file: codec.h ***/
  107402. #ifndef _vorbis_codec_h_
  107403. #define _vorbis_codec_h_
  107404. #ifdef __cplusplus
  107405. extern "C"
  107406. {
  107407. #endif /* __cplusplus */
  107408. /*** Start of inlined file: ogg.h ***/
  107409. #ifndef _OGG_H
  107410. #define _OGG_H
  107411. #ifdef __cplusplus
  107412. extern "C" {
  107413. #endif
  107414. /*** Start of inlined file: os_types.h ***/
  107415. #ifndef _OS_TYPES_H
  107416. #define _OS_TYPES_H
  107417. /* make it easy on the folks that want to compile the libs with a
  107418. different malloc than stdlib */
  107419. #define _ogg_malloc malloc
  107420. #define _ogg_calloc calloc
  107421. #define _ogg_realloc realloc
  107422. #define _ogg_free free
  107423. #if defined(_WIN32)
  107424. # if defined(__CYGWIN__)
  107425. # include <_G_config.h>
  107426. typedef _G_int64_t ogg_int64_t;
  107427. typedef _G_int32_t ogg_int32_t;
  107428. typedef _G_uint32_t ogg_uint32_t;
  107429. typedef _G_int16_t ogg_int16_t;
  107430. typedef _G_uint16_t ogg_uint16_t;
  107431. # elif defined(__MINGW32__)
  107432. typedef short ogg_int16_t;
  107433. typedef unsigned short ogg_uint16_t;
  107434. typedef int ogg_int32_t;
  107435. typedef unsigned int ogg_uint32_t;
  107436. typedef long long ogg_int64_t;
  107437. typedef unsigned long long ogg_uint64_t;
  107438. # elif defined(__MWERKS__)
  107439. typedef long long ogg_int64_t;
  107440. typedef int ogg_int32_t;
  107441. typedef unsigned int ogg_uint32_t;
  107442. typedef short ogg_int16_t;
  107443. typedef unsigned short ogg_uint16_t;
  107444. # else
  107445. /* MSVC/Borland */
  107446. typedef __int64 ogg_int64_t;
  107447. typedef __int32 ogg_int32_t;
  107448. typedef unsigned __int32 ogg_uint32_t;
  107449. typedef __int16 ogg_int16_t;
  107450. typedef unsigned __int16 ogg_uint16_t;
  107451. # endif
  107452. #elif defined(__MACOS__)
  107453. # include <sys/types.h>
  107454. typedef SInt16 ogg_int16_t;
  107455. typedef UInt16 ogg_uint16_t;
  107456. typedef SInt32 ogg_int32_t;
  107457. typedef UInt32 ogg_uint32_t;
  107458. typedef SInt64 ogg_int64_t;
  107459. #elif defined(__MACOSX__) /* MacOS X Framework build */
  107460. # include <sys/types.h>
  107461. typedef int16_t ogg_int16_t;
  107462. typedef u_int16_t ogg_uint16_t;
  107463. typedef int32_t ogg_int32_t;
  107464. typedef u_int32_t ogg_uint32_t;
  107465. typedef int64_t ogg_int64_t;
  107466. #elif defined(__BEOS__)
  107467. /* Be */
  107468. # include <inttypes.h>
  107469. typedef int16_t ogg_int16_t;
  107470. typedef u_int16_t ogg_uint16_t;
  107471. typedef int32_t ogg_int32_t;
  107472. typedef u_int32_t ogg_uint32_t;
  107473. typedef int64_t ogg_int64_t;
  107474. #elif defined (__EMX__)
  107475. /* OS/2 GCC */
  107476. typedef short ogg_int16_t;
  107477. typedef unsigned short ogg_uint16_t;
  107478. typedef int ogg_int32_t;
  107479. typedef unsigned int ogg_uint32_t;
  107480. typedef long long ogg_int64_t;
  107481. #elif defined (DJGPP)
  107482. /* DJGPP */
  107483. typedef short ogg_int16_t;
  107484. typedef int ogg_int32_t;
  107485. typedef unsigned int ogg_uint32_t;
  107486. typedef long long ogg_int64_t;
  107487. #elif defined(R5900)
  107488. /* PS2 EE */
  107489. typedef long ogg_int64_t;
  107490. typedef int ogg_int32_t;
  107491. typedef unsigned ogg_uint32_t;
  107492. typedef short ogg_int16_t;
  107493. #elif defined(__SYMBIAN32__)
  107494. /* Symbian GCC */
  107495. typedef signed short ogg_int16_t;
  107496. typedef unsigned short ogg_uint16_t;
  107497. typedef signed int ogg_int32_t;
  107498. typedef unsigned int ogg_uint32_t;
  107499. typedef long long int ogg_int64_t;
  107500. #else
  107501. # include <sys/types.h>
  107502. /*** Start of inlined file: config_types.h ***/
  107503. #ifndef __CONFIG_TYPES_H__
  107504. #define __CONFIG_TYPES_H__
  107505. typedef int16_t ogg_int16_t;
  107506. typedef unsigned short ogg_uint16_t;
  107507. typedef int32_t ogg_int32_t;
  107508. typedef unsigned int ogg_uint32_t;
  107509. typedef int64_t ogg_int64_t;
  107510. #endif
  107511. /*** End of inlined file: config_types.h ***/
  107512. #endif
  107513. #endif /* _OS_TYPES_H */
  107514. /*** End of inlined file: os_types.h ***/
  107515. typedef struct {
  107516. long endbyte;
  107517. int endbit;
  107518. unsigned char *buffer;
  107519. unsigned char *ptr;
  107520. long storage;
  107521. } oggpack_buffer;
  107522. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  107523. typedef struct {
  107524. unsigned char *header;
  107525. long header_len;
  107526. unsigned char *body;
  107527. long body_len;
  107528. } ogg_page;
  107529. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  107530. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  107531. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  107532. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  107533. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  107534. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  107535. }
  107536. /* ogg_stream_state contains the current encode/decode state of a logical
  107537. Ogg bitstream **********************************************************/
  107538. typedef struct {
  107539. unsigned char *body_data; /* bytes from packet bodies */
  107540. long body_storage; /* storage elements allocated */
  107541. long body_fill; /* elements stored; fill mark */
  107542. long body_returned; /* elements of fill returned */
  107543. int *lacing_vals; /* The values that will go to the segment table */
  107544. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  107545. this way, but it is simple coupled to the
  107546. lacing fifo */
  107547. long lacing_storage;
  107548. long lacing_fill;
  107549. long lacing_packet;
  107550. long lacing_returned;
  107551. unsigned char header[282]; /* working space for header encode */
  107552. int header_fill;
  107553. int e_o_s; /* set when we have buffered the last packet in the
  107554. logical bitstream */
  107555. int b_o_s; /* set after we've written the initial page
  107556. of a logical bitstream */
  107557. long serialno;
  107558. long pageno;
  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_int64_t granulepos;
  107565. } ogg_stream_state;
  107566. /* ogg_packet is used to encapsulate the data and metadata belonging
  107567. to a single raw Ogg/Vorbis packet *************************************/
  107568. typedef struct {
  107569. unsigned char *packet;
  107570. long bytes;
  107571. long b_o_s;
  107572. long e_o_s;
  107573. ogg_int64_t granulepos;
  107574. ogg_int64_t packetno; /* sequence number for decode; the framing
  107575. knows where there's a hole in the data,
  107576. but we need coupling so that the codec
  107577. (which is in a seperate abstraction
  107578. layer) also knows about the gap */
  107579. } ogg_packet;
  107580. typedef struct {
  107581. unsigned char *data;
  107582. int storage;
  107583. int fill;
  107584. int returned;
  107585. int unsynced;
  107586. int headerbytes;
  107587. int bodybytes;
  107588. } ogg_sync_state;
  107589. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  107590. extern void oggpack_writeinit(oggpack_buffer *b);
  107591. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  107592. extern void oggpack_writealign(oggpack_buffer *b);
  107593. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  107594. extern void oggpack_reset(oggpack_buffer *b);
  107595. extern void oggpack_writeclear(oggpack_buffer *b);
  107596. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107597. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  107598. extern long oggpack_look(oggpack_buffer *b,int bits);
  107599. extern long oggpack_look1(oggpack_buffer *b);
  107600. extern void oggpack_adv(oggpack_buffer *b,int bits);
  107601. extern void oggpack_adv1(oggpack_buffer *b);
  107602. extern long oggpack_read(oggpack_buffer *b,int bits);
  107603. extern long oggpack_read1(oggpack_buffer *b);
  107604. extern long oggpack_bytes(oggpack_buffer *b);
  107605. extern long oggpack_bits(oggpack_buffer *b);
  107606. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  107607. extern void oggpackB_writeinit(oggpack_buffer *b);
  107608. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  107609. extern void oggpackB_writealign(oggpack_buffer *b);
  107610. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  107611. extern void oggpackB_reset(oggpack_buffer *b);
  107612. extern void oggpackB_writeclear(oggpack_buffer *b);
  107613. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  107614. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  107615. extern long oggpackB_look(oggpack_buffer *b,int bits);
  107616. extern long oggpackB_look1(oggpack_buffer *b);
  107617. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  107618. extern void oggpackB_adv1(oggpack_buffer *b);
  107619. extern long oggpackB_read(oggpack_buffer *b,int bits);
  107620. extern long oggpackB_read1(oggpack_buffer *b);
  107621. extern long oggpackB_bytes(oggpack_buffer *b);
  107622. extern long oggpackB_bits(oggpack_buffer *b);
  107623. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  107624. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  107625. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  107626. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  107627. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  107628. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  107629. extern int ogg_sync_init(ogg_sync_state *oy);
  107630. extern int ogg_sync_clear(ogg_sync_state *oy);
  107631. extern int ogg_sync_reset(ogg_sync_state *oy);
  107632. extern int ogg_sync_destroy(ogg_sync_state *oy);
  107633. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  107634. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  107635. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  107636. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  107637. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  107638. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  107639. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  107640. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  107641. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  107642. extern int ogg_stream_clear(ogg_stream_state *os);
  107643. extern int ogg_stream_reset(ogg_stream_state *os);
  107644. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  107645. extern int ogg_stream_destroy(ogg_stream_state *os);
  107646. extern int ogg_stream_eos(ogg_stream_state *os);
  107647. extern void ogg_page_checksum_set(ogg_page *og);
  107648. extern int ogg_page_version(ogg_page *og);
  107649. extern int ogg_page_continued(ogg_page *og);
  107650. extern int ogg_page_bos(ogg_page *og);
  107651. extern int ogg_page_eos(ogg_page *og);
  107652. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  107653. extern int ogg_page_serialno(ogg_page *og);
  107654. extern long ogg_page_pageno(ogg_page *og);
  107655. extern int ogg_page_packets(ogg_page *og);
  107656. extern void ogg_packet_clear(ogg_packet *op);
  107657. #ifdef __cplusplus
  107658. }
  107659. #endif
  107660. #endif /* _OGG_H */
  107661. /*** End of inlined file: ogg.h ***/
  107662. typedef struct vorbis_info{
  107663. int version;
  107664. int channels;
  107665. long rate;
  107666. /* The below bitrate declarations are *hints*.
  107667. Combinations of the three values carry the following implications:
  107668. all three set to the same value:
  107669. implies a fixed rate bitstream
  107670. only nominal set:
  107671. implies a VBR stream that averages the nominal bitrate. No hard
  107672. upper/lower limit
  107673. upper and or lower set:
  107674. implies a VBR bitstream that obeys the bitrate limits. nominal
  107675. may also be set to give a nominal rate.
  107676. none set:
  107677. the coder does not care to speculate.
  107678. */
  107679. long bitrate_upper;
  107680. long bitrate_nominal;
  107681. long bitrate_lower;
  107682. long bitrate_window;
  107683. void *codec_setup;
  107684. } vorbis_info;
  107685. /* vorbis_dsp_state buffers the current vorbis audio
  107686. analysis/synthesis state. The DSP state belongs to a specific
  107687. logical bitstream ****************************************************/
  107688. typedef struct vorbis_dsp_state{
  107689. int analysisp;
  107690. vorbis_info *vi;
  107691. float **pcm;
  107692. float **pcmret;
  107693. int pcm_storage;
  107694. int pcm_current;
  107695. int pcm_returned;
  107696. int preextrapolate;
  107697. int eofflag;
  107698. long lW;
  107699. long W;
  107700. long nW;
  107701. long centerW;
  107702. ogg_int64_t granulepos;
  107703. ogg_int64_t sequence;
  107704. ogg_int64_t glue_bits;
  107705. ogg_int64_t time_bits;
  107706. ogg_int64_t floor_bits;
  107707. ogg_int64_t res_bits;
  107708. void *backend_state;
  107709. } vorbis_dsp_state;
  107710. typedef struct vorbis_block{
  107711. /* necessary stream state for linking to the framing abstraction */
  107712. float **pcm; /* this is a pointer into local storage */
  107713. oggpack_buffer opb;
  107714. long lW;
  107715. long W;
  107716. long nW;
  107717. int pcmend;
  107718. int mode;
  107719. int eofflag;
  107720. ogg_int64_t granulepos;
  107721. ogg_int64_t sequence;
  107722. vorbis_dsp_state *vd; /* For read-only access of configuration */
  107723. /* local storage to avoid remallocing; it's up to the mapping to
  107724. structure it */
  107725. void *localstore;
  107726. long localtop;
  107727. long localalloc;
  107728. long totaluse;
  107729. struct alloc_chain *reap;
  107730. /* bitmetrics for the frame */
  107731. long glue_bits;
  107732. long time_bits;
  107733. long floor_bits;
  107734. long res_bits;
  107735. void *internal;
  107736. } vorbis_block;
  107737. /* vorbis_block is a single block of data to be processed as part of
  107738. the analysis/synthesis stream; it belongs to a specific logical
  107739. bitstream, but is independant from other vorbis_blocks belonging to
  107740. that logical bitstream. *************************************************/
  107741. struct alloc_chain{
  107742. void *ptr;
  107743. struct alloc_chain *next;
  107744. };
  107745. /* vorbis_info contains all the setup information specific to the
  107746. specific compression/decompression mode in progress (eg,
  107747. psychoacoustic settings, channel setup, options, codebook
  107748. etc). vorbis_info and substructures are in backends.h.
  107749. *********************************************************************/
  107750. /* the comments are not part of vorbis_info so that vorbis_info can be
  107751. static storage */
  107752. typedef struct vorbis_comment{
  107753. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  107754. whatever vendor is set to in encode */
  107755. char **user_comments;
  107756. int *comment_lengths;
  107757. int comments;
  107758. char *vendor;
  107759. } vorbis_comment;
  107760. /* libvorbis encodes in two abstraction layers; first we perform DSP
  107761. and produce a packet (see docs/analysis.txt). The packet is then
  107762. coded into a framed OggSquish bitstream by the second layer (see
  107763. docs/framing.txt). Decode is the reverse process; we sync/frame
  107764. the bitstream and extract individual packets, then decode the
  107765. packet back into PCM audio.
  107766. The extra framing/packetizing is used in streaming formats, such as
  107767. files. Over the net (such as with UDP), the framing and
  107768. packetization aren't necessary as they're provided by the transport
  107769. and the streaming layer is not used */
  107770. /* Vorbis PRIMITIVES: general ***************************************/
  107771. extern void vorbis_info_init(vorbis_info *vi);
  107772. extern void vorbis_info_clear(vorbis_info *vi);
  107773. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  107774. extern void vorbis_comment_init(vorbis_comment *vc);
  107775. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  107776. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  107777. const char *tag, char *contents);
  107778. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  107779. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  107780. extern void vorbis_comment_clear(vorbis_comment *vc);
  107781. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  107782. extern int vorbis_block_clear(vorbis_block *vb);
  107783. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  107784. extern double vorbis_granule_time(vorbis_dsp_state *v,
  107785. ogg_int64_t granulepos);
  107786. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  107787. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107788. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  107789. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  107790. vorbis_comment *vc,
  107791. ogg_packet *op,
  107792. ogg_packet *op_comm,
  107793. ogg_packet *op_code);
  107794. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  107795. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  107796. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  107797. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  107798. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  107799. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  107800. ogg_packet *op);
  107801. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  107802. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  107803. ogg_packet *op);
  107804. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  107805. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  107806. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  107807. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  107808. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  107809. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  107810. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  107811. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  107812. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  107813. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  107814. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  107815. /* Vorbis ERRORS and return codes ***********************************/
  107816. #define OV_FALSE -1
  107817. #define OV_EOF -2
  107818. #define OV_HOLE -3
  107819. #define OV_EREAD -128
  107820. #define OV_EFAULT -129
  107821. #define OV_EIMPL -130
  107822. #define OV_EINVAL -131
  107823. #define OV_ENOTVORBIS -132
  107824. #define OV_EBADHEADER -133
  107825. #define OV_EVERSION -134
  107826. #define OV_ENOTAUDIO -135
  107827. #define OV_EBADPACKET -136
  107828. #define OV_EBADLINK -137
  107829. #define OV_ENOSEEK -138
  107830. #ifdef __cplusplus
  107831. }
  107832. #endif /* __cplusplus */
  107833. #endif
  107834. /*** End of inlined file: codec.h ***/
  107835. extern int vorbis_encode_init(vorbis_info *vi,
  107836. long channels,
  107837. long rate,
  107838. long max_bitrate,
  107839. long nominal_bitrate,
  107840. long min_bitrate);
  107841. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  107842. long channels,
  107843. long rate,
  107844. long max_bitrate,
  107845. long nominal_bitrate,
  107846. long min_bitrate);
  107847. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  107848. long channels,
  107849. long rate,
  107850. float quality /* quality level from 0. (lo) to 1. (hi) */
  107851. );
  107852. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  107853. long channels,
  107854. long rate,
  107855. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  107856. );
  107857. extern int vorbis_encode_setup_init(vorbis_info *vi);
  107858. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  107859. /* deprecated rate management supported only for compatability */
  107860. #define OV_ECTL_RATEMANAGE_GET 0x10
  107861. #define OV_ECTL_RATEMANAGE_SET 0x11
  107862. #define OV_ECTL_RATEMANAGE_AVG 0x12
  107863. #define OV_ECTL_RATEMANAGE_HARD 0x13
  107864. struct ovectl_ratemanage_arg {
  107865. int management_active;
  107866. long bitrate_hard_min;
  107867. long bitrate_hard_max;
  107868. double bitrate_hard_window;
  107869. long bitrate_av_lo;
  107870. long bitrate_av_hi;
  107871. double bitrate_av_window;
  107872. double bitrate_av_window_center;
  107873. };
  107874. /* new rate setup */
  107875. #define OV_ECTL_RATEMANAGE2_GET 0x14
  107876. #define OV_ECTL_RATEMANAGE2_SET 0x15
  107877. struct ovectl_ratemanage2_arg {
  107878. int management_active;
  107879. long bitrate_limit_min_kbps;
  107880. long bitrate_limit_max_kbps;
  107881. long bitrate_limit_reservoir_bits;
  107882. double bitrate_limit_reservoir_bias;
  107883. long bitrate_average_kbps;
  107884. double bitrate_average_damping;
  107885. };
  107886. #define OV_ECTL_LOWPASS_GET 0x20
  107887. #define OV_ECTL_LOWPASS_SET 0x21
  107888. #define OV_ECTL_IBLOCK_GET 0x30
  107889. #define OV_ECTL_IBLOCK_SET 0x31
  107890. #ifdef __cplusplus
  107891. }
  107892. #endif /* __cplusplus */
  107893. #endif
  107894. /*** End of inlined file: vorbisenc.h ***/
  107895. /*** Start of inlined file: vorbisfile.h ***/
  107896. #ifndef _OV_FILE_H_
  107897. #define _OV_FILE_H_
  107898. #ifdef __cplusplus
  107899. extern "C"
  107900. {
  107901. #endif /* __cplusplus */
  107902. #include <stdio.h>
  107903. /* The function prototypes for the callbacks are basically the same as for
  107904. * the stdio functions fread, fseek, fclose, ftell.
  107905. * The one difference is that the FILE * arguments have been replaced with
  107906. * a void * - this is to be used as a pointer to whatever internal data these
  107907. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  107908. *
  107909. * If you use other functions, check the docs for these functions and return
  107910. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  107911. * unseekable
  107912. */
  107913. typedef struct {
  107914. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  107915. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  107916. int (*close_func) (void *datasource);
  107917. long (*tell_func) (void *datasource);
  107918. } ov_callbacks;
  107919. #define NOTOPEN 0
  107920. #define PARTOPEN 1
  107921. #define OPENED 2
  107922. #define STREAMSET 3
  107923. #define INITSET 4
  107924. typedef struct OggVorbis_File {
  107925. void *datasource; /* Pointer to a FILE *, etc. */
  107926. int seekable;
  107927. ogg_int64_t offset;
  107928. ogg_int64_t end;
  107929. ogg_sync_state oy;
  107930. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  107931. stream appears */
  107932. int links;
  107933. ogg_int64_t *offsets;
  107934. ogg_int64_t *dataoffsets;
  107935. long *serialnos;
  107936. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  107937. compatability; x2 size, stores both
  107938. beginning and end values */
  107939. vorbis_info *vi;
  107940. vorbis_comment *vc;
  107941. /* Decoding working state local storage */
  107942. ogg_int64_t pcm_offset;
  107943. int ready_state;
  107944. long current_serialno;
  107945. int current_link;
  107946. double bittrack;
  107947. double samptrack;
  107948. ogg_stream_state os; /* take physical pages, weld into a logical
  107949. stream of packets */
  107950. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  107951. vorbis_block vb; /* local working space for packet->PCM decode */
  107952. ov_callbacks callbacks;
  107953. } OggVorbis_File;
  107954. extern int ov_clear(OggVorbis_File *vf);
  107955. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107956. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  107957. char *initial, long ibytes, ov_callbacks callbacks);
  107958. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  107959. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  107960. char *initial, long ibytes, ov_callbacks callbacks);
  107961. extern int ov_test_open(OggVorbis_File *vf);
  107962. extern long ov_bitrate(OggVorbis_File *vf,int i);
  107963. extern long ov_bitrate_instant(OggVorbis_File *vf);
  107964. extern long ov_streams(OggVorbis_File *vf);
  107965. extern long ov_seekable(OggVorbis_File *vf);
  107966. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  107967. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  107968. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  107969. extern double ov_time_total(OggVorbis_File *vf,int i);
  107970. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107971. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  107972. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  107973. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  107974. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  107975. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107976. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107977. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  107978. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  107979. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  107980. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  107981. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  107982. extern double ov_time_tell(OggVorbis_File *vf);
  107983. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  107984. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  107985. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  107986. int *bitstream);
  107987. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  107988. int bigendianp,int word,int sgned,int *bitstream);
  107989. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  107990. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  107991. extern int ov_halfrate_p(OggVorbis_File *vf);
  107992. #ifdef __cplusplus
  107993. }
  107994. #endif /* __cplusplus */
  107995. #endif
  107996. /*** End of inlined file: vorbisfile.h ***/
  107997. /*** Start of inlined file: bitwise.c ***/
  107998. /* We're 'LSb' endian; if we write a word but read individual bits,
  107999. then we'll read the lsb first */
  108000. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108001. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108002. // tasks..
  108003. #if JUCE_MSVC
  108004. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108005. #endif
  108006. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108007. #if JUCE_USE_OGGVORBIS
  108008. #include <string.h>
  108009. #include <stdlib.h>
  108010. #define BUFFER_INCREMENT 256
  108011. static const unsigned long mask[]=
  108012. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  108013. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  108014. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  108015. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  108016. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  108017. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  108018. 0x3fffffff,0x7fffffff,0xffffffff };
  108019. static const unsigned int mask8B[]=
  108020. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  108021. void oggpack_writeinit(oggpack_buffer *b){
  108022. memset(b,0,sizeof(*b));
  108023. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  108024. b->buffer[0]='\0';
  108025. b->storage=BUFFER_INCREMENT;
  108026. }
  108027. void oggpackB_writeinit(oggpack_buffer *b){
  108028. oggpack_writeinit(b);
  108029. }
  108030. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  108031. long bytes=bits>>3;
  108032. bits-=bytes*8;
  108033. b->ptr=b->buffer+bytes;
  108034. b->endbit=bits;
  108035. b->endbyte=bytes;
  108036. *b->ptr&=mask[bits];
  108037. }
  108038. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  108039. long bytes=bits>>3;
  108040. bits-=bytes*8;
  108041. b->ptr=b->buffer+bytes;
  108042. b->endbit=bits;
  108043. b->endbyte=bytes;
  108044. *b->ptr&=mask8B[bits];
  108045. }
  108046. /* Takes only up to 32 bits. */
  108047. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  108048. if(b->endbyte+4>=b->storage){
  108049. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108050. b->storage+=BUFFER_INCREMENT;
  108051. b->ptr=b->buffer+b->endbyte;
  108052. }
  108053. value&=mask[bits];
  108054. bits+=b->endbit;
  108055. b->ptr[0]|=value<<b->endbit;
  108056. if(bits>=8){
  108057. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  108058. if(bits>=16){
  108059. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  108060. if(bits>=24){
  108061. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  108062. if(bits>=32){
  108063. if(b->endbit)
  108064. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  108065. else
  108066. b->ptr[4]=0;
  108067. }
  108068. }
  108069. }
  108070. }
  108071. b->endbyte+=bits/8;
  108072. b->ptr+=bits/8;
  108073. b->endbit=bits&7;
  108074. }
  108075. /* Takes only up to 32 bits. */
  108076. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  108077. if(b->endbyte+4>=b->storage){
  108078. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  108079. b->storage+=BUFFER_INCREMENT;
  108080. b->ptr=b->buffer+b->endbyte;
  108081. }
  108082. value=(value&mask[bits])<<(32-bits);
  108083. bits+=b->endbit;
  108084. b->ptr[0]|=value>>(24+b->endbit);
  108085. if(bits>=8){
  108086. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  108087. if(bits>=16){
  108088. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  108089. if(bits>=24){
  108090. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  108091. if(bits>=32){
  108092. if(b->endbit)
  108093. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  108094. else
  108095. b->ptr[4]=0;
  108096. }
  108097. }
  108098. }
  108099. }
  108100. b->endbyte+=bits/8;
  108101. b->ptr+=bits/8;
  108102. b->endbit=bits&7;
  108103. }
  108104. void oggpack_writealign(oggpack_buffer *b){
  108105. int bits=8-b->endbit;
  108106. if(bits<8)
  108107. oggpack_write(b,0,bits);
  108108. }
  108109. void oggpackB_writealign(oggpack_buffer *b){
  108110. int bits=8-b->endbit;
  108111. if(bits<8)
  108112. oggpackB_write(b,0,bits);
  108113. }
  108114. static void oggpack_writecopy_helper(oggpack_buffer *b,
  108115. void *source,
  108116. long bits,
  108117. void (*w)(oggpack_buffer *,
  108118. unsigned long,
  108119. int),
  108120. int msb){
  108121. unsigned char *ptr=(unsigned char *)source;
  108122. long bytes=bits/8;
  108123. bits-=bytes*8;
  108124. if(b->endbit){
  108125. int i;
  108126. /* unaligned copy. Do it the hard way. */
  108127. for(i=0;i<bytes;i++)
  108128. w(b,(unsigned long)(ptr[i]),8);
  108129. }else{
  108130. /* aligned block copy */
  108131. if(b->endbyte+bytes+1>=b->storage){
  108132. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  108133. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  108134. b->ptr=b->buffer+b->endbyte;
  108135. }
  108136. memmove(b->ptr,source,bytes);
  108137. b->ptr+=bytes;
  108138. b->endbyte+=bytes;
  108139. *b->ptr=0;
  108140. }
  108141. if(bits){
  108142. if(msb)
  108143. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  108144. else
  108145. w(b,(unsigned long)(ptr[bytes]),bits);
  108146. }
  108147. }
  108148. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  108149. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  108150. }
  108151. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  108152. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  108153. }
  108154. void oggpack_reset(oggpack_buffer *b){
  108155. b->ptr=b->buffer;
  108156. b->buffer[0]=0;
  108157. b->endbit=b->endbyte=0;
  108158. }
  108159. void oggpackB_reset(oggpack_buffer *b){
  108160. oggpack_reset(b);
  108161. }
  108162. void oggpack_writeclear(oggpack_buffer *b){
  108163. _ogg_free(b->buffer);
  108164. memset(b,0,sizeof(*b));
  108165. }
  108166. void oggpackB_writeclear(oggpack_buffer *b){
  108167. oggpack_writeclear(b);
  108168. }
  108169. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108170. memset(b,0,sizeof(*b));
  108171. b->buffer=b->ptr=buf;
  108172. b->storage=bytes;
  108173. }
  108174. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  108175. oggpack_readinit(b,buf,bytes);
  108176. }
  108177. /* Read in bits without advancing the bitptr; bits <= 32 */
  108178. long oggpack_look(oggpack_buffer *b,int bits){
  108179. unsigned long ret;
  108180. unsigned long m=mask[bits];
  108181. bits+=b->endbit;
  108182. if(b->endbyte+4>=b->storage){
  108183. /* not the main path */
  108184. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108185. }
  108186. ret=b->ptr[0]>>b->endbit;
  108187. if(bits>8){
  108188. ret|=b->ptr[1]<<(8-b->endbit);
  108189. if(bits>16){
  108190. ret|=b->ptr[2]<<(16-b->endbit);
  108191. if(bits>24){
  108192. ret|=b->ptr[3]<<(24-b->endbit);
  108193. if(bits>32 && b->endbit)
  108194. ret|=b->ptr[4]<<(32-b->endbit);
  108195. }
  108196. }
  108197. }
  108198. return(m&ret);
  108199. }
  108200. /* Read in bits without advancing the bitptr; bits <= 32 */
  108201. long oggpackB_look(oggpack_buffer *b,int bits){
  108202. unsigned long ret;
  108203. int m=32-bits;
  108204. bits+=b->endbit;
  108205. if(b->endbyte+4>=b->storage){
  108206. /* not the main path */
  108207. if(b->endbyte*8+bits>b->storage*8)return(-1);
  108208. }
  108209. ret=b->ptr[0]<<(24+b->endbit);
  108210. if(bits>8){
  108211. ret|=b->ptr[1]<<(16+b->endbit);
  108212. if(bits>16){
  108213. ret|=b->ptr[2]<<(8+b->endbit);
  108214. if(bits>24){
  108215. ret|=b->ptr[3]<<(b->endbit);
  108216. if(bits>32 && b->endbit)
  108217. ret|=b->ptr[4]>>(8-b->endbit);
  108218. }
  108219. }
  108220. }
  108221. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  108222. }
  108223. long oggpack_look1(oggpack_buffer *b){
  108224. if(b->endbyte>=b->storage)return(-1);
  108225. return((b->ptr[0]>>b->endbit)&1);
  108226. }
  108227. long oggpackB_look1(oggpack_buffer *b){
  108228. if(b->endbyte>=b->storage)return(-1);
  108229. return((b->ptr[0]>>(7-b->endbit))&1);
  108230. }
  108231. void oggpack_adv(oggpack_buffer *b,int bits){
  108232. bits+=b->endbit;
  108233. b->ptr+=bits/8;
  108234. b->endbyte+=bits/8;
  108235. b->endbit=bits&7;
  108236. }
  108237. void oggpackB_adv(oggpack_buffer *b,int bits){
  108238. oggpack_adv(b,bits);
  108239. }
  108240. void oggpack_adv1(oggpack_buffer *b){
  108241. if(++(b->endbit)>7){
  108242. b->endbit=0;
  108243. b->ptr++;
  108244. b->endbyte++;
  108245. }
  108246. }
  108247. void oggpackB_adv1(oggpack_buffer *b){
  108248. oggpack_adv1(b);
  108249. }
  108250. /* bits <= 32 */
  108251. long oggpack_read(oggpack_buffer *b,int bits){
  108252. long ret;
  108253. unsigned long m=mask[bits];
  108254. bits+=b->endbit;
  108255. if(b->endbyte+4>=b->storage){
  108256. /* not the main path */
  108257. ret=-1L;
  108258. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108259. }
  108260. ret=b->ptr[0]>>b->endbit;
  108261. if(bits>8){
  108262. ret|=b->ptr[1]<<(8-b->endbit);
  108263. if(bits>16){
  108264. ret|=b->ptr[2]<<(16-b->endbit);
  108265. if(bits>24){
  108266. ret|=b->ptr[3]<<(24-b->endbit);
  108267. if(bits>32 && b->endbit){
  108268. ret|=b->ptr[4]<<(32-b->endbit);
  108269. }
  108270. }
  108271. }
  108272. }
  108273. ret&=m;
  108274. overflow:
  108275. b->ptr+=bits/8;
  108276. b->endbyte+=bits/8;
  108277. b->endbit=bits&7;
  108278. return(ret);
  108279. }
  108280. /* bits <= 32 */
  108281. long oggpackB_read(oggpack_buffer *b,int bits){
  108282. long ret;
  108283. long m=32-bits;
  108284. bits+=b->endbit;
  108285. if(b->endbyte+4>=b->storage){
  108286. /* not the main path */
  108287. ret=-1L;
  108288. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  108289. }
  108290. ret=b->ptr[0]<<(24+b->endbit);
  108291. if(bits>8){
  108292. ret|=b->ptr[1]<<(16+b->endbit);
  108293. if(bits>16){
  108294. ret|=b->ptr[2]<<(8+b->endbit);
  108295. if(bits>24){
  108296. ret|=b->ptr[3]<<(b->endbit);
  108297. if(bits>32 && b->endbit)
  108298. ret|=b->ptr[4]>>(8-b->endbit);
  108299. }
  108300. }
  108301. }
  108302. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  108303. overflow:
  108304. b->ptr+=bits/8;
  108305. b->endbyte+=bits/8;
  108306. b->endbit=bits&7;
  108307. return(ret);
  108308. }
  108309. long oggpack_read1(oggpack_buffer *b){
  108310. long ret;
  108311. if(b->endbyte>=b->storage){
  108312. /* not the main path */
  108313. ret=-1L;
  108314. goto overflow;
  108315. }
  108316. ret=(b->ptr[0]>>b->endbit)&1;
  108317. overflow:
  108318. b->endbit++;
  108319. if(b->endbit>7){
  108320. b->endbit=0;
  108321. b->ptr++;
  108322. b->endbyte++;
  108323. }
  108324. return(ret);
  108325. }
  108326. long oggpackB_read1(oggpack_buffer *b){
  108327. long ret;
  108328. if(b->endbyte>=b->storage){
  108329. /* not the main path */
  108330. ret=-1L;
  108331. goto overflow;
  108332. }
  108333. ret=(b->ptr[0]>>(7-b->endbit))&1;
  108334. overflow:
  108335. b->endbit++;
  108336. if(b->endbit>7){
  108337. b->endbit=0;
  108338. b->ptr++;
  108339. b->endbyte++;
  108340. }
  108341. return(ret);
  108342. }
  108343. long oggpack_bytes(oggpack_buffer *b){
  108344. return(b->endbyte+(b->endbit+7)/8);
  108345. }
  108346. long oggpack_bits(oggpack_buffer *b){
  108347. return(b->endbyte*8+b->endbit);
  108348. }
  108349. long oggpackB_bytes(oggpack_buffer *b){
  108350. return oggpack_bytes(b);
  108351. }
  108352. long oggpackB_bits(oggpack_buffer *b){
  108353. return oggpack_bits(b);
  108354. }
  108355. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  108356. return(b->buffer);
  108357. }
  108358. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  108359. return oggpack_get_buffer(b);
  108360. }
  108361. /* Self test of the bitwise routines; everything else is based on
  108362. them, so they damned well better be solid. */
  108363. #ifdef _V_SELFTEST
  108364. #include <stdio.h>
  108365. static int ilog(unsigned int v){
  108366. int ret=0;
  108367. while(v){
  108368. ret++;
  108369. v>>=1;
  108370. }
  108371. return(ret);
  108372. }
  108373. oggpack_buffer o;
  108374. oggpack_buffer r;
  108375. void report(char *in){
  108376. fprintf(stderr,"%s",in);
  108377. exit(1);
  108378. }
  108379. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108380. long bytes,i;
  108381. unsigned char *buffer;
  108382. oggpack_reset(&o);
  108383. for(i=0;i<vals;i++)
  108384. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  108385. buffer=oggpack_get_buffer(&o);
  108386. bytes=oggpack_bytes(&o);
  108387. if(bytes!=compsize)report("wrong number of bytes!\n");
  108388. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108389. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108390. report("wrote incorrect value!\n");
  108391. }
  108392. oggpack_readinit(&r,buffer,bytes);
  108393. for(i=0;i<vals;i++){
  108394. int tbit=bits?bits:ilog(b[i]);
  108395. if(oggpack_look(&r,tbit)==-1)
  108396. report("out of data!\n");
  108397. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  108398. report("looked at incorrect value!\n");
  108399. if(tbit==1)
  108400. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  108401. report("looked at single bit incorrect value!\n");
  108402. if(tbit==1){
  108403. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  108404. report("read incorrect single bit value!\n");
  108405. }else{
  108406. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  108407. report("read incorrect value!\n");
  108408. }
  108409. }
  108410. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108411. }
  108412. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  108413. long bytes,i;
  108414. unsigned char *buffer;
  108415. oggpackB_reset(&o);
  108416. for(i=0;i<vals;i++)
  108417. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  108418. buffer=oggpackB_get_buffer(&o);
  108419. bytes=oggpackB_bytes(&o);
  108420. if(bytes!=compsize)report("wrong number of bytes!\n");
  108421. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  108422. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  108423. report("wrote incorrect value!\n");
  108424. }
  108425. oggpackB_readinit(&r,buffer,bytes);
  108426. for(i=0;i<vals;i++){
  108427. int tbit=bits?bits:ilog(b[i]);
  108428. if(oggpackB_look(&r,tbit)==-1)
  108429. report("out of data!\n");
  108430. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  108431. report("looked at incorrect value!\n");
  108432. if(tbit==1)
  108433. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  108434. report("looked at single bit incorrect value!\n");
  108435. if(tbit==1){
  108436. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  108437. report("read incorrect single bit value!\n");
  108438. }else{
  108439. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  108440. report("read incorrect value!\n");
  108441. }
  108442. }
  108443. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108444. }
  108445. int main(void){
  108446. unsigned char *buffer;
  108447. long bytes,i;
  108448. static unsigned long testbuffer1[]=
  108449. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  108450. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  108451. int test1size=43;
  108452. static unsigned long testbuffer2[]=
  108453. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  108454. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  108455. 85525151,0,12321,1,349528352};
  108456. int test2size=21;
  108457. static unsigned long testbuffer3[]=
  108458. {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,
  108459. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  108460. int test3size=56;
  108461. static unsigned long large[]=
  108462. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  108463. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  108464. 85525151,0,12321,1,2146528352};
  108465. int onesize=33;
  108466. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  108467. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  108468. 223,4};
  108469. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  108470. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  108471. 245,251,128};
  108472. int twosize=6;
  108473. static int two[6]={61,255,255,251,231,29};
  108474. static int twoB[6]={247,63,255,253,249,120};
  108475. int threesize=54;
  108476. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  108477. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  108478. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  108479. 100,52,4,14,18,86,77,1};
  108480. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  108481. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  108482. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  108483. 200,20,254,4,58,106,176,144,0};
  108484. int foursize=38;
  108485. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  108486. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  108487. 28,2,133,0,1};
  108488. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  108489. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  108490. 129,10,4,32};
  108491. int fivesize=45;
  108492. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  108493. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  108494. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  108495. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  108496. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  108497. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  108498. int sixsize=7;
  108499. static int six[7]={17,177,170,242,169,19,148};
  108500. static int sixB[7]={136,141,85,79,149,200,41};
  108501. /* Test read/write together */
  108502. /* Later we test against pregenerated bitstreams */
  108503. oggpack_writeinit(&o);
  108504. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  108505. cliptest(testbuffer1,test1size,0,one,onesize);
  108506. fprintf(stderr,"ok.");
  108507. fprintf(stderr,"\nNull bit call (LSb): ");
  108508. cliptest(testbuffer3,test3size,0,two,twosize);
  108509. fprintf(stderr,"ok.");
  108510. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  108511. cliptest(testbuffer2,test2size,0,three,threesize);
  108512. fprintf(stderr,"ok.");
  108513. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  108514. oggpack_reset(&o);
  108515. for(i=0;i<test2size;i++)
  108516. oggpack_write(&o,large[i],32);
  108517. buffer=oggpack_get_buffer(&o);
  108518. bytes=oggpack_bytes(&o);
  108519. oggpack_readinit(&r,buffer,bytes);
  108520. for(i=0;i<test2size;i++){
  108521. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  108522. if(oggpack_look(&r,32)!=large[i]){
  108523. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  108524. oggpack_look(&r,32),large[i]);
  108525. report("read incorrect value!\n");
  108526. }
  108527. oggpack_adv(&r,32);
  108528. }
  108529. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108530. fprintf(stderr,"ok.");
  108531. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  108532. cliptest(testbuffer1,test1size,7,four,foursize);
  108533. fprintf(stderr,"ok.");
  108534. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  108535. cliptest(testbuffer2,test2size,17,five,fivesize);
  108536. fprintf(stderr,"ok.");
  108537. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  108538. cliptest(testbuffer3,test3size,1,six,sixsize);
  108539. fprintf(stderr,"ok.");
  108540. fprintf(stderr,"\nTesting read past end (LSb): ");
  108541. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108542. for(i=0;i<64;i++){
  108543. if(oggpack_read(&r,1)!=0){
  108544. fprintf(stderr,"failed; got -1 prematurely.\n");
  108545. exit(1);
  108546. }
  108547. }
  108548. if(oggpack_look(&r,1)!=-1 ||
  108549. oggpack_read(&r,1)!=-1){
  108550. fprintf(stderr,"failed; read past end without -1.\n");
  108551. exit(1);
  108552. }
  108553. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108554. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  108555. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108556. exit(1);
  108557. }
  108558. if(oggpack_look(&r,18)!=0 ||
  108559. oggpack_look(&r,18)!=0){
  108560. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108561. exit(1);
  108562. }
  108563. if(oggpack_look(&r,19)!=-1 ||
  108564. oggpack_look(&r,19)!=-1){
  108565. fprintf(stderr,"failed; read past end without -1.\n");
  108566. exit(1);
  108567. }
  108568. if(oggpack_look(&r,32)!=-1 ||
  108569. oggpack_look(&r,32)!=-1){
  108570. fprintf(stderr,"failed; read past end without -1.\n");
  108571. exit(1);
  108572. }
  108573. oggpack_writeclear(&o);
  108574. fprintf(stderr,"ok.\n");
  108575. /********** lazy, cut-n-paste retest with MSb packing ***********/
  108576. /* Test read/write together */
  108577. /* Later we test against pregenerated bitstreams */
  108578. oggpackB_writeinit(&o);
  108579. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  108580. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  108581. fprintf(stderr,"ok.");
  108582. fprintf(stderr,"\nNull bit call (MSb): ");
  108583. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  108584. fprintf(stderr,"ok.");
  108585. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  108586. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  108587. fprintf(stderr,"ok.");
  108588. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  108589. oggpackB_reset(&o);
  108590. for(i=0;i<test2size;i++)
  108591. oggpackB_write(&o,large[i],32);
  108592. buffer=oggpackB_get_buffer(&o);
  108593. bytes=oggpackB_bytes(&o);
  108594. oggpackB_readinit(&r,buffer,bytes);
  108595. for(i=0;i<test2size;i++){
  108596. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  108597. if(oggpackB_look(&r,32)!=large[i]){
  108598. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  108599. oggpackB_look(&r,32),large[i]);
  108600. report("read incorrect value!\n");
  108601. }
  108602. oggpackB_adv(&r,32);
  108603. }
  108604. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  108605. fprintf(stderr,"ok.");
  108606. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  108607. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  108608. fprintf(stderr,"ok.");
  108609. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  108610. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  108611. fprintf(stderr,"ok.");
  108612. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  108613. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  108614. fprintf(stderr,"ok.");
  108615. fprintf(stderr,"\nTesting read past end (MSb): ");
  108616. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108617. for(i=0;i<64;i++){
  108618. if(oggpackB_read(&r,1)!=0){
  108619. fprintf(stderr,"failed; got -1 prematurely.\n");
  108620. exit(1);
  108621. }
  108622. }
  108623. if(oggpackB_look(&r,1)!=-1 ||
  108624. oggpackB_read(&r,1)!=-1){
  108625. fprintf(stderr,"failed; read past end without -1.\n");
  108626. exit(1);
  108627. }
  108628. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  108629. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  108630. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  108631. exit(1);
  108632. }
  108633. if(oggpackB_look(&r,18)!=0 ||
  108634. oggpackB_look(&r,18)!=0){
  108635. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  108636. exit(1);
  108637. }
  108638. if(oggpackB_look(&r,19)!=-1 ||
  108639. oggpackB_look(&r,19)!=-1){
  108640. fprintf(stderr,"failed; read past end without -1.\n");
  108641. exit(1);
  108642. }
  108643. if(oggpackB_look(&r,32)!=-1 ||
  108644. oggpackB_look(&r,32)!=-1){
  108645. fprintf(stderr,"failed; read past end without -1.\n");
  108646. exit(1);
  108647. }
  108648. oggpackB_writeclear(&o);
  108649. fprintf(stderr,"ok.\n\n");
  108650. return(0);
  108651. }
  108652. #endif /* _V_SELFTEST */
  108653. #undef BUFFER_INCREMENT
  108654. #endif
  108655. /*** End of inlined file: bitwise.c ***/
  108656. /*** Start of inlined file: framing.c ***/
  108657. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  108658. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108659. // tasks..
  108660. #if JUCE_MSVC
  108661. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108662. #endif
  108663. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  108664. #if JUCE_USE_OGGVORBIS
  108665. #include <stdlib.h>
  108666. #include <string.h>
  108667. /* A complete description of Ogg framing exists in docs/framing.html */
  108668. int ogg_page_version(ogg_page *og){
  108669. return((int)(og->header[4]));
  108670. }
  108671. int ogg_page_continued(ogg_page *og){
  108672. return((int)(og->header[5]&0x01));
  108673. }
  108674. int ogg_page_bos(ogg_page *og){
  108675. return((int)(og->header[5]&0x02));
  108676. }
  108677. int ogg_page_eos(ogg_page *og){
  108678. return((int)(og->header[5]&0x04));
  108679. }
  108680. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  108681. unsigned char *page=og->header;
  108682. ogg_int64_t granulepos=page[13]&(0xff);
  108683. granulepos= (granulepos<<8)|(page[12]&0xff);
  108684. granulepos= (granulepos<<8)|(page[11]&0xff);
  108685. granulepos= (granulepos<<8)|(page[10]&0xff);
  108686. granulepos= (granulepos<<8)|(page[9]&0xff);
  108687. granulepos= (granulepos<<8)|(page[8]&0xff);
  108688. granulepos= (granulepos<<8)|(page[7]&0xff);
  108689. granulepos= (granulepos<<8)|(page[6]&0xff);
  108690. return(granulepos);
  108691. }
  108692. int ogg_page_serialno(ogg_page *og){
  108693. return(og->header[14] |
  108694. (og->header[15]<<8) |
  108695. (og->header[16]<<16) |
  108696. (og->header[17]<<24));
  108697. }
  108698. long ogg_page_pageno(ogg_page *og){
  108699. return(og->header[18] |
  108700. (og->header[19]<<8) |
  108701. (og->header[20]<<16) |
  108702. (og->header[21]<<24));
  108703. }
  108704. /* returns the number of packets that are completed on this page (if
  108705. the leading packet is begun on a previous page, but ends on this
  108706. page, it's counted */
  108707. /* NOTE:
  108708. If a page consists of a packet begun on a previous page, and a new
  108709. packet begun (but not completed) on this page, the return will be:
  108710. ogg_page_packets(page) ==1,
  108711. ogg_page_continued(page) !=0
  108712. If a page happens to be a single packet that was begun on a
  108713. previous page, and spans to the next page (in the case of a three or
  108714. more page packet), the return will be:
  108715. ogg_page_packets(page) ==0,
  108716. ogg_page_continued(page) !=0
  108717. */
  108718. int ogg_page_packets(ogg_page *og){
  108719. int i,n=og->header[26],count=0;
  108720. for(i=0;i<n;i++)
  108721. if(og->header[27+i]<255)count++;
  108722. return(count);
  108723. }
  108724. #if 0
  108725. /* helper to initialize lookup for direct-table CRC (illustrative; we
  108726. use the static init below) */
  108727. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  108728. int i;
  108729. unsigned long r;
  108730. r = index << 24;
  108731. for (i=0; i<8; i++)
  108732. if (r & 0x80000000UL)
  108733. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  108734. polynomial, although we use an
  108735. unreflected alg and an init/final
  108736. of 0, not 0xffffffff */
  108737. else
  108738. r<<=1;
  108739. return (r & 0xffffffffUL);
  108740. }
  108741. #endif
  108742. static const ogg_uint32_t crc_lookup[256]={
  108743. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  108744. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  108745. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  108746. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  108747. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  108748. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  108749. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  108750. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  108751. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  108752. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  108753. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  108754. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  108755. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  108756. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  108757. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  108758. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  108759. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  108760. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  108761. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  108762. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  108763. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  108764. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  108765. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  108766. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  108767. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  108768. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  108769. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  108770. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  108771. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  108772. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  108773. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  108774. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  108775. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  108776. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  108777. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  108778. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  108779. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  108780. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  108781. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  108782. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  108783. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  108784. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  108785. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  108786. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  108787. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  108788. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  108789. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  108790. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  108791. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  108792. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  108793. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  108794. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  108795. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  108796. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  108797. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  108798. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  108799. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  108800. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  108801. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  108802. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  108803. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  108804. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  108805. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  108806. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  108807. /* init the encode/decode logical stream state */
  108808. int ogg_stream_init(ogg_stream_state *os,int serialno){
  108809. if(os){
  108810. memset(os,0,sizeof(*os));
  108811. os->body_storage=16*1024;
  108812. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  108813. os->lacing_storage=1024;
  108814. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  108815. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  108816. os->serialno=serialno;
  108817. return(0);
  108818. }
  108819. return(-1);
  108820. }
  108821. /* _clear does not free os, only the non-flat storage within */
  108822. int ogg_stream_clear(ogg_stream_state *os){
  108823. if(os){
  108824. if(os->body_data)_ogg_free(os->body_data);
  108825. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  108826. if(os->granule_vals)_ogg_free(os->granule_vals);
  108827. memset(os,0,sizeof(*os));
  108828. }
  108829. return(0);
  108830. }
  108831. int ogg_stream_destroy(ogg_stream_state *os){
  108832. if(os){
  108833. ogg_stream_clear(os);
  108834. _ogg_free(os);
  108835. }
  108836. return(0);
  108837. }
  108838. /* Helpers for ogg_stream_encode; this keeps the structure and
  108839. what's happening fairly clear */
  108840. static void _os_body_expand(ogg_stream_state *os,int needed){
  108841. if(os->body_storage<=os->body_fill+needed){
  108842. os->body_storage+=(needed+1024);
  108843. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  108844. }
  108845. }
  108846. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  108847. if(os->lacing_storage<=os->lacing_fill+needed){
  108848. os->lacing_storage+=(needed+32);
  108849. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  108850. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  108851. }
  108852. }
  108853. /* checksum the page */
  108854. /* Direct table CRC; note that this will be faster in the future if we
  108855. perform the checksum silmultaneously with other copies */
  108856. void ogg_page_checksum_set(ogg_page *og){
  108857. if(og){
  108858. ogg_uint32_t crc_reg=0;
  108859. int i;
  108860. /* safety; needed for API behavior, but not framing code */
  108861. og->header[22]=0;
  108862. og->header[23]=0;
  108863. og->header[24]=0;
  108864. og->header[25]=0;
  108865. for(i=0;i<og->header_len;i++)
  108866. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  108867. for(i=0;i<og->body_len;i++)
  108868. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  108869. og->header[22]=(unsigned char)(crc_reg&0xff);
  108870. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  108871. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  108872. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  108873. }
  108874. }
  108875. /* submit data to the internal buffer of the framing engine */
  108876. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  108877. int lacing_vals=op->bytes/255+1,i;
  108878. if(os->body_returned){
  108879. /* advance packet data according to the body_returned pointer. We
  108880. had to keep it around to return a pointer into the buffer last
  108881. call */
  108882. os->body_fill-=os->body_returned;
  108883. if(os->body_fill)
  108884. memmove(os->body_data,os->body_data+os->body_returned,
  108885. os->body_fill);
  108886. os->body_returned=0;
  108887. }
  108888. /* make sure we have the buffer storage */
  108889. _os_body_expand(os,op->bytes);
  108890. _os_lacing_expand(os,lacing_vals);
  108891. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  108892. the liability of overly clean abstraction for the time being. It
  108893. will actually be fairly easy to eliminate the extra copy in the
  108894. future */
  108895. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  108896. os->body_fill+=op->bytes;
  108897. /* Store lacing vals for this packet */
  108898. for(i=0;i<lacing_vals-1;i++){
  108899. os->lacing_vals[os->lacing_fill+i]=255;
  108900. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  108901. }
  108902. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  108903. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  108904. /* flag the first segment as the beginning of the packet */
  108905. os->lacing_vals[os->lacing_fill]|= 0x100;
  108906. os->lacing_fill+=lacing_vals;
  108907. /* for the sake of completeness */
  108908. os->packetno++;
  108909. if(op->e_o_s)os->e_o_s=1;
  108910. return(0);
  108911. }
  108912. /* This will flush remaining packets into a page (returning nonzero),
  108913. even if there is not enough data to trigger a flush normally
  108914. (undersized page). If there are no packets or partial packets to
  108915. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  108916. try to flush a normal sized page like ogg_stream_pageout; a call to
  108917. ogg_stream_flush does not guarantee that all packets have flushed.
  108918. Only a return value of 0 from ogg_stream_flush indicates all packet
  108919. data is flushed into pages.
  108920. since ogg_stream_flush will flush the last page in a stream even if
  108921. it's undersized, you almost certainly want to use ogg_stream_pageout
  108922. (and *not* ogg_stream_flush) unless you specifically need to flush
  108923. an page regardless of size in the middle of a stream. */
  108924. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  108925. int i;
  108926. int vals=0;
  108927. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  108928. int bytes=0;
  108929. long acc=0;
  108930. ogg_int64_t granule_pos=-1;
  108931. if(maxvals==0)return(0);
  108932. /* construct a page */
  108933. /* decide how many segments to include */
  108934. /* If this is the initial header case, the first page must only include
  108935. the initial header packet */
  108936. if(os->b_o_s==0){ /* 'initial header page' case */
  108937. granule_pos=0;
  108938. for(vals=0;vals<maxvals;vals++){
  108939. if((os->lacing_vals[vals]&0x0ff)<255){
  108940. vals++;
  108941. break;
  108942. }
  108943. }
  108944. }else{
  108945. for(vals=0;vals<maxvals;vals++){
  108946. if(acc>4096)break;
  108947. acc+=os->lacing_vals[vals]&0x0ff;
  108948. if((os->lacing_vals[vals]&0xff)<255)
  108949. granule_pos=os->granule_vals[vals];
  108950. }
  108951. }
  108952. /* construct the header in temp storage */
  108953. memcpy(os->header,"OggS",4);
  108954. /* stream structure version */
  108955. os->header[4]=0x00;
  108956. /* continued packet flag? */
  108957. os->header[5]=0x00;
  108958. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  108959. /* first page flag? */
  108960. if(os->b_o_s==0)os->header[5]|=0x02;
  108961. /* last page flag? */
  108962. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  108963. os->b_o_s=1;
  108964. /* 64 bits of PCM position */
  108965. for(i=6;i<14;i++){
  108966. os->header[i]=(unsigned char)(granule_pos&0xff);
  108967. granule_pos>>=8;
  108968. }
  108969. /* 32 bits of stream serial number */
  108970. {
  108971. long serialno=os->serialno;
  108972. for(i=14;i<18;i++){
  108973. os->header[i]=(unsigned char)(serialno&0xff);
  108974. serialno>>=8;
  108975. }
  108976. }
  108977. /* 32 bits of page counter (we have both counter and page header
  108978. because this val can roll over) */
  108979. if(os->pageno==-1)os->pageno=0; /* because someone called
  108980. stream_reset; this would be a
  108981. strange thing to do in an
  108982. encode stream, but it has
  108983. plausible uses */
  108984. {
  108985. long pageno=os->pageno++;
  108986. for(i=18;i<22;i++){
  108987. os->header[i]=(unsigned char)(pageno&0xff);
  108988. pageno>>=8;
  108989. }
  108990. }
  108991. /* zero for computation; filled in later */
  108992. os->header[22]=0;
  108993. os->header[23]=0;
  108994. os->header[24]=0;
  108995. os->header[25]=0;
  108996. /* segment table */
  108997. os->header[26]=(unsigned char)(vals&0xff);
  108998. for(i=0;i<vals;i++)
  108999. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  109000. /* set pointers in the ogg_page struct */
  109001. og->header=os->header;
  109002. og->header_len=os->header_fill=vals+27;
  109003. og->body=os->body_data+os->body_returned;
  109004. og->body_len=bytes;
  109005. /* advance the lacing data and set the body_returned pointer */
  109006. os->lacing_fill-=vals;
  109007. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  109008. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  109009. os->body_returned+=bytes;
  109010. /* calculate the checksum */
  109011. ogg_page_checksum_set(og);
  109012. /* done */
  109013. return(1);
  109014. }
  109015. /* This constructs pages from buffered packet segments. The pointers
  109016. returned are to static buffers; do not free. The returned buffers are
  109017. good only until the next call (using the same ogg_stream_state) */
  109018. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  109019. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  109020. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  109021. os->lacing_fill>=255 || /* 'segment table full' case */
  109022. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  109023. return(ogg_stream_flush(os,og));
  109024. }
  109025. /* not enough data to construct a page and not end of stream */
  109026. return(0);
  109027. }
  109028. int ogg_stream_eos(ogg_stream_state *os){
  109029. return os->e_o_s;
  109030. }
  109031. /* DECODING PRIMITIVES: packet streaming layer **********************/
  109032. /* This has two layers to place more of the multi-serialno and paging
  109033. control in the application's hands. First, we expose a data buffer
  109034. using ogg_sync_buffer(). The app either copies into the
  109035. buffer, or passes it directly to read(), etc. We then call
  109036. ogg_sync_wrote() to tell how many bytes we just added.
  109037. Pages are returned (pointers into the buffer in ogg_sync_state)
  109038. by ogg_sync_pageout(). The page is then submitted to
  109039. ogg_stream_pagein() along with the appropriate
  109040. ogg_stream_state* (ie, matching serialno). We then get raw
  109041. packets out calling ogg_stream_packetout() with a
  109042. ogg_stream_state. */
  109043. /* initialize the struct to a known state */
  109044. int ogg_sync_init(ogg_sync_state *oy){
  109045. if(oy){
  109046. memset(oy,0,sizeof(*oy));
  109047. }
  109048. return(0);
  109049. }
  109050. /* clear non-flat storage within */
  109051. int ogg_sync_clear(ogg_sync_state *oy){
  109052. if(oy){
  109053. if(oy->data)_ogg_free(oy->data);
  109054. ogg_sync_init(oy);
  109055. }
  109056. return(0);
  109057. }
  109058. int ogg_sync_destroy(ogg_sync_state *oy){
  109059. if(oy){
  109060. ogg_sync_clear(oy);
  109061. _ogg_free(oy);
  109062. }
  109063. return(0);
  109064. }
  109065. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  109066. /* first, clear out any space that has been previously returned */
  109067. if(oy->returned){
  109068. oy->fill-=oy->returned;
  109069. if(oy->fill>0)
  109070. memmove(oy->data,oy->data+oy->returned,oy->fill);
  109071. oy->returned=0;
  109072. }
  109073. if(size>oy->storage-oy->fill){
  109074. /* We need to extend the internal buffer */
  109075. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  109076. if(oy->data)
  109077. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  109078. else
  109079. oy->data=(unsigned char*) _ogg_malloc(newsize);
  109080. oy->storage=newsize;
  109081. }
  109082. /* expose a segment at least as large as requested at the fill mark */
  109083. return((char *)oy->data+oy->fill);
  109084. }
  109085. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  109086. if(oy->fill+bytes>oy->storage)return(-1);
  109087. oy->fill+=bytes;
  109088. return(0);
  109089. }
  109090. /* sync the stream. This is meant to be useful for finding page
  109091. boundaries.
  109092. return values for this:
  109093. -n) skipped n bytes
  109094. 0) page not ready; more data (no bytes skipped)
  109095. n) page synced at current location; page length n bytes
  109096. */
  109097. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  109098. unsigned char *page=oy->data+oy->returned;
  109099. unsigned char *next;
  109100. long bytes=oy->fill-oy->returned;
  109101. if(oy->headerbytes==0){
  109102. int headerbytes,i;
  109103. if(bytes<27)return(0); /* not enough for a header */
  109104. /* verify capture pattern */
  109105. if(memcmp(page,"OggS",4))goto sync_fail;
  109106. headerbytes=page[26]+27;
  109107. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  109108. /* count up body length in the segment table */
  109109. for(i=0;i<page[26];i++)
  109110. oy->bodybytes+=page[27+i];
  109111. oy->headerbytes=headerbytes;
  109112. }
  109113. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  109114. /* The whole test page is buffered. Verify the checksum */
  109115. {
  109116. /* Grab the checksum bytes, set the header field to zero */
  109117. char chksum[4];
  109118. ogg_page log;
  109119. memcpy(chksum,page+22,4);
  109120. memset(page+22,0,4);
  109121. /* set up a temp page struct and recompute the checksum */
  109122. log.header=page;
  109123. log.header_len=oy->headerbytes;
  109124. log.body=page+oy->headerbytes;
  109125. log.body_len=oy->bodybytes;
  109126. ogg_page_checksum_set(&log);
  109127. /* Compare */
  109128. if(memcmp(chksum,page+22,4)){
  109129. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  109130. at all) */
  109131. /* replace the computed checksum with the one actually read in */
  109132. memcpy(page+22,chksum,4);
  109133. /* Bad checksum. Lose sync */
  109134. goto sync_fail;
  109135. }
  109136. }
  109137. /* yes, have a whole page all ready to go */
  109138. {
  109139. unsigned char *page=oy->data+oy->returned;
  109140. long bytes;
  109141. if(og){
  109142. og->header=page;
  109143. og->header_len=oy->headerbytes;
  109144. og->body=page+oy->headerbytes;
  109145. og->body_len=oy->bodybytes;
  109146. }
  109147. oy->unsynced=0;
  109148. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  109149. oy->headerbytes=0;
  109150. oy->bodybytes=0;
  109151. return(bytes);
  109152. }
  109153. sync_fail:
  109154. oy->headerbytes=0;
  109155. oy->bodybytes=0;
  109156. /* search for possible capture */
  109157. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  109158. if(!next)
  109159. next=oy->data+oy->fill;
  109160. oy->returned=next-oy->data;
  109161. return(-(next-page));
  109162. }
  109163. /* sync the stream and get a page. Keep trying until we find a page.
  109164. Supress 'sync errors' after reporting the first.
  109165. return values:
  109166. -1) recapture (hole in data)
  109167. 0) need more data
  109168. 1) page returned
  109169. Returns pointers into buffered data; invalidated by next call to
  109170. _stream, _clear, _init, or _buffer */
  109171. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  109172. /* all we need to do is verify a page at the head of the stream
  109173. buffer. If it doesn't verify, we look for the next potential
  109174. frame */
  109175. for(;;){
  109176. long ret=ogg_sync_pageseek(oy,og);
  109177. if(ret>0){
  109178. /* have a page */
  109179. return(1);
  109180. }
  109181. if(ret==0){
  109182. /* need more data */
  109183. return(0);
  109184. }
  109185. /* head did not start a synced page... skipped some bytes */
  109186. if(!oy->unsynced){
  109187. oy->unsynced=1;
  109188. return(-1);
  109189. }
  109190. /* loop. keep looking */
  109191. }
  109192. }
  109193. /* add the incoming page to the stream state; we decompose the page
  109194. into packet segments here as well. */
  109195. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  109196. unsigned char *header=og->header;
  109197. unsigned char *body=og->body;
  109198. long bodysize=og->body_len;
  109199. int segptr=0;
  109200. int version=ogg_page_version(og);
  109201. int continued=ogg_page_continued(og);
  109202. int bos=ogg_page_bos(og);
  109203. int eos=ogg_page_eos(og);
  109204. ogg_int64_t granulepos=ogg_page_granulepos(og);
  109205. int serialno=ogg_page_serialno(og);
  109206. long pageno=ogg_page_pageno(og);
  109207. int segments=header[26];
  109208. /* clean up 'returned data' */
  109209. {
  109210. long lr=os->lacing_returned;
  109211. long br=os->body_returned;
  109212. /* body data */
  109213. if(br){
  109214. os->body_fill-=br;
  109215. if(os->body_fill)
  109216. memmove(os->body_data,os->body_data+br,os->body_fill);
  109217. os->body_returned=0;
  109218. }
  109219. if(lr){
  109220. /* segment table */
  109221. if(os->lacing_fill-lr){
  109222. memmove(os->lacing_vals,os->lacing_vals+lr,
  109223. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  109224. memmove(os->granule_vals,os->granule_vals+lr,
  109225. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  109226. }
  109227. os->lacing_fill-=lr;
  109228. os->lacing_packet-=lr;
  109229. os->lacing_returned=0;
  109230. }
  109231. }
  109232. /* check the serial number */
  109233. if(serialno!=os->serialno)return(-1);
  109234. if(version>0)return(-1);
  109235. _os_lacing_expand(os,segments+1);
  109236. /* are we in sequence? */
  109237. if(pageno!=os->pageno){
  109238. int i;
  109239. /* unroll previous partial packet (if any) */
  109240. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  109241. os->body_fill-=os->lacing_vals[i]&0xff;
  109242. os->lacing_fill=os->lacing_packet;
  109243. /* make a note of dropped data in segment table */
  109244. if(os->pageno!=-1){
  109245. os->lacing_vals[os->lacing_fill++]=0x400;
  109246. os->lacing_packet++;
  109247. }
  109248. }
  109249. /* are we a 'continued packet' page? If so, we may need to skip
  109250. some segments */
  109251. if(continued){
  109252. if(os->lacing_fill<1 ||
  109253. os->lacing_vals[os->lacing_fill-1]==0x400){
  109254. bos=0;
  109255. for(;segptr<segments;segptr++){
  109256. int val=header[27+segptr];
  109257. body+=val;
  109258. bodysize-=val;
  109259. if(val<255){
  109260. segptr++;
  109261. break;
  109262. }
  109263. }
  109264. }
  109265. }
  109266. if(bodysize){
  109267. _os_body_expand(os,bodysize);
  109268. memcpy(os->body_data+os->body_fill,body,bodysize);
  109269. os->body_fill+=bodysize;
  109270. }
  109271. {
  109272. int saved=-1;
  109273. while(segptr<segments){
  109274. int val=header[27+segptr];
  109275. os->lacing_vals[os->lacing_fill]=val;
  109276. os->granule_vals[os->lacing_fill]=-1;
  109277. if(bos){
  109278. os->lacing_vals[os->lacing_fill]|=0x100;
  109279. bos=0;
  109280. }
  109281. if(val<255)saved=os->lacing_fill;
  109282. os->lacing_fill++;
  109283. segptr++;
  109284. if(val<255)os->lacing_packet=os->lacing_fill;
  109285. }
  109286. /* set the granulepos on the last granuleval of the last full packet */
  109287. if(saved!=-1){
  109288. os->granule_vals[saved]=granulepos;
  109289. }
  109290. }
  109291. if(eos){
  109292. os->e_o_s=1;
  109293. if(os->lacing_fill>0)
  109294. os->lacing_vals[os->lacing_fill-1]|=0x200;
  109295. }
  109296. os->pageno=pageno+1;
  109297. return(0);
  109298. }
  109299. /* clear things to an initial state. Good to call, eg, before seeking */
  109300. int ogg_sync_reset(ogg_sync_state *oy){
  109301. oy->fill=0;
  109302. oy->returned=0;
  109303. oy->unsynced=0;
  109304. oy->headerbytes=0;
  109305. oy->bodybytes=0;
  109306. return(0);
  109307. }
  109308. int ogg_stream_reset(ogg_stream_state *os){
  109309. os->body_fill=0;
  109310. os->body_returned=0;
  109311. os->lacing_fill=0;
  109312. os->lacing_packet=0;
  109313. os->lacing_returned=0;
  109314. os->header_fill=0;
  109315. os->e_o_s=0;
  109316. os->b_o_s=0;
  109317. os->pageno=-1;
  109318. os->packetno=0;
  109319. os->granulepos=0;
  109320. return(0);
  109321. }
  109322. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  109323. ogg_stream_reset(os);
  109324. os->serialno=serialno;
  109325. return(0);
  109326. }
  109327. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  109328. /* The last part of decode. We have the stream broken into packet
  109329. segments. Now we need to group them into packets (or return the
  109330. out of sync markers) */
  109331. int ptr=os->lacing_returned;
  109332. if(os->lacing_packet<=ptr)return(0);
  109333. if(os->lacing_vals[ptr]&0x400){
  109334. /* we need to tell the codec there's a gap; it might need to
  109335. handle previous packet dependencies. */
  109336. os->lacing_returned++;
  109337. os->packetno++;
  109338. return(-1);
  109339. }
  109340. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  109341. to ask if there's a whole packet
  109342. waiting */
  109343. /* Gather the whole packet. We'll have no holes or a partial packet */
  109344. {
  109345. int size=os->lacing_vals[ptr]&0xff;
  109346. int bytes=size;
  109347. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  109348. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  109349. while(size==255){
  109350. int val=os->lacing_vals[++ptr];
  109351. size=val&0xff;
  109352. if(val&0x200)eos=0x200;
  109353. bytes+=size;
  109354. }
  109355. if(op){
  109356. op->e_o_s=eos;
  109357. op->b_o_s=bos;
  109358. op->packet=os->body_data+os->body_returned;
  109359. op->packetno=os->packetno;
  109360. op->granulepos=os->granule_vals[ptr];
  109361. op->bytes=bytes;
  109362. }
  109363. if(adv){
  109364. os->body_returned+=bytes;
  109365. os->lacing_returned=ptr+1;
  109366. os->packetno++;
  109367. }
  109368. }
  109369. return(1);
  109370. }
  109371. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  109372. return _packetout(os,op,1);
  109373. }
  109374. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  109375. return _packetout(os,op,0);
  109376. }
  109377. void ogg_packet_clear(ogg_packet *op) {
  109378. _ogg_free(op->packet);
  109379. memset(op, 0, sizeof(*op));
  109380. }
  109381. #ifdef _V_SELFTEST
  109382. #include <stdio.h>
  109383. ogg_stream_state os_en, os_de;
  109384. ogg_sync_state oy;
  109385. void checkpacket(ogg_packet *op,int len, int no, int pos){
  109386. long j;
  109387. static int sequence=0;
  109388. static int lastno=0;
  109389. if(op->bytes!=len){
  109390. fprintf(stderr,"incorrect packet length!\n");
  109391. exit(1);
  109392. }
  109393. if(op->granulepos!=pos){
  109394. fprintf(stderr,"incorrect packet position!\n");
  109395. exit(1);
  109396. }
  109397. /* packet number just follows sequence/gap; adjust the input number
  109398. for that */
  109399. if(no==0){
  109400. sequence=0;
  109401. }else{
  109402. sequence++;
  109403. if(no>lastno+1)
  109404. sequence++;
  109405. }
  109406. lastno=no;
  109407. if(op->packetno!=sequence){
  109408. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  109409. (long)(op->packetno),sequence);
  109410. exit(1);
  109411. }
  109412. /* Test data */
  109413. for(j=0;j<op->bytes;j++)
  109414. if(op->packet[j]!=((j+no)&0xff)){
  109415. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  109416. j,op->packet[j],(j+no)&0xff);
  109417. exit(1);
  109418. }
  109419. }
  109420. void check_page(unsigned char *data,const int *header,ogg_page *og){
  109421. long j;
  109422. /* Test data */
  109423. for(j=0;j<og->body_len;j++)
  109424. if(og->body[j]!=data[j]){
  109425. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  109426. j,data[j],og->body[j]);
  109427. exit(1);
  109428. }
  109429. /* Test header */
  109430. for(j=0;j<og->header_len;j++){
  109431. if(og->header[j]!=header[j]){
  109432. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  109433. for(j=0;j<header[26]+27;j++)
  109434. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  109435. fprintf(stderr,"\n");
  109436. exit(1);
  109437. }
  109438. }
  109439. if(og->header_len!=header[26]+27){
  109440. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  109441. og->header_len,header[26]+27);
  109442. exit(1);
  109443. }
  109444. }
  109445. void print_header(ogg_page *og){
  109446. int j;
  109447. fprintf(stderr,"\nHEADER:\n");
  109448. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  109449. og->header[0],og->header[1],og->header[2],og->header[3],
  109450. (int)og->header[4],(int)og->header[5]);
  109451. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  109452. (og->header[9]<<24)|(og->header[8]<<16)|
  109453. (og->header[7]<<8)|og->header[6],
  109454. (og->header[17]<<24)|(og->header[16]<<16)|
  109455. (og->header[15]<<8)|og->header[14],
  109456. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  109457. (og->header[19]<<8)|og->header[18]);
  109458. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  109459. (int)og->header[22],(int)og->header[23],
  109460. (int)og->header[24],(int)og->header[25],
  109461. (int)og->header[26]);
  109462. for(j=27;j<og->header_len;j++)
  109463. fprintf(stderr,"%d ",(int)og->header[j]);
  109464. fprintf(stderr,")\n\n");
  109465. }
  109466. void copy_page(ogg_page *og){
  109467. unsigned char *temp=_ogg_malloc(og->header_len);
  109468. memcpy(temp,og->header,og->header_len);
  109469. og->header=temp;
  109470. temp=_ogg_malloc(og->body_len);
  109471. memcpy(temp,og->body,og->body_len);
  109472. og->body=temp;
  109473. }
  109474. void free_page(ogg_page *og){
  109475. _ogg_free (og->header);
  109476. _ogg_free (og->body);
  109477. }
  109478. void error(void){
  109479. fprintf(stderr,"error!\n");
  109480. exit(1);
  109481. }
  109482. /* 17 only */
  109483. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  109484. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109485. 0x01,0x02,0x03,0x04,0,0,0,0,
  109486. 0x15,0xed,0xec,0x91,
  109487. 1,
  109488. 17};
  109489. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109490. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109491. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109492. 0x01,0x02,0x03,0x04,0,0,0,0,
  109493. 0x59,0x10,0x6c,0x2c,
  109494. 1,
  109495. 17};
  109496. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109497. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  109498. 0x01,0x02,0x03,0x04,1,0,0,0,
  109499. 0x89,0x33,0x85,0xce,
  109500. 13,
  109501. 254,255,0,255,1,255,245,255,255,0,
  109502. 255,255,90};
  109503. /* nil packets; beginning,middle,end */
  109504. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109505. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109506. 0x01,0x02,0x03,0x04,0,0,0,0,
  109507. 0xff,0x7b,0x23,0x17,
  109508. 1,
  109509. 0};
  109510. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109511. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  109512. 0x01,0x02,0x03,0x04,1,0,0,0,
  109513. 0x5c,0x3f,0x66,0xcb,
  109514. 17,
  109515. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  109516. 255,255,90,0};
  109517. /* large initial packet */
  109518. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109519. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109520. 0x01,0x02,0x03,0x04,0,0,0,0,
  109521. 0x01,0x27,0x31,0xaa,
  109522. 18,
  109523. 255,255,255,255,255,255,255,255,
  109524. 255,255,255,255,255,255,255,255,255,10};
  109525. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109526. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109527. 0x01,0x02,0x03,0x04,1,0,0,0,
  109528. 0x7f,0x4e,0x8a,0xd2,
  109529. 4,
  109530. 255,4,255,0};
  109531. /* continuing packet test */
  109532. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109533. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109534. 0x01,0x02,0x03,0x04,0,0,0,0,
  109535. 0xff,0x7b,0x23,0x17,
  109536. 1,
  109537. 0};
  109538. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109539. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109540. 0x01,0x02,0x03,0x04,1,0,0,0,
  109541. 0x54,0x05,0x51,0xc8,
  109542. 17,
  109543. 255,255,255,255,255,255,255,255,
  109544. 255,255,255,255,255,255,255,255,255};
  109545. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109546. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  109547. 0x01,0x02,0x03,0x04,2,0,0,0,
  109548. 0xc8,0xc3,0xcb,0xed,
  109549. 5,
  109550. 10,255,4,255,0};
  109551. /* page with the 255 segment limit */
  109552. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109553. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109554. 0x01,0x02,0x03,0x04,0,0,0,0,
  109555. 0xff,0x7b,0x23,0x17,
  109556. 1,
  109557. 0};
  109558. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109559. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  109560. 0x01,0x02,0x03,0x04,1,0,0,0,
  109561. 0xed,0x2a,0x2e,0xa7,
  109562. 255,
  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,10,
  109580. 10,10,10,10,10,10,10,10,
  109581. 10,10,10,10,10,10,10,10,
  109582. 10,10,10,10,10,10,10,10,
  109583. 10,10,10,10,10,10,10,10,
  109584. 10,10,10,10,10,10,10,10,
  109585. 10,10,10,10,10,10,10,10,
  109586. 10,10,10,10,10,10,10,10,
  109587. 10,10,10,10,10,10,10,10,
  109588. 10,10,10,10,10,10,10,10,
  109589. 10,10,10,10,10,10,10,10,
  109590. 10,10,10,10,10,10,10,10,
  109591. 10,10,10,10,10,10,10,10,
  109592. 10,10,10,10,10,10,10,10,
  109593. 10,10,10,10,10,10,10,10,
  109594. 10,10,10,10,10,10,10};
  109595. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  109596. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  109597. 0x01,0x02,0x03,0x04,2,0,0,0,
  109598. 0x6c,0x3b,0x82,0x3d,
  109599. 1,
  109600. 50};
  109601. /* packet that overspans over an entire page */
  109602. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109603. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109604. 0x01,0x02,0x03,0x04,0,0,0,0,
  109605. 0xff,0x7b,0x23,0x17,
  109606. 1,
  109607. 0};
  109608. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109609. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109610. 0x01,0x02,0x03,0x04,1,0,0,0,
  109611. 0x3c,0xd9,0x4d,0x3f,
  109612. 17,
  109613. 100,255,255,255,255,255,255,255,255,
  109614. 255,255,255,255,255,255,255,255};
  109615. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  109616. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  109617. 0x01,0x02,0x03,0x04,2,0,0,0,
  109618. 0x01,0xd2,0xe5,0xe5,
  109619. 17,
  109620. 255,255,255,255,255,255,255,255,
  109621. 255,255,255,255,255,255,255,255,255};
  109622. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109623. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  109624. 0x01,0x02,0x03,0x04,3,0,0,0,
  109625. 0xef,0xdd,0x88,0xde,
  109626. 7,
  109627. 255,255,75,255,4,255,0};
  109628. /* packet that overspans over an entire page */
  109629. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  109630. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  109631. 0x01,0x02,0x03,0x04,0,0,0,0,
  109632. 0xff,0x7b,0x23,0x17,
  109633. 1,
  109634. 0};
  109635. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  109636. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  109637. 0x01,0x02,0x03,0x04,1,0,0,0,
  109638. 0x3c,0xd9,0x4d,0x3f,
  109639. 17,
  109640. 100,255,255,255,255,255,255,255,255,
  109641. 255,255,255,255,255,255,255,255};
  109642. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  109643. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  109644. 0x01,0x02,0x03,0x04,2,0,0,0,
  109645. 0xd4,0xe0,0x60,0xe5,
  109646. 1,0};
  109647. void test_pack(const int *pl, const int **headers, int byteskip,
  109648. int pageskip, int packetskip){
  109649. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  109650. long inptr=0;
  109651. long outptr=0;
  109652. long deptr=0;
  109653. long depacket=0;
  109654. long granule_pos=7,pageno=0;
  109655. int i,j,packets,pageout=pageskip;
  109656. int eosflag=0;
  109657. int bosflag=0;
  109658. int byteskipcount=0;
  109659. ogg_stream_reset(&os_en);
  109660. ogg_stream_reset(&os_de);
  109661. ogg_sync_reset(&oy);
  109662. for(packets=0;packets<packetskip;packets++)
  109663. depacket+=pl[packets];
  109664. for(packets=0;;packets++)if(pl[packets]==-1)break;
  109665. for(i=0;i<packets;i++){
  109666. /* construct a test packet */
  109667. ogg_packet op;
  109668. int len=pl[i];
  109669. op.packet=data+inptr;
  109670. op.bytes=len;
  109671. op.e_o_s=(pl[i+1]<0?1:0);
  109672. op.granulepos=granule_pos;
  109673. granule_pos+=1024;
  109674. for(j=0;j<len;j++)data[inptr++]=i+j;
  109675. /* submit the test packet */
  109676. ogg_stream_packetin(&os_en,&op);
  109677. /* retrieve any finished pages */
  109678. {
  109679. ogg_page og;
  109680. while(ogg_stream_pageout(&os_en,&og)){
  109681. /* We have a page. Check it carefully */
  109682. fprintf(stderr,"%ld, ",pageno);
  109683. if(headers[pageno]==NULL){
  109684. fprintf(stderr,"coded too many pages!\n");
  109685. exit(1);
  109686. }
  109687. check_page(data+outptr,headers[pageno],&og);
  109688. outptr+=og.body_len;
  109689. pageno++;
  109690. if(pageskip){
  109691. bosflag=1;
  109692. pageskip--;
  109693. deptr+=og.body_len;
  109694. }
  109695. /* have a complete page; submit it to sync/decode */
  109696. {
  109697. ogg_page og_de;
  109698. ogg_packet op_de,op_de2;
  109699. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  109700. char *next=buf;
  109701. byteskipcount+=og.header_len;
  109702. if(byteskipcount>byteskip){
  109703. memcpy(next,og.header,byteskipcount-byteskip);
  109704. next+=byteskipcount-byteskip;
  109705. byteskipcount=byteskip;
  109706. }
  109707. byteskipcount+=og.body_len;
  109708. if(byteskipcount>byteskip){
  109709. memcpy(next,og.body,byteskipcount-byteskip);
  109710. next+=byteskipcount-byteskip;
  109711. byteskipcount=byteskip;
  109712. }
  109713. ogg_sync_wrote(&oy,next-buf);
  109714. while(1){
  109715. int ret=ogg_sync_pageout(&oy,&og_de);
  109716. if(ret==0)break;
  109717. if(ret<0)continue;
  109718. /* got a page. Happy happy. Verify that it's good. */
  109719. fprintf(stderr,"(%ld), ",pageout);
  109720. check_page(data+deptr,headers[pageout],&og_de);
  109721. deptr+=og_de.body_len;
  109722. pageout++;
  109723. /* submit it to deconstitution */
  109724. ogg_stream_pagein(&os_de,&og_de);
  109725. /* packets out? */
  109726. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  109727. ogg_stream_packetpeek(&os_de,NULL);
  109728. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  109729. /* verify peek and out match */
  109730. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  109731. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  109732. depacket);
  109733. exit(1);
  109734. }
  109735. /* verify the packet! */
  109736. /* check data */
  109737. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  109738. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  109739. depacket);
  109740. exit(1);
  109741. }
  109742. /* check bos flag */
  109743. if(bosflag==0 && op_de.b_o_s==0){
  109744. fprintf(stderr,"b_o_s flag not set on packet!\n");
  109745. exit(1);
  109746. }
  109747. if(bosflag && op_de.b_o_s){
  109748. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  109749. exit(1);
  109750. }
  109751. bosflag=1;
  109752. depacket+=op_de.bytes;
  109753. /* check eos flag */
  109754. if(eosflag){
  109755. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  109756. exit(1);
  109757. }
  109758. if(op_de.e_o_s)eosflag=1;
  109759. /* check granulepos flag */
  109760. if(op_de.granulepos!=-1){
  109761. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  109762. }
  109763. }
  109764. }
  109765. }
  109766. }
  109767. }
  109768. }
  109769. _ogg_free(data);
  109770. if(headers[pageno]!=NULL){
  109771. fprintf(stderr,"did not write last page!\n");
  109772. exit(1);
  109773. }
  109774. if(headers[pageout]!=NULL){
  109775. fprintf(stderr,"did not decode last page!\n");
  109776. exit(1);
  109777. }
  109778. if(inptr!=outptr){
  109779. fprintf(stderr,"encoded page data incomplete!\n");
  109780. exit(1);
  109781. }
  109782. if(inptr!=deptr){
  109783. fprintf(stderr,"decoded page data incomplete!\n");
  109784. exit(1);
  109785. }
  109786. if(inptr!=depacket){
  109787. fprintf(stderr,"decoded packet data incomplete!\n");
  109788. exit(1);
  109789. }
  109790. if(!eosflag){
  109791. fprintf(stderr,"Never got a packet with EOS set!\n");
  109792. exit(1);
  109793. }
  109794. fprintf(stderr,"ok.\n");
  109795. }
  109796. int main(void){
  109797. ogg_stream_init(&os_en,0x04030201);
  109798. ogg_stream_init(&os_de,0x04030201);
  109799. ogg_sync_init(&oy);
  109800. /* Exercise each code path in the framing code. Also verify that
  109801. the checksums are working. */
  109802. {
  109803. /* 17 only */
  109804. const int packets[]={17, -1};
  109805. const int *headret[]={head1_0,NULL};
  109806. fprintf(stderr,"testing single page encoding... ");
  109807. test_pack(packets,headret,0,0,0);
  109808. }
  109809. {
  109810. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  109811. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  109812. const int *headret[]={head1_1,head2_1,NULL};
  109813. fprintf(stderr,"testing basic page encoding... ");
  109814. test_pack(packets,headret,0,0,0);
  109815. }
  109816. {
  109817. /* nil packets; beginning,middle,end */
  109818. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  109819. const int *headret[]={head1_2,head2_2,NULL};
  109820. fprintf(stderr,"testing basic nil packets... ");
  109821. test_pack(packets,headret,0,0,0);
  109822. }
  109823. {
  109824. /* large initial packet */
  109825. const int packets[]={4345,259,255,-1};
  109826. const int *headret[]={head1_3,head2_3,NULL};
  109827. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  109828. test_pack(packets,headret,0,0,0);
  109829. }
  109830. {
  109831. /* continuing packet test */
  109832. const int packets[]={0,4345,259,255,-1};
  109833. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  109834. fprintf(stderr,"testing single packet page span... ");
  109835. test_pack(packets,headret,0,0,0);
  109836. }
  109837. /* page with the 255 segment limit */
  109838. {
  109839. const int packets[]={0,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,10,
  109856. 10,10,10,10,10,10,10,10,
  109857. 10,10,10,10,10,10,10,10,
  109858. 10,10,10,10,10,10,10,10,
  109859. 10,10,10,10,10,10,10,10,
  109860. 10,10,10,10,10,10,10,10,
  109861. 10,10,10,10,10,10,10,10,
  109862. 10,10,10,10,10,10,10,10,
  109863. 10,10,10,10,10,10,10,10,
  109864. 10,10,10,10,10,10,10,10,
  109865. 10,10,10,10,10,10,10,10,
  109866. 10,10,10,10,10,10,10,10,
  109867. 10,10,10,10,10,10,10,10,
  109868. 10,10,10,10,10,10,10,10,
  109869. 10,10,10,10,10,10,10,10,
  109870. 10,10,10,10,10,10,10,50,-1};
  109871. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  109872. fprintf(stderr,"testing max packet segments... ");
  109873. test_pack(packets,headret,0,0,0);
  109874. }
  109875. {
  109876. /* packet that overspans over an entire page */
  109877. const int packets[]={0,100,9000,259,255,-1};
  109878. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109879. fprintf(stderr,"testing very large packets... ");
  109880. test_pack(packets,headret,0,0,0);
  109881. }
  109882. {
  109883. /* test for the libogg 1.1.1 resync in large continuation bug
  109884. found by Josh Coalson) */
  109885. const int packets[]={0,100,9000,259,255,-1};
  109886. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  109887. fprintf(stderr,"testing continuation resync in very large packets... ");
  109888. test_pack(packets,headret,100,2,3);
  109889. }
  109890. {
  109891. /* term only page. why not? */
  109892. const int packets[]={0,100,4080,-1};
  109893. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  109894. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  109895. test_pack(packets,headret,0,0,0);
  109896. }
  109897. {
  109898. /* build a bunch of pages for testing */
  109899. unsigned char *data=_ogg_malloc(1024*1024);
  109900. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  109901. int inptr=0,i,j;
  109902. ogg_page og[5];
  109903. ogg_stream_reset(&os_en);
  109904. for(i=0;pl[i]!=-1;i++){
  109905. ogg_packet op;
  109906. int len=pl[i];
  109907. op.packet=data+inptr;
  109908. op.bytes=len;
  109909. op.e_o_s=(pl[i+1]<0?1:0);
  109910. op.granulepos=(i+1)*1000;
  109911. for(j=0;j<len;j++)data[inptr++]=i+j;
  109912. ogg_stream_packetin(&os_en,&op);
  109913. }
  109914. _ogg_free(data);
  109915. /* retrieve finished pages */
  109916. for(i=0;i<5;i++){
  109917. if(ogg_stream_pageout(&os_en,&og[i])==0){
  109918. fprintf(stderr,"Too few pages output building sync tests!\n");
  109919. exit(1);
  109920. }
  109921. copy_page(&og[i]);
  109922. }
  109923. /* Test lost pages on pagein/packetout: no rollback */
  109924. {
  109925. ogg_page temp;
  109926. ogg_packet test;
  109927. fprintf(stderr,"Testing loss of pages... ");
  109928. ogg_sync_reset(&oy);
  109929. ogg_stream_reset(&os_de);
  109930. for(i=0;i<5;i++){
  109931. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109932. og[i].header_len);
  109933. ogg_sync_wrote(&oy,og[i].header_len);
  109934. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109935. ogg_sync_wrote(&oy,og[i].body_len);
  109936. }
  109937. ogg_sync_pageout(&oy,&temp);
  109938. ogg_stream_pagein(&os_de,&temp);
  109939. ogg_sync_pageout(&oy,&temp);
  109940. ogg_stream_pagein(&os_de,&temp);
  109941. ogg_sync_pageout(&oy,&temp);
  109942. /* skip */
  109943. ogg_sync_pageout(&oy,&temp);
  109944. ogg_stream_pagein(&os_de,&temp);
  109945. /* do we get the expected results/packets? */
  109946. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109947. checkpacket(&test,0,0,0);
  109948. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109949. checkpacket(&test,100,1,-1);
  109950. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109951. checkpacket(&test,4079,2,3000);
  109952. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109953. fprintf(stderr,"Error: loss of page did not return error\n");
  109954. exit(1);
  109955. }
  109956. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109957. checkpacket(&test,76,5,-1);
  109958. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109959. checkpacket(&test,34,6,-1);
  109960. fprintf(stderr,"ok.\n");
  109961. }
  109962. /* Test lost pages on pagein/packetout: rollback with continuation */
  109963. {
  109964. ogg_page temp;
  109965. ogg_packet test;
  109966. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  109967. ogg_sync_reset(&oy);
  109968. ogg_stream_reset(&os_de);
  109969. for(i=0;i<5;i++){
  109970. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  109971. og[i].header_len);
  109972. ogg_sync_wrote(&oy,og[i].header_len);
  109973. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  109974. ogg_sync_wrote(&oy,og[i].body_len);
  109975. }
  109976. ogg_sync_pageout(&oy,&temp);
  109977. ogg_stream_pagein(&os_de,&temp);
  109978. ogg_sync_pageout(&oy,&temp);
  109979. ogg_stream_pagein(&os_de,&temp);
  109980. ogg_sync_pageout(&oy,&temp);
  109981. ogg_stream_pagein(&os_de,&temp);
  109982. ogg_sync_pageout(&oy,&temp);
  109983. /* skip */
  109984. ogg_sync_pageout(&oy,&temp);
  109985. ogg_stream_pagein(&os_de,&temp);
  109986. /* do we get the expected results/packets? */
  109987. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109988. checkpacket(&test,0,0,0);
  109989. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109990. checkpacket(&test,100,1,-1);
  109991. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109992. checkpacket(&test,4079,2,3000);
  109993. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  109994. checkpacket(&test,2956,3,4000);
  109995. if(ogg_stream_packetout(&os_de,&test)!=-1){
  109996. fprintf(stderr,"Error: loss of page did not return error\n");
  109997. exit(1);
  109998. }
  109999. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  110000. checkpacket(&test,300,13,14000);
  110001. fprintf(stderr,"ok.\n");
  110002. }
  110003. /* the rest only test sync */
  110004. {
  110005. ogg_page og_de;
  110006. /* Test fractional page inputs: incomplete capture */
  110007. fprintf(stderr,"Testing sync on partial inputs... ");
  110008. ogg_sync_reset(&oy);
  110009. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110010. 3);
  110011. ogg_sync_wrote(&oy,3);
  110012. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110013. /* Test fractional page inputs: incomplete fixed header */
  110014. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  110015. 20);
  110016. ogg_sync_wrote(&oy,20);
  110017. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110018. /* Test fractional page inputs: incomplete header */
  110019. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  110020. 5);
  110021. ogg_sync_wrote(&oy,5);
  110022. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110023. /* Test fractional page inputs: incomplete body */
  110024. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  110025. og[1].header_len-28);
  110026. ogg_sync_wrote(&oy,og[1].header_len-28);
  110027. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110028. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  110029. ogg_sync_wrote(&oy,1000);
  110030. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110031. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  110032. og[1].body_len-1000);
  110033. ogg_sync_wrote(&oy,og[1].body_len-1000);
  110034. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110035. fprintf(stderr,"ok.\n");
  110036. }
  110037. /* Test fractional page inputs: page + incomplete capture */
  110038. {
  110039. ogg_page og_de;
  110040. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  110041. ogg_sync_reset(&oy);
  110042. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110043. og[1].header_len);
  110044. ogg_sync_wrote(&oy,og[1].header_len);
  110045. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110046. og[1].body_len);
  110047. ogg_sync_wrote(&oy,og[1].body_len);
  110048. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110049. 20);
  110050. ogg_sync_wrote(&oy,20);
  110051. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110052. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110053. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  110054. og[1].header_len-20);
  110055. ogg_sync_wrote(&oy,og[1].header_len-20);
  110056. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110057. og[1].body_len);
  110058. ogg_sync_wrote(&oy,og[1].body_len);
  110059. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110060. fprintf(stderr,"ok.\n");
  110061. }
  110062. /* Test recapture: garbage + page */
  110063. {
  110064. ogg_page og_de;
  110065. fprintf(stderr,"Testing search for capture... ");
  110066. ogg_sync_reset(&oy);
  110067. /* 'garbage' */
  110068. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110069. og[1].body_len);
  110070. ogg_sync_wrote(&oy,og[1].body_len);
  110071. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110072. og[1].header_len);
  110073. ogg_sync_wrote(&oy,og[1].header_len);
  110074. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110075. og[1].body_len);
  110076. ogg_sync_wrote(&oy,og[1].body_len);
  110077. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110078. 20);
  110079. ogg_sync_wrote(&oy,20);
  110080. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110081. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110082. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110083. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  110084. og[2].header_len-20);
  110085. ogg_sync_wrote(&oy,og[2].header_len-20);
  110086. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110087. og[2].body_len);
  110088. ogg_sync_wrote(&oy,og[2].body_len);
  110089. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110090. fprintf(stderr,"ok.\n");
  110091. }
  110092. /* Test recapture: page + garbage + page */
  110093. {
  110094. ogg_page og_de;
  110095. fprintf(stderr,"Testing recapture... ");
  110096. ogg_sync_reset(&oy);
  110097. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  110098. og[1].header_len);
  110099. ogg_sync_wrote(&oy,og[1].header_len);
  110100. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  110101. og[1].body_len);
  110102. ogg_sync_wrote(&oy,og[1].body_len);
  110103. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110104. og[2].header_len);
  110105. ogg_sync_wrote(&oy,og[2].header_len);
  110106. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  110107. og[2].header_len);
  110108. ogg_sync_wrote(&oy,og[2].header_len);
  110109. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110110. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  110111. og[2].body_len-5);
  110112. ogg_sync_wrote(&oy,og[2].body_len-5);
  110113. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  110114. og[3].header_len);
  110115. ogg_sync_wrote(&oy,og[3].header_len);
  110116. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  110117. og[3].body_len);
  110118. ogg_sync_wrote(&oy,og[3].body_len);
  110119. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  110120. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  110121. fprintf(stderr,"ok.\n");
  110122. }
  110123. /* Free page data that was previously copied */
  110124. {
  110125. for(i=0;i<5;i++){
  110126. free_page(&og[i]);
  110127. }
  110128. }
  110129. }
  110130. return(0);
  110131. }
  110132. #endif
  110133. #endif
  110134. /*** End of inlined file: framing.c ***/
  110135. /*** Start of inlined file: analysis.c ***/
  110136. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  110137. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110138. // tasks..
  110139. #if JUCE_MSVC
  110140. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110141. #endif
  110142. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  110143. #if JUCE_USE_OGGVORBIS
  110144. #include <stdio.h>
  110145. #include <string.h>
  110146. #include <math.h>
  110147. /*** Start of inlined file: codec_internal.h ***/
  110148. #ifndef _V_CODECI_H_
  110149. #define _V_CODECI_H_
  110150. /*** Start of inlined file: envelope.h ***/
  110151. #ifndef _V_ENVELOPE_
  110152. #define _V_ENVELOPE_
  110153. /*** Start of inlined file: mdct.h ***/
  110154. #ifndef _OGG_mdct_H_
  110155. #define _OGG_mdct_H_
  110156. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  110157. #ifdef MDCT_INTEGERIZED
  110158. #define DATA_TYPE int
  110159. #define REG_TYPE register int
  110160. #define TRIGBITS 14
  110161. #define cPI3_8 6270
  110162. #define cPI2_8 11585
  110163. #define cPI1_8 15137
  110164. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  110165. #define MULT_NORM(x) ((x)>>TRIGBITS)
  110166. #define HALVE(x) ((x)>>1)
  110167. #else
  110168. #define DATA_TYPE float
  110169. #define REG_TYPE float
  110170. #define cPI3_8 .38268343236508977175F
  110171. #define cPI2_8 .70710678118654752441F
  110172. #define cPI1_8 .92387953251128675613F
  110173. #define FLOAT_CONV(x) (x)
  110174. #define MULT_NORM(x) (x)
  110175. #define HALVE(x) ((x)*.5f)
  110176. #endif
  110177. typedef struct {
  110178. int n;
  110179. int log2n;
  110180. DATA_TYPE *trig;
  110181. int *bitrev;
  110182. DATA_TYPE scale;
  110183. } mdct_lookup;
  110184. extern void mdct_init(mdct_lookup *lookup,int n);
  110185. extern void mdct_clear(mdct_lookup *l);
  110186. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110187. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  110188. #endif
  110189. /*** End of inlined file: mdct.h ***/
  110190. #define VE_PRE 16
  110191. #define VE_WIN 4
  110192. #define VE_POST 2
  110193. #define VE_AMP (VE_PRE+VE_POST-1)
  110194. #define VE_BANDS 7
  110195. #define VE_NEARDC 15
  110196. #define VE_MINSTRETCH 2 /* a bit less than short block */
  110197. #define VE_MAXSTRETCH 12 /* one-third full block */
  110198. typedef struct {
  110199. float ampbuf[VE_AMP];
  110200. int ampptr;
  110201. float nearDC[VE_NEARDC];
  110202. float nearDC_acc;
  110203. float nearDC_partialacc;
  110204. int nearptr;
  110205. } envelope_filter_state;
  110206. typedef struct {
  110207. int begin;
  110208. int end;
  110209. float *window;
  110210. float total;
  110211. } envelope_band;
  110212. typedef struct {
  110213. int ch;
  110214. int winlength;
  110215. int searchstep;
  110216. float minenergy;
  110217. mdct_lookup mdct;
  110218. float *mdct_win;
  110219. envelope_band band[VE_BANDS];
  110220. envelope_filter_state *filter;
  110221. int stretch;
  110222. int *mark;
  110223. long storage;
  110224. long current;
  110225. long curmark;
  110226. long cursor;
  110227. } envelope_lookup;
  110228. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  110229. extern void _ve_envelope_clear(envelope_lookup *e);
  110230. extern long _ve_envelope_search(vorbis_dsp_state *v);
  110231. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  110232. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  110233. #endif
  110234. /*** End of inlined file: envelope.h ***/
  110235. /*** Start of inlined file: codebook.h ***/
  110236. #ifndef _V_CODEBOOK_H_
  110237. #define _V_CODEBOOK_H_
  110238. /* This structure encapsulates huffman and VQ style encoding books; it
  110239. doesn't do anything specific to either.
  110240. valuelist/quantlist are nonNULL (and q_* significant) only if
  110241. there's entry->value mapping to be done.
  110242. If encode-side mapping must be done (and thus the entry needs to be
  110243. hunted), the auxiliary encode pointer will point to a decision
  110244. tree. This is true of both VQ and huffman, but is mostly useful
  110245. with VQ.
  110246. */
  110247. typedef struct static_codebook{
  110248. long dim; /* codebook dimensions (elements per vector) */
  110249. long entries; /* codebook entries */
  110250. long *lengthlist; /* codeword lengths in bits */
  110251. /* mapping ***************************************************************/
  110252. int maptype; /* 0=none
  110253. 1=implicitly populated values from map column
  110254. 2=listed arbitrary values */
  110255. /* The below does a linear, single monotonic sequence mapping. */
  110256. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  110257. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  110258. int q_quant; /* bits: 0 < quant <= 16 */
  110259. int q_sequencep; /* bitflag */
  110260. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  110261. map == 2: list of dim*entries quantized entry vals
  110262. */
  110263. /* encode helpers ********************************************************/
  110264. struct encode_aux_nearestmatch *nearest_tree;
  110265. struct encode_aux_threshmatch *thresh_tree;
  110266. struct encode_aux_pigeonhole *pigeon_tree;
  110267. int allocedp;
  110268. } static_codebook;
  110269. /* this structures an arbitrary trained book to quickly find the
  110270. nearest cell match */
  110271. typedef struct encode_aux_nearestmatch{
  110272. /* pre-calculated partitioning tree */
  110273. long *ptr0;
  110274. long *ptr1;
  110275. long *p; /* decision points (each is an entry) */
  110276. long *q; /* decision points (each is an entry) */
  110277. long aux; /* number of tree entries */
  110278. long alloc;
  110279. } encode_aux_nearestmatch;
  110280. /* assumes a maptype of 1; encode side only, so that's OK */
  110281. typedef struct encode_aux_threshmatch{
  110282. float *quantthresh;
  110283. long *quantmap;
  110284. int quantvals;
  110285. int threshvals;
  110286. } encode_aux_threshmatch;
  110287. typedef struct encode_aux_pigeonhole{
  110288. float min;
  110289. float del;
  110290. int mapentries;
  110291. int quantvals;
  110292. long *pigeonmap;
  110293. long fittotal;
  110294. long *fitlist;
  110295. long *fitmap;
  110296. long *fitlength;
  110297. } encode_aux_pigeonhole;
  110298. typedef struct codebook{
  110299. long dim; /* codebook dimensions (elements per vector) */
  110300. long entries; /* codebook entries */
  110301. long used_entries; /* populated codebook entries */
  110302. const static_codebook *c;
  110303. /* for encode, the below are entry-ordered, fully populated */
  110304. /* for decode, the below are ordered by bitreversed codeword and only
  110305. used entries are populated */
  110306. float *valuelist; /* list of dim*entries actual entry values */
  110307. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  110308. int *dec_index; /* only used if sparseness collapsed */
  110309. char *dec_codelengths;
  110310. ogg_uint32_t *dec_firsttable;
  110311. int dec_firsttablen;
  110312. int dec_maxlength;
  110313. } codebook;
  110314. extern void vorbis_staticbook_clear(static_codebook *b);
  110315. extern void vorbis_staticbook_destroy(static_codebook *b);
  110316. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  110317. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  110318. extern void vorbis_book_clear(codebook *b);
  110319. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  110320. extern float *_book_logdist(const static_codebook *b,float *vals);
  110321. extern float _float32_unpack(long val);
  110322. extern long _float32_pack(float val);
  110323. extern int _best(codebook *book, float *a, int step);
  110324. extern int _ilog(unsigned int v);
  110325. extern long _book_maptype1_quantvals(const static_codebook *b);
  110326. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  110327. extern long vorbis_book_codeword(codebook *book,int entry);
  110328. extern long vorbis_book_codelen(codebook *book,int entry);
  110329. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  110330. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  110331. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  110332. extern int vorbis_book_errorv(codebook *book, float *a);
  110333. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  110334. oggpack_buffer *b);
  110335. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  110336. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  110337. oggpack_buffer *b,int n);
  110338. extern long vorbis_book_decodev_set(codebook *book, float *a,
  110339. oggpack_buffer *b,int n);
  110340. extern long vorbis_book_decodev_add(codebook *book, float *a,
  110341. oggpack_buffer *b,int n);
  110342. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  110343. long off,int ch,
  110344. oggpack_buffer *b,int n);
  110345. #endif
  110346. /*** End of inlined file: codebook.h ***/
  110347. #define BLOCKTYPE_IMPULSE 0
  110348. #define BLOCKTYPE_PADDING 1
  110349. #define BLOCKTYPE_TRANSITION 0
  110350. #define BLOCKTYPE_LONG 1
  110351. #define PACKETBLOBS 15
  110352. typedef struct vorbis_block_internal{
  110353. float **pcmdelay; /* this is a pointer into local storage */
  110354. float ampmax;
  110355. int blocktype;
  110356. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  110357. blob [PACKETBLOBS/2] points to
  110358. the oggpack_buffer in the
  110359. main vorbis_block */
  110360. } vorbis_block_internal;
  110361. typedef void vorbis_look_floor;
  110362. typedef void vorbis_look_residue;
  110363. typedef void vorbis_look_transform;
  110364. /* mode ************************************************************/
  110365. typedef struct {
  110366. int blockflag;
  110367. int windowtype;
  110368. int transformtype;
  110369. int mapping;
  110370. } vorbis_info_mode;
  110371. typedef void vorbis_info_floor;
  110372. typedef void vorbis_info_residue;
  110373. typedef void vorbis_info_mapping;
  110374. /*** Start of inlined file: psy.h ***/
  110375. #ifndef _V_PSY_H_
  110376. #define _V_PSY_H_
  110377. /*** Start of inlined file: smallft.h ***/
  110378. #ifndef _V_SMFT_H_
  110379. #define _V_SMFT_H_
  110380. typedef struct {
  110381. int n;
  110382. float *trigcache;
  110383. int *splitcache;
  110384. } drft_lookup;
  110385. extern void drft_forward(drft_lookup *l,float *data);
  110386. extern void drft_backward(drft_lookup *l,float *data);
  110387. extern void drft_init(drft_lookup *l,int n);
  110388. extern void drft_clear(drft_lookup *l);
  110389. #endif
  110390. /*** End of inlined file: smallft.h ***/
  110391. /*** Start of inlined file: backends.h ***/
  110392. /* this is exposed up here because we need it for static modes.
  110393. Lookups for each backend aren't exposed because there's no reason
  110394. to do so */
  110395. #ifndef _vorbis_backend_h_
  110396. #define _vorbis_backend_h_
  110397. /* this would all be simpler/shorter with templates, but.... */
  110398. /* Floor backend generic *****************************************/
  110399. typedef struct{
  110400. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  110401. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  110402. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  110403. void (*free_info) (vorbis_info_floor *);
  110404. void (*free_look) (vorbis_look_floor *);
  110405. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  110406. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  110407. void *buffer,float *);
  110408. } vorbis_func_floor;
  110409. typedef struct{
  110410. int order;
  110411. long rate;
  110412. long barkmap;
  110413. int ampbits;
  110414. int ampdB;
  110415. int numbooks; /* <= 16 */
  110416. int books[16];
  110417. float lessthan; /* encode-only config setting hacks for libvorbis */
  110418. float greaterthan; /* encode-only config setting hacks for libvorbis */
  110419. } vorbis_info_floor0;
  110420. #define VIF_POSIT 63
  110421. #define VIF_CLASS 16
  110422. #define VIF_PARTS 31
  110423. typedef struct{
  110424. int partitions; /* 0 to 31 */
  110425. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  110426. int class_dim[VIF_CLASS]; /* 1 to 8 */
  110427. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  110428. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  110429. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  110430. int mult; /* 1 2 3 or 4 */
  110431. int postlist[VIF_POSIT+2]; /* first two implicit */
  110432. /* encode side analysis parameters */
  110433. float maxover;
  110434. float maxunder;
  110435. float maxerr;
  110436. float twofitweight;
  110437. float twofitatten;
  110438. int n;
  110439. } vorbis_info_floor1;
  110440. /* Residue backend generic *****************************************/
  110441. typedef struct{
  110442. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  110443. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  110444. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  110445. vorbis_info_residue *);
  110446. void (*free_info) (vorbis_info_residue *);
  110447. void (*free_look) (vorbis_look_residue *);
  110448. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  110449. float **,int *,int);
  110450. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  110451. vorbis_look_residue *,
  110452. float **,float **,int *,int,long **);
  110453. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  110454. float **,int *,int);
  110455. } vorbis_func_residue;
  110456. typedef struct vorbis_info_residue0{
  110457. /* block-partitioned VQ coded straight residue */
  110458. long begin;
  110459. long end;
  110460. /* first stage (lossless partitioning) */
  110461. int grouping; /* group n vectors per partition */
  110462. int partitions; /* possible codebooks for a partition */
  110463. int groupbook; /* huffbook for partitioning */
  110464. int secondstages[64]; /* expanded out to pointers in lookup */
  110465. int booklist[256]; /* list of second stage books */
  110466. float classmetric1[64];
  110467. float classmetric2[64];
  110468. } vorbis_info_residue0;
  110469. /* Mapping backend generic *****************************************/
  110470. typedef struct{
  110471. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  110472. oggpack_buffer *);
  110473. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  110474. void (*free_info) (vorbis_info_mapping *);
  110475. int (*forward) (struct vorbis_block *vb);
  110476. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  110477. } vorbis_func_mapping;
  110478. typedef struct vorbis_info_mapping0{
  110479. int submaps; /* <= 16 */
  110480. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  110481. int floorsubmap[16]; /* [mux] submap to floors */
  110482. int residuesubmap[16]; /* [mux] submap to residue */
  110483. int coupling_steps;
  110484. int coupling_mag[256];
  110485. int coupling_ang[256];
  110486. } vorbis_info_mapping0;
  110487. #endif
  110488. /*** End of inlined file: backends.h ***/
  110489. #ifndef EHMER_MAX
  110490. #define EHMER_MAX 56
  110491. #endif
  110492. /* psychoacoustic setup ********************************************/
  110493. #define P_BANDS 17 /* 62Hz to 16kHz */
  110494. #define P_LEVELS 8 /* 30dB to 100dB */
  110495. #define P_LEVEL_0 30. /* 30 dB */
  110496. #define P_NOISECURVES 3
  110497. #define NOISE_COMPAND_LEVELS 40
  110498. typedef struct vorbis_info_psy{
  110499. int blockflag;
  110500. float ath_adjatt;
  110501. float ath_maxatt;
  110502. float tone_masteratt[P_NOISECURVES];
  110503. float tone_centerboost;
  110504. float tone_decay;
  110505. float tone_abs_limit;
  110506. float toneatt[P_BANDS];
  110507. int noisemaskp;
  110508. float noisemaxsupp;
  110509. float noisewindowlo;
  110510. float noisewindowhi;
  110511. int noisewindowlomin;
  110512. int noisewindowhimin;
  110513. int noisewindowfixed;
  110514. float noiseoff[P_NOISECURVES][P_BANDS];
  110515. float noisecompand[NOISE_COMPAND_LEVELS];
  110516. float max_curve_dB;
  110517. int normal_channel_p;
  110518. int normal_point_p;
  110519. int normal_start;
  110520. int normal_partition;
  110521. double normal_thresh;
  110522. } vorbis_info_psy;
  110523. typedef struct{
  110524. int eighth_octave_lines;
  110525. /* for block long/short tuning; encode only */
  110526. float preecho_thresh[VE_BANDS];
  110527. float postecho_thresh[VE_BANDS];
  110528. float stretch_penalty;
  110529. float preecho_minenergy;
  110530. float ampmax_att_per_sec;
  110531. /* channel coupling config */
  110532. int coupling_pkHz[PACKETBLOBS];
  110533. int coupling_pointlimit[2][PACKETBLOBS];
  110534. int coupling_prepointamp[PACKETBLOBS];
  110535. int coupling_postpointamp[PACKETBLOBS];
  110536. int sliding_lowpass[2][PACKETBLOBS];
  110537. } vorbis_info_psy_global;
  110538. typedef struct {
  110539. float ampmax;
  110540. int channels;
  110541. vorbis_info_psy_global *gi;
  110542. int coupling_pointlimit[2][P_NOISECURVES];
  110543. } vorbis_look_psy_global;
  110544. typedef struct {
  110545. int n;
  110546. struct vorbis_info_psy *vi;
  110547. float ***tonecurves;
  110548. float **noiseoffset;
  110549. float *ath;
  110550. long *octave; /* in n.ocshift format */
  110551. long *bark;
  110552. long firstoc;
  110553. long shiftoc;
  110554. int eighth_octave_lines; /* power of two, please */
  110555. int total_octave_lines;
  110556. long rate; /* cache it */
  110557. float m_val; /* Masking compensation value */
  110558. } vorbis_look_psy;
  110559. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  110560. vorbis_info_psy_global *gi,int n,long rate);
  110561. extern void _vp_psy_clear(vorbis_look_psy *p);
  110562. extern void *_vi_psy_dup(void *source);
  110563. extern void _vi_psy_free(vorbis_info_psy *i);
  110564. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  110565. extern void _vp_remove_floor(vorbis_look_psy *p,
  110566. float *mdct,
  110567. int *icodedflr,
  110568. float *residue,
  110569. int sliding_lowpass);
  110570. extern void _vp_noisemask(vorbis_look_psy *p,
  110571. float *logmdct,
  110572. float *logmask);
  110573. extern void _vp_tonemask(vorbis_look_psy *p,
  110574. float *logfft,
  110575. float *logmask,
  110576. float global_specmax,
  110577. float local_specmax);
  110578. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  110579. float *noise,
  110580. float *tone,
  110581. int offset_select,
  110582. float *logmask,
  110583. float *mdct,
  110584. float *logmdct);
  110585. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  110586. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  110587. vorbis_info_psy_global *g,
  110588. vorbis_look_psy *p,
  110589. vorbis_info_mapping0 *vi,
  110590. float **mdct);
  110591. extern void _vp_couple(int blobno,
  110592. vorbis_info_psy_global *g,
  110593. vorbis_look_psy *p,
  110594. vorbis_info_mapping0 *vi,
  110595. float **res,
  110596. float **mag_memo,
  110597. int **mag_sort,
  110598. int **ifloor,
  110599. int *nonzero,
  110600. int sliding_lowpass);
  110601. extern void _vp_noise_normalize(vorbis_look_psy *p,
  110602. float *in,float *out,int *sortedindex);
  110603. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  110604. float *magnitudes,int *sortedindex);
  110605. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  110606. vorbis_look_psy *p,
  110607. vorbis_info_mapping0 *vi,
  110608. float **mags);
  110609. extern void hf_reduction(vorbis_info_psy_global *g,
  110610. vorbis_look_psy *p,
  110611. vorbis_info_mapping0 *vi,
  110612. float **mdct);
  110613. #endif
  110614. /*** End of inlined file: psy.h ***/
  110615. /*** Start of inlined file: bitrate.h ***/
  110616. #ifndef _V_BITRATE_H_
  110617. #define _V_BITRATE_H_
  110618. /*** Start of inlined file: os.h ***/
  110619. #ifndef _OS_H
  110620. #define _OS_H
  110621. /********************************************************************
  110622. * *
  110623. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  110624. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  110625. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  110626. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  110627. * *
  110628. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  110629. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  110630. * *
  110631. ********************************************************************
  110632. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  110633. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  110634. ********************************************************************/
  110635. #ifdef HAVE_CONFIG_H
  110636. #include "config.h"
  110637. #endif
  110638. #include <math.h>
  110639. /*** Start of inlined file: misc.h ***/
  110640. #ifndef _V_RANDOM_H_
  110641. #define _V_RANDOM_H_
  110642. extern int analysis_noisy;
  110643. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  110644. extern void _vorbis_block_ripcord(vorbis_block *vb);
  110645. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  110646. ogg_int64_t off);
  110647. #ifdef DEBUG_MALLOC
  110648. #define _VDBG_GRAPHFILE "malloc.m"
  110649. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  110650. extern void _VDBG_free(void *ptr,char *file,long line);
  110651. #ifndef MISC_C
  110652. #undef _ogg_malloc
  110653. #undef _ogg_calloc
  110654. #undef _ogg_realloc
  110655. #undef _ogg_free
  110656. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  110657. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  110658. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  110659. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  110660. #endif
  110661. #endif
  110662. #endif
  110663. /*** End of inlined file: misc.h ***/
  110664. #ifndef _V_IFDEFJAIL_H_
  110665. # define _V_IFDEFJAIL_H_
  110666. # ifdef __GNUC__
  110667. # define STIN static __inline__
  110668. # elif _WIN32
  110669. # define STIN static __inline
  110670. # else
  110671. # define STIN static
  110672. # endif
  110673. #ifdef DJGPP
  110674. # define rint(x) (floor((x)+0.5f))
  110675. #endif
  110676. #ifndef M_PI
  110677. # define M_PI (3.1415926536f)
  110678. #endif
  110679. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  110680. # include <malloc.h>
  110681. # define rint(x) (floor((x)+0.5f))
  110682. # define NO_FLOAT_MATH_LIB
  110683. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  110684. #endif
  110685. #if defined(__SYMBIAN32__) && defined(__WINS__)
  110686. void *_alloca(size_t size);
  110687. # define alloca _alloca
  110688. #endif
  110689. #ifndef FAST_HYPOT
  110690. # define FAST_HYPOT hypot
  110691. #endif
  110692. #endif
  110693. #ifdef HAVE_ALLOCA_H
  110694. # include <alloca.h>
  110695. #endif
  110696. #ifdef USE_MEMORY_H
  110697. # include <memory.h>
  110698. #endif
  110699. #ifndef min
  110700. # define min(x,y) ((x)>(y)?(y):(x))
  110701. #endif
  110702. #ifndef max
  110703. # define max(x,y) ((x)<(y)?(y):(x))
  110704. #endif
  110705. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  110706. # define VORBIS_FPU_CONTROL
  110707. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  110708. Because of encapsulation constraints (GCC can't see inside the asm
  110709. block and so we end up doing stupid things like a store/load that
  110710. is collectively a noop), we do it this way */
  110711. /* we must set up the fpu before this works!! */
  110712. typedef ogg_int16_t vorbis_fpu_control;
  110713. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110714. ogg_int16_t ret;
  110715. ogg_int16_t temp;
  110716. __asm__ __volatile__("fnstcw %0\n\t"
  110717. "movw %0,%%dx\n\t"
  110718. "orw $62463,%%dx\n\t"
  110719. "movw %%dx,%1\n\t"
  110720. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  110721. *fpu=ret;
  110722. }
  110723. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110724. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  110725. }
  110726. /* assumes the FPU is in round mode! */
  110727. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  110728. we get extra fst/fld to
  110729. truncate precision */
  110730. int i;
  110731. __asm__("fistl %0": "=m"(i) : "t"(f));
  110732. return(i);
  110733. }
  110734. #endif
  110735. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  110736. # define VORBIS_FPU_CONTROL
  110737. typedef ogg_int16_t vorbis_fpu_control;
  110738. static __inline int vorbis_ftoi(double f){
  110739. int i;
  110740. __asm{
  110741. fld f
  110742. fistp i
  110743. }
  110744. return i;
  110745. }
  110746. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  110747. }
  110748. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  110749. }
  110750. #endif
  110751. #ifndef VORBIS_FPU_CONTROL
  110752. typedef int vorbis_fpu_control;
  110753. static int vorbis_ftoi(double f){
  110754. return (int)(f+.5);
  110755. }
  110756. /* We don't have special code for this compiler/arch, so do it the slow way */
  110757. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  110758. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  110759. #endif
  110760. #endif /* _OS_H */
  110761. /*** End of inlined file: os.h ***/
  110762. /* encode side bitrate tracking */
  110763. typedef struct bitrate_manager_state {
  110764. int managed;
  110765. long avg_reservoir;
  110766. long minmax_reservoir;
  110767. long avg_bitsper;
  110768. long min_bitsper;
  110769. long max_bitsper;
  110770. long short_per_long;
  110771. double avgfloat;
  110772. vorbis_block *vb;
  110773. int choice;
  110774. } bitrate_manager_state;
  110775. typedef struct bitrate_manager_info{
  110776. long avg_rate;
  110777. long min_rate;
  110778. long max_rate;
  110779. long reservoir_bits;
  110780. double reservoir_bias;
  110781. double slew_damp;
  110782. } bitrate_manager_info;
  110783. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  110784. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  110785. extern int vorbis_bitrate_managed(vorbis_block *vb);
  110786. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  110787. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  110788. #endif
  110789. /*** End of inlined file: bitrate.h ***/
  110790. static int ilog(unsigned int v){
  110791. int ret=0;
  110792. while(v){
  110793. ret++;
  110794. v>>=1;
  110795. }
  110796. return(ret);
  110797. }
  110798. static int ilog2(unsigned int v){
  110799. int ret=0;
  110800. if(v)--v;
  110801. while(v){
  110802. ret++;
  110803. v>>=1;
  110804. }
  110805. return(ret);
  110806. }
  110807. typedef struct private_state {
  110808. /* local lookup storage */
  110809. envelope_lookup *ve; /* envelope lookup */
  110810. int window[2];
  110811. vorbis_look_transform **transform[2]; /* block, type */
  110812. drft_lookup fft_look[2];
  110813. int modebits;
  110814. vorbis_look_floor **flr;
  110815. vorbis_look_residue **residue;
  110816. vorbis_look_psy *psy;
  110817. vorbis_look_psy_global *psy_g_look;
  110818. /* local storage, only used on the encoding side. This way the
  110819. application does not need to worry about freeing some packets'
  110820. memory and not others'; packet storage is always tracked.
  110821. Cleared next call to a _dsp_ function */
  110822. unsigned char *header;
  110823. unsigned char *header1;
  110824. unsigned char *header2;
  110825. bitrate_manager_state bms;
  110826. ogg_int64_t sample_count;
  110827. } private_state;
  110828. /* codec_setup_info contains all the setup information specific to the
  110829. specific compression/decompression mode in progress (eg,
  110830. psychoacoustic settings, channel setup, options, codebook
  110831. etc).
  110832. *********************************************************************/
  110833. /*** Start of inlined file: highlevel.h ***/
  110834. typedef struct highlevel_byblocktype {
  110835. double tone_mask_setting;
  110836. double tone_peaklimit_setting;
  110837. double noise_bias_setting;
  110838. double noise_compand_setting;
  110839. } highlevel_byblocktype;
  110840. typedef struct highlevel_encode_setup {
  110841. void *setup;
  110842. int set_in_stone;
  110843. double base_setting;
  110844. double long_setting;
  110845. double short_setting;
  110846. double impulse_noisetune;
  110847. int managed;
  110848. long bitrate_min;
  110849. long bitrate_av;
  110850. double bitrate_av_damp;
  110851. long bitrate_max;
  110852. long bitrate_reservoir;
  110853. double bitrate_reservoir_bias;
  110854. int impulse_block_p;
  110855. int noise_normalize_p;
  110856. double stereo_point_setting;
  110857. double lowpass_kHz;
  110858. double ath_floating_dB;
  110859. double ath_absolute_dB;
  110860. double amplitude_track_dBpersec;
  110861. double trigger_setting;
  110862. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  110863. } highlevel_encode_setup;
  110864. /*** End of inlined file: highlevel.h ***/
  110865. typedef struct codec_setup_info {
  110866. /* Vorbis supports only short and long blocks, but allows the
  110867. encoder to choose the sizes */
  110868. long blocksizes[2];
  110869. /* modes are the primary means of supporting on-the-fly different
  110870. blocksizes, different channel mappings (LR or M/A),
  110871. different residue backends, etc. Each mode consists of a
  110872. blocksize flag and a mapping (along with the mapping setup */
  110873. int modes;
  110874. int maps;
  110875. int floors;
  110876. int residues;
  110877. int books;
  110878. int psys; /* encode only */
  110879. vorbis_info_mode *mode_param[64];
  110880. int map_type[64];
  110881. vorbis_info_mapping *map_param[64];
  110882. int floor_type[64];
  110883. vorbis_info_floor *floor_param[64];
  110884. int residue_type[64];
  110885. vorbis_info_residue *residue_param[64];
  110886. static_codebook *book_param[256];
  110887. codebook *fullbooks;
  110888. vorbis_info_psy *psy_param[4]; /* encode only */
  110889. vorbis_info_psy_global psy_g_param;
  110890. bitrate_manager_info bi;
  110891. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  110892. highly redundant structure, but
  110893. improves clarity of program flow. */
  110894. int halfrate_flag; /* painless downsample for decode */
  110895. } codec_setup_info;
  110896. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  110897. extern void _vp_global_free(vorbis_look_psy_global *look);
  110898. #endif
  110899. /*** End of inlined file: codec_internal.h ***/
  110900. /*** Start of inlined file: registry.h ***/
  110901. #ifndef _V_REG_H_
  110902. #define _V_REG_H_
  110903. #define VI_TRANSFORMB 1
  110904. #define VI_WINDOWB 1
  110905. #define VI_TIMEB 1
  110906. #define VI_FLOORB 2
  110907. #define VI_RESB 3
  110908. #define VI_MAPB 1
  110909. extern vorbis_func_floor *_floor_P[];
  110910. extern vorbis_func_residue *_residue_P[];
  110911. extern vorbis_func_mapping *_mapping_P[];
  110912. #endif
  110913. /*** End of inlined file: registry.h ***/
  110914. /*** Start of inlined file: scales.h ***/
  110915. #ifndef _V_SCALES_H_
  110916. #define _V_SCALES_H_
  110917. #include <math.h>
  110918. /* 20log10(x) */
  110919. #define VORBIS_IEEE_FLOAT32 1
  110920. #ifdef VORBIS_IEEE_FLOAT32
  110921. static float unitnorm(float x){
  110922. union {
  110923. ogg_uint32_t i;
  110924. float f;
  110925. } ix;
  110926. ix.f = x;
  110927. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  110928. return ix.f;
  110929. }
  110930. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  110931. static float todB(const float *x){
  110932. union {
  110933. ogg_uint32_t i;
  110934. float f;
  110935. } ix;
  110936. ix.f = *x;
  110937. ix.i = ix.i&0x7fffffff;
  110938. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  110939. }
  110940. #define todB_nn(x) todB(x)
  110941. #else
  110942. static float unitnorm(float x){
  110943. if(x<0)return(-1.f);
  110944. return(1.f);
  110945. }
  110946. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  110947. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  110948. #endif
  110949. #define fromdB(x) (exp((x)*.11512925f))
  110950. /* The bark scale equations are approximations, since the original
  110951. table was somewhat hand rolled. The below are chosen to have the
  110952. best possible fit to the rolled tables, thus their somewhat odd
  110953. appearance (these are more accurate and over a longer range than
  110954. the oft-quoted bark equations found in the texts I have). The
  110955. approximations are valid from 0 - 30kHz (nyquist) or so.
  110956. all f in Hz, z in Bark */
  110957. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  110958. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  110959. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  110960. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  110961. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  110962. 0.0 */
  110963. #define toOC(n) (log(n)*1.442695f-5.965784f)
  110964. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  110965. #endif
  110966. /*** End of inlined file: scales.h ***/
  110967. int analysis_noisy=1;
  110968. /* decides between modes, dispatches to the appropriate mapping. */
  110969. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  110970. int ret,i;
  110971. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  110972. vb->glue_bits=0;
  110973. vb->time_bits=0;
  110974. vb->floor_bits=0;
  110975. vb->res_bits=0;
  110976. /* first things first. Make sure encode is ready */
  110977. for(i=0;i<PACKETBLOBS;i++)
  110978. oggpack_reset(vbi->packetblob[i]);
  110979. /* we only have one mapping type (0), and we let the mapping code
  110980. itself figure out what soft mode to use. This allows easier
  110981. bitrate management */
  110982. if((ret=_mapping_P[0]->forward(vb)))
  110983. return(ret);
  110984. if(op){
  110985. if(vorbis_bitrate_managed(vb))
  110986. /* The app is using a bitmanaged mode... but not using the
  110987. bitrate management interface. */
  110988. return(OV_EINVAL);
  110989. op->packet=oggpack_get_buffer(&vb->opb);
  110990. op->bytes=oggpack_bytes(&vb->opb);
  110991. op->b_o_s=0;
  110992. op->e_o_s=vb->eofflag;
  110993. op->granulepos=vb->granulepos;
  110994. op->packetno=vb->sequence; /* for sake of completeness */
  110995. }
  110996. return(0);
  110997. }
  110998. /* there was no great place to put this.... */
  110999. void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  111000. int j;
  111001. FILE *of;
  111002. char buffer[80];
  111003. /* if(i==5870){*/
  111004. sprintf(buffer,"%s_%d.m",base,i);
  111005. of=fopen(buffer,"w");
  111006. if(!of)perror("failed to open data dump file");
  111007. for(j=0;j<n;j++){
  111008. if(bark){
  111009. float b=toBARK((4000.f*j/n)+.25);
  111010. fprintf(of,"%f ",b);
  111011. }else
  111012. if(off!=0)
  111013. fprintf(of,"%f ",(double)(j+off)/8000.);
  111014. else
  111015. fprintf(of,"%f ",(double)j);
  111016. if(dB){
  111017. float val;
  111018. if(v[j]==0.)
  111019. val=-140.;
  111020. else
  111021. val=todB(v+j);
  111022. fprintf(of,"%f\n",val);
  111023. }else{
  111024. fprintf(of,"%f\n",v[j]);
  111025. }
  111026. }
  111027. fclose(of);
  111028. /* } */
  111029. }
  111030. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  111031. ogg_int64_t off){
  111032. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  111033. }
  111034. #endif
  111035. /*** End of inlined file: analysis.c ***/
  111036. /*** Start of inlined file: bitrate.c ***/
  111037. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111038. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111039. // tasks..
  111040. #if JUCE_MSVC
  111041. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111042. #endif
  111043. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111044. #if JUCE_USE_OGGVORBIS
  111045. #include <stdlib.h>
  111046. #include <string.h>
  111047. #include <math.h>
  111048. /* compute bitrate tracking setup */
  111049. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  111050. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111051. bitrate_manager_info *bi=&ci->bi;
  111052. memset(bm,0,sizeof(*bm));
  111053. if(bi && (bi->reservoir_bits>0)){
  111054. long ratesamples=vi->rate;
  111055. int halfsamples=ci->blocksizes[0]>>1;
  111056. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  111057. bm->managed=1;
  111058. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  111059. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  111060. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  111061. bm->avgfloat=PACKETBLOBS/2;
  111062. /* not a necessary fix, but one that leads to a more balanced
  111063. typical initialization */
  111064. {
  111065. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111066. bm->minmax_reservoir=desired_fill;
  111067. bm->avg_reservoir=desired_fill;
  111068. }
  111069. }
  111070. }
  111071. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  111072. memset(bm,0,sizeof(*bm));
  111073. return;
  111074. }
  111075. int vorbis_bitrate_managed(vorbis_block *vb){
  111076. vorbis_dsp_state *vd=vb->vd;
  111077. private_state *b=(private_state*)vd->backend_state;
  111078. bitrate_manager_state *bm=&b->bms;
  111079. if(bm && bm->managed)return(1);
  111080. return(0);
  111081. }
  111082. /* finish taking in the block we just processed */
  111083. int vorbis_bitrate_addblock(vorbis_block *vb){
  111084. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111085. vorbis_dsp_state *vd=vb->vd;
  111086. private_state *b=(private_state*)vd->backend_state;
  111087. bitrate_manager_state *bm=&b->bms;
  111088. vorbis_info *vi=vd->vi;
  111089. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111090. bitrate_manager_info *bi=&ci->bi;
  111091. int choice=rint(bm->avgfloat);
  111092. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111093. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  111094. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  111095. int samples=ci->blocksizes[vb->W]>>1;
  111096. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  111097. if(!bm->managed){
  111098. /* not a bitrate managed stream, but for API simplicity, we'll
  111099. buffer the packet to keep the code path clean */
  111100. if(bm->vb)return(-1); /* one has been submitted without
  111101. being claimed */
  111102. bm->vb=vb;
  111103. return(0);
  111104. }
  111105. bm->vb=vb;
  111106. /* look ahead for avg floater */
  111107. if(bm->avg_bitsper>0){
  111108. double slew=0.;
  111109. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111110. double slewlimit= 15./bi->slew_damp;
  111111. /* choosing a new floater:
  111112. if we're over target, we slew down
  111113. if we're under target, we slew up
  111114. choose slew as follows: look through packetblobs of this frame
  111115. and set slew as the first in the appropriate direction that
  111116. gives us the slew we want. This may mean no slew if delta is
  111117. already favorable.
  111118. Then limit slew to slew max */
  111119. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111120. while(choice>0 && this_bits>avg_target_bits &&
  111121. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  111122. choice--;
  111123. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111124. }
  111125. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111126. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  111127. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  111128. choice++;
  111129. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111130. }
  111131. }
  111132. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  111133. if(slew<-slewlimit)slew=-slewlimit;
  111134. if(slew>slewlimit)slew=slewlimit;
  111135. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  111136. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111137. }
  111138. /* enforce min(if used) on the current floater (if used) */
  111139. if(bm->min_bitsper>0){
  111140. /* do we need to force the bitrate up? */
  111141. if(this_bits<min_target_bits){
  111142. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  111143. choice++;
  111144. if(choice>=PACKETBLOBS)break;
  111145. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111146. }
  111147. }
  111148. }
  111149. /* enforce max (if used) on the current floater (if used) */
  111150. if(bm->max_bitsper>0){
  111151. /* do we need to force the bitrate down? */
  111152. if(this_bits>max_target_bits){
  111153. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  111154. choice--;
  111155. if(choice<0)break;
  111156. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111157. }
  111158. }
  111159. }
  111160. /* Choice of packetblobs now made based on floater, and min/max
  111161. requirements. Now boundary check extreme choices */
  111162. if(choice<0){
  111163. /* choosing a smaller packetblob is insufficient to trim bitrate.
  111164. frame will need to be truncated */
  111165. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  111166. bm->choice=choice=0;
  111167. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  111168. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  111169. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111170. }
  111171. }else{
  111172. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  111173. if(choice>=PACKETBLOBS)
  111174. choice=PACKETBLOBS-1;
  111175. bm->choice=choice;
  111176. /* prop up bitrate according to demand. pad this frame out with zeroes */
  111177. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  111178. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  111179. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  111180. }
  111181. /* now we have the final packet and the final packet size. Update statistics */
  111182. /* min and max reservoir */
  111183. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  111184. if(max_target_bits>0 && this_bits>max_target_bits){
  111185. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111186. }else if(min_target_bits>0 && this_bits<min_target_bits){
  111187. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111188. }else{
  111189. /* inbetween; we want to take reservoir toward but not past desired_fill */
  111190. if(bm->minmax_reservoir>desired_fill){
  111191. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  111192. bm->minmax_reservoir+=(this_bits-max_target_bits);
  111193. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  111194. }else{
  111195. bm->minmax_reservoir=desired_fill;
  111196. }
  111197. }else{
  111198. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  111199. bm->minmax_reservoir+=(this_bits-min_target_bits);
  111200. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  111201. }else{
  111202. bm->minmax_reservoir=desired_fill;
  111203. }
  111204. }
  111205. }
  111206. }
  111207. /* avg reservoir */
  111208. if(bm->avg_bitsper>0){
  111209. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  111210. bm->avg_reservoir+=this_bits-avg_target_bits;
  111211. }
  111212. return(0);
  111213. }
  111214. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  111215. private_state *b=(private_state*)vd->backend_state;
  111216. bitrate_manager_state *bm=&b->bms;
  111217. vorbis_block *vb=bm->vb;
  111218. int choice=PACKETBLOBS/2;
  111219. if(!vb)return 0;
  111220. if(op){
  111221. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111222. if(vorbis_bitrate_managed(vb))
  111223. choice=bm->choice;
  111224. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  111225. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  111226. op->b_o_s=0;
  111227. op->e_o_s=vb->eofflag;
  111228. op->granulepos=vb->granulepos;
  111229. op->packetno=vb->sequence; /* for sake of completeness */
  111230. }
  111231. bm->vb=0;
  111232. return(1);
  111233. }
  111234. #endif
  111235. /*** End of inlined file: bitrate.c ***/
  111236. /*** Start of inlined file: block.c ***/
  111237. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  111238. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111239. // tasks..
  111240. #if JUCE_MSVC
  111241. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111242. #endif
  111243. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  111244. #if JUCE_USE_OGGVORBIS
  111245. #include <stdio.h>
  111246. #include <stdlib.h>
  111247. #include <string.h>
  111248. /*** Start of inlined file: window.h ***/
  111249. #ifndef _V_WINDOW_
  111250. #define _V_WINDOW_
  111251. extern float *_vorbis_window_get(int n);
  111252. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  111253. int lW,int W,int nW);
  111254. #endif
  111255. /*** End of inlined file: window.h ***/
  111256. /*** Start of inlined file: lpc.h ***/
  111257. #ifndef _V_LPC_H_
  111258. #define _V_LPC_H_
  111259. /* simple linear scale LPC code */
  111260. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  111261. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  111262. float *data,long n);
  111263. #endif
  111264. /*** End of inlined file: lpc.h ***/
  111265. /* pcm accumulator examples (not exhaustive):
  111266. <-------------- lW ---------------->
  111267. <--------------- W ---------------->
  111268. : .....|..... _______________ |
  111269. : .''' | '''_--- | |\ |
  111270. :.....''' |_____--- '''......| | \_______|
  111271. :.................|__________________|_______|__|______|
  111272. |<------ Sl ------>| > Sr < |endW
  111273. |beginSl |endSl | |endSr
  111274. |beginW |endlW |beginSr
  111275. |< lW >|
  111276. <--------------- W ---------------->
  111277. | | .. ______________ |
  111278. | | ' `/ | ---_ |
  111279. |___.'___/`. | ---_____|
  111280. |_______|__|_______|_________________|
  111281. | >|Sl|< |<------ Sr ----->|endW
  111282. | | |endSl |beginSr |endSr
  111283. |beginW | |endlW
  111284. mult[0] |beginSl mult[n]
  111285. <-------------- lW ----------------->
  111286. |<--W-->|
  111287. : .............. ___ | |
  111288. : .''' |`/ \ | |
  111289. :.....''' |/`....\|...|
  111290. :.........................|___|___|___|
  111291. |Sl |Sr |endW
  111292. | | |endSr
  111293. | |beginSr
  111294. | |endSl
  111295. |beginSl
  111296. |beginW
  111297. */
  111298. /* block abstraction setup *********************************************/
  111299. #ifndef WORD_ALIGN
  111300. #define WORD_ALIGN 8
  111301. #endif
  111302. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  111303. int i;
  111304. memset(vb,0,sizeof(*vb));
  111305. vb->vd=v;
  111306. vb->localalloc=0;
  111307. vb->localstore=NULL;
  111308. if(v->analysisp){
  111309. vorbis_block_internal *vbi=(vorbis_block_internal*)
  111310. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  111311. vbi->ampmax=-9999;
  111312. for(i=0;i<PACKETBLOBS;i++){
  111313. if(i==PACKETBLOBS/2){
  111314. vbi->packetblob[i]=&vb->opb;
  111315. }else{
  111316. vbi->packetblob[i]=
  111317. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  111318. }
  111319. oggpack_writeinit(vbi->packetblob[i]);
  111320. }
  111321. }
  111322. return(0);
  111323. }
  111324. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  111325. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  111326. if(bytes+vb->localtop>vb->localalloc){
  111327. /* can't just _ogg_realloc... there are outstanding pointers */
  111328. if(vb->localstore){
  111329. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  111330. vb->totaluse+=vb->localtop;
  111331. link->next=vb->reap;
  111332. link->ptr=vb->localstore;
  111333. vb->reap=link;
  111334. }
  111335. /* highly conservative */
  111336. vb->localalloc=bytes;
  111337. vb->localstore=_ogg_malloc(vb->localalloc);
  111338. vb->localtop=0;
  111339. }
  111340. {
  111341. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  111342. vb->localtop+=bytes;
  111343. return ret;
  111344. }
  111345. }
  111346. /* reap the chain, pull the ripcord */
  111347. void _vorbis_block_ripcord(vorbis_block *vb){
  111348. /* reap the chain */
  111349. struct alloc_chain *reap=vb->reap;
  111350. while(reap){
  111351. struct alloc_chain *next=reap->next;
  111352. _ogg_free(reap->ptr);
  111353. memset(reap,0,sizeof(*reap));
  111354. _ogg_free(reap);
  111355. reap=next;
  111356. }
  111357. /* consolidate storage */
  111358. if(vb->totaluse){
  111359. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  111360. vb->localalloc+=vb->totaluse;
  111361. vb->totaluse=0;
  111362. }
  111363. /* pull the ripcord */
  111364. vb->localtop=0;
  111365. vb->reap=NULL;
  111366. }
  111367. int vorbis_block_clear(vorbis_block *vb){
  111368. int i;
  111369. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  111370. _vorbis_block_ripcord(vb);
  111371. if(vb->localstore)_ogg_free(vb->localstore);
  111372. if(vbi){
  111373. for(i=0;i<PACKETBLOBS;i++){
  111374. oggpack_writeclear(vbi->packetblob[i]);
  111375. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  111376. }
  111377. _ogg_free(vbi);
  111378. }
  111379. memset(vb,0,sizeof(*vb));
  111380. return(0);
  111381. }
  111382. /* Analysis side code, but directly related to blocking. Thus it's
  111383. here and not in analysis.c (which is for analysis transforms only).
  111384. The init is here because some of it is shared */
  111385. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  111386. int i;
  111387. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111388. private_state *b=NULL;
  111389. int hs;
  111390. if(ci==NULL) return 1;
  111391. hs=ci->halfrate_flag;
  111392. memset(v,0,sizeof(*v));
  111393. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  111394. v->vi=vi;
  111395. b->modebits=ilog2(ci->modes);
  111396. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  111397. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  111398. /* MDCT is tranform 0 */
  111399. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111400. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  111401. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  111402. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  111403. /* Vorbis I uses only window type 0 */
  111404. b->window[0]=ilog2(ci->blocksizes[0])-6;
  111405. b->window[1]=ilog2(ci->blocksizes[1])-6;
  111406. if(encp){ /* encode/decode differ here */
  111407. /* analysis always needs an fft */
  111408. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  111409. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  111410. /* finish the codebooks */
  111411. if(!ci->fullbooks){
  111412. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111413. for(i=0;i<ci->books;i++)
  111414. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  111415. }
  111416. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  111417. for(i=0;i<ci->psys;i++){
  111418. _vp_psy_init(b->psy+i,
  111419. ci->psy_param[i],
  111420. &ci->psy_g_param,
  111421. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  111422. vi->rate);
  111423. }
  111424. v->analysisp=1;
  111425. }else{
  111426. /* finish the codebooks */
  111427. if(!ci->fullbooks){
  111428. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  111429. for(i=0;i<ci->books;i++){
  111430. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  111431. /* decode codebooks are now standalone after init */
  111432. vorbis_staticbook_destroy(ci->book_param[i]);
  111433. ci->book_param[i]=NULL;
  111434. }
  111435. }
  111436. }
  111437. /* initialize the storage vectors. blocksize[1] is small for encode,
  111438. but the correct size for decode */
  111439. v->pcm_storage=ci->blocksizes[1];
  111440. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  111441. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  111442. {
  111443. int i;
  111444. for(i=0;i<vi->channels;i++)
  111445. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  111446. }
  111447. /* all 1 (large block) or 0 (small block) */
  111448. /* explicitly set for the sake of clarity */
  111449. v->lW=0; /* previous window size */
  111450. v->W=0; /* current window size */
  111451. /* all vector indexes */
  111452. v->centerW=ci->blocksizes[1]/2;
  111453. v->pcm_current=v->centerW;
  111454. /* initialize all the backend lookups */
  111455. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  111456. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  111457. for(i=0;i<ci->floors;i++)
  111458. b->flr[i]=_floor_P[ci->floor_type[i]]->
  111459. look(v,ci->floor_param[i]);
  111460. for(i=0;i<ci->residues;i++)
  111461. b->residue[i]=_residue_P[ci->residue_type[i]]->
  111462. look(v,ci->residue_param[i]);
  111463. return 0;
  111464. }
  111465. /* arbitrary settings and spec-mandated numbers get filled in here */
  111466. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111467. private_state *b=NULL;
  111468. if(_vds_shared_init(v,vi,1))return 1;
  111469. b=(private_state*)v->backend_state;
  111470. b->psy_g_look=_vp_global_look(vi);
  111471. /* Initialize the envelope state storage */
  111472. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  111473. _ve_envelope_init(b->ve,vi);
  111474. vorbis_bitrate_init(vi,&b->bms);
  111475. /* compressed audio packets start after the headers
  111476. with sequence number 3 */
  111477. v->sequence=3;
  111478. return(0);
  111479. }
  111480. void vorbis_dsp_clear(vorbis_dsp_state *v){
  111481. int i;
  111482. if(v){
  111483. vorbis_info *vi=v->vi;
  111484. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  111485. private_state *b=(private_state*)v->backend_state;
  111486. if(b){
  111487. if(b->ve){
  111488. _ve_envelope_clear(b->ve);
  111489. _ogg_free(b->ve);
  111490. }
  111491. if(b->transform[0]){
  111492. mdct_clear((mdct_lookup*) b->transform[0][0]);
  111493. _ogg_free(b->transform[0][0]);
  111494. _ogg_free(b->transform[0]);
  111495. }
  111496. if(b->transform[1]){
  111497. mdct_clear((mdct_lookup*) b->transform[1][0]);
  111498. _ogg_free(b->transform[1][0]);
  111499. _ogg_free(b->transform[1]);
  111500. }
  111501. if(b->flr){
  111502. for(i=0;i<ci->floors;i++)
  111503. _floor_P[ci->floor_type[i]]->
  111504. free_look(b->flr[i]);
  111505. _ogg_free(b->flr);
  111506. }
  111507. if(b->residue){
  111508. for(i=0;i<ci->residues;i++)
  111509. _residue_P[ci->residue_type[i]]->
  111510. free_look(b->residue[i]);
  111511. _ogg_free(b->residue);
  111512. }
  111513. if(b->psy){
  111514. for(i=0;i<ci->psys;i++)
  111515. _vp_psy_clear(b->psy+i);
  111516. _ogg_free(b->psy);
  111517. }
  111518. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  111519. vorbis_bitrate_clear(&b->bms);
  111520. drft_clear(&b->fft_look[0]);
  111521. drft_clear(&b->fft_look[1]);
  111522. }
  111523. if(v->pcm){
  111524. for(i=0;i<vi->channels;i++)
  111525. if(v->pcm[i])_ogg_free(v->pcm[i]);
  111526. _ogg_free(v->pcm);
  111527. if(v->pcmret)_ogg_free(v->pcmret);
  111528. }
  111529. if(b){
  111530. /* free header, header1, header2 */
  111531. if(b->header)_ogg_free(b->header);
  111532. if(b->header1)_ogg_free(b->header1);
  111533. if(b->header2)_ogg_free(b->header2);
  111534. _ogg_free(b);
  111535. }
  111536. memset(v,0,sizeof(*v));
  111537. }
  111538. }
  111539. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  111540. int i;
  111541. vorbis_info *vi=v->vi;
  111542. private_state *b=(private_state*)v->backend_state;
  111543. /* free header, header1, header2 */
  111544. if(b->header)_ogg_free(b->header);b->header=NULL;
  111545. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  111546. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  111547. /* Do we have enough storage space for the requested buffer? If not,
  111548. expand the PCM (and envelope) storage */
  111549. if(v->pcm_current+vals>=v->pcm_storage){
  111550. v->pcm_storage=v->pcm_current+vals*2;
  111551. for(i=0;i<vi->channels;i++){
  111552. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  111553. }
  111554. }
  111555. for(i=0;i<vi->channels;i++)
  111556. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  111557. return(v->pcmret);
  111558. }
  111559. static void _preextrapolate_helper(vorbis_dsp_state *v){
  111560. int i;
  111561. int order=32;
  111562. float *lpc=(float*)alloca(order*sizeof(*lpc));
  111563. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  111564. long j;
  111565. v->preextrapolate=1;
  111566. if(v->pcm_current-v->centerW>order*2){ /* safety */
  111567. for(i=0;i<v->vi->channels;i++){
  111568. /* need to run the extrapolation in reverse! */
  111569. for(j=0;j<v->pcm_current;j++)
  111570. work[j]=v->pcm[i][v->pcm_current-j-1];
  111571. /* prime as above */
  111572. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  111573. /* run the predictor filter */
  111574. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  111575. order,
  111576. work+v->pcm_current-v->centerW,
  111577. v->centerW);
  111578. for(j=0;j<v->pcm_current;j++)
  111579. v->pcm[i][v->pcm_current-j-1]=work[j];
  111580. }
  111581. }
  111582. }
  111583. /* call with val<=0 to set eof */
  111584. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  111585. vorbis_info *vi=v->vi;
  111586. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111587. if(vals<=0){
  111588. int order=32;
  111589. int i;
  111590. float *lpc=(float*) alloca(order*sizeof(*lpc));
  111591. /* if it wasn't done earlier (very short sample) */
  111592. if(!v->preextrapolate)
  111593. _preextrapolate_helper(v);
  111594. /* We're encoding the end of the stream. Just make sure we have
  111595. [at least] a few full blocks of zeroes at the end. */
  111596. /* actually, we don't want zeroes; that could drop a large
  111597. amplitude off a cliff, creating spread spectrum noise that will
  111598. suck to encode. Extrapolate for the sake of cleanliness. */
  111599. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  111600. v->eofflag=v->pcm_current;
  111601. v->pcm_current+=ci->blocksizes[1]*3;
  111602. for(i=0;i<vi->channels;i++){
  111603. if(v->eofflag>order*2){
  111604. /* extrapolate with LPC to fill in */
  111605. long n;
  111606. /* make a predictor filter */
  111607. n=v->eofflag;
  111608. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  111609. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  111610. /* run the predictor filter */
  111611. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  111612. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  111613. }else{
  111614. /* not enough data to extrapolate (unlikely to happen due to
  111615. guarding the overlap, but bulletproof in case that
  111616. assumtion goes away). zeroes will do. */
  111617. memset(v->pcm[i]+v->eofflag,0,
  111618. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  111619. }
  111620. }
  111621. }else{
  111622. if(v->pcm_current+vals>v->pcm_storage)
  111623. return(OV_EINVAL);
  111624. v->pcm_current+=vals;
  111625. /* we may want to reverse extrapolate the beginning of a stream
  111626. too... in case we're beginning on a cliff! */
  111627. /* clumsy, but simple. It only runs once, so simple is good. */
  111628. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  111629. _preextrapolate_helper(v);
  111630. }
  111631. return(0);
  111632. }
  111633. /* do the deltas, envelope shaping, pre-echo and determine the size of
  111634. the next block on which to continue analysis */
  111635. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  111636. int i;
  111637. vorbis_info *vi=v->vi;
  111638. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111639. private_state *b=(private_state*)v->backend_state;
  111640. vorbis_look_psy_global *g=b->psy_g_look;
  111641. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  111642. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  111643. /* check to see if we're started... */
  111644. if(!v->preextrapolate)return(0);
  111645. /* check to see if we're done... */
  111646. if(v->eofflag==-1)return(0);
  111647. /* By our invariant, we have lW, W and centerW set. Search for
  111648. the next boundary so we can determine nW (the next window size)
  111649. which lets us compute the shape of the current block's window */
  111650. /* we do an envelope search even on a single blocksize; we may still
  111651. be throwing more bits at impulses, and envelope search handles
  111652. marking impulses too. */
  111653. {
  111654. long bp=_ve_envelope_search(v);
  111655. if(bp==-1){
  111656. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  111657. full long block */
  111658. v->nW=0;
  111659. }else{
  111660. if(ci->blocksizes[0]==ci->blocksizes[1])
  111661. v->nW=0;
  111662. else
  111663. v->nW=bp;
  111664. }
  111665. }
  111666. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  111667. {
  111668. /* center of next block + next block maximum right side. */
  111669. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  111670. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  111671. although this check is
  111672. less strict that the
  111673. _ve_envelope_search,
  111674. the search is not run
  111675. if we only use one
  111676. block size */
  111677. }
  111678. /* fill in the block. Note that for a short window, lW and nW are *short*
  111679. regardless of actual settings in the stream */
  111680. _vorbis_block_ripcord(vb);
  111681. vb->lW=v->lW;
  111682. vb->W=v->W;
  111683. vb->nW=v->nW;
  111684. if(v->W){
  111685. if(!v->lW || !v->nW){
  111686. vbi->blocktype=BLOCKTYPE_TRANSITION;
  111687. /*fprintf(stderr,"-");*/
  111688. }else{
  111689. vbi->blocktype=BLOCKTYPE_LONG;
  111690. /*fprintf(stderr,"_");*/
  111691. }
  111692. }else{
  111693. if(_ve_envelope_mark(v)){
  111694. vbi->blocktype=BLOCKTYPE_IMPULSE;
  111695. /*fprintf(stderr,"|");*/
  111696. }else{
  111697. vbi->blocktype=BLOCKTYPE_PADDING;
  111698. /*fprintf(stderr,".");*/
  111699. }
  111700. }
  111701. vb->vd=v;
  111702. vb->sequence=v->sequence++;
  111703. vb->granulepos=v->granulepos;
  111704. vb->pcmend=ci->blocksizes[v->W];
  111705. /* copy the vectors; this uses the local storage in vb */
  111706. /* this tracks 'strongest peak' for later psychoacoustics */
  111707. /* moved to the global psy state; clean this mess up */
  111708. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  111709. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  111710. vbi->ampmax=g->ampmax;
  111711. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  111712. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  111713. for(i=0;i<vi->channels;i++){
  111714. vbi->pcmdelay[i]=
  111715. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111716. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  111717. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  111718. /* before we added the delay
  111719. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  111720. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  111721. */
  111722. }
  111723. /* handle eof detection: eof==0 means that we've not yet received EOF
  111724. eof>0 marks the last 'real' sample in pcm[]
  111725. eof<0 'no more to do'; doesn't get here */
  111726. if(v->eofflag){
  111727. if(v->centerW>=v->eofflag){
  111728. v->eofflag=-1;
  111729. vb->eofflag=1;
  111730. return(1);
  111731. }
  111732. }
  111733. /* advance storage vectors and clean up */
  111734. {
  111735. int new_centerNext=ci->blocksizes[1]/2;
  111736. int movementW=centerNext-new_centerNext;
  111737. if(movementW>0){
  111738. _ve_envelope_shift(b->ve,movementW);
  111739. v->pcm_current-=movementW;
  111740. for(i=0;i<vi->channels;i++)
  111741. memmove(v->pcm[i],v->pcm[i]+movementW,
  111742. v->pcm_current*sizeof(*v->pcm[i]));
  111743. v->lW=v->W;
  111744. v->W=v->nW;
  111745. v->centerW=new_centerNext;
  111746. if(v->eofflag){
  111747. v->eofflag-=movementW;
  111748. if(v->eofflag<=0)v->eofflag=-1;
  111749. /* do not add padding to end of stream! */
  111750. if(v->centerW>=v->eofflag){
  111751. v->granulepos+=movementW-(v->centerW-v->eofflag);
  111752. }else{
  111753. v->granulepos+=movementW;
  111754. }
  111755. }else{
  111756. v->granulepos+=movementW;
  111757. }
  111758. }
  111759. }
  111760. /* done */
  111761. return(1);
  111762. }
  111763. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  111764. vorbis_info *vi=v->vi;
  111765. codec_setup_info *ci;
  111766. int hs;
  111767. if(!v->backend_state)return -1;
  111768. if(!vi)return -1;
  111769. ci=(codec_setup_info*) vi->codec_setup;
  111770. if(!ci)return -1;
  111771. hs=ci->halfrate_flag;
  111772. v->centerW=ci->blocksizes[1]>>(hs+1);
  111773. v->pcm_current=v->centerW>>hs;
  111774. v->pcm_returned=-1;
  111775. v->granulepos=-1;
  111776. v->sequence=-1;
  111777. v->eofflag=0;
  111778. ((private_state *)(v->backend_state))->sample_count=-1;
  111779. return(0);
  111780. }
  111781. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  111782. if(_vds_shared_init(v,vi,0)) return 1;
  111783. vorbis_synthesis_restart(v);
  111784. return 0;
  111785. }
  111786. /* Unlike in analysis, the window is only partially applied for each
  111787. block. The time domain envelope is not yet handled at the point of
  111788. calling (as it relies on the previous block). */
  111789. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  111790. vorbis_info *vi=v->vi;
  111791. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111792. private_state *b=(private_state*)v->backend_state;
  111793. int hs=ci->halfrate_flag;
  111794. int i,j;
  111795. if(!vb)return(OV_EINVAL);
  111796. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  111797. v->lW=v->W;
  111798. v->W=vb->W;
  111799. v->nW=-1;
  111800. if((v->sequence==-1)||
  111801. (v->sequence+1 != vb->sequence)){
  111802. v->granulepos=-1; /* out of sequence; lose count */
  111803. b->sample_count=-1;
  111804. }
  111805. v->sequence=vb->sequence;
  111806. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  111807. was called on block */
  111808. int n=ci->blocksizes[v->W]>>(hs+1);
  111809. int n0=ci->blocksizes[0]>>(hs+1);
  111810. int n1=ci->blocksizes[1]>>(hs+1);
  111811. int thisCenter;
  111812. int prevCenter;
  111813. v->glue_bits+=vb->glue_bits;
  111814. v->time_bits+=vb->time_bits;
  111815. v->floor_bits+=vb->floor_bits;
  111816. v->res_bits+=vb->res_bits;
  111817. if(v->centerW){
  111818. thisCenter=n1;
  111819. prevCenter=0;
  111820. }else{
  111821. thisCenter=0;
  111822. prevCenter=n1;
  111823. }
  111824. /* v->pcm is now used like a two-stage double buffer. We don't want
  111825. to have to constantly shift *or* adjust memory usage. Don't
  111826. accept a new block until the old is shifted out */
  111827. for(j=0;j<vi->channels;j++){
  111828. /* the overlap/add section */
  111829. if(v->lW){
  111830. if(v->W){
  111831. /* large/large */
  111832. float *w=_vorbis_window_get(b->window[1]-hs);
  111833. float *pcm=v->pcm[j]+prevCenter;
  111834. float *p=vb->pcm[j];
  111835. for(i=0;i<n1;i++)
  111836. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  111837. }else{
  111838. /* large/small */
  111839. float *w=_vorbis_window_get(b->window[0]-hs);
  111840. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  111841. float *p=vb->pcm[j];
  111842. for(i=0;i<n0;i++)
  111843. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111844. }
  111845. }else{
  111846. if(v->W){
  111847. /* small/large */
  111848. float *w=_vorbis_window_get(b->window[0]-hs);
  111849. float *pcm=v->pcm[j]+prevCenter;
  111850. float *p=vb->pcm[j]+n1/2-n0/2;
  111851. for(i=0;i<n0;i++)
  111852. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111853. for(;i<n1/2+n0/2;i++)
  111854. pcm[i]=p[i];
  111855. }else{
  111856. /* small/small */
  111857. float *w=_vorbis_window_get(b->window[0]-hs);
  111858. float *pcm=v->pcm[j]+prevCenter;
  111859. float *p=vb->pcm[j];
  111860. for(i=0;i<n0;i++)
  111861. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  111862. }
  111863. }
  111864. /* the copy section */
  111865. {
  111866. float *pcm=v->pcm[j]+thisCenter;
  111867. float *p=vb->pcm[j]+n;
  111868. for(i=0;i<n;i++)
  111869. pcm[i]=p[i];
  111870. }
  111871. }
  111872. if(v->centerW)
  111873. v->centerW=0;
  111874. else
  111875. v->centerW=n1;
  111876. /* deal with initial packet state; we do this using the explicit
  111877. pcm_returned==-1 flag otherwise we're sensitive to first block
  111878. being short or long */
  111879. if(v->pcm_returned==-1){
  111880. v->pcm_returned=thisCenter;
  111881. v->pcm_current=thisCenter;
  111882. }else{
  111883. v->pcm_returned=prevCenter;
  111884. v->pcm_current=prevCenter+
  111885. ((ci->blocksizes[v->lW]/4+
  111886. ci->blocksizes[v->W]/4)>>hs);
  111887. }
  111888. }
  111889. /* track the frame number... This is for convenience, but also
  111890. making sure our last packet doesn't end with added padding. If
  111891. the last packet is partial, the number of samples we'll have to
  111892. return will be past the vb->granulepos.
  111893. This is not foolproof! It will be confused if we begin
  111894. decoding at the last page after a seek or hole. In that case,
  111895. we don't have a starting point to judge where the last frame
  111896. is. For this reason, vorbisfile will always try to make sure
  111897. it reads the last two marked pages in proper sequence */
  111898. if(b->sample_count==-1){
  111899. b->sample_count=0;
  111900. }else{
  111901. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111902. }
  111903. if(v->granulepos==-1){
  111904. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  111905. v->granulepos=vb->granulepos;
  111906. /* is this a short page? */
  111907. if(b->sample_count>v->granulepos){
  111908. /* corner case; if this is both the first and last audio page,
  111909. then spec says the end is cut, not beginning */
  111910. if(vb->eofflag){
  111911. /* trim the end */
  111912. /* no preceeding granulepos; assume we started at zero (we'd
  111913. have to in a short single-page stream) */
  111914. /* granulepos could be -1 due to a seek, but that would result
  111915. in a long count, not short count */
  111916. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  111917. }else{
  111918. /* trim the beginning */
  111919. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  111920. if(v->pcm_returned>v->pcm_current)
  111921. v->pcm_returned=v->pcm_current;
  111922. }
  111923. }
  111924. }
  111925. }else{
  111926. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  111927. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  111928. if(v->granulepos>vb->granulepos){
  111929. long extra=v->granulepos-vb->granulepos;
  111930. if(extra)
  111931. if(vb->eofflag){
  111932. /* partial last frame. Strip the extra samples off */
  111933. v->pcm_current-=extra>>hs;
  111934. } /* else {Shouldn't happen *unless* the bitstream is out of
  111935. spec. Either way, believe the bitstream } */
  111936. } /* else {Shouldn't happen *unless* the bitstream is out of
  111937. spec. Either way, believe the bitstream } */
  111938. v->granulepos=vb->granulepos;
  111939. }
  111940. }
  111941. /* Update, cleanup */
  111942. if(vb->eofflag)v->eofflag=1;
  111943. return(0);
  111944. }
  111945. /* pcm==NULL indicates we just want the pending samples, no more */
  111946. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  111947. vorbis_info *vi=v->vi;
  111948. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  111949. if(pcm){
  111950. int i;
  111951. for(i=0;i<vi->channels;i++)
  111952. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  111953. *pcm=v->pcmret;
  111954. }
  111955. return(v->pcm_current-v->pcm_returned);
  111956. }
  111957. return(0);
  111958. }
  111959. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  111960. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  111961. v->pcm_returned+=n;
  111962. return(0);
  111963. }
  111964. /* intended for use with a specific vorbisfile feature; we want access
  111965. to the [usually synthetic/postextrapolated] buffer and lapping at
  111966. the end of a decode cycle, specifically, a half-short-block worth.
  111967. This funtion works like pcmout above, except it will also expose
  111968. this implicit buffer data not normally decoded. */
  111969. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  111970. vorbis_info *vi=v->vi;
  111971. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  111972. int hs=ci->halfrate_flag;
  111973. int n=ci->blocksizes[v->W]>>(hs+1);
  111974. int n0=ci->blocksizes[0]>>(hs+1);
  111975. int n1=ci->blocksizes[1]>>(hs+1);
  111976. int i,j;
  111977. if(v->pcm_returned<0)return 0;
  111978. /* our returned data ends at pcm_returned; because the synthesis pcm
  111979. buffer is a two-fragment ring, that means our data block may be
  111980. fragmented by buffering, wrapping or a short block not filling
  111981. out a buffer. To simplify things, we unfragment if it's at all
  111982. possibly needed. Otherwise, we'd need to call lapout more than
  111983. once as well as hold additional dsp state. Opt for
  111984. simplicity. */
  111985. /* centerW was advanced by blockin; it would be the center of the
  111986. *next* block */
  111987. if(v->centerW==n1){
  111988. /* the data buffer wraps; swap the halves */
  111989. /* slow, sure, small */
  111990. for(j=0;j<vi->channels;j++){
  111991. float *p=v->pcm[j];
  111992. for(i=0;i<n1;i++){
  111993. float temp=p[i];
  111994. p[i]=p[i+n1];
  111995. p[i+n1]=temp;
  111996. }
  111997. }
  111998. v->pcm_current-=n1;
  111999. v->pcm_returned-=n1;
  112000. v->centerW=0;
  112001. }
  112002. /* solidify buffer into contiguous space */
  112003. if((v->lW^v->W)==1){
  112004. /* long/short or short/long */
  112005. for(j=0;j<vi->channels;j++){
  112006. float *s=v->pcm[j];
  112007. float *d=v->pcm[j]+(n1-n0)/2;
  112008. for(i=(n1+n0)/2-1;i>=0;--i)
  112009. d[i]=s[i];
  112010. }
  112011. v->pcm_returned+=(n1-n0)/2;
  112012. v->pcm_current+=(n1-n0)/2;
  112013. }else{
  112014. if(v->lW==0){
  112015. /* short/short */
  112016. for(j=0;j<vi->channels;j++){
  112017. float *s=v->pcm[j];
  112018. float *d=v->pcm[j]+n1-n0;
  112019. for(i=n0-1;i>=0;--i)
  112020. d[i]=s[i];
  112021. }
  112022. v->pcm_returned+=n1-n0;
  112023. v->pcm_current+=n1-n0;
  112024. }
  112025. }
  112026. if(pcm){
  112027. int i;
  112028. for(i=0;i<vi->channels;i++)
  112029. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  112030. *pcm=v->pcmret;
  112031. }
  112032. return(n1+n-v->pcm_returned);
  112033. }
  112034. float *vorbis_window(vorbis_dsp_state *v,int W){
  112035. vorbis_info *vi=v->vi;
  112036. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  112037. int hs=ci->halfrate_flag;
  112038. private_state *b=(private_state*)v->backend_state;
  112039. if(b->window[W]-1<0)return NULL;
  112040. return _vorbis_window_get(b->window[W]-hs);
  112041. }
  112042. #endif
  112043. /*** End of inlined file: block.c ***/
  112044. /*** Start of inlined file: codebook.c ***/
  112045. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112046. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112047. // tasks..
  112048. #if JUCE_MSVC
  112049. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112050. #endif
  112051. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112052. #if JUCE_USE_OGGVORBIS
  112053. #include <stdlib.h>
  112054. #include <string.h>
  112055. #include <math.h>
  112056. /* packs the given codebook into the bitstream **************************/
  112057. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  112058. long i,j;
  112059. int ordered=0;
  112060. /* first the basic parameters */
  112061. oggpack_write(opb,0x564342,24);
  112062. oggpack_write(opb,c->dim,16);
  112063. oggpack_write(opb,c->entries,24);
  112064. /* pack the codewords. There are two packings; length ordered and
  112065. length random. Decide between the two now. */
  112066. for(i=1;i<c->entries;i++)
  112067. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  112068. if(i==c->entries)ordered=1;
  112069. if(ordered){
  112070. /* length ordered. We only need to say how many codewords of
  112071. each length. The actual codewords are generated
  112072. deterministically */
  112073. long count=0;
  112074. oggpack_write(opb,1,1); /* ordered */
  112075. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  112076. for(i=1;i<c->entries;i++){
  112077. long thisx=c->lengthlist[i];
  112078. long last=c->lengthlist[i-1];
  112079. if(thisx>last){
  112080. for(j=last;j<thisx;j++){
  112081. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112082. count=i;
  112083. }
  112084. }
  112085. }
  112086. oggpack_write(opb,i-count,_ilog(c->entries-count));
  112087. }else{
  112088. /* length random. Again, we don't code the codeword itself, just
  112089. the length. This time, though, we have to encode each length */
  112090. oggpack_write(opb,0,1); /* unordered */
  112091. /* algortihmic mapping has use for 'unused entries', which we tag
  112092. here. The algorithmic mapping happens as usual, but the unused
  112093. entry has no codeword. */
  112094. for(i=0;i<c->entries;i++)
  112095. if(c->lengthlist[i]==0)break;
  112096. if(i==c->entries){
  112097. oggpack_write(opb,0,1); /* no unused entries */
  112098. for(i=0;i<c->entries;i++)
  112099. oggpack_write(opb,c->lengthlist[i]-1,5);
  112100. }else{
  112101. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  112102. for(i=0;i<c->entries;i++){
  112103. if(c->lengthlist[i]==0){
  112104. oggpack_write(opb,0,1);
  112105. }else{
  112106. oggpack_write(opb,1,1);
  112107. oggpack_write(opb,c->lengthlist[i]-1,5);
  112108. }
  112109. }
  112110. }
  112111. }
  112112. /* is the entry number the desired return value, or do we have a
  112113. mapping? If we have a mapping, what type? */
  112114. oggpack_write(opb,c->maptype,4);
  112115. switch(c->maptype){
  112116. case 0:
  112117. /* no mapping */
  112118. break;
  112119. case 1:case 2:
  112120. /* implicitly populated value mapping */
  112121. /* explicitly populated value mapping */
  112122. if(!c->quantlist){
  112123. /* no quantlist? error */
  112124. return(-1);
  112125. }
  112126. /* values that define the dequantization */
  112127. oggpack_write(opb,c->q_min,32);
  112128. oggpack_write(opb,c->q_delta,32);
  112129. oggpack_write(opb,c->q_quant-1,4);
  112130. oggpack_write(opb,c->q_sequencep,1);
  112131. {
  112132. int quantvals;
  112133. switch(c->maptype){
  112134. case 1:
  112135. /* a single column of (c->entries/c->dim) quantized values for
  112136. building a full value list algorithmically (square lattice) */
  112137. quantvals=_book_maptype1_quantvals(c);
  112138. break;
  112139. case 2:
  112140. /* every value (c->entries*c->dim total) specified explicitly */
  112141. quantvals=c->entries*c->dim;
  112142. break;
  112143. default: /* NOT_REACHABLE */
  112144. quantvals=-1;
  112145. }
  112146. /* quantized values */
  112147. for(i=0;i<quantvals;i++)
  112148. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  112149. }
  112150. break;
  112151. default:
  112152. /* error case; we don't have any other map types now */
  112153. return(-1);
  112154. }
  112155. return(0);
  112156. }
  112157. /* unpacks a codebook from the packet buffer into the codebook struct,
  112158. readies the codebook auxiliary structures for decode *************/
  112159. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  112160. long i,j;
  112161. memset(s,0,sizeof(*s));
  112162. s->allocedp=1;
  112163. /* make sure alignment is correct */
  112164. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  112165. /* first the basic parameters */
  112166. s->dim=oggpack_read(opb,16);
  112167. s->entries=oggpack_read(opb,24);
  112168. if(s->entries==-1)goto _eofout;
  112169. /* codeword ordering.... length ordered or unordered? */
  112170. switch((int)oggpack_read(opb,1)){
  112171. case 0:
  112172. /* unordered */
  112173. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112174. /* allocated but unused entries? */
  112175. if(oggpack_read(opb,1)){
  112176. /* yes, unused entries */
  112177. for(i=0;i<s->entries;i++){
  112178. if(oggpack_read(opb,1)){
  112179. long num=oggpack_read(opb,5);
  112180. if(num==-1)goto _eofout;
  112181. s->lengthlist[i]=num+1;
  112182. }else
  112183. s->lengthlist[i]=0;
  112184. }
  112185. }else{
  112186. /* all entries used; no tagging */
  112187. for(i=0;i<s->entries;i++){
  112188. long num=oggpack_read(opb,5);
  112189. if(num==-1)goto _eofout;
  112190. s->lengthlist[i]=num+1;
  112191. }
  112192. }
  112193. break;
  112194. case 1:
  112195. /* ordered */
  112196. {
  112197. long length=oggpack_read(opb,5)+1;
  112198. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  112199. for(i=0;i<s->entries;){
  112200. long num=oggpack_read(opb,_ilog(s->entries-i));
  112201. if(num==-1)goto _eofout;
  112202. for(j=0;j<num && i<s->entries;j++,i++)
  112203. s->lengthlist[i]=length;
  112204. length++;
  112205. }
  112206. }
  112207. break;
  112208. default:
  112209. /* EOF */
  112210. return(-1);
  112211. }
  112212. /* Do we have a mapping to unpack? */
  112213. switch((s->maptype=oggpack_read(opb,4))){
  112214. case 0:
  112215. /* no mapping */
  112216. break;
  112217. case 1: case 2:
  112218. /* implicitly populated value mapping */
  112219. /* explicitly populated value mapping */
  112220. s->q_min=oggpack_read(opb,32);
  112221. s->q_delta=oggpack_read(opb,32);
  112222. s->q_quant=oggpack_read(opb,4)+1;
  112223. s->q_sequencep=oggpack_read(opb,1);
  112224. {
  112225. int quantvals=0;
  112226. switch(s->maptype){
  112227. case 1:
  112228. quantvals=_book_maptype1_quantvals(s);
  112229. break;
  112230. case 2:
  112231. quantvals=s->entries*s->dim;
  112232. break;
  112233. }
  112234. /* quantized values */
  112235. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  112236. for(i=0;i<quantvals;i++)
  112237. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  112238. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  112239. }
  112240. break;
  112241. default:
  112242. goto _errout;
  112243. }
  112244. /* all set */
  112245. return(0);
  112246. _errout:
  112247. _eofout:
  112248. vorbis_staticbook_clear(s);
  112249. return(-1);
  112250. }
  112251. /* returns the number of bits ************************************************/
  112252. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  112253. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  112254. return(book->c->lengthlist[a]);
  112255. }
  112256. /* One the encode side, our vector writers are each designed for a
  112257. specific purpose, and the encoder is not flexible without modification:
  112258. The LSP vector coder uses a single stage nearest-match with no
  112259. interleave, so no step and no error return. This is specced by floor0
  112260. and doesn't change.
  112261. Residue0 encoding interleaves, uses multiple stages, and each stage
  112262. peels of a specific amount of resolution from a lattice (thus we want
  112263. to match by threshold, not nearest match). Residue doesn't *have* to
  112264. be encoded that way, but to change it, one will need to add more
  112265. infrastructure on the encode side (decode side is specced and simpler) */
  112266. /* floor0 LSP (single stage, non interleaved, nearest match) */
  112267. /* returns entry number and *modifies a* to the quantization value *****/
  112268. int vorbis_book_errorv(codebook *book,float *a){
  112269. int dim=book->dim,k;
  112270. int best=_best(book,a,1);
  112271. for(k=0;k<dim;k++)
  112272. a[k]=(book->valuelist+best*dim)[k];
  112273. return(best);
  112274. }
  112275. /* returns the number of bits and *modifies a* to the quantization value *****/
  112276. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  112277. int k,dim=book->dim;
  112278. for(k=0;k<dim;k++)
  112279. a[k]=(book->valuelist+best*dim)[k];
  112280. return(vorbis_book_encode(book,best,b));
  112281. }
  112282. /* the 'eliminate the decode tree' optimization actually requires the
  112283. codewords to be MSb first, not LSb. This is an annoying inelegancy
  112284. (and one of the first places where carefully thought out design
  112285. turned out to be wrong; Vorbis II and future Ogg codecs should go
  112286. to an MSb bitpacker), but not actually the huge hit it appears to
  112287. be. The first-stage decode table catches most words so that
  112288. bitreverse is not in the main execution path. */
  112289. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  112290. int read=book->dec_maxlength;
  112291. long lo,hi;
  112292. long lok = oggpack_look(b,book->dec_firsttablen);
  112293. if (lok >= 0) {
  112294. long entry = book->dec_firsttable[lok];
  112295. if(entry&0x80000000UL){
  112296. lo=(entry>>15)&0x7fff;
  112297. hi=book->used_entries-(entry&0x7fff);
  112298. }else{
  112299. oggpack_adv(b, book->dec_codelengths[entry-1]);
  112300. return(entry-1);
  112301. }
  112302. }else{
  112303. lo=0;
  112304. hi=book->used_entries;
  112305. }
  112306. lok = oggpack_look(b, read);
  112307. while(lok<0 && read>1)
  112308. lok = oggpack_look(b, --read);
  112309. if(lok<0)return -1;
  112310. /* bisect search for the codeword in the ordered list */
  112311. {
  112312. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  112313. while(hi-lo>1){
  112314. long p=(hi-lo)>>1;
  112315. long test=book->codelist[lo+p]>testword;
  112316. lo+=p&(test-1);
  112317. hi-=p&(-test);
  112318. }
  112319. if(book->dec_codelengths[lo]<=read){
  112320. oggpack_adv(b, book->dec_codelengths[lo]);
  112321. return(lo);
  112322. }
  112323. }
  112324. oggpack_adv(b, read);
  112325. return(-1);
  112326. }
  112327. /* Decode side is specced and easier, because we don't need to find
  112328. matches using different criteria; we simply read and map. There are
  112329. two things we need to do 'depending':
  112330. We may need to support interleave. We don't really, but it's
  112331. convenient to do it here rather than rebuild the vector later.
  112332. Cascades may be additive or multiplicitive; this is not inherent in
  112333. the codebook, but set in the code using the codebook. Like
  112334. interleaving, it's easiest to do it here.
  112335. addmul==0 -> declarative (set the value)
  112336. addmul==1 -> additive
  112337. addmul==2 -> multiplicitive */
  112338. /* returns the [original, not compacted] entry number or -1 on eof *********/
  112339. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  112340. long packed_entry=decode_packed_entry_number(book,b);
  112341. if(packed_entry>=0)
  112342. return(book->dec_index[packed_entry]);
  112343. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  112344. return(packed_entry);
  112345. }
  112346. /* returns 0 on OK or -1 on eof *************************************/
  112347. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112348. int step=n/book->dim;
  112349. long *entry = (long*)alloca(sizeof(*entry)*step);
  112350. float **t = (float**)alloca(sizeof(*t)*step);
  112351. int i,j,o;
  112352. for (i = 0; i < step; i++) {
  112353. entry[i]=decode_packed_entry_number(book,b);
  112354. if(entry[i]==-1)return(-1);
  112355. t[i] = book->valuelist+entry[i]*book->dim;
  112356. }
  112357. for(i=0,o=0;i<book->dim;i++,o+=step)
  112358. for (j=0;j<step;j++)
  112359. a[o+j]+=t[j][i];
  112360. return(0);
  112361. }
  112362. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  112363. int i,j,entry;
  112364. float *t;
  112365. if(book->dim>8){
  112366. for(i=0;i<n;){
  112367. entry = decode_packed_entry_number(book,b);
  112368. if(entry==-1)return(-1);
  112369. t = book->valuelist+entry*book->dim;
  112370. for (j=0;j<book->dim;)
  112371. a[i++]+=t[j++];
  112372. }
  112373. }else{
  112374. for(i=0;i<n;){
  112375. entry = decode_packed_entry_number(book,b);
  112376. if(entry==-1)return(-1);
  112377. t = book->valuelist+entry*book->dim;
  112378. j=0;
  112379. switch((int)book->dim){
  112380. case 8:
  112381. a[i++]+=t[j++];
  112382. case 7:
  112383. a[i++]+=t[j++];
  112384. case 6:
  112385. a[i++]+=t[j++];
  112386. case 5:
  112387. a[i++]+=t[j++];
  112388. case 4:
  112389. a[i++]+=t[j++];
  112390. case 3:
  112391. a[i++]+=t[j++];
  112392. case 2:
  112393. a[i++]+=t[j++];
  112394. case 1:
  112395. a[i++]+=t[j++];
  112396. case 0:
  112397. break;
  112398. }
  112399. }
  112400. }
  112401. return(0);
  112402. }
  112403. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  112404. int i,j,entry;
  112405. float *t;
  112406. for(i=0;i<n;){
  112407. entry = decode_packed_entry_number(book,b);
  112408. if(entry==-1)return(-1);
  112409. t = book->valuelist+entry*book->dim;
  112410. for (j=0;j<book->dim;)
  112411. a[i++]=t[j++];
  112412. }
  112413. return(0);
  112414. }
  112415. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  112416. oggpack_buffer *b,int n){
  112417. long i,j,entry;
  112418. int chptr=0;
  112419. for(i=offset/ch;i<(offset+n)/ch;){
  112420. entry = decode_packed_entry_number(book,b);
  112421. if(entry==-1)return(-1);
  112422. {
  112423. const float *t = book->valuelist+entry*book->dim;
  112424. for (j=0;j<book->dim;j++){
  112425. a[chptr++][i]+=t[j];
  112426. if(chptr==ch){
  112427. chptr=0;
  112428. i++;
  112429. }
  112430. }
  112431. }
  112432. }
  112433. return(0);
  112434. }
  112435. #ifdef _V_SELFTEST
  112436. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  112437. number of vectors through (keeping track of the quantized values),
  112438. and decode using the unpacked book. quantized version of in should
  112439. exactly equal out */
  112440. #include <stdio.h>
  112441. #include "vorbis/book/lsp20_0.vqh"
  112442. #include "vorbis/book/res0a_13.vqh"
  112443. #define TESTSIZE 40
  112444. float test1[TESTSIZE]={
  112445. 0.105939f,
  112446. 0.215373f,
  112447. 0.429117f,
  112448. 0.587974f,
  112449. 0.181173f,
  112450. 0.296583f,
  112451. 0.515707f,
  112452. 0.715261f,
  112453. 0.162327f,
  112454. 0.263834f,
  112455. 0.342876f,
  112456. 0.406025f,
  112457. 0.103571f,
  112458. 0.223561f,
  112459. 0.368513f,
  112460. 0.540313f,
  112461. 0.136672f,
  112462. 0.395882f,
  112463. 0.587183f,
  112464. 0.652476f,
  112465. 0.114338f,
  112466. 0.417300f,
  112467. 0.525486f,
  112468. 0.698679f,
  112469. 0.147492f,
  112470. 0.324481f,
  112471. 0.643089f,
  112472. 0.757582f,
  112473. 0.139556f,
  112474. 0.215795f,
  112475. 0.324559f,
  112476. 0.399387f,
  112477. 0.120236f,
  112478. 0.267420f,
  112479. 0.446940f,
  112480. 0.608760f,
  112481. 0.115587f,
  112482. 0.287234f,
  112483. 0.571081f,
  112484. 0.708603f,
  112485. };
  112486. float test3[TESTSIZE]={
  112487. 0,1,-2,3,4,-5,6,7,8,9,
  112488. 8,-2,7,-1,4,6,8,3,1,-9,
  112489. 10,11,12,13,14,15,26,17,18,19,
  112490. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  112491. static_codebook *testlist[]={&_vq_book_lsp20_0,
  112492. &_vq_book_res0a_13,NULL};
  112493. float *testvec[]={test1,test3};
  112494. int main(){
  112495. oggpack_buffer write;
  112496. oggpack_buffer read;
  112497. long ptr=0,i;
  112498. oggpack_writeinit(&write);
  112499. fprintf(stderr,"Testing codebook abstraction...:\n");
  112500. while(testlist[ptr]){
  112501. codebook c;
  112502. static_codebook s;
  112503. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  112504. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  112505. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  112506. memset(iv,0,sizeof(*iv)*TESTSIZE);
  112507. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  112508. /* pack the codebook, write the testvector */
  112509. oggpack_reset(&write);
  112510. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  112511. we can write */
  112512. vorbis_staticbook_pack(testlist[ptr],&write);
  112513. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  112514. for(i=0;i<TESTSIZE;i+=c.dim){
  112515. int best=_best(&c,qv+i,1);
  112516. vorbis_book_encodev(&c,best,qv+i,&write);
  112517. }
  112518. vorbis_book_clear(&c);
  112519. fprintf(stderr,"OK.\n");
  112520. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  112521. /* transfer the write data to a read buffer and unpack/read */
  112522. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  112523. if(vorbis_staticbook_unpack(&read,&s)){
  112524. fprintf(stderr,"Error unpacking codebook.\n");
  112525. exit(1);
  112526. }
  112527. if(vorbis_book_init_decode(&c,&s)){
  112528. fprintf(stderr,"Error initializing codebook.\n");
  112529. exit(1);
  112530. }
  112531. for(i=0;i<TESTSIZE;i+=c.dim)
  112532. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  112533. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  112534. exit(1);
  112535. }
  112536. for(i=0;i<TESTSIZE;i++)
  112537. if(fabs(qv[i]-iv[i])>.000001){
  112538. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  112539. iv[i],qv[i],i);
  112540. exit(1);
  112541. }
  112542. fprintf(stderr,"OK\n");
  112543. ptr++;
  112544. }
  112545. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  112546. exit(0);
  112547. }
  112548. #endif
  112549. #endif
  112550. /*** End of inlined file: codebook.c ***/
  112551. /*** Start of inlined file: envelope.c ***/
  112552. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112553. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112554. // tasks..
  112555. #if JUCE_MSVC
  112556. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112557. #endif
  112558. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112559. #if JUCE_USE_OGGVORBIS
  112560. #include <stdlib.h>
  112561. #include <string.h>
  112562. #include <stdio.h>
  112563. #include <math.h>
  112564. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  112565. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112566. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112567. int ch=vi->channels;
  112568. int i,j;
  112569. int n=e->winlength=128;
  112570. e->searchstep=64; /* not random */
  112571. e->minenergy=gi->preecho_minenergy;
  112572. e->ch=ch;
  112573. e->storage=128;
  112574. e->cursor=ci->blocksizes[1]/2;
  112575. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  112576. mdct_init(&e->mdct,n);
  112577. for(i=0;i<n;i++){
  112578. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  112579. e->mdct_win[i]*=e->mdct_win[i];
  112580. }
  112581. /* magic follows */
  112582. e->band[0].begin=2; e->band[0].end=4;
  112583. e->band[1].begin=4; e->band[1].end=5;
  112584. e->band[2].begin=6; e->band[2].end=6;
  112585. e->band[3].begin=9; e->band[3].end=8;
  112586. e->band[4].begin=13; e->band[4].end=8;
  112587. e->band[5].begin=17; e->band[5].end=8;
  112588. e->band[6].begin=22; e->band[6].end=8;
  112589. for(j=0;j<VE_BANDS;j++){
  112590. n=e->band[j].end;
  112591. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  112592. for(i=0;i<n;i++){
  112593. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  112594. e->band[j].total+=e->band[j].window[i];
  112595. }
  112596. e->band[j].total=1./e->band[j].total;
  112597. }
  112598. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  112599. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  112600. }
  112601. void _ve_envelope_clear(envelope_lookup *e){
  112602. int i;
  112603. mdct_clear(&e->mdct);
  112604. for(i=0;i<VE_BANDS;i++)
  112605. _ogg_free(e->band[i].window);
  112606. _ogg_free(e->mdct_win);
  112607. _ogg_free(e->filter);
  112608. _ogg_free(e->mark);
  112609. memset(e,0,sizeof(*e));
  112610. }
  112611. /* fairly straight threshhold-by-band based until we find something
  112612. that works better and isn't patented. */
  112613. static int _ve_amp(envelope_lookup *ve,
  112614. vorbis_info_psy_global *gi,
  112615. float *data,
  112616. envelope_band *bands,
  112617. envelope_filter_state *filters,
  112618. long pos){
  112619. long n=ve->winlength;
  112620. int ret=0;
  112621. long i,j;
  112622. float decay;
  112623. /* we want to have a 'minimum bar' for energy, else we're just
  112624. basing blocks on quantization noise that outweighs the signal
  112625. itself (for low power signals) */
  112626. float minV=ve->minenergy;
  112627. float *vec=(float*) alloca(n*sizeof(*vec));
  112628. /* stretch is used to gradually lengthen the number of windows
  112629. considered prevoius-to-potential-trigger */
  112630. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  112631. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  112632. if(penalty<0.f)penalty=0.f;
  112633. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  112634. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  112635. totalshift+pos*ve->searchstep);*/
  112636. /* window and transform */
  112637. for(i=0;i<n;i++)
  112638. vec[i]=data[i]*ve->mdct_win[i];
  112639. mdct_forward(&ve->mdct,vec,vec);
  112640. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  112641. /* near-DC spreading function; this has nothing to do with
  112642. psychoacoustics, just sidelobe leakage and window size */
  112643. {
  112644. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  112645. int ptr=filters->nearptr;
  112646. /* the accumulation is regularly refreshed from scratch to avoid
  112647. floating point creep */
  112648. if(ptr==0){
  112649. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  112650. filters->nearDC_partialacc=temp;
  112651. }else{
  112652. decay=filters->nearDC_acc+=temp;
  112653. filters->nearDC_partialacc+=temp;
  112654. }
  112655. filters->nearDC_acc-=filters->nearDC[ptr];
  112656. filters->nearDC[ptr]=temp;
  112657. decay*=(1./(VE_NEARDC+1));
  112658. filters->nearptr++;
  112659. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  112660. decay=todB(&decay)*.5-15.f;
  112661. }
  112662. /* perform spreading and limiting, also smooth the spectrum. yes,
  112663. the MDCT results in all real coefficients, but it still *behaves*
  112664. like real/imaginary pairs */
  112665. for(i=0;i<n/2;i+=2){
  112666. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  112667. val=todB(&val)*.5f;
  112668. if(val<decay)val=decay;
  112669. if(val<minV)val=minV;
  112670. vec[i>>1]=val;
  112671. decay-=8.;
  112672. }
  112673. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  112674. /* perform preecho/postecho triggering by band */
  112675. for(j=0;j<VE_BANDS;j++){
  112676. float acc=0.;
  112677. float valmax,valmin;
  112678. /* accumulate amplitude */
  112679. for(i=0;i<bands[j].end;i++)
  112680. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  112681. acc*=bands[j].total;
  112682. /* convert amplitude to delta */
  112683. {
  112684. int p,thisx=filters[j].ampptr;
  112685. float postmax,postmin,premax=-99999.f,premin=99999.f;
  112686. p=thisx;
  112687. p--;
  112688. if(p<0)p+=VE_AMP;
  112689. postmax=max(acc,filters[j].ampbuf[p]);
  112690. postmin=min(acc,filters[j].ampbuf[p]);
  112691. for(i=0;i<stretch;i++){
  112692. p--;
  112693. if(p<0)p+=VE_AMP;
  112694. premax=max(premax,filters[j].ampbuf[p]);
  112695. premin=min(premin,filters[j].ampbuf[p]);
  112696. }
  112697. valmin=postmin-premin;
  112698. valmax=postmax-premax;
  112699. /*filters[j].markers[pos]=valmax;*/
  112700. filters[j].ampbuf[thisx]=acc;
  112701. filters[j].ampptr++;
  112702. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  112703. }
  112704. /* look at min/max, decide trigger */
  112705. if(valmax>gi->preecho_thresh[j]+penalty){
  112706. ret|=1;
  112707. ret|=4;
  112708. }
  112709. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  112710. }
  112711. return(ret);
  112712. }
  112713. #if 0
  112714. static int seq=0;
  112715. static ogg_int64_t totalshift=-1024;
  112716. #endif
  112717. long _ve_envelope_search(vorbis_dsp_state *v){
  112718. vorbis_info *vi=v->vi;
  112719. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  112720. vorbis_info_psy_global *gi=&ci->psy_g_param;
  112721. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112722. long i,j;
  112723. int first=ve->current/ve->searchstep;
  112724. int last=v->pcm_current/ve->searchstep-VE_WIN;
  112725. if(first<0)first=0;
  112726. /* make sure we have enough storage to match the PCM */
  112727. if(last+VE_WIN+VE_POST>ve->storage){
  112728. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  112729. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  112730. }
  112731. for(j=first;j<last;j++){
  112732. int ret=0;
  112733. ve->stretch++;
  112734. if(ve->stretch>VE_MAXSTRETCH*2)
  112735. ve->stretch=VE_MAXSTRETCH*2;
  112736. for(i=0;i<ve->ch;i++){
  112737. float *pcm=v->pcm[i]+ve->searchstep*(j);
  112738. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  112739. }
  112740. ve->mark[j+VE_POST]=0;
  112741. if(ret&1){
  112742. ve->mark[j]=1;
  112743. ve->mark[j+1]=1;
  112744. }
  112745. if(ret&2){
  112746. ve->mark[j]=1;
  112747. if(j>0)ve->mark[j-1]=1;
  112748. }
  112749. if(ret&4)ve->stretch=-1;
  112750. }
  112751. ve->current=last*ve->searchstep;
  112752. {
  112753. long centerW=v->centerW;
  112754. long testW=
  112755. centerW+
  112756. ci->blocksizes[v->W]/4+
  112757. ci->blocksizes[1]/2+
  112758. ci->blocksizes[0]/4;
  112759. j=ve->cursor;
  112760. while(j<ve->current-(ve->searchstep)){/* account for postecho
  112761. working back one window */
  112762. if(j>=testW)return(1);
  112763. ve->cursor=j;
  112764. if(ve->mark[j/ve->searchstep]){
  112765. if(j>centerW){
  112766. #if 0
  112767. if(j>ve->curmark){
  112768. float *marker=alloca(v->pcm_current*sizeof(*marker));
  112769. int l,m;
  112770. memset(marker,0,sizeof(*marker)*v->pcm_current);
  112771. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  112772. seq,
  112773. (totalshift+ve->cursor)/44100.,
  112774. (totalshift+j)/44100.);
  112775. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  112776. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  112777. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  112778. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  112779. for(m=0;m<VE_BANDS;m++){
  112780. char buf[80];
  112781. sprintf(buf,"delL%d",m);
  112782. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  112783. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112784. }
  112785. for(m=0;m<VE_BANDS;m++){
  112786. char buf[80];
  112787. sprintf(buf,"delR%d",m);
  112788. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  112789. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  112790. }
  112791. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  112792. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  112793. seq++;
  112794. }
  112795. #endif
  112796. ve->curmark=j;
  112797. if(j>=testW)return(1);
  112798. return(0);
  112799. }
  112800. }
  112801. j+=ve->searchstep;
  112802. }
  112803. }
  112804. return(-1);
  112805. }
  112806. int _ve_envelope_mark(vorbis_dsp_state *v){
  112807. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  112808. vorbis_info *vi=v->vi;
  112809. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112810. long centerW=v->centerW;
  112811. long beginW=centerW-ci->blocksizes[v->W]/4;
  112812. long endW=centerW+ci->blocksizes[v->W]/4;
  112813. if(v->W){
  112814. beginW-=ci->blocksizes[v->lW]/4;
  112815. endW+=ci->blocksizes[v->nW]/4;
  112816. }else{
  112817. beginW-=ci->blocksizes[0]/4;
  112818. endW+=ci->blocksizes[0]/4;
  112819. }
  112820. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  112821. {
  112822. long first=beginW/ve->searchstep;
  112823. long last=endW/ve->searchstep;
  112824. long i;
  112825. for(i=first;i<last;i++)
  112826. if(ve->mark[i])return(1);
  112827. }
  112828. return(0);
  112829. }
  112830. void _ve_envelope_shift(envelope_lookup *e,long shift){
  112831. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  112832. ahead of ve->current */
  112833. int smallshift=shift/e->searchstep;
  112834. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  112835. #if 0
  112836. for(i=0;i<VE_BANDS*e->ch;i++)
  112837. memmove(e->filter[i].markers,
  112838. e->filter[i].markers+smallshift,
  112839. (1024-smallshift)*sizeof(*(*e->filter).markers));
  112840. totalshift+=shift;
  112841. #endif
  112842. e->current-=shift;
  112843. if(e->curmark>=0)
  112844. e->curmark-=shift;
  112845. e->cursor-=shift;
  112846. }
  112847. #endif
  112848. /*** End of inlined file: envelope.c ***/
  112849. /*** Start of inlined file: floor0.c ***/
  112850. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  112851. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112852. // tasks..
  112853. #if JUCE_MSVC
  112854. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112855. #endif
  112856. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  112857. #if JUCE_USE_OGGVORBIS
  112858. #include <stdlib.h>
  112859. #include <string.h>
  112860. #include <math.h>
  112861. /*** Start of inlined file: lsp.h ***/
  112862. #ifndef _V_LSP_H_
  112863. #define _V_LSP_H_
  112864. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  112865. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  112866. float *lsp,int m,
  112867. float amp,float ampoffset);
  112868. #endif
  112869. /*** End of inlined file: lsp.h ***/
  112870. #include <stdio.h>
  112871. typedef struct {
  112872. int ln;
  112873. int m;
  112874. int **linearmap;
  112875. int n[2];
  112876. vorbis_info_floor0 *vi;
  112877. long bits;
  112878. long frames;
  112879. } vorbis_look_floor0;
  112880. /***********************************************/
  112881. static void floor0_free_info(vorbis_info_floor *i){
  112882. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  112883. if(info){
  112884. memset(info,0,sizeof(*info));
  112885. _ogg_free(info);
  112886. }
  112887. }
  112888. static void floor0_free_look(vorbis_look_floor *i){
  112889. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112890. if(look){
  112891. if(look->linearmap){
  112892. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  112893. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  112894. _ogg_free(look->linearmap);
  112895. }
  112896. memset(look,0,sizeof(*look));
  112897. _ogg_free(look);
  112898. }
  112899. }
  112900. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  112901. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112902. int j;
  112903. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  112904. info->order=oggpack_read(opb,8);
  112905. info->rate=oggpack_read(opb,16);
  112906. info->barkmap=oggpack_read(opb,16);
  112907. info->ampbits=oggpack_read(opb,6);
  112908. info->ampdB=oggpack_read(opb,8);
  112909. info->numbooks=oggpack_read(opb,4)+1;
  112910. if(info->order<1)goto err_out;
  112911. if(info->rate<1)goto err_out;
  112912. if(info->barkmap<1)goto err_out;
  112913. if(info->numbooks<1)goto err_out;
  112914. for(j=0;j<info->numbooks;j++){
  112915. info->books[j]=oggpack_read(opb,8);
  112916. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  112917. }
  112918. return(info);
  112919. err_out:
  112920. floor0_free_info(info);
  112921. return(NULL);
  112922. }
  112923. /* initialize Bark scale and normalization lookups. We could do this
  112924. with static tables, but Vorbis allows a number of possible
  112925. combinations, so it's best to do it computationally.
  112926. The below is authoritative in terms of defining scale mapping.
  112927. Note that the scale depends on the sampling rate as well as the
  112928. linear block and mapping sizes */
  112929. static void floor0_map_lazy_init(vorbis_block *vb,
  112930. vorbis_info_floor *infoX,
  112931. vorbis_look_floor0 *look){
  112932. if(!look->linearmap[vb->W]){
  112933. vorbis_dsp_state *vd=vb->vd;
  112934. vorbis_info *vi=vd->vi;
  112935. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112936. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  112937. int W=vb->W;
  112938. int n=ci->blocksizes[W]/2,j;
  112939. /* we choose a scaling constant so that:
  112940. floor(bark(rate/2-1)*C)=mapped-1
  112941. floor(bark(rate/2)*C)=mapped */
  112942. float scale=look->ln/toBARK(info->rate/2.f);
  112943. /* the mapping from a linear scale to a smaller bark scale is
  112944. straightforward. We do *not* make sure that the linear mapping
  112945. does not skip bark-scale bins; the decoder simply skips them and
  112946. the encoder may do what it wishes in filling them. They're
  112947. necessary in some mapping combinations to keep the scale spacing
  112948. accurate */
  112949. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  112950. for(j=0;j<n;j++){
  112951. int val=floor( toBARK((info->rate/2.f)/n*j)
  112952. *scale); /* bark numbers represent band edges */
  112953. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  112954. look->linearmap[W][j]=val;
  112955. }
  112956. look->linearmap[W][j]=-1;
  112957. look->n[W]=n;
  112958. }
  112959. }
  112960. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  112961. vorbis_info_floor *i){
  112962. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  112963. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  112964. look->m=info->order;
  112965. look->ln=info->barkmap;
  112966. look->vi=info;
  112967. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  112968. return look;
  112969. }
  112970. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  112971. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  112972. vorbis_info_floor0 *info=look->vi;
  112973. int j,k;
  112974. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  112975. if(ampraw>0){ /* also handles the -1 out of data case */
  112976. long maxval=(1<<info->ampbits)-1;
  112977. float amp=(float)ampraw/maxval*info->ampdB;
  112978. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  112979. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  112980. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  112981. codebook *b=ci->fullbooks+info->books[booknum];
  112982. float last=0.f;
  112983. /* the additional b->dim is a guard against any possible stack
  112984. smash; b->dim is provably more than we can overflow the
  112985. vector */
  112986. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  112987. for(j=0;j<look->m;j+=b->dim)
  112988. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  112989. for(j=0;j<look->m;){
  112990. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  112991. last=lsp[j-1];
  112992. }
  112993. lsp[look->m]=amp;
  112994. return(lsp);
  112995. }
  112996. }
  112997. eop:
  112998. return(NULL);
  112999. }
  113000. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  113001. void *memo,float *out){
  113002. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  113003. vorbis_info_floor0 *info=look->vi;
  113004. floor0_map_lazy_init(vb,info,look);
  113005. if(memo){
  113006. float *lsp=(float *)memo;
  113007. float amp=lsp[look->m];
  113008. /* take the coefficients back to a spectral envelope curve */
  113009. vorbis_lsp_to_curve(out,
  113010. look->linearmap[vb->W],
  113011. look->n[vb->W],
  113012. look->ln,
  113013. lsp,look->m,amp,(float)info->ampdB);
  113014. return(1);
  113015. }
  113016. memset(out,0,sizeof(*out)*look->n[vb->W]);
  113017. return(0);
  113018. }
  113019. /* export hooks */
  113020. vorbis_func_floor floor0_exportbundle={
  113021. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  113022. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  113023. };
  113024. #endif
  113025. /*** End of inlined file: floor0.c ***/
  113026. /*** Start of inlined file: floor1.c ***/
  113027. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113028. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113029. // tasks..
  113030. #if JUCE_MSVC
  113031. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113032. #endif
  113033. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113034. #if JUCE_USE_OGGVORBIS
  113035. #include <stdlib.h>
  113036. #include <string.h>
  113037. #include <math.h>
  113038. #include <stdio.h>
  113039. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  113040. typedef struct {
  113041. int sorted_index[VIF_POSIT+2];
  113042. int forward_index[VIF_POSIT+2];
  113043. int reverse_index[VIF_POSIT+2];
  113044. int hineighbor[VIF_POSIT];
  113045. int loneighbor[VIF_POSIT];
  113046. int posts;
  113047. int n;
  113048. int quant_q;
  113049. vorbis_info_floor1 *vi;
  113050. long phrasebits;
  113051. long postbits;
  113052. long frames;
  113053. } vorbis_look_floor1;
  113054. typedef struct lsfit_acc{
  113055. long x0;
  113056. long x1;
  113057. long xa;
  113058. long ya;
  113059. long x2a;
  113060. long y2a;
  113061. long xya;
  113062. long an;
  113063. } lsfit_acc;
  113064. /***********************************************/
  113065. static void floor1_free_info(vorbis_info_floor *i){
  113066. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113067. if(info){
  113068. memset(info,0,sizeof(*info));
  113069. _ogg_free(info);
  113070. }
  113071. }
  113072. static void floor1_free_look(vorbis_look_floor *i){
  113073. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  113074. if(look){
  113075. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  113076. (float)look->phrasebits/look->frames,
  113077. (float)look->postbits/look->frames,
  113078. (float)(look->postbits+look->phrasebits)/look->frames);*/
  113079. memset(look,0,sizeof(*look));
  113080. _ogg_free(look);
  113081. }
  113082. }
  113083. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  113084. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  113085. int j,k;
  113086. int count=0;
  113087. int rangebits;
  113088. int maxposit=info->postlist[1];
  113089. int maxclass=-1;
  113090. /* save out partitions */
  113091. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  113092. for(j=0;j<info->partitions;j++){
  113093. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  113094. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113095. }
  113096. /* save out partition classes */
  113097. for(j=0;j<maxclass+1;j++){
  113098. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  113099. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  113100. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  113101. for(k=0;k<(1<<info->class_subs[j]);k++)
  113102. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  113103. }
  113104. /* save out the post list */
  113105. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  113106. oggpack_write(opb,ilog2(maxposit),4);
  113107. rangebits=ilog2(maxposit);
  113108. for(j=0,k=0;j<info->partitions;j++){
  113109. count+=info->class_dim[info->partitionclass[j]];
  113110. for(;k<count;k++)
  113111. oggpack_write(opb,info->postlist[k+2],rangebits);
  113112. }
  113113. }
  113114. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  113115. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  113116. int j,k,count=0,maxclass=-1,rangebits;
  113117. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  113118. /* read partitions */
  113119. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  113120. for(j=0;j<info->partitions;j++){
  113121. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  113122. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  113123. }
  113124. /* read partition classes */
  113125. for(j=0;j<maxclass+1;j++){
  113126. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  113127. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  113128. if(info->class_subs[j]<0)
  113129. goto err_out;
  113130. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  113131. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  113132. goto err_out;
  113133. for(k=0;k<(1<<info->class_subs[j]);k++){
  113134. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  113135. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  113136. goto err_out;
  113137. }
  113138. }
  113139. /* read the post list */
  113140. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  113141. rangebits=oggpack_read(opb,4);
  113142. for(j=0,k=0;j<info->partitions;j++){
  113143. count+=info->class_dim[info->partitionclass[j]];
  113144. for(;k<count;k++){
  113145. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  113146. if(t<0 || t>=(1<<rangebits))
  113147. goto err_out;
  113148. }
  113149. }
  113150. info->postlist[0]=0;
  113151. info->postlist[1]=1<<rangebits;
  113152. return(info);
  113153. err_out:
  113154. floor1_free_info(info);
  113155. return(NULL);
  113156. }
  113157. static int JUCE_CDECL icomp(const void *a,const void *b){
  113158. return(**(int **)a-**(int **)b);
  113159. }
  113160. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  113161. vorbis_info_floor *in){
  113162. int *sortpointer[VIF_POSIT+2];
  113163. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  113164. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  113165. int i,j,n=0;
  113166. look->vi=info;
  113167. look->n=info->postlist[1];
  113168. /* we drop each position value in-between already decoded values,
  113169. and use linear interpolation to predict each new value past the
  113170. edges. The positions are read in the order of the position
  113171. list... we precompute the bounding positions in the lookup. Of
  113172. course, the neighbors can change (if a position is declined), but
  113173. this is an initial mapping */
  113174. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  113175. n+=2;
  113176. look->posts=n;
  113177. /* also store a sorted position index */
  113178. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  113179. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  113180. /* points from sort order back to range number */
  113181. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  113182. /* points from range order to sorted position */
  113183. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  113184. /* we actually need the post values too */
  113185. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  113186. /* quantize values to multiplier spec */
  113187. switch(info->mult){
  113188. case 1: /* 1024 -> 256 */
  113189. look->quant_q=256;
  113190. break;
  113191. case 2: /* 1024 -> 128 */
  113192. look->quant_q=128;
  113193. break;
  113194. case 3: /* 1024 -> 86 */
  113195. look->quant_q=86;
  113196. break;
  113197. case 4: /* 1024 -> 64 */
  113198. look->quant_q=64;
  113199. break;
  113200. }
  113201. /* discover our neighbors for decode where we don't use fit flags
  113202. (that would push the neighbors outward) */
  113203. for(i=0;i<n-2;i++){
  113204. int lo=0;
  113205. int hi=1;
  113206. int lx=0;
  113207. int hx=look->n;
  113208. int currentx=info->postlist[i+2];
  113209. for(j=0;j<i+2;j++){
  113210. int x=info->postlist[j];
  113211. if(x>lx && x<currentx){
  113212. lo=j;
  113213. lx=x;
  113214. }
  113215. if(x<hx && x>currentx){
  113216. hi=j;
  113217. hx=x;
  113218. }
  113219. }
  113220. look->loneighbor[i]=lo;
  113221. look->hineighbor[i]=hi;
  113222. }
  113223. return(look);
  113224. }
  113225. static int render_point(int x0,int x1,int y0,int y1,int x){
  113226. y0&=0x7fff; /* mask off flag */
  113227. y1&=0x7fff;
  113228. {
  113229. int dy=y1-y0;
  113230. int adx=x1-x0;
  113231. int ady=abs(dy);
  113232. int err=ady*(x-x0);
  113233. int off=err/adx;
  113234. if(dy<0)return(y0-off);
  113235. return(y0+off);
  113236. }
  113237. }
  113238. static int vorbis_dBquant(const float *x){
  113239. int i= *x*7.3142857f+1023.5f;
  113240. if(i>1023)return(1023);
  113241. if(i<0)return(0);
  113242. return i;
  113243. }
  113244. static float FLOOR1_fromdB_LOOKUP[256]={
  113245. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  113246. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  113247. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  113248. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  113249. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  113250. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  113251. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  113252. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  113253. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  113254. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  113255. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  113256. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  113257. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  113258. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  113259. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  113260. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  113261. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  113262. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  113263. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  113264. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  113265. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  113266. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  113267. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  113268. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  113269. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  113270. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  113271. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  113272. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  113273. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  113274. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  113275. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  113276. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  113277. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  113278. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  113279. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  113280. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  113281. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  113282. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  113283. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  113284. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  113285. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  113286. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  113287. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  113288. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  113289. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  113290. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  113291. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  113292. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  113293. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  113294. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  113295. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  113296. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  113297. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  113298. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  113299. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  113300. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  113301. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  113302. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  113303. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  113304. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  113305. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  113306. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  113307. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  113308. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  113309. };
  113310. static void render_line(int x0,int x1,int y0,int y1,float *d){
  113311. int dy=y1-y0;
  113312. int adx=x1-x0;
  113313. int ady=abs(dy);
  113314. int base=dy/adx;
  113315. int sy=(dy<0?base-1:base+1);
  113316. int x=x0;
  113317. int y=y0;
  113318. int err=0;
  113319. ady-=abs(base*adx);
  113320. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113321. while(++x<x1){
  113322. err=err+ady;
  113323. if(err>=adx){
  113324. err-=adx;
  113325. y+=sy;
  113326. }else{
  113327. y+=base;
  113328. }
  113329. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  113330. }
  113331. }
  113332. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  113333. int dy=y1-y0;
  113334. int adx=x1-x0;
  113335. int ady=abs(dy);
  113336. int base=dy/adx;
  113337. int sy=(dy<0?base-1:base+1);
  113338. int x=x0;
  113339. int y=y0;
  113340. int err=0;
  113341. ady-=abs(base*adx);
  113342. d[x]=y;
  113343. while(++x<x1){
  113344. err=err+ady;
  113345. if(err>=adx){
  113346. err-=adx;
  113347. y+=sy;
  113348. }else{
  113349. y+=base;
  113350. }
  113351. d[x]=y;
  113352. }
  113353. }
  113354. /* the floor has already been filtered to only include relevant sections */
  113355. static int accumulate_fit(const float *flr,const float *mdct,
  113356. int x0, int x1,lsfit_acc *a,
  113357. int n,vorbis_info_floor1 *info){
  113358. long i;
  113359. 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;
  113360. memset(a,0,sizeof(*a));
  113361. a->x0=x0;
  113362. a->x1=x1;
  113363. if(x1>=n)x1=n-1;
  113364. for(i=x0;i<=x1;i++){
  113365. int quantized=vorbis_dBquant(flr+i);
  113366. if(quantized){
  113367. if(mdct[i]+info->twofitatten>=flr[i]){
  113368. xa += i;
  113369. ya += quantized;
  113370. x2a += i*i;
  113371. y2a += quantized*quantized;
  113372. xya += i*quantized;
  113373. na++;
  113374. }else{
  113375. xb += i;
  113376. yb += quantized;
  113377. x2b += i*i;
  113378. y2b += quantized*quantized;
  113379. xyb += i*quantized;
  113380. nb++;
  113381. }
  113382. }
  113383. }
  113384. xb+=xa;
  113385. yb+=ya;
  113386. x2b+=x2a;
  113387. y2b+=y2a;
  113388. xyb+=xya;
  113389. nb+=na;
  113390. /* weight toward the actually used frequencies if we meet the threshhold */
  113391. {
  113392. int weight=nb*info->twofitweight/(na+1);
  113393. a->xa=xa*weight+xb;
  113394. a->ya=ya*weight+yb;
  113395. a->x2a=x2a*weight+x2b;
  113396. a->y2a=y2a*weight+y2b;
  113397. a->xya=xya*weight+xyb;
  113398. a->an=na*weight+nb;
  113399. }
  113400. return(na);
  113401. }
  113402. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  113403. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  113404. long x0=a[0].x0;
  113405. long x1=a[fits-1].x1;
  113406. for(i=0;i<fits;i++){
  113407. x+=a[i].xa;
  113408. y+=a[i].ya;
  113409. x2+=a[i].x2a;
  113410. y2+=a[i].y2a;
  113411. xy+=a[i].xya;
  113412. an+=a[i].an;
  113413. }
  113414. if(*y0>=0){
  113415. x+= x0;
  113416. y+= *y0;
  113417. x2+= x0 * x0;
  113418. y2+= *y0 * *y0;
  113419. xy+= *y0 * x0;
  113420. an++;
  113421. }
  113422. if(*y1>=0){
  113423. x+= x1;
  113424. y+= *y1;
  113425. x2+= x1 * x1;
  113426. y2+= *y1 * *y1;
  113427. xy+= *y1 * x1;
  113428. an++;
  113429. }
  113430. if(an){
  113431. /* need 64 bit multiplies, which C doesn't give portably as int */
  113432. double fx=x;
  113433. double fy=y;
  113434. double fx2=x2;
  113435. double fxy=xy;
  113436. double denom=1./(an*fx2-fx*fx);
  113437. double a=(fy*fx2-fxy*fx)*denom;
  113438. double b=(an*fxy-fx*fy)*denom;
  113439. *y0=rint(a+b*x0);
  113440. *y1=rint(a+b*x1);
  113441. /* limit to our range! */
  113442. if(*y0>1023)*y0=1023;
  113443. if(*y1>1023)*y1=1023;
  113444. if(*y0<0)*y0=0;
  113445. if(*y1<0)*y1=0;
  113446. }else{
  113447. *y0=0;
  113448. *y1=0;
  113449. }
  113450. }
  113451. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  113452. long y=0;
  113453. int i;
  113454. for(i=0;i<fits && y==0;i++)
  113455. y+=a[i].ya;
  113456. *y0=*y1=y;
  113457. }*/
  113458. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  113459. const float *mdct,
  113460. vorbis_info_floor1 *info){
  113461. int dy=y1-y0;
  113462. int adx=x1-x0;
  113463. int ady=abs(dy);
  113464. int base=dy/adx;
  113465. int sy=(dy<0?base-1:base+1);
  113466. int x=x0;
  113467. int y=y0;
  113468. int err=0;
  113469. int val=vorbis_dBquant(mask+x);
  113470. int mse=0;
  113471. int n=0;
  113472. ady-=abs(base*adx);
  113473. mse=(y-val);
  113474. mse*=mse;
  113475. n++;
  113476. if(mdct[x]+info->twofitatten>=mask[x]){
  113477. if(y+info->maxover<val)return(1);
  113478. if(y-info->maxunder>val)return(1);
  113479. }
  113480. while(++x<x1){
  113481. err=err+ady;
  113482. if(err>=adx){
  113483. err-=adx;
  113484. y+=sy;
  113485. }else{
  113486. y+=base;
  113487. }
  113488. val=vorbis_dBquant(mask+x);
  113489. mse+=((y-val)*(y-val));
  113490. n++;
  113491. if(mdct[x]+info->twofitatten>=mask[x]){
  113492. if(val){
  113493. if(y+info->maxover<val)return(1);
  113494. if(y-info->maxunder>val)return(1);
  113495. }
  113496. }
  113497. }
  113498. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  113499. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  113500. if(mse/n>info->maxerr)return(1);
  113501. return(0);
  113502. }
  113503. static int post_Y(int *A,int *B,int pos){
  113504. if(A[pos]<0)
  113505. return B[pos];
  113506. if(B[pos]<0)
  113507. return A[pos];
  113508. return (A[pos]+B[pos])>>1;
  113509. }
  113510. int *floor1_fit(vorbis_block *vb,void *look_,
  113511. const float *logmdct, /* in */
  113512. const float *logmask){
  113513. long i,j;
  113514. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  113515. vorbis_info_floor1 *info=look->vi;
  113516. long n=look->n;
  113517. long posts=look->posts;
  113518. long nonzero=0;
  113519. lsfit_acc fits[VIF_POSIT+1];
  113520. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  113521. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  113522. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  113523. int hineighbor[VIF_POSIT+2];
  113524. int *output=NULL;
  113525. int memo[VIF_POSIT+2];
  113526. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  113527. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  113528. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  113529. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  113530. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  113531. /* quantize the relevant floor points and collect them into line fit
  113532. structures (one per minimal division) at the same time */
  113533. if(posts==0){
  113534. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  113535. }else{
  113536. for(i=0;i<posts-1;i++)
  113537. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  113538. look->sorted_index[i+1],fits+i,
  113539. n,info);
  113540. }
  113541. if(nonzero){
  113542. /* start by fitting the implicit base case.... */
  113543. int y0=-200;
  113544. int y1=-200;
  113545. fit_line(fits,posts-1,&y0,&y1);
  113546. fit_valueA[0]=y0;
  113547. fit_valueB[0]=y0;
  113548. fit_valueB[1]=y1;
  113549. fit_valueA[1]=y1;
  113550. /* Non degenerate case */
  113551. /* start progressive splitting. This is a greedy, non-optimal
  113552. algorithm, but simple and close enough to the best
  113553. answer. */
  113554. for(i=2;i<posts;i++){
  113555. int sortpos=look->reverse_index[i];
  113556. int ln=loneighbor[sortpos];
  113557. int hn=hineighbor[sortpos];
  113558. /* eliminate repeat searches of a particular range with a memo */
  113559. if(memo[ln]!=hn){
  113560. /* haven't performed this error search yet */
  113561. int lsortpos=look->reverse_index[ln];
  113562. int hsortpos=look->reverse_index[hn];
  113563. memo[ln]=hn;
  113564. {
  113565. /* A note: we want to bound/minimize *local*, not global, error */
  113566. int lx=info->postlist[ln];
  113567. int hx=info->postlist[hn];
  113568. int ly=post_Y(fit_valueA,fit_valueB,ln);
  113569. int hy=post_Y(fit_valueA,fit_valueB,hn);
  113570. if(ly==-1 || hy==-1){
  113571. exit(1);
  113572. }
  113573. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  113574. /* outside error bounds/begin search area. Split it. */
  113575. int ly0=-200;
  113576. int ly1=-200;
  113577. int hy0=-200;
  113578. int hy1=-200;
  113579. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  113580. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  113581. /* store new edge values */
  113582. fit_valueB[ln]=ly0;
  113583. if(ln==0)fit_valueA[ln]=ly0;
  113584. fit_valueA[i]=ly1;
  113585. fit_valueB[i]=hy0;
  113586. fit_valueA[hn]=hy1;
  113587. if(hn==1)fit_valueB[hn]=hy1;
  113588. if(ly1>=0 || hy0>=0){
  113589. /* store new neighbor values */
  113590. for(j=sortpos-1;j>=0;j--)
  113591. if(hineighbor[j]==hn)
  113592. hineighbor[j]=i;
  113593. else
  113594. break;
  113595. for(j=sortpos+1;j<posts;j++)
  113596. if(loneighbor[j]==ln)
  113597. loneighbor[j]=i;
  113598. else
  113599. break;
  113600. }
  113601. }else{
  113602. fit_valueA[i]=-200;
  113603. fit_valueB[i]=-200;
  113604. }
  113605. }
  113606. }
  113607. }
  113608. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113609. output[0]=post_Y(fit_valueA,fit_valueB,0);
  113610. output[1]=post_Y(fit_valueA,fit_valueB,1);
  113611. /* fill in posts marked as not using a fit; we will zero
  113612. back out to 'unused' when encoding them so long as curve
  113613. interpolation doesn't force them into use */
  113614. for(i=2;i<posts;i++){
  113615. int ln=look->loneighbor[i-2];
  113616. int hn=look->hineighbor[i-2];
  113617. int x0=info->postlist[ln];
  113618. int x1=info->postlist[hn];
  113619. int y0=output[ln];
  113620. int y1=output[hn];
  113621. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113622. int vx=post_Y(fit_valueA,fit_valueB,i);
  113623. if(vx>=0 && predicted!=vx){
  113624. output[i]=vx;
  113625. }else{
  113626. output[i]= predicted|0x8000;
  113627. }
  113628. }
  113629. }
  113630. return(output);
  113631. }
  113632. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  113633. int *A,int *B,
  113634. int del){
  113635. long i;
  113636. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  113637. long posts=look->posts;
  113638. int *output=NULL;
  113639. if(A && B){
  113640. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  113641. for(i=0;i<posts;i++){
  113642. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  113643. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  113644. }
  113645. }
  113646. return(output);
  113647. }
  113648. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  113649. void*look_,
  113650. int *post,int *ilogmask){
  113651. long i,j;
  113652. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  113653. vorbis_info_floor1 *info=look->vi;
  113654. long posts=look->posts;
  113655. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113656. int out[VIF_POSIT+2];
  113657. static_codebook **sbooks=ci->book_param;
  113658. codebook *books=ci->fullbooks;
  113659. static long seq=0;
  113660. /* quantize values to multiplier spec */
  113661. if(post){
  113662. for(i=0;i<posts;i++){
  113663. int val=post[i]&0x7fff;
  113664. switch(info->mult){
  113665. case 1: /* 1024 -> 256 */
  113666. val>>=2;
  113667. break;
  113668. case 2: /* 1024 -> 128 */
  113669. val>>=3;
  113670. break;
  113671. case 3: /* 1024 -> 86 */
  113672. val/=12;
  113673. break;
  113674. case 4: /* 1024 -> 64 */
  113675. val>>=4;
  113676. break;
  113677. }
  113678. post[i]=val | (post[i]&0x8000);
  113679. }
  113680. out[0]=post[0];
  113681. out[1]=post[1];
  113682. /* find prediction values for each post and subtract them */
  113683. for(i=2;i<posts;i++){
  113684. int ln=look->loneighbor[i-2];
  113685. int hn=look->hineighbor[i-2];
  113686. int x0=info->postlist[ln];
  113687. int x1=info->postlist[hn];
  113688. int y0=post[ln];
  113689. int y1=post[hn];
  113690. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  113691. if((post[i]&0x8000) || (predicted==post[i])){
  113692. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  113693. in interpolation */
  113694. out[i]=0;
  113695. }else{
  113696. int headroom=(look->quant_q-predicted<predicted?
  113697. look->quant_q-predicted:predicted);
  113698. int val=post[i]-predicted;
  113699. /* at this point the 'deviation' value is in the range +/- max
  113700. range, but the real, unique range can always be mapped to
  113701. only [0-maxrange). So we want to wrap the deviation into
  113702. this limited range, but do it in the way that least screws
  113703. an essentially gaussian probability distribution. */
  113704. if(val<0)
  113705. if(val<-headroom)
  113706. val=headroom-val-1;
  113707. else
  113708. val=-1-(val<<1);
  113709. else
  113710. if(val>=headroom)
  113711. val= val+headroom;
  113712. else
  113713. val<<=1;
  113714. out[i]=val;
  113715. post[ln]&=0x7fff;
  113716. post[hn]&=0x7fff;
  113717. }
  113718. }
  113719. /* we have everything we need. pack it out */
  113720. /* mark nontrivial floor */
  113721. oggpack_write(opb,1,1);
  113722. /* beginning/end post */
  113723. look->frames++;
  113724. look->postbits+=ilog(look->quant_q-1)*2;
  113725. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  113726. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  113727. /* partition by partition */
  113728. for(i=0,j=2;i<info->partitions;i++){
  113729. int classx=info->partitionclass[i];
  113730. int cdim=info->class_dim[classx];
  113731. int csubbits=info->class_subs[classx];
  113732. int csub=1<<csubbits;
  113733. int bookas[8]={0,0,0,0,0,0,0,0};
  113734. int cval=0;
  113735. int cshift=0;
  113736. int k,l;
  113737. /* generate the partition's first stage cascade value */
  113738. if(csubbits){
  113739. int maxval[8];
  113740. for(k=0;k<csub;k++){
  113741. int booknum=info->class_subbook[classx][k];
  113742. if(booknum<0){
  113743. maxval[k]=1;
  113744. }else{
  113745. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  113746. }
  113747. }
  113748. for(k=0;k<cdim;k++){
  113749. for(l=0;l<csub;l++){
  113750. int val=out[j+k];
  113751. if(val<maxval[l]){
  113752. bookas[k]=l;
  113753. break;
  113754. }
  113755. }
  113756. cval|= bookas[k]<<cshift;
  113757. cshift+=csubbits;
  113758. }
  113759. /* write it */
  113760. look->phrasebits+=
  113761. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  113762. #ifdef TRAIN_FLOOR1
  113763. {
  113764. FILE *of;
  113765. char buffer[80];
  113766. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  113767. vb->pcmend/2,posts-2,class);
  113768. of=fopen(buffer,"a");
  113769. fprintf(of,"%d\n",cval);
  113770. fclose(of);
  113771. }
  113772. #endif
  113773. }
  113774. /* write post values */
  113775. for(k=0;k<cdim;k++){
  113776. int book=info->class_subbook[classx][bookas[k]];
  113777. if(book>=0){
  113778. /* hack to allow training with 'bad' books */
  113779. if(out[j+k]<(books+book)->entries)
  113780. look->postbits+=vorbis_book_encode(books+book,
  113781. out[j+k],opb);
  113782. /*else
  113783. fprintf(stderr,"+!");*/
  113784. #ifdef TRAIN_FLOOR1
  113785. {
  113786. FILE *of;
  113787. char buffer[80];
  113788. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  113789. vb->pcmend/2,posts-2,class,bookas[k]);
  113790. of=fopen(buffer,"a");
  113791. fprintf(of,"%d\n",out[j+k]);
  113792. fclose(of);
  113793. }
  113794. #endif
  113795. }
  113796. }
  113797. j+=cdim;
  113798. }
  113799. {
  113800. /* generate quantized floor equivalent to what we'd unpack in decode */
  113801. /* render the lines */
  113802. int hx=0;
  113803. int lx=0;
  113804. int ly=post[0]*info->mult;
  113805. for(j=1;j<look->posts;j++){
  113806. int current=look->forward_index[j];
  113807. int hy=post[current]&0x7fff;
  113808. if(hy==post[current]){
  113809. hy*=info->mult;
  113810. hx=info->postlist[current];
  113811. render_line0(lx,hx,ly,hy,ilogmask);
  113812. lx=hx;
  113813. ly=hy;
  113814. }
  113815. }
  113816. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  113817. seq++;
  113818. return(1);
  113819. }
  113820. }else{
  113821. oggpack_write(opb,0,1);
  113822. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  113823. seq++;
  113824. return(0);
  113825. }
  113826. }
  113827. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  113828. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113829. vorbis_info_floor1 *info=look->vi;
  113830. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113831. int i,j,k;
  113832. codebook *books=ci->fullbooks;
  113833. /* unpack wrapped/predicted values from stream */
  113834. if(oggpack_read(&vb->opb,1)==1){
  113835. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  113836. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113837. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  113838. /* partition by partition */
  113839. for(i=0,j=2;i<info->partitions;i++){
  113840. int classx=info->partitionclass[i];
  113841. int cdim=info->class_dim[classx];
  113842. int csubbits=info->class_subs[classx];
  113843. int csub=1<<csubbits;
  113844. int cval=0;
  113845. /* decode the partition's first stage cascade value */
  113846. if(csubbits){
  113847. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  113848. if(cval==-1)goto eop;
  113849. }
  113850. for(k=0;k<cdim;k++){
  113851. int book=info->class_subbook[classx][cval&(csub-1)];
  113852. cval>>=csubbits;
  113853. if(book>=0){
  113854. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  113855. goto eop;
  113856. }else{
  113857. fit_value[j+k]=0;
  113858. }
  113859. }
  113860. j+=cdim;
  113861. }
  113862. /* unwrap positive values and reconsitute via linear interpolation */
  113863. for(i=2;i<look->posts;i++){
  113864. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  113865. info->postlist[look->hineighbor[i-2]],
  113866. fit_value[look->loneighbor[i-2]],
  113867. fit_value[look->hineighbor[i-2]],
  113868. info->postlist[i]);
  113869. int hiroom=look->quant_q-predicted;
  113870. int loroom=predicted;
  113871. int room=(hiroom<loroom?hiroom:loroom)<<1;
  113872. int val=fit_value[i];
  113873. if(val){
  113874. if(val>=room){
  113875. if(hiroom>loroom){
  113876. val = val-loroom;
  113877. }else{
  113878. val = -1-(val-hiroom);
  113879. }
  113880. }else{
  113881. if(val&1){
  113882. val= -((val+1)>>1);
  113883. }else{
  113884. val>>=1;
  113885. }
  113886. }
  113887. fit_value[i]=val+predicted;
  113888. fit_value[look->loneighbor[i-2]]&=0x7fff;
  113889. fit_value[look->hineighbor[i-2]]&=0x7fff;
  113890. }else{
  113891. fit_value[i]=predicted|0x8000;
  113892. }
  113893. }
  113894. return(fit_value);
  113895. }
  113896. eop:
  113897. return(NULL);
  113898. }
  113899. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  113900. float *out){
  113901. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  113902. vorbis_info_floor1 *info=look->vi;
  113903. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  113904. int n=ci->blocksizes[vb->W]/2;
  113905. int j;
  113906. if(memo){
  113907. /* render the lines */
  113908. int *fit_value=(int *)memo;
  113909. int hx=0;
  113910. int lx=0;
  113911. int ly=fit_value[0]*info->mult;
  113912. for(j=1;j<look->posts;j++){
  113913. int current=look->forward_index[j];
  113914. int hy=fit_value[current]&0x7fff;
  113915. if(hy==fit_value[current]){
  113916. hy*=info->mult;
  113917. hx=info->postlist[current];
  113918. render_line(lx,hx,ly,hy,out);
  113919. lx=hx;
  113920. ly=hy;
  113921. }
  113922. }
  113923. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  113924. return(1);
  113925. }
  113926. memset(out,0,sizeof(*out)*n);
  113927. return(0);
  113928. }
  113929. /* export hooks */
  113930. vorbis_func_floor floor1_exportbundle={
  113931. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  113932. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  113933. };
  113934. #endif
  113935. /*** End of inlined file: floor1.c ***/
  113936. /*** Start of inlined file: info.c ***/
  113937. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  113938. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113939. // tasks..
  113940. #if JUCE_MSVC
  113941. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113942. #endif
  113943. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  113944. #if JUCE_USE_OGGVORBIS
  113945. /* general handling of the header and the vorbis_info structure (and
  113946. substructures) */
  113947. #include <stdlib.h>
  113948. #include <string.h>
  113949. #include <ctype.h>
  113950. static void _v_writestring(oggpack_buffer *o, const char *s, int bytes){
  113951. while(bytes--){
  113952. oggpack_write(o,*s++,8);
  113953. }
  113954. }
  113955. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  113956. while(bytes--){
  113957. *buf++=oggpack_read(o,8);
  113958. }
  113959. }
  113960. void vorbis_comment_init(vorbis_comment *vc){
  113961. memset(vc,0,sizeof(*vc));
  113962. }
  113963. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  113964. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  113965. (vc->comments+2)*sizeof(*vc->user_comments));
  113966. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  113967. (vc->comments+2)*sizeof(*vc->comment_lengths));
  113968. vc->comment_lengths[vc->comments]=strlen(comment);
  113969. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  113970. strcpy(vc->user_comments[vc->comments], comment);
  113971. vc->comments++;
  113972. vc->user_comments[vc->comments]=NULL;
  113973. }
  113974. void vorbis_comment_add_tag(vorbis_comment *vc, const char *tag, char *contents){
  113975. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  113976. strcpy(comment, tag);
  113977. strcat(comment, "=");
  113978. strcat(comment, contents);
  113979. vorbis_comment_add(vc, comment);
  113980. }
  113981. /* This is more or less the same as strncasecmp - but that doesn't exist
  113982. * everywhere, and this is a fairly trivial function, so we include it */
  113983. static int tagcompare(const char *s1, const char *s2, int n){
  113984. int c=0;
  113985. while(c < n){
  113986. if(toupper(s1[c]) != toupper(s2[c]))
  113987. return !0;
  113988. c++;
  113989. }
  113990. return 0;
  113991. }
  113992. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  113993. long i;
  113994. int found = 0;
  113995. int taglen = strlen(tag)+1; /* +1 for the = we append */
  113996. char *fulltag = (char*)alloca(taglen+ 1);
  113997. strcpy(fulltag, tag);
  113998. strcat(fulltag, "=");
  113999. for(i=0;i<vc->comments;i++){
  114000. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  114001. if(count == found)
  114002. /* We return a pointer to the data, not a copy */
  114003. return vc->user_comments[i] + taglen;
  114004. else
  114005. found++;
  114006. }
  114007. }
  114008. return NULL; /* didn't find anything */
  114009. }
  114010. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  114011. int i,count=0;
  114012. int taglen = strlen(tag)+1; /* +1 for the = we append */
  114013. char *fulltag = (char*)alloca(taglen+1);
  114014. strcpy(fulltag,tag);
  114015. strcat(fulltag, "=");
  114016. for(i=0;i<vc->comments;i++){
  114017. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  114018. count++;
  114019. }
  114020. return count;
  114021. }
  114022. void vorbis_comment_clear(vorbis_comment *vc){
  114023. if(vc){
  114024. long i;
  114025. for(i=0;i<vc->comments;i++)
  114026. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  114027. if(vc->user_comments)_ogg_free(vc->user_comments);
  114028. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  114029. if(vc->vendor)_ogg_free(vc->vendor);
  114030. }
  114031. memset(vc,0,sizeof(*vc));
  114032. }
  114033. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  114034. They may be equal, but short will never ge greater than long */
  114035. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  114036. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  114037. return ci ? ci->blocksizes[zo] : -1;
  114038. }
  114039. /* used by synthesis, which has a full, alloced vi */
  114040. void vorbis_info_init(vorbis_info *vi){
  114041. memset(vi,0,sizeof(*vi));
  114042. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  114043. }
  114044. void vorbis_info_clear(vorbis_info *vi){
  114045. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114046. int i;
  114047. if(ci){
  114048. for(i=0;i<ci->modes;i++)
  114049. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  114050. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  114051. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  114052. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  114053. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  114054. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  114055. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  114056. for(i=0;i<ci->books;i++){
  114057. if(ci->book_param[i]){
  114058. /* knows if the book was not alloced */
  114059. vorbis_staticbook_destroy(ci->book_param[i]);
  114060. }
  114061. if(ci->fullbooks)
  114062. vorbis_book_clear(ci->fullbooks+i);
  114063. }
  114064. if(ci->fullbooks)
  114065. _ogg_free(ci->fullbooks);
  114066. for(i=0;i<ci->psys;i++)
  114067. _vi_psy_free(ci->psy_param[i]);
  114068. _ogg_free(ci);
  114069. }
  114070. memset(vi,0,sizeof(*vi));
  114071. }
  114072. /* Header packing/unpacking ********************************************/
  114073. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  114074. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114075. if(!ci)return(OV_EFAULT);
  114076. vi->version=oggpack_read(opb,32);
  114077. if(vi->version!=0)return(OV_EVERSION);
  114078. vi->channels=oggpack_read(opb,8);
  114079. vi->rate=oggpack_read(opb,32);
  114080. vi->bitrate_upper=oggpack_read(opb,32);
  114081. vi->bitrate_nominal=oggpack_read(opb,32);
  114082. vi->bitrate_lower=oggpack_read(opb,32);
  114083. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  114084. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  114085. if(vi->rate<1)goto err_out;
  114086. if(vi->channels<1)goto err_out;
  114087. if(ci->blocksizes[0]<8)goto err_out;
  114088. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  114089. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114090. return(0);
  114091. err_out:
  114092. vorbis_info_clear(vi);
  114093. return(OV_EBADHEADER);
  114094. }
  114095. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  114096. int i;
  114097. int vendorlen=oggpack_read(opb,32);
  114098. if(vendorlen<0)goto err_out;
  114099. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  114100. _v_readstring(opb,vc->vendor,vendorlen);
  114101. vc->comments=oggpack_read(opb,32);
  114102. if(vc->comments<0)goto err_out;
  114103. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  114104. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  114105. for(i=0;i<vc->comments;i++){
  114106. int len=oggpack_read(opb,32);
  114107. if(len<0)goto err_out;
  114108. vc->comment_lengths[i]=len;
  114109. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  114110. _v_readstring(opb,vc->user_comments[i],len);
  114111. }
  114112. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  114113. return(0);
  114114. err_out:
  114115. vorbis_comment_clear(vc);
  114116. return(OV_EBADHEADER);
  114117. }
  114118. /* all of the real encoding details are here. The modes, books,
  114119. everything */
  114120. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  114121. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114122. int i;
  114123. if(!ci)return(OV_EFAULT);
  114124. /* codebooks */
  114125. ci->books=oggpack_read(opb,8)+1;
  114126. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  114127. for(i=0;i<ci->books;i++){
  114128. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  114129. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  114130. }
  114131. /* time backend settings; hooks are unused */
  114132. {
  114133. int times=oggpack_read(opb,6)+1;
  114134. for(i=0;i<times;i++){
  114135. int test=oggpack_read(opb,16);
  114136. if(test<0 || test>=VI_TIMEB)goto err_out;
  114137. }
  114138. }
  114139. /* floor backend settings */
  114140. ci->floors=oggpack_read(opb,6)+1;
  114141. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  114142. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  114143. for(i=0;i<ci->floors;i++){
  114144. ci->floor_type[i]=oggpack_read(opb,16);
  114145. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  114146. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  114147. if(!ci->floor_param[i])goto err_out;
  114148. }
  114149. /* residue backend settings */
  114150. ci->residues=oggpack_read(opb,6)+1;
  114151. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  114152. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  114153. for(i=0;i<ci->residues;i++){
  114154. ci->residue_type[i]=oggpack_read(opb,16);
  114155. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  114156. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  114157. if(!ci->residue_param[i])goto err_out;
  114158. }
  114159. /* map backend settings */
  114160. ci->maps=oggpack_read(opb,6)+1;
  114161. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  114162. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  114163. for(i=0;i<ci->maps;i++){
  114164. ci->map_type[i]=oggpack_read(opb,16);
  114165. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  114166. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  114167. if(!ci->map_param[i])goto err_out;
  114168. }
  114169. /* mode settings */
  114170. ci->modes=oggpack_read(opb,6)+1;
  114171. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  114172. for(i=0;i<ci->modes;i++){
  114173. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  114174. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  114175. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  114176. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  114177. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  114178. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  114179. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  114180. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  114181. }
  114182. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  114183. return(0);
  114184. err_out:
  114185. vorbis_info_clear(vi);
  114186. return(OV_EBADHEADER);
  114187. }
  114188. /* The Vorbis header is in three packets; the initial small packet in
  114189. the first page that identifies basic parameters, a second packet
  114190. with bitstream comments and a third packet that holds the
  114191. codebook. */
  114192. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  114193. oggpack_buffer opb;
  114194. if(op){
  114195. oggpack_readinit(&opb,op->packet,op->bytes);
  114196. /* Which of the three types of header is this? */
  114197. /* Also verify header-ness, vorbis */
  114198. {
  114199. char buffer[6];
  114200. int packtype=oggpack_read(&opb,8);
  114201. memset(buffer,0,6);
  114202. _v_readstring(&opb,buffer,6);
  114203. if(memcmp(buffer,"vorbis",6)){
  114204. /* not a vorbis header */
  114205. return(OV_ENOTVORBIS);
  114206. }
  114207. switch(packtype){
  114208. case 0x01: /* least significant *bit* is read first */
  114209. if(!op->b_o_s){
  114210. /* Not the initial packet */
  114211. return(OV_EBADHEADER);
  114212. }
  114213. if(vi->rate!=0){
  114214. /* previously initialized info header */
  114215. return(OV_EBADHEADER);
  114216. }
  114217. return(_vorbis_unpack_info(vi,&opb));
  114218. case 0x03: /* least significant *bit* is read first */
  114219. if(vi->rate==0){
  114220. /* um... we didn't get the initial header */
  114221. return(OV_EBADHEADER);
  114222. }
  114223. return(_vorbis_unpack_comment(vc,&opb));
  114224. case 0x05: /* least significant *bit* is read first */
  114225. if(vi->rate==0 || vc->vendor==NULL){
  114226. /* um... we didn;t get the initial header or comments yet */
  114227. return(OV_EBADHEADER);
  114228. }
  114229. return(_vorbis_unpack_books(vi,&opb));
  114230. default:
  114231. /* Not a valid vorbis header type */
  114232. return(OV_EBADHEADER);
  114233. break;
  114234. }
  114235. }
  114236. }
  114237. return(OV_EBADHEADER);
  114238. }
  114239. /* pack side **********************************************************/
  114240. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  114241. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114242. if(!ci)return(OV_EFAULT);
  114243. /* preamble */
  114244. oggpack_write(opb,0x01,8);
  114245. _v_writestring(opb,"vorbis", 6);
  114246. /* basic information about the stream */
  114247. oggpack_write(opb,0x00,32);
  114248. oggpack_write(opb,vi->channels,8);
  114249. oggpack_write(opb,vi->rate,32);
  114250. oggpack_write(opb,vi->bitrate_upper,32);
  114251. oggpack_write(opb,vi->bitrate_nominal,32);
  114252. oggpack_write(opb,vi->bitrate_lower,32);
  114253. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  114254. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  114255. oggpack_write(opb,1,1);
  114256. return(0);
  114257. }
  114258. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  114259. char temp[]="Xiph.Org libVorbis I 20050304";
  114260. int bytes = strlen(temp);
  114261. /* preamble */
  114262. oggpack_write(opb,0x03,8);
  114263. _v_writestring(opb,"vorbis", 6);
  114264. /* vendor */
  114265. oggpack_write(opb,bytes,32);
  114266. _v_writestring(opb,temp, bytes);
  114267. /* comments */
  114268. oggpack_write(opb,vc->comments,32);
  114269. if(vc->comments){
  114270. int i;
  114271. for(i=0;i<vc->comments;i++){
  114272. if(vc->user_comments[i]){
  114273. oggpack_write(opb,vc->comment_lengths[i],32);
  114274. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  114275. }else{
  114276. oggpack_write(opb,0,32);
  114277. }
  114278. }
  114279. }
  114280. oggpack_write(opb,1,1);
  114281. return(0);
  114282. }
  114283. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  114284. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114285. int i;
  114286. if(!ci)return(OV_EFAULT);
  114287. oggpack_write(opb,0x05,8);
  114288. _v_writestring(opb,"vorbis", 6);
  114289. /* books */
  114290. oggpack_write(opb,ci->books-1,8);
  114291. for(i=0;i<ci->books;i++)
  114292. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  114293. /* times; hook placeholders */
  114294. oggpack_write(opb,0,6);
  114295. oggpack_write(opb,0,16);
  114296. /* floors */
  114297. oggpack_write(opb,ci->floors-1,6);
  114298. for(i=0;i<ci->floors;i++){
  114299. oggpack_write(opb,ci->floor_type[i],16);
  114300. if(_floor_P[ci->floor_type[i]]->pack)
  114301. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  114302. else
  114303. goto err_out;
  114304. }
  114305. /* residues */
  114306. oggpack_write(opb,ci->residues-1,6);
  114307. for(i=0;i<ci->residues;i++){
  114308. oggpack_write(opb,ci->residue_type[i],16);
  114309. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  114310. }
  114311. /* maps */
  114312. oggpack_write(opb,ci->maps-1,6);
  114313. for(i=0;i<ci->maps;i++){
  114314. oggpack_write(opb,ci->map_type[i],16);
  114315. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  114316. }
  114317. /* modes */
  114318. oggpack_write(opb,ci->modes-1,6);
  114319. for(i=0;i<ci->modes;i++){
  114320. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  114321. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  114322. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  114323. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  114324. }
  114325. oggpack_write(opb,1,1);
  114326. return(0);
  114327. err_out:
  114328. return(-1);
  114329. }
  114330. int vorbis_commentheader_out(vorbis_comment *vc,
  114331. ogg_packet *op){
  114332. oggpack_buffer opb;
  114333. oggpack_writeinit(&opb);
  114334. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  114335. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114336. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  114337. op->bytes=oggpack_bytes(&opb);
  114338. op->b_o_s=0;
  114339. op->e_o_s=0;
  114340. op->granulepos=0;
  114341. op->packetno=1;
  114342. return 0;
  114343. }
  114344. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  114345. vorbis_comment *vc,
  114346. ogg_packet *op,
  114347. ogg_packet *op_comm,
  114348. ogg_packet *op_code){
  114349. int ret=OV_EIMPL;
  114350. vorbis_info *vi=v->vi;
  114351. oggpack_buffer opb;
  114352. private_state *b=(private_state*)v->backend_state;
  114353. if(!b){
  114354. ret=OV_EFAULT;
  114355. goto err_out;
  114356. }
  114357. /* first header packet **********************************************/
  114358. oggpack_writeinit(&opb);
  114359. if(_vorbis_pack_info(&opb,vi))goto err_out;
  114360. /* build the packet */
  114361. if(b->header)_ogg_free(b->header);
  114362. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114363. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  114364. op->packet=b->header;
  114365. op->bytes=oggpack_bytes(&opb);
  114366. op->b_o_s=1;
  114367. op->e_o_s=0;
  114368. op->granulepos=0;
  114369. op->packetno=0;
  114370. /* second header packet (comments) **********************************/
  114371. oggpack_reset(&opb);
  114372. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  114373. if(b->header1)_ogg_free(b->header1);
  114374. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114375. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  114376. op_comm->packet=b->header1;
  114377. op_comm->bytes=oggpack_bytes(&opb);
  114378. op_comm->b_o_s=0;
  114379. op_comm->e_o_s=0;
  114380. op_comm->granulepos=0;
  114381. op_comm->packetno=1;
  114382. /* third header packet (modes/codebooks) ****************************/
  114383. oggpack_reset(&opb);
  114384. if(_vorbis_pack_books(&opb,vi))goto err_out;
  114385. if(b->header2)_ogg_free(b->header2);
  114386. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  114387. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  114388. op_code->packet=b->header2;
  114389. op_code->bytes=oggpack_bytes(&opb);
  114390. op_code->b_o_s=0;
  114391. op_code->e_o_s=0;
  114392. op_code->granulepos=0;
  114393. op_code->packetno=2;
  114394. oggpack_writeclear(&opb);
  114395. return(0);
  114396. err_out:
  114397. oggpack_writeclear(&opb);
  114398. memset(op,0,sizeof(*op));
  114399. memset(op_comm,0,sizeof(*op_comm));
  114400. memset(op_code,0,sizeof(*op_code));
  114401. if(b->header)_ogg_free(b->header);
  114402. if(b->header1)_ogg_free(b->header1);
  114403. if(b->header2)_ogg_free(b->header2);
  114404. b->header=NULL;
  114405. b->header1=NULL;
  114406. b->header2=NULL;
  114407. return(ret);
  114408. }
  114409. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  114410. if(granulepos>=0)
  114411. return((double)granulepos/v->vi->rate);
  114412. return(-1);
  114413. }
  114414. #endif
  114415. /*** End of inlined file: info.c ***/
  114416. /*** Start of inlined file: lpc.c ***/
  114417. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  114418. are derived from code written by Jutta Degener and Carsten Bormann;
  114419. thus we include their copyright below. The entirety of this file
  114420. is freely redistributable on the condition that both of these
  114421. copyright notices are preserved without modification. */
  114422. /* Preserved Copyright: *********************************************/
  114423. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  114424. Technische Universita"t Berlin
  114425. Any use of this software is permitted provided that this notice is not
  114426. removed and that neither the authors nor the Technische Universita"t
  114427. Berlin are deemed to have made any representations as to the
  114428. suitability of this software for any purpose nor are held responsible
  114429. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  114430. THIS SOFTWARE.
  114431. As a matter of courtesy, the authors request to be informed about uses
  114432. this software has found, about bugs in this software, and about any
  114433. improvements that may be of general interest.
  114434. Berlin, 28.11.1994
  114435. Jutta Degener
  114436. Carsten Bormann
  114437. *********************************************************************/
  114438. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114439. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114440. // tasks..
  114441. #if JUCE_MSVC
  114442. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114443. #endif
  114444. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114445. #if JUCE_USE_OGGVORBIS
  114446. #include <stdlib.h>
  114447. #include <string.h>
  114448. #include <math.h>
  114449. /* Autocorrelation LPC coeff generation algorithm invented by
  114450. N. Levinson in 1947, modified by J. Durbin in 1959. */
  114451. /* Input : n elements of time doamin data
  114452. Output: m lpc coefficients, excitation energy */
  114453. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  114454. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  114455. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  114456. double error;
  114457. int i,j;
  114458. /* autocorrelation, p+1 lag coefficients */
  114459. j=m+1;
  114460. while(j--){
  114461. double d=0; /* double needed for accumulator depth */
  114462. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  114463. aut[j]=d;
  114464. }
  114465. /* Generate lpc coefficients from autocorr values */
  114466. error=aut[0];
  114467. for(i=0;i<m;i++){
  114468. double r= -aut[i+1];
  114469. if(error==0){
  114470. memset(lpci,0,m*sizeof(*lpci));
  114471. return 0;
  114472. }
  114473. /* Sum up this iteration's reflection coefficient; note that in
  114474. Vorbis we don't save it. If anyone wants to recycle this code
  114475. and needs reflection coefficients, save the results of 'r' from
  114476. each iteration. */
  114477. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  114478. r/=error;
  114479. /* Update LPC coefficients and total error */
  114480. lpc[i]=r;
  114481. for(j=0;j<i/2;j++){
  114482. double tmp=lpc[j];
  114483. lpc[j]+=r*lpc[i-1-j];
  114484. lpc[i-1-j]+=r*tmp;
  114485. }
  114486. if(i%2)lpc[j]+=lpc[j]*r;
  114487. error*=1.f-r*r;
  114488. }
  114489. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  114490. /* we need the error value to know how big an impulse to hit the
  114491. filter with later */
  114492. return error;
  114493. }
  114494. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  114495. float *data,long n){
  114496. /* in: coeff[0...m-1] LPC coefficients
  114497. prime[0...m-1] initial values (allocated size of n+m-1)
  114498. out: data[0...n-1] data samples */
  114499. long i,j,o,p;
  114500. float y;
  114501. float *work=(float*)alloca(sizeof(*work)*(m+n));
  114502. if(!prime)
  114503. for(i=0;i<m;i++)
  114504. work[i]=0.f;
  114505. else
  114506. for(i=0;i<m;i++)
  114507. work[i]=prime[i];
  114508. for(i=0;i<n;i++){
  114509. y=0;
  114510. o=i;
  114511. p=m;
  114512. for(j=0;j<m;j++)
  114513. y-=work[o++]*coeff[--p];
  114514. data[i]=work[o]=y;
  114515. }
  114516. }
  114517. #endif
  114518. /*** End of inlined file: lpc.c ***/
  114519. /*** Start of inlined file: lsp.c ***/
  114520. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  114521. an iterative root polisher (CACM algorithm 283). It *is* possible
  114522. to confuse this algorithm into not converging; that should only
  114523. happen with absurdly closely spaced roots (very sharp peaks in the
  114524. LPC f response) which in turn should be impossible in our use of
  114525. the code. If this *does* happen anyway, it's a bug in the floor
  114526. finder; find the cause of the confusion (probably a single bin
  114527. spike or accidental near-float-limit resolution problems) and
  114528. correct it. */
  114529. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114530. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114531. // tasks..
  114532. #if JUCE_MSVC
  114533. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114534. #endif
  114535. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114536. #if JUCE_USE_OGGVORBIS
  114537. #include <math.h>
  114538. #include <string.h>
  114539. #include <stdlib.h>
  114540. /*** Start of inlined file: lookup.h ***/
  114541. #ifndef _V_LOOKUP_H_
  114542. #ifdef FLOAT_LOOKUP
  114543. extern float vorbis_coslook(float a);
  114544. extern float vorbis_invsqlook(float a);
  114545. extern float vorbis_invsq2explook(int a);
  114546. extern float vorbis_fromdBlook(float a);
  114547. #endif
  114548. #ifdef INT_LOOKUP
  114549. extern long vorbis_invsqlook_i(long a,long e);
  114550. extern long vorbis_coslook_i(long a);
  114551. extern float vorbis_fromdBlook_i(long a);
  114552. #endif
  114553. #endif
  114554. /*** End of inlined file: lookup.h ***/
  114555. /* three possible LSP to f curve functions; the exact computation
  114556. (float), a lookup based float implementation, and an integer
  114557. implementation. The float lookup is likely the optimal choice on
  114558. any machine with an FPU. The integer implementation is *not* fixed
  114559. point (due to the need for a large dynamic range and thus a
  114560. seperately tracked exponent) and thus much more complex than the
  114561. relatively simple float implementations. It's mostly for future
  114562. work on a fully fixed point implementation for processors like the
  114563. ARM family. */
  114564. /* undefine both for the 'old' but more precise implementation */
  114565. #define FLOAT_LOOKUP
  114566. #undef INT_LOOKUP
  114567. #ifdef FLOAT_LOOKUP
  114568. /*** Start of inlined file: lookup.c ***/
  114569. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114570. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114571. // tasks..
  114572. #if JUCE_MSVC
  114573. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114574. #endif
  114575. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114576. #if JUCE_USE_OGGVORBIS
  114577. #include <math.h>
  114578. /*** Start of inlined file: lookup.h ***/
  114579. #ifndef _V_LOOKUP_H_
  114580. #ifdef FLOAT_LOOKUP
  114581. extern float vorbis_coslook(float a);
  114582. extern float vorbis_invsqlook(float a);
  114583. extern float vorbis_invsq2explook(int a);
  114584. extern float vorbis_fromdBlook(float a);
  114585. #endif
  114586. #ifdef INT_LOOKUP
  114587. extern long vorbis_invsqlook_i(long a,long e);
  114588. extern long vorbis_coslook_i(long a);
  114589. extern float vorbis_fromdBlook_i(long a);
  114590. #endif
  114591. #endif
  114592. /*** End of inlined file: lookup.h ***/
  114593. /*** Start of inlined file: lookup_data.h ***/
  114594. #ifndef _V_LOOKUP_DATA_H_
  114595. #ifdef FLOAT_LOOKUP
  114596. #define COS_LOOKUP_SZ 128
  114597. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114598. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114599. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114600. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114601. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114602. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114603. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114604. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114605. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114606. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114607. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114608. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114609. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114610. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114611. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114612. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114613. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114614. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114615. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114616. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114617. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114618. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114619. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114620. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114621. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114622. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114623. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114624. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114625. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114626. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114627. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114628. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114629. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114630. -1.0000000000000f,
  114631. };
  114632. #define INVSQ_LOOKUP_SZ 32
  114633. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114634. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114635. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114636. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114637. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114638. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114639. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114640. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114641. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114642. 1.000000000000f,
  114643. };
  114644. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114645. #define INVSQ2EXP_LOOKUP_MAX 32
  114646. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114647. INVSQ2EXP_LOOKUP_MIN+1]={
  114648. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114649. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114650. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114651. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114652. 256.f, 181.019336f, 128.f, 90.50966799f,
  114653. 64.f, 45.254834f, 32.f, 22.627417f,
  114654. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114655. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114656. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114657. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114658. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114659. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114660. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114661. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114662. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114663. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114664. 1.525878906e-05f,
  114665. };
  114666. #endif
  114667. #define FROMdB_LOOKUP_SZ 35
  114668. #define FROMdB2_LOOKUP_SZ 32
  114669. #define FROMdB_SHIFT 5
  114670. #define FROMdB2_SHIFT 3
  114671. #define FROMdB2_MASK 31
  114672. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114673. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114674. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114675. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114676. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114677. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114678. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114679. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114680. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114681. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114682. };
  114683. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114684. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114685. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114686. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114687. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114688. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114689. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114690. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114691. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114692. };
  114693. #ifdef INT_LOOKUP
  114694. #define INVSQ_LOOKUP_I_SHIFT 10
  114695. #define INVSQ_LOOKUP_I_MASK 1023
  114696. static long INVSQ_LOOKUP_I[64+1]={
  114697. 92682l, 91966l, 91267l, 90583l,
  114698. 89915l, 89261l, 88621l, 87995l,
  114699. 87381l, 86781l, 86192l, 85616l,
  114700. 85051l, 84497l, 83953l, 83420l,
  114701. 82897l, 82384l, 81880l, 81385l,
  114702. 80899l, 80422l, 79953l, 79492l,
  114703. 79039l, 78594l, 78156l, 77726l,
  114704. 77302l, 76885l, 76475l, 76072l,
  114705. 75674l, 75283l, 74898l, 74519l,
  114706. 74146l, 73778l, 73415l, 73058l,
  114707. 72706l, 72359l, 72016l, 71679l,
  114708. 71347l, 71019l, 70695l, 70376l,
  114709. 70061l, 69750l, 69444l, 69141l,
  114710. 68842l, 68548l, 68256l, 67969l,
  114711. 67685l, 67405l, 67128l, 66855l,
  114712. 66585l, 66318l, 66054l, 65794l,
  114713. 65536l,
  114714. };
  114715. #define COS_LOOKUP_I_SHIFT 9
  114716. #define COS_LOOKUP_I_MASK 511
  114717. #define COS_LOOKUP_I_SZ 128
  114718. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114719. 16384l, 16379l, 16364l, 16340l,
  114720. 16305l, 16261l, 16207l, 16143l,
  114721. 16069l, 15986l, 15893l, 15791l,
  114722. 15679l, 15557l, 15426l, 15286l,
  114723. 15137l, 14978l, 14811l, 14635l,
  114724. 14449l, 14256l, 14053l, 13842l,
  114725. 13623l, 13395l, 13160l, 12916l,
  114726. 12665l, 12406l, 12140l, 11866l,
  114727. 11585l, 11297l, 11003l, 10702l,
  114728. 10394l, 10080l, 9760l, 9434l,
  114729. 9102l, 8765l, 8423l, 8076l,
  114730. 7723l, 7366l, 7005l, 6639l,
  114731. 6270l, 5897l, 5520l, 5139l,
  114732. 4756l, 4370l, 3981l, 3590l,
  114733. 3196l, 2801l, 2404l, 2006l,
  114734. 1606l, 1205l, 804l, 402l,
  114735. 0l, -401l, -803l, -1204l,
  114736. -1605l, -2005l, -2403l, -2800l,
  114737. -3195l, -3589l, -3980l, -4369l,
  114738. -4755l, -5138l, -5519l, -5896l,
  114739. -6269l, -6638l, -7004l, -7365l,
  114740. -7722l, -8075l, -8422l, -8764l,
  114741. -9101l, -9433l, -9759l, -10079l,
  114742. -10393l, -10701l, -11002l, -11296l,
  114743. -11584l, -11865l, -12139l, -12405l,
  114744. -12664l, -12915l, -13159l, -13394l,
  114745. -13622l, -13841l, -14052l, -14255l,
  114746. -14448l, -14634l, -14810l, -14977l,
  114747. -15136l, -15285l, -15425l, -15556l,
  114748. -15678l, -15790l, -15892l, -15985l,
  114749. -16068l, -16142l, -16206l, -16260l,
  114750. -16304l, -16339l, -16363l, -16378l,
  114751. -16383l,
  114752. };
  114753. #endif
  114754. #endif
  114755. /*** End of inlined file: lookup_data.h ***/
  114756. #ifdef FLOAT_LOOKUP
  114757. /* interpolated lookup based cos function, domain 0 to PI only */
  114758. float vorbis_coslook(float a){
  114759. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114760. int i=vorbis_ftoi(d-.5);
  114761. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114762. }
  114763. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114764. float vorbis_invsqlook(float a){
  114765. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114766. int i=vorbis_ftoi(d-.5f);
  114767. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114768. }
  114769. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114770. float vorbis_invsq2explook(int a){
  114771. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114772. }
  114773. #include <stdio.h>
  114774. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114775. float vorbis_fromdBlook(float a){
  114776. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114777. return (i<0)?1.f:
  114778. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114779. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114780. }
  114781. #endif
  114782. #ifdef INT_LOOKUP
  114783. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114784. 16.16 format
  114785. returns in m.8 format */
  114786. long vorbis_invsqlook_i(long a,long e){
  114787. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114788. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114789. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114790. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114791. d)>>16); /* result 1.16 */
  114792. e+=32;
  114793. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114794. e=(e>>1)-8;
  114795. return(val>>e);
  114796. }
  114797. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114798. /* a is in n.12 format */
  114799. float vorbis_fromdBlook_i(long a){
  114800. int i=(-a)>>(12-FROMdB2_SHIFT);
  114801. return (i<0)?1.f:
  114802. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114803. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114804. }
  114805. /* interpolated lookup based cos function, domain 0 to PI only */
  114806. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114807. long vorbis_coslook_i(long a){
  114808. int i=a>>COS_LOOKUP_I_SHIFT;
  114809. int d=a&COS_LOOKUP_I_MASK;
  114810. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114811. COS_LOOKUP_I_SHIFT);
  114812. }
  114813. #endif
  114814. #endif
  114815. /*** End of inlined file: lookup.c ***/
  114816. /* catch this in the build system; we #include for
  114817. compilers (like gcc) that can't inline across
  114818. modules */
  114819. /* side effect: changes *lsp to cosines of lsp */
  114820. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114821. float amp,float ampoffset){
  114822. int i;
  114823. float wdel=M_PI/ln;
  114824. vorbis_fpu_control fpu;
  114825. (void) fpu; // to avoid an unused variable warning
  114826. vorbis_fpu_setround(&fpu);
  114827. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  114828. i=0;
  114829. while(i<n){
  114830. int k=map[i];
  114831. int qexp;
  114832. float p=.7071067812f;
  114833. float q=.7071067812f;
  114834. float w=vorbis_coslook(wdel*k);
  114835. float *ftmp=lsp;
  114836. int c=m>>1;
  114837. do{
  114838. q*=ftmp[0]-w;
  114839. p*=ftmp[1]-w;
  114840. ftmp+=2;
  114841. }while(--c);
  114842. if(m&1){
  114843. /* odd order filter; slightly assymetric */
  114844. /* the last coefficient */
  114845. q*=ftmp[0]-w;
  114846. q*=q;
  114847. p*=p*(1.f-w*w);
  114848. }else{
  114849. /* even order filter; still symmetric */
  114850. q*=q*(1.f+w);
  114851. p*=p*(1.f-w);
  114852. }
  114853. q=frexp(p+q,&qexp);
  114854. q=vorbis_fromdBlook(amp*
  114855. vorbis_invsqlook(q)*
  114856. vorbis_invsq2explook(qexp+m)-
  114857. ampoffset);
  114858. do{
  114859. curve[i++]*=q;
  114860. }while(map[i]==k);
  114861. }
  114862. vorbis_fpu_restore(fpu);
  114863. }
  114864. #else
  114865. #ifdef INT_LOOKUP
  114866. /*** Start of inlined file: lookup.c ***/
  114867. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  114868. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114869. // tasks..
  114870. #if JUCE_MSVC
  114871. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114872. #endif
  114873. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  114874. #if JUCE_USE_OGGVORBIS
  114875. #include <math.h>
  114876. /*** Start of inlined file: lookup.h ***/
  114877. #ifndef _V_LOOKUP_H_
  114878. #ifdef FLOAT_LOOKUP
  114879. extern float vorbis_coslook(float a);
  114880. extern float vorbis_invsqlook(float a);
  114881. extern float vorbis_invsq2explook(int a);
  114882. extern float vorbis_fromdBlook(float a);
  114883. #endif
  114884. #ifdef INT_LOOKUP
  114885. extern long vorbis_invsqlook_i(long a,long e);
  114886. extern long vorbis_coslook_i(long a);
  114887. extern float vorbis_fromdBlook_i(long a);
  114888. #endif
  114889. #endif
  114890. /*** End of inlined file: lookup.h ***/
  114891. /*** Start of inlined file: lookup_data.h ***/
  114892. #ifndef _V_LOOKUP_DATA_H_
  114893. #ifdef FLOAT_LOOKUP
  114894. #define COS_LOOKUP_SZ 128
  114895. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  114896. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  114897. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  114898. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  114899. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  114900. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  114901. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  114902. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  114903. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  114904. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  114905. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  114906. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  114907. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  114908. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  114909. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  114910. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  114911. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  114912. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  114913. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  114914. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  114915. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  114916. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  114917. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  114918. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  114919. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  114920. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  114921. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  114922. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  114923. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  114924. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  114925. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  114926. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  114927. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  114928. -1.0000000000000f,
  114929. };
  114930. #define INVSQ_LOOKUP_SZ 32
  114931. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  114932. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  114933. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  114934. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  114935. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  114936. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  114937. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  114938. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  114939. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  114940. 1.000000000000f,
  114941. };
  114942. #define INVSQ2EXP_LOOKUP_MIN (-32)
  114943. #define INVSQ2EXP_LOOKUP_MAX 32
  114944. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  114945. INVSQ2EXP_LOOKUP_MIN+1]={
  114946. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  114947. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  114948. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  114949. 1024.f, 724.0773439f, 512.f, 362.038672f,
  114950. 256.f, 181.019336f, 128.f, 90.50966799f,
  114951. 64.f, 45.254834f, 32.f, 22.627417f,
  114952. 16.f, 11.3137085f, 8.f, 5.656854249f,
  114953. 4.f, 2.828427125f, 2.f, 1.414213562f,
  114954. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  114955. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  114956. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  114957. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  114958. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  114959. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  114960. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  114961. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  114962. 1.525878906e-05f,
  114963. };
  114964. #endif
  114965. #define FROMdB_LOOKUP_SZ 35
  114966. #define FROMdB2_LOOKUP_SZ 32
  114967. #define FROMdB_SHIFT 5
  114968. #define FROMdB2_SHIFT 3
  114969. #define FROMdB2_MASK 31
  114970. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  114971. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  114972. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  114973. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  114974. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  114975. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  114976. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  114977. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  114978. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  114979. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  114980. };
  114981. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  114982. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  114983. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  114984. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114985. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114986. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114987. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114988. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114989. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114990. };
  114991. #ifdef INT_LOOKUP
  114992. #define INVSQ_LOOKUP_I_SHIFT 10
  114993. #define INVSQ_LOOKUP_I_MASK 1023
  114994. static long INVSQ_LOOKUP_I[64+1]={
  114995. 92682l, 91966l, 91267l, 90583l,
  114996. 89915l, 89261l, 88621l, 87995l,
  114997. 87381l, 86781l, 86192l, 85616l,
  114998. 85051l, 84497l, 83953l, 83420l,
  114999. 82897l, 82384l, 81880l, 81385l,
  115000. 80899l, 80422l, 79953l, 79492l,
  115001. 79039l, 78594l, 78156l, 77726l,
  115002. 77302l, 76885l, 76475l, 76072l,
  115003. 75674l, 75283l, 74898l, 74519l,
  115004. 74146l, 73778l, 73415l, 73058l,
  115005. 72706l, 72359l, 72016l, 71679l,
  115006. 71347l, 71019l, 70695l, 70376l,
  115007. 70061l, 69750l, 69444l, 69141l,
  115008. 68842l, 68548l, 68256l, 67969l,
  115009. 67685l, 67405l, 67128l, 66855l,
  115010. 66585l, 66318l, 66054l, 65794l,
  115011. 65536l,
  115012. };
  115013. #define COS_LOOKUP_I_SHIFT 9
  115014. #define COS_LOOKUP_I_MASK 511
  115015. #define COS_LOOKUP_I_SZ 128
  115016. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  115017. 16384l, 16379l, 16364l, 16340l,
  115018. 16305l, 16261l, 16207l, 16143l,
  115019. 16069l, 15986l, 15893l, 15791l,
  115020. 15679l, 15557l, 15426l, 15286l,
  115021. 15137l, 14978l, 14811l, 14635l,
  115022. 14449l, 14256l, 14053l, 13842l,
  115023. 13623l, 13395l, 13160l, 12916l,
  115024. 12665l, 12406l, 12140l, 11866l,
  115025. 11585l, 11297l, 11003l, 10702l,
  115026. 10394l, 10080l, 9760l, 9434l,
  115027. 9102l, 8765l, 8423l, 8076l,
  115028. 7723l, 7366l, 7005l, 6639l,
  115029. 6270l, 5897l, 5520l, 5139l,
  115030. 4756l, 4370l, 3981l, 3590l,
  115031. 3196l, 2801l, 2404l, 2006l,
  115032. 1606l, 1205l, 804l, 402l,
  115033. 0l, -401l, -803l, -1204l,
  115034. -1605l, -2005l, -2403l, -2800l,
  115035. -3195l, -3589l, -3980l, -4369l,
  115036. -4755l, -5138l, -5519l, -5896l,
  115037. -6269l, -6638l, -7004l, -7365l,
  115038. -7722l, -8075l, -8422l, -8764l,
  115039. -9101l, -9433l, -9759l, -10079l,
  115040. -10393l, -10701l, -11002l, -11296l,
  115041. -11584l, -11865l, -12139l, -12405l,
  115042. -12664l, -12915l, -13159l, -13394l,
  115043. -13622l, -13841l, -14052l, -14255l,
  115044. -14448l, -14634l, -14810l, -14977l,
  115045. -15136l, -15285l, -15425l, -15556l,
  115046. -15678l, -15790l, -15892l, -15985l,
  115047. -16068l, -16142l, -16206l, -16260l,
  115048. -16304l, -16339l, -16363l, -16378l,
  115049. -16383l,
  115050. };
  115051. #endif
  115052. #endif
  115053. /*** End of inlined file: lookup_data.h ***/
  115054. #ifdef FLOAT_LOOKUP
  115055. /* interpolated lookup based cos function, domain 0 to PI only */
  115056. float vorbis_coslook(float a){
  115057. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  115058. int i=vorbis_ftoi(d-.5);
  115059. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  115060. }
  115061. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115062. float vorbis_invsqlook(float a){
  115063. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  115064. int i=vorbis_ftoi(d-.5f);
  115065. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  115066. }
  115067. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  115068. float vorbis_invsq2explook(int a){
  115069. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  115070. }
  115071. #include <stdio.h>
  115072. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115073. float vorbis_fromdBlook(float a){
  115074. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  115075. return (i<0)?1.f:
  115076. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115077. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115078. }
  115079. #endif
  115080. #ifdef INT_LOOKUP
  115081. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  115082. 16.16 format
  115083. returns in m.8 format */
  115084. long vorbis_invsqlook_i(long a,long e){
  115085. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  115086. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  115087. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  115088. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  115089. d)>>16); /* result 1.16 */
  115090. e+=32;
  115091. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  115092. e=(e>>1)-8;
  115093. return(val>>e);
  115094. }
  115095. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  115096. /* a is in n.12 format */
  115097. float vorbis_fromdBlook_i(long a){
  115098. int i=(-a)>>(12-FROMdB2_SHIFT);
  115099. return (i<0)?1.f:
  115100. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  115101. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  115102. }
  115103. /* interpolated lookup based cos function, domain 0 to PI only */
  115104. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  115105. long vorbis_coslook_i(long a){
  115106. int i=a>>COS_LOOKUP_I_SHIFT;
  115107. int d=a&COS_LOOKUP_I_MASK;
  115108. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  115109. COS_LOOKUP_I_SHIFT);
  115110. }
  115111. #endif
  115112. #endif
  115113. /*** End of inlined file: lookup.c ***/
  115114. /* catch this in the build system; we #include for
  115115. compilers (like gcc) that can't inline across
  115116. modules */
  115117. static int MLOOP_1[64]={
  115118. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  115119. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  115120. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115121. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  115122. };
  115123. static int MLOOP_2[64]={
  115124. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  115125. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  115126. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115127. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  115128. };
  115129. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  115130. /* side effect: changes *lsp to cosines of lsp */
  115131. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115132. float amp,float ampoffset){
  115133. /* 0 <= m < 256 */
  115134. /* set up for using all int later */
  115135. int i;
  115136. int ampoffseti=rint(ampoffset*4096.f);
  115137. int ampi=rint(amp*16.f);
  115138. long *ilsp=alloca(m*sizeof(*ilsp));
  115139. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  115140. i=0;
  115141. while(i<n){
  115142. int j,k=map[i];
  115143. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  115144. unsigned long qi=46341;
  115145. int qexp=0,shift;
  115146. long wi=vorbis_coslook_i(k*65536/ln);
  115147. qi*=labs(ilsp[0]-wi);
  115148. pi*=labs(ilsp[1]-wi);
  115149. for(j=3;j<m;j+=2){
  115150. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115151. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115152. shift=MLOOP_3[(pi|qi)>>16];
  115153. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115154. pi=(pi>>shift)*labs(ilsp[j]-wi);
  115155. qexp+=shift;
  115156. }
  115157. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115158. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115159. shift=MLOOP_3[(pi|qi)>>16];
  115160. /* pi,qi normalized collectively, both tracked using qexp */
  115161. if(m&1){
  115162. /* odd order filter; slightly assymetric */
  115163. /* the last coefficient */
  115164. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  115165. pi=(pi>>shift)<<14;
  115166. qexp+=shift;
  115167. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  115168. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  115169. shift=MLOOP_3[(pi|qi)>>16];
  115170. pi>>=shift;
  115171. qi>>=shift;
  115172. qexp+=shift-14*((m+1)>>1);
  115173. pi=((pi*pi)>>16);
  115174. qi=((qi*qi)>>16);
  115175. qexp=qexp*2+m;
  115176. pi*=(1<<14)-((wi*wi)>>14);
  115177. qi+=pi>>14;
  115178. }else{
  115179. /* even order filter; still symmetric */
  115180. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  115181. worth tracking step by step */
  115182. pi>>=shift;
  115183. qi>>=shift;
  115184. qexp+=shift-7*m;
  115185. pi=((pi*pi)>>16);
  115186. qi=((qi*qi)>>16);
  115187. qexp=qexp*2+m;
  115188. pi*=(1<<14)-wi;
  115189. qi*=(1<<14)+wi;
  115190. qi=(qi+pi)>>14;
  115191. }
  115192. /* we've let the normalization drift because it wasn't important;
  115193. however, for the lookup, things must be normalized again. We
  115194. need at most one right shift or a number of left shifts */
  115195. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  115196. qi>>=1; qexp++;
  115197. }else
  115198. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  115199. qi<<=1; qexp--;
  115200. }
  115201. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  115202. vorbis_invsqlook_i(qi,qexp)-
  115203. /* m.8, m+n<=8 */
  115204. ampoffseti); /* 8.12[0] */
  115205. curve[i]*=amp;
  115206. while(map[++i]==k)curve[i]*=amp;
  115207. }
  115208. }
  115209. #else
  115210. /* old, nonoptimized but simple version for any poor sap who needs to
  115211. figure out what the hell this code does, or wants the other
  115212. fraction of a dB precision */
  115213. /* side effect: changes *lsp to cosines of lsp */
  115214. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  115215. float amp,float ampoffset){
  115216. int i;
  115217. float wdel=M_PI/ln;
  115218. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  115219. i=0;
  115220. while(i<n){
  115221. int j,k=map[i];
  115222. float p=.5f;
  115223. float q=.5f;
  115224. float w=2.f*cos(wdel*k);
  115225. for(j=1;j<m;j+=2){
  115226. q *= w-lsp[j-1];
  115227. p *= w-lsp[j];
  115228. }
  115229. if(j==m){
  115230. /* odd order filter; slightly assymetric */
  115231. /* the last coefficient */
  115232. q*=w-lsp[j-1];
  115233. p*=p*(4.f-w*w);
  115234. q*=q;
  115235. }else{
  115236. /* even order filter; still symmetric */
  115237. p*=p*(2.f-w);
  115238. q*=q*(2.f+w);
  115239. }
  115240. q=fromdB(amp/sqrt(p+q)-ampoffset);
  115241. curve[i]*=q;
  115242. while(map[++i]==k)curve[i]*=q;
  115243. }
  115244. }
  115245. #endif
  115246. #endif
  115247. static void cheby(float *g, int ord) {
  115248. int i, j;
  115249. g[0] *= .5f;
  115250. for(i=2; i<= ord; i++) {
  115251. for(j=ord; j >= i; j--) {
  115252. g[j-2] -= g[j];
  115253. g[j] += g[j];
  115254. }
  115255. }
  115256. }
  115257. static int JUCE_CDECL comp(const void *a,const void *b){
  115258. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  115259. }
  115260. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  115261. but there are root sets for which it gets into limit cycles
  115262. (exacerbated by zero suppression) and fails. We can't afford to
  115263. fail, even if the failure is 1 in 100,000,000, so we now use
  115264. Laguerre and later polish with Newton-Raphson (which can then
  115265. afford to fail) */
  115266. #define EPSILON 10e-7
  115267. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  115268. int i,m;
  115269. double lastdelta=0.f;
  115270. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  115271. for(i=0;i<=ord;i++)defl[i]=a[i];
  115272. for(m=ord;m>0;m--){
  115273. double newx=0.f,delta;
  115274. /* iterate a root */
  115275. while(1){
  115276. double p=defl[m],pp=0.f,ppp=0.f,denom;
  115277. /* eval the polynomial and its first two derivatives */
  115278. for(i=m;i>0;i--){
  115279. ppp = newx*ppp + pp;
  115280. pp = newx*pp + p;
  115281. p = newx*p + defl[i-1];
  115282. }
  115283. /* Laguerre's method */
  115284. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  115285. if(denom<0)
  115286. return(-1); /* complex root! The LPC generator handed us a bad filter */
  115287. if(pp>0){
  115288. denom = pp + sqrt(denom);
  115289. if(denom<EPSILON)denom=EPSILON;
  115290. }else{
  115291. denom = pp - sqrt(denom);
  115292. if(denom>-(EPSILON))denom=-(EPSILON);
  115293. }
  115294. delta = m*p/denom;
  115295. newx -= delta;
  115296. if(delta<0.f)delta*=-1;
  115297. if(fabs(delta/newx)<10e-12)break;
  115298. lastdelta=delta;
  115299. }
  115300. r[m-1]=newx;
  115301. /* forward deflation */
  115302. for(i=m;i>0;i--)
  115303. defl[i-1]+=newx*defl[i];
  115304. defl++;
  115305. }
  115306. return(0);
  115307. }
  115308. /* for spit-and-polish only */
  115309. static int Newton_Raphson(float *a,int ord,float *r){
  115310. int i, k, count=0;
  115311. double error=1.f;
  115312. double *root=(double*)alloca(ord*sizeof(*root));
  115313. for(i=0; i<ord;i++) root[i] = r[i];
  115314. while(error>1e-20){
  115315. error=0;
  115316. for(i=0; i<ord; i++) { /* Update each point. */
  115317. double pp=0.,delta;
  115318. double rooti=root[i];
  115319. double p=a[ord];
  115320. for(k=ord-1; k>= 0; k--) {
  115321. pp= pp* rooti + p;
  115322. p = p * rooti + a[k];
  115323. }
  115324. delta = p/pp;
  115325. root[i] -= delta;
  115326. error+= delta*delta;
  115327. }
  115328. if(count>40)return(-1);
  115329. count++;
  115330. }
  115331. /* Replaced the original bubble sort with a real sort. With your
  115332. help, we can eliminate the bubble sort in our lifetime. --Monty */
  115333. for(i=0; i<ord;i++) r[i] = root[i];
  115334. return(0);
  115335. }
  115336. /* Convert lpc coefficients to lsp coefficients */
  115337. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  115338. int order2=(m+1)>>1;
  115339. int g1_order,g2_order;
  115340. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  115341. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  115342. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  115343. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  115344. int i;
  115345. /* even and odd are slightly different base cases */
  115346. g1_order=(m+1)>>1;
  115347. g2_order=(m) >>1;
  115348. /* Compute the lengths of the x polynomials. */
  115349. /* Compute the first half of K & R F1 & F2 polynomials. */
  115350. /* Compute half of the symmetric and antisymmetric polynomials. */
  115351. /* Remove the roots at +1 and -1. */
  115352. g1[g1_order] = 1.f;
  115353. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  115354. g2[g2_order] = 1.f;
  115355. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  115356. if(g1_order>g2_order){
  115357. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  115358. }else{
  115359. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  115360. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  115361. }
  115362. /* Convert into polynomials in cos(alpha) */
  115363. cheby(g1,g1_order);
  115364. cheby(g2,g2_order);
  115365. /* Find the roots of the 2 even polynomials.*/
  115366. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  115367. Laguerre_With_Deflation(g2,g2_order,g2r))
  115368. return(-1);
  115369. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  115370. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  115371. qsort(g1r,g1_order,sizeof(*g1r),comp);
  115372. qsort(g2r,g2_order,sizeof(*g2r),comp);
  115373. for(i=0;i<g1_order;i++)
  115374. lsp[i*2] = acos(g1r[i]);
  115375. for(i=0;i<g2_order;i++)
  115376. lsp[i*2+1] = acos(g2r[i]);
  115377. return(0);
  115378. }
  115379. #endif
  115380. /*** End of inlined file: lsp.c ***/
  115381. /*** Start of inlined file: mapping0.c ***/
  115382. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  115383. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115384. // tasks..
  115385. #if JUCE_MSVC
  115386. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115387. #endif
  115388. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  115389. #if JUCE_USE_OGGVORBIS
  115390. #include <stdlib.h>
  115391. #include <stdio.h>
  115392. #include <string.h>
  115393. #include <math.h>
  115394. /* simplistic, wasteful way of doing this (unique lookup for each
  115395. mode/submapping); there should be a central repository for
  115396. identical lookups. That will require minor work, so I'm putting it
  115397. off as low priority.
  115398. Why a lookup for each backend in a given mode? Because the
  115399. blocksize is set by the mode, and low backend lookups may require
  115400. parameters from other areas of the mode/mapping */
  115401. static void mapping0_free_info(vorbis_info_mapping *i){
  115402. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  115403. if(info){
  115404. memset(info,0,sizeof(*info));
  115405. _ogg_free(info);
  115406. }
  115407. }
  115408. static int ilog3(unsigned int v){
  115409. int ret=0;
  115410. if(v)--v;
  115411. while(v){
  115412. ret++;
  115413. v>>=1;
  115414. }
  115415. return(ret);
  115416. }
  115417. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  115418. oggpack_buffer *opb){
  115419. int i;
  115420. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  115421. /* another 'we meant to do it this way' hack... up to beta 4, we
  115422. packed 4 binary zeros here to signify one submapping in use. We
  115423. now redefine that to mean four bitflags that indicate use of
  115424. deeper features; bit0:submappings, bit1:coupling,
  115425. bit2,3:reserved. This is backward compatable with all actual uses
  115426. of the beta code. */
  115427. if(info->submaps>1){
  115428. oggpack_write(opb,1,1);
  115429. oggpack_write(opb,info->submaps-1,4);
  115430. }else
  115431. oggpack_write(opb,0,1);
  115432. if(info->coupling_steps>0){
  115433. oggpack_write(opb,1,1);
  115434. oggpack_write(opb,info->coupling_steps-1,8);
  115435. for(i=0;i<info->coupling_steps;i++){
  115436. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  115437. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  115438. }
  115439. }else
  115440. oggpack_write(opb,0,1);
  115441. oggpack_write(opb,0,2); /* 2,3:reserved */
  115442. /* we don't write the channel submappings if we only have one... */
  115443. if(info->submaps>1){
  115444. for(i=0;i<vi->channels;i++)
  115445. oggpack_write(opb,info->chmuxlist[i],4);
  115446. }
  115447. for(i=0;i<info->submaps;i++){
  115448. oggpack_write(opb,0,8); /* time submap unused */
  115449. oggpack_write(opb,info->floorsubmap[i],8);
  115450. oggpack_write(opb,info->residuesubmap[i],8);
  115451. }
  115452. }
  115453. /* also responsible for range checking */
  115454. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  115455. int i;
  115456. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  115457. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115458. memset(info,0,sizeof(*info));
  115459. if(oggpack_read(opb,1))
  115460. info->submaps=oggpack_read(opb,4)+1;
  115461. else
  115462. info->submaps=1;
  115463. if(oggpack_read(opb,1)){
  115464. info->coupling_steps=oggpack_read(opb,8)+1;
  115465. for(i=0;i<info->coupling_steps;i++){
  115466. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  115467. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  115468. if(testM<0 ||
  115469. testA<0 ||
  115470. testM==testA ||
  115471. testM>=vi->channels ||
  115472. testA>=vi->channels) goto err_out;
  115473. }
  115474. }
  115475. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  115476. if(info->submaps>1){
  115477. for(i=0;i<vi->channels;i++){
  115478. info->chmuxlist[i]=oggpack_read(opb,4);
  115479. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  115480. }
  115481. }
  115482. for(i=0;i<info->submaps;i++){
  115483. oggpack_read(opb,8); /* time submap unused */
  115484. info->floorsubmap[i]=oggpack_read(opb,8);
  115485. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  115486. info->residuesubmap[i]=oggpack_read(opb,8);
  115487. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  115488. }
  115489. return info;
  115490. err_out:
  115491. mapping0_free_info(info);
  115492. return(NULL);
  115493. }
  115494. #if 0
  115495. static long seq=0;
  115496. static ogg_int64_t total=0;
  115497. static float FLOOR1_fromdB_LOOKUP[256]={
  115498. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  115499. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  115500. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  115501. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  115502. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  115503. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  115504. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  115505. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  115506. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  115507. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  115508. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  115509. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  115510. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  115511. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  115512. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  115513. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  115514. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  115515. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  115516. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  115517. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  115518. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  115519. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  115520. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  115521. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  115522. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  115523. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  115524. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  115525. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  115526. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  115527. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  115528. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  115529. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  115530. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  115531. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  115532. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  115533. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  115534. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  115535. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  115536. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  115537. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  115538. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  115539. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  115540. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  115541. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  115542. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  115543. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  115544. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  115545. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  115546. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  115547. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  115548. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  115549. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  115550. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  115551. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  115552. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  115553. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  115554. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  115555. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  115556. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  115557. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  115558. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  115559. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  115560. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  115561. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  115562. };
  115563. #endif
  115564. extern int *floor1_fit(vorbis_block *vb,void *look,
  115565. const float *logmdct, /* in */
  115566. const float *logmask);
  115567. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  115568. int *A,int *B,
  115569. int del);
  115570. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  115571. void*look,
  115572. int *post,int *ilogmask);
  115573. static int mapping0_forward(vorbis_block *vb){
  115574. vorbis_dsp_state *vd=vb->vd;
  115575. vorbis_info *vi=vd->vi;
  115576. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  115577. private_state *b=(private_state*)vb->vd->backend_state;
  115578. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  115579. int n=vb->pcmend;
  115580. int i,j,k;
  115581. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  115582. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  115583. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  115584. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  115585. float global_ampmax=vbi->ampmax;
  115586. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  115587. int blocktype=vbi->blocktype;
  115588. int modenumber=vb->W;
  115589. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  115590. vorbis_look_psy *psy_look=
  115591. b->psy+blocktype+(vb->W?2:0);
  115592. vb->mode=modenumber;
  115593. for(i=0;i<vi->channels;i++){
  115594. float scale=4.f/n;
  115595. float scale_dB;
  115596. float *pcm =vb->pcm[i];
  115597. float *logfft =pcm;
  115598. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115599. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  115600. todB estimation used on IEEE 754
  115601. compliant machines had a bug that
  115602. returned dB values about a third
  115603. of a decibel too high. The bug
  115604. was harmless because tunings
  115605. implicitly took that into
  115606. account. However, fixing the bug
  115607. in the estimator requires
  115608. changing all the tunings as well.
  115609. For now, it's easier to sync
  115610. things back up here, and
  115611. recalibrate the tunings in the
  115612. next major model upgrade. */
  115613. #if 0
  115614. if(vi->channels==2)
  115615. if(i==0)
  115616. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  115617. else
  115618. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  115619. #endif
  115620. /* window the PCM data */
  115621. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  115622. #if 0
  115623. if(vi->channels==2)
  115624. if(i==0)
  115625. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  115626. else
  115627. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  115628. #endif
  115629. /* transform the PCM data */
  115630. /* only MDCT right now.... */
  115631. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  115632. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  115633. drft_forward(&b->fft_look[vb->W],pcm);
  115634. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  115635. original todB estimation used on
  115636. IEEE 754 compliant machines had a
  115637. bug that returned dB values about
  115638. a third of a decibel too high.
  115639. The bug was harmless because
  115640. tunings implicitly took that into
  115641. account. However, fixing the bug
  115642. in the estimator requires
  115643. changing all the tunings as well.
  115644. For now, it's easier to sync
  115645. things back up here, and
  115646. recalibrate the tunings in the
  115647. next major model upgrade. */
  115648. local_ampmax[i]=logfft[0];
  115649. for(j=1;j<n-1;j+=2){
  115650. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  115651. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  115652. .345 is a hack; the original todB
  115653. estimation used on IEEE 754
  115654. compliant machines had a bug that
  115655. returned dB values about a third
  115656. of a decibel too high. The bug
  115657. was harmless because tunings
  115658. implicitly took that into
  115659. account. However, fixing the bug
  115660. in the estimator requires
  115661. changing all the tunings as well.
  115662. For now, it's easier to sync
  115663. things back up here, and
  115664. recalibrate the tunings in the
  115665. next major model upgrade. */
  115666. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  115667. }
  115668. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  115669. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  115670. #if 0
  115671. if(vi->channels==2){
  115672. if(i==0){
  115673. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  115674. }else{
  115675. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  115676. }
  115677. }
  115678. #endif
  115679. }
  115680. {
  115681. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  115682. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  115683. for(i=0;i<vi->channels;i++){
  115684. /* the encoder setup assumes that all the modes used by any
  115685. specific bitrate tweaking use the same floor */
  115686. int submap=info->chmuxlist[i];
  115687. /* the following makes things clearer to *me* anyway */
  115688. float *mdct =gmdct[i];
  115689. float *logfft =vb->pcm[i];
  115690. float *logmdct =logfft+n/2;
  115691. float *logmask =logfft;
  115692. vb->mode=modenumber;
  115693. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  115694. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  115695. for(j=0;j<n/2;j++)
  115696. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  115697. todB estimation used on IEEE 754
  115698. compliant machines had a bug that
  115699. returned dB values about a third
  115700. of a decibel too high. The bug
  115701. was harmless because tunings
  115702. implicitly took that into
  115703. account. However, fixing the bug
  115704. in the estimator requires
  115705. changing all the tunings as well.
  115706. For now, it's easier to sync
  115707. things back up here, and
  115708. recalibrate the tunings in the
  115709. next major model upgrade. */
  115710. #if 0
  115711. if(vi->channels==2){
  115712. if(i==0)
  115713. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  115714. else
  115715. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  115716. }else{
  115717. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  115718. }
  115719. #endif
  115720. /* first step; noise masking. Not only does 'noise masking'
  115721. give us curves from which we can decide how much resolution
  115722. to give noise parts of the spectrum, it also implicitly hands
  115723. us a tonality estimate (the larger the value in the
  115724. 'noise_depth' vector, the more tonal that area is) */
  115725. _vp_noisemask(psy_look,
  115726. logmdct,
  115727. noise); /* noise does not have by-frequency offset
  115728. bias applied yet */
  115729. #if 0
  115730. if(vi->channels==2){
  115731. if(i==0)
  115732. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  115733. else
  115734. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  115735. }
  115736. #endif
  115737. /* second step: 'all the other crap'; all the stuff that isn't
  115738. computed/fit for bitrate management goes in the second psy
  115739. vector. This includes tone masking, peak limiting and ATH */
  115740. _vp_tonemask(psy_look,
  115741. logfft,
  115742. tone,
  115743. global_ampmax,
  115744. local_ampmax[i]);
  115745. #if 0
  115746. if(vi->channels==2){
  115747. if(i==0)
  115748. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  115749. else
  115750. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  115751. }
  115752. #endif
  115753. /* third step; we offset the noise vectors, overlay tone
  115754. masking. We then do a floor1-specific line fit. If we're
  115755. performing bitrate management, the line fit is performed
  115756. multiple times for up/down tweakage on demand. */
  115757. #if 0
  115758. {
  115759. float aotuv[psy_look->n];
  115760. #endif
  115761. _vp_offset_and_mix(psy_look,
  115762. noise,
  115763. tone,
  115764. 1,
  115765. logmask,
  115766. mdct,
  115767. logmdct);
  115768. #if 0
  115769. if(vi->channels==2){
  115770. if(i==0)
  115771. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  115772. else
  115773. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  115774. }
  115775. }
  115776. #endif
  115777. #if 0
  115778. if(vi->channels==2){
  115779. if(i==0)
  115780. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  115781. else
  115782. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  115783. }
  115784. #endif
  115785. /* this algorithm is hardwired to floor 1 for now; abort out if
  115786. we're *not* floor1. This won't happen unless someone has
  115787. broken the encode setup lib. Guard it anyway. */
  115788. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  115789. floor_posts[i][PACKETBLOBS/2]=
  115790. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115791. logmdct,
  115792. logmask);
  115793. /* are we managing bitrate? If so, perform two more fits for
  115794. later rate tweaking (fits represent hi/lo) */
  115795. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  115796. /* higher rate by way of lower noise curve */
  115797. _vp_offset_and_mix(psy_look,
  115798. noise,
  115799. tone,
  115800. 2,
  115801. logmask,
  115802. mdct,
  115803. logmdct);
  115804. #if 0
  115805. if(vi->channels==2){
  115806. if(i==0)
  115807. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  115808. else
  115809. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  115810. }
  115811. #endif
  115812. floor_posts[i][PACKETBLOBS-1]=
  115813. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115814. logmdct,
  115815. logmask);
  115816. /* lower rate by way of higher noise curve */
  115817. _vp_offset_and_mix(psy_look,
  115818. noise,
  115819. tone,
  115820. 0,
  115821. logmask,
  115822. mdct,
  115823. logmdct);
  115824. #if 0
  115825. if(vi->channels==2)
  115826. if(i==0)
  115827. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115828. else
  115829. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115830. #endif
  115831. floor_posts[i][0]=
  115832. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115833. logmdct,
  115834. logmask);
  115835. /* we also interpolate a range of intermediate curves for
  115836. intermediate rates */
  115837. for(k=1;k<PACKETBLOBS/2;k++)
  115838. floor_posts[i][k]=
  115839. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115840. floor_posts[i][0],
  115841. floor_posts[i][PACKETBLOBS/2],
  115842. k*65536/(PACKETBLOBS/2));
  115843. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115844. floor_posts[i][k]=
  115845. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115846. floor_posts[i][PACKETBLOBS/2],
  115847. floor_posts[i][PACKETBLOBS-1],
  115848. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115849. }
  115850. }
  115851. }
  115852. vbi->ampmax=global_ampmax;
  115853. /*
  115854. the next phases are performed once for vbr-only and PACKETBLOB
  115855. times for bitrate managed modes.
  115856. 1) encode actual mode being used
  115857. 2) encode the floor for each channel, compute coded mask curve/res
  115858. 3) normalize and couple.
  115859. 4) encode residue
  115860. 5) save packet bytes to the packetblob vector
  115861. */
  115862. /* iterate over the many masking curve fits we've created */
  115863. {
  115864. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115865. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115866. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115867. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115868. float **mag_memo;
  115869. int **mag_sort;
  115870. if(info->coupling_steps){
  115871. mag_memo=_vp_quantize_couple_memo(vb,
  115872. &ci->psy_g_param,
  115873. psy_look,
  115874. info,
  115875. gmdct);
  115876. mag_sort=_vp_quantize_couple_sort(vb,
  115877. psy_look,
  115878. info,
  115879. mag_memo);
  115880. hf_reduction(&ci->psy_g_param,
  115881. psy_look,
  115882. info,
  115883. mag_memo);
  115884. }
  115885. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115886. if(psy_look->vi->normal_channel_p){
  115887. for(i=0;i<vi->channels;i++){
  115888. float *mdct =gmdct[i];
  115889. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115890. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115891. }
  115892. }
  115893. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115894. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115895. k++){
  115896. oggpack_buffer *opb=vbi->packetblob[k];
  115897. /* start out our new packet blob with packet type and mode */
  115898. /* Encode the packet type */
  115899. oggpack_write(opb,0,1);
  115900. /* Encode the modenumber */
  115901. /* Encode frame mode, pre,post windowsize, then dispatch */
  115902. oggpack_write(opb,modenumber,b->modebits);
  115903. if(vb->W){
  115904. oggpack_write(opb,vb->lW,1);
  115905. oggpack_write(opb,vb->nW,1);
  115906. }
  115907. /* encode floor, compute masking curve, sep out residue */
  115908. for(i=0;i<vi->channels;i++){
  115909. int submap=info->chmuxlist[i];
  115910. float *mdct =gmdct[i];
  115911. float *res =vb->pcm[i];
  115912. int *ilogmask=ilogmaskch[i]=
  115913. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115914. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115915. floor_posts[i][k],
  115916. ilogmask);
  115917. #if 0
  115918. {
  115919. char buf[80];
  115920. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115921. float work[n/2];
  115922. for(j=0;j<n/2;j++)
  115923. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115924. _analysis_output(buf,seq,work,n/2,1,1,0);
  115925. }
  115926. #endif
  115927. _vp_remove_floor(psy_look,
  115928. mdct,
  115929. ilogmask,
  115930. res,
  115931. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115932. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115933. #if 0
  115934. {
  115935. char buf[80];
  115936. float work[n/2];
  115937. for(j=0;j<n/2;j++)
  115938. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115939. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115940. _analysis_output(buf,seq,work,n/2,1,1,0);
  115941. }
  115942. #endif
  115943. }
  115944. /* our iteration is now based on masking curve, not prequant and
  115945. coupling. Only one prequant/coupling step */
  115946. /* quantize/couple */
  115947. /* incomplete implementation that assumes the tree is all depth
  115948. one, or no tree at all */
  115949. if(info->coupling_steps){
  115950. _vp_couple(k,
  115951. &ci->psy_g_param,
  115952. psy_look,
  115953. info,
  115954. vb->pcm,
  115955. mag_memo,
  115956. mag_sort,
  115957. ilogmaskch,
  115958. nonzero,
  115959. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115960. }
  115961. /* classify and encode by submap */
  115962. for(i=0;i<info->submaps;i++){
  115963. int ch_in_bundle=0;
  115964. long **classifications;
  115965. int resnum=info->residuesubmap[i];
  115966. for(j=0;j<vi->channels;j++){
  115967. if(info->chmuxlist[j]==i){
  115968. zerobundle[ch_in_bundle]=0;
  115969. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115970. res_bundle[ch_in_bundle]=vb->pcm[j];
  115971. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115972. }
  115973. }
  115974. classifications=_residue_P[ci->residue_type[resnum]]->
  115975. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115976. _residue_P[ci->residue_type[resnum]]->
  115977. forward(opb,vb,b->residue[resnum],
  115978. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115979. }
  115980. /* ok, done encoding. Next protopacket. */
  115981. }
  115982. }
  115983. #if 0
  115984. seq++;
  115985. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115986. #endif
  115987. return(0);
  115988. }
  115989. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115990. vorbis_dsp_state *vd=vb->vd;
  115991. vorbis_info *vi=vd->vi;
  115992. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115993. private_state *b=(private_state*)vd->backend_state;
  115994. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115995. int i,j;
  115996. long n=vb->pcmend=ci->blocksizes[vb->W];
  115997. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115998. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115999. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  116000. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  116001. /* recover the spectral envelope; store it in the PCM vector for now */
  116002. for(i=0;i<vi->channels;i++){
  116003. int submap=info->chmuxlist[i];
  116004. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116005. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  116006. if(floormemo[i])
  116007. nonzero[i]=1;
  116008. else
  116009. nonzero[i]=0;
  116010. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  116011. }
  116012. /* channel coupling can 'dirty' the nonzero listing */
  116013. for(i=0;i<info->coupling_steps;i++){
  116014. if(nonzero[info->coupling_mag[i]] ||
  116015. nonzero[info->coupling_ang[i]]){
  116016. nonzero[info->coupling_mag[i]]=1;
  116017. nonzero[info->coupling_ang[i]]=1;
  116018. }
  116019. }
  116020. /* recover the residue into our working vectors */
  116021. for(i=0;i<info->submaps;i++){
  116022. int ch_in_bundle=0;
  116023. for(j=0;j<vi->channels;j++){
  116024. if(info->chmuxlist[j]==i){
  116025. if(nonzero[j])
  116026. zerobundle[ch_in_bundle]=1;
  116027. else
  116028. zerobundle[ch_in_bundle]=0;
  116029. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  116030. }
  116031. }
  116032. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  116033. inverse(vb,b->residue[info->residuesubmap[i]],
  116034. pcmbundle,zerobundle,ch_in_bundle);
  116035. }
  116036. /* channel coupling */
  116037. for(i=info->coupling_steps-1;i>=0;i--){
  116038. float *pcmM=vb->pcm[info->coupling_mag[i]];
  116039. float *pcmA=vb->pcm[info->coupling_ang[i]];
  116040. for(j=0;j<n/2;j++){
  116041. float mag=pcmM[j];
  116042. float ang=pcmA[j];
  116043. if(mag>0)
  116044. if(ang>0){
  116045. pcmM[j]=mag;
  116046. pcmA[j]=mag-ang;
  116047. }else{
  116048. pcmA[j]=mag;
  116049. pcmM[j]=mag+ang;
  116050. }
  116051. else
  116052. if(ang>0){
  116053. pcmM[j]=mag;
  116054. pcmA[j]=mag+ang;
  116055. }else{
  116056. pcmA[j]=mag;
  116057. pcmM[j]=mag-ang;
  116058. }
  116059. }
  116060. }
  116061. /* compute and apply spectral envelope */
  116062. for(i=0;i<vi->channels;i++){
  116063. float *pcm=vb->pcm[i];
  116064. int submap=info->chmuxlist[i];
  116065. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  116066. inverse2(vb,b->flr[info->floorsubmap[submap]],
  116067. floormemo[i],pcm);
  116068. }
  116069. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  116070. /* only MDCT right now.... */
  116071. for(i=0;i<vi->channels;i++){
  116072. float *pcm=vb->pcm[i];
  116073. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  116074. }
  116075. /* all done! */
  116076. return(0);
  116077. }
  116078. /* export hooks */
  116079. vorbis_func_mapping mapping0_exportbundle={
  116080. &mapping0_pack,
  116081. &mapping0_unpack,
  116082. &mapping0_free_info,
  116083. &mapping0_forward,
  116084. &mapping0_inverse
  116085. };
  116086. #endif
  116087. /*** End of inlined file: mapping0.c ***/
  116088. /*** Start of inlined file: mdct.c ***/
  116089. /* this can also be run as an integer transform by uncommenting a
  116090. define in mdct.h; the integerization is a first pass and although
  116091. it's likely stable for Vorbis, the dynamic range is constrained and
  116092. roundoff isn't done (so it's noisy). Consider it functional, but
  116093. only a starting point. There's no point on a machine with an FPU */
  116094. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116095. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116096. // tasks..
  116097. #if JUCE_MSVC
  116098. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116099. #endif
  116100. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116101. #if JUCE_USE_OGGVORBIS
  116102. #include <stdio.h>
  116103. #include <stdlib.h>
  116104. #include <string.h>
  116105. #include <math.h>
  116106. /* build lookups for trig functions; also pre-figure scaling and
  116107. some window function algebra. */
  116108. void mdct_init(mdct_lookup *lookup,int n){
  116109. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  116110. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  116111. int i;
  116112. int n2=n>>1;
  116113. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  116114. lookup->n=n;
  116115. lookup->trig=T;
  116116. lookup->bitrev=bitrev;
  116117. /* trig lookups... */
  116118. for(i=0;i<n/4;i++){
  116119. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  116120. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  116121. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  116122. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  116123. }
  116124. for(i=0;i<n/8;i++){
  116125. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  116126. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  116127. }
  116128. /* bitreverse lookup... */
  116129. {
  116130. int mask=(1<<(log2n-1))-1,i,j;
  116131. int msb=1<<(log2n-2);
  116132. for(i=0;i<n/8;i++){
  116133. int acc=0;
  116134. for(j=0;msb>>j;j++)
  116135. if((msb>>j)&i)acc|=1<<j;
  116136. bitrev[i*2]=((~acc)&mask)-1;
  116137. bitrev[i*2+1]=acc;
  116138. }
  116139. }
  116140. lookup->scale=FLOAT_CONV(4.f/n);
  116141. }
  116142. /* 8 point butterfly (in place, 4 register) */
  116143. STIN void mdct_butterfly_8(DATA_TYPE *x){
  116144. REG_TYPE r0 = x[6] + x[2];
  116145. REG_TYPE r1 = x[6] - x[2];
  116146. REG_TYPE r2 = x[4] + x[0];
  116147. REG_TYPE r3 = x[4] - x[0];
  116148. x[6] = r0 + r2;
  116149. x[4] = r0 - r2;
  116150. r0 = x[5] - x[1];
  116151. r2 = x[7] - x[3];
  116152. x[0] = r1 + r0;
  116153. x[2] = r1 - r0;
  116154. r0 = x[5] + x[1];
  116155. r1 = x[7] + x[3];
  116156. x[3] = r2 + r3;
  116157. x[1] = r2 - r3;
  116158. x[7] = r1 + r0;
  116159. x[5] = r1 - r0;
  116160. }
  116161. /* 16 point butterfly (in place, 4 register) */
  116162. STIN void mdct_butterfly_16(DATA_TYPE *x){
  116163. REG_TYPE r0 = x[1] - x[9];
  116164. REG_TYPE r1 = x[0] - x[8];
  116165. x[8] += x[0];
  116166. x[9] += x[1];
  116167. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  116168. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  116169. r0 = x[3] - x[11];
  116170. r1 = x[10] - x[2];
  116171. x[10] += x[2];
  116172. x[11] += x[3];
  116173. x[2] = r0;
  116174. x[3] = r1;
  116175. r0 = x[12] - x[4];
  116176. r1 = x[13] - x[5];
  116177. x[12] += x[4];
  116178. x[13] += x[5];
  116179. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  116180. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  116181. r0 = x[14] - x[6];
  116182. r1 = x[15] - x[7];
  116183. x[14] += x[6];
  116184. x[15] += x[7];
  116185. x[6] = r0;
  116186. x[7] = r1;
  116187. mdct_butterfly_8(x);
  116188. mdct_butterfly_8(x+8);
  116189. }
  116190. /* 32 point butterfly (in place, 4 register) */
  116191. STIN void mdct_butterfly_32(DATA_TYPE *x){
  116192. REG_TYPE r0 = x[30] - x[14];
  116193. REG_TYPE r1 = x[31] - x[15];
  116194. x[30] += x[14];
  116195. x[31] += x[15];
  116196. x[14] = r0;
  116197. x[15] = r1;
  116198. r0 = x[28] - x[12];
  116199. r1 = x[29] - x[13];
  116200. x[28] += x[12];
  116201. x[29] += x[13];
  116202. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  116203. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  116204. r0 = x[26] - x[10];
  116205. r1 = x[27] - x[11];
  116206. x[26] += x[10];
  116207. x[27] += x[11];
  116208. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  116209. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  116210. r0 = x[24] - x[8];
  116211. r1 = x[25] - x[9];
  116212. x[24] += x[8];
  116213. x[25] += x[9];
  116214. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  116215. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116216. r0 = x[22] - x[6];
  116217. r1 = x[7] - x[23];
  116218. x[22] += x[6];
  116219. x[23] += x[7];
  116220. x[6] = r1;
  116221. x[7] = r0;
  116222. r0 = x[4] - x[20];
  116223. r1 = x[5] - x[21];
  116224. x[20] += x[4];
  116225. x[21] += x[5];
  116226. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  116227. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  116228. r0 = x[2] - x[18];
  116229. r1 = x[3] - x[19];
  116230. x[18] += x[2];
  116231. x[19] += x[3];
  116232. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  116233. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  116234. r0 = x[0] - x[16];
  116235. r1 = x[1] - x[17];
  116236. x[16] += x[0];
  116237. x[17] += x[1];
  116238. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  116239. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  116240. mdct_butterfly_16(x);
  116241. mdct_butterfly_16(x+16);
  116242. }
  116243. /* N point first stage butterfly (in place, 2 register) */
  116244. STIN void mdct_butterfly_first(DATA_TYPE *T,
  116245. DATA_TYPE *x,
  116246. int points){
  116247. DATA_TYPE *x1 = x + points - 8;
  116248. DATA_TYPE *x2 = x + (points>>1) - 8;
  116249. REG_TYPE r0;
  116250. REG_TYPE r1;
  116251. do{
  116252. r0 = x1[6] - x2[6];
  116253. r1 = x1[7] - x2[7];
  116254. x1[6] += x2[6];
  116255. x1[7] += x2[7];
  116256. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116257. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116258. r0 = x1[4] - x2[4];
  116259. r1 = x1[5] - x2[5];
  116260. x1[4] += x2[4];
  116261. x1[5] += x2[5];
  116262. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  116263. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  116264. r0 = x1[2] - x2[2];
  116265. r1 = x1[3] - x2[3];
  116266. x1[2] += x2[2];
  116267. x1[3] += x2[3];
  116268. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  116269. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  116270. r0 = x1[0] - x2[0];
  116271. r1 = x1[1] - x2[1];
  116272. x1[0] += x2[0];
  116273. x1[1] += x2[1];
  116274. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  116275. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  116276. x1-=8;
  116277. x2-=8;
  116278. T+=16;
  116279. }while(x2>=x);
  116280. }
  116281. /* N/stage point generic N stage butterfly (in place, 2 register) */
  116282. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  116283. DATA_TYPE *x,
  116284. int points,
  116285. int trigint){
  116286. DATA_TYPE *x1 = x + points - 8;
  116287. DATA_TYPE *x2 = x + (points>>1) - 8;
  116288. REG_TYPE r0;
  116289. REG_TYPE r1;
  116290. do{
  116291. r0 = x1[6] - x2[6];
  116292. r1 = x1[7] - x2[7];
  116293. x1[6] += x2[6];
  116294. x1[7] += x2[7];
  116295. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116296. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116297. T+=trigint;
  116298. r0 = x1[4] - x2[4];
  116299. r1 = x1[5] - x2[5];
  116300. x1[4] += x2[4];
  116301. x1[5] += x2[5];
  116302. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116303. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116304. T+=trigint;
  116305. r0 = x1[2] - x2[2];
  116306. r1 = x1[3] - x2[3];
  116307. x1[2] += x2[2];
  116308. x1[3] += x2[3];
  116309. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116310. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116311. T+=trigint;
  116312. r0 = x1[0] - x2[0];
  116313. r1 = x1[1] - x2[1];
  116314. x1[0] += x2[0];
  116315. x1[1] += x2[1];
  116316. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  116317. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  116318. T+=trigint;
  116319. x1-=8;
  116320. x2-=8;
  116321. }while(x2>=x);
  116322. }
  116323. STIN void mdct_butterflies(mdct_lookup *init,
  116324. DATA_TYPE *x,
  116325. int points){
  116326. DATA_TYPE *T=init->trig;
  116327. int stages=init->log2n-5;
  116328. int i,j;
  116329. if(--stages>0){
  116330. mdct_butterfly_first(T,x,points);
  116331. }
  116332. for(i=1;--stages>0;i++){
  116333. for(j=0;j<(1<<i);j++)
  116334. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  116335. }
  116336. for(j=0;j<points;j+=32)
  116337. mdct_butterfly_32(x+j);
  116338. }
  116339. void mdct_clear(mdct_lookup *l){
  116340. if(l){
  116341. if(l->trig)_ogg_free(l->trig);
  116342. if(l->bitrev)_ogg_free(l->bitrev);
  116343. memset(l,0,sizeof(*l));
  116344. }
  116345. }
  116346. STIN void mdct_bitreverse(mdct_lookup *init,
  116347. DATA_TYPE *x){
  116348. int n = init->n;
  116349. int *bit = init->bitrev;
  116350. DATA_TYPE *w0 = x;
  116351. DATA_TYPE *w1 = x = w0+(n>>1);
  116352. DATA_TYPE *T = init->trig+n;
  116353. do{
  116354. DATA_TYPE *x0 = x+bit[0];
  116355. DATA_TYPE *x1 = x+bit[1];
  116356. REG_TYPE r0 = x0[1] - x1[1];
  116357. REG_TYPE r1 = x0[0] + x1[0];
  116358. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  116359. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  116360. w1 -= 4;
  116361. r0 = HALVE(x0[1] + x1[1]);
  116362. r1 = HALVE(x0[0] - x1[0]);
  116363. w0[0] = r0 + r2;
  116364. w1[2] = r0 - r2;
  116365. w0[1] = r1 + r3;
  116366. w1[3] = r3 - r1;
  116367. x0 = x+bit[2];
  116368. x1 = x+bit[3];
  116369. r0 = x0[1] - x1[1];
  116370. r1 = x0[0] + x1[0];
  116371. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  116372. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  116373. r0 = HALVE(x0[1] + x1[1]);
  116374. r1 = HALVE(x0[0] - x1[0]);
  116375. w0[2] = r0 + r2;
  116376. w1[0] = r0 - r2;
  116377. w0[3] = r1 + r3;
  116378. w1[1] = r3 - r1;
  116379. T += 4;
  116380. bit += 4;
  116381. w0 += 4;
  116382. }while(w0<w1);
  116383. }
  116384. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116385. int n=init->n;
  116386. int n2=n>>1;
  116387. int n4=n>>2;
  116388. /* rotate */
  116389. DATA_TYPE *iX = in+n2-7;
  116390. DATA_TYPE *oX = out+n2+n4;
  116391. DATA_TYPE *T = init->trig+n4;
  116392. do{
  116393. oX -= 4;
  116394. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  116395. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  116396. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  116397. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  116398. iX -= 8;
  116399. T += 4;
  116400. }while(iX>=in);
  116401. iX = in+n2-8;
  116402. oX = out+n2+n4;
  116403. T = init->trig+n4;
  116404. do{
  116405. T -= 4;
  116406. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  116407. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  116408. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  116409. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  116410. iX -= 8;
  116411. oX += 4;
  116412. }while(iX>=in);
  116413. mdct_butterflies(init,out+n2,n2);
  116414. mdct_bitreverse(init,out);
  116415. /* roatate + window */
  116416. {
  116417. DATA_TYPE *oX1=out+n2+n4;
  116418. DATA_TYPE *oX2=out+n2+n4;
  116419. DATA_TYPE *iX =out;
  116420. T =init->trig+n2;
  116421. do{
  116422. oX1-=4;
  116423. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  116424. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  116425. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  116426. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  116427. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  116428. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  116429. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  116430. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  116431. oX2+=4;
  116432. iX += 8;
  116433. T += 8;
  116434. }while(iX<oX1);
  116435. iX=out+n2+n4;
  116436. oX1=out+n4;
  116437. oX2=oX1;
  116438. do{
  116439. oX1-=4;
  116440. iX-=4;
  116441. oX2[0] = -(oX1[3] = iX[3]);
  116442. oX2[1] = -(oX1[2] = iX[2]);
  116443. oX2[2] = -(oX1[1] = iX[1]);
  116444. oX2[3] = -(oX1[0] = iX[0]);
  116445. oX2+=4;
  116446. }while(oX2<iX);
  116447. iX=out+n2+n4;
  116448. oX1=out+n2+n4;
  116449. oX2=out+n2;
  116450. do{
  116451. oX1-=4;
  116452. oX1[0]= iX[3];
  116453. oX1[1]= iX[2];
  116454. oX1[2]= iX[1];
  116455. oX1[3]= iX[0];
  116456. iX+=4;
  116457. }while(oX1>oX2);
  116458. }
  116459. }
  116460. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  116461. int n=init->n;
  116462. int n2=n>>1;
  116463. int n4=n>>2;
  116464. int n8=n>>3;
  116465. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  116466. DATA_TYPE *w2=w+n2;
  116467. /* rotate */
  116468. /* window + rotate + step 1 */
  116469. REG_TYPE r0;
  116470. REG_TYPE r1;
  116471. DATA_TYPE *x0=in+n2+n4;
  116472. DATA_TYPE *x1=x0+1;
  116473. DATA_TYPE *T=init->trig+n2;
  116474. int i=0;
  116475. for(i=0;i<n8;i+=2){
  116476. x0 -=4;
  116477. T-=2;
  116478. r0= x0[2] + x1[0];
  116479. r1= x0[0] + x1[2];
  116480. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116481. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116482. x1 +=4;
  116483. }
  116484. x1=in+1;
  116485. for(;i<n2-n8;i+=2){
  116486. T-=2;
  116487. x0 -=4;
  116488. r0= x0[2] - x1[0];
  116489. r1= x0[0] - x1[2];
  116490. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116491. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116492. x1 +=4;
  116493. }
  116494. x0=in+n;
  116495. for(;i<n2;i+=2){
  116496. T-=2;
  116497. x0 -=4;
  116498. r0= -x0[2] - x1[0];
  116499. r1= -x0[0] - x1[2];
  116500. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  116501. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  116502. x1 +=4;
  116503. }
  116504. mdct_butterflies(init,w+n2,n2);
  116505. mdct_bitreverse(init,w);
  116506. /* roatate + window */
  116507. T=init->trig+n2;
  116508. x0=out+n2;
  116509. for(i=0;i<n4;i++){
  116510. x0--;
  116511. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  116512. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  116513. w+=2;
  116514. T+=2;
  116515. }
  116516. }
  116517. #endif
  116518. /*** End of inlined file: mdct.c ***/
  116519. /*** Start of inlined file: psy.c ***/
  116520. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  116521. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  116522. // tasks..
  116523. #if JUCE_MSVC
  116524. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116525. #endif
  116526. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  116527. #if JUCE_USE_OGGVORBIS
  116528. #include <stdlib.h>
  116529. #include <math.h>
  116530. #include <string.h>
  116531. /*** Start of inlined file: masking.h ***/
  116532. #ifndef _V_MASKING_H_
  116533. #define _V_MASKING_H_
  116534. /* more detailed ATH; the bass if flat to save stressing the floor
  116535. overly for only a bin or two of savings. */
  116536. #define MAX_ATH 88
  116537. static float ATH[]={
  116538. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116539. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116540. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116541. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116542. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116543. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116544. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116545. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116546. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116547. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116548. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116549. };
  116550. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116551. replaced by an empirically collected data set. The previously
  116552. published values were, far too often, simply on crack. */
  116553. #define EHMER_OFFSET 16
  116554. #define EHMER_MAX 56
  116555. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116556. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116557. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116558. for collection of these curves) */
  116559. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116560. /* 62.5 Hz */
  116561. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116562. -60, -60, -60, -60, -62, -62, -65, -73,
  116563. -69, -68, -68, -67, -70, -70, -72, -74,
  116564. -75, -79, -79, -80, -83, -88, -93, -100,
  116565. -110, -999, -999, -999, -999, -999, -999, -999,
  116566. -999, -999, -999, -999, -999, -999, -999, -999,
  116567. -999, -999, -999, -999, -999, -999, -999, -999},
  116568. { -48, -48, -48, -48, -48, -48, -48, -48,
  116569. -48, -48, -48, -48, -48, -53, -61, -66,
  116570. -66, -68, -67, -70, -76, -76, -72, -73,
  116571. -75, -76, -78, -79, -83, -88, -93, -100,
  116572. -110, -999, -999, -999, -999, -999, -999, -999,
  116573. -999, -999, -999, -999, -999, -999, -999, -999,
  116574. -999, -999, -999, -999, -999, -999, -999, -999},
  116575. { -37, -37, -37, -37, -37, -37, -37, -37,
  116576. -38, -40, -42, -46, -48, -53, -55, -62,
  116577. -65, -58, -56, -56, -61, -60, -65, -67,
  116578. -69, -71, -77, -77, -78, -80, -82, -84,
  116579. -88, -93, -98, -106, -112, -999, -999, -999,
  116580. -999, -999, -999, -999, -999, -999, -999, -999,
  116581. -999, -999, -999, -999, -999, -999, -999, -999},
  116582. { -25, -25, -25, -25, -25, -25, -25, -25,
  116583. -25, -26, -27, -29, -32, -38, -48, -52,
  116584. -52, -50, -48, -48, -51, -52, -54, -60,
  116585. -67, -67, -66, -68, -69, -73, -73, -76,
  116586. -80, -81, -81, -85, -85, -86, -88, -93,
  116587. -100, -110, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -999, -999, -999, -999},
  116589. { -16, -16, -16, -16, -16, -16, -16, -16,
  116590. -17, -19, -20, -22, -26, -28, -31, -40,
  116591. -47, -39, -39, -40, -42, -43, -47, -51,
  116592. -57, -52, -55, -55, -60, -58, -62, -63,
  116593. -70, -67, -69, -72, -73, -77, -80, -82,
  116594. -83, -87, -90, -94, -98, -104, -115, -999,
  116595. -999, -999, -999, -999, -999, -999, -999, -999},
  116596. { -8, -8, -8, -8, -8, -8, -8, -8,
  116597. -8, -8, -10, -11, -15, -19, -25, -30,
  116598. -34, -31, -30, -31, -29, -32, -35, -42,
  116599. -48, -42, -44, -46, -50, -50, -51, -52,
  116600. -59, -54, -55, -55, -58, -62, -63, -66,
  116601. -72, -73, -76, -75, -78, -80, -80, -81,
  116602. -84, -88, -90, -94, -98, -101, -106, -110}},
  116603. /* 88Hz */
  116604. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116605. -66, -66, -66, -66, -66, -67, -67, -67,
  116606. -76, -72, -71, -74, -76, -76, -75, -78,
  116607. -79, -79, -81, -83, -86, -89, -93, -97,
  116608. -100, -105, -110, -999, -999, -999, -999, -999,
  116609. -999, -999, -999, -999, -999, -999, -999, -999,
  116610. -999, -999, -999, -999, -999, -999, -999, -999},
  116611. { -47, -47, -47, -47, -47, -47, -47, -47,
  116612. -47, -47, -47, -48, -51, -55, -59, -66,
  116613. -66, -66, -67, -66, -68, -69, -70, -74,
  116614. -79, -77, -77, -78, -80, -81, -82, -84,
  116615. -86, -88, -91, -95, -100, -108, -116, -999,
  116616. -999, -999, -999, -999, -999, -999, -999, -999,
  116617. -999, -999, -999, -999, -999, -999, -999, -999},
  116618. { -36, -36, -36, -36, -36, -36, -36, -36,
  116619. -36, -37, -37, -41, -44, -48, -51, -58,
  116620. -62, -60, -57, -59, -59, -60, -63, -65,
  116621. -72, -71, -70, -72, -74, -77, -76, -78,
  116622. -81, -81, -80, -83, -86, -91, -96, -100,
  116623. -105, -110, -999, -999, -999, -999, -999, -999,
  116624. -999, -999, -999, -999, -999, -999, -999, -999},
  116625. { -28, -28, -28, -28, -28, -28, -28, -28,
  116626. -28, -30, -32, -32, -33, -35, -41, -49,
  116627. -50, -49, -47, -48, -48, -52, -51, -57,
  116628. -65, -61, -59, -61, -64, -69, -70, -74,
  116629. -77, -77, -78, -81, -84, -85, -87, -90,
  116630. -92, -96, -100, -107, -112, -999, -999, -999,
  116631. -999, -999, -999, -999, -999, -999, -999, -999},
  116632. { -19, -19, -19, -19, -19, -19, -19, -19,
  116633. -20, -21, -23, -27, -30, -35, -36, -41,
  116634. -46, -44, -42, -40, -41, -41, -43, -48,
  116635. -55, -53, -52, -53, -56, -59, -58, -60,
  116636. -67, -66, -69, -71, -72, -75, -79, -81,
  116637. -84, -87, -90, -93, -97, -101, -107, -114,
  116638. -999, -999, -999, -999, -999, -999, -999, -999},
  116639. { -9, -9, -9, -9, -9, -9, -9, -9,
  116640. -11, -12, -12, -15, -16, -20, -23, -30,
  116641. -37, -34, -33, -34, -31, -32, -32, -38,
  116642. -47, -44, -41, -40, -47, -49, -46, -46,
  116643. -58, -50, -50, -54, -58, -62, -64, -67,
  116644. -67, -70, -72, -76, -79, -83, -87, -91,
  116645. -96, -100, -104, -110, -999, -999, -999, -999}},
  116646. /* 125 Hz */
  116647. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116648. -62, -62, -63, -64, -66, -67, -66, -68,
  116649. -75, -72, -76, -75, -76, -78, -79, -82,
  116650. -84, -85, -90, -94, -101, -110, -999, -999,
  116651. -999, -999, -999, -999, -999, -999, -999, -999,
  116652. -999, -999, -999, -999, -999, -999, -999, -999,
  116653. -999, -999, -999, -999, -999, -999, -999, -999},
  116654. { -59, -59, -59, -59, -59, -59, -59, -59,
  116655. -59, -59, -59, -60, -60, -61, -63, -66,
  116656. -71, -68, -70, -70, -71, -72, -72, -75,
  116657. -81, -78, -79, -82, -83, -86, -90, -97,
  116658. -103, -113, -999, -999, -999, -999, -999, -999,
  116659. -999, -999, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -999, -999, -999, -999},
  116661. { -53, -53, -53, -53, -53, -53, -53, -53,
  116662. -53, -54, -55, -57, -56, -57, -55, -61,
  116663. -65, -60, -60, -62, -63, -63, -66, -68,
  116664. -74, -73, -75, -75, -78, -80, -80, -82,
  116665. -85, -90, -96, -101, -108, -999, -999, -999,
  116666. -999, -999, -999, -999, -999, -999, -999, -999,
  116667. -999, -999, -999, -999, -999, -999, -999, -999},
  116668. { -46, -46, -46, -46, -46, -46, -46, -46,
  116669. -46, -46, -47, -47, -47, -47, -48, -51,
  116670. -57, -51, -49, -50, -51, -53, -54, -59,
  116671. -66, -60, -62, -67, -67, -70, -72, -75,
  116672. -76, -78, -81, -85, -88, -94, -97, -104,
  116673. -112, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -999, -999, -999, -999, -999},
  116675. { -36, -36, -36, -36, -36, -36, -36, -36,
  116676. -39, -41, -42, -42, -39, -38, -41, -43,
  116677. -52, -44, -40, -39, -37, -37, -40, -47,
  116678. -54, -50, -48, -50, -55, -61, -59, -62,
  116679. -66, -66, -66, -69, -69, -73, -74, -74,
  116680. -75, -77, -79, -82, -87, -91, -95, -100,
  116681. -108, -115, -999, -999, -999, -999, -999, -999},
  116682. { -28, -26, -24, -22, -20, -20, -23, -29,
  116683. -30, -31, -28, -27, -28, -28, -28, -35,
  116684. -40, -33, -32, -29, -30, -30, -30, -37,
  116685. -45, -41, -37, -38, -45, -47, -47, -48,
  116686. -53, -49, -48, -50, -49, -49, -51, -52,
  116687. -58, -56, -57, -56, -60, -61, -62, -70,
  116688. -72, -74, -78, -83, -88, -93, -100, -106}},
  116689. /* 177 Hz */
  116690. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116691. -999, -110, -105, -100, -95, -91, -87, -83,
  116692. -80, -78, -76, -78, -78, -81, -83, -85,
  116693. -86, -85, -86, -87, -90, -97, -107, -999,
  116694. -999, -999, -999, -999, -999, -999, -999, -999,
  116695. -999, -999, -999, -999, -999, -999, -999, -999,
  116696. -999, -999, -999, -999, -999, -999, -999, -999},
  116697. {-999, -999, -999, -110, -105, -100, -95, -90,
  116698. -85, -81, -77, -73, -70, -67, -67, -68,
  116699. -75, -73, -70, -69, -70, -72, -75, -79,
  116700. -84, -83, -84, -86, -88, -89, -89, -93,
  116701. -98, -105, -112, -999, -999, -999, -999, -999,
  116702. -999, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -999, -999, -999},
  116704. {-105, -100, -95, -90, -85, -80, -76, -71,
  116705. -68, -68, -65, -63, -63, -62, -62, -64,
  116706. -65, -64, -61, -62, -63, -64, -66, -68,
  116707. -73, -73, -74, -75, -76, -81, -83, -85,
  116708. -88, -89, -92, -95, -100, -108, -999, -999,
  116709. -999, -999, -999, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -999, -999, -999},
  116711. { -80, -75, -71, -68, -65, -63, -62, -61,
  116712. -61, -61, -61, -59, -56, -57, -53, -50,
  116713. -58, -52, -50, -50, -52, -53, -54, -58,
  116714. -67, -63, -67, -68, -72, -75, -78, -80,
  116715. -81, -81, -82, -85, -89, -90, -93, -97,
  116716. -101, -107, -114, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -999, -999, -999},
  116718. { -65, -61, -59, -57, -56, -55, -55, -56,
  116719. -56, -57, -55, -53, -52, -47, -44, -44,
  116720. -50, -44, -41, -39, -39, -42, -40, -46,
  116721. -51, -49, -50, -53, -54, -63, -60, -61,
  116722. -62, -66, -66, -66, -70, -73, -74, -75,
  116723. -76, -75, -79, -85, -89, -91, -96, -102,
  116724. -110, -999, -999, -999, -999, -999, -999, -999},
  116725. { -52, -50, -49, -49, -48, -48, -48, -49,
  116726. -50, -50, -49, -46, -43, -39, -35, -33,
  116727. -38, -36, -32, -29, -32, -32, -32, -35,
  116728. -44, -39, -38, -38, -46, -50, -45, -46,
  116729. -53, -50, -50, -50, -54, -54, -53, -53,
  116730. -56, -57, -59, -66, -70, -72, -74, -79,
  116731. -83, -85, -90, -97, -114, -999, -999, -999}},
  116732. /* 250 Hz */
  116733. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116734. -100, -95, -90, -86, -80, -75, -75, -79,
  116735. -80, -79, -80, -81, -82, -88, -95, -103,
  116736. -110, -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, -999, -999, -999, -999, -999},
  116740. {-999, -999, -999, -999, -108, -103, -98, -93,
  116741. -88, -83, -79, -78, -75, -71, -67, -68,
  116742. -73, -73, -72, -73, -75, -77, -80, -82,
  116743. -88, -93, -100, -107, -114, -999, -999, -999,
  116744. -999, -999, -999, -999, -999, -999, -999, -999,
  116745. -999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -999, -999, -999, -999, -999},
  116747. {-999, -999, -999, -110, -105, -101, -96, -90,
  116748. -86, -81, -77, -73, -69, -66, -61, -62,
  116749. -66, -64, -62, -65, -66, -70, -72, -76,
  116750. -81, -80, -84, -90, -95, -102, -110, -999,
  116751. -999, -999, -999, -999, -999, -999, -999, -999,
  116752. -999, -999, -999, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -999, -999, -999, -999, -999},
  116754. {-999, -999, -999, -107, -103, -97, -92, -88,
  116755. -83, -79, -74, -70, -66, -59, -53, -58,
  116756. -62, -55, -54, -54, -54, -58, -61, -62,
  116757. -72, -70, -72, -75, -78, -80, -81, -80,
  116758. -83, -83, -88, -93, -100, -107, -115, -999,
  116759. -999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -999, -999, -999, -999, -999},
  116761. {-999, -999, -999, -105, -100, -95, -90, -85,
  116762. -80, -75, -70, -66, -62, -56, -48, -44,
  116763. -48, -46, -46, -43, -46, -48, -48, -51,
  116764. -58, -58, -59, -60, -62, -62, -61, -61,
  116765. -65, -64, -65, -68, -70, -74, -75, -78,
  116766. -81, -86, -95, -110, -999, -999, -999, -999,
  116767. -999, -999, -999, -999, -999, -999, -999, -999},
  116768. {-999, -999, -105, -100, -95, -90, -85, -80,
  116769. -75, -70, -65, -61, -55, -49, -39, -33,
  116770. -40, -35, -32, -38, -40, -33, -35, -37,
  116771. -46, -41, -45, -44, -46, -42, -45, -46,
  116772. -52, -50, -50, -50, -54, -54, -55, -57,
  116773. -62, -64, -66, -68, -70, -76, -81, -90,
  116774. -100, -110, -999, -999, -999, -999, -999, -999}},
  116775. /* 354 hz */
  116776. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116777. -105, -98, -90, -85, -82, -83, -80, -78,
  116778. -84, -79, -80, -83, -87, -89, -91, -93,
  116779. -99, -106, -117, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  116784. -105, -98, -90, -85, -80, -75, -70, -68,
  116785. -74, -72, -74, -77, -80, -82, -85, -87,
  116786. -92, -89, -91, -95, -100, -106, -112, -999,
  116787. -999, -999, -999, -999, -999, -999, -999, -999,
  116788. -999, -999, -999, -999, -999, -999, -999, -999,
  116789. -999, -999, -999, -999, -999, -999, -999, -999},
  116790. {-999, -999, -999, -999, -999, -999, -999, -999,
  116791. -105, -98, -90, -83, -75, -71, -63, -64,
  116792. -67, -62, -64, -67, -70, -73, -77, -81,
  116793. -84, -83, -85, -89, -90, -93, -98, -104,
  116794. -109, -114, -999, -999, -999, -999, -999, -999,
  116795. -999, -999, -999, -999, -999, -999, -999, -999,
  116796. -999, -999, -999, -999, -999, -999, -999, -999},
  116797. {-999, -999, -999, -999, -999, -999, -999, -999,
  116798. -103, -96, -88, -81, -75, -68, -58, -54,
  116799. -56, -54, -56, -56, -58, -60, -63, -66,
  116800. -74, -69, -72, -72, -75, -74, -77, -81,
  116801. -81, -82, -84, -87, -93, -96, -99, -104,
  116802. -110, -999, -999, -999, -999, -999, -999, -999,
  116803. -999, -999, -999, -999, -999, -999, -999, -999},
  116804. {-999, -999, -999, -999, -999, -108, -102, -96,
  116805. -91, -85, -80, -74, -68, -60, -51, -46,
  116806. -48, -46, -43, -45, -47, -47, -49, -48,
  116807. -56, -53, -55, -58, -57, -63, -58, -60,
  116808. -66, -64, -67, -70, -70, -74, -77, -84,
  116809. -86, -89, -91, -93, -94, -101, -109, -118,
  116810. -999, -999, -999, -999, -999, -999, -999, -999},
  116811. {-999, -999, -999, -108, -103, -98, -93, -88,
  116812. -83, -78, -73, -68, -60, -53, -44, -35,
  116813. -38, -38, -34, -34, -36, -40, -41, -44,
  116814. -51, -45, -46, -47, -46, -54, -50, -49,
  116815. -50, -50, -50, -51, -54, -57, -58, -60,
  116816. -66, -66, -66, -64, -65, -68, -77, -82,
  116817. -87, -95, -110, -999, -999, -999, -999, -999}},
  116818. /* 500 Hz */
  116819. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116820. -107, -102, -97, -92, -87, -83, -78, -75,
  116821. -82, -79, -83, -85, -89, -92, -95, -98,
  116822. -101, -105, -109, -113, -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, -999, -999, -999},
  116826. {-999, -999, -999, -999, -999, -999, -999, -106,
  116827. -100, -95, -90, -86, -81, -78, -74, -69,
  116828. -74, -74, -76, -79, -83, -84, -86, -89,
  116829. -92, -97, -93, -100, -103, -107, -110, -999,
  116830. -999, -999, -999, -999, -999, -999, -999, -999,
  116831. -999, -999, -999, -999, -999, -999, -999, -999,
  116832. -999, -999, -999, -999, -999, -999, -999, -999},
  116833. {-999, -999, -999, -999, -999, -999, -106, -100,
  116834. -95, -90, -87, -83, -80, -75, -69, -60,
  116835. -66, -66, -68, -70, -74, -78, -79, -81,
  116836. -81, -83, -84, -87, -93, -96, -99, -103,
  116837. -107, -110, -999, -999, -999, -999, -999, -999,
  116838. -999, -999, -999, -999, -999, -999, -999, -999,
  116839. -999, -999, -999, -999, -999, -999, -999, -999},
  116840. {-999, -999, -999, -999, -999, -108, -103, -98,
  116841. -93, -89, -85, -82, -78, -71, -62, -55,
  116842. -58, -58, -54, -54, -55, -59, -61, -62,
  116843. -70, -66, -66, -67, -70, -72, -75, -78,
  116844. -84, -84, -84, -88, -91, -90, -95, -98,
  116845. -102, -103, -106, -110, -999, -999, -999, -999,
  116846. -999, -999, -999, -999, -999, -999, -999, -999},
  116847. {-999, -999, -999, -999, -108, -103, -98, -94,
  116848. -90, -87, -82, -79, -73, -67, -58, -47,
  116849. -50, -45, -41, -45, -48, -44, -44, -49,
  116850. -54, -51, -48, -47, -49, -50, -51, -57,
  116851. -58, -60, -63, -69, -70, -69, -71, -74,
  116852. -78, -82, -90, -95, -101, -105, -110, -999,
  116853. -999, -999, -999, -999, -999, -999, -999, -999},
  116854. {-999, -999, -999, -105, -101, -97, -93, -90,
  116855. -85, -80, -77, -72, -65, -56, -48, -37,
  116856. -40, -36, -34, -40, -50, -47, -38, -41,
  116857. -47, -38, -35, -39, -38, -43, -40, -45,
  116858. -50, -45, -44, -47, -50, -55, -48, -48,
  116859. -52, -66, -70, -76, -82, -90, -97, -105,
  116860. -110, -999, -999, -999, -999, -999, -999, -999}},
  116861. /* 707 Hz */
  116862. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116863. -999, -108, -103, -98, -93, -86, -79, -76,
  116864. -83, -81, -85, -87, -89, -93, -98, -102,
  116865. -107, -112, -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. {-999, -999, -999, -999, -999, -999, -999, -999,
  116870. -999, -108, -103, -98, -93, -86, -79, -71,
  116871. -77, -74, -77, -79, -81, -84, -85, -90,
  116872. -92, -93, -92, -98, -101, -108, -112, -999,
  116873. -999, -999, -999, -999, -999, -999, -999, -999,
  116874. -999, -999, -999, -999, -999, -999, -999, -999,
  116875. -999, -999, -999, -999, -999, -999, -999, -999},
  116876. {-999, -999, -999, -999, -999, -999, -999, -999,
  116877. -108, -103, -98, -93, -87, -78, -68, -65,
  116878. -66, -62, -65, -67, -70, -73, -75, -78,
  116879. -82, -82, -83, -84, -91, -93, -98, -102,
  116880. -106, -110, -999, -999, -999, -999, -999, -999,
  116881. -999, -999, -999, -999, -999, -999, -999, -999,
  116882. -999, -999, -999, -999, -999, -999, -999, -999},
  116883. {-999, -999, -999, -999, -999, -999, -999, -999,
  116884. -105, -100, -95, -90, -82, -74, -62, -57,
  116885. -58, -56, -51, -52, -52, -54, -54, -58,
  116886. -66, -59, -60, -63, -66, -69, -73, -79,
  116887. -83, -84, -80, -81, -81, -82, -88, -92,
  116888. -98, -105, -113, -999, -999, -999, -999, -999,
  116889. -999, -999, -999, -999, -999, -999, -999, -999},
  116890. {-999, -999, -999, -999, -999, -999, -999, -107,
  116891. -102, -97, -92, -84, -79, -69, -57, -47,
  116892. -52, -47, -44, -45, -50, -52, -42, -42,
  116893. -53, -43, -43, -48, -51, -56, -55, -52,
  116894. -57, -59, -61, -62, -67, -71, -78, -83,
  116895. -86, -94, -98, -103, -110, -999, -999, -999,
  116896. -999, -999, -999, -999, -999, -999, -999, -999},
  116897. {-999, -999, -999, -999, -999, -999, -105, -100,
  116898. -95, -90, -84, -78, -70, -61, -51, -41,
  116899. -40, -38, -40, -46, -52, -51, -41, -40,
  116900. -46, -40, -38, -38, -41, -46, -41, -46,
  116901. -47, -43, -43, -45, -41, -45, -56, -67,
  116902. -68, -83, -87, -90, -95, -102, -107, -113,
  116903. -999, -999, -999, -999, -999, -999, -999, -999}},
  116904. /* 1000 Hz */
  116905. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116906. -999, -109, -105, -101, -96, -91, -84, -77,
  116907. -82, -82, -85, -89, -94, -100, -106, -110,
  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, -999},
  116912. {-999, -999, -999, -999, -999, -999, -999, -999,
  116913. -999, -106, -103, -98, -92, -85, -80, -71,
  116914. -75, -72, -76, -80, -84, -86, -89, -93,
  116915. -100, -107, -113, -999, -999, -999, -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, -999, -999},
  116919. {-999, -999, -999, -999, -999, -999, -999, -107,
  116920. -104, -101, -97, -92, -88, -84, -80, -64,
  116921. -66, -63, -64, -66, -69, -73, -77, -83,
  116922. -83, -86, -91, -98, -104, -111, -999, -999,
  116923. -999, -999, -999, -999, -999, -999, -999, -999,
  116924. -999, -999, -999, -999, -999, -999, -999, -999,
  116925. -999, -999, -999, -999, -999, -999, -999, -999},
  116926. {-999, -999, -999, -999, -999, -999, -999, -107,
  116927. -104, -101, -97, -92, -90, -84, -74, -57,
  116928. -58, -52, -55, -54, -50, -52, -50, -52,
  116929. -63, -62, -69, -76, -77, -78, -78, -79,
  116930. -82, -88, -94, -100, -106, -111, -999, -999,
  116931. -999, -999, -999, -999, -999, -999, -999, -999,
  116932. -999, -999, -999, -999, -999, -999, -999, -999},
  116933. {-999, -999, -999, -999, -999, -999, -106, -102,
  116934. -98, -95, -90, -85, -83, -78, -70, -50,
  116935. -50, -41, -44, -49, -47, -50, -50, -44,
  116936. -55, -46, -47, -48, -48, -54, -49, -49,
  116937. -58, -62, -71, -81, -87, -92, -97, -102,
  116938. -108, -114, -999, -999, -999, -999, -999, -999,
  116939. -999, -999, -999, -999, -999, -999, -999, -999},
  116940. {-999, -999, -999, -999, -999, -999, -106, -102,
  116941. -98, -95, -90, -85, -83, -78, -70, -45,
  116942. -43, -41, -47, -50, -51, -50, -49, -45,
  116943. -47, -41, -44, -41, -39, -43, -38, -37,
  116944. -40, -41, -44, -50, -58, -65, -73, -79,
  116945. -85, -92, -97, -101, -105, -109, -113, -999,
  116946. -999, -999, -999, -999, -999, -999, -999, -999}},
  116947. /* 1414 Hz */
  116948. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116949. -999, -999, -999, -107, -100, -95, -87, -81,
  116950. -85, -83, -88, -93, -100, -107, -114, -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, -999, -999, -999, -999, -999, -999,
  116956. -999, -999, -107, -101, -95, -88, -83, -76,
  116957. -73, -72, -79, -84, -90, -95, -100, -105,
  116958. -110, -115, -999, -999, -999, -999, -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, -999},
  116962. {-999, -999, -999, -999, -999, -999, -999, -999,
  116963. -999, -999, -104, -98, -92, -87, -81, -70,
  116964. -65, -62, -67, -71, -74, -80, -85, -91,
  116965. -95, -99, -103, -108, -111, -114, -999, -999,
  116966. -999, -999, -999, -999, -999, -999, -999, -999,
  116967. -999, -999, -999, -999, -999, -999, -999, -999,
  116968. -999, -999, -999, -999, -999, -999, -999, -999},
  116969. {-999, -999, -999, -999, -999, -999, -999, -999,
  116970. -999, -999, -103, -97, -90, -85, -76, -60,
  116971. -56, -54, -60, -62, -61, -56, -63, -65,
  116972. -73, -74, -77, -75, -78, -81, -86, -87,
  116973. -88, -91, -94, -98, -103, -110, -999, -999,
  116974. -999, -999, -999, -999, -999, -999, -999, -999,
  116975. -999, -999, -999, -999, -999, -999, -999, -999},
  116976. {-999, -999, -999, -999, -999, -999, -999, -105,
  116977. -100, -97, -92, -86, -81, -79, -70, -57,
  116978. -51, -47, -51, -58, -60, -56, -53, -50,
  116979. -58, -52, -50, -50, -53, -55, -64, -69,
  116980. -71, -85, -82, -78, -81, -85, -95, -102,
  116981. -112, -999, -999, -999, -999, -999, -999, -999,
  116982. -999, -999, -999, -999, -999, -999, -999, -999},
  116983. {-999, -999, -999, -999, -999, -999, -999, -105,
  116984. -100, -97, -92, -85, -83, -79, -72, -49,
  116985. -40, -43, -43, -54, -56, -51, -50, -40,
  116986. -43, -38, -36, -35, -37, -38, -37, -44,
  116987. -54, -60, -57, -60, -70, -75, -84, -92,
  116988. -103, -112, -999, -999, -999, -999, -999, -999,
  116989. -999, -999, -999, -999, -999, -999, -999, -999}},
  116990. /* 2000 Hz */
  116991. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116992. -999, -999, -999, -110, -102, -95, -89, -82,
  116993. -83, -84, -90, -92, -99, -107, -113, -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, -999, -999, -999, -999, -999, -999, -999,
  116999. -999, -999, -107, -101, -95, -89, -83, -72,
  117000. -74, -78, -85, -88, -88, -90, -92, -98,
  117001. -105, -111, -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, -999, -999, -999, -999, -999, -999, -999,
  117006. -999, -109, -103, -97, -93, -87, -81, -70,
  117007. -70, -67, -75, -73, -76, -79, -81, -83,
  117008. -88, -89, -97, -103, -110, -999, -999, -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, -999, -999, -999, -999, -999, -999, -999,
  117013. -999, -107, -100, -94, -88, -83, -75, -63,
  117014. -59, -59, -63, -66, -60, -62, -67, -67,
  117015. -77, -76, -81, -88, -86, -92, -96, -102,
  117016. -109, -116, -999, -999, -999, -999, -999, -999,
  117017. -999, -999, -999, -999, -999, -999, -999, -999,
  117018. -999, -999, -999, -999, -999, -999, -999, -999},
  117019. {-999, -999, -999, -999, -999, -999, -999, -999,
  117020. -999, -105, -98, -92, -86, -81, -73, -56,
  117021. -52, -47, -55, -60, -58, -52, -51, -45,
  117022. -49, -50, -53, -54, -61, -71, -70, -69,
  117023. -78, -79, -87, -90, -96, -104, -112, -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, -103, -96, -90, -86, -78, -70, -51,
  117028. -42, -47, -48, -55, -54, -54, -53, -42,
  117029. -35, -28, -33, -38, -37, -44, -47, -49,
  117030. -54, -63, -68, -78, -82, -89, -94, -99,
  117031. -104, -109, -114, -999, -999, -999, -999, -999,
  117032. -999, -999, -999, -999, -999, -999, -999, -999}},
  117033. /* 2828 Hz */
  117034. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117035. -999, -999, -999, -999, -110, -100, -90, -79,
  117036. -85, -81, -82, -82, -89, -94, -99, -103,
  117037. -109, -115, -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, -999, -999, -999, -999, -999,
  117042. -999, -999, -999, -999, -105, -97, -85, -72,
  117043. -74, -70, -70, -70, -76, -85, -91, -93,
  117044. -97, -103, -109, -115, -999, -999, -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, -999, -999, -999, -999, -999,
  117049. -999, -999, -999, -999, -112, -93, -81, -68,
  117050. -62, -60, -60, -57, -63, -70, -77, -82,
  117051. -90, -93, -98, -104, -109, -113, -999, -999,
  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, -999, -999, -999, -999, -999, -999,
  117056. -999, -999, -999, -113, -100, -93, -84, -63,
  117057. -58, -48, -53, -54, -52, -52, -57, -64,
  117058. -66, -76, -83, -81, -85, -85, -90, -95,
  117059. -98, -101, -103, -106, -108, -111, -999, -999,
  117060. -999, -999, -999, -999, -999, -999, -999, -999,
  117061. -999, -999, -999, -999, -999, -999, -999, -999},
  117062. {-999, -999, -999, -999, -999, -999, -999, -999,
  117063. -999, -999, -999, -105, -95, -86, -74, -53,
  117064. -50, -38, -43, -49, -43, -42, -39, -39,
  117065. -46, -52, -57, -56, -72, -69, -74, -81,
  117066. -87, -92, -94, -97, -99, -102, -105, -108,
  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, -108, -99, -90, -76, -66, -45,
  117071. -43, -41, -44, -47, -43, -47, -40, -30,
  117072. -31, -31, -39, -33, -40, -41, -43, -53,
  117073. -59, -70, -73, -77, -79, -82, -84, -87,
  117074. -999, -999, -999, -999, -999, -999, -999, -999,
  117075. -999, -999, -999, -999, -999, -999, -999, -999}},
  117076. /* 4000 Hz */
  117077. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117078. -999, -999, -999, -999, -999, -110, -91, -76,
  117079. -75, -85, -93, -98, -104, -110, -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, -999, -999, -999, -999,
  117085. -999, -999, -999, -999, -999, -110, -91, -70,
  117086. -70, -75, -86, -89, -94, -98, -101, -106,
  117087. -110, -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, -999, -999, -999, -999,
  117092. -999, -999, -999, -999, -110, -95, -80, -60,
  117093. -65, -64, -74, -83, -88, -91, -95, -99,
  117094. -103, -107, -110, -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, -999, -999, -999, -999, -999,
  117099. -999, -999, -999, -999, -110, -95, -80, -58,
  117100. -55, -49, -66, -68, -71, -78, -78, -80,
  117101. -88, -85, -89, -97, -100, -105, -110, -999,
  117102. -999, -999, -999, -999, -999, -999, -999, -999,
  117103. -999, -999, -999, -999, -999, -999, -999, -999,
  117104. -999, -999, -999, -999, -999, -999, -999, -999},
  117105. {-999, -999, -999, -999, -999, -999, -999, -999,
  117106. -999, -999, -999, -999, -110, -95, -80, -53,
  117107. -52, -41, -59, -59, -49, -58, -56, -63,
  117108. -86, -79, -90, -93, -98, -103, -107, -112,
  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, -999, -110, -97, -91, -73, -45,
  117114. -40, -33, -53, -61, -49, -54, -50, -50,
  117115. -60, -52, -67, -74, -81, -92, -96, -100,
  117116. -105, -110, -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. /* 5657 Hz */
  117120. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117121. -999, -999, -999, -113, -106, -99, -92, -77,
  117122. -80, -88, -97, -106, -115, -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, -999, -999, -999, -999, -999, -999,
  117128. -999, -999, -116, -109, -102, -95, -89, -74,
  117129. -72, -88, -87, -95, -102, -109, -116, -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, -999, -999, -999, -999, -999, -999,
  117135. -999, -999, -116, -109, -102, -95, -89, -75,
  117136. -66, -74, -77, -78, -86, -87, -90, -96,
  117137. -105, -115, -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, -999, -999, -999, -999, -999, -999, -999,
  117142. -999, -999, -115, -108, -101, -94, -88, -66,
  117143. -56, -61, -70, -65, -78, -72, -83, -84,
  117144. -93, -98, -105, -110, -999, -999, -999, -999,
  117145. -999, -999, -999, -999, -999, -999, -999, -999,
  117146. -999, -999, -999, -999, -999, -999, -999, -999,
  117147. -999, -999, -999, -999, -999, -999, -999, -999},
  117148. {-999, -999, -999, -999, -999, -999, -999, -999,
  117149. -999, -999, -110, -105, -95, -89, -82, -57,
  117150. -52, -52, -59, -56, -59, -58, -69, -67,
  117151. -88, -82, -82, -89, -94, -100, -108, -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, -110, -101, -96, -90, -83, -77, -54,
  117157. -43, -38, -50, -48, -52, -48, -42, -42,
  117158. -51, -52, -53, -59, -65, -71, -78, -85,
  117159. -95, -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. /* 8000 Hz */
  117163. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117164. -999, -999, -999, -999, -120, -105, -86, -68,
  117165. -78, -79, -90, -100, -110, -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, -999, -999, -999, -999, -999,
  117171. -999, -999, -999, -999, -120, -105, -86, -66,
  117172. -73, -77, -88, -96, -105, -115, -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, -999, -999, -999, -999, -999,
  117178. -999, -999, -999, -120, -105, -92, -80, -61,
  117179. -64, -68, -80, -87, -92, -100, -110, -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, -999, -999, -999, -999, -999,
  117185. -999, -999, -999, -120, -104, -91, -79, -52,
  117186. -60, -54, -64, -69, -77, -80, -82, -84,
  117187. -85, -87, -88, -90, -999, -999, -999, -999,
  117188. -999, -999, -999, -999, -999, -999, -999, -999,
  117189. -999, -999, -999, -999, -999, -999, -999, -999,
  117190. -999, -999, -999, -999, -999, -999, -999, -999},
  117191. {-999, -999, -999, -999, -999, -999, -999, -999,
  117192. -999, -999, -999, -118, -100, -87, -77, -49,
  117193. -50, -44, -58, -61, -61, -67, -65, -62,
  117194. -62, -62, -65, -68, -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, -115, -98, -84, -62, -49,
  117200. -44, -38, -46, -49, -49, -46, -39, -37,
  117201. -39, -40, -42, -43, -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. /* 11314 Hz */
  117206. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117207. -999, -999, -999, -999, -999, -110, -88, -74,
  117208. -77, -82, -82, -85, -90, -94, -99, -104,
  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, -999, -999, -999,
  117214. -999, -999, -999, -999, -999, -110, -88, -66,
  117215. -70, -81, -80, -81, -84, -88, -91, -93,
  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, -999, -999, -999, -999,
  117221. -999, -999, -999, -999, -999, -110, -88, -61,
  117222. -63, -70, -71, -74, -77, -80, -83, -85,
  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, -999, -999, -999, -999,
  117228. -999, -999, -999, -999, -999, -110, -86, -62,
  117229. -63, -62, -62, -58, -52, -50, -50, -52,
  117230. -54, -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. -999, -999, -999, -999, -999, -999, -999, -999},
  117234. {-999, -999, -999, -999, -999, -999, -999, -999,
  117235. -999, -999, -999, -999, -118, -108, -84, -53,
  117236. -50, -50, -50, -55, -47, -45, -40, -40,
  117237. -40, -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, -999, -118, -100, -73, -43,
  117243. -37, -42, -43, -53, -38, -37, -35, -35,
  117244. -38, -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. /* 16000 Hz */
  117249. {{-999, -999, -999, -999, -999, -999, -999, -999,
  117250. -999, -999, -999, -110, -100, -91, -84, -74,
  117251. -80, -80, -80, -80, -80, -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, -999, -999, -999, -999, -999,
  117257. -999, -999, -999, -110, -100, -91, -84, -74,
  117258. -68, -68, -68, -68, -68, -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, -999, -999, -999, -999, -999,
  117264. -999, -999, -999, -110, -100, -86, -78, -70,
  117265. -60, -45, -30, -21, -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, -999, -999, -999, -999, -999,
  117271. -999, -999, -999, -110, -100, -87, -78, -67,
  117272. -48, -38, -29, -21, -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. -999, -999, -999, -999, -999, -999, -999, -999},
  117277. {-999, -999, -999, -999, -999, -999, -999, -999,
  117278. -999, -999, -999, -110, -100, -86, -69, -56,
  117279. -45, -35, -33, -29, -999, -999, -999, -999,
  117280. -999, -999, -999, -999, -999, -999, -999, -999,
  117281. -999, -999, -999, -999, -999, -999, -999, -999,
  117282. -999, -999, -999, -999, -999, -999, -999, -999,
  117283. -999, -999, -999, -999, -999, -999, -999, -999},
  117284. {-999, -999, -999, -999, -999, -999, -999, -999,
  117285. -999, -999, -999, -110, -100, -83, -71, -48,
  117286. -27, -38, -37, -34, -999, -999, -999, -999,
  117287. -999, -999, -999, -999, -999, -999, -999, -999,
  117288. -999, -999, -999, -999, -999, -999, -999, -999,
  117289. -999, -999, -999, -999, -999, -999, -999, -999,
  117290. -999, -999, -999, -999, -999, -999, -999, -999}}
  117291. };
  117292. #endif
  117293. /*** End of inlined file: masking.h ***/
  117294. #define NEGINF -9999.f
  117295. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  117296. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  117297. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  117298. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117299. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117300. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  117301. look->channels=vi->channels;
  117302. look->ampmax=-9999.;
  117303. look->gi=gi;
  117304. return(look);
  117305. }
  117306. void _vp_global_free(vorbis_look_psy_global *look){
  117307. if(look){
  117308. memset(look,0,sizeof(*look));
  117309. _ogg_free(look);
  117310. }
  117311. }
  117312. void _vi_gpsy_free(vorbis_info_psy_global *i){
  117313. if(i){
  117314. memset(i,0,sizeof(*i));
  117315. _ogg_free(i);
  117316. }
  117317. }
  117318. void _vi_psy_free(vorbis_info_psy *i){
  117319. if(i){
  117320. memset(i,0,sizeof(*i));
  117321. _ogg_free(i);
  117322. }
  117323. }
  117324. static void min_curve(float *c,
  117325. float *c2){
  117326. int i;
  117327. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  117328. }
  117329. static void max_curve(float *c,
  117330. float *c2){
  117331. int i;
  117332. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  117333. }
  117334. static void attenuate_curve(float *c,float att){
  117335. int i;
  117336. for(i=0;i<EHMER_MAX;i++)
  117337. c[i]+=att;
  117338. }
  117339. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  117340. float center_boost, float center_decay_rate){
  117341. int i,j,k,m;
  117342. float ath[EHMER_MAX];
  117343. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  117344. float athc[P_LEVELS][EHMER_MAX];
  117345. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  117346. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  117347. memset(workc,0,sizeof(workc));
  117348. for(i=0;i<P_BANDS;i++){
  117349. /* we add back in the ATH to avoid low level curves falling off to
  117350. -infinity and unnecessarily cutting off high level curves in the
  117351. curve limiting (last step). */
  117352. /* A half-band's settings must be valid over the whole band, and
  117353. it's better to mask too little than too much */
  117354. int ath_offset=i*4;
  117355. for(j=0;j<EHMER_MAX;j++){
  117356. float min=999.;
  117357. for(k=0;k<4;k++)
  117358. if(j+k+ath_offset<MAX_ATH){
  117359. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  117360. }else{
  117361. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  117362. }
  117363. ath[j]=min;
  117364. }
  117365. /* copy curves into working space, replicate the 50dB curve to 30
  117366. and 40, replicate the 100dB curve to 110 */
  117367. for(j=0;j<6;j++)
  117368. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  117369. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117370. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  117371. /* apply centered curve boost/decay */
  117372. for(j=0;j<P_LEVELS;j++){
  117373. for(k=0;k<EHMER_MAX;k++){
  117374. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  117375. if(adj<0. && center_boost>0)adj=0.;
  117376. if(adj>0. && center_boost<0)adj=0.;
  117377. workc[i][j][k]+=adj;
  117378. }
  117379. }
  117380. /* normalize curves so the driving amplitude is 0dB */
  117381. /* make temp curves with the ATH overlayed */
  117382. for(j=0;j<P_LEVELS;j++){
  117383. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  117384. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  117385. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  117386. max_curve(athc[j],workc[i][j]);
  117387. }
  117388. /* Now limit the louder curves.
  117389. the idea is this: We don't know what the playback attenuation
  117390. will be; 0dB SL moves every time the user twiddles the volume
  117391. knob. So that means we have to use a single 'most pessimal' curve
  117392. for all masking amplitudes, right? Wrong. The *loudest* sound
  117393. can be in (we assume) a range of ...+100dB] SL. However, sounds
  117394. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  117395. etc... */
  117396. for(j=1;j<P_LEVELS;j++){
  117397. min_curve(athc[j],athc[j-1]);
  117398. min_curve(workc[i][j],athc[j]);
  117399. }
  117400. }
  117401. for(i=0;i<P_BANDS;i++){
  117402. int hi_curve,lo_curve,bin;
  117403. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  117404. /* low frequency curves are measured with greater resolution than
  117405. the MDCT/FFT will actually give us; we want the curve applied
  117406. to the tone data to be pessimistic and thus apply the minimum
  117407. masking possible for a given bin. That means that a single bin
  117408. could span more than one octave and that the curve will be a
  117409. composite of multiple octaves. It also may mean that a single
  117410. bin may span > an eighth of an octave and that the eighth
  117411. octave values may also be composited. */
  117412. /* which octave curves will we be compositing? */
  117413. bin=floor(fromOC(i*.5)/binHz);
  117414. lo_curve= ceil(toOC(bin*binHz+1)*2);
  117415. hi_curve= floor(toOC((bin+1)*binHz)*2);
  117416. if(lo_curve>i)lo_curve=i;
  117417. if(lo_curve<0)lo_curve=0;
  117418. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  117419. for(m=0;m<P_LEVELS;m++){
  117420. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  117421. for(j=0;j<n;j++)brute_buffer[j]=999.;
  117422. /* render the curve into bins, then pull values back into curve.
  117423. The point is that any inherent subsampling aliasing results in
  117424. a safe minimum */
  117425. for(k=lo_curve;k<=hi_curve;k++){
  117426. int l=0;
  117427. for(j=0;j<EHMER_MAX;j++){
  117428. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  117429. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  117430. if(lo_bin<0)lo_bin=0;
  117431. if(lo_bin>n)lo_bin=n;
  117432. if(lo_bin<l)l=lo_bin;
  117433. if(hi_bin<0)hi_bin=0;
  117434. if(hi_bin>n)hi_bin=n;
  117435. for(;l<hi_bin && l<n;l++)
  117436. if(brute_buffer[l]>workc[k][m][j])
  117437. brute_buffer[l]=workc[k][m][j];
  117438. }
  117439. for(;l<n;l++)
  117440. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117441. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117442. }
  117443. /* be equally paranoid about being valid up to next half ocatve */
  117444. if(i+1<P_BANDS){
  117445. int l=0;
  117446. k=i+1;
  117447. for(j=0;j<EHMER_MAX;j++){
  117448. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  117449. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  117450. if(lo_bin<0)lo_bin=0;
  117451. if(lo_bin>n)lo_bin=n;
  117452. if(lo_bin<l)l=lo_bin;
  117453. if(hi_bin<0)hi_bin=0;
  117454. if(hi_bin>n)hi_bin=n;
  117455. for(;l<hi_bin && l<n;l++)
  117456. if(brute_buffer[l]>workc[k][m][j])
  117457. brute_buffer[l]=workc[k][m][j];
  117458. }
  117459. for(;l<n;l++)
  117460. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  117461. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  117462. }
  117463. for(j=0;j<EHMER_MAX;j++){
  117464. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  117465. if(bin<0){
  117466. ret[i][m][j+2]=-999.;
  117467. }else{
  117468. if(bin>=n){
  117469. ret[i][m][j+2]=-999.;
  117470. }else{
  117471. ret[i][m][j+2]=brute_buffer[bin];
  117472. }
  117473. }
  117474. }
  117475. /* add fenceposts */
  117476. for(j=0;j<EHMER_OFFSET;j++)
  117477. if(ret[i][m][j+2]>-200.f)break;
  117478. ret[i][m][0]=j;
  117479. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  117480. if(ret[i][m][j+2]>-200.f)
  117481. break;
  117482. ret[i][m][1]=j;
  117483. }
  117484. }
  117485. return(ret);
  117486. }
  117487. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  117488. vorbis_info_psy_global *gi,int n,long rate){
  117489. long i,j,lo=-99,hi=1;
  117490. long maxoc;
  117491. memset(p,0,sizeof(*p));
  117492. p->eighth_octave_lines=gi->eighth_octave_lines;
  117493. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  117494. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  117495. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  117496. p->total_octave_lines=maxoc-p->firstoc+1;
  117497. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  117498. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  117499. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  117500. p->vi=vi;
  117501. p->n=n;
  117502. p->rate=rate;
  117503. /* AoTuV HF weighting */
  117504. p->m_val = 1.;
  117505. if(rate < 26000) p->m_val = 0;
  117506. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  117507. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  117508. /* set up the lookups for a given blocksize and sample rate */
  117509. for(i=0,j=0;i<MAX_ATH-1;i++){
  117510. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117511. float base=ATH[i];
  117512. if(j<endpos){
  117513. float delta=(ATH[i+1]-base)/(endpos-j);
  117514. for(;j<endpos && j<n;j++){
  117515. p->ath[j]=base+100.;
  117516. base+=delta;
  117517. }
  117518. }
  117519. }
  117520. for(i=0;i<n;i++){
  117521. float bark=toBARK(rate/(2*n)*i);
  117522. for(;lo+vi->noisewindowlomin<i &&
  117523. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117524. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117525. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117526. p->bark[i]=((lo-1)<<16)+(hi-1);
  117527. }
  117528. for(i=0;i<n;i++)
  117529. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117530. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117531. vi->tone_centerboost,vi->tone_decay);
  117532. /* set up rolling noise median */
  117533. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117534. for(i=0;i<P_NOISECURVES;i++)
  117535. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117536. for(i=0;i<n;i++){
  117537. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117538. int inthalfoc;
  117539. float del;
  117540. if(halfoc<0)halfoc=0;
  117541. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117542. inthalfoc=(int)halfoc;
  117543. del=halfoc-inthalfoc;
  117544. for(j=0;j<P_NOISECURVES;j++)
  117545. p->noiseoffset[j][i]=
  117546. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117547. p->vi->noiseoff[j][inthalfoc+1]*del;
  117548. }
  117549. #if 0
  117550. {
  117551. static int ls=0;
  117552. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117553. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117554. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117555. }
  117556. #endif
  117557. }
  117558. void _vp_psy_clear(vorbis_look_psy *p){
  117559. int i,j;
  117560. if(p){
  117561. if(p->ath)_ogg_free(p->ath);
  117562. if(p->octave)_ogg_free(p->octave);
  117563. if(p->bark)_ogg_free(p->bark);
  117564. if(p->tonecurves){
  117565. for(i=0;i<P_BANDS;i++){
  117566. for(j=0;j<P_LEVELS;j++){
  117567. _ogg_free(p->tonecurves[i][j]);
  117568. }
  117569. _ogg_free(p->tonecurves[i]);
  117570. }
  117571. _ogg_free(p->tonecurves);
  117572. }
  117573. if(p->noiseoffset){
  117574. for(i=0;i<P_NOISECURVES;i++){
  117575. _ogg_free(p->noiseoffset[i]);
  117576. }
  117577. _ogg_free(p->noiseoffset);
  117578. }
  117579. memset(p,0,sizeof(*p));
  117580. }
  117581. }
  117582. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117583. static void seed_curve(float *seed,
  117584. const float **curves,
  117585. float amp,
  117586. int oc, int n,
  117587. int linesper,float dBoffset){
  117588. int i,post1;
  117589. int seedptr;
  117590. const float *posts,*curve;
  117591. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117592. choice=max(choice,0);
  117593. choice=min(choice,P_LEVELS-1);
  117594. posts=curves[choice];
  117595. curve=posts+2;
  117596. post1=(int)posts[1];
  117597. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117598. for(i=posts[0];i<post1;i++){
  117599. if(seedptr>0){
  117600. float lin=amp+curve[i];
  117601. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117602. }
  117603. seedptr+=linesper;
  117604. if(seedptr>=n)break;
  117605. }
  117606. }
  117607. static void seed_loop(vorbis_look_psy *p,
  117608. const float ***curves,
  117609. const float *f,
  117610. const float *flr,
  117611. float *seed,
  117612. float specmax){
  117613. vorbis_info_psy *vi=p->vi;
  117614. long n=p->n,i;
  117615. float dBoffset=vi->max_curve_dB-specmax;
  117616. /* prime the working vector with peak values */
  117617. for(i=0;i<n;i++){
  117618. float max=f[i];
  117619. long oc=p->octave[i];
  117620. while(i+1<n && p->octave[i+1]==oc){
  117621. i++;
  117622. if(f[i]>max)max=f[i];
  117623. }
  117624. if(max+6.f>flr[i]){
  117625. oc=oc>>p->shiftoc;
  117626. if(oc>=P_BANDS)oc=P_BANDS-1;
  117627. if(oc<0)oc=0;
  117628. seed_curve(seed,
  117629. curves[oc],
  117630. max,
  117631. p->octave[i]-p->firstoc,
  117632. p->total_octave_lines,
  117633. p->eighth_octave_lines,
  117634. dBoffset);
  117635. }
  117636. }
  117637. }
  117638. static void seed_chase(float *seeds, int linesper, long n){
  117639. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117640. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117641. long stack=0;
  117642. long pos=0;
  117643. long i;
  117644. for(i=0;i<n;i++){
  117645. if(stack<2){
  117646. posstack[stack]=i;
  117647. ampstack[stack++]=seeds[i];
  117648. }else{
  117649. while(1){
  117650. if(seeds[i]<ampstack[stack-1]){
  117651. posstack[stack]=i;
  117652. ampstack[stack++]=seeds[i];
  117653. break;
  117654. }else{
  117655. if(i<posstack[stack-1]+linesper){
  117656. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117657. i<posstack[stack-2]+linesper){
  117658. /* we completely overlap, making stack-1 irrelevant. pop it */
  117659. stack--;
  117660. continue;
  117661. }
  117662. }
  117663. posstack[stack]=i;
  117664. ampstack[stack++]=seeds[i];
  117665. break;
  117666. }
  117667. }
  117668. }
  117669. }
  117670. /* the stack now contains only the positions that are relevant. Scan
  117671. 'em straight through */
  117672. for(i=0;i<stack;i++){
  117673. long endpos;
  117674. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117675. endpos=posstack[i+1];
  117676. }else{
  117677. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117678. discarded in short frames */
  117679. }
  117680. if(endpos>n)endpos=n;
  117681. for(;pos<endpos;pos++)
  117682. seeds[pos]=ampstack[i];
  117683. }
  117684. /* there. Linear time. I now remember this was on a problem set I
  117685. had in Grad Skool... I didn't solve it at the time ;-) */
  117686. }
  117687. /* bleaugh, this is more complicated than it needs to be */
  117688. #include<stdio.h>
  117689. static void max_seeds(vorbis_look_psy *p,
  117690. float *seed,
  117691. float *flr){
  117692. long n=p->total_octave_lines;
  117693. int linesper=p->eighth_octave_lines;
  117694. long linpos=0;
  117695. long pos;
  117696. seed_chase(seed,linesper,n); /* for masking */
  117697. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117698. while(linpos+1<p->n){
  117699. float minV=seed[pos];
  117700. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117701. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117702. while(pos+1<=end){
  117703. pos++;
  117704. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117705. minV=seed[pos];
  117706. }
  117707. end=pos+p->firstoc;
  117708. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117709. if(flr[linpos]<minV)flr[linpos]=minV;
  117710. }
  117711. {
  117712. float minV=seed[p->total_octave_lines-1];
  117713. for(;linpos<p->n;linpos++)
  117714. if(flr[linpos]<minV)flr[linpos]=minV;
  117715. }
  117716. }
  117717. static void bark_noise_hybridmp(int n,const long *b,
  117718. const float *f,
  117719. float *noise,
  117720. const float offset,
  117721. const int fixed){
  117722. float *N=(float*) alloca(n*sizeof(*N));
  117723. float *X=(float*) alloca(n*sizeof(*N));
  117724. float *XX=(float*) alloca(n*sizeof(*N));
  117725. float *Y=(float*) alloca(n*sizeof(*N));
  117726. float *XY=(float*) alloca(n*sizeof(*N));
  117727. float tN, tX, tXX, tY, tXY;
  117728. int i;
  117729. int lo, hi;
  117730. float R, A, B, D;
  117731. float w, x, y;
  117732. tN = tX = tXX = tY = tXY = 0.f;
  117733. y = f[0] + offset;
  117734. if (y < 1.f) y = 1.f;
  117735. w = y * y * .5;
  117736. tN += w;
  117737. tX += w;
  117738. tY += w * y;
  117739. N[0] = tN;
  117740. X[0] = tX;
  117741. XX[0] = tXX;
  117742. Y[0] = tY;
  117743. XY[0] = tXY;
  117744. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117745. y = f[i] + offset;
  117746. if (y < 1.f) y = 1.f;
  117747. w = y * y;
  117748. tN += w;
  117749. tX += w * x;
  117750. tXX += w * x * x;
  117751. tY += w * y;
  117752. tXY += w * x * y;
  117753. N[i] = tN;
  117754. X[i] = tX;
  117755. XX[i] = tXX;
  117756. Y[i] = tY;
  117757. XY[i] = tXY;
  117758. }
  117759. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117760. lo = b[i] >> 16;
  117761. if( lo>=0 ) break;
  117762. hi = b[i] & 0xffff;
  117763. tN = N[hi] + N[-lo];
  117764. tX = X[hi] - X[-lo];
  117765. tXX = XX[hi] + XX[-lo];
  117766. tY = Y[hi] + Y[-lo];
  117767. tXY = XY[hi] - XY[-lo];
  117768. A = tY * tXX - tX * tXY;
  117769. B = tN * tXY - tX * tY;
  117770. D = tN * tXX - tX * tX;
  117771. R = (A + x * B) / D;
  117772. if (R < 0.f)
  117773. R = 0.f;
  117774. noise[i] = R - offset;
  117775. }
  117776. for ( ;; i++, x += 1.f) {
  117777. lo = b[i] >> 16;
  117778. hi = b[i] & 0xffff;
  117779. if(hi>=n)break;
  117780. tN = N[hi] - N[lo];
  117781. tX = X[hi] - X[lo];
  117782. tXX = XX[hi] - XX[lo];
  117783. tY = Y[hi] - Y[lo];
  117784. tXY = XY[hi] - XY[lo];
  117785. A = tY * tXX - tX * tXY;
  117786. B = tN * tXY - tX * tY;
  117787. D = tN * tXX - tX * tX;
  117788. R = (A + x * B) / D;
  117789. if (R < 0.f) R = 0.f;
  117790. noise[i] = R - offset;
  117791. }
  117792. for ( ; i < n; i++, x += 1.f) {
  117793. R = (A + x * B) / D;
  117794. if (R < 0.f) R = 0.f;
  117795. noise[i] = R - offset;
  117796. }
  117797. if (fixed <= 0) return;
  117798. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117799. hi = i + fixed / 2;
  117800. lo = hi - fixed;
  117801. if(lo>=0)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++, x += 1.f) {
  117814. hi = i + fixed / 2;
  117815. lo = hi - fixed;
  117816. if(hi>=n)break;
  117817. tN = N[hi] - N[lo];
  117818. tX = X[hi] - X[lo];
  117819. tXX = XX[hi] - XX[lo];
  117820. tY = Y[hi] - Y[lo];
  117821. tXY = XY[hi] - XY[lo];
  117822. A = tY * tXX - tX * tXY;
  117823. B = tN * tXY - tX * tY;
  117824. D = tN * tXX - tX * tX;
  117825. R = (A + x * B) / D;
  117826. if (R - offset < noise[i]) noise[i] = R - offset;
  117827. }
  117828. for ( ; i < n; i++, x += 1.f) {
  117829. R = (A + x * B) / D;
  117830. if (R - offset < noise[i]) noise[i] = R - offset;
  117831. }
  117832. }
  117833. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117834. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117835. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117836. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117837. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117838. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117839. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117840. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117841. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117842. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117843. 973377.F, 913981.F, 858210.F, 805842.F,
  117844. 756669.F, 710497.F, 667142.F, 626433.F,
  117845. 588208.F, 552316.F, 518613.F, 486967.F,
  117846. 457252.F, 429351.F, 403152.F, 378551.F,
  117847. 355452.F, 333762.F, 313396.F, 294273.F,
  117848. 276316.F, 259455.F, 243623.F, 228757.F,
  117849. 214798.F, 201691.F, 189384.F, 177828.F,
  117850. 166977.F, 156788.F, 147221.F, 138237.F,
  117851. 129802.F, 121881.F, 114444.F, 107461.F,
  117852. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117853. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117854. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117855. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117856. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117857. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117858. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117859. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117860. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117861. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117862. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117863. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117864. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117865. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117866. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117867. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117868. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117869. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117870. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117871. 842.910F, 791.475F, 743.179F, 697.830F,
  117872. 655.249F, 615.265F, 577.722F, 542.469F,
  117873. 509.367F, 478.286F, 449.101F, 421.696F,
  117874. 395.964F, 371.803F, 349.115F, 327.812F,
  117875. 307.809F, 289.026F, 271.390F, 254.830F,
  117876. 239.280F, 224.679F, 210.969F, 198.096F,
  117877. 186.008F, 174.658F, 164.000F, 153.993F,
  117878. 144.596F, 135.773F, 127.488F, 119.708F,
  117879. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117880. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117881. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117882. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117883. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117884. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117885. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117886. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117887. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117888. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117889. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117890. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117891. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117892. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117893. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117894. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117895. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117896. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117897. 1.20790F, 1.13419F, 1.06499F, 1.F
  117898. };
  117899. void _vp_remove_floor(vorbis_look_psy *p,
  117900. float *mdct,
  117901. int *codedflr,
  117902. float *residue,
  117903. int sliding_lowpass){
  117904. int i,n=p->n;
  117905. if(sliding_lowpass>n)sliding_lowpass=n;
  117906. for(i=0;i<sliding_lowpass;i++){
  117907. residue[i]=
  117908. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117909. }
  117910. for(;i<n;i++)
  117911. residue[i]=0.;
  117912. }
  117913. void _vp_noisemask(vorbis_look_psy *p,
  117914. float *logmdct,
  117915. float *logmask){
  117916. int i,n=p->n;
  117917. float *work=(float*) alloca(n*sizeof(*work));
  117918. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117919. 140.,-1);
  117920. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117921. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117922. p->vi->noisewindowfixed);
  117923. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117924. #if 0
  117925. {
  117926. static int seq=0;
  117927. float work2[n];
  117928. for(i=0;i<n;i++){
  117929. work2[i]=logmask[i]+work[i];
  117930. }
  117931. if(seq&1)
  117932. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117933. else
  117934. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117935. if(seq&1)
  117936. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117937. else
  117938. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117939. seq++;
  117940. }
  117941. #endif
  117942. for(i=0;i<n;i++){
  117943. int dB=logmask[i]+.5;
  117944. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117945. if(dB<0)dB=0;
  117946. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117947. }
  117948. }
  117949. void _vp_tonemask(vorbis_look_psy *p,
  117950. float *logfft,
  117951. float *logmask,
  117952. float global_specmax,
  117953. float local_specmax){
  117954. int i,n=p->n;
  117955. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117956. float att=local_specmax+p->vi->ath_adjatt;
  117957. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117958. /* set the ATH (floating below localmax, not global max by a
  117959. specified att) */
  117960. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117961. for(i=0;i<n;i++)
  117962. logmask[i]=p->ath[i]+att;
  117963. /* tone masking */
  117964. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117965. max_seeds(p,seed,logmask);
  117966. }
  117967. void _vp_offset_and_mix(vorbis_look_psy *p,
  117968. float *noise,
  117969. float *tone,
  117970. int offset_select,
  117971. float *logmask,
  117972. float *mdct,
  117973. float *logmdct){
  117974. int i,n=p->n;
  117975. float de, coeffi, cx;/* AoTuV */
  117976. float toneatt=p->vi->tone_masteratt[offset_select];
  117977. cx = p->m_val;
  117978. for(i=0;i<n;i++){
  117979. float val= noise[i]+p->noiseoffset[offset_select][i];
  117980. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117981. logmask[i]=max(val,tone[i]+toneatt);
  117982. /* AoTuV */
  117983. /** @ M1 **
  117984. The following codes improve a noise problem.
  117985. A fundamental idea uses the value of masking and carries out
  117986. the relative compensation of the MDCT.
  117987. However, this code is not perfect and all noise problems cannot be solved.
  117988. by Aoyumi @ 2004/04/18
  117989. */
  117990. if(offset_select == 1) {
  117991. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117992. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117993. if(val > coeffi){
  117994. /* mdct value is > -17.2 dB below floor */
  117995. de = 1.0-((val-coeffi)*0.005*cx);
  117996. /* pro-rated attenuation:
  117997. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117998. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117999. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  118000. etc... */
  118001. if(de < 0) de = 0.0001;
  118002. }else
  118003. /* mdct value is <= -17.2 dB below floor */
  118004. de = 1.0-((val-coeffi)*0.0003*cx);
  118005. /* pro-rated attenuation:
  118006. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  118007. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  118008. etc... */
  118009. mdct[i] *= de;
  118010. }
  118011. }
  118012. }
  118013. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  118014. vorbis_info *vi=vd->vi;
  118015. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  118016. vorbis_info_psy_global *gi=&ci->psy_g_param;
  118017. int n=ci->blocksizes[vd->W]/2;
  118018. float secs=(float)n/vi->rate;
  118019. amp+=secs*gi->ampmax_att_per_sec;
  118020. if(amp<-9999)amp=-9999;
  118021. return(amp);
  118022. }
  118023. static void couple_lossless(float A, float B,
  118024. float *qA, float *qB){
  118025. int test1=fabs(*qA)>fabs(*qB);
  118026. test1-= fabs(*qA)<fabs(*qB);
  118027. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  118028. if(test1==1){
  118029. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  118030. }else{
  118031. float temp=*qB;
  118032. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  118033. *qA=temp;
  118034. }
  118035. if(*qB>fabs(*qA)*1.9999f){
  118036. *qB= -fabs(*qA)*2.f;
  118037. *qA= -*qA;
  118038. }
  118039. }
  118040. static float hypot_lookup[32]={
  118041. -0.009935, -0.011245, -0.012726, -0.014397,
  118042. -0.016282, -0.018407, -0.020800, -0.023494,
  118043. -0.026522, -0.029923, -0.033737, -0.038010,
  118044. -0.042787, -0.048121, -0.054064, -0.060671,
  118045. -0.068000, -0.076109, -0.085054, -0.094892,
  118046. -0.105675, -0.117451, -0.130260, -0.144134,
  118047. -0.159093, -0.175146, -0.192286, -0.210490,
  118048. -0.229718, -0.249913, -0.271001, -0.292893};
  118049. static void precomputed_couple_point(float premag,
  118050. int floorA,int floorB,
  118051. float *mag, float *ang){
  118052. int test=(floorA>floorB)-1;
  118053. int offset=31-abs(floorA-floorB);
  118054. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  118055. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  118056. *mag=premag*floormag;
  118057. *ang=0.f;
  118058. }
  118059. /* just like below, this is currently set up to only do
  118060. single-step-depth coupling. Otherwise, we'd have to do more
  118061. copying (which will be inevitable later) */
  118062. /* doing the real circular magnitude calculation is audibly superior
  118063. to (A+B)/sqrt(2) */
  118064. static float dipole_hypot(float a, float b){
  118065. if(a>0.){
  118066. if(b>0.)return sqrt(a*a+b*b);
  118067. if(a>-b)return sqrt(a*a-b*b);
  118068. return -sqrt(b*b-a*a);
  118069. }
  118070. if(b<0.)return -sqrt(a*a+b*b);
  118071. if(-a>b)return -sqrt(a*a-b*b);
  118072. return sqrt(b*b-a*a);
  118073. }
  118074. static float round_hypot(float a, float b){
  118075. if(a>0.){
  118076. if(b>0.)return sqrt(a*a+b*b);
  118077. if(a>-b)return sqrt(a*a+b*b);
  118078. return -sqrt(b*b+a*a);
  118079. }
  118080. if(b<0.)return -sqrt(a*a+b*b);
  118081. if(-a>b)return -sqrt(a*a+b*b);
  118082. return sqrt(b*b+a*a);
  118083. }
  118084. /* revert to round hypot for now */
  118085. float **_vp_quantize_couple_memo(vorbis_block *vb,
  118086. vorbis_info_psy_global *g,
  118087. vorbis_look_psy *p,
  118088. vorbis_info_mapping0 *vi,
  118089. float **mdct){
  118090. int i,j,n=p->n;
  118091. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118092. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118093. for(i=0;i<vi->coupling_steps;i++){
  118094. float *mdctM=mdct[vi->coupling_mag[i]];
  118095. float *mdctA=mdct[vi->coupling_ang[i]];
  118096. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118097. for(j=0;j<limit;j++)
  118098. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  118099. for(;j<n;j++)
  118100. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  118101. }
  118102. return(ret);
  118103. }
  118104. /* this is for per-channel noise normalization */
  118105. static int JUCE_CDECL apsort(const void *a, const void *b){
  118106. float f1=fabs(**(float**)a);
  118107. float f2=fabs(**(float**)b);
  118108. return (f1<f2)-(f1>f2);
  118109. }
  118110. int **_vp_quantize_couple_sort(vorbis_block *vb,
  118111. vorbis_look_psy *p,
  118112. vorbis_info_mapping0 *vi,
  118113. float **mags){
  118114. if(p->vi->normal_point_p){
  118115. int i,j,k,n=p->n;
  118116. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  118117. int partition=p->vi->normal_partition;
  118118. float **work=(float**) alloca(sizeof(*work)*partition);
  118119. for(i=0;i<vi->coupling_steps;i++){
  118120. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  118121. for(j=0;j<n;j+=partition){
  118122. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  118123. qsort(work,partition,sizeof(*work),apsort);
  118124. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  118125. }
  118126. }
  118127. return(ret);
  118128. }
  118129. return(NULL);
  118130. }
  118131. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  118132. float *magnitudes,int *sortedindex){
  118133. int i,j,n=p->n;
  118134. vorbis_info_psy *vi=p->vi;
  118135. int partition=vi->normal_partition;
  118136. float **work=(float**) alloca(sizeof(*work)*partition);
  118137. int start=vi->normal_start;
  118138. for(j=start;j<n;j+=partition){
  118139. if(j+partition>n)partition=n-j;
  118140. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  118141. qsort(work,partition,sizeof(*work),apsort);
  118142. for(i=0;i<partition;i++){
  118143. sortedindex[i+j-start]=work[i]-magnitudes;
  118144. }
  118145. }
  118146. }
  118147. void _vp_noise_normalize(vorbis_look_psy *p,
  118148. float *in,float *out,int *sortedindex){
  118149. int flag=0,i,j=0,n=p->n;
  118150. vorbis_info_psy *vi=p->vi;
  118151. int partition=vi->normal_partition;
  118152. int start=vi->normal_start;
  118153. if(start>n)start=n;
  118154. if(vi->normal_channel_p){
  118155. for(;j<start;j++)
  118156. out[j]=rint(in[j]);
  118157. for(;j+partition<=n;j+=partition){
  118158. float acc=0.;
  118159. int k;
  118160. for(i=j;i<j+partition;i++)
  118161. acc+=in[i]*in[i];
  118162. for(i=0;i<partition;i++){
  118163. k=sortedindex[i+j-start];
  118164. if(in[k]*in[k]>=.25f){
  118165. out[k]=rint(in[k]);
  118166. acc-=in[k]*in[k];
  118167. flag=1;
  118168. }else{
  118169. if(acc<vi->normal_thresh)break;
  118170. out[k]=unitnorm(in[k]);
  118171. acc-=1.;
  118172. }
  118173. }
  118174. for(;i<partition;i++){
  118175. k=sortedindex[i+j-start];
  118176. out[k]=0.;
  118177. }
  118178. }
  118179. }
  118180. for(;j<n;j++)
  118181. out[j]=rint(in[j]);
  118182. }
  118183. void _vp_couple(int blobno,
  118184. vorbis_info_psy_global *g,
  118185. vorbis_look_psy *p,
  118186. vorbis_info_mapping0 *vi,
  118187. float **res,
  118188. float **mag_memo,
  118189. int **mag_sort,
  118190. int **ifloor,
  118191. int *nonzero,
  118192. int sliding_lowpass){
  118193. int i,j,k,n=p->n;
  118194. /* perform any requested channel coupling */
  118195. /* point stereo can only be used in a first stage (in this encoder)
  118196. because of the dependency on floor lookups */
  118197. for(i=0;i<vi->coupling_steps;i++){
  118198. /* once we're doing multistage coupling in which a channel goes
  118199. through more than one coupling step, the floor vector
  118200. magnitudes will also have to be recalculated an propogated
  118201. along with PCM. Right now, we're not (that will wait until 5.1
  118202. most likely), so the code isn't here yet. The memory management
  118203. here is all assuming single depth couplings anyway. */
  118204. /* make sure coupling a zero and a nonzero channel results in two
  118205. nonzero channels. */
  118206. if(nonzero[vi->coupling_mag[i]] ||
  118207. nonzero[vi->coupling_ang[i]]){
  118208. float *rM=res[vi->coupling_mag[i]];
  118209. float *rA=res[vi->coupling_ang[i]];
  118210. float *qM=rM+n;
  118211. float *qA=rA+n;
  118212. int *floorM=ifloor[vi->coupling_mag[i]];
  118213. int *floorA=ifloor[vi->coupling_ang[i]];
  118214. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  118215. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  118216. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  118217. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  118218. int pointlimit=limit;
  118219. nonzero[vi->coupling_mag[i]]=1;
  118220. nonzero[vi->coupling_ang[i]]=1;
  118221. /* The threshold of a stereo is changed with the size of n */
  118222. if(n > 1000)
  118223. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  118224. for(j=0;j<p->n;j+=partition){
  118225. float acc=0.f;
  118226. for(k=0;k<partition;k++){
  118227. int l=k+j;
  118228. if(l<sliding_lowpass){
  118229. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  118230. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  118231. precomputed_couple_point(mag_memo[i][l],
  118232. floorM[l],floorA[l],
  118233. qM+l,qA+l);
  118234. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  118235. }else{
  118236. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  118237. }
  118238. }else{
  118239. qM[l]=0.;
  118240. qA[l]=0.;
  118241. }
  118242. }
  118243. if(p->vi->normal_point_p){
  118244. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  118245. int l=mag_sort[i][j+k];
  118246. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  118247. qM[l]=unitnorm(qM[l]);
  118248. acc-=1.f;
  118249. }
  118250. }
  118251. }
  118252. }
  118253. }
  118254. }
  118255. }
  118256. /* AoTuV */
  118257. /** @ M2 **
  118258. The boost problem by the combination of noise normalization and point stereo is eased.
  118259. However, this is a temporary patch.
  118260. by Aoyumi @ 2004/04/18
  118261. */
  118262. void hf_reduction(vorbis_info_psy_global *g,
  118263. vorbis_look_psy *p,
  118264. vorbis_info_mapping0 *vi,
  118265. float **mdct){
  118266. int i,j,n=p->n, de=0.3*p->m_val;
  118267. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  118268. for(i=0; i<vi->coupling_steps; i++){
  118269. /* for(j=start; j<limit; j++){} // ???*/
  118270. for(j=limit; j<n; j++)
  118271. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  118272. }
  118273. }
  118274. #endif
  118275. /*** End of inlined file: psy.c ***/
  118276. /*** Start of inlined file: registry.c ***/
  118277. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118278. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118279. // tasks..
  118280. #if JUCE_MSVC
  118281. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118282. #endif
  118283. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118284. #if JUCE_USE_OGGVORBIS
  118285. /* seems like major overkill now; the backend numbers will grow into
  118286. the infrastructure soon enough */
  118287. extern vorbis_func_floor floor0_exportbundle;
  118288. extern vorbis_func_floor floor1_exportbundle;
  118289. extern vorbis_func_residue residue0_exportbundle;
  118290. extern vorbis_func_residue residue1_exportbundle;
  118291. extern vorbis_func_residue residue2_exportbundle;
  118292. extern vorbis_func_mapping mapping0_exportbundle;
  118293. vorbis_func_floor *_floor_P[]={
  118294. &floor0_exportbundle,
  118295. &floor1_exportbundle,
  118296. };
  118297. vorbis_func_residue *_residue_P[]={
  118298. &residue0_exportbundle,
  118299. &residue1_exportbundle,
  118300. &residue2_exportbundle,
  118301. };
  118302. vorbis_func_mapping *_mapping_P[]={
  118303. &mapping0_exportbundle,
  118304. };
  118305. #endif
  118306. /*** End of inlined file: registry.c ***/
  118307. /*** Start of inlined file: res0.c ***/
  118308. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  118309. encode/decode loops are coded for clarity and performance is not
  118310. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  118311. it's slow. */
  118312. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  118313. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118314. // tasks..
  118315. #if JUCE_MSVC
  118316. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118317. #endif
  118318. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  118319. #if JUCE_USE_OGGVORBIS
  118320. #include <stdlib.h>
  118321. #include <string.h>
  118322. #include <math.h>
  118323. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118324. #include <stdio.h>
  118325. #endif
  118326. typedef struct {
  118327. vorbis_info_residue0 *info;
  118328. int parts;
  118329. int stages;
  118330. codebook *fullbooks;
  118331. codebook *phrasebook;
  118332. codebook ***partbooks;
  118333. int partvals;
  118334. int **decodemap;
  118335. long postbits;
  118336. long phrasebits;
  118337. long frames;
  118338. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118339. int train_seq;
  118340. long *training_data[8][64];
  118341. float training_max[8][64];
  118342. float training_min[8][64];
  118343. float tmin;
  118344. float tmax;
  118345. #endif
  118346. } vorbis_look_residue0;
  118347. void res0_free_info(vorbis_info_residue *i){
  118348. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118349. if(info){
  118350. memset(info,0,sizeof(*info));
  118351. _ogg_free(info);
  118352. }
  118353. }
  118354. void res0_free_look(vorbis_look_residue *i){
  118355. int j;
  118356. if(i){
  118357. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118358. #ifdef TRAIN_RES
  118359. {
  118360. int j,k,l;
  118361. for(j=0;j<look->parts;j++){
  118362. /*fprintf(stderr,"partition %d: ",j);*/
  118363. for(k=0;k<8;k++)
  118364. if(look->training_data[k][j]){
  118365. char buffer[80];
  118366. FILE *of;
  118367. codebook *statebook=look->partbooks[j][k];
  118368. /* long and short into the same bucket by current convention */
  118369. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118370. of=fopen(buffer,"a");
  118371. for(l=0;l<statebook->entries;l++)
  118372. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118373. fclose(of);
  118374. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118375. look->training_min[k][j],look->training_max[k][j]);*/
  118376. _ogg_free(look->training_data[k][j]);
  118377. look->training_data[k][j]=NULL;
  118378. }
  118379. /*fprintf(stderr,"\n");*/
  118380. }
  118381. }
  118382. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118383. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118384. (float)look->phrasebits/look->frames,
  118385. (float)look->postbits/look->frames,
  118386. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118387. #endif
  118388. /*vorbis_info_residue0 *info=look->info;
  118389. fprintf(stderr,
  118390. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118391. "(%g/frame) \n",look->frames,look->phrasebits,
  118392. look->resbitsflat,
  118393. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118394. for(j=0;j<look->parts;j++){
  118395. long acc=0;
  118396. fprintf(stderr,"\t[%d] == ",j);
  118397. for(k=0;k<look->stages;k++)
  118398. if((info->secondstages[j]>>k)&1){
  118399. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118400. acc+=look->resbits[j][k];
  118401. }
  118402. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118403. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118404. }
  118405. fprintf(stderr,"\n");*/
  118406. for(j=0;j<look->parts;j++)
  118407. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118408. _ogg_free(look->partbooks);
  118409. for(j=0;j<look->partvals;j++)
  118410. _ogg_free(look->decodemap[j]);
  118411. _ogg_free(look->decodemap);
  118412. memset(look,0,sizeof(*look));
  118413. _ogg_free(look);
  118414. }
  118415. }
  118416. static int icount(unsigned int v){
  118417. int ret=0;
  118418. while(v){
  118419. ret+=v&1;
  118420. v>>=1;
  118421. }
  118422. return(ret);
  118423. }
  118424. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118425. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118426. int j,acc=0;
  118427. oggpack_write(opb,info->begin,24);
  118428. oggpack_write(opb,info->end,24);
  118429. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118430. code with a partitioned book */
  118431. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118432. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118433. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118434. bitmask of one indicates this partition class has bits to write
  118435. this pass */
  118436. for(j=0;j<info->partitions;j++){
  118437. if(ilog(info->secondstages[j])>3){
  118438. /* yes, this is a minor hack due to not thinking ahead */
  118439. oggpack_write(opb,info->secondstages[j],3);
  118440. oggpack_write(opb,1,1);
  118441. oggpack_write(opb,info->secondstages[j]>>3,5);
  118442. }else
  118443. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118444. acc+=icount(info->secondstages[j]);
  118445. }
  118446. for(j=0;j<acc;j++)
  118447. oggpack_write(opb,info->booklist[j],8);
  118448. }
  118449. /* vorbis_info is for range checking */
  118450. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118451. int j,acc=0;
  118452. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118453. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118454. info->begin=oggpack_read(opb,24);
  118455. info->end=oggpack_read(opb,24);
  118456. info->grouping=oggpack_read(opb,24)+1;
  118457. info->partitions=oggpack_read(opb,6)+1;
  118458. info->groupbook=oggpack_read(opb,8);
  118459. for(j=0;j<info->partitions;j++){
  118460. int cascade=oggpack_read(opb,3);
  118461. if(oggpack_read(opb,1))
  118462. cascade|=(oggpack_read(opb,5)<<3);
  118463. info->secondstages[j]=cascade;
  118464. acc+=icount(cascade);
  118465. }
  118466. for(j=0;j<acc;j++)
  118467. info->booklist[j]=oggpack_read(opb,8);
  118468. if(info->groupbook>=ci->books)goto errout;
  118469. for(j=0;j<acc;j++)
  118470. if(info->booklist[j]>=ci->books)goto errout;
  118471. return(info);
  118472. errout:
  118473. res0_free_info(info);
  118474. return(NULL);
  118475. }
  118476. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118477. vorbis_info_residue *vr){
  118478. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118479. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118480. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118481. int j,k,acc=0;
  118482. int dim;
  118483. int maxstage=0;
  118484. look->info=info;
  118485. look->parts=info->partitions;
  118486. look->fullbooks=ci->fullbooks;
  118487. look->phrasebook=ci->fullbooks+info->groupbook;
  118488. dim=look->phrasebook->dim;
  118489. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118490. for(j=0;j<look->parts;j++){
  118491. int stages=ilog(info->secondstages[j]);
  118492. if(stages){
  118493. if(stages>maxstage)maxstage=stages;
  118494. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118495. for(k=0;k<stages;k++)
  118496. if(info->secondstages[j]&(1<<k)){
  118497. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118498. #ifdef TRAIN_RES
  118499. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118500. sizeof(***look->training_data));
  118501. #endif
  118502. }
  118503. }
  118504. }
  118505. look->partvals=rint(pow((float)look->parts,(float)dim));
  118506. look->stages=maxstage;
  118507. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118508. for(j=0;j<look->partvals;j++){
  118509. long val=j;
  118510. long mult=look->partvals/look->parts;
  118511. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118512. for(k=0;k<dim;k++){
  118513. long deco=val/mult;
  118514. val-=deco*mult;
  118515. mult/=look->parts;
  118516. look->decodemap[j][k]=deco;
  118517. }
  118518. }
  118519. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118520. {
  118521. static int train_seq=0;
  118522. look->train_seq=train_seq++;
  118523. }
  118524. #endif
  118525. return(look);
  118526. }
  118527. /* break an abstraction and copy some code for performance purposes */
  118528. static int local_book_besterror(codebook *book,float *a){
  118529. int dim=book->dim,i,k,o;
  118530. int best=0;
  118531. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118532. /* find the quant val of each scalar */
  118533. for(k=0,o=dim;k<dim;++k){
  118534. float val=a[--o];
  118535. i=tt->threshvals>>1;
  118536. if(val<tt->quantthresh[i]){
  118537. if(val<tt->quantthresh[i-1]){
  118538. for(--i;i>0;--i)
  118539. if(val>=tt->quantthresh[i-1])
  118540. break;
  118541. }
  118542. }else{
  118543. for(++i;i<tt->threshvals-1;++i)
  118544. if(val<tt->quantthresh[i])break;
  118545. }
  118546. best=(best*tt->quantvals)+tt->quantmap[i];
  118547. }
  118548. /* regular lattices are easy :-) */
  118549. if(book->c->lengthlist[best]<=0){
  118550. const static_codebook *c=book->c;
  118551. int i,j;
  118552. float bestf=0.f;
  118553. float *e=book->valuelist;
  118554. best=-1;
  118555. for(i=0;i<book->entries;i++){
  118556. if(c->lengthlist[i]>0){
  118557. float thisx=0.f;
  118558. for(j=0;j<dim;j++){
  118559. float val=(e[j]-a[j]);
  118560. thisx+=val*val;
  118561. }
  118562. if(best==-1 || thisx<bestf){
  118563. bestf=thisx;
  118564. best=i;
  118565. }
  118566. }
  118567. e+=dim;
  118568. }
  118569. }
  118570. {
  118571. float *ptr=book->valuelist+best*dim;
  118572. for(i=0;i<dim;i++)
  118573. *a++ -= *ptr++;
  118574. }
  118575. return(best);
  118576. }
  118577. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118578. codebook *book,long *acc){
  118579. int i,bits=0;
  118580. int dim=book->dim;
  118581. int step=n/dim;
  118582. for(i=0;i<step;i++){
  118583. int entry=local_book_besterror(book,vec+i*dim);
  118584. #ifdef TRAIN_RES
  118585. acc[entry]++;
  118586. #endif
  118587. bits+=vorbis_book_encode(book,entry,opb);
  118588. }
  118589. return(bits);
  118590. }
  118591. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118592. float **in,int ch){
  118593. long i,j,k;
  118594. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118595. vorbis_info_residue0 *info=look->info;
  118596. /* move all this setup out later */
  118597. int samples_per_partition=info->grouping;
  118598. int possible_partitions=info->partitions;
  118599. int n=info->end-info->begin;
  118600. int partvals=n/samples_per_partition;
  118601. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118602. float scale=100./samples_per_partition;
  118603. /* we find the partition type for each partition of each
  118604. channel. We'll go back and do the interleaved encoding in a
  118605. bit. For now, clarity */
  118606. for(i=0;i<ch;i++){
  118607. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118608. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118609. }
  118610. for(i=0;i<partvals;i++){
  118611. int offset=i*samples_per_partition+info->begin;
  118612. for(j=0;j<ch;j++){
  118613. float max=0.;
  118614. float ent=0.;
  118615. for(k=0;k<samples_per_partition;k++){
  118616. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118617. ent+=fabs(rint(in[j][offset+k]));
  118618. }
  118619. ent*=scale;
  118620. for(k=0;k<possible_partitions-1;k++)
  118621. if(max<=info->classmetric1[k] &&
  118622. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118623. break;
  118624. partword[j][i]=k;
  118625. }
  118626. }
  118627. #ifdef TRAIN_RESAUX
  118628. {
  118629. FILE *of;
  118630. char buffer[80];
  118631. for(i=0;i<ch;i++){
  118632. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118633. of=fopen(buffer,"a");
  118634. for(j=0;j<partvals;j++)
  118635. fprintf(of,"%ld, ",partword[i][j]);
  118636. fprintf(of,"\n");
  118637. fclose(of);
  118638. }
  118639. }
  118640. #endif
  118641. look->frames++;
  118642. return(partword);
  118643. }
  118644. /* designed for stereo or other modes where the partition size is an
  118645. integer multiple of the number of channels encoded in the current
  118646. submap */
  118647. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118648. int ch){
  118649. long i,j,k,l;
  118650. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118651. vorbis_info_residue0 *info=look->info;
  118652. /* move all this setup out later */
  118653. int samples_per_partition=info->grouping;
  118654. int possible_partitions=info->partitions;
  118655. int n=info->end-info->begin;
  118656. int partvals=n/samples_per_partition;
  118657. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118658. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118659. FILE *of;
  118660. char buffer[80];
  118661. #endif
  118662. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118663. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118664. for(i=0,l=info->begin/ch;i<partvals;i++){
  118665. float magmax=0.f;
  118666. float angmax=0.f;
  118667. for(j=0;j<samples_per_partition;j+=ch){
  118668. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118669. for(k=1;k<ch;k++)
  118670. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118671. l++;
  118672. }
  118673. for(j=0;j<possible_partitions-1;j++)
  118674. if(magmax<=info->classmetric1[j] &&
  118675. angmax<=info->classmetric2[j])
  118676. break;
  118677. partword[0][i]=j;
  118678. }
  118679. #ifdef TRAIN_RESAUX
  118680. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118681. of=fopen(buffer,"a");
  118682. for(i=0;i<partvals;i++)
  118683. fprintf(of,"%ld, ",partword[0][i]);
  118684. fprintf(of,"\n");
  118685. fclose(of);
  118686. #endif
  118687. look->frames++;
  118688. return(partword);
  118689. }
  118690. static int _01forward(oggpack_buffer *opb,
  118691. vorbis_block *vb,vorbis_look_residue *vl,
  118692. float **in,int ch,
  118693. long **partword,
  118694. int (*encode)(oggpack_buffer *,float *,int,
  118695. codebook *,long *)){
  118696. long i,j,k,s;
  118697. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118698. vorbis_info_residue0 *info=look->info;
  118699. /* move all this setup out later */
  118700. int samples_per_partition=info->grouping;
  118701. int possible_partitions=info->partitions;
  118702. int partitions_per_word=look->phrasebook->dim;
  118703. int n=info->end-info->begin;
  118704. int partvals=n/samples_per_partition;
  118705. long resbits[128];
  118706. long resvals[128];
  118707. #ifdef TRAIN_RES
  118708. for(i=0;i<ch;i++)
  118709. for(j=info->begin;j<info->end;j++){
  118710. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118711. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118712. }
  118713. #endif
  118714. memset(resbits,0,sizeof(resbits));
  118715. memset(resvals,0,sizeof(resvals));
  118716. /* we code the partition words for each channel, then the residual
  118717. words for a partition per channel until we've written all the
  118718. residual words for that partition word. Then write the next
  118719. partition channel words... */
  118720. for(s=0;s<look->stages;s++){
  118721. for(i=0;i<partvals;){
  118722. /* first we encode a partition codeword for each channel */
  118723. if(s==0){
  118724. for(j=0;j<ch;j++){
  118725. long val=partword[j][i];
  118726. for(k=1;k<partitions_per_word;k++){
  118727. val*=possible_partitions;
  118728. if(i+k<partvals)
  118729. val+=partword[j][i+k];
  118730. }
  118731. /* training hack */
  118732. if(val<look->phrasebook->entries)
  118733. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118734. #if 0 /*def TRAIN_RES*/
  118735. else
  118736. fprintf(stderr,"!");
  118737. #endif
  118738. }
  118739. }
  118740. /* now we encode interleaved residual values for the partitions */
  118741. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118742. long offset=i*samples_per_partition+info->begin;
  118743. for(j=0;j<ch;j++){
  118744. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118745. if(info->secondstages[partword[j][i]]&(1<<s)){
  118746. codebook *statebook=look->partbooks[partword[j][i]][s];
  118747. if(statebook){
  118748. int ret;
  118749. long *accumulator=NULL;
  118750. #ifdef TRAIN_RES
  118751. accumulator=look->training_data[s][partword[j][i]];
  118752. {
  118753. int l;
  118754. float *samples=in[j]+offset;
  118755. for(l=0;l<samples_per_partition;l++){
  118756. if(samples[l]<look->training_min[s][partword[j][i]])
  118757. look->training_min[s][partword[j][i]]=samples[l];
  118758. if(samples[l]>look->training_max[s][partword[j][i]])
  118759. look->training_max[s][partword[j][i]]=samples[l];
  118760. }
  118761. }
  118762. #endif
  118763. ret=encode(opb,in[j]+offset,samples_per_partition,
  118764. statebook,accumulator);
  118765. look->postbits+=ret;
  118766. resbits[partword[j][i]]+=ret;
  118767. }
  118768. }
  118769. }
  118770. }
  118771. }
  118772. }
  118773. /*{
  118774. long total=0;
  118775. long totalbits=0;
  118776. fprintf(stderr,"%d :: ",vb->mode);
  118777. for(k=0;k<possible_partitions;k++){
  118778. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118779. total+=resvals[k];
  118780. totalbits+=resbits[k];
  118781. }
  118782. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118783. }*/
  118784. return(0);
  118785. }
  118786. /* a truncated packet here just means 'stop working'; it's not an error */
  118787. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118788. float **in,int ch,
  118789. long (*decodepart)(codebook *, float *,
  118790. oggpack_buffer *,int)){
  118791. long i,j,k,l,s;
  118792. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118793. vorbis_info_residue0 *info=look->info;
  118794. /* move all this setup out later */
  118795. int samples_per_partition=info->grouping;
  118796. int partitions_per_word=look->phrasebook->dim;
  118797. int n=info->end-info->begin;
  118798. int partvals=n/samples_per_partition;
  118799. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118800. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118801. for(j=0;j<ch;j++)
  118802. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118803. for(s=0;s<look->stages;s++){
  118804. /* each loop decodes on partition codeword containing
  118805. partitions_pre_word partitions */
  118806. for(i=0,l=0;i<partvals;l++){
  118807. if(s==0){
  118808. /* fetch the partition word for each channel */
  118809. for(j=0;j<ch;j++){
  118810. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118811. if(temp==-1)goto eopbreak;
  118812. partword[j][l]=look->decodemap[temp];
  118813. if(partword[j][l]==NULL)goto errout;
  118814. }
  118815. }
  118816. /* now we decode residual values for the partitions */
  118817. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118818. for(j=0;j<ch;j++){
  118819. long offset=info->begin+i*samples_per_partition;
  118820. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118821. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118822. if(stagebook){
  118823. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118824. samples_per_partition)==-1)goto eopbreak;
  118825. }
  118826. }
  118827. }
  118828. }
  118829. }
  118830. errout:
  118831. eopbreak:
  118832. return(0);
  118833. }
  118834. #if 0
  118835. /* residue 0 and 1 are just slight variants of one another. 0 is
  118836. interleaved, 1 is not */
  118837. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118838. float **in,int *nonzero,int ch){
  118839. /* we encode only the nonzero parts of a bundle */
  118840. int i,used=0;
  118841. for(i=0;i<ch;i++)
  118842. if(nonzero[i])
  118843. in[used++]=in[i];
  118844. if(used)
  118845. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118846. return(_01class(vb,vl,in,used));
  118847. else
  118848. return(0);
  118849. }
  118850. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118851. float **in,float **out,int *nonzero,int ch,
  118852. long **partword){
  118853. /* we encode only the nonzero parts of a bundle */
  118854. int i,j,used=0,n=vb->pcmend/2;
  118855. for(i=0;i<ch;i++)
  118856. if(nonzero[i]){
  118857. if(out)
  118858. for(j=0;j<n;j++)
  118859. out[i][j]+=in[i][j];
  118860. in[used++]=in[i];
  118861. }
  118862. if(used){
  118863. int ret=_01forward(vb,vl,in,used,partword,
  118864. _interleaved_encodepart);
  118865. if(out){
  118866. used=0;
  118867. for(i=0;i<ch;i++)
  118868. if(nonzero[i]){
  118869. for(j=0;j<n;j++)
  118870. out[i][j]-=in[used][j];
  118871. used++;
  118872. }
  118873. }
  118874. return(ret);
  118875. }else{
  118876. return(0);
  118877. }
  118878. }
  118879. #endif
  118880. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118881. float **in,int *nonzero,int ch){
  118882. int i,used=0;
  118883. for(i=0;i<ch;i++)
  118884. if(nonzero[i])
  118885. in[used++]=in[i];
  118886. if(used)
  118887. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118888. else
  118889. return(0);
  118890. }
  118891. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118892. float **in,float **out,int *nonzero,int ch,
  118893. long **partword){
  118894. int i,j,used=0,n=vb->pcmend/2;
  118895. for(i=0;i<ch;i++)
  118896. if(nonzero[i]){
  118897. if(out)
  118898. for(j=0;j<n;j++)
  118899. out[i][j]+=in[i][j];
  118900. in[used++]=in[i];
  118901. }
  118902. if(used){
  118903. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118904. if(out){
  118905. used=0;
  118906. for(i=0;i<ch;i++)
  118907. if(nonzero[i]){
  118908. for(j=0;j<n;j++)
  118909. out[i][j]-=in[used][j];
  118910. used++;
  118911. }
  118912. }
  118913. return(ret);
  118914. }else{
  118915. return(0);
  118916. }
  118917. }
  118918. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118919. float **in,int *nonzero,int ch){
  118920. int i,used=0;
  118921. for(i=0;i<ch;i++)
  118922. if(nonzero[i])
  118923. in[used++]=in[i];
  118924. if(used)
  118925. return(_01class(vb,vl,in,used));
  118926. else
  118927. return(0);
  118928. }
  118929. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118930. float **in,int *nonzero,int ch){
  118931. int i,used=0;
  118932. for(i=0;i<ch;i++)
  118933. if(nonzero[i])
  118934. in[used++]=in[i];
  118935. if(used)
  118936. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118937. else
  118938. return(0);
  118939. }
  118940. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118941. float **in,int *nonzero,int ch){
  118942. int i,used=0;
  118943. for(i=0;i<ch;i++)
  118944. if(nonzero[i])used++;
  118945. if(used)
  118946. return(_2class(vb,vl,in,ch));
  118947. else
  118948. return(0);
  118949. }
  118950. /* res2 is slightly more different; all the channels are interleaved
  118951. into a single vector and encoded. */
  118952. int res2_forward(oggpack_buffer *opb,
  118953. vorbis_block *vb,vorbis_look_residue *vl,
  118954. float **in,float **out,int *nonzero,int ch,
  118955. long **partword){
  118956. long i,j,k,n=vb->pcmend/2,used=0;
  118957. /* don't duplicate the code; use a working vector hack for now and
  118958. reshape ourselves into a single channel res1 */
  118959. /* ugly; reallocs for each coupling pass :-( */
  118960. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118961. for(i=0;i<ch;i++){
  118962. float *pcm=in[i];
  118963. if(nonzero[i])used++;
  118964. for(j=0,k=i;j<n;j++,k+=ch)
  118965. work[k]=pcm[j];
  118966. }
  118967. if(used){
  118968. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118969. /* update the sofar vector */
  118970. if(out){
  118971. for(i=0;i<ch;i++){
  118972. float *pcm=in[i];
  118973. float *sofar=out[i];
  118974. for(j=0,k=i;j<n;j++,k+=ch)
  118975. sofar[j]+=pcm[j]-work[k];
  118976. }
  118977. }
  118978. return(ret);
  118979. }else{
  118980. return(0);
  118981. }
  118982. }
  118983. /* duplicate code here as speed is somewhat more important */
  118984. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118985. float **in,int *nonzero,int ch){
  118986. long i,k,l,s;
  118987. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118988. vorbis_info_residue0 *info=look->info;
  118989. /* move all this setup out later */
  118990. int samples_per_partition=info->grouping;
  118991. int partitions_per_word=look->phrasebook->dim;
  118992. int n=info->end-info->begin;
  118993. int partvals=n/samples_per_partition;
  118994. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118995. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118996. for(i=0;i<ch;i++)if(nonzero[i])break;
  118997. if(i==ch)return(0); /* no nonzero vectors */
  118998. for(s=0;s<look->stages;s++){
  118999. for(i=0,l=0;i<partvals;l++){
  119000. if(s==0){
  119001. /* fetch the partition word */
  119002. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  119003. if(temp==-1)goto eopbreak;
  119004. partword[l]=look->decodemap[temp];
  119005. if(partword[l]==NULL)goto errout;
  119006. }
  119007. /* now we decode residual values for the partitions */
  119008. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  119009. if(info->secondstages[partword[l][k]]&(1<<s)){
  119010. codebook *stagebook=look->partbooks[partword[l][k]][s];
  119011. if(stagebook){
  119012. if(vorbis_book_decodevv_add(stagebook,in,
  119013. i*samples_per_partition+info->begin,ch,
  119014. &vb->opb,samples_per_partition)==-1)
  119015. goto eopbreak;
  119016. }
  119017. }
  119018. }
  119019. }
  119020. errout:
  119021. eopbreak:
  119022. return(0);
  119023. }
  119024. vorbis_func_residue residue0_exportbundle={
  119025. NULL,
  119026. &res0_unpack,
  119027. &res0_look,
  119028. &res0_free_info,
  119029. &res0_free_look,
  119030. NULL,
  119031. NULL,
  119032. &res0_inverse
  119033. };
  119034. vorbis_func_residue residue1_exportbundle={
  119035. &res0_pack,
  119036. &res0_unpack,
  119037. &res0_look,
  119038. &res0_free_info,
  119039. &res0_free_look,
  119040. &res1_class,
  119041. &res1_forward,
  119042. &res1_inverse
  119043. };
  119044. vorbis_func_residue residue2_exportbundle={
  119045. &res0_pack,
  119046. &res0_unpack,
  119047. &res0_look,
  119048. &res0_free_info,
  119049. &res0_free_look,
  119050. &res2_class,
  119051. &res2_forward,
  119052. &res2_inverse
  119053. };
  119054. #endif
  119055. /*** End of inlined file: res0.c ***/
  119056. /*** Start of inlined file: sharedbook.c ***/
  119057. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119058. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119059. // tasks..
  119060. #if JUCE_MSVC
  119061. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119062. #endif
  119063. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119064. #if JUCE_USE_OGGVORBIS
  119065. #include <stdlib.h>
  119066. #include <math.h>
  119067. #include <string.h>
  119068. /**** pack/unpack helpers ******************************************/
  119069. int _ilog(unsigned int v){
  119070. int ret=0;
  119071. while(v){
  119072. ret++;
  119073. v>>=1;
  119074. }
  119075. return(ret);
  119076. }
  119077. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119078. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119079. Why not IEEE? It's just not that important here. */
  119080. #define VQ_FEXP 10
  119081. #define VQ_FMAN 21
  119082. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119083. /* doesn't currently guard under/overflow */
  119084. long _float32_pack(float val){
  119085. int sign=0;
  119086. long exp;
  119087. long mant;
  119088. if(val<0){
  119089. sign=0x80000000;
  119090. val= -val;
  119091. }
  119092. exp= floor(log(val)/log(2.f));
  119093. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119094. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119095. return(sign|exp|mant);
  119096. }
  119097. float _float32_unpack(long val){
  119098. double mant=val&0x1fffff;
  119099. int sign=val&0x80000000;
  119100. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119101. if(sign)mant= -mant;
  119102. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119103. }
  119104. /* given a list of word lengths, generate a list of codewords. Works
  119105. for length ordered or unordered, always assigns the lowest valued
  119106. codewords first. Extended to handle unused entries (length 0) */
  119107. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119108. long i,j,count=0;
  119109. ogg_uint32_t marker[33];
  119110. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119111. memset(marker,0,sizeof(marker));
  119112. for(i=0;i<n;i++){
  119113. long length=l[i];
  119114. if(length>0){
  119115. ogg_uint32_t entry=marker[length];
  119116. /* when we claim a node for an entry, we also claim the nodes
  119117. below it (pruning off the imagined tree that may have dangled
  119118. from it) as well as blocking the use of any nodes directly
  119119. above for leaves */
  119120. /* update ourself */
  119121. if(length<32 && (entry>>length)){
  119122. /* error condition; the lengths must specify an overpopulated tree */
  119123. _ogg_free(r);
  119124. return(NULL);
  119125. }
  119126. r[count++]=entry;
  119127. /* Look to see if the next shorter marker points to the node
  119128. above. if so, update it and repeat. */
  119129. {
  119130. for(j=length;j>0;j--){
  119131. if(marker[j]&1){
  119132. /* have to jump branches */
  119133. if(j==1)
  119134. marker[1]++;
  119135. else
  119136. marker[j]=marker[j-1]<<1;
  119137. break; /* invariant says next upper marker would already
  119138. have been moved if it was on the same path */
  119139. }
  119140. marker[j]++;
  119141. }
  119142. }
  119143. /* prune the tree; the implicit invariant says all the longer
  119144. markers were dangling from our just-taken node. Dangle them
  119145. from our *new* node. */
  119146. for(j=length+1;j<33;j++)
  119147. if((marker[j]>>1) == entry){
  119148. entry=marker[j];
  119149. marker[j]=marker[j-1]<<1;
  119150. }else
  119151. break;
  119152. }else
  119153. if(sparsecount==0)count++;
  119154. }
  119155. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119156. endian */
  119157. for(i=0,count=0;i<n;i++){
  119158. ogg_uint32_t temp=0;
  119159. for(j=0;j<l[i];j++){
  119160. temp<<=1;
  119161. temp|=(r[count]>>j)&1;
  119162. }
  119163. if(sparsecount){
  119164. if(l[i])
  119165. r[count++]=temp;
  119166. }else
  119167. r[count++]=temp;
  119168. }
  119169. return(r);
  119170. }
  119171. /* there might be a straightforward one-line way to do the below
  119172. that's portable and totally safe against roundoff, but I haven't
  119173. thought of it. Therefore, we opt on the side of caution */
  119174. long _book_maptype1_quantvals(const static_codebook *b){
  119175. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119176. /* the above *should* be reliable, but we'll not assume that FP is
  119177. ever reliable when bitstream sync is at stake; verify via integer
  119178. means that vals really is the greatest value of dim for which
  119179. vals^b->bim <= b->entries */
  119180. /* treat the above as an initial guess */
  119181. while(1){
  119182. long acc=1;
  119183. long acc1=1;
  119184. int i;
  119185. for(i=0;i<b->dim;i++){
  119186. acc*=vals;
  119187. acc1*=vals+1;
  119188. }
  119189. if(acc<=b->entries && acc1>b->entries){
  119190. return(vals);
  119191. }else{
  119192. if(acc>b->entries){
  119193. vals--;
  119194. }else{
  119195. vals++;
  119196. }
  119197. }
  119198. }
  119199. }
  119200. /* unpack the quantized list of values for encode/decode ***********/
  119201. /* we need to deal with two map types: in map type 1, the values are
  119202. generated algorithmically (each column of the vector counts through
  119203. the values in the quant vector). in map type 2, all the values came
  119204. in in an explicit list. Both value lists must be unpacked */
  119205. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119206. long j,k,count=0;
  119207. if(b->maptype==1 || b->maptype==2){
  119208. int quantvals;
  119209. float mindel=_float32_unpack(b->q_min);
  119210. float delta=_float32_unpack(b->q_delta);
  119211. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119212. /* maptype 1 and 2 both use a quantized value vector, but
  119213. different sizes */
  119214. switch(b->maptype){
  119215. case 1:
  119216. /* most of the time, entries%dimensions == 0, but we need to be
  119217. well defined. We define that the possible vales at each
  119218. scalar is values == entries/dim. If entries%dim != 0, we'll
  119219. have 'too few' values (values*dim<entries), which means that
  119220. we'll have 'left over' entries; left over entries use zeroed
  119221. values (and are wasted). So don't generate codebooks like
  119222. that */
  119223. quantvals=_book_maptype1_quantvals(b);
  119224. for(j=0;j<b->entries;j++){
  119225. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119226. float last=0.f;
  119227. int indexdiv=1;
  119228. for(k=0;k<b->dim;k++){
  119229. int index= (j/indexdiv)%quantvals;
  119230. float val=b->quantlist[index];
  119231. val=fabs(val)*delta+mindel+last;
  119232. if(b->q_sequencep)last=val;
  119233. if(sparsemap)
  119234. r[sparsemap[count]*b->dim+k]=val;
  119235. else
  119236. r[count*b->dim+k]=val;
  119237. indexdiv*=quantvals;
  119238. }
  119239. count++;
  119240. }
  119241. }
  119242. break;
  119243. case 2:
  119244. for(j=0;j<b->entries;j++){
  119245. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119246. float last=0.f;
  119247. for(k=0;k<b->dim;k++){
  119248. float val=b->quantlist[j*b->dim+k];
  119249. val=fabs(val)*delta+mindel+last;
  119250. if(b->q_sequencep)last=val;
  119251. if(sparsemap)
  119252. r[sparsemap[count]*b->dim+k]=val;
  119253. else
  119254. r[count*b->dim+k]=val;
  119255. }
  119256. count++;
  119257. }
  119258. }
  119259. break;
  119260. }
  119261. return(r);
  119262. }
  119263. return(NULL);
  119264. }
  119265. void vorbis_staticbook_clear(static_codebook *b){
  119266. if(b->allocedp){
  119267. if(b->quantlist)_ogg_free(b->quantlist);
  119268. if(b->lengthlist)_ogg_free(b->lengthlist);
  119269. if(b->nearest_tree){
  119270. _ogg_free(b->nearest_tree->ptr0);
  119271. _ogg_free(b->nearest_tree->ptr1);
  119272. _ogg_free(b->nearest_tree->p);
  119273. _ogg_free(b->nearest_tree->q);
  119274. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119275. _ogg_free(b->nearest_tree);
  119276. }
  119277. if(b->thresh_tree){
  119278. _ogg_free(b->thresh_tree->quantthresh);
  119279. _ogg_free(b->thresh_tree->quantmap);
  119280. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119281. _ogg_free(b->thresh_tree);
  119282. }
  119283. memset(b,0,sizeof(*b));
  119284. }
  119285. }
  119286. void vorbis_staticbook_destroy(static_codebook *b){
  119287. if(b->allocedp){
  119288. vorbis_staticbook_clear(b);
  119289. _ogg_free(b);
  119290. }
  119291. }
  119292. void vorbis_book_clear(codebook *b){
  119293. /* static book is not cleared; we're likely called on the lookup and
  119294. the static codebook belongs to the info struct */
  119295. if(b->valuelist)_ogg_free(b->valuelist);
  119296. if(b->codelist)_ogg_free(b->codelist);
  119297. if(b->dec_index)_ogg_free(b->dec_index);
  119298. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119299. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119300. memset(b,0,sizeof(*b));
  119301. }
  119302. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119303. memset(c,0,sizeof(*c));
  119304. c->c=s;
  119305. c->entries=s->entries;
  119306. c->used_entries=s->entries;
  119307. c->dim=s->dim;
  119308. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119309. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119310. return(0);
  119311. }
  119312. static int JUCE_CDECL sort32a(const void *a,const void *b){
  119313. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119314. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119315. }
  119316. /* decode codebook arrangement is more heavily optimized than encode */
  119317. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119318. int i,j,n=0,tabn;
  119319. int *sortindex;
  119320. memset(c,0,sizeof(*c));
  119321. /* count actually used entries */
  119322. for(i=0;i<s->entries;i++)
  119323. if(s->lengthlist[i]>0)
  119324. n++;
  119325. c->entries=s->entries;
  119326. c->used_entries=n;
  119327. c->dim=s->dim;
  119328. /* two different remappings go on here.
  119329. First, we collapse the likely sparse codebook down only to
  119330. actually represented values/words. This collapsing needs to be
  119331. indexed as map-valueless books are used to encode original entry
  119332. positions as integers.
  119333. Second, we reorder all vectors, including the entry index above,
  119334. by sorted bitreversed codeword to allow treeless decode. */
  119335. {
  119336. /* perform sort */
  119337. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119338. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119339. if(codes==NULL)goto err_out;
  119340. for(i=0;i<n;i++){
  119341. codes[i]=ogg_bitreverse(codes[i]);
  119342. codep[i]=codes+i;
  119343. }
  119344. qsort(codep,n,sizeof(*codep),sort32a);
  119345. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119346. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119347. /* the index is a reverse index */
  119348. for(i=0;i<n;i++){
  119349. int position=codep[i]-codes;
  119350. sortindex[position]=i;
  119351. }
  119352. for(i=0;i<n;i++)
  119353. c->codelist[sortindex[i]]=codes[i];
  119354. _ogg_free(codes);
  119355. }
  119356. c->valuelist=_book_unquantize(s,n,sortindex);
  119357. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119358. for(n=0,i=0;i<s->entries;i++)
  119359. if(s->lengthlist[i]>0)
  119360. c->dec_index[sortindex[n++]]=i;
  119361. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119362. for(n=0,i=0;i<s->entries;i++)
  119363. if(s->lengthlist[i]>0)
  119364. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119365. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119366. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119367. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119368. tabn=1<<c->dec_firsttablen;
  119369. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119370. c->dec_maxlength=0;
  119371. for(i=0;i<n;i++){
  119372. if(c->dec_maxlength<c->dec_codelengths[i])
  119373. c->dec_maxlength=c->dec_codelengths[i];
  119374. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119375. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119376. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119377. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119378. }
  119379. }
  119380. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119381. hints for the non-direct-hits */
  119382. {
  119383. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119384. long lo=0,hi=0;
  119385. for(i=0;i<tabn;i++){
  119386. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119387. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119388. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119389. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119390. /* we only actually have 15 bits per hint to play with here.
  119391. In order to overflow gracefully (nothing breaks, efficiency
  119392. just drops), encode as the difference from the extremes. */
  119393. {
  119394. unsigned long loval=lo;
  119395. unsigned long hival=n-hi;
  119396. if(loval>0x7fff)loval=0x7fff;
  119397. if(hival>0x7fff)hival=0x7fff;
  119398. c->dec_firsttable[ogg_bitreverse(word)]=
  119399. 0x80000000UL | (loval<<15) | hival;
  119400. }
  119401. }
  119402. }
  119403. }
  119404. return(0);
  119405. err_out:
  119406. vorbis_book_clear(c);
  119407. return(-1);
  119408. }
  119409. static float _dist(int el,float *ref, float *b,int step){
  119410. int i;
  119411. float acc=0.f;
  119412. for(i=0;i<el;i++){
  119413. float val=(ref[i]-b[i*step]);
  119414. acc+=val*val;
  119415. }
  119416. return(acc);
  119417. }
  119418. int _best(codebook *book, float *a, int step){
  119419. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119420. #if 0
  119421. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119422. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119423. #endif
  119424. int dim=book->dim;
  119425. int k,o;
  119426. /*int savebest=-1;
  119427. float saverr;*/
  119428. /* do we have a threshhold encode hint? */
  119429. if(tt){
  119430. int index=0,i;
  119431. /* find the quant val of each scalar */
  119432. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119433. i=tt->threshvals>>1;
  119434. if(a[o]<tt->quantthresh[i]){
  119435. for(;i>0;i--)
  119436. if(a[o]>=tt->quantthresh[i-1])
  119437. break;
  119438. }else{
  119439. for(i++;i<tt->threshvals-1;i++)
  119440. if(a[o]<tt->quantthresh[i])break;
  119441. }
  119442. index=(index*tt->quantvals)+tt->quantmap[i];
  119443. }
  119444. /* regular lattices are easy :-) */
  119445. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119446. use a decision tree after all
  119447. and fall through*/
  119448. return(index);
  119449. }
  119450. #if 0
  119451. /* do we have a pigeonhole encode hint? */
  119452. if(pt){
  119453. const static_codebook *c=book->c;
  119454. int i,besti=-1;
  119455. float best=0.f;
  119456. int entry=0;
  119457. /* dealing with sequentialness is a pain in the ass */
  119458. if(c->q_sequencep){
  119459. int pv;
  119460. long mul=1;
  119461. float qlast=0;
  119462. for(k=0,o=0;k<dim;k++,o+=step){
  119463. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119464. if(pv<0 || pv>=pt->mapentries)break;
  119465. entry+=pt->pigeonmap[pv]*mul;
  119466. mul*=pt->quantvals;
  119467. qlast+=pv*pt->del+pt->min;
  119468. }
  119469. }else{
  119470. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119471. int pv=(int)((a[o]-pt->min)/pt->del);
  119472. if(pv<0 || pv>=pt->mapentries)break;
  119473. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119474. }
  119475. }
  119476. /* must be within the pigeonholable range; if we quant outside (or
  119477. in an entry that we define no list for), brute force it */
  119478. if(k==dim && pt->fitlength[entry]){
  119479. /* search the abbreviated list */
  119480. long *list=pt->fitlist+pt->fitmap[entry];
  119481. for(i=0;i<pt->fitlength[entry];i++){
  119482. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119483. if(besti==-1 || this<best){
  119484. best=this;
  119485. besti=list[i];
  119486. }
  119487. }
  119488. return(besti);
  119489. }
  119490. }
  119491. if(nt){
  119492. /* optimized using the decision tree */
  119493. while(1){
  119494. float c=0.f;
  119495. float *p=book->valuelist+nt->p[ptr];
  119496. float *q=book->valuelist+nt->q[ptr];
  119497. for(k=0,o=0;k<dim;k++,o+=step)
  119498. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119499. if(c>0.f) /* in A */
  119500. ptr= -nt->ptr0[ptr];
  119501. else /* in B */
  119502. ptr= -nt->ptr1[ptr];
  119503. if(ptr<=0)break;
  119504. }
  119505. return(-ptr);
  119506. }
  119507. #endif
  119508. /* brute force it! */
  119509. {
  119510. const static_codebook *c=book->c;
  119511. int i,besti=-1;
  119512. float best=0.f;
  119513. float *e=book->valuelist;
  119514. for(i=0;i<book->entries;i++){
  119515. if(c->lengthlist[i]>0){
  119516. float thisx=_dist(dim,e,a,step);
  119517. if(besti==-1 || thisx<best){
  119518. best=thisx;
  119519. besti=i;
  119520. }
  119521. }
  119522. e+=dim;
  119523. }
  119524. /*if(savebest!=-1 && savebest!=besti){
  119525. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119526. "original:");
  119527. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119528. fprintf(stderr,"\n"
  119529. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119530. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119531. (book->valuelist+savebest*dim)[i]);
  119532. fprintf(stderr,"\n"
  119533. "bruteforce (entry %d, err %g):",besti,best);
  119534. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119535. (book->valuelist+besti*dim)[i]);
  119536. fprintf(stderr,"\n");
  119537. }*/
  119538. return(besti);
  119539. }
  119540. }
  119541. long vorbis_book_codeword(codebook *book,int entry){
  119542. if(book->c) /* only use with encode; decode optimizations are
  119543. allowed to break this */
  119544. return book->codelist[entry];
  119545. return -1;
  119546. }
  119547. long vorbis_book_codelen(codebook *book,int entry){
  119548. if(book->c) /* only use with encode; decode optimizations are
  119549. allowed to break this */
  119550. return book->c->lengthlist[entry];
  119551. return -1;
  119552. }
  119553. #ifdef _V_SELFTEST
  119554. /* Unit tests of the dequantizer; this stuff will be OK
  119555. cross-platform, I simply want to be sure that special mapping cases
  119556. actually work properly; a bug could go unnoticed for a while */
  119557. #include <stdio.h>
  119558. /* cases:
  119559. no mapping
  119560. full, explicit mapping
  119561. algorithmic mapping
  119562. nonsequential
  119563. sequential
  119564. */
  119565. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119566. static long partial_quantlist1[]={0,7,2};
  119567. /* no mapping */
  119568. static_codebook test1={
  119569. 4,16,
  119570. NULL,
  119571. 0,
  119572. 0,0,0,0,
  119573. NULL,
  119574. NULL,NULL
  119575. };
  119576. static float *test1_result=NULL;
  119577. /* linear, full mapping, nonsequential */
  119578. static_codebook test2={
  119579. 4,3,
  119580. NULL,
  119581. 2,
  119582. -533200896,1611661312,4,0,
  119583. full_quantlist1,
  119584. NULL,NULL
  119585. };
  119586. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119587. /* linear, full mapping, sequential */
  119588. static_codebook test3={
  119589. 4,3,
  119590. NULL,
  119591. 2,
  119592. -533200896,1611661312,4,1,
  119593. full_quantlist1,
  119594. NULL,NULL
  119595. };
  119596. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119597. /* linear, algorithmic mapping, nonsequential */
  119598. static_codebook test4={
  119599. 3,27,
  119600. NULL,
  119601. 1,
  119602. -533200896,1611661312,4,0,
  119603. partial_quantlist1,
  119604. NULL,NULL
  119605. };
  119606. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119607. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119608. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119609. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119610. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119611. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119612. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119613. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119614. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119615. /* linear, algorithmic mapping, sequential */
  119616. static_codebook test5={
  119617. 3,27,
  119618. NULL,
  119619. 1,
  119620. -533200896,1611661312,4,1,
  119621. partial_quantlist1,
  119622. NULL,NULL
  119623. };
  119624. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119625. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119626. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119627. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119628. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119629. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119630. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119631. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119632. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119633. void run_test(static_codebook *b,float *comp){
  119634. float *out=_book_unquantize(b,b->entries,NULL);
  119635. int i;
  119636. if(comp){
  119637. if(!out){
  119638. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119639. exit(1);
  119640. }
  119641. for(i=0;i<b->entries*b->dim;i++)
  119642. if(fabs(out[i]-comp[i])>.0001){
  119643. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119644. "position %d, %g != %g\n",i,out[i],comp[i]);
  119645. exit(1);
  119646. }
  119647. }else{
  119648. if(out){
  119649. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119650. " correct result should have been NULL\n");
  119651. exit(1);
  119652. }
  119653. }
  119654. }
  119655. int main(){
  119656. /* run the nine dequant tests, and compare to the hand-rolled results */
  119657. fprintf(stderr,"Dequant test 1... ");
  119658. run_test(&test1,test1_result);
  119659. fprintf(stderr,"OK\nDequant test 2... ");
  119660. run_test(&test2,test2_result);
  119661. fprintf(stderr,"OK\nDequant test 3... ");
  119662. run_test(&test3,test3_result);
  119663. fprintf(stderr,"OK\nDequant test 4... ");
  119664. run_test(&test4,test4_result);
  119665. fprintf(stderr,"OK\nDequant test 5... ");
  119666. run_test(&test5,test5_result);
  119667. fprintf(stderr,"OK\n\n");
  119668. return(0);
  119669. }
  119670. #endif
  119671. #endif
  119672. /*** End of inlined file: sharedbook.c ***/
  119673. /*** Start of inlined file: smallft.c ***/
  119674. /* FFT implementation from OggSquish, minus cosine transforms,
  119675. * minus all but radix 2/4 case. In Vorbis we only need this
  119676. * cut-down version.
  119677. *
  119678. * To do more than just power-of-two sized vectors, see the full
  119679. * version I wrote for NetLib.
  119680. *
  119681. * Note that the packing is a little strange; rather than the FFT r/i
  119682. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119683. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119684. * FORTRAN version
  119685. */
  119686. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  119687. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119688. // tasks..
  119689. #if JUCE_MSVC
  119690. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119691. #endif
  119692. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  119693. #if JUCE_USE_OGGVORBIS
  119694. #include <stdlib.h>
  119695. #include <string.h>
  119696. #include <math.h>
  119697. static void drfti1(int n, float *wa, int *ifac){
  119698. static int ntryh[4] = { 4,2,3,5 };
  119699. static float tpi = 6.28318530717958648f;
  119700. float arg,argh,argld,fi;
  119701. int ntry=0,i,j=-1;
  119702. int k1, l1, l2, ib;
  119703. int ld, ii, ip, is, nq, nr;
  119704. int ido, ipm, nfm1;
  119705. int nl=n;
  119706. int nf=0;
  119707. L101:
  119708. j++;
  119709. if (j < 4)
  119710. ntry=ntryh[j];
  119711. else
  119712. ntry+=2;
  119713. L104:
  119714. nq=nl/ntry;
  119715. nr=nl-ntry*nq;
  119716. if (nr!=0) goto L101;
  119717. nf++;
  119718. ifac[nf+1]=ntry;
  119719. nl=nq;
  119720. if(ntry!=2)goto L107;
  119721. if(nf==1)goto L107;
  119722. for (i=1;i<nf;i++){
  119723. ib=nf-i+1;
  119724. ifac[ib+1]=ifac[ib];
  119725. }
  119726. ifac[2] = 2;
  119727. L107:
  119728. if(nl!=1)goto L104;
  119729. ifac[0]=n;
  119730. ifac[1]=nf;
  119731. argh=tpi/n;
  119732. is=0;
  119733. nfm1=nf-1;
  119734. l1=1;
  119735. if(nfm1==0)return;
  119736. for (k1=0;k1<nfm1;k1++){
  119737. ip=ifac[k1+2];
  119738. ld=0;
  119739. l2=l1*ip;
  119740. ido=n/l2;
  119741. ipm=ip-1;
  119742. for (j=0;j<ipm;j++){
  119743. ld+=l1;
  119744. i=is;
  119745. argld=(float)ld*argh;
  119746. fi=0.f;
  119747. for (ii=2;ii<ido;ii+=2){
  119748. fi+=1.f;
  119749. arg=fi*argld;
  119750. wa[i++]=cos(arg);
  119751. wa[i++]=sin(arg);
  119752. }
  119753. is+=ido;
  119754. }
  119755. l1=l2;
  119756. }
  119757. }
  119758. static void fdrffti(int n, float *wsave, int *ifac){
  119759. if (n == 1) return;
  119760. drfti1(n, wsave+n, ifac);
  119761. }
  119762. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119763. int i,k;
  119764. float ti2,tr2;
  119765. int t0,t1,t2,t3,t4,t5,t6;
  119766. t1=0;
  119767. t0=(t2=l1*ido);
  119768. t3=ido<<1;
  119769. for(k=0;k<l1;k++){
  119770. ch[t1<<1]=cc[t1]+cc[t2];
  119771. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119772. t1+=ido;
  119773. t2+=ido;
  119774. }
  119775. if(ido<2)return;
  119776. if(ido==2)goto L105;
  119777. t1=0;
  119778. t2=t0;
  119779. for(k=0;k<l1;k++){
  119780. t3=t2;
  119781. t4=(t1<<1)+(ido<<1);
  119782. t5=t1;
  119783. t6=t1+t1;
  119784. for(i=2;i<ido;i+=2){
  119785. t3+=2;
  119786. t4-=2;
  119787. t5+=2;
  119788. t6+=2;
  119789. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119790. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119791. ch[t6]=cc[t5]+ti2;
  119792. ch[t4]=ti2-cc[t5];
  119793. ch[t6-1]=cc[t5-1]+tr2;
  119794. ch[t4-1]=cc[t5-1]-tr2;
  119795. }
  119796. t1+=ido;
  119797. t2+=ido;
  119798. }
  119799. if(ido%2==1)return;
  119800. L105:
  119801. t3=(t2=(t1=ido)-1);
  119802. t2+=t0;
  119803. for(k=0;k<l1;k++){
  119804. ch[t1]=-cc[t2];
  119805. ch[t1-1]=cc[t3];
  119806. t1+=ido<<1;
  119807. t2+=ido;
  119808. t3+=ido;
  119809. }
  119810. }
  119811. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119812. float *wa2,float *wa3){
  119813. static float hsqt2 = .70710678118654752f;
  119814. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119815. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119816. t0=l1*ido;
  119817. t1=t0;
  119818. t4=t1<<1;
  119819. t2=t1+(t1<<1);
  119820. t3=0;
  119821. for(k=0;k<l1;k++){
  119822. tr1=cc[t1]+cc[t2];
  119823. tr2=cc[t3]+cc[t4];
  119824. ch[t5=t3<<2]=tr1+tr2;
  119825. ch[(ido<<2)+t5-1]=tr2-tr1;
  119826. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119827. ch[t5]=cc[t2]-cc[t1];
  119828. t1+=ido;
  119829. t2+=ido;
  119830. t3+=ido;
  119831. t4+=ido;
  119832. }
  119833. if(ido<2)return;
  119834. if(ido==2)goto L105;
  119835. t1=0;
  119836. for(k=0;k<l1;k++){
  119837. t2=t1;
  119838. t4=t1<<2;
  119839. t5=(t6=ido<<1)+t4;
  119840. for(i=2;i<ido;i+=2){
  119841. t3=(t2+=2);
  119842. t4+=2;
  119843. t5-=2;
  119844. t3+=t0;
  119845. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119846. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119847. t3+=t0;
  119848. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119849. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119850. t3+=t0;
  119851. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119852. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119853. tr1=cr2+cr4;
  119854. tr4=cr4-cr2;
  119855. ti1=ci2+ci4;
  119856. ti4=ci2-ci4;
  119857. ti2=cc[t2]+ci3;
  119858. ti3=cc[t2]-ci3;
  119859. tr2=cc[t2-1]+cr3;
  119860. tr3=cc[t2-1]-cr3;
  119861. ch[t4-1]=tr1+tr2;
  119862. ch[t4]=ti1+ti2;
  119863. ch[t5-1]=tr3-ti4;
  119864. ch[t5]=tr4-ti3;
  119865. ch[t4+t6-1]=ti4+tr3;
  119866. ch[t4+t6]=tr4+ti3;
  119867. ch[t5+t6-1]=tr2-tr1;
  119868. ch[t5+t6]=ti1-ti2;
  119869. }
  119870. t1+=ido;
  119871. }
  119872. if(ido&1)return;
  119873. L105:
  119874. t2=(t1=t0+ido-1)+(t0<<1);
  119875. t3=ido<<2;
  119876. t4=ido;
  119877. t5=ido<<1;
  119878. t6=ido;
  119879. for(k=0;k<l1;k++){
  119880. ti1=-hsqt2*(cc[t1]+cc[t2]);
  119881. tr1=hsqt2*(cc[t1]-cc[t2]);
  119882. ch[t4-1]=tr1+cc[t6-1];
  119883. ch[t4+t5-1]=cc[t6-1]-tr1;
  119884. ch[t4]=ti1-cc[t1+t0];
  119885. ch[t4+t5]=ti1+cc[t1+t0];
  119886. t1+=ido;
  119887. t2+=ido;
  119888. t4+=t3;
  119889. t6+=ido;
  119890. }
  119891. }
  119892. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  119893. float *c2,float *ch,float *ch2,float *wa){
  119894. static float tpi=6.283185307179586f;
  119895. int idij,ipph,i,j,k,l,ic,ik,is;
  119896. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  119897. float dc2,ai1,ai2,ar1,ar2,ds2;
  119898. int nbd;
  119899. float dcp,arg,dsp,ar1h,ar2h;
  119900. int idp2,ipp2;
  119901. arg=tpi/(float)ip;
  119902. dcp=cos(arg);
  119903. dsp=sin(arg);
  119904. ipph=(ip+1)>>1;
  119905. ipp2=ip;
  119906. idp2=ido;
  119907. nbd=(ido-1)>>1;
  119908. t0=l1*ido;
  119909. t10=ip*ido;
  119910. if(ido==1)goto L119;
  119911. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  119912. t1=0;
  119913. for(j=1;j<ip;j++){
  119914. t1+=t0;
  119915. t2=t1;
  119916. for(k=0;k<l1;k++){
  119917. ch[t2]=c1[t2];
  119918. t2+=ido;
  119919. }
  119920. }
  119921. is=-ido;
  119922. t1=0;
  119923. if(nbd>l1){
  119924. for(j=1;j<ip;j++){
  119925. t1+=t0;
  119926. is+=ido;
  119927. t2= -ido+t1;
  119928. for(k=0;k<l1;k++){
  119929. idij=is-1;
  119930. t2+=ido;
  119931. t3=t2;
  119932. for(i=2;i<ido;i+=2){
  119933. idij+=2;
  119934. t3+=2;
  119935. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119936. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119937. }
  119938. }
  119939. }
  119940. }else{
  119941. for(j=1;j<ip;j++){
  119942. is+=ido;
  119943. idij=is-1;
  119944. t1+=t0;
  119945. t2=t1;
  119946. for(i=2;i<ido;i+=2){
  119947. idij+=2;
  119948. t2+=2;
  119949. t3=t2;
  119950. for(k=0;k<l1;k++){
  119951. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  119952. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  119953. t3+=ido;
  119954. }
  119955. }
  119956. }
  119957. }
  119958. t1=0;
  119959. t2=ipp2*t0;
  119960. if(nbd<l1){
  119961. for(j=1;j<ipph;j++){
  119962. t1+=t0;
  119963. t2-=t0;
  119964. t3=t1;
  119965. t4=t2;
  119966. for(i=2;i<ido;i+=2){
  119967. t3+=2;
  119968. t4+=2;
  119969. t5=t3-ido;
  119970. t6=t4-ido;
  119971. for(k=0;k<l1;k++){
  119972. t5+=ido;
  119973. t6+=ido;
  119974. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119975. c1[t6-1]=ch[t5]-ch[t6];
  119976. c1[t5]=ch[t5]+ch[t6];
  119977. c1[t6]=ch[t6-1]-ch[t5-1];
  119978. }
  119979. }
  119980. }
  119981. }else{
  119982. for(j=1;j<ipph;j++){
  119983. t1+=t0;
  119984. t2-=t0;
  119985. t3=t1;
  119986. t4=t2;
  119987. for(k=0;k<l1;k++){
  119988. t5=t3;
  119989. t6=t4;
  119990. for(i=2;i<ido;i+=2){
  119991. t5+=2;
  119992. t6+=2;
  119993. c1[t5-1]=ch[t5-1]+ch[t6-1];
  119994. c1[t6-1]=ch[t5]-ch[t6];
  119995. c1[t5]=ch[t5]+ch[t6];
  119996. c1[t6]=ch[t6-1]-ch[t5-1];
  119997. }
  119998. t3+=ido;
  119999. t4+=ido;
  120000. }
  120001. }
  120002. }
  120003. L119:
  120004. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120005. t1=0;
  120006. t2=ipp2*idl1;
  120007. for(j=1;j<ipph;j++){
  120008. t1+=t0;
  120009. t2-=t0;
  120010. t3=t1-ido;
  120011. t4=t2-ido;
  120012. for(k=0;k<l1;k++){
  120013. t3+=ido;
  120014. t4+=ido;
  120015. c1[t3]=ch[t3]+ch[t4];
  120016. c1[t4]=ch[t4]-ch[t3];
  120017. }
  120018. }
  120019. ar1=1.f;
  120020. ai1=0.f;
  120021. t1=0;
  120022. t2=ipp2*idl1;
  120023. t3=(ip-1)*idl1;
  120024. for(l=1;l<ipph;l++){
  120025. t1+=idl1;
  120026. t2-=idl1;
  120027. ar1h=dcp*ar1-dsp*ai1;
  120028. ai1=dcp*ai1+dsp*ar1;
  120029. ar1=ar1h;
  120030. t4=t1;
  120031. t5=t2;
  120032. t6=t3;
  120033. t7=idl1;
  120034. for(ik=0;ik<idl1;ik++){
  120035. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  120036. ch2[t5++]=ai1*c2[t6++];
  120037. }
  120038. dc2=ar1;
  120039. ds2=ai1;
  120040. ar2=ar1;
  120041. ai2=ai1;
  120042. t4=idl1;
  120043. t5=(ipp2-1)*idl1;
  120044. for(j=2;j<ipph;j++){
  120045. t4+=idl1;
  120046. t5-=idl1;
  120047. ar2h=dc2*ar2-ds2*ai2;
  120048. ai2=dc2*ai2+ds2*ar2;
  120049. ar2=ar2h;
  120050. t6=t1;
  120051. t7=t2;
  120052. t8=t4;
  120053. t9=t5;
  120054. for(ik=0;ik<idl1;ik++){
  120055. ch2[t6++]+=ar2*c2[t8++];
  120056. ch2[t7++]+=ai2*c2[t9++];
  120057. }
  120058. }
  120059. }
  120060. t1=0;
  120061. for(j=1;j<ipph;j++){
  120062. t1+=idl1;
  120063. t2=t1;
  120064. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120065. }
  120066. if(ido<l1)goto L132;
  120067. t1=0;
  120068. t2=0;
  120069. for(k=0;k<l1;k++){
  120070. t3=t1;
  120071. t4=t2;
  120072. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120073. t1+=ido;
  120074. t2+=t10;
  120075. }
  120076. goto L135;
  120077. L132:
  120078. for(i=0;i<ido;i++){
  120079. t1=i;
  120080. t2=i;
  120081. for(k=0;k<l1;k++){
  120082. cc[t2]=ch[t1];
  120083. t1+=ido;
  120084. t2+=t10;
  120085. }
  120086. }
  120087. L135:
  120088. t1=0;
  120089. t2=ido<<1;
  120090. t3=0;
  120091. t4=ipp2*t0;
  120092. for(j=1;j<ipph;j++){
  120093. t1+=t2;
  120094. t3+=t0;
  120095. t4-=t0;
  120096. t5=t1;
  120097. t6=t3;
  120098. t7=t4;
  120099. for(k=0;k<l1;k++){
  120100. cc[t5-1]=ch[t6];
  120101. cc[t5]=ch[t7];
  120102. t5+=t10;
  120103. t6+=ido;
  120104. t7+=ido;
  120105. }
  120106. }
  120107. if(ido==1)return;
  120108. if(nbd<l1)goto L141;
  120109. t1=-ido;
  120110. t3=0;
  120111. t4=0;
  120112. t5=ipp2*t0;
  120113. for(j=1;j<ipph;j++){
  120114. t1+=t2;
  120115. t3+=t2;
  120116. t4+=t0;
  120117. t5-=t0;
  120118. t6=t1;
  120119. t7=t3;
  120120. t8=t4;
  120121. t9=t5;
  120122. for(k=0;k<l1;k++){
  120123. for(i=2;i<ido;i+=2){
  120124. ic=idp2-i;
  120125. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120126. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120127. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120128. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120129. }
  120130. t6+=t10;
  120131. t7+=t10;
  120132. t8+=ido;
  120133. t9+=ido;
  120134. }
  120135. }
  120136. return;
  120137. L141:
  120138. t1=-ido;
  120139. t3=0;
  120140. t4=0;
  120141. t5=ipp2*t0;
  120142. for(j=1;j<ipph;j++){
  120143. t1+=t2;
  120144. t3+=t2;
  120145. t4+=t0;
  120146. t5-=t0;
  120147. for(i=2;i<ido;i+=2){
  120148. t6=idp2+t1-i;
  120149. t7=i+t3;
  120150. t8=i+t4;
  120151. t9=i+t5;
  120152. for(k=0;k<l1;k++){
  120153. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120154. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120155. cc[t7]=ch[t8]+ch[t9];
  120156. cc[t6]=ch[t9]-ch[t8];
  120157. t6+=t10;
  120158. t7+=t10;
  120159. t8+=ido;
  120160. t9+=ido;
  120161. }
  120162. }
  120163. }
  120164. }
  120165. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120166. int i,k1,l1,l2;
  120167. int na,kh,nf;
  120168. int ip,iw,ido,idl1,ix2,ix3;
  120169. nf=ifac[1];
  120170. na=1;
  120171. l2=n;
  120172. iw=n;
  120173. for(k1=0;k1<nf;k1++){
  120174. kh=nf-k1;
  120175. ip=ifac[kh+1];
  120176. l1=l2/ip;
  120177. ido=n/l2;
  120178. idl1=ido*l1;
  120179. iw-=(ip-1)*ido;
  120180. na=1-na;
  120181. if(ip!=4)goto L102;
  120182. ix2=iw+ido;
  120183. ix3=ix2+ido;
  120184. if(na!=0)
  120185. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120186. else
  120187. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120188. goto L110;
  120189. L102:
  120190. if(ip!=2)goto L104;
  120191. if(na!=0)goto L103;
  120192. dradf2(ido,l1,c,ch,wa+iw-1);
  120193. goto L110;
  120194. L103:
  120195. dradf2(ido,l1,ch,c,wa+iw-1);
  120196. goto L110;
  120197. L104:
  120198. if(ido==1)na=1-na;
  120199. if(na!=0)goto L109;
  120200. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120201. na=1;
  120202. goto L110;
  120203. L109:
  120204. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120205. na=0;
  120206. L110:
  120207. l2=l1;
  120208. }
  120209. if(na==1)return;
  120210. for(i=0;i<n;i++)c[i]=ch[i];
  120211. }
  120212. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120213. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120214. float ti2,tr2;
  120215. t0=l1*ido;
  120216. t1=0;
  120217. t2=0;
  120218. t3=(ido<<1)-1;
  120219. for(k=0;k<l1;k++){
  120220. ch[t1]=cc[t2]+cc[t3+t2];
  120221. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120222. t2=(t1+=ido)<<1;
  120223. }
  120224. if(ido<2)return;
  120225. if(ido==2)goto L105;
  120226. t1=0;
  120227. t2=0;
  120228. for(k=0;k<l1;k++){
  120229. t3=t1;
  120230. t5=(t4=t2)+(ido<<1);
  120231. t6=t0+t1;
  120232. for(i=2;i<ido;i+=2){
  120233. t3+=2;
  120234. t4+=2;
  120235. t5-=2;
  120236. t6+=2;
  120237. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120238. tr2=cc[t4-1]-cc[t5-1];
  120239. ch[t3]=cc[t4]-cc[t5];
  120240. ti2=cc[t4]+cc[t5];
  120241. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120242. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120243. }
  120244. t2=(t1+=ido)<<1;
  120245. }
  120246. if(ido%2==1)return;
  120247. L105:
  120248. t1=ido-1;
  120249. t2=ido-1;
  120250. for(k=0;k<l1;k++){
  120251. ch[t1]=cc[t2]+cc[t2];
  120252. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120253. t1+=ido;
  120254. t2+=ido<<1;
  120255. }
  120256. }
  120257. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120258. float *wa2){
  120259. static float taur = -.5f;
  120260. static float taui = .8660254037844386f;
  120261. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120262. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120263. t0=l1*ido;
  120264. t1=0;
  120265. t2=t0<<1;
  120266. t3=ido<<1;
  120267. t4=ido+(ido<<1);
  120268. t5=0;
  120269. for(k=0;k<l1;k++){
  120270. tr2=cc[t3-1]+cc[t3-1];
  120271. cr2=cc[t5]+(taur*tr2);
  120272. ch[t1]=cc[t5]+tr2;
  120273. ci3=taui*(cc[t3]+cc[t3]);
  120274. ch[t1+t0]=cr2-ci3;
  120275. ch[t1+t2]=cr2+ci3;
  120276. t1+=ido;
  120277. t3+=t4;
  120278. t5+=t4;
  120279. }
  120280. if(ido==1)return;
  120281. t1=0;
  120282. t3=ido<<1;
  120283. for(k=0;k<l1;k++){
  120284. t7=t1+(t1<<1);
  120285. t6=(t5=t7+t3);
  120286. t8=t1;
  120287. t10=(t9=t1+t0)+t0;
  120288. for(i=2;i<ido;i+=2){
  120289. t5+=2;
  120290. t6-=2;
  120291. t7+=2;
  120292. t8+=2;
  120293. t9+=2;
  120294. t10+=2;
  120295. tr2=cc[t5-1]+cc[t6-1];
  120296. cr2=cc[t7-1]+(taur*tr2);
  120297. ch[t8-1]=cc[t7-1]+tr2;
  120298. ti2=cc[t5]-cc[t6];
  120299. ci2=cc[t7]+(taur*ti2);
  120300. ch[t8]=cc[t7]+ti2;
  120301. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120302. ci3=taui*(cc[t5]+cc[t6]);
  120303. dr2=cr2-ci3;
  120304. dr3=cr2+ci3;
  120305. di2=ci2+cr3;
  120306. di3=ci2-cr3;
  120307. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120308. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120309. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120310. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120311. }
  120312. t1+=ido;
  120313. }
  120314. }
  120315. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120316. float *wa2,float *wa3){
  120317. static float sqrt2=1.414213562373095f;
  120318. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120319. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120320. t0=l1*ido;
  120321. t1=0;
  120322. t2=ido<<2;
  120323. t3=0;
  120324. t6=ido<<1;
  120325. for(k=0;k<l1;k++){
  120326. t4=t3+t6;
  120327. t5=t1;
  120328. tr3=cc[t4-1]+cc[t4-1];
  120329. tr4=cc[t4]+cc[t4];
  120330. tr1=cc[t3]-cc[(t4+=t6)-1];
  120331. tr2=cc[t3]+cc[t4-1];
  120332. ch[t5]=tr2+tr3;
  120333. ch[t5+=t0]=tr1-tr4;
  120334. ch[t5+=t0]=tr2-tr3;
  120335. ch[t5+=t0]=tr1+tr4;
  120336. t1+=ido;
  120337. t3+=t2;
  120338. }
  120339. if(ido<2)return;
  120340. if(ido==2)goto L105;
  120341. t1=0;
  120342. for(k=0;k<l1;k++){
  120343. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120344. t7=t1;
  120345. for(i=2;i<ido;i+=2){
  120346. t2+=2;
  120347. t3+=2;
  120348. t4-=2;
  120349. t5-=2;
  120350. t7+=2;
  120351. ti1=cc[t2]+cc[t5];
  120352. ti2=cc[t2]-cc[t5];
  120353. ti3=cc[t3]-cc[t4];
  120354. tr4=cc[t3]+cc[t4];
  120355. tr1=cc[t2-1]-cc[t5-1];
  120356. tr2=cc[t2-1]+cc[t5-1];
  120357. ti4=cc[t3-1]-cc[t4-1];
  120358. tr3=cc[t3-1]+cc[t4-1];
  120359. ch[t7-1]=tr2+tr3;
  120360. cr3=tr2-tr3;
  120361. ch[t7]=ti2+ti3;
  120362. ci3=ti2-ti3;
  120363. cr2=tr1-tr4;
  120364. cr4=tr1+tr4;
  120365. ci2=ti1+ti4;
  120366. ci4=ti1-ti4;
  120367. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120368. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120369. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120370. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120371. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120372. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120373. }
  120374. t1+=ido;
  120375. }
  120376. if(ido%2 == 1)return;
  120377. L105:
  120378. t1=ido;
  120379. t2=ido<<2;
  120380. t3=ido-1;
  120381. t4=ido+(ido<<1);
  120382. for(k=0;k<l1;k++){
  120383. t5=t3;
  120384. ti1=cc[t1]+cc[t4];
  120385. ti2=cc[t4]-cc[t1];
  120386. tr1=cc[t1-1]-cc[t4-1];
  120387. tr2=cc[t1-1]+cc[t4-1];
  120388. ch[t5]=tr2+tr2;
  120389. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120390. ch[t5+=t0]=ti2+ti2;
  120391. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120392. t3+=ido;
  120393. t1+=t2;
  120394. t4+=t2;
  120395. }
  120396. }
  120397. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120398. float *c2,float *ch,float *ch2,float *wa){
  120399. static float tpi=6.283185307179586f;
  120400. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120401. t11,t12;
  120402. float dc2,ai1,ai2,ar1,ar2,ds2;
  120403. int nbd;
  120404. float dcp,arg,dsp,ar1h,ar2h;
  120405. int ipp2;
  120406. t10=ip*ido;
  120407. t0=l1*ido;
  120408. arg=tpi/(float)ip;
  120409. dcp=cos(arg);
  120410. dsp=sin(arg);
  120411. nbd=(ido-1)>>1;
  120412. ipp2=ip;
  120413. ipph=(ip+1)>>1;
  120414. if(ido<l1)goto L103;
  120415. t1=0;
  120416. t2=0;
  120417. for(k=0;k<l1;k++){
  120418. t3=t1;
  120419. t4=t2;
  120420. for(i=0;i<ido;i++){
  120421. ch[t3]=cc[t4];
  120422. t3++;
  120423. t4++;
  120424. }
  120425. t1+=ido;
  120426. t2+=t10;
  120427. }
  120428. goto L106;
  120429. L103:
  120430. t1=0;
  120431. for(i=0;i<ido;i++){
  120432. t2=t1;
  120433. t3=t1;
  120434. for(k=0;k<l1;k++){
  120435. ch[t2]=cc[t3];
  120436. t2+=ido;
  120437. t3+=t10;
  120438. }
  120439. t1++;
  120440. }
  120441. L106:
  120442. t1=0;
  120443. t2=ipp2*t0;
  120444. t7=(t5=ido<<1);
  120445. for(j=1;j<ipph;j++){
  120446. t1+=t0;
  120447. t2-=t0;
  120448. t3=t1;
  120449. t4=t2;
  120450. t6=t5;
  120451. for(k=0;k<l1;k++){
  120452. ch[t3]=cc[t6-1]+cc[t6-1];
  120453. ch[t4]=cc[t6]+cc[t6];
  120454. t3+=ido;
  120455. t4+=ido;
  120456. t6+=t10;
  120457. }
  120458. t5+=t7;
  120459. }
  120460. if (ido == 1)goto L116;
  120461. if(nbd<l1)goto L112;
  120462. t1=0;
  120463. t2=ipp2*t0;
  120464. t7=0;
  120465. for(j=1;j<ipph;j++){
  120466. t1+=t0;
  120467. t2-=t0;
  120468. t3=t1;
  120469. t4=t2;
  120470. t7+=(ido<<1);
  120471. t8=t7;
  120472. for(k=0;k<l1;k++){
  120473. t5=t3;
  120474. t6=t4;
  120475. t9=t8;
  120476. t11=t8;
  120477. for(i=2;i<ido;i+=2){
  120478. t5+=2;
  120479. t6+=2;
  120480. t9+=2;
  120481. t11-=2;
  120482. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120483. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120484. ch[t5]=cc[t9]-cc[t11];
  120485. ch[t6]=cc[t9]+cc[t11];
  120486. }
  120487. t3+=ido;
  120488. t4+=ido;
  120489. t8+=t10;
  120490. }
  120491. }
  120492. goto L116;
  120493. L112:
  120494. t1=0;
  120495. t2=ipp2*t0;
  120496. t7=0;
  120497. for(j=1;j<ipph;j++){
  120498. t1+=t0;
  120499. t2-=t0;
  120500. t3=t1;
  120501. t4=t2;
  120502. t7+=(ido<<1);
  120503. t8=t7;
  120504. t9=t7;
  120505. for(i=2;i<ido;i+=2){
  120506. t3+=2;
  120507. t4+=2;
  120508. t8+=2;
  120509. t9-=2;
  120510. t5=t3;
  120511. t6=t4;
  120512. t11=t8;
  120513. t12=t9;
  120514. for(k=0;k<l1;k++){
  120515. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120516. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120517. ch[t5]=cc[t11]-cc[t12];
  120518. ch[t6]=cc[t11]+cc[t12];
  120519. t5+=ido;
  120520. t6+=ido;
  120521. t11+=t10;
  120522. t12+=t10;
  120523. }
  120524. }
  120525. }
  120526. L116:
  120527. ar1=1.f;
  120528. ai1=0.f;
  120529. t1=0;
  120530. t9=(t2=ipp2*idl1);
  120531. t3=(ip-1)*idl1;
  120532. for(l=1;l<ipph;l++){
  120533. t1+=idl1;
  120534. t2-=idl1;
  120535. ar1h=dcp*ar1-dsp*ai1;
  120536. ai1=dcp*ai1+dsp*ar1;
  120537. ar1=ar1h;
  120538. t4=t1;
  120539. t5=t2;
  120540. t6=0;
  120541. t7=idl1;
  120542. t8=t3;
  120543. for(ik=0;ik<idl1;ik++){
  120544. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120545. c2[t5++]=ai1*ch2[t8++];
  120546. }
  120547. dc2=ar1;
  120548. ds2=ai1;
  120549. ar2=ar1;
  120550. ai2=ai1;
  120551. t6=idl1;
  120552. t7=t9-idl1;
  120553. for(j=2;j<ipph;j++){
  120554. t6+=idl1;
  120555. t7-=idl1;
  120556. ar2h=dc2*ar2-ds2*ai2;
  120557. ai2=dc2*ai2+ds2*ar2;
  120558. ar2=ar2h;
  120559. t4=t1;
  120560. t5=t2;
  120561. t11=t6;
  120562. t12=t7;
  120563. for(ik=0;ik<idl1;ik++){
  120564. c2[t4++]+=ar2*ch2[t11++];
  120565. c2[t5++]+=ai2*ch2[t12++];
  120566. }
  120567. }
  120568. }
  120569. t1=0;
  120570. for(j=1;j<ipph;j++){
  120571. t1+=idl1;
  120572. t2=t1;
  120573. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120574. }
  120575. t1=0;
  120576. t2=ipp2*t0;
  120577. for(j=1;j<ipph;j++){
  120578. t1+=t0;
  120579. t2-=t0;
  120580. t3=t1;
  120581. t4=t2;
  120582. for(k=0;k<l1;k++){
  120583. ch[t3]=c1[t3]-c1[t4];
  120584. ch[t4]=c1[t3]+c1[t4];
  120585. t3+=ido;
  120586. t4+=ido;
  120587. }
  120588. }
  120589. if(ido==1)goto L132;
  120590. if(nbd<l1)goto L128;
  120591. t1=0;
  120592. t2=ipp2*t0;
  120593. for(j=1;j<ipph;j++){
  120594. t1+=t0;
  120595. t2-=t0;
  120596. t3=t1;
  120597. t4=t2;
  120598. for(k=0;k<l1;k++){
  120599. t5=t3;
  120600. t6=t4;
  120601. for(i=2;i<ido;i+=2){
  120602. t5+=2;
  120603. t6+=2;
  120604. ch[t5-1]=c1[t5-1]-c1[t6];
  120605. ch[t6-1]=c1[t5-1]+c1[t6];
  120606. ch[t5]=c1[t5]+c1[t6-1];
  120607. ch[t6]=c1[t5]-c1[t6-1];
  120608. }
  120609. t3+=ido;
  120610. t4+=ido;
  120611. }
  120612. }
  120613. goto L132;
  120614. L128:
  120615. t1=0;
  120616. t2=ipp2*t0;
  120617. for(j=1;j<ipph;j++){
  120618. t1+=t0;
  120619. t2-=t0;
  120620. t3=t1;
  120621. t4=t2;
  120622. for(i=2;i<ido;i+=2){
  120623. t3+=2;
  120624. t4+=2;
  120625. t5=t3;
  120626. t6=t4;
  120627. for(k=0;k<l1;k++){
  120628. ch[t5-1]=c1[t5-1]-c1[t6];
  120629. ch[t6-1]=c1[t5-1]+c1[t6];
  120630. ch[t5]=c1[t5]+c1[t6-1];
  120631. ch[t6]=c1[t5]-c1[t6-1];
  120632. t5+=ido;
  120633. t6+=ido;
  120634. }
  120635. }
  120636. }
  120637. L132:
  120638. if(ido==1)return;
  120639. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120640. t1=0;
  120641. for(j=1;j<ip;j++){
  120642. t2=(t1+=t0);
  120643. for(k=0;k<l1;k++){
  120644. c1[t2]=ch[t2];
  120645. t2+=ido;
  120646. }
  120647. }
  120648. if(nbd>l1)goto L139;
  120649. is= -ido-1;
  120650. t1=0;
  120651. for(j=1;j<ip;j++){
  120652. is+=ido;
  120653. t1+=t0;
  120654. idij=is;
  120655. t2=t1;
  120656. for(i=2;i<ido;i+=2){
  120657. t2+=2;
  120658. idij+=2;
  120659. t3=t2;
  120660. for(k=0;k<l1;k++){
  120661. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120662. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120663. t3+=ido;
  120664. }
  120665. }
  120666. }
  120667. return;
  120668. L139:
  120669. is= -ido-1;
  120670. t1=0;
  120671. for(j=1;j<ip;j++){
  120672. is+=ido;
  120673. t1+=t0;
  120674. t2=t1;
  120675. for(k=0;k<l1;k++){
  120676. idij=is;
  120677. t3=t2;
  120678. for(i=2;i<ido;i+=2){
  120679. idij+=2;
  120680. t3+=2;
  120681. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120682. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120683. }
  120684. t2+=ido;
  120685. }
  120686. }
  120687. }
  120688. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120689. int i,k1,l1,l2;
  120690. int na;
  120691. int nf,ip,iw,ix2,ix3,ido,idl1;
  120692. nf=ifac[1];
  120693. na=0;
  120694. l1=1;
  120695. iw=1;
  120696. for(k1=0;k1<nf;k1++){
  120697. ip=ifac[k1 + 2];
  120698. l2=ip*l1;
  120699. ido=n/l2;
  120700. idl1=ido*l1;
  120701. if(ip!=4)goto L103;
  120702. ix2=iw+ido;
  120703. ix3=ix2+ido;
  120704. if(na!=0)
  120705. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120706. else
  120707. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120708. na=1-na;
  120709. goto L115;
  120710. L103:
  120711. if(ip!=2)goto L106;
  120712. if(na!=0)
  120713. dradb2(ido,l1,ch,c,wa+iw-1);
  120714. else
  120715. dradb2(ido,l1,c,ch,wa+iw-1);
  120716. na=1-na;
  120717. goto L115;
  120718. L106:
  120719. if(ip!=3)goto L109;
  120720. ix2=iw+ido;
  120721. if(na!=0)
  120722. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120723. else
  120724. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120725. na=1-na;
  120726. goto L115;
  120727. L109:
  120728. /* The radix five case can be translated later..... */
  120729. /* if(ip!=5)goto L112;
  120730. ix2=iw+ido;
  120731. ix3=ix2+ido;
  120732. ix4=ix3+ido;
  120733. if(na!=0)
  120734. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120735. else
  120736. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120737. na=1-na;
  120738. goto L115;
  120739. L112:*/
  120740. if(na!=0)
  120741. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120742. else
  120743. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120744. if(ido==1)na=1-na;
  120745. L115:
  120746. l1=l2;
  120747. iw+=(ip-1)*ido;
  120748. }
  120749. if(na==0)return;
  120750. for(i=0;i<n;i++)c[i]=ch[i];
  120751. }
  120752. void drft_forward(drft_lookup *l,float *data){
  120753. if(l->n==1)return;
  120754. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120755. }
  120756. void drft_backward(drft_lookup *l,float *data){
  120757. if (l->n==1)return;
  120758. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120759. }
  120760. void drft_init(drft_lookup *l,int n){
  120761. l->n=n;
  120762. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120763. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120764. fdrffti(n, l->trigcache, l->splitcache);
  120765. }
  120766. void drft_clear(drft_lookup *l){
  120767. if(l){
  120768. if(l->trigcache)_ogg_free(l->trigcache);
  120769. if(l->splitcache)_ogg_free(l->splitcache);
  120770. memset(l,0,sizeof(*l));
  120771. }
  120772. }
  120773. #endif
  120774. /*** End of inlined file: smallft.c ***/
  120775. /*** Start of inlined file: synthesis.c ***/
  120776. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120777. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120778. // tasks..
  120779. #if JUCE_MSVC
  120780. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120781. #endif
  120782. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120783. #if JUCE_USE_OGGVORBIS
  120784. #include <stdio.h>
  120785. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  120786. vorbis_dsp_state *vd=vb->vd;
  120787. private_state *b=(private_state*)vd->backend_state;
  120788. vorbis_info *vi=vd->vi;
  120789. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  120790. oggpack_buffer *opb=&vb->opb;
  120791. int type,mode,i;
  120792. /* first things first. Make sure decode is ready */
  120793. _vorbis_block_ripcord(vb);
  120794. oggpack_readinit(opb,op->packet,op->bytes);
  120795. /* Check the packet type */
  120796. if(oggpack_read(opb,1)!=0){
  120797. /* Oops. This is not an audio data packet */
  120798. return(OV_ENOTAUDIO);
  120799. }
  120800. /* read our mode and pre/post windowsize */
  120801. mode=oggpack_read(opb,b->modebits);
  120802. if(mode==-1)return(OV_EBADPACKET);
  120803. vb->mode=mode;
  120804. vb->W=ci->mode_param[mode]->blockflag;
  120805. if(vb->W){
  120806. /* this doesn;t get mapped through mode selection as it's used
  120807. only for window selection */
  120808. vb->lW=oggpack_read(opb,1);
  120809. vb->nW=oggpack_read(opb,1);
  120810. if(vb->nW==-1) return(OV_EBADPACKET);
  120811. }else{
  120812. vb->lW=0;
  120813. vb->nW=0;
  120814. }
  120815. /* more setup */
  120816. vb->granulepos=op->granulepos;
  120817. vb->sequence=op->packetno;
  120818. vb->eofflag=op->e_o_s;
  120819. /* alloc pcm passback storage */
  120820. vb->pcmend=ci->blocksizes[vb->W];
  120821. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  120822. for(i=0;i<vi->channels;i++)
  120823. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  120824. /* unpack_header enforces range checking */
  120825. type=ci->map_type[ci->mode_param[mode]->mapping];
  120826. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  120827. mapping]));
  120828. }
  120829. /* used to track pcm position without actually performing decode.
  120830. Useful for sequential 'fast forward' */
  120831. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  120832. vorbis_dsp_state *vd=vb->vd;
  120833. private_state *b=(private_state*)vd->backend_state;
  120834. vorbis_info *vi=vd->vi;
  120835. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120836. oggpack_buffer *opb=&vb->opb;
  120837. int mode;
  120838. /* first things first. Make sure decode is ready */
  120839. _vorbis_block_ripcord(vb);
  120840. oggpack_readinit(opb,op->packet,op->bytes);
  120841. /* Check the packet type */
  120842. if(oggpack_read(opb,1)!=0){
  120843. /* Oops. This is not an audio data packet */
  120844. return(OV_ENOTAUDIO);
  120845. }
  120846. /* read our mode and pre/post windowsize */
  120847. mode=oggpack_read(opb,b->modebits);
  120848. if(mode==-1)return(OV_EBADPACKET);
  120849. vb->mode=mode;
  120850. vb->W=ci->mode_param[mode]->blockflag;
  120851. if(vb->W){
  120852. vb->lW=oggpack_read(opb,1);
  120853. vb->nW=oggpack_read(opb,1);
  120854. if(vb->nW==-1) return(OV_EBADPACKET);
  120855. }else{
  120856. vb->lW=0;
  120857. vb->nW=0;
  120858. }
  120859. /* more setup */
  120860. vb->granulepos=op->granulepos;
  120861. vb->sequence=op->packetno;
  120862. vb->eofflag=op->e_o_s;
  120863. /* no pcm */
  120864. vb->pcmend=0;
  120865. vb->pcm=NULL;
  120866. return(0);
  120867. }
  120868. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  120869. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120870. oggpack_buffer opb;
  120871. int mode;
  120872. oggpack_readinit(&opb,op->packet,op->bytes);
  120873. /* Check the packet type */
  120874. if(oggpack_read(&opb,1)!=0){
  120875. /* Oops. This is not an audio data packet */
  120876. return(OV_ENOTAUDIO);
  120877. }
  120878. {
  120879. int modebits=0;
  120880. int v=ci->modes;
  120881. while(v>1){
  120882. modebits++;
  120883. v>>=1;
  120884. }
  120885. /* read our mode and pre/post windowsize */
  120886. mode=oggpack_read(&opb,modebits);
  120887. }
  120888. if(mode==-1)return(OV_EBADPACKET);
  120889. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  120890. }
  120891. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  120892. /* set / clear half-sample-rate mode */
  120893. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120894. /* right now, our MDCT can't handle < 64 sample windows. */
  120895. if(ci->blocksizes[0]<=64 && flag)return -1;
  120896. ci->halfrate_flag=(flag?1:0);
  120897. return 0;
  120898. }
  120899. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  120900. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  120901. return ci->halfrate_flag;
  120902. }
  120903. #endif
  120904. /*** End of inlined file: synthesis.c ***/
  120905. /*** Start of inlined file: vorbisenc.c ***/
  120906. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  120907. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120908. // tasks..
  120909. #if JUCE_MSVC
  120910. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  120911. #endif
  120912. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  120913. #if JUCE_USE_OGGVORBIS
  120914. #include <stdlib.h>
  120915. #include <string.h>
  120916. #include <math.h>
  120917. /* careful with this; it's using static array sizing to make managing
  120918. all the modes a little less annoying. If we use a residue backend
  120919. with > 12 partition types, or a different division of iteration,
  120920. this needs to be updated. */
  120921. typedef struct {
  120922. static_codebook *books[12][3];
  120923. } static_bookblock;
  120924. typedef struct {
  120925. int res_type;
  120926. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  120927. vorbis_info_residue0 *res;
  120928. static_codebook *book_aux;
  120929. static_codebook *book_aux_managed;
  120930. static_bookblock *books_base;
  120931. static_bookblock *books_base_managed;
  120932. } vorbis_residue_template;
  120933. typedef struct {
  120934. vorbis_info_mapping0 *map;
  120935. vorbis_residue_template *res;
  120936. } vorbis_mapping_template;
  120937. typedef struct vp_adjblock{
  120938. int block[P_BANDS];
  120939. } vp_adjblock;
  120940. typedef struct {
  120941. int data[NOISE_COMPAND_LEVELS];
  120942. } compandblock;
  120943. /* high level configuration information for setting things up
  120944. step-by-step with the detailed vorbis_encode_ctl interface.
  120945. There's a fair amount of redundancy such that interactive setup
  120946. does not directly deal with any vorbis_info or codec_setup_info
  120947. initialization; it's all stored (until full init) in this highlevel
  120948. setup, then flushed out to the real codec setup structs later. */
  120949. typedef struct {
  120950. int att[P_NOISECURVES];
  120951. float boost;
  120952. float decay;
  120953. } att3;
  120954. typedef struct { int data[P_NOISECURVES]; } adj3;
  120955. typedef struct {
  120956. int pre[PACKETBLOBS];
  120957. int post[PACKETBLOBS];
  120958. float kHz[PACKETBLOBS];
  120959. float lowpasskHz[PACKETBLOBS];
  120960. } adj_stereo;
  120961. typedef struct {
  120962. int lo;
  120963. int hi;
  120964. int fixed;
  120965. } noiseguard;
  120966. typedef struct {
  120967. int data[P_NOISECURVES][17];
  120968. } noise3;
  120969. typedef struct {
  120970. int mappings;
  120971. double *rate_mapping;
  120972. double *quality_mapping;
  120973. int coupling_restriction;
  120974. long samplerate_min_restriction;
  120975. long samplerate_max_restriction;
  120976. int *blocksize_short;
  120977. int *blocksize_long;
  120978. att3 *psy_tone_masteratt;
  120979. int *psy_tone_0dB;
  120980. int *psy_tone_dBsuppress;
  120981. vp_adjblock *psy_tone_adj_impulse;
  120982. vp_adjblock *psy_tone_adj_long;
  120983. vp_adjblock *psy_tone_adj_other;
  120984. noiseguard *psy_noiseguards;
  120985. noise3 *psy_noise_bias_impulse;
  120986. noise3 *psy_noise_bias_padding;
  120987. noise3 *psy_noise_bias_trans;
  120988. noise3 *psy_noise_bias_long;
  120989. int *psy_noise_dBsuppress;
  120990. compandblock *psy_noise_compand;
  120991. double *psy_noise_compand_short_mapping;
  120992. double *psy_noise_compand_long_mapping;
  120993. int *psy_noise_normal_start[2];
  120994. int *psy_noise_normal_partition[2];
  120995. double *psy_noise_normal_thresh;
  120996. int *psy_ath_float;
  120997. int *psy_ath_abs;
  120998. double *psy_lowpass;
  120999. vorbis_info_psy_global *global_params;
  121000. double *global_mapping;
  121001. adj_stereo *stereo_modes;
  121002. static_codebook ***floor_books;
  121003. vorbis_info_floor1 *floor_params;
  121004. int *floor_short_mapping;
  121005. int *floor_long_mapping;
  121006. vorbis_mapping_template *maps;
  121007. } ve_setup_data_template;
  121008. /* a few static coder conventions */
  121009. static vorbis_info_mode _mode_template[2]={
  121010. {0,0,0,0},
  121011. {1,0,0,1}
  121012. };
  121013. static vorbis_info_mapping0 _map_nominal[2]={
  121014. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  121015. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  121016. };
  121017. /*** Start of inlined file: setup_44.h ***/
  121018. /*** Start of inlined file: floor_all.h ***/
  121019. /*** Start of inlined file: floor_books.h ***/
  121020. static long _huff_lengthlist_line_256x7_0sub1[] = {
  121021. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  121022. };
  121023. static static_codebook _huff_book_line_256x7_0sub1 = {
  121024. 1, 9,
  121025. _huff_lengthlist_line_256x7_0sub1,
  121026. 0, 0, 0, 0, 0,
  121027. NULL,
  121028. NULL,
  121029. NULL,
  121030. NULL,
  121031. 0
  121032. };
  121033. static long _huff_lengthlist_line_256x7_0sub2[] = {
  121034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  121035. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  121036. };
  121037. static static_codebook _huff_book_line_256x7_0sub2 = {
  121038. 1, 25,
  121039. _huff_lengthlist_line_256x7_0sub2,
  121040. 0, 0, 0, 0, 0,
  121041. NULL,
  121042. NULL,
  121043. NULL,
  121044. NULL,
  121045. 0
  121046. };
  121047. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121050. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121051. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121052. };
  121053. static static_codebook _huff_book_line_256x7_0sub3 = {
  121054. 1, 64,
  121055. _huff_lengthlist_line_256x7_0sub3,
  121056. 0, 0, 0, 0, 0,
  121057. NULL,
  121058. NULL,
  121059. NULL,
  121060. NULL,
  121061. 0
  121062. };
  121063. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121064. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121065. };
  121066. static static_codebook _huff_book_line_256x7_1sub1 = {
  121067. 1, 9,
  121068. _huff_lengthlist_line_256x7_1sub1,
  121069. 0, 0, 0, 0, 0,
  121070. NULL,
  121071. NULL,
  121072. NULL,
  121073. NULL,
  121074. 0
  121075. };
  121076. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121078. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121079. };
  121080. static static_codebook _huff_book_line_256x7_1sub2 = {
  121081. 1, 25,
  121082. _huff_lengthlist_line_256x7_1sub2,
  121083. 0, 0, 0, 0, 0,
  121084. NULL,
  121085. NULL,
  121086. NULL,
  121087. NULL,
  121088. 0
  121089. };
  121090. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121093. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121094. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121095. };
  121096. static static_codebook _huff_book_line_256x7_1sub3 = {
  121097. 1, 64,
  121098. _huff_lengthlist_line_256x7_1sub3,
  121099. 0, 0, 0, 0, 0,
  121100. NULL,
  121101. NULL,
  121102. NULL,
  121103. NULL,
  121104. 0
  121105. };
  121106. static long _huff_lengthlist_line_256x7_class0[] = {
  121107. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121108. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121109. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121110. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121111. };
  121112. static static_codebook _huff_book_line_256x7_class0 = {
  121113. 1, 64,
  121114. _huff_lengthlist_line_256x7_class0,
  121115. 0, 0, 0, 0, 0,
  121116. NULL,
  121117. NULL,
  121118. NULL,
  121119. NULL,
  121120. 0
  121121. };
  121122. static long _huff_lengthlist_line_256x7_class1[] = {
  121123. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121124. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121125. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121126. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121127. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121128. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121129. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121130. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121131. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121132. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121133. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121134. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121135. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121136. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121137. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121138. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121139. };
  121140. static static_codebook _huff_book_line_256x7_class1 = {
  121141. 1, 256,
  121142. _huff_lengthlist_line_256x7_class1,
  121143. 0, 0, 0, 0, 0,
  121144. NULL,
  121145. NULL,
  121146. NULL,
  121147. NULL,
  121148. 0
  121149. };
  121150. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121151. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121152. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121153. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121154. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121155. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121156. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121157. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121158. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121159. };
  121160. static static_codebook _huff_book_line_512x17_0sub0 = {
  121161. 1, 128,
  121162. _huff_lengthlist_line_512x17_0sub0,
  121163. 0, 0, 0, 0, 0,
  121164. NULL,
  121165. NULL,
  121166. NULL,
  121167. NULL,
  121168. 0
  121169. };
  121170. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121171. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121172. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121173. };
  121174. static static_codebook _huff_book_line_512x17_1sub0 = {
  121175. 1, 32,
  121176. _huff_lengthlist_line_512x17_1sub0,
  121177. 0, 0, 0, 0, 0,
  121178. NULL,
  121179. NULL,
  121180. NULL,
  121181. NULL,
  121182. 0
  121183. };
  121184. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121187. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121188. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121189. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121190. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121191. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121192. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121193. };
  121194. static static_codebook _huff_book_line_512x17_1sub1 = {
  121195. 1, 128,
  121196. _huff_lengthlist_line_512x17_1sub1,
  121197. 0, 0, 0, 0, 0,
  121198. NULL,
  121199. NULL,
  121200. NULL,
  121201. NULL,
  121202. 0
  121203. };
  121204. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121205. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121206. 5, 3,
  121207. };
  121208. static static_codebook _huff_book_line_512x17_2sub1 = {
  121209. 1, 18,
  121210. _huff_lengthlist_line_512x17_2sub1,
  121211. 0, 0, 0, 0, 0,
  121212. NULL,
  121213. NULL,
  121214. NULL,
  121215. NULL,
  121216. 0
  121217. };
  121218. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121220. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121221. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121222. 9, 8,
  121223. };
  121224. static static_codebook _huff_book_line_512x17_2sub2 = {
  121225. 1, 50,
  121226. _huff_lengthlist_line_512x17_2sub2,
  121227. 0, 0, 0, 0, 0,
  121228. NULL,
  121229. NULL,
  121230. NULL,
  121231. NULL,
  121232. 0
  121233. };
  121234. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121238. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121239. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121240. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121241. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121242. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121243. };
  121244. static static_codebook _huff_book_line_512x17_2sub3 = {
  121245. 1, 128,
  121246. _huff_lengthlist_line_512x17_2sub3,
  121247. 0, 0, 0, 0, 0,
  121248. NULL,
  121249. NULL,
  121250. NULL,
  121251. NULL,
  121252. 0
  121253. };
  121254. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121255. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121256. 5, 5,
  121257. };
  121258. static static_codebook _huff_book_line_512x17_3sub1 = {
  121259. 1, 18,
  121260. _huff_lengthlist_line_512x17_3sub1,
  121261. 0, 0, 0, 0, 0,
  121262. NULL,
  121263. NULL,
  121264. NULL,
  121265. NULL,
  121266. 0
  121267. };
  121268. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121270. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121271. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121272. 11,14,
  121273. };
  121274. static static_codebook _huff_book_line_512x17_3sub2 = {
  121275. 1, 50,
  121276. _huff_lengthlist_line_512x17_3sub2,
  121277. 0, 0, 0, 0, 0,
  121278. NULL,
  121279. NULL,
  121280. NULL,
  121281. NULL,
  121282. 0
  121283. };
  121284. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121288. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121289. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121290. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121291. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121292. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121293. };
  121294. static static_codebook _huff_book_line_512x17_3sub3 = {
  121295. 1, 128,
  121296. _huff_lengthlist_line_512x17_3sub3,
  121297. 0, 0, 0, 0, 0,
  121298. NULL,
  121299. NULL,
  121300. NULL,
  121301. NULL,
  121302. 0
  121303. };
  121304. static long _huff_lengthlist_line_512x17_class1[] = {
  121305. 1, 2, 3, 6, 5, 4, 7, 7,
  121306. };
  121307. static static_codebook _huff_book_line_512x17_class1 = {
  121308. 1, 8,
  121309. _huff_lengthlist_line_512x17_class1,
  121310. 0, 0, 0, 0, 0,
  121311. NULL,
  121312. NULL,
  121313. NULL,
  121314. NULL,
  121315. 0
  121316. };
  121317. static long _huff_lengthlist_line_512x17_class2[] = {
  121318. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121319. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121320. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121321. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121322. };
  121323. static static_codebook _huff_book_line_512x17_class2 = {
  121324. 1, 64,
  121325. _huff_lengthlist_line_512x17_class2,
  121326. 0, 0, 0, 0, 0,
  121327. NULL,
  121328. NULL,
  121329. NULL,
  121330. NULL,
  121331. 0
  121332. };
  121333. static long _huff_lengthlist_line_512x17_class3[] = {
  121334. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121335. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121336. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121337. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121338. };
  121339. static static_codebook _huff_book_line_512x17_class3 = {
  121340. 1, 64,
  121341. _huff_lengthlist_line_512x17_class3,
  121342. 0, 0, 0, 0, 0,
  121343. NULL,
  121344. NULL,
  121345. NULL,
  121346. NULL,
  121347. 0
  121348. };
  121349. static long _huff_lengthlist_line_128x4_class0[] = {
  121350. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121351. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121352. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121353. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121354. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121355. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121356. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121357. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121358. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121359. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121360. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121361. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121362. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121363. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121364. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121365. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121366. };
  121367. static static_codebook _huff_book_line_128x4_class0 = {
  121368. 1, 256,
  121369. _huff_lengthlist_line_128x4_class0,
  121370. 0, 0, 0, 0, 0,
  121371. NULL,
  121372. NULL,
  121373. NULL,
  121374. NULL,
  121375. 0
  121376. };
  121377. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121378. 2, 2, 2, 2,
  121379. };
  121380. static static_codebook _huff_book_line_128x4_0sub0 = {
  121381. 1, 4,
  121382. _huff_lengthlist_line_128x4_0sub0,
  121383. 0, 0, 0, 0, 0,
  121384. NULL,
  121385. NULL,
  121386. NULL,
  121387. NULL,
  121388. 0
  121389. };
  121390. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121391. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121392. };
  121393. static static_codebook _huff_book_line_128x4_0sub1 = {
  121394. 1, 10,
  121395. _huff_lengthlist_line_128x4_0sub1,
  121396. 0, 0, 0, 0, 0,
  121397. NULL,
  121398. NULL,
  121399. NULL,
  121400. NULL,
  121401. 0
  121402. };
  121403. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121405. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121406. };
  121407. static static_codebook _huff_book_line_128x4_0sub2 = {
  121408. 1, 25,
  121409. _huff_lengthlist_line_128x4_0sub2,
  121410. 0, 0, 0, 0, 0,
  121411. NULL,
  121412. NULL,
  121413. NULL,
  121414. NULL,
  121415. 0
  121416. };
  121417. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121420. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121421. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121422. };
  121423. static static_codebook _huff_book_line_128x4_0sub3 = {
  121424. 1, 64,
  121425. _huff_lengthlist_line_128x4_0sub3,
  121426. 0, 0, 0, 0, 0,
  121427. NULL,
  121428. NULL,
  121429. NULL,
  121430. NULL,
  121431. 0
  121432. };
  121433. static long _huff_lengthlist_line_256x4_class0[] = {
  121434. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121435. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121436. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121437. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121438. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121439. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121440. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121441. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121442. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121443. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121444. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121445. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121446. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121447. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121448. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121449. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121450. };
  121451. static static_codebook _huff_book_line_256x4_class0 = {
  121452. 1, 256,
  121453. _huff_lengthlist_line_256x4_class0,
  121454. 0, 0, 0, 0, 0,
  121455. NULL,
  121456. NULL,
  121457. NULL,
  121458. NULL,
  121459. 0
  121460. };
  121461. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121462. 2, 2, 2, 2,
  121463. };
  121464. static static_codebook _huff_book_line_256x4_0sub0 = {
  121465. 1, 4,
  121466. _huff_lengthlist_line_256x4_0sub0,
  121467. 0, 0, 0, 0, 0,
  121468. NULL,
  121469. NULL,
  121470. NULL,
  121471. NULL,
  121472. 0
  121473. };
  121474. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121475. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121476. };
  121477. static static_codebook _huff_book_line_256x4_0sub1 = {
  121478. 1, 10,
  121479. _huff_lengthlist_line_256x4_0sub1,
  121480. 0, 0, 0, 0, 0,
  121481. NULL,
  121482. NULL,
  121483. NULL,
  121484. NULL,
  121485. 0
  121486. };
  121487. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121489. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121490. };
  121491. static static_codebook _huff_book_line_256x4_0sub2 = {
  121492. 1, 25,
  121493. _huff_lengthlist_line_256x4_0sub2,
  121494. 0, 0, 0, 0, 0,
  121495. NULL,
  121496. NULL,
  121497. NULL,
  121498. NULL,
  121499. 0
  121500. };
  121501. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121504. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121505. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121506. };
  121507. static static_codebook _huff_book_line_256x4_0sub3 = {
  121508. 1, 64,
  121509. _huff_lengthlist_line_256x4_0sub3,
  121510. 0, 0, 0, 0, 0,
  121511. NULL,
  121512. NULL,
  121513. NULL,
  121514. NULL,
  121515. 0
  121516. };
  121517. static long _huff_lengthlist_line_128x7_class0[] = {
  121518. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121519. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121520. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121521. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121522. };
  121523. static static_codebook _huff_book_line_128x7_class0 = {
  121524. 1, 64,
  121525. _huff_lengthlist_line_128x7_class0,
  121526. 0, 0, 0, 0, 0,
  121527. NULL,
  121528. NULL,
  121529. NULL,
  121530. NULL,
  121531. 0
  121532. };
  121533. static long _huff_lengthlist_line_128x7_class1[] = {
  121534. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121535. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121536. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121537. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121538. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121539. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121540. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121541. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121542. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121543. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121544. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121545. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121546. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121547. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121548. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121549. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121550. };
  121551. static static_codebook _huff_book_line_128x7_class1 = {
  121552. 1, 256,
  121553. _huff_lengthlist_line_128x7_class1,
  121554. 0, 0, 0, 0, 0,
  121555. NULL,
  121556. NULL,
  121557. NULL,
  121558. NULL,
  121559. 0
  121560. };
  121561. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121562. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  121563. };
  121564. static static_codebook _huff_book_line_128x7_0sub1 = {
  121565. 1, 9,
  121566. _huff_lengthlist_line_128x7_0sub1,
  121567. 0, 0, 0, 0, 0,
  121568. NULL,
  121569. NULL,
  121570. NULL,
  121571. NULL,
  121572. 0
  121573. };
  121574. static long _huff_lengthlist_line_128x7_0sub2[] = {
  121575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  121576. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  121577. };
  121578. static static_codebook _huff_book_line_128x7_0sub2 = {
  121579. 1, 25,
  121580. _huff_lengthlist_line_128x7_0sub2,
  121581. 0, 0, 0, 0, 0,
  121582. NULL,
  121583. NULL,
  121584. NULL,
  121585. NULL,
  121586. 0
  121587. };
  121588. static long _huff_lengthlist_line_128x7_0sub3[] = {
  121589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 3, 5, 3, 5, 4,
  121591. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121592. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  121593. };
  121594. static static_codebook _huff_book_line_128x7_0sub3 = {
  121595. 1, 64,
  121596. _huff_lengthlist_line_128x7_0sub3,
  121597. 0, 0, 0, 0, 0,
  121598. NULL,
  121599. NULL,
  121600. NULL,
  121601. NULL,
  121602. 0
  121603. };
  121604. static long _huff_lengthlist_line_128x7_1sub1[] = {
  121605. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  121606. };
  121607. static static_codebook _huff_book_line_128x7_1sub1 = {
  121608. 1, 9,
  121609. _huff_lengthlist_line_128x7_1sub1,
  121610. 0, 0, 0, 0, 0,
  121611. NULL,
  121612. NULL,
  121613. NULL,
  121614. NULL,
  121615. 0
  121616. };
  121617. static long _huff_lengthlist_line_128x7_1sub2[] = {
  121618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  121619. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  121620. };
  121621. static static_codebook _huff_book_line_128x7_1sub2 = {
  121622. 1, 25,
  121623. _huff_lengthlist_line_128x7_1sub2,
  121624. 0, 0, 0, 0, 0,
  121625. NULL,
  121626. NULL,
  121627. NULL,
  121628. NULL,
  121629. 0
  121630. };
  121631. static long _huff_lengthlist_line_128x7_1sub3[] = {
  121632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 7, 2, 7, 3, 8, 4,
  121634. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  121635. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  121636. };
  121637. static static_codebook _huff_book_line_128x7_1sub3 = {
  121638. 1, 64,
  121639. _huff_lengthlist_line_128x7_1sub3,
  121640. 0, 0, 0, 0, 0,
  121641. NULL,
  121642. NULL,
  121643. NULL,
  121644. NULL,
  121645. 0
  121646. };
  121647. static long _huff_lengthlist_line_128x11_class1[] = {
  121648. 1, 6, 3, 7, 2, 4, 5, 7,
  121649. };
  121650. static static_codebook _huff_book_line_128x11_class1 = {
  121651. 1, 8,
  121652. _huff_lengthlist_line_128x11_class1,
  121653. 0, 0, 0, 0, 0,
  121654. NULL,
  121655. NULL,
  121656. NULL,
  121657. NULL,
  121658. 0
  121659. };
  121660. static long _huff_lengthlist_line_128x11_class2[] = {
  121661. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  121662. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  121663. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  121664. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  121665. };
  121666. static static_codebook _huff_book_line_128x11_class2 = {
  121667. 1, 64,
  121668. _huff_lengthlist_line_128x11_class2,
  121669. 0, 0, 0, 0, 0,
  121670. NULL,
  121671. NULL,
  121672. NULL,
  121673. NULL,
  121674. 0
  121675. };
  121676. static long _huff_lengthlist_line_128x11_class3[] = {
  121677. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  121678. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  121679. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  121680. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  121681. };
  121682. static static_codebook _huff_book_line_128x11_class3 = {
  121683. 1, 64,
  121684. _huff_lengthlist_line_128x11_class3,
  121685. 0, 0, 0, 0, 0,
  121686. NULL,
  121687. NULL,
  121688. NULL,
  121689. NULL,
  121690. 0
  121691. };
  121692. static long _huff_lengthlist_line_128x11_0sub0[] = {
  121693. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121694. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  121695. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  121696. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  121697. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  121698. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  121699. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  121700. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121701. };
  121702. static static_codebook _huff_book_line_128x11_0sub0 = {
  121703. 1, 128,
  121704. _huff_lengthlist_line_128x11_0sub0,
  121705. 0, 0, 0, 0, 0,
  121706. NULL,
  121707. NULL,
  121708. NULL,
  121709. NULL,
  121710. 0
  121711. };
  121712. static long _huff_lengthlist_line_128x11_1sub0[] = {
  121713. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  121714. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  121715. };
  121716. static static_codebook _huff_book_line_128x11_1sub0 = {
  121717. 1, 32,
  121718. _huff_lengthlist_line_128x11_1sub0,
  121719. 0, 0, 0, 0, 0,
  121720. NULL,
  121721. NULL,
  121722. NULL,
  121723. NULL,
  121724. 0
  121725. };
  121726. static long _huff_lengthlist_line_128x11_1sub1[] = {
  121727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121729. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  121730. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  121731. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  121732. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  121733. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  121734. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  121735. };
  121736. static static_codebook _huff_book_line_128x11_1sub1 = {
  121737. 1, 128,
  121738. _huff_lengthlist_line_128x11_1sub1,
  121739. 0, 0, 0, 0, 0,
  121740. NULL,
  121741. NULL,
  121742. NULL,
  121743. NULL,
  121744. 0
  121745. };
  121746. static long _huff_lengthlist_line_128x11_2sub1[] = {
  121747. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  121748. 5, 5,
  121749. };
  121750. static static_codebook _huff_book_line_128x11_2sub1 = {
  121751. 1, 18,
  121752. _huff_lengthlist_line_128x11_2sub1,
  121753. 0, 0, 0, 0, 0,
  121754. NULL,
  121755. NULL,
  121756. NULL,
  121757. NULL,
  121758. 0
  121759. };
  121760. static long _huff_lengthlist_line_128x11_2sub2[] = {
  121761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121762. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  121763. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  121764. 8,11,
  121765. };
  121766. static static_codebook _huff_book_line_128x11_2sub2 = {
  121767. 1, 50,
  121768. _huff_lengthlist_line_128x11_2sub2,
  121769. 0, 0, 0, 0, 0,
  121770. NULL,
  121771. NULL,
  121772. NULL,
  121773. NULL,
  121774. 0
  121775. };
  121776. static long _huff_lengthlist_line_128x11_2sub3[] = {
  121777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121780. 0, 0, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  121781. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121782. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121783. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121784. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121785. };
  121786. static static_codebook _huff_book_line_128x11_2sub3 = {
  121787. 1, 128,
  121788. _huff_lengthlist_line_128x11_2sub3,
  121789. 0, 0, 0, 0, 0,
  121790. NULL,
  121791. NULL,
  121792. NULL,
  121793. NULL,
  121794. 0
  121795. };
  121796. static long _huff_lengthlist_line_128x11_3sub1[] = {
  121797. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  121798. 5, 4,
  121799. };
  121800. static static_codebook _huff_book_line_128x11_3sub1 = {
  121801. 1, 18,
  121802. _huff_lengthlist_line_128x11_3sub1,
  121803. 0, 0, 0, 0, 0,
  121804. NULL,
  121805. NULL,
  121806. NULL,
  121807. NULL,
  121808. 0
  121809. };
  121810. static long _huff_lengthlist_line_128x11_3sub2[] = {
  121811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121812. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  121813. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  121814. 12, 6,
  121815. };
  121816. static static_codebook _huff_book_line_128x11_3sub2 = {
  121817. 1, 50,
  121818. _huff_lengthlist_line_128x11_3sub2,
  121819. 0, 0, 0, 0, 0,
  121820. NULL,
  121821. NULL,
  121822. NULL,
  121823. NULL,
  121824. 0
  121825. };
  121826. static long _huff_lengthlist_line_128x11_3sub3[] = {
  121827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121830. 0, 0, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  121831. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  121832. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121833. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121834. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  121835. };
  121836. static static_codebook _huff_book_line_128x11_3sub3 = {
  121837. 1, 128,
  121838. _huff_lengthlist_line_128x11_3sub3,
  121839. 0, 0, 0, 0, 0,
  121840. NULL,
  121841. NULL,
  121842. NULL,
  121843. NULL,
  121844. 0
  121845. };
  121846. static long _huff_lengthlist_line_128x17_class1[] = {
  121847. 1, 3, 4, 7, 2, 5, 6, 7,
  121848. };
  121849. static static_codebook _huff_book_line_128x17_class1 = {
  121850. 1, 8,
  121851. _huff_lengthlist_line_128x17_class1,
  121852. 0, 0, 0, 0, 0,
  121853. NULL,
  121854. NULL,
  121855. NULL,
  121856. NULL,
  121857. 0
  121858. };
  121859. static long _huff_lengthlist_line_128x17_class2[] = {
  121860. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  121861. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  121862. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  121863. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121864. };
  121865. static static_codebook _huff_book_line_128x17_class2 = {
  121866. 1, 64,
  121867. _huff_lengthlist_line_128x17_class2,
  121868. 0, 0, 0, 0, 0,
  121869. NULL,
  121870. NULL,
  121871. NULL,
  121872. NULL,
  121873. 0
  121874. };
  121875. static long _huff_lengthlist_line_128x17_class3[] = {
  121876. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  121877. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  121878. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  121879. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  121880. };
  121881. static static_codebook _huff_book_line_128x17_class3 = {
  121882. 1, 64,
  121883. _huff_lengthlist_line_128x17_class3,
  121884. 0, 0, 0, 0, 0,
  121885. NULL,
  121886. NULL,
  121887. NULL,
  121888. NULL,
  121889. 0
  121890. };
  121891. static long _huff_lengthlist_line_128x17_0sub0[] = {
  121892. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  121893. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  121894. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  121895. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  121896. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  121897. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  121898. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  121899. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  121900. };
  121901. static static_codebook _huff_book_line_128x17_0sub0 = {
  121902. 1, 128,
  121903. _huff_lengthlist_line_128x17_0sub0,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_128x17_1sub0[] = {
  121912. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121913. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  121914. };
  121915. static static_codebook _huff_book_line_128x17_1sub0 = {
  121916. 1, 32,
  121917. _huff_lengthlist_line_128x17_1sub0,
  121918. 0, 0, 0, 0, 0,
  121919. NULL,
  121920. NULL,
  121921. NULL,
  121922. NULL,
  121923. 0
  121924. };
  121925. static long _huff_lengthlist_line_128x17_1sub1[] = {
  121926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121928. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  121929. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  121930. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  121931. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  121932. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  121933. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  121934. };
  121935. static static_codebook _huff_book_line_128x17_1sub1 = {
  121936. 1, 128,
  121937. _huff_lengthlist_line_128x17_1sub1,
  121938. 0, 0, 0, 0, 0,
  121939. NULL,
  121940. NULL,
  121941. NULL,
  121942. NULL,
  121943. 0
  121944. };
  121945. static long _huff_lengthlist_line_128x17_2sub1[] = {
  121946. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  121947. 9, 4,
  121948. };
  121949. static static_codebook _huff_book_line_128x17_2sub1 = {
  121950. 1, 18,
  121951. _huff_lengthlist_line_128x17_2sub1,
  121952. 0, 0, 0, 0, 0,
  121953. NULL,
  121954. NULL,
  121955. NULL,
  121956. NULL,
  121957. 0
  121958. };
  121959. static long _huff_lengthlist_line_128x17_2sub2[] = {
  121960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121961. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  121962. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  121963. 13,13,
  121964. };
  121965. static static_codebook _huff_book_line_128x17_2sub2 = {
  121966. 1, 50,
  121967. _huff_lengthlist_line_128x17_2sub2,
  121968. 0, 0, 0, 0, 0,
  121969. NULL,
  121970. NULL,
  121971. NULL,
  121972. NULL,
  121973. 0
  121974. };
  121975. static long _huff_lengthlist_line_128x17_2sub3[] = {
  121976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121979. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121980. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  121981. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121982. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121983. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  121984. };
  121985. static static_codebook _huff_book_line_128x17_2sub3 = {
  121986. 1, 128,
  121987. _huff_lengthlist_line_128x17_2sub3,
  121988. 0, 0, 0, 0, 0,
  121989. NULL,
  121990. NULL,
  121991. NULL,
  121992. NULL,
  121993. 0
  121994. };
  121995. static long _huff_lengthlist_line_128x17_3sub1[] = {
  121996. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  121997. 6, 4,
  121998. };
  121999. static static_codebook _huff_book_line_128x17_3sub1 = {
  122000. 1, 18,
  122001. _huff_lengthlist_line_128x17_3sub1,
  122002. 0, 0, 0, 0, 0,
  122003. NULL,
  122004. NULL,
  122005. NULL,
  122006. NULL,
  122007. 0
  122008. };
  122009. static long _huff_lengthlist_line_128x17_3sub2[] = {
  122010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122011. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  122012. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  122013. 10, 8,
  122014. };
  122015. static static_codebook _huff_book_line_128x17_3sub2 = {
  122016. 1, 50,
  122017. _huff_lengthlist_line_128x17_3sub2,
  122018. 0, 0, 0, 0, 0,
  122019. NULL,
  122020. NULL,
  122021. NULL,
  122022. NULL,
  122023. 0
  122024. };
  122025. static long _huff_lengthlist_line_128x17_3sub3[] = {
  122026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122029. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  122030. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  122031. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122034. };
  122035. static static_codebook _huff_book_line_128x17_3sub3 = {
  122036. 1, 128,
  122037. _huff_lengthlist_line_128x17_3sub3,
  122038. 0, 0, 0, 0, 0,
  122039. NULL,
  122040. NULL,
  122041. NULL,
  122042. NULL,
  122043. 0
  122044. };
  122045. static long _huff_lengthlist_line_1024x27_class1[] = {
  122046. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122047. };
  122048. static static_codebook _huff_book_line_1024x27_class1 = {
  122049. 1, 16,
  122050. _huff_lengthlist_line_1024x27_class1,
  122051. 0, 0, 0, 0, 0,
  122052. NULL,
  122053. NULL,
  122054. NULL,
  122055. NULL,
  122056. 0
  122057. };
  122058. static long _huff_lengthlist_line_1024x27_class2[] = {
  122059. 1, 4, 2, 6, 3, 7, 5, 7,
  122060. };
  122061. static static_codebook _huff_book_line_1024x27_class2 = {
  122062. 1, 8,
  122063. _huff_lengthlist_line_1024x27_class2,
  122064. 0, 0, 0, 0, 0,
  122065. NULL,
  122066. NULL,
  122067. NULL,
  122068. NULL,
  122069. 0
  122070. };
  122071. static long _huff_lengthlist_line_1024x27_class3[] = {
  122072. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122073. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122074. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122075. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122076. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122077. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122078. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122079. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122080. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122081. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122082. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122083. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122084. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122085. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122086. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122087. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122088. };
  122089. static static_codebook _huff_book_line_1024x27_class3 = {
  122090. 1, 256,
  122091. _huff_lengthlist_line_1024x27_class3,
  122092. 0, 0, 0, 0, 0,
  122093. NULL,
  122094. NULL,
  122095. NULL,
  122096. NULL,
  122097. 0
  122098. };
  122099. static long _huff_lengthlist_line_1024x27_class4[] = {
  122100. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122101. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122102. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122103. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122104. };
  122105. static static_codebook _huff_book_line_1024x27_class4 = {
  122106. 1, 64,
  122107. _huff_lengthlist_line_1024x27_class4,
  122108. 0, 0, 0, 0, 0,
  122109. NULL,
  122110. NULL,
  122111. NULL,
  122112. NULL,
  122113. 0
  122114. };
  122115. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122116. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122117. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122118. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122119. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122120. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122121. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122122. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122123. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122124. };
  122125. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122126. 1, 128,
  122127. _huff_lengthlist_line_1024x27_0sub0,
  122128. 0, 0, 0, 0, 0,
  122129. NULL,
  122130. NULL,
  122131. NULL,
  122132. NULL,
  122133. 0
  122134. };
  122135. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122136. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122137. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122138. };
  122139. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122140. 1, 32,
  122141. _huff_lengthlist_line_1024x27_1sub0,
  122142. 0, 0, 0, 0, 0,
  122143. NULL,
  122144. NULL,
  122145. NULL,
  122146. NULL,
  122147. 0
  122148. };
  122149. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122152. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122153. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122154. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122155. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122156. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122157. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122158. };
  122159. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122160. 1, 128,
  122161. _huff_lengthlist_line_1024x27_1sub1,
  122162. 0, 0, 0, 0, 0,
  122163. NULL,
  122164. NULL,
  122165. NULL,
  122166. NULL,
  122167. 0
  122168. };
  122169. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122170. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122171. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122172. };
  122173. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122174. 1, 32,
  122175. _huff_lengthlist_line_1024x27_2sub0,
  122176. 0, 0, 0, 0, 0,
  122177. NULL,
  122178. NULL,
  122179. NULL,
  122180. NULL,
  122181. 0
  122182. };
  122183. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122186. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122187. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122188. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122189. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122190. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122191. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122192. };
  122193. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122194. 1, 128,
  122195. _huff_lengthlist_line_1024x27_2sub1,
  122196. 0, 0, 0, 0, 0,
  122197. NULL,
  122198. NULL,
  122199. NULL,
  122200. NULL,
  122201. 0
  122202. };
  122203. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122204. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122205. 5, 5,
  122206. };
  122207. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122208. 1, 18,
  122209. _huff_lengthlist_line_1024x27_3sub1,
  122210. 0, 0, 0, 0, 0,
  122211. NULL,
  122212. NULL,
  122213. NULL,
  122214. NULL,
  122215. 0
  122216. };
  122217. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122219. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122220. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122221. 9,11,
  122222. };
  122223. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122224. 1, 50,
  122225. _huff_lengthlist_line_1024x27_3sub2,
  122226. 0, 0, 0, 0, 0,
  122227. NULL,
  122228. NULL,
  122229. NULL,
  122230. NULL,
  122231. 0
  122232. };
  122233. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122237. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122238. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122239. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122240. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122241. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122242. };
  122243. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122244. 1, 128,
  122245. _huff_lengthlist_line_1024x27_3sub3,
  122246. 0, 0, 0, 0, 0,
  122247. NULL,
  122248. NULL,
  122249. NULL,
  122250. NULL,
  122251. 0
  122252. };
  122253. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122254. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122255. 5, 4,
  122256. };
  122257. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122258. 1, 18,
  122259. _huff_lengthlist_line_1024x27_4sub1,
  122260. 0, 0, 0, 0, 0,
  122261. NULL,
  122262. NULL,
  122263. NULL,
  122264. NULL,
  122265. 0
  122266. };
  122267. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122269. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122270. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122271. 9,12,
  122272. };
  122273. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122274. 1, 50,
  122275. _huff_lengthlist_line_1024x27_4sub2,
  122276. 0, 0, 0, 0, 0,
  122277. NULL,
  122278. NULL,
  122279. NULL,
  122280. NULL,
  122281. 0
  122282. };
  122283. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122287. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122288. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122289. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122290. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122291. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122292. };
  122293. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122294. 1, 128,
  122295. _huff_lengthlist_line_1024x27_4sub3,
  122296. 0, 0, 0, 0, 0,
  122297. NULL,
  122298. NULL,
  122299. NULL,
  122300. NULL,
  122301. 0
  122302. };
  122303. static long _huff_lengthlist_line_2048x27_class1[] = {
  122304. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122305. };
  122306. static static_codebook _huff_book_line_2048x27_class1 = {
  122307. 1, 16,
  122308. _huff_lengthlist_line_2048x27_class1,
  122309. 0, 0, 0, 0, 0,
  122310. NULL,
  122311. NULL,
  122312. NULL,
  122313. NULL,
  122314. 0
  122315. };
  122316. static long _huff_lengthlist_line_2048x27_class2[] = {
  122317. 1, 2, 3, 6, 4, 7, 5, 7,
  122318. };
  122319. static static_codebook _huff_book_line_2048x27_class2 = {
  122320. 1, 8,
  122321. _huff_lengthlist_line_2048x27_class2,
  122322. 0, 0, 0, 0, 0,
  122323. NULL,
  122324. NULL,
  122325. NULL,
  122326. NULL,
  122327. 0
  122328. };
  122329. static long _huff_lengthlist_line_2048x27_class3[] = {
  122330. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122331. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122332. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122333. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122334. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122335. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122336. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122337. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122338. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122339. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122340. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122341. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122342. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122343. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122344. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122345. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122346. };
  122347. static static_codebook _huff_book_line_2048x27_class3 = {
  122348. 1, 256,
  122349. _huff_lengthlist_line_2048x27_class3,
  122350. 0, 0, 0, 0, 0,
  122351. NULL,
  122352. NULL,
  122353. NULL,
  122354. NULL,
  122355. 0
  122356. };
  122357. static long _huff_lengthlist_line_2048x27_class4[] = {
  122358. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122359. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122360. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122361. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122362. };
  122363. static static_codebook _huff_book_line_2048x27_class4 = {
  122364. 1, 64,
  122365. _huff_lengthlist_line_2048x27_class4,
  122366. 0, 0, 0, 0, 0,
  122367. NULL,
  122368. NULL,
  122369. NULL,
  122370. NULL,
  122371. 0
  122372. };
  122373. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122374. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122375. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122376. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122377. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122378. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122379. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122380. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122381. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122382. };
  122383. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122384. 1, 128,
  122385. _huff_lengthlist_line_2048x27_0sub0,
  122386. 0, 0, 0, 0, 0,
  122387. NULL,
  122388. NULL,
  122389. NULL,
  122390. NULL,
  122391. 0
  122392. };
  122393. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122394. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122395. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122396. };
  122397. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122398. 1, 32,
  122399. _huff_lengthlist_line_2048x27_1sub0,
  122400. 0, 0, 0, 0, 0,
  122401. NULL,
  122402. NULL,
  122403. NULL,
  122404. NULL,
  122405. 0
  122406. };
  122407. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122410. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122411. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122412. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122413. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122414. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122415. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122416. };
  122417. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122418. 1, 128,
  122419. _huff_lengthlist_line_2048x27_1sub1,
  122420. 0, 0, 0, 0, 0,
  122421. NULL,
  122422. NULL,
  122423. NULL,
  122424. NULL,
  122425. 0
  122426. };
  122427. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122428. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122429. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122430. };
  122431. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122432. 1, 32,
  122433. _huff_lengthlist_line_2048x27_2sub0,
  122434. 0, 0, 0, 0, 0,
  122435. NULL,
  122436. NULL,
  122437. NULL,
  122438. NULL,
  122439. 0
  122440. };
  122441. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122444. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122445. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122446. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122447. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122448. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122449. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122450. };
  122451. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122452. 1, 128,
  122453. _huff_lengthlist_line_2048x27_2sub1,
  122454. 0, 0, 0, 0, 0,
  122455. NULL,
  122456. NULL,
  122457. NULL,
  122458. NULL,
  122459. 0
  122460. };
  122461. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122462. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122463. 5, 5,
  122464. };
  122465. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122466. 1, 18,
  122467. _huff_lengthlist_line_2048x27_3sub1,
  122468. 0, 0, 0, 0, 0,
  122469. NULL,
  122470. NULL,
  122471. NULL,
  122472. NULL,
  122473. 0
  122474. };
  122475. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122477. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122478. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122479. 10,12,
  122480. };
  122481. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122482. 1, 50,
  122483. _huff_lengthlist_line_2048x27_3sub2,
  122484. 0, 0, 0, 0, 0,
  122485. NULL,
  122486. NULL,
  122487. NULL,
  122488. NULL,
  122489. 0
  122490. };
  122491. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122495. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122496. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122497. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122498. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122499. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122500. };
  122501. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122502. 1, 128,
  122503. _huff_lengthlist_line_2048x27_3sub3,
  122504. 0, 0, 0, 0, 0,
  122505. NULL,
  122506. NULL,
  122507. NULL,
  122508. NULL,
  122509. 0
  122510. };
  122511. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122512. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122513. 4, 5,
  122514. };
  122515. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122516. 1, 18,
  122517. _huff_lengthlist_line_2048x27_4sub1,
  122518. 0, 0, 0, 0, 0,
  122519. NULL,
  122520. NULL,
  122521. NULL,
  122522. NULL,
  122523. 0
  122524. };
  122525. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122527. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122528. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122529. 10,10,
  122530. };
  122531. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122532. 1, 50,
  122533. _huff_lengthlist_line_2048x27_4sub2,
  122534. 0, 0, 0, 0, 0,
  122535. NULL,
  122536. NULL,
  122537. NULL,
  122538. NULL,
  122539. 0
  122540. };
  122541. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122545. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122546. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122547. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122548. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122549. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122550. };
  122551. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122552. 1, 128,
  122553. _huff_lengthlist_line_2048x27_4sub3,
  122554. 0, 0, 0, 0, 0,
  122555. NULL,
  122556. NULL,
  122557. NULL,
  122558. NULL,
  122559. 0
  122560. };
  122561. static long _huff_lengthlist_line_256x4low_class0[] = {
  122562. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  122563. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  122564. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  122565. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  122566. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  122567. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  122568. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  122569. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  122570. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  122571. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  122572. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  122573. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  122574. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  122575. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  122576. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  122577. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  122578. };
  122579. static static_codebook _huff_book_line_256x4low_class0 = {
  122580. 1, 256,
  122581. _huff_lengthlist_line_256x4low_class0,
  122582. 0, 0, 0, 0, 0,
  122583. NULL,
  122584. NULL,
  122585. NULL,
  122586. NULL,
  122587. 0
  122588. };
  122589. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  122590. 1, 3, 2, 3,
  122591. };
  122592. static static_codebook _huff_book_line_256x4low_0sub0 = {
  122593. 1, 4,
  122594. _huff_lengthlist_line_256x4low_0sub0,
  122595. 0, 0, 0, 0, 0,
  122596. NULL,
  122597. NULL,
  122598. NULL,
  122599. NULL,
  122600. 0
  122601. };
  122602. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  122603. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  122604. };
  122605. static static_codebook _huff_book_line_256x4low_0sub1 = {
  122606. 1, 10,
  122607. _huff_lengthlist_line_256x4low_0sub1,
  122608. 0, 0, 0, 0, 0,
  122609. NULL,
  122610. NULL,
  122611. NULL,
  122612. NULL,
  122613. 0
  122614. };
  122615. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  122616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  122617. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  122618. };
  122619. static static_codebook _huff_book_line_256x4low_0sub2 = {
  122620. 1, 25,
  122621. _huff_lengthlist_line_256x4low_0sub2,
  122622. 0, 0, 0, 0, 0,
  122623. NULL,
  122624. NULL,
  122625. NULL,
  122626. NULL,
  122627. 0
  122628. };
  122629. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  122630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  122632. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  122633. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  122634. };
  122635. static static_codebook _huff_book_line_256x4low_0sub3 = {
  122636. 1, 64,
  122637. _huff_lengthlist_line_256x4low_0sub3,
  122638. 0, 0, 0, 0, 0,
  122639. NULL,
  122640. NULL,
  122641. NULL,
  122642. NULL,
  122643. 0
  122644. };
  122645. /*** End of inlined file: floor_books.h ***/
  122646. static static_codebook *_floor_128x4_books[]={
  122647. &_huff_book_line_128x4_class0,
  122648. &_huff_book_line_128x4_0sub0,
  122649. &_huff_book_line_128x4_0sub1,
  122650. &_huff_book_line_128x4_0sub2,
  122651. &_huff_book_line_128x4_0sub3,
  122652. };
  122653. static static_codebook *_floor_256x4_books[]={
  122654. &_huff_book_line_256x4_class0,
  122655. &_huff_book_line_256x4_0sub0,
  122656. &_huff_book_line_256x4_0sub1,
  122657. &_huff_book_line_256x4_0sub2,
  122658. &_huff_book_line_256x4_0sub3,
  122659. };
  122660. static static_codebook *_floor_128x7_books[]={
  122661. &_huff_book_line_128x7_class0,
  122662. &_huff_book_line_128x7_class1,
  122663. &_huff_book_line_128x7_0sub1,
  122664. &_huff_book_line_128x7_0sub2,
  122665. &_huff_book_line_128x7_0sub3,
  122666. &_huff_book_line_128x7_1sub1,
  122667. &_huff_book_line_128x7_1sub2,
  122668. &_huff_book_line_128x7_1sub3,
  122669. };
  122670. static static_codebook *_floor_256x7_books[]={
  122671. &_huff_book_line_256x7_class0,
  122672. &_huff_book_line_256x7_class1,
  122673. &_huff_book_line_256x7_0sub1,
  122674. &_huff_book_line_256x7_0sub2,
  122675. &_huff_book_line_256x7_0sub3,
  122676. &_huff_book_line_256x7_1sub1,
  122677. &_huff_book_line_256x7_1sub2,
  122678. &_huff_book_line_256x7_1sub3,
  122679. };
  122680. static static_codebook *_floor_128x11_books[]={
  122681. &_huff_book_line_128x11_class1,
  122682. &_huff_book_line_128x11_class2,
  122683. &_huff_book_line_128x11_class3,
  122684. &_huff_book_line_128x11_0sub0,
  122685. &_huff_book_line_128x11_1sub0,
  122686. &_huff_book_line_128x11_1sub1,
  122687. &_huff_book_line_128x11_2sub1,
  122688. &_huff_book_line_128x11_2sub2,
  122689. &_huff_book_line_128x11_2sub3,
  122690. &_huff_book_line_128x11_3sub1,
  122691. &_huff_book_line_128x11_3sub2,
  122692. &_huff_book_line_128x11_3sub3,
  122693. };
  122694. static static_codebook *_floor_128x17_books[]={
  122695. &_huff_book_line_128x17_class1,
  122696. &_huff_book_line_128x17_class2,
  122697. &_huff_book_line_128x17_class3,
  122698. &_huff_book_line_128x17_0sub0,
  122699. &_huff_book_line_128x17_1sub0,
  122700. &_huff_book_line_128x17_1sub1,
  122701. &_huff_book_line_128x17_2sub1,
  122702. &_huff_book_line_128x17_2sub2,
  122703. &_huff_book_line_128x17_2sub3,
  122704. &_huff_book_line_128x17_3sub1,
  122705. &_huff_book_line_128x17_3sub2,
  122706. &_huff_book_line_128x17_3sub3,
  122707. };
  122708. static static_codebook *_floor_256x4low_books[]={
  122709. &_huff_book_line_256x4low_class0,
  122710. &_huff_book_line_256x4low_0sub0,
  122711. &_huff_book_line_256x4low_0sub1,
  122712. &_huff_book_line_256x4low_0sub2,
  122713. &_huff_book_line_256x4low_0sub3,
  122714. };
  122715. static static_codebook *_floor_1024x27_books[]={
  122716. &_huff_book_line_1024x27_class1,
  122717. &_huff_book_line_1024x27_class2,
  122718. &_huff_book_line_1024x27_class3,
  122719. &_huff_book_line_1024x27_class4,
  122720. &_huff_book_line_1024x27_0sub0,
  122721. &_huff_book_line_1024x27_1sub0,
  122722. &_huff_book_line_1024x27_1sub1,
  122723. &_huff_book_line_1024x27_2sub0,
  122724. &_huff_book_line_1024x27_2sub1,
  122725. &_huff_book_line_1024x27_3sub1,
  122726. &_huff_book_line_1024x27_3sub2,
  122727. &_huff_book_line_1024x27_3sub3,
  122728. &_huff_book_line_1024x27_4sub1,
  122729. &_huff_book_line_1024x27_4sub2,
  122730. &_huff_book_line_1024x27_4sub3,
  122731. };
  122732. static static_codebook *_floor_2048x27_books[]={
  122733. &_huff_book_line_2048x27_class1,
  122734. &_huff_book_line_2048x27_class2,
  122735. &_huff_book_line_2048x27_class3,
  122736. &_huff_book_line_2048x27_class4,
  122737. &_huff_book_line_2048x27_0sub0,
  122738. &_huff_book_line_2048x27_1sub0,
  122739. &_huff_book_line_2048x27_1sub1,
  122740. &_huff_book_line_2048x27_2sub0,
  122741. &_huff_book_line_2048x27_2sub1,
  122742. &_huff_book_line_2048x27_3sub1,
  122743. &_huff_book_line_2048x27_3sub2,
  122744. &_huff_book_line_2048x27_3sub3,
  122745. &_huff_book_line_2048x27_4sub1,
  122746. &_huff_book_line_2048x27_4sub2,
  122747. &_huff_book_line_2048x27_4sub3,
  122748. };
  122749. static static_codebook *_floor_512x17_books[]={
  122750. &_huff_book_line_512x17_class1,
  122751. &_huff_book_line_512x17_class2,
  122752. &_huff_book_line_512x17_class3,
  122753. &_huff_book_line_512x17_0sub0,
  122754. &_huff_book_line_512x17_1sub0,
  122755. &_huff_book_line_512x17_1sub1,
  122756. &_huff_book_line_512x17_2sub1,
  122757. &_huff_book_line_512x17_2sub2,
  122758. &_huff_book_line_512x17_2sub3,
  122759. &_huff_book_line_512x17_3sub1,
  122760. &_huff_book_line_512x17_3sub2,
  122761. &_huff_book_line_512x17_3sub3,
  122762. };
  122763. static static_codebook **_floor_books[10]={
  122764. _floor_128x4_books,
  122765. _floor_256x4_books,
  122766. _floor_128x7_books,
  122767. _floor_256x7_books,
  122768. _floor_128x11_books,
  122769. _floor_128x17_books,
  122770. _floor_256x4low_books,
  122771. _floor_1024x27_books,
  122772. _floor_2048x27_books,
  122773. _floor_512x17_books,
  122774. };
  122775. static vorbis_info_floor1 _floor[10]={
  122776. /* 128 x 4 */
  122777. {
  122778. 1,{0},{4},{2},{0},
  122779. {{1,2,3,4}},
  122780. 4,{0,128, 33,8,16,70},
  122781. 60,30,500, 1.,18., -1
  122782. },
  122783. /* 256 x 4 */
  122784. {
  122785. 1,{0},{4},{2},{0},
  122786. {{1,2,3,4}},
  122787. 4,{0,256, 66,16,32,140},
  122788. 60,30,500, 1.,18., -1
  122789. },
  122790. /* 128 x 7 */
  122791. {
  122792. 2,{0,1},{3,4},{2,2},{0,1},
  122793. {{-1,2,3,4},{-1,5,6,7}},
  122794. 4,{0,128, 14,4,58, 2,8,28,90},
  122795. 60,30,500, 1.,18., -1
  122796. },
  122797. /* 256 x 7 */
  122798. {
  122799. 2,{0,1},{3,4},{2,2},{0,1},
  122800. {{-1,2,3,4},{-1,5,6,7}},
  122801. 4,{0,256, 28,8,116, 4,16,56,180},
  122802. 60,30,500, 1.,18., -1
  122803. },
  122804. /* 128 x 11 */
  122805. {
  122806. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122807. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122808. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  122809. 60,30,500, 1,18., -1
  122810. },
  122811. /* 128 x 17 */
  122812. {
  122813. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122814. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122815. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  122816. 60,30,500, 1,18., -1
  122817. },
  122818. /* 256 x 4 (low bitrate version) */
  122819. {
  122820. 1,{0},{4},{2},{0},
  122821. {{1,2,3,4}},
  122822. 4,{0,256, 66,16,32,140},
  122823. 60,30,500, 1.,18., -1
  122824. },
  122825. /* 1024 x 27 */
  122826. {
  122827. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122828. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122829. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  122830. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  122831. 60,30,500, 3,18., -1 /* lowpass */
  122832. },
  122833. /* 2048 x 27 */
  122834. {
  122835. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  122836. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  122837. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  122838. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  122839. 60,30,500, 3,18., -1 /* lowpass */
  122840. },
  122841. /* 512 x 17 */
  122842. {
  122843. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  122844. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  122845. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  122846. 7,23,39, 55,79,110, 156,232,360},
  122847. 60,30,500, 1,18., -1 /* lowpass! */
  122848. },
  122849. };
  122850. /*** End of inlined file: floor_all.h ***/
  122851. /*** Start of inlined file: residue_44.h ***/
  122852. /*** Start of inlined file: res_books_stereo.h ***/
  122853. static long _vq_quantlist__16c0_s_p1_0[] = {
  122854. 1,
  122855. 0,
  122856. 2,
  122857. };
  122858. static long _vq_lengthlist__16c0_s_p1_0[] = {
  122859. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  122860. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  122865. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  122870. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  122905. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  122910. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  122915. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122950. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  122951. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  122956. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  122961. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123269. 0,
  123270. };
  123271. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123272. -0.5, 0.5,
  123273. };
  123274. static long _vq_quantmap__16c0_s_p1_0[] = {
  123275. 1, 0, 2,
  123276. };
  123277. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123278. _vq_quantthresh__16c0_s_p1_0,
  123279. _vq_quantmap__16c0_s_p1_0,
  123280. 3,
  123281. 3
  123282. };
  123283. static static_codebook _16c0_s_p1_0 = {
  123284. 8, 6561,
  123285. _vq_lengthlist__16c0_s_p1_0,
  123286. 1, -535822336, 1611661312, 2, 0,
  123287. _vq_quantlist__16c0_s_p1_0,
  123288. NULL,
  123289. &_vq_auxt__16c0_s_p1_0,
  123290. NULL,
  123291. 0
  123292. };
  123293. static long _vq_quantlist__16c0_s_p2_0[] = {
  123294. 2,
  123295. 1,
  123296. 3,
  123297. 0,
  123298. 4,
  123299. };
  123300. static long _vq_lengthlist__16c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123340. 0,
  123341. };
  123342. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123343. -1.5, -0.5, 0.5, 1.5,
  123344. };
  123345. static long _vq_quantmap__16c0_s_p2_0[] = {
  123346. 3, 1, 0, 2, 4,
  123347. };
  123348. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123349. _vq_quantthresh__16c0_s_p2_0,
  123350. _vq_quantmap__16c0_s_p2_0,
  123351. 5,
  123352. 5
  123353. };
  123354. static static_codebook _16c0_s_p2_0 = {
  123355. 4, 625,
  123356. _vq_lengthlist__16c0_s_p2_0,
  123357. 1, -533725184, 1611661312, 3, 0,
  123358. _vq_quantlist__16c0_s_p2_0,
  123359. NULL,
  123360. &_vq_auxt__16c0_s_p2_0,
  123361. NULL,
  123362. 0
  123363. };
  123364. static long _vq_quantlist__16c0_s_p3_0[] = {
  123365. 2,
  123366. 1,
  123367. 3,
  123368. 0,
  123369. 4,
  123370. };
  123371. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123372. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123375. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123378. 0, 0, 0, 0, 6, 6, 6, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123411. 0,
  123412. };
  123413. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123414. -1.5, -0.5, 0.5, 1.5,
  123415. };
  123416. static long _vq_quantmap__16c0_s_p3_0[] = {
  123417. 3, 1, 0, 2, 4,
  123418. };
  123419. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123420. _vq_quantthresh__16c0_s_p3_0,
  123421. _vq_quantmap__16c0_s_p3_0,
  123422. 5,
  123423. 5
  123424. };
  123425. static static_codebook _16c0_s_p3_0 = {
  123426. 4, 625,
  123427. _vq_lengthlist__16c0_s_p3_0,
  123428. 1, -533725184, 1611661312, 3, 0,
  123429. _vq_quantlist__16c0_s_p3_0,
  123430. NULL,
  123431. &_vq_auxt__16c0_s_p3_0,
  123432. NULL,
  123433. 0
  123434. };
  123435. static long _vq_quantlist__16c0_s_p4_0[] = {
  123436. 4,
  123437. 3,
  123438. 5,
  123439. 2,
  123440. 6,
  123441. 1,
  123442. 7,
  123443. 0,
  123444. 8,
  123445. };
  123446. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123447. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123448. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123449. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123450. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123451. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123452. 0,
  123453. };
  123454. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123455. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123456. };
  123457. static long _vq_quantmap__16c0_s_p4_0[] = {
  123458. 7, 5, 3, 1, 0, 2, 4, 6,
  123459. 8,
  123460. };
  123461. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123462. _vq_quantthresh__16c0_s_p4_0,
  123463. _vq_quantmap__16c0_s_p4_0,
  123464. 9,
  123465. 9
  123466. };
  123467. static static_codebook _16c0_s_p4_0 = {
  123468. 2, 81,
  123469. _vq_lengthlist__16c0_s_p4_0,
  123470. 1, -531628032, 1611661312, 4, 0,
  123471. _vq_quantlist__16c0_s_p4_0,
  123472. NULL,
  123473. &_vq_auxt__16c0_s_p4_0,
  123474. NULL,
  123475. 0
  123476. };
  123477. static long _vq_quantlist__16c0_s_p5_0[] = {
  123478. 4,
  123479. 3,
  123480. 5,
  123481. 2,
  123482. 6,
  123483. 1,
  123484. 7,
  123485. 0,
  123486. 8,
  123487. };
  123488. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123489. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123490. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123491. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123492. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123493. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123494. 10,
  123495. };
  123496. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123497. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123498. };
  123499. static long _vq_quantmap__16c0_s_p5_0[] = {
  123500. 7, 5, 3, 1, 0, 2, 4, 6,
  123501. 8,
  123502. };
  123503. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123504. _vq_quantthresh__16c0_s_p5_0,
  123505. _vq_quantmap__16c0_s_p5_0,
  123506. 9,
  123507. 9
  123508. };
  123509. static static_codebook _16c0_s_p5_0 = {
  123510. 2, 81,
  123511. _vq_lengthlist__16c0_s_p5_0,
  123512. 1, -531628032, 1611661312, 4, 0,
  123513. _vq_quantlist__16c0_s_p5_0,
  123514. NULL,
  123515. &_vq_auxt__16c0_s_p5_0,
  123516. NULL,
  123517. 0
  123518. };
  123519. static long _vq_quantlist__16c0_s_p6_0[] = {
  123520. 8,
  123521. 7,
  123522. 9,
  123523. 6,
  123524. 10,
  123525. 5,
  123526. 11,
  123527. 4,
  123528. 12,
  123529. 3,
  123530. 13,
  123531. 2,
  123532. 14,
  123533. 1,
  123534. 15,
  123535. 0,
  123536. 16,
  123537. };
  123538. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123539. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123540. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123541. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123542. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123543. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123544. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123545. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123546. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123547. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123548. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123549. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123550. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123551. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123552. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123553. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123554. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123555. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123557. 14,
  123558. };
  123559. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123560. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123561. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123562. };
  123563. static long _vq_quantmap__16c0_s_p6_0[] = {
  123564. 15, 13, 11, 9, 7, 5, 3, 1,
  123565. 0, 2, 4, 6, 8, 10, 12, 14,
  123566. 16,
  123567. };
  123568. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  123569. _vq_quantthresh__16c0_s_p6_0,
  123570. _vq_quantmap__16c0_s_p6_0,
  123571. 17,
  123572. 17
  123573. };
  123574. static static_codebook _16c0_s_p6_0 = {
  123575. 2, 289,
  123576. _vq_lengthlist__16c0_s_p6_0,
  123577. 1, -529530880, 1611661312, 5, 0,
  123578. _vq_quantlist__16c0_s_p6_0,
  123579. NULL,
  123580. &_vq_auxt__16c0_s_p6_0,
  123581. NULL,
  123582. 0
  123583. };
  123584. static long _vq_quantlist__16c0_s_p7_0[] = {
  123585. 1,
  123586. 0,
  123587. 2,
  123588. };
  123589. static long _vq_lengthlist__16c0_s_p7_0[] = {
  123590. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  123591. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  123592. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  123593. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  123594. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  123595. 13,
  123596. };
  123597. static float _vq_quantthresh__16c0_s_p7_0[] = {
  123598. -5.5, 5.5,
  123599. };
  123600. static long _vq_quantmap__16c0_s_p7_0[] = {
  123601. 1, 0, 2,
  123602. };
  123603. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  123604. _vq_quantthresh__16c0_s_p7_0,
  123605. _vq_quantmap__16c0_s_p7_0,
  123606. 3,
  123607. 3
  123608. };
  123609. static static_codebook _16c0_s_p7_0 = {
  123610. 4, 81,
  123611. _vq_lengthlist__16c0_s_p7_0,
  123612. 1, -529137664, 1618345984, 2, 0,
  123613. _vq_quantlist__16c0_s_p7_0,
  123614. NULL,
  123615. &_vq_auxt__16c0_s_p7_0,
  123616. NULL,
  123617. 0
  123618. };
  123619. static long _vq_quantlist__16c0_s_p7_1[] = {
  123620. 5,
  123621. 4,
  123622. 6,
  123623. 3,
  123624. 7,
  123625. 2,
  123626. 8,
  123627. 1,
  123628. 9,
  123629. 0,
  123630. 10,
  123631. };
  123632. static long _vq_lengthlist__16c0_s_p7_1[] = {
  123633. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  123634. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  123635. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  123636. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  123637. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  123638. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  123639. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  123640. 11,11,11, 9, 9, 9, 9,10,10,
  123641. };
  123642. static float _vq_quantthresh__16c0_s_p7_1[] = {
  123643. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  123644. 3.5, 4.5,
  123645. };
  123646. static long _vq_quantmap__16c0_s_p7_1[] = {
  123647. 9, 7, 5, 3, 1, 0, 2, 4,
  123648. 6, 8, 10,
  123649. };
  123650. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  123651. _vq_quantthresh__16c0_s_p7_1,
  123652. _vq_quantmap__16c0_s_p7_1,
  123653. 11,
  123654. 11
  123655. };
  123656. static static_codebook _16c0_s_p7_1 = {
  123657. 2, 121,
  123658. _vq_lengthlist__16c0_s_p7_1,
  123659. 1, -531365888, 1611661312, 4, 0,
  123660. _vq_quantlist__16c0_s_p7_1,
  123661. NULL,
  123662. &_vq_auxt__16c0_s_p7_1,
  123663. NULL,
  123664. 0
  123665. };
  123666. static long _vq_quantlist__16c0_s_p8_0[] = {
  123667. 6,
  123668. 5,
  123669. 7,
  123670. 4,
  123671. 8,
  123672. 3,
  123673. 9,
  123674. 2,
  123675. 10,
  123676. 1,
  123677. 11,
  123678. 0,
  123679. 12,
  123680. };
  123681. static long _vq_lengthlist__16c0_s_p8_0[] = {
  123682. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  123683. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  123684. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  123685. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  123686. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  123687. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  123688. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  123689. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  123690. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  123691. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  123692. 0,12,13,13,12,13,14,14,14,
  123693. };
  123694. static float _vq_quantthresh__16c0_s_p8_0[] = {
  123695. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  123696. 12.5, 17.5, 22.5, 27.5,
  123697. };
  123698. static long _vq_quantmap__16c0_s_p8_0[] = {
  123699. 11, 9, 7, 5, 3, 1, 0, 2,
  123700. 4, 6, 8, 10, 12,
  123701. };
  123702. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  123703. _vq_quantthresh__16c0_s_p8_0,
  123704. _vq_quantmap__16c0_s_p8_0,
  123705. 13,
  123706. 13
  123707. };
  123708. static static_codebook _16c0_s_p8_0 = {
  123709. 2, 169,
  123710. _vq_lengthlist__16c0_s_p8_0,
  123711. 1, -526516224, 1616117760, 4, 0,
  123712. _vq_quantlist__16c0_s_p8_0,
  123713. NULL,
  123714. &_vq_auxt__16c0_s_p8_0,
  123715. NULL,
  123716. 0
  123717. };
  123718. static long _vq_quantlist__16c0_s_p8_1[] = {
  123719. 2,
  123720. 1,
  123721. 3,
  123722. 0,
  123723. 4,
  123724. };
  123725. static long _vq_lengthlist__16c0_s_p8_1[] = {
  123726. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  123727. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  123728. };
  123729. static float _vq_quantthresh__16c0_s_p8_1[] = {
  123730. -1.5, -0.5, 0.5, 1.5,
  123731. };
  123732. static long _vq_quantmap__16c0_s_p8_1[] = {
  123733. 3, 1, 0, 2, 4,
  123734. };
  123735. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  123736. _vq_quantthresh__16c0_s_p8_1,
  123737. _vq_quantmap__16c0_s_p8_1,
  123738. 5,
  123739. 5
  123740. };
  123741. static static_codebook _16c0_s_p8_1 = {
  123742. 2, 25,
  123743. _vq_lengthlist__16c0_s_p8_1,
  123744. 1, -533725184, 1611661312, 3, 0,
  123745. _vq_quantlist__16c0_s_p8_1,
  123746. NULL,
  123747. &_vq_auxt__16c0_s_p8_1,
  123748. NULL,
  123749. 0
  123750. };
  123751. static long _vq_quantlist__16c0_s_p9_0[] = {
  123752. 1,
  123753. 0,
  123754. 2,
  123755. };
  123756. static long _vq_lengthlist__16c0_s_p9_0[] = {
  123757. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123758. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  123759. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123760. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123761. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  123762. 7,
  123763. };
  123764. static float _vq_quantthresh__16c0_s_p9_0[] = {
  123765. -157.5, 157.5,
  123766. };
  123767. static long _vq_quantmap__16c0_s_p9_0[] = {
  123768. 1, 0, 2,
  123769. };
  123770. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  123771. _vq_quantthresh__16c0_s_p9_0,
  123772. _vq_quantmap__16c0_s_p9_0,
  123773. 3,
  123774. 3
  123775. };
  123776. static static_codebook _16c0_s_p9_0 = {
  123777. 4, 81,
  123778. _vq_lengthlist__16c0_s_p9_0,
  123779. 1, -518803456, 1628680192, 2, 0,
  123780. _vq_quantlist__16c0_s_p9_0,
  123781. NULL,
  123782. &_vq_auxt__16c0_s_p9_0,
  123783. NULL,
  123784. 0
  123785. };
  123786. static long _vq_quantlist__16c0_s_p9_1[] = {
  123787. 7,
  123788. 6,
  123789. 8,
  123790. 5,
  123791. 9,
  123792. 4,
  123793. 10,
  123794. 3,
  123795. 11,
  123796. 2,
  123797. 12,
  123798. 1,
  123799. 13,
  123800. 0,
  123801. 14,
  123802. };
  123803. static long _vq_lengthlist__16c0_s_p9_1[] = {
  123804. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  123805. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  123806. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  123807. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  123808. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123809. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123810. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123811. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123812. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123813. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123814. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123815. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123816. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123817. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  123818. 10,
  123819. };
  123820. static float _vq_quantthresh__16c0_s_p9_1[] = {
  123821. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  123822. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  123823. };
  123824. static long _vq_quantmap__16c0_s_p9_1[] = {
  123825. 13, 11, 9, 7, 5, 3, 1, 0,
  123826. 2, 4, 6, 8, 10, 12, 14,
  123827. };
  123828. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  123829. _vq_quantthresh__16c0_s_p9_1,
  123830. _vq_quantmap__16c0_s_p9_1,
  123831. 15,
  123832. 15
  123833. };
  123834. static static_codebook _16c0_s_p9_1 = {
  123835. 2, 225,
  123836. _vq_lengthlist__16c0_s_p9_1,
  123837. 1, -520986624, 1620377600, 4, 0,
  123838. _vq_quantlist__16c0_s_p9_1,
  123839. NULL,
  123840. &_vq_auxt__16c0_s_p9_1,
  123841. NULL,
  123842. 0
  123843. };
  123844. static long _vq_quantlist__16c0_s_p9_2[] = {
  123845. 10,
  123846. 9,
  123847. 11,
  123848. 8,
  123849. 12,
  123850. 7,
  123851. 13,
  123852. 6,
  123853. 14,
  123854. 5,
  123855. 15,
  123856. 4,
  123857. 16,
  123858. 3,
  123859. 17,
  123860. 2,
  123861. 18,
  123862. 1,
  123863. 19,
  123864. 0,
  123865. 20,
  123866. };
  123867. static long _vq_lengthlist__16c0_s_p9_2[] = {
  123868. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  123869. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  123870. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  123871. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  123872. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  123873. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  123874. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  123875. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  123876. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  123877. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  123878. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  123879. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  123880. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  123881. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  123882. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  123883. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  123884. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  123885. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  123886. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  123887. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  123888. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  123889. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  123890. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  123891. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  123892. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  123893. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  123894. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  123895. 10,11,10,10,11, 9,10,10,10,
  123896. };
  123897. static float _vq_quantthresh__16c0_s_p9_2[] = {
  123898. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  123899. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  123900. 6.5, 7.5, 8.5, 9.5,
  123901. };
  123902. static long _vq_quantmap__16c0_s_p9_2[] = {
  123903. 19, 17, 15, 13, 11, 9, 7, 5,
  123904. 3, 1, 0, 2, 4, 6, 8, 10,
  123905. 12, 14, 16, 18, 20,
  123906. };
  123907. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  123908. _vq_quantthresh__16c0_s_p9_2,
  123909. _vq_quantmap__16c0_s_p9_2,
  123910. 21,
  123911. 21
  123912. };
  123913. static static_codebook _16c0_s_p9_2 = {
  123914. 2, 441,
  123915. _vq_lengthlist__16c0_s_p9_2,
  123916. 1, -529268736, 1611661312, 5, 0,
  123917. _vq_quantlist__16c0_s_p9_2,
  123918. NULL,
  123919. &_vq_auxt__16c0_s_p9_2,
  123920. NULL,
  123921. 0
  123922. };
  123923. static long _huff_lengthlist__16c0_s_single[] = {
  123924. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  123925. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  123926. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  123927. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  123928. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  123929. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  123930. 16,16,18,18,
  123931. };
  123932. static static_codebook _huff_book__16c0_s_single = {
  123933. 2, 100,
  123934. _huff_lengthlist__16c0_s_single,
  123935. 0, 0, 0, 0, 0,
  123936. NULL,
  123937. NULL,
  123938. NULL,
  123939. NULL,
  123940. 0
  123941. };
  123942. static long _huff_lengthlist__16c1_s_long[] = {
  123943. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  123944. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  123945. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  123946. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  123947. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  123948. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  123949. 12,11,11,13,
  123950. };
  123951. static static_codebook _huff_book__16c1_s_long = {
  123952. 2, 100,
  123953. _huff_lengthlist__16c1_s_long,
  123954. 0, 0, 0, 0, 0,
  123955. NULL,
  123956. NULL,
  123957. NULL,
  123958. NULL,
  123959. 0
  123960. };
  123961. static long _vq_quantlist__16c1_s_p1_0[] = {
  123962. 1,
  123963. 0,
  123964. 2,
  123965. };
  123966. static long _vq_lengthlist__16c1_s_p1_0[] = {
  123967. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123968. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  123973. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  123978. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  124013. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  124018. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  124023. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124058. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124059. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124064. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124069. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124377. 0,
  124378. };
  124379. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124380. -0.5, 0.5,
  124381. };
  124382. static long _vq_quantmap__16c1_s_p1_0[] = {
  124383. 1, 0, 2,
  124384. };
  124385. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124386. _vq_quantthresh__16c1_s_p1_0,
  124387. _vq_quantmap__16c1_s_p1_0,
  124388. 3,
  124389. 3
  124390. };
  124391. static static_codebook _16c1_s_p1_0 = {
  124392. 8, 6561,
  124393. _vq_lengthlist__16c1_s_p1_0,
  124394. 1, -535822336, 1611661312, 2, 0,
  124395. _vq_quantlist__16c1_s_p1_0,
  124396. NULL,
  124397. &_vq_auxt__16c1_s_p1_0,
  124398. NULL,
  124399. 0
  124400. };
  124401. static long _vq_quantlist__16c1_s_p2_0[] = {
  124402. 2,
  124403. 1,
  124404. 3,
  124405. 0,
  124406. 4,
  124407. };
  124408. static long _vq_lengthlist__16c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124448. 0,
  124449. };
  124450. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124451. -1.5, -0.5, 0.5, 1.5,
  124452. };
  124453. static long _vq_quantmap__16c1_s_p2_0[] = {
  124454. 3, 1, 0, 2, 4,
  124455. };
  124456. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124457. _vq_quantthresh__16c1_s_p2_0,
  124458. _vq_quantmap__16c1_s_p2_0,
  124459. 5,
  124460. 5
  124461. };
  124462. static static_codebook _16c1_s_p2_0 = {
  124463. 4, 625,
  124464. _vq_lengthlist__16c1_s_p2_0,
  124465. 1, -533725184, 1611661312, 3, 0,
  124466. _vq_quantlist__16c1_s_p2_0,
  124467. NULL,
  124468. &_vq_auxt__16c1_s_p2_0,
  124469. NULL,
  124470. 0
  124471. };
  124472. static long _vq_quantlist__16c1_s_p3_0[] = {
  124473. 2,
  124474. 1,
  124475. 3,
  124476. 0,
  124477. 4,
  124478. };
  124479. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124480. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124483. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124486. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124519. 0,
  124520. };
  124521. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124522. -1.5, -0.5, 0.5, 1.5,
  124523. };
  124524. static long _vq_quantmap__16c1_s_p3_0[] = {
  124525. 3, 1, 0, 2, 4,
  124526. };
  124527. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124528. _vq_quantthresh__16c1_s_p3_0,
  124529. _vq_quantmap__16c1_s_p3_0,
  124530. 5,
  124531. 5
  124532. };
  124533. static static_codebook _16c1_s_p3_0 = {
  124534. 4, 625,
  124535. _vq_lengthlist__16c1_s_p3_0,
  124536. 1, -533725184, 1611661312, 3, 0,
  124537. _vq_quantlist__16c1_s_p3_0,
  124538. NULL,
  124539. &_vq_auxt__16c1_s_p3_0,
  124540. NULL,
  124541. 0
  124542. };
  124543. static long _vq_quantlist__16c1_s_p4_0[] = {
  124544. 4,
  124545. 3,
  124546. 5,
  124547. 2,
  124548. 6,
  124549. 1,
  124550. 7,
  124551. 0,
  124552. 8,
  124553. };
  124554. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124555. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124556. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124557. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124558. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124559. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124560. 0,
  124561. };
  124562. static float _vq_quantthresh__16c1_s_p4_0[] = {
  124563. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124564. };
  124565. static long _vq_quantmap__16c1_s_p4_0[] = {
  124566. 7, 5, 3, 1, 0, 2, 4, 6,
  124567. 8,
  124568. };
  124569. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  124570. _vq_quantthresh__16c1_s_p4_0,
  124571. _vq_quantmap__16c1_s_p4_0,
  124572. 9,
  124573. 9
  124574. };
  124575. static static_codebook _16c1_s_p4_0 = {
  124576. 2, 81,
  124577. _vq_lengthlist__16c1_s_p4_0,
  124578. 1, -531628032, 1611661312, 4, 0,
  124579. _vq_quantlist__16c1_s_p4_0,
  124580. NULL,
  124581. &_vq_auxt__16c1_s_p4_0,
  124582. NULL,
  124583. 0
  124584. };
  124585. static long _vq_quantlist__16c1_s_p5_0[] = {
  124586. 4,
  124587. 3,
  124588. 5,
  124589. 2,
  124590. 6,
  124591. 1,
  124592. 7,
  124593. 0,
  124594. 8,
  124595. };
  124596. static long _vq_lengthlist__16c1_s_p5_0[] = {
  124597. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  124598. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  124599. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  124600. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  124601. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  124602. 10,
  124603. };
  124604. static float _vq_quantthresh__16c1_s_p5_0[] = {
  124605. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  124606. };
  124607. static long _vq_quantmap__16c1_s_p5_0[] = {
  124608. 7, 5, 3, 1, 0, 2, 4, 6,
  124609. 8,
  124610. };
  124611. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  124612. _vq_quantthresh__16c1_s_p5_0,
  124613. _vq_quantmap__16c1_s_p5_0,
  124614. 9,
  124615. 9
  124616. };
  124617. static static_codebook _16c1_s_p5_0 = {
  124618. 2, 81,
  124619. _vq_lengthlist__16c1_s_p5_0,
  124620. 1, -531628032, 1611661312, 4, 0,
  124621. _vq_quantlist__16c1_s_p5_0,
  124622. NULL,
  124623. &_vq_auxt__16c1_s_p5_0,
  124624. NULL,
  124625. 0
  124626. };
  124627. static long _vq_quantlist__16c1_s_p6_0[] = {
  124628. 8,
  124629. 7,
  124630. 9,
  124631. 6,
  124632. 10,
  124633. 5,
  124634. 11,
  124635. 4,
  124636. 12,
  124637. 3,
  124638. 13,
  124639. 2,
  124640. 14,
  124641. 1,
  124642. 15,
  124643. 0,
  124644. 16,
  124645. };
  124646. static long _vq_lengthlist__16c1_s_p6_0[] = {
  124647. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  124648. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  124649. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  124650. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  124651. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  124652. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  124653. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  124654. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  124655. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  124656. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  124657. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  124658. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  124659. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  124660. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  124661. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  124662. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  124663. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  124665. 14,
  124666. };
  124667. static float _vq_quantthresh__16c1_s_p6_0[] = {
  124668. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  124669. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  124670. };
  124671. static long _vq_quantmap__16c1_s_p6_0[] = {
  124672. 15, 13, 11, 9, 7, 5, 3, 1,
  124673. 0, 2, 4, 6, 8, 10, 12, 14,
  124674. 16,
  124675. };
  124676. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  124677. _vq_quantthresh__16c1_s_p6_0,
  124678. _vq_quantmap__16c1_s_p6_0,
  124679. 17,
  124680. 17
  124681. };
  124682. static static_codebook _16c1_s_p6_0 = {
  124683. 2, 289,
  124684. _vq_lengthlist__16c1_s_p6_0,
  124685. 1, -529530880, 1611661312, 5, 0,
  124686. _vq_quantlist__16c1_s_p6_0,
  124687. NULL,
  124688. &_vq_auxt__16c1_s_p6_0,
  124689. NULL,
  124690. 0
  124691. };
  124692. static long _vq_quantlist__16c1_s_p7_0[] = {
  124693. 1,
  124694. 0,
  124695. 2,
  124696. };
  124697. static long _vq_lengthlist__16c1_s_p7_0[] = {
  124698. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  124699. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124700. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  124701. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  124702. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  124703. 11,
  124704. };
  124705. static float _vq_quantthresh__16c1_s_p7_0[] = {
  124706. -5.5, 5.5,
  124707. };
  124708. static long _vq_quantmap__16c1_s_p7_0[] = {
  124709. 1, 0, 2,
  124710. };
  124711. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  124712. _vq_quantthresh__16c1_s_p7_0,
  124713. _vq_quantmap__16c1_s_p7_0,
  124714. 3,
  124715. 3
  124716. };
  124717. static static_codebook _16c1_s_p7_0 = {
  124718. 4, 81,
  124719. _vq_lengthlist__16c1_s_p7_0,
  124720. 1, -529137664, 1618345984, 2, 0,
  124721. _vq_quantlist__16c1_s_p7_0,
  124722. NULL,
  124723. &_vq_auxt__16c1_s_p7_0,
  124724. NULL,
  124725. 0
  124726. };
  124727. static long _vq_quantlist__16c1_s_p7_1[] = {
  124728. 5,
  124729. 4,
  124730. 6,
  124731. 3,
  124732. 7,
  124733. 2,
  124734. 8,
  124735. 1,
  124736. 9,
  124737. 0,
  124738. 10,
  124739. };
  124740. static long _vq_lengthlist__16c1_s_p7_1[] = {
  124741. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  124742. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  124743. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  124744. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  124745. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  124746. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  124747. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  124748. 10,10,10, 8, 8, 8, 8, 9, 9,
  124749. };
  124750. static float _vq_quantthresh__16c1_s_p7_1[] = {
  124751. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124752. 3.5, 4.5,
  124753. };
  124754. static long _vq_quantmap__16c1_s_p7_1[] = {
  124755. 9, 7, 5, 3, 1, 0, 2, 4,
  124756. 6, 8, 10,
  124757. };
  124758. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  124759. _vq_quantthresh__16c1_s_p7_1,
  124760. _vq_quantmap__16c1_s_p7_1,
  124761. 11,
  124762. 11
  124763. };
  124764. static static_codebook _16c1_s_p7_1 = {
  124765. 2, 121,
  124766. _vq_lengthlist__16c1_s_p7_1,
  124767. 1, -531365888, 1611661312, 4, 0,
  124768. _vq_quantlist__16c1_s_p7_1,
  124769. NULL,
  124770. &_vq_auxt__16c1_s_p7_1,
  124771. NULL,
  124772. 0
  124773. };
  124774. static long _vq_quantlist__16c1_s_p8_0[] = {
  124775. 6,
  124776. 5,
  124777. 7,
  124778. 4,
  124779. 8,
  124780. 3,
  124781. 9,
  124782. 2,
  124783. 10,
  124784. 1,
  124785. 11,
  124786. 0,
  124787. 12,
  124788. };
  124789. static long _vq_lengthlist__16c1_s_p8_0[] = {
  124790. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  124791. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  124792. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  124793. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  124794. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  124795. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  124796. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  124797. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  124798. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  124799. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  124800. 0,12,12,12,12,13,13,14,15,
  124801. };
  124802. static float _vq_quantthresh__16c1_s_p8_0[] = {
  124803. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124804. 12.5, 17.5, 22.5, 27.5,
  124805. };
  124806. static long _vq_quantmap__16c1_s_p8_0[] = {
  124807. 11, 9, 7, 5, 3, 1, 0, 2,
  124808. 4, 6, 8, 10, 12,
  124809. };
  124810. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  124811. _vq_quantthresh__16c1_s_p8_0,
  124812. _vq_quantmap__16c1_s_p8_0,
  124813. 13,
  124814. 13
  124815. };
  124816. static static_codebook _16c1_s_p8_0 = {
  124817. 2, 169,
  124818. _vq_lengthlist__16c1_s_p8_0,
  124819. 1, -526516224, 1616117760, 4, 0,
  124820. _vq_quantlist__16c1_s_p8_0,
  124821. NULL,
  124822. &_vq_auxt__16c1_s_p8_0,
  124823. NULL,
  124824. 0
  124825. };
  124826. static long _vq_quantlist__16c1_s_p8_1[] = {
  124827. 2,
  124828. 1,
  124829. 3,
  124830. 0,
  124831. 4,
  124832. };
  124833. static long _vq_lengthlist__16c1_s_p8_1[] = {
  124834. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  124835. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  124836. };
  124837. static float _vq_quantthresh__16c1_s_p8_1[] = {
  124838. -1.5, -0.5, 0.5, 1.5,
  124839. };
  124840. static long _vq_quantmap__16c1_s_p8_1[] = {
  124841. 3, 1, 0, 2, 4,
  124842. };
  124843. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  124844. _vq_quantthresh__16c1_s_p8_1,
  124845. _vq_quantmap__16c1_s_p8_1,
  124846. 5,
  124847. 5
  124848. };
  124849. static static_codebook _16c1_s_p8_1 = {
  124850. 2, 25,
  124851. _vq_lengthlist__16c1_s_p8_1,
  124852. 1, -533725184, 1611661312, 3, 0,
  124853. _vq_quantlist__16c1_s_p8_1,
  124854. NULL,
  124855. &_vq_auxt__16c1_s_p8_1,
  124856. NULL,
  124857. 0
  124858. };
  124859. static long _vq_quantlist__16c1_s_p9_0[] = {
  124860. 6,
  124861. 5,
  124862. 7,
  124863. 4,
  124864. 8,
  124865. 3,
  124866. 9,
  124867. 2,
  124868. 10,
  124869. 1,
  124870. 11,
  124871. 0,
  124872. 12,
  124873. };
  124874. static long _vq_lengthlist__16c1_s_p9_0[] = {
  124875. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124876. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124877. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124878. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124879. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  124880. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124881. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124882. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124883. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124884. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124885. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124886. };
  124887. static float _vq_quantthresh__16c1_s_p9_0[] = {
  124888. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  124889. 787.5, 1102.5, 1417.5, 1732.5,
  124890. };
  124891. static long _vq_quantmap__16c1_s_p9_0[] = {
  124892. 11, 9, 7, 5, 3, 1, 0, 2,
  124893. 4, 6, 8, 10, 12,
  124894. };
  124895. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  124896. _vq_quantthresh__16c1_s_p9_0,
  124897. _vq_quantmap__16c1_s_p9_0,
  124898. 13,
  124899. 13
  124900. };
  124901. static static_codebook _16c1_s_p9_0 = {
  124902. 2, 169,
  124903. _vq_lengthlist__16c1_s_p9_0,
  124904. 1, -513964032, 1628680192, 4, 0,
  124905. _vq_quantlist__16c1_s_p9_0,
  124906. NULL,
  124907. &_vq_auxt__16c1_s_p9_0,
  124908. NULL,
  124909. 0
  124910. };
  124911. static long _vq_quantlist__16c1_s_p9_1[] = {
  124912. 7,
  124913. 6,
  124914. 8,
  124915. 5,
  124916. 9,
  124917. 4,
  124918. 10,
  124919. 3,
  124920. 11,
  124921. 2,
  124922. 12,
  124923. 1,
  124924. 13,
  124925. 0,
  124926. 14,
  124927. };
  124928. static long _vq_lengthlist__16c1_s_p9_1[] = {
  124929. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  124930. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  124931. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  124932. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  124933. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  124934. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  124935. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  124936. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124937. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124938. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  124939. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124940. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124941. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  124942. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  124943. 13,
  124944. };
  124945. static float _vq_quantthresh__16c1_s_p9_1[] = {
  124946. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124947. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124948. };
  124949. static long _vq_quantmap__16c1_s_p9_1[] = {
  124950. 13, 11, 9, 7, 5, 3, 1, 0,
  124951. 2, 4, 6, 8, 10, 12, 14,
  124952. };
  124953. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  124954. _vq_quantthresh__16c1_s_p9_1,
  124955. _vq_quantmap__16c1_s_p9_1,
  124956. 15,
  124957. 15
  124958. };
  124959. static static_codebook _16c1_s_p9_1 = {
  124960. 2, 225,
  124961. _vq_lengthlist__16c1_s_p9_1,
  124962. 1, -520986624, 1620377600, 4, 0,
  124963. _vq_quantlist__16c1_s_p9_1,
  124964. NULL,
  124965. &_vq_auxt__16c1_s_p9_1,
  124966. NULL,
  124967. 0
  124968. };
  124969. static long _vq_quantlist__16c1_s_p9_2[] = {
  124970. 10,
  124971. 9,
  124972. 11,
  124973. 8,
  124974. 12,
  124975. 7,
  124976. 13,
  124977. 6,
  124978. 14,
  124979. 5,
  124980. 15,
  124981. 4,
  124982. 16,
  124983. 3,
  124984. 17,
  124985. 2,
  124986. 18,
  124987. 1,
  124988. 19,
  124989. 0,
  124990. 20,
  124991. };
  124992. static long _vq_lengthlist__16c1_s_p9_2[] = {
  124993. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  124994. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  124995. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  124996. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  124997. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  124998. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  124999. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  125000. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  125001. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  125002. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  125003. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  125004. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  125005. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  125006. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  125007. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  125008. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  125009. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  125010. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  125011. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  125012. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  125013. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  125014. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  125015. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  125016. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  125017. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  125018. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  125019. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  125020. 11,11,11,11,12,11,11,12,11,
  125021. };
  125022. static float _vq_quantthresh__16c1_s_p9_2[] = {
  125023. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125024. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125025. 6.5, 7.5, 8.5, 9.5,
  125026. };
  125027. static long _vq_quantmap__16c1_s_p9_2[] = {
  125028. 19, 17, 15, 13, 11, 9, 7, 5,
  125029. 3, 1, 0, 2, 4, 6, 8, 10,
  125030. 12, 14, 16, 18, 20,
  125031. };
  125032. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  125033. _vq_quantthresh__16c1_s_p9_2,
  125034. _vq_quantmap__16c1_s_p9_2,
  125035. 21,
  125036. 21
  125037. };
  125038. static static_codebook _16c1_s_p9_2 = {
  125039. 2, 441,
  125040. _vq_lengthlist__16c1_s_p9_2,
  125041. 1, -529268736, 1611661312, 5, 0,
  125042. _vq_quantlist__16c1_s_p9_2,
  125043. NULL,
  125044. &_vq_auxt__16c1_s_p9_2,
  125045. NULL,
  125046. 0
  125047. };
  125048. static long _huff_lengthlist__16c1_s_short[] = {
  125049. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125050. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125051. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125052. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125053. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125054. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125055. 9, 9,10,13,
  125056. };
  125057. static static_codebook _huff_book__16c1_s_short = {
  125058. 2, 100,
  125059. _huff_lengthlist__16c1_s_short,
  125060. 0, 0, 0, 0, 0,
  125061. NULL,
  125062. NULL,
  125063. NULL,
  125064. NULL,
  125065. 0
  125066. };
  125067. static long _huff_lengthlist__16c2_s_long[] = {
  125068. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125069. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125070. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125071. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125072. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125073. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125074. 14,14,16,18,
  125075. };
  125076. static static_codebook _huff_book__16c2_s_long = {
  125077. 2, 100,
  125078. _huff_lengthlist__16c2_s_long,
  125079. 0, 0, 0, 0, 0,
  125080. NULL,
  125081. NULL,
  125082. NULL,
  125083. NULL,
  125084. 0
  125085. };
  125086. static long _vq_quantlist__16c2_s_p1_0[] = {
  125087. 1,
  125088. 0,
  125089. 2,
  125090. };
  125091. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125092. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125093. 0, 0, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125097. 0,
  125098. };
  125099. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125100. -0.5, 0.5,
  125101. };
  125102. static long _vq_quantmap__16c2_s_p1_0[] = {
  125103. 1, 0, 2,
  125104. };
  125105. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125106. _vq_quantthresh__16c2_s_p1_0,
  125107. _vq_quantmap__16c2_s_p1_0,
  125108. 3,
  125109. 3
  125110. };
  125111. static static_codebook _16c2_s_p1_0 = {
  125112. 4, 81,
  125113. _vq_lengthlist__16c2_s_p1_0,
  125114. 1, -535822336, 1611661312, 2, 0,
  125115. _vq_quantlist__16c2_s_p1_0,
  125116. NULL,
  125117. &_vq_auxt__16c2_s_p1_0,
  125118. NULL,
  125119. 0
  125120. };
  125121. static long _vq_quantlist__16c2_s_p2_0[] = {
  125122. 2,
  125123. 1,
  125124. 3,
  125125. 0,
  125126. 4,
  125127. };
  125128. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125129. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125130. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125131. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125132. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125133. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125134. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125135. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125136. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 0, 0, 0,
  125137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125141. 0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8,11,11, 0, 0, 0,
  125142. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125143. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125144. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  125145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125147. 0, 0, 0, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125150. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125151. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125152. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125157. 0, 0, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125158. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125159. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125160. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8,
  125165. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125166. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125167. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125168. 13,
  125169. };
  125170. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125171. -1.5, -0.5, 0.5, 1.5,
  125172. };
  125173. static long _vq_quantmap__16c2_s_p2_0[] = {
  125174. 3, 1, 0, 2, 4,
  125175. };
  125176. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125177. _vq_quantthresh__16c2_s_p2_0,
  125178. _vq_quantmap__16c2_s_p2_0,
  125179. 5,
  125180. 5
  125181. };
  125182. static static_codebook _16c2_s_p2_0 = {
  125183. 4, 625,
  125184. _vq_lengthlist__16c2_s_p2_0,
  125185. 1, -533725184, 1611661312, 3, 0,
  125186. _vq_quantlist__16c2_s_p2_0,
  125187. NULL,
  125188. &_vq_auxt__16c2_s_p2_0,
  125189. NULL,
  125190. 0
  125191. };
  125192. static long _vq_quantlist__16c2_s_p3_0[] = {
  125193. 4,
  125194. 3,
  125195. 5,
  125196. 2,
  125197. 6,
  125198. 1,
  125199. 7,
  125200. 0,
  125201. 8,
  125202. };
  125203. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125204. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125205. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125206. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125207. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125209. 0,
  125210. };
  125211. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125212. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125213. };
  125214. static long _vq_quantmap__16c2_s_p3_0[] = {
  125215. 7, 5, 3, 1, 0, 2, 4, 6,
  125216. 8,
  125217. };
  125218. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125219. _vq_quantthresh__16c2_s_p3_0,
  125220. _vq_quantmap__16c2_s_p3_0,
  125221. 9,
  125222. 9
  125223. };
  125224. static static_codebook _16c2_s_p3_0 = {
  125225. 2, 81,
  125226. _vq_lengthlist__16c2_s_p3_0,
  125227. 1, -531628032, 1611661312, 4, 0,
  125228. _vq_quantlist__16c2_s_p3_0,
  125229. NULL,
  125230. &_vq_auxt__16c2_s_p3_0,
  125231. NULL,
  125232. 0
  125233. };
  125234. static long _vq_quantlist__16c2_s_p4_0[] = {
  125235. 8,
  125236. 7,
  125237. 9,
  125238. 6,
  125239. 10,
  125240. 5,
  125241. 11,
  125242. 4,
  125243. 12,
  125244. 3,
  125245. 13,
  125246. 2,
  125247. 14,
  125248. 1,
  125249. 15,
  125250. 0,
  125251. 16,
  125252. };
  125253. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125254. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125255. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125256. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125257. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125258. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125259. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125260. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125261. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125262. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125263. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  125264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125272. 0,
  125273. };
  125274. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125275. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125276. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125277. };
  125278. static long _vq_quantmap__16c2_s_p4_0[] = {
  125279. 15, 13, 11, 9, 7, 5, 3, 1,
  125280. 0, 2, 4, 6, 8, 10, 12, 14,
  125281. 16,
  125282. };
  125283. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125284. _vq_quantthresh__16c2_s_p4_0,
  125285. _vq_quantmap__16c2_s_p4_0,
  125286. 17,
  125287. 17
  125288. };
  125289. static static_codebook _16c2_s_p4_0 = {
  125290. 2, 289,
  125291. _vq_lengthlist__16c2_s_p4_0,
  125292. 1, -529530880, 1611661312, 5, 0,
  125293. _vq_quantlist__16c2_s_p4_0,
  125294. NULL,
  125295. &_vq_auxt__16c2_s_p4_0,
  125296. NULL,
  125297. 0
  125298. };
  125299. static long _vq_quantlist__16c2_s_p5_0[] = {
  125300. 1,
  125301. 0,
  125302. 2,
  125303. };
  125304. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125305. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125306. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125307. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125308. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125309. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125310. 12,
  125311. };
  125312. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125313. -5.5, 5.5,
  125314. };
  125315. static long _vq_quantmap__16c2_s_p5_0[] = {
  125316. 1, 0, 2,
  125317. };
  125318. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125319. _vq_quantthresh__16c2_s_p5_0,
  125320. _vq_quantmap__16c2_s_p5_0,
  125321. 3,
  125322. 3
  125323. };
  125324. static static_codebook _16c2_s_p5_0 = {
  125325. 4, 81,
  125326. _vq_lengthlist__16c2_s_p5_0,
  125327. 1, -529137664, 1618345984, 2, 0,
  125328. _vq_quantlist__16c2_s_p5_0,
  125329. NULL,
  125330. &_vq_auxt__16c2_s_p5_0,
  125331. NULL,
  125332. 0
  125333. };
  125334. static long _vq_quantlist__16c2_s_p5_1[] = {
  125335. 5,
  125336. 4,
  125337. 6,
  125338. 3,
  125339. 7,
  125340. 2,
  125341. 8,
  125342. 1,
  125343. 9,
  125344. 0,
  125345. 10,
  125346. };
  125347. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125348. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125349. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125350. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125351. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125352. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125353. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125354. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125355. 11,11,11, 7, 7, 8, 8, 8, 8,
  125356. };
  125357. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125358. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125359. 3.5, 4.5,
  125360. };
  125361. static long _vq_quantmap__16c2_s_p5_1[] = {
  125362. 9, 7, 5, 3, 1, 0, 2, 4,
  125363. 6, 8, 10,
  125364. };
  125365. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125366. _vq_quantthresh__16c2_s_p5_1,
  125367. _vq_quantmap__16c2_s_p5_1,
  125368. 11,
  125369. 11
  125370. };
  125371. static static_codebook _16c2_s_p5_1 = {
  125372. 2, 121,
  125373. _vq_lengthlist__16c2_s_p5_1,
  125374. 1, -531365888, 1611661312, 4, 0,
  125375. _vq_quantlist__16c2_s_p5_1,
  125376. NULL,
  125377. &_vq_auxt__16c2_s_p5_1,
  125378. NULL,
  125379. 0
  125380. };
  125381. static long _vq_quantlist__16c2_s_p6_0[] = {
  125382. 6,
  125383. 5,
  125384. 7,
  125385. 4,
  125386. 8,
  125387. 3,
  125388. 9,
  125389. 2,
  125390. 10,
  125391. 1,
  125392. 11,
  125393. 0,
  125394. 12,
  125395. };
  125396. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125397. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125398. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125399. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125400. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125401. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125402. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125407. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125408. };
  125409. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125410. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125411. 12.5, 17.5, 22.5, 27.5,
  125412. };
  125413. static long _vq_quantmap__16c2_s_p6_0[] = {
  125414. 11, 9, 7, 5, 3, 1, 0, 2,
  125415. 4, 6, 8, 10, 12,
  125416. };
  125417. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125418. _vq_quantthresh__16c2_s_p6_0,
  125419. _vq_quantmap__16c2_s_p6_0,
  125420. 13,
  125421. 13
  125422. };
  125423. static static_codebook _16c2_s_p6_0 = {
  125424. 2, 169,
  125425. _vq_lengthlist__16c2_s_p6_0,
  125426. 1, -526516224, 1616117760, 4, 0,
  125427. _vq_quantlist__16c2_s_p6_0,
  125428. NULL,
  125429. &_vq_auxt__16c2_s_p6_0,
  125430. NULL,
  125431. 0
  125432. };
  125433. static long _vq_quantlist__16c2_s_p6_1[] = {
  125434. 2,
  125435. 1,
  125436. 3,
  125437. 0,
  125438. 4,
  125439. };
  125440. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125441. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125442. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125443. };
  125444. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125445. -1.5, -0.5, 0.5, 1.5,
  125446. };
  125447. static long _vq_quantmap__16c2_s_p6_1[] = {
  125448. 3, 1, 0, 2, 4,
  125449. };
  125450. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125451. _vq_quantthresh__16c2_s_p6_1,
  125452. _vq_quantmap__16c2_s_p6_1,
  125453. 5,
  125454. 5
  125455. };
  125456. static static_codebook _16c2_s_p6_1 = {
  125457. 2, 25,
  125458. _vq_lengthlist__16c2_s_p6_1,
  125459. 1, -533725184, 1611661312, 3, 0,
  125460. _vq_quantlist__16c2_s_p6_1,
  125461. NULL,
  125462. &_vq_auxt__16c2_s_p6_1,
  125463. NULL,
  125464. 0
  125465. };
  125466. static long _vq_quantlist__16c2_s_p7_0[] = {
  125467. 6,
  125468. 5,
  125469. 7,
  125470. 4,
  125471. 8,
  125472. 3,
  125473. 9,
  125474. 2,
  125475. 10,
  125476. 1,
  125477. 11,
  125478. 0,
  125479. 12,
  125480. };
  125481. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125482. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125483. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125484. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125485. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125486. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125487. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125488. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125489. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125490. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125491. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125492. 18,13,14,13,13,14,13,15,14,
  125493. };
  125494. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125495. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125496. 27.5, 38.5, 49.5, 60.5,
  125497. };
  125498. static long _vq_quantmap__16c2_s_p7_0[] = {
  125499. 11, 9, 7, 5, 3, 1, 0, 2,
  125500. 4, 6, 8, 10, 12,
  125501. };
  125502. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125503. _vq_quantthresh__16c2_s_p7_0,
  125504. _vq_quantmap__16c2_s_p7_0,
  125505. 13,
  125506. 13
  125507. };
  125508. static static_codebook _16c2_s_p7_0 = {
  125509. 2, 169,
  125510. _vq_lengthlist__16c2_s_p7_0,
  125511. 1, -523206656, 1618345984, 4, 0,
  125512. _vq_quantlist__16c2_s_p7_0,
  125513. NULL,
  125514. &_vq_auxt__16c2_s_p7_0,
  125515. NULL,
  125516. 0
  125517. };
  125518. static long _vq_quantlist__16c2_s_p7_1[] = {
  125519. 5,
  125520. 4,
  125521. 6,
  125522. 3,
  125523. 7,
  125524. 2,
  125525. 8,
  125526. 1,
  125527. 9,
  125528. 0,
  125529. 10,
  125530. };
  125531. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125532. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125533. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125534. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125535. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125536. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125537. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125538. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125539. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125540. };
  125541. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125542. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125543. 3.5, 4.5,
  125544. };
  125545. static long _vq_quantmap__16c2_s_p7_1[] = {
  125546. 9, 7, 5, 3, 1, 0, 2, 4,
  125547. 6, 8, 10,
  125548. };
  125549. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125550. _vq_quantthresh__16c2_s_p7_1,
  125551. _vq_quantmap__16c2_s_p7_1,
  125552. 11,
  125553. 11
  125554. };
  125555. static static_codebook _16c2_s_p7_1 = {
  125556. 2, 121,
  125557. _vq_lengthlist__16c2_s_p7_1,
  125558. 1, -531365888, 1611661312, 4, 0,
  125559. _vq_quantlist__16c2_s_p7_1,
  125560. NULL,
  125561. &_vq_auxt__16c2_s_p7_1,
  125562. NULL,
  125563. 0
  125564. };
  125565. static long _vq_quantlist__16c2_s_p8_0[] = {
  125566. 7,
  125567. 6,
  125568. 8,
  125569. 5,
  125570. 9,
  125571. 4,
  125572. 10,
  125573. 3,
  125574. 11,
  125575. 2,
  125576. 12,
  125577. 1,
  125578. 13,
  125579. 0,
  125580. 14,
  125581. };
  125582. static long _vq_lengthlist__16c2_s_p8_0[] = {
  125583. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  125584. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  125585. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  125586. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  125587. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  125588. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  125589. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  125590. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  125591. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  125592. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  125593. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  125594. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  125595. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  125596. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  125597. 13,
  125598. };
  125599. static float _vq_quantthresh__16c2_s_p8_0[] = {
  125600. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125601. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125602. };
  125603. static long _vq_quantmap__16c2_s_p8_0[] = {
  125604. 13, 11, 9, 7, 5, 3, 1, 0,
  125605. 2, 4, 6, 8, 10, 12, 14,
  125606. };
  125607. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  125608. _vq_quantthresh__16c2_s_p8_0,
  125609. _vq_quantmap__16c2_s_p8_0,
  125610. 15,
  125611. 15
  125612. };
  125613. static static_codebook _16c2_s_p8_0 = {
  125614. 2, 225,
  125615. _vq_lengthlist__16c2_s_p8_0,
  125616. 1, -520986624, 1620377600, 4, 0,
  125617. _vq_quantlist__16c2_s_p8_0,
  125618. NULL,
  125619. &_vq_auxt__16c2_s_p8_0,
  125620. NULL,
  125621. 0
  125622. };
  125623. static long _vq_quantlist__16c2_s_p8_1[] = {
  125624. 10,
  125625. 9,
  125626. 11,
  125627. 8,
  125628. 12,
  125629. 7,
  125630. 13,
  125631. 6,
  125632. 14,
  125633. 5,
  125634. 15,
  125635. 4,
  125636. 16,
  125637. 3,
  125638. 17,
  125639. 2,
  125640. 18,
  125641. 1,
  125642. 19,
  125643. 0,
  125644. 20,
  125645. };
  125646. static long _vq_lengthlist__16c2_s_p8_1[] = {
  125647. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  125648. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  125649. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  125650. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  125651. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  125652. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  125653. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  125654. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  125655. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  125656. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  125657. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  125658. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  125659. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  125660. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  125661. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  125662. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  125663. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  125664. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  125665. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  125666. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  125667. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  125668. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  125669. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  125670. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  125671. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  125672. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  125673. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  125674. 10,11,10,10,10,10,10,10,10,
  125675. };
  125676. static float _vq_quantthresh__16c2_s_p8_1[] = {
  125677. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125678. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125679. 6.5, 7.5, 8.5, 9.5,
  125680. };
  125681. static long _vq_quantmap__16c2_s_p8_1[] = {
  125682. 19, 17, 15, 13, 11, 9, 7, 5,
  125683. 3, 1, 0, 2, 4, 6, 8, 10,
  125684. 12, 14, 16, 18, 20,
  125685. };
  125686. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  125687. _vq_quantthresh__16c2_s_p8_1,
  125688. _vq_quantmap__16c2_s_p8_1,
  125689. 21,
  125690. 21
  125691. };
  125692. static static_codebook _16c2_s_p8_1 = {
  125693. 2, 441,
  125694. _vq_lengthlist__16c2_s_p8_1,
  125695. 1, -529268736, 1611661312, 5, 0,
  125696. _vq_quantlist__16c2_s_p8_1,
  125697. NULL,
  125698. &_vq_auxt__16c2_s_p8_1,
  125699. NULL,
  125700. 0
  125701. };
  125702. static long _vq_quantlist__16c2_s_p9_0[] = {
  125703. 6,
  125704. 5,
  125705. 7,
  125706. 4,
  125707. 8,
  125708. 3,
  125709. 9,
  125710. 2,
  125711. 10,
  125712. 1,
  125713. 11,
  125714. 0,
  125715. 12,
  125716. };
  125717. static long _vq_lengthlist__16c2_s_p9_0[] = {
  125718. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125719. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125720. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125721. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125722. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125723. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125724. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125725. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125726. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125727. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125728. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125729. };
  125730. static float _vq_quantthresh__16c2_s_p9_0[] = {
  125731. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  125732. 2327.5, 3258.5, 4189.5, 5120.5,
  125733. };
  125734. static long _vq_quantmap__16c2_s_p9_0[] = {
  125735. 11, 9, 7, 5, 3, 1, 0, 2,
  125736. 4, 6, 8, 10, 12,
  125737. };
  125738. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  125739. _vq_quantthresh__16c2_s_p9_0,
  125740. _vq_quantmap__16c2_s_p9_0,
  125741. 13,
  125742. 13
  125743. };
  125744. static static_codebook _16c2_s_p9_0 = {
  125745. 2, 169,
  125746. _vq_lengthlist__16c2_s_p9_0,
  125747. 1, -510275072, 1631393792, 4, 0,
  125748. _vq_quantlist__16c2_s_p9_0,
  125749. NULL,
  125750. &_vq_auxt__16c2_s_p9_0,
  125751. NULL,
  125752. 0
  125753. };
  125754. static long _vq_quantlist__16c2_s_p9_1[] = {
  125755. 8,
  125756. 7,
  125757. 9,
  125758. 6,
  125759. 10,
  125760. 5,
  125761. 11,
  125762. 4,
  125763. 12,
  125764. 3,
  125765. 13,
  125766. 2,
  125767. 14,
  125768. 1,
  125769. 15,
  125770. 0,
  125771. 16,
  125772. };
  125773. static long _vq_lengthlist__16c2_s_p9_1[] = {
  125774. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  125775. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  125776. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  125777. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  125778. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  125779. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  125780. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  125781. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  125782. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  125783. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  125784. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125785. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125786. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125787. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125788. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125789. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  125790. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  125791. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  125792. 10,
  125793. };
  125794. static float _vq_quantthresh__16c2_s_p9_1[] = {
  125795. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  125796. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  125797. };
  125798. static long _vq_quantmap__16c2_s_p9_1[] = {
  125799. 15, 13, 11, 9, 7, 5, 3, 1,
  125800. 0, 2, 4, 6, 8, 10, 12, 14,
  125801. 16,
  125802. };
  125803. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  125804. _vq_quantthresh__16c2_s_p9_1,
  125805. _vq_quantmap__16c2_s_p9_1,
  125806. 17,
  125807. 17
  125808. };
  125809. static static_codebook _16c2_s_p9_1 = {
  125810. 2, 289,
  125811. _vq_lengthlist__16c2_s_p9_1,
  125812. 1, -518488064, 1622704128, 5, 0,
  125813. _vq_quantlist__16c2_s_p9_1,
  125814. NULL,
  125815. &_vq_auxt__16c2_s_p9_1,
  125816. NULL,
  125817. 0
  125818. };
  125819. static long _vq_quantlist__16c2_s_p9_2[] = {
  125820. 13,
  125821. 12,
  125822. 14,
  125823. 11,
  125824. 15,
  125825. 10,
  125826. 16,
  125827. 9,
  125828. 17,
  125829. 8,
  125830. 18,
  125831. 7,
  125832. 19,
  125833. 6,
  125834. 20,
  125835. 5,
  125836. 21,
  125837. 4,
  125838. 22,
  125839. 3,
  125840. 23,
  125841. 2,
  125842. 24,
  125843. 1,
  125844. 25,
  125845. 0,
  125846. 26,
  125847. };
  125848. static long _vq_lengthlist__16c2_s_p9_2[] = {
  125849. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  125850. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  125851. };
  125852. static float _vq_quantthresh__16c2_s_p9_2[] = {
  125853. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  125854. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125855. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  125856. 11.5, 12.5,
  125857. };
  125858. static long _vq_quantmap__16c2_s_p9_2[] = {
  125859. 25, 23, 21, 19, 17, 15, 13, 11,
  125860. 9, 7, 5, 3, 1, 0, 2, 4,
  125861. 6, 8, 10, 12, 14, 16, 18, 20,
  125862. 22, 24, 26,
  125863. };
  125864. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  125865. _vq_quantthresh__16c2_s_p9_2,
  125866. _vq_quantmap__16c2_s_p9_2,
  125867. 27,
  125868. 27
  125869. };
  125870. static static_codebook _16c2_s_p9_2 = {
  125871. 1, 27,
  125872. _vq_lengthlist__16c2_s_p9_2,
  125873. 1, -528875520, 1611661312, 5, 0,
  125874. _vq_quantlist__16c2_s_p9_2,
  125875. NULL,
  125876. &_vq_auxt__16c2_s_p9_2,
  125877. NULL,
  125878. 0
  125879. };
  125880. static long _huff_lengthlist__16c2_s_short[] = {
  125881. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  125882. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  125883. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  125884. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  125885. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  125886. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  125887. 15,12,14,14,
  125888. };
  125889. static static_codebook _huff_book__16c2_s_short = {
  125890. 2, 100,
  125891. _huff_lengthlist__16c2_s_short,
  125892. 0, 0, 0, 0, 0,
  125893. NULL,
  125894. NULL,
  125895. NULL,
  125896. NULL,
  125897. 0
  125898. };
  125899. static long _vq_quantlist__8c0_s_p1_0[] = {
  125900. 1,
  125901. 0,
  125902. 2,
  125903. };
  125904. static long _vq_lengthlist__8c0_s_p1_0[] = {
  125905. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  125906. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  125911. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  125916. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  125951. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  125956. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 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, 7, 9,10, 0, 0,
  125961. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  125962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125996. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  125997. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  126002. 0, 0, 0, 0, 0, 9,10,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  126007. 0, 0, 0, 0, 0, 0, 8,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126315. 0,
  126316. };
  126317. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126318. -0.5, 0.5,
  126319. };
  126320. static long _vq_quantmap__8c0_s_p1_0[] = {
  126321. 1, 0, 2,
  126322. };
  126323. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126324. _vq_quantthresh__8c0_s_p1_0,
  126325. _vq_quantmap__8c0_s_p1_0,
  126326. 3,
  126327. 3
  126328. };
  126329. static static_codebook _8c0_s_p1_0 = {
  126330. 8, 6561,
  126331. _vq_lengthlist__8c0_s_p1_0,
  126332. 1, -535822336, 1611661312, 2, 0,
  126333. _vq_quantlist__8c0_s_p1_0,
  126334. NULL,
  126335. &_vq_auxt__8c0_s_p1_0,
  126336. NULL,
  126337. 0
  126338. };
  126339. static long _vq_quantlist__8c0_s_p2_0[] = {
  126340. 2,
  126341. 1,
  126342. 3,
  126343. 0,
  126344. 4,
  126345. };
  126346. static long _vq_lengthlist__8c0_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0,
  126387. };
  126388. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126389. -1.5, -0.5, 0.5, 1.5,
  126390. };
  126391. static long _vq_quantmap__8c0_s_p2_0[] = {
  126392. 3, 1, 0, 2, 4,
  126393. };
  126394. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126395. _vq_quantthresh__8c0_s_p2_0,
  126396. _vq_quantmap__8c0_s_p2_0,
  126397. 5,
  126398. 5
  126399. };
  126400. static static_codebook _8c0_s_p2_0 = {
  126401. 4, 625,
  126402. _vq_lengthlist__8c0_s_p2_0,
  126403. 1, -533725184, 1611661312, 3, 0,
  126404. _vq_quantlist__8c0_s_p2_0,
  126405. NULL,
  126406. &_vq_auxt__8c0_s_p2_0,
  126407. NULL,
  126408. 0
  126409. };
  126410. static long _vq_quantlist__8c0_s_p3_0[] = {
  126411. 2,
  126412. 1,
  126413. 3,
  126414. 0,
  126415. 4,
  126416. };
  126417. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126418. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 6, 7, 7, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0,
  126458. };
  126459. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126460. -1.5, -0.5, 0.5, 1.5,
  126461. };
  126462. static long _vq_quantmap__8c0_s_p3_0[] = {
  126463. 3, 1, 0, 2, 4,
  126464. };
  126465. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126466. _vq_quantthresh__8c0_s_p3_0,
  126467. _vq_quantmap__8c0_s_p3_0,
  126468. 5,
  126469. 5
  126470. };
  126471. static static_codebook _8c0_s_p3_0 = {
  126472. 4, 625,
  126473. _vq_lengthlist__8c0_s_p3_0,
  126474. 1, -533725184, 1611661312, 3, 0,
  126475. _vq_quantlist__8c0_s_p3_0,
  126476. NULL,
  126477. &_vq_auxt__8c0_s_p3_0,
  126478. NULL,
  126479. 0
  126480. };
  126481. static long _vq_quantlist__8c0_s_p4_0[] = {
  126482. 4,
  126483. 3,
  126484. 5,
  126485. 2,
  126486. 6,
  126487. 1,
  126488. 7,
  126489. 0,
  126490. 8,
  126491. };
  126492. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126493. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126494. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126495. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126496. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126497. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0,
  126499. };
  126500. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126501. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126502. };
  126503. static long _vq_quantmap__8c0_s_p4_0[] = {
  126504. 7, 5, 3, 1, 0, 2, 4, 6,
  126505. 8,
  126506. };
  126507. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126508. _vq_quantthresh__8c0_s_p4_0,
  126509. _vq_quantmap__8c0_s_p4_0,
  126510. 9,
  126511. 9
  126512. };
  126513. static static_codebook _8c0_s_p4_0 = {
  126514. 2, 81,
  126515. _vq_lengthlist__8c0_s_p4_0,
  126516. 1, -531628032, 1611661312, 4, 0,
  126517. _vq_quantlist__8c0_s_p4_0,
  126518. NULL,
  126519. &_vq_auxt__8c0_s_p4_0,
  126520. NULL,
  126521. 0
  126522. };
  126523. static long _vq_quantlist__8c0_s_p5_0[] = {
  126524. 4,
  126525. 3,
  126526. 5,
  126527. 2,
  126528. 6,
  126529. 1,
  126530. 7,
  126531. 0,
  126532. 8,
  126533. };
  126534. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126535. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126536. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126537. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126538. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126539. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126540. 10,
  126541. };
  126542. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126543. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126544. };
  126545. static long _vq_quantmap__8c0_s_p5_0[] = {
  126546. 7, 5, 3, 1, 0, 2, 4, 6,
  126547. 8,
  126548. };
  126549. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126550. _vq_quantthresh__8c0_s_p5_0,
  126551. _vq_quantmap__8c0_s_p5_0,
  126552. 9,
  126553. 9
  126554. };
  126555. static static_codebook _8c0_s_p5_0 = {
  126556. 2, 81,
  126557. _vq_lengthlist__8c0_s_p5_0,
  126558. 1, -531628032, 1611661312, 4, 0,
  126559. _vq_quantlist__8c0_s_p5_0,
  126560. NULL,
  126561. &_vq_auxt__8c0_s_p5_0,
  126562. NULL,
  126563. 0
  126564. };
  126565. static long _vq_quantlist__8c0_s_p6_0[] = {
  126566. 8,
  126567. 7,
  126568. 9,
  126569. 6,
  126570. 10,
  126571. 5,
  126572. 11,
  126573. 4,
  126574. 12,
  126575. 3,
  126576. 13,
  126577. 2,
  126578. 14,
  126579. 1,
  126580. 15,
  126581. 0,
  126582. 16,
  126583. };
  126584. static long _vq_lengthlist__8c0_s_p6_0[] = {
  126585. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  126586. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  126587. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  126588. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  126589. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  126590. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  126591. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  126592. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  126593. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  126594. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  126595. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  126596. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  126597. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  126598. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  126599. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  126600. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  126601. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  126603. 14,
  126604. };
  126605. static float _vq_quantthresh__8c0_s_p6_0[] = {
  126606. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  126607. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  126608. };
  126609. static long _vq_quantmap__8c0_s_p6_0[] = {
  126610. 15, 13, 11, 9, 7, 5, 3, 1,
  126611. 0, 2, 4, 6, 8, 10, 12, 14,
  126612. 16,
  126613. };
  126614. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  126615. _vq_quantthresh__8c0_s_p6_0,
  126616. _vq_quantmap__8c0_s_p6_0,
  126617. 17,
  126618. 17
  126619. };
  126620. static static_codebook _8c0_s_p6_0 = {
  126621. 2, 289,
  126622. _vq_lengthlist__8c0_s_p6_0,
  126623. 1, -529530880, 1611661312, 5, 0,
  126624. _vq_quantlist__8c0_s_p6_0,
  126625. NULL,
  126626. &_vq_auxt__8c0_s_p6_0,
  126627. NULL,
  126628. 0
  126629. };
  126630. static long _vq_quantlist__8c0_s_p7_0[] = {
  126631. 1,
  126632. 0,
  126633. 2,
  126634. };
  126635. static long _vq_lengthlist__8c0_s_p7_0[] = {
  126636. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  126637. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  126638. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  126639. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  126640. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  126641. 10,
  126642. };
  126643. static float _vq_quantthresh__8c0_s_p7_0[] = {
  126644. -5.5, 5.5,
  126645. };
  126646. static long _vq_quantmap__8c0_s_p7_0[] = {
  126647. 1, 0, 2,
  126648. };
  126649. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  126650. _vq_quantthresh__8c0_s_p7_0,
  126651. _vq_quantmap__8c0_s_p7_0,
  126652. 3,
  126653. 3
  126654. };
  126655. static static_codebook _8c0_s_p7_0 = {
  126656. 4, 81,
  126657. _vq_lengthlist__8c0_s_p7_0,
  126658. 1, -529137664, 1618345984, 2, 0,
  126659. _vq_quantlist__8c0_s_p7_0,
  126660. NULL,
  126661. &_vq_auxt__8c0_s_p7_0,
  126662. NULL,
  126663. 0
  126664. };
  126665. static long _vq_quantlist__8c0_s_p7_1[] = {
  126666. 5,
  126667. 4,
  126668. 6,
  126669. 3,
  126670. 7,
  126671. 2,
  126672. 8,
  126673. 1,
  126674. 9,
  126675. 0,
  126676. 10,
  126677. };
  126678. static long _vq_lengthlist__8c0_s_p7_1[] = {
  126679. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  126680. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  126681. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  126682. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  126683. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  126684. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  126685. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  126686. 10,10,10, 9, 9, 9,10,10,10,
  126687. };
  126688. static float _vq_quantthresh__8c0_s_p7_1[] = {
  126689. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126690. 3.5, 4.5,
  126691. };
  126692. static long _vq_quantmap__8c0_s_p7_1[] = {
  126693. 9, 7, 5, 3, 1, 0, 2, 4,
  126694. 6, 8, 10,
  126695. };
  126696. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  126697. _vq_quantthresh__8c0_s_p7_1,
  126698. _vq_quantmap__8c0_s_p7_1,
  126699. 11,
  126700. 11
  126701. };
  126702. static static_codebook _8c0_s_p7_1 = {
  126703. 2, 121,
  126704. _vq_lengthlist__8c0_s_p7_1,
  126705. 1, -531365888, 1611661312, 4, 0,
  126706. _vq_quantlist__8c0_s_p7_1,
  126707. NULL,
  126708. &_vq_auxt__8c0_s_p7_1,
  126709. NULL,
  126710. 0
  126711. };
  126712. static long _vq_quantlist__8c0_s_p8_0[] = {
  126713. 6,
  126714. 5,
  126715. 7,
  126716. 4,
  126717. 8,
  126718. 3,
  126719. 9,
  126720. 2,
  126721. 10,
  126722. 1,
  126723. 11,
  126724. 0,
  126725. 12,
  126726. };
  126727. static long _vq_lengthlist__8c0_s_p8_0[] = {
  126728. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  126729. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  126730. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  126731. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  126732. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  126733. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  126734. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  126735. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  126736. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  126737. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  126738. 0, 0,13,13,11,13,13,11,12,
  126739. };
  126740. static float _vq_quantthresh__8c0_s_p8_0[] = {
  126741. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  126742. 12.5, 17.5, 22.5, 27.5,
  126743. };
  126744. static long _vq_quantmap__8c0_s_p8_0[] = {
  126745. 11, 9, 7, 5, 3, 1, 0, 2,
  126746. 4, 6, 8, 10, 12,
  126747. };
  126748. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  126749. _vq_quantthresh__8c0_s_p8_0,
  126750. _vq_quantmap__8c0_s_p8_0,
  126751. 13,
  126752. 13
  126753. };
  126754. static static_codebook _8c0_s_p8_0 = {
  126755. 2, 169,
  126756. _vq_lengthlist__8c0_s_p8_0,
  126757. 1, -526516224, 1616117760, 4, 0,
  126758. _vq_quantlist__8c0_s_p8_0,
  126759. NULL,
  126760. &_vq_auxt__8c0_s_p8_0,
  126761. NULL,
  126762. 0
  126763. };
  126764. static long _vq_quantlist__8c0_s_p8_1[] = {
  126765. 2,
  126766. 1,
  126767. 3,
  126768. 0,
  126769. 4,
  126770. };
  126771. static long _vq_lengthlist__8c0_s_p8_1[] = {
  126772. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  126773. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  126774. };
  126775. static float _vq_quantthresh__8c0_s_p8_1[] = {
  126776. -1.5, -0.5, 0.5, 1.5,
  126777. };
  126778. static long _vq_quantmap__8c0_s_p8_1[] = {
  126779. 3, 1, 0, 2, 4,
  126780. };
  126781. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  126782. _vq_quantthresh__8c0_s_p8_1,
  126783. _vq_quantmap__8c0_s_p8_1,
  126784. 5,
  126785. 5
  126786. };
  126787. static static_codebook _8c0_s_p8_1 = {
  126788. 2, 25,
  126789. _vq_lengthlist__8c0_s_p8_1,
  126790. 1, -533725184, 1611661312, 3, 0,
  126791. _vq_quantlist__8c0_s_p8_1,
  126792. NULL,
  126793. &_vq_auxt__8c0_s_p8_1,
  126794. NULL,
  126795. 0
  126796. };
  126797. static long _vq_quantlist__8c0_s_p9_0[] = {
  126798. 1,
  126799. 0,
  126800. 2,
  126801. };
  126802. static long _vq_lengthlist__8c0_s_p9_0[] = {
  126803. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126804. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126805. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126806. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126807. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  126808. 7,
  126809. };
  126810. static float _vq_quantthresh__8c0_s_p9_0[] = {
  126811. -157.5, 157.5,
  126812. };
  126813. static long _vq_quantmap__8c0_s_p9_0[] = {
  126814. 1, 0, 2,
  126815. };
  126816. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  126817. _vq_quantthresh__8c0_s_p9_0,
  126818. _vq_quantmap__8c0_s_p9_0,
  126819. 3,
  126820. 3
  126821. };
  126822. static static_codebook _8c0_s_p9_0 = {
  126823. 4, 81,
  126824. _vq_lengthlist__8c0_s_p9_0,
  126825. 1, -518803456, 1628680192, 2, 0,
  126826. _vq_quantlist__8c0_s_p9_0,
  126827. NULL,
  126828. &_vq_auxt__8c0_s_p9_0,
  126829. NULL,
  126830. 0
  126831. };
  126832. static long _vq_quantlist__8c0_s_p9_1[] = {
  126833. 7,
  126834. 6,
  126835. 8,
  126836. 5,
  126837. 9,
  126838. 4,
  126839. 10,
  126840. 3,
  126841. 11,
  126842. 2,
  126843. 12,
  126844. 1,
  126845. 13,
  126846. 0,
  126847. 14,
  126848. };
  126849. static long _vq_lengthlist__8c0_s_p9_1[] = {
  126850. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  126851. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  126852. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  126853. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  126854. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126855. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  126856. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126857. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126858. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126859. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126860. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126861. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126862. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126863. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  126864. 11,
  126865. };
  126866. static float _vq_quantthresh__8c0_s_p9_1[] = {
  126867. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126868. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126869. };
  126870. static long _vq_quantmap__8c0_s_p9_1[] = {
  126871. 13, 11, 9, 7, 5, 3, 1, 0,
  126872. 2, 4, 6, 8, 10, 12, 14,
  126873. };
  126874. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  126875. _vq_quantthresh__8c0_s_p9_1,
  126876. _vq_quantmap__8c0_s_p9_1,
  126877. 15,
  126878. 15
  126879. };
  126880. static static_codebook _8c0_s_p9_1 = {
  126881. 2, 225,
  126882. _vq_lengthlist__8c0_s_p9_1,
  126883. 1, -520986624, 1620377600, 4, 0,
  126884. _vq_quantlist__8c0_s_p9_1,
  126885. NULL,
  126886. &_vq_auxt__8c0_s_p9_1,
  126887. NULL,
  126888. 0
  126889. };
  126890. static long _vq_quantlist__8c0_s_p9_2[] = {
  126891. 10,
  126892. 9,
  126893. 11,
  126894. 8,
  126895. 12,
  126896. 7,
  126897. 13,
  126898. 6,
  126899. 14,
  126900. 5,
  126901. 15,
  126902. 4,
  126903. 16,
  126904. 3,
  126905. 17,
  126906. 2,
  126907. 18,
  126908. 1,
  126909. 19,
  126910. 0,
  126911. 20,
  126912. };
  126913. static long _vq_lengthlist__8c0_s_p9_2[] = {
  126914. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  126915. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  126916. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  126917. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  126918. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  126919. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  126920. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  126921. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  126922. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  126923. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  126924. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  126925. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  126926. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  126927. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  126928. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  126929. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  126930. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  126931. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  126932. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  126933. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  126934. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  126935. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  126936. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  126937. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  126938. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  126939. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  126940. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  126941. 10,11, 9,11,10, 9,10, 9,10,
  126942. };
  126943. static float _vq_quantthresh__8c0_s_p9_2[] = {
  126944. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126945. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126946. 6.5, 7.5, 8.5, 9.5,
  126947. };
  126948. static long _vq_quantmap__8c0_s_p9_2[] = {
  126949. 19, 17, 15, 13, 11, 9, 7, 5,
  126950. 3, 1, 0, 2, 4, 6, 8, 10,
  126951. 12, 14, 16, 18, 20,
  126952. };
  126953. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  126954. _vq_quantthresh__8c0_s_p9_2,
  126955. _vq_quantmap__8c0_s_p9_2,
  126956. 21,
  126957. 21
  126958. };
  126959. static static_codebook _8c0_s_p9_2 = {
  126960. 2, 441,
  126961. _vq_lengthlist__8c0_s_p9_2,
  126962. 1, -529268736, 1611661312, 5, 0,
  126963. _vq_quantlist__8c0_s_p9_2,
  126964. NULL,
  126965. &_vq_auxt__8c0_s_p9_2,
  126966. NULL,
  126967. 0
  126968. };
  126969. static long _huff_lengthlist__8c0_s_single[] = {
  126970. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  126971. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  126972. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  126973. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  126974. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  126975. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  126976. 17,16,17,17,
  126977. };
  126978. static static_codebook _huff_book__8c0_s_single = {
  126979. 2, 100,
  126980. _huff_lengthlist__8c0_s_single,
  126981. 0, 0, 0, 0, 0,
  126982. NULL,
  126983. NULL,
  126984. NULL,
  126985. NULL,
  126986. 0
  126987. };
  126988. static long _vq_quantlist__8c1_s_p1_0[] = {
  126989. 1,
  126990. 0,
  126991. 2,
  126992. };
  126993. static long _vq_lengthlist__8c1_s_p1_0[] = {
  126994. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126995. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  127000. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  127005. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  127040. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  127045. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  127050. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127085. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127086. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127091. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127096. 0, 0, 0, 0, 0, 0, 8,10, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127404. 0,
  127405. };
  127406. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127407. -0.5, 0.5,
  127408. };
  127409. static long _vq_quantmap__8c1_s_p1_0[] = {
  127410. 1, 0, 2,
  127411. };
  127412. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127413. _vq_quantthresh__8c1_s_p1_0,
  127414. _vq_quantmap__8c1_s_p1_0,
  127415. 3,
  127416. 3
  127417. };
  127418. static static_codebook _8c1_s_p1_0 = {
  127419. 8, 6561,
  127420. _vq_lengthlist__8c1_s_p1_0,
  127421. 1, -535822336, 1611661312, 2, 0,
  127422. _vq_quantlist__8c1_s_p1_0,
  127423. NULL,
  127424. &_vq_auxt__8c1_s_p1_0,
  127425. NULL,
  127426. 0
  127427. };
  127428. static long _vq_quantlist__8c1_s_p2_0[] = {
  127429. 2,
  127430. 1,
  127431. 3,
  127432. 0,
  127433. 4,
  127434. };
  127435. static long _vq_lengthlist__8c1_s_p2_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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0,
  127476. };
  127477. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127478. -1.5, -0.5, 0.5, 1.5,
  127479. };
  127480. static long _vq_quantmap__8c1_s_p2_0[] = {
  127481. 3, 1, 0, 2, 4,
  127482. };
  127483. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127484. _vq_quantthresh__8c1_s_p2_0,
  127485. _vq_quantmap__8c1_s_p2_0,
  127486. 5,
  127487. 5
  127488. };
  127489. static static_codebook _8c1_s_p2_0 = {
  127490. 4, 625,
  127491. _vq_lengthlist__8c1_s_p2_0,
  127492. 1, -533725184, 1611661312, 3, 0,
  127493. _vq_quantlist__8c1_s_p2_0,
  127494. NULL,
  127495. &_vq_auxt__8c1_s_p2_0,
  127496. NULL,
  127497. 0
  127498. };
  127499. static long _vq_quantlist__8c1_s_p3_0[] = {
  127500. 2,
  127501. 1,
  127502. 3,
  127503. 0,
  127504. 4,
  127505. };
  127506. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127507. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 6, 6, 6, 7, 7, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0,
  127547. };
  127548. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127549. -1.5, -0.5, 0.5, 1.5,
  127550. };
  127551. static long _vq_quantmap__8c1_s_p3_0[] = {
  127552. 3, 1, 0, 2, 4,
  127553. };
  127554. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127555. _vq_quantthresh__8c1_s_p3_0,
  127556. _vq_quantmap__8c1_s_p3_0,
  127557. 5,
  127558. 5
  127559. };
  127560. static static_codebook _8c1_s_p3_0 = {
  127561. 4, 625,
  127562. _vq_lengthlist__8c1_s_p3_0,
  127563. 1, -533725184, 1611661312, 3, 0,
  127564. _vq_quantlist__8c1_s_p3_0,
  127565. NULL,
  127566. &_vq_auxt__8c1_s_p3_0,
  127567. NULL,
  127568. 0
  127569. };
  127570. static long _vq_quantlist__8c1_s_p4_0[] = {
  127571. 4,
  127572. 3,
  127573. 5,
  127574. 2,
  127575. 6,
  127576. 1,
  127577. 7,
  127578. 0,
  127579. 8,
  127580. };
  127581. static long _vq_lengthlist__8c1_s_p4_0[] = {
  127582. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  127583. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  127584. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127585. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  127586. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0,
  127588. };
  127589. static float _vq_quantthresh__8c1_s_p4_0[] = {
  127590. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127591. };
  127592. static long _vq_quantmap__8c1_s_p4_0[] = {
  127593. 7, 5, 3, 1, 0, 2, 4, 6,
  127594. 8,
  127595. };
  127596. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  127597. _vq_quantthresh__8c1_s_p4_0,
  127598. _vq_quantmap__8c1_s_p4_0,
  127599. 9,
  127600. 9
  127601. };
  127602. static static_codebook _8c1_s_p4_0 = {
  127603. 2, 81,
  127604. _vq_lengthlist__8c1_s_p4_0,
  127605. 1, -531628032, 1611661312, 4, 0,
  127606. _vq_quantlist__8c1_s_p4_0,
  127607. NULL,
  127608. &_vq_auxt__8c1_s_p4_0,
  127609. NULL,
  127610. 0
  127611. };
  127612. static long _vq_quantlist__8c1_s_p5_0[] = {
  127613. 4,
  127614. 3,
  127615. 5,
  127616. 2,
  127617. 6,
  127618. 1,
  127619. 7,
  127620. 0,
  127621. 8,
  127622. };
  127623. static long _vq_lengthlist__8c1_s_p5_0[] = {
  127624. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  127625. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  127626. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  127627. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  127628. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  127629. 10,
  127630. };
  127631. static float _vq_quantthresh__8c1_s_p5_0[] = {
  127632. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  127633. };
  127634. static long _vq_quantmap__8c1_s_p5_0[] = {
  127635. 7, 5, 3, 1, 0, 2, 4, 6,
  127636. 8,
  127637. };
  127638. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  127639. _vq_quantthresh__8c1_s_p5_0,
  127640. _vq_quantmap__8c1_s_p5_0,
  127641. 9,
  127642. 9
  127643. };
  127644. static static_codebook _8c1_s_p5_0 = {
  127645. 2, 81,
  127646. _vq_lengthlist__8c1_s_p5_0,
  127647. 1, -531628032, 1611661312, 4, 0,
  127648. _vq_quantlist__8c1_s_p5_0,
  127649. NULL,
  127650. &_vq_auxt__8c1_s_p5_0,
  127651. NULL,
  127652. 0
  127653. };
  127654. static long _vq_quantlist__8c1_s_p6_0[] = {
  127655. 8,
  127656. 7,
  127657. 9,
  127658. 6,
  127659. 10,
  127660. 5,
  127661. 11,
  127662. 4,
  127663. 12,
  127664. 3,
  127665. 13,
  127666. 2,
  127667. 14,
  127668. 1,
  127669. 15,
  127670. 0,
  127671. 16,
  127672. };
  127673. static long _vq_lengthlist__8c1_s_p6_0[] = {
  127674. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  127675. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127676. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127677. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  127678. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  127679. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  127680. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  127681. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  127682. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  127683. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127684. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  127685. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  127686. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  127687. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  127688. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  127689. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  127690. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  127692. 14,
  127693. };
  127694. static float _vq_quantthresh__8c1_s_p6_0[] = {
  127695. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127696. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127697. };
  127698. static long _vq_quantmap__8c1_s_p6_0[] = {
  127699. 15, 13, 11, 9, 7, 5, 3, 1,
  127700. 0, 2, 4, 6, 8, 10, 12, 14,
  127701. 16,
  127702. };
  127703. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  127704. _vq_quantthresh__8c1_s_p6_0,
  127705. _vq_quantmap__8c1_s_p6_0,
  127706. 17,
  127707. 17
  127708. };
  127709. static static_codebook _8c1_s_p6_0 = {
  127710. 2, 289,
  127711. _vq_lengthlist__8c1_s_p6_0,
  127712. 1, -529530880, 1611661312, 5, 0,
  127713. _vq_quantlist__8c1_s_p6_0,
  127714. NULL,
  127715. &_vq_auxt__8c1_s_p6_0,
  127716. NULL,
  127717. 0
  127718. };
  127719. static long _vq_quantlist__8c1_s_p7_0[] = {
  127720. 1,
  127721. 0,
  127722. 2,
  127723. };
  127724. static long _vq_lengthlist__8c1_s_p7_0[] = {
  127725. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  127726. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  127727. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  127728. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  127729. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  127730. 9,
  127731. };
  127732. static float _vq_quantthresh__8c1_s_p7_0[] = {
  127733. -5.5, 5.5,
  127734. };
  127735. static long _vq_quantmap__8c1_s_p7_0[] = {
  127736. 1, 0, 2,
  127737. };
  127738. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  127739. _vq_quantthresh__8c1_s_p7_0,
  127740. _vq_quantmap__8c1_s_p7_0,
  127741. 3,
  127742. 3
  127743. };
  127744. static static_codebook _8c1_s_p7_0 = {
  127745. 4, 81,
  127746. _vq_lengthlist__8c1_s_p7_0,
  127747. 1, -529137664, 1618345984, 2, 0,
  127748. _vq_quantlist__8c1_s_p7_0,
  127749. NULL,
  127750. &_vq_auxt__8c1_s_p7_0,
  127751. NULL,
  127752. 0
  127753. };
  127754. static long _vq_quantlist__8c1_s_p7_1[] = {
  127755. 5,
  127756. 4,
  127757. 6,
  127758. 3,
  127759. 7,
  127760. 2,
  127761. 8,
  127762. 1,
  127763. 9,
  127764. 0,
  127765. 10,
  127766. };
  127767. static long _vq_lengthlist__8c1_s_p7_1[] = {
  127768. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  127769. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  127770. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  127771. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  127772. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  127773. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  127774. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  127775. 10,10,10, 8, 8, 8, 8, 8, 8,
  127776. };
  127777. static float _vq_quantthresh__8c1_s_p7_1[] = {
  127778. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127779. 3.5, 4.5,
  127780. };
  127781. static long _vq_quantmap__8c1_s_p7_1[] = {
  127782. 9, 7, 5, 3, 1, 0, 2, 4,
  127783. 6, 8, 10,
  127784. };
  127785. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  127786. _vq_quantthresh__8c1_s_p7_1,
  127787. _vq_quantmap__8c1_s_p7_1,
  127788. 11,
  127789. 11
  127790. };
  127791. static static_codebook _8c1_s_p7_1 = {
  127792. 2, 121,
  127793. _vq_lengthlist__8c1_s_p7_1,
  127794. 1, -531365888, 1611661312, 4, 0,
  127795. _vq_quantlist__8c1_s_p7_1,
  127796. NULL,
  127797. &_vq_auxt__8c1_s_p7_1,
  127798. NULL,
  127799. 0
  127800. };
  127801. static long _vq_quantlist__8c1_s_p8_0[] = {
  127802. 6,
  127803. 5,
  127804. 7,
  127805. 4,
  127806. 8,
  127807. 3,
  127808. 9,
  127809. 2,
  127810. 10,
  127811. 1,
  127812. 11,
  127813. 0,
  127814. 12,
  127815. };
  127816. static long _vq_lengthlist__8c1_s_p8_0[] = {
  127817. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  127818. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  127819. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  127820. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  127821. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  127822. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  127823. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  127824. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  127825. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  127826. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  127827. 0,12,12,11,10,12,11,13,12,
  127828. };
  127829. static float _vq_quantthresh__8c1_s_p8_0[] = {
  127830. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127831. 12.5, 17.5, 22.5, 27.5,
  127832. };
  127833. static long _vq_quantmap__8c1_s_p8_0[] = {
  127834. 11, 9, 7, 5, 3, 1, 0, 2,
  127835. 4, 6, 8, 10, 12,
  127836. };
  127837. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  127838. _vq_quantthresh__8c1_s_p8_0,
  127839. _vq_quantmap__8c1_s_p8_0,
  127840. 13,
  127841. 13
  127842. };
  127843. static static_codebook _8c1_s_p8_0 = {
  127844. 2, 169,
  127845. _vq_lengthlist__8c1_s_p8_0,
  127846. 1, -526516224, 1616117760, 4, 0,
  127847. _vq_quantlist__8c1_s_p8_0,
  127848. NULL,
  127849. &_vq_auxt__8c1_s_p8_0,
  127850. NULL,
  127851. 0
  127852. };
  127853. static long _vq_quantlist__8c1_s_p8_1[] = {
  127854. 2,
  127855. 1,
  127856. 3,
  127857. 0,
  127858. 4,
  127859. };
  127860. static long _vq_lengthlist__8c1_s_p8_1[] = {
  127861. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  127862. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  127863. };
  127864. static float _vq_quantthresh__8c1_s_p8_1[] = {
  127865. -1.5, -0.5, 0.5, 1.5,
  127866. };
  127867. static long _vq_quantmap__8c1_s_p8_1[] = {
  127868. 3, 1, 0, 2, 4,
  127869. };
  127870. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  127871. _vq_quantthresh__8c1_s_p8_1,
  127872. _vq_quantmap__8c1_s_p8_1,
  127873. 5,
  127874. 5
  127875. };
  127876. static static_codebook _8c1_s_p8_1 = {
  127877. 2, 25,
  127878. _vq_lengthlist__8c1_s_p8_1,
  127879. 1, -533725184, 1611661312, 3, 0,
  127880. _vq_quantlist__8c1_s_p8_1,
  127881. NULL,
  127882. &_vq_auxt__8c1_s_p8_1,
  127883. NULL,
  127884. 0
  127885. };
  127886. static long _vq_quantlist__8c1_s_p9_0[] = {
  127887. 6,
  127888. 5,
  127889. 7,
  127890. 4,
  127891. 8,
  127892. 3,
  127893. 9,
  127894. 2,
  127895. 10,
  127896. 1,
  127897. 11,
  127898. 0,
  127899. 12,
  127900. };
  127901. static long _vq_lengthlist__8c1_s_p9_0[] = {
  127902. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  127903. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  127904. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127905. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127906. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127907. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127908. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127909. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127910. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127911. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  127912. 10,10,10,10,10, 9, 9, 9, 9,
  127913. };
  127914. static float _vq_quantthresh__8c1_s_p9_0[] = {
  127915. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  127916. 787.5, 1102.5, 1417.5, 1732.5,
  127917. };
  127918. static long _vq_quantmap__8c1_s_p9_0[] = {
  127919. 11, 9, 7, 5, 3, 1, 0, 2,
  127920. 4, 6, 8, 10, 12,
  127921. };
  127922. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  127923. _vq_quantthresh__8c1_s_p9_0,
  127924. _vq_quantmap__8c1_s_p9_0,
  127925. 13,
  127926. 13
  127927. };
  127928. static static_codebook _8c1_s_p9_0 = {
  127929. 2, 169,
  127930. _vq_lengthlist__8c1_s_p9_0,
  127931. 1, -513964032, 1628680192, 4, 0,
  127932. _vq_quantlist__8c1_s_p9_0,
  127933. NULL,
  127934. &_vq_auxt__8c1_s_p9_0,
  127935. NULL,
  127936. 0
  127937. };
  127938. static long _vq_quantlist__8c1_s_p9_1[] = {
  127939. 7,
  127940. 6,
  127941. 8,
  127942. 5,
  127943. 9,
  127944. 4,
  127945. 10,
  127946. 3,
  127947. 11,
  127948. 2,
  127949. 12,
  127950. 1,
  127951. 13,
  127952. 0,
  127953. 14,
  127954. };
  127955. static long _vq_lengthlist__8c1_s_p9_1[] = {
  127956. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  127957. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  127958. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  127959. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  127960. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  127961. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  127962. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  127963. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  127964. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  127965. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  127966. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  127967. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  127968. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  127969. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  127970. 15,
  127971. };
  127972. static float _vq_quantthresh__8c1_s_p9_1[] = {
  127973. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127974. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127975. };
  127976. static long _vq_quantmap__8c1_s_p9_1[] = {
  127977. 13, 11, 9, 7, 5, 3, 1, 0,
  127978. 2, 4, 6, 8, 10, 12, 14,
  127979. };
  127980. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  127981. _vq_quantthresh__8c1_s_p9_1,
  127982. _vq_quantmap__8c1_s_p9_1,
  127983. 15,
  127984. 15
  127985. };
  127986. static static_codebook _8c1_s_p9_1 = {
  127987. 2, 225,
  127988. _vq_lengthlist__8c1_s_p9_1,
  127989. 1, -520986624, 1620377600, 4, 0,
  127990. _vq_quantlist__8c1_s_p9_1,
  127991. NULL,
  127992. &_vq_auxt__8c1_s_p9_1,
  127993. NULL,
  127994. 0
  127995. };
  127996. static long _vq_quantlist__8c1_s_p9_2[] = {
  127997. 10,
  127998. 9,
  127999. 11,
  128000. 8,
  128001. 12,
  128002. 7,
  128003. 13,
  128004. 6,
  128005. 14,
  128006. 5,
  128007. 15,
  128008. 4,
  128009. 16,
  128010. 3,
  128011. 17,
  128012. 2,
  128013. 18,
  128014. 1,
  128015. 19,
  128016. 0,
  128017. 20,
  128018. };
  128019. static long _vq_lengthlist__8c1_s_p9_2[] = {
  128020. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  128021. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  128022. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  128023. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  128024. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128025. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128026. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128027. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  128028. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128029. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  128030. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  128031. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  128032. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  128033. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128034. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  128035. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  128036. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128037. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  128038. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  128039. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  128040. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128041. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128042. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128043. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128044. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128045. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128046. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128047. 10,10,10,10,10,10,10,10,10,
  128048. };
  128049. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128050. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128051. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128052. 6.5, 7.5, 8.5, 9.5,
  128053. };
  128054. static long _vq_quantmap__8c1_s_p9_2[] = {
  128055. 19, 17, 15, 13, 11, 9, 7, 5,
  128056. 3, 1, 0, 2, 4, 6, 8, 10,
  128057. 12, 14, 16, 18, 20,
  128058. };
  128059. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128060. _vq_quantthresh__8c1_s_p9_2,
  128061. _vq_quantmap__8c1_s_p9_2,
  128062. 21,
  128063. 21
  128064. };
  128065. static static_codebook _8c1_s_p9_2 = {
  128066. 2, 441,
  128067. _vq_lengthlist__8c1_s_p9_2,
  128068. 1, -529268736, 1611661312, 5, 0,
  128069. _vq_quantlist__8c1_s_p9_2,
  128070. NULL,
  128071. &_vq_auxt__8c1_s_p9_2,
  128072. NULL,
  128073. 0
  128074. };
  128075. static long _huff_lengthlist__8c1_s_single[] = {
  128076. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128077. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128078. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128079. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128080. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128081. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128082. 9, 7, 7, 8,
  128083. };
  128084. static static_codebook _huff_book__8c1_s_single = {
  128085. 2, 100,
  128086. _huff_lengthlist__8c1_s_single,
  128087. 0, 0, 0, 0, 0,
  128088. NULL,
  128089. NULL,
  128090. NULL,
  128091. NULL,
  128092. 0
  128093. };
  128094. static long _huff_lengthlist__44c2_s_long[] = {
  128095. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128096. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128097. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128098. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128099. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128100. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128101. 10, 8, 8, 9,
  128102. };
  128103. static static_codebook _huff_book__44c2_s_long = {
  128104. 2, 100,
  128105. _huff_lengthlist__44c2_s_long,
  128106. 0, 0, 0, 0, 0,
  128107. NULL,
  128108. NULL,
  128109. NULL,
  128110. NULL,
  128111. 0
  128112. };
  128113. static long _vq_quantlist__44c2_s_p1_0[] = {
  128114. 1,
  128115. 0,
  128116. 2,
  128117. };
  128118. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128119. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128120. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128125. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128130. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128165. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  128170. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  128175. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128210. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128211. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128216. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128221. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128529. 0,
  128530. };
  128531. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128532. -0.5, 0.5,
  128533. };
  128534. static long _vq_quantmap__44c2_s_p1_0[] = {
  128535. 1, 0, 2,
  128536. };
  128537. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128538. _vq_quantthresh__44c2_s_p1_0,
  128539. _vq_quantmap__44c2_s_p1_0,
  128540. 3,
  128541. 3
  128542. };
  128543. static static_codebook _44c2_s_p1_0 = {
  128544. 8, 6561,
  128545. _vq_lengthlist__44c2_s_p1_0,
  128546. 1, -535822336, 1611661312, 2, 0,
  128547. _vq_quantlist__44c2_s_p1_0,
  128548. NULL,
  128549. &_vq_auxt__44c2_s_p1_0,
  128550. NULL,
  128551. 0
  128552. };
  128553. static long _vq_quantlist__44c2_s_p2_0[] = {
  128554. 2,
  128555. 1,
  128556. 3,
  128557. 0,
  128558. 4,
  128559. };
  128560. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128561. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128562. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  128563. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  128564. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  128565. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  128571. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  128572. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  128573. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  128579. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  128580. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  128587. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  128588. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0,
  128601. };
  128602. static float _vq_quantthresh__44c2_s_p2_0[] = {
  128603. -1.5, -0.5, 0.5, 1.5,
  128604. };
  128605. static long _vq_quantmap__44c2_s_p2_0[] = {
  128606. 3, 1, 0, 2, 4,
  128607. };
  128608. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  128609. _vq_quantthresh__44c2_s_p2_0,
  128610. _vq_quantmap__44c2_s_p2_0,
  128611. 5,
  128612. 5
  128613. };
  128614. static static_codebook _44c2_s_p2_0 = {
  128615. 4, 625,
  128616. _vq_lengthlist__44c2_s_p2_0,
  128617. 1, -533725184, 1611661312, 3, 0,
  128618. _vq_quantlist__44c2_s_p2_0,
  128619. NULL,
  128620. &_vq_auxt__44c2_s_p2_0,
  128621. NULL,
  128622. 0
  128623. };
  128624. static long _vq_quantlist__44c2_s_p3_0[] = {
  128625. 2,
  128626. 1,
  128627. 3,
  128628. 0,
  128629. 4,
  128630. };
  128631. static long _vq_lengthlist__44c2_s_p3_0[] = {
  128632. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0,
  128672. };
  128673. static float _vq_quantthresh__44c2_s_p3_0[] = {
  128674. -1.5, -0.5, 0.5, 1.5,
  128675. };
  128676. static long _vq_quantmap__44c2_s_p3_0[] = {
  128677. 3, 1, 0, 2, 4,
  128678. };
  128679. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  128680. _vq_quantthresh__44c2_s_p3_0,
  128681. _vq_quantmap__44c2_s_p3_0,
  128682. 5,
  128683. 5
  128684. };
  128685. static static_codebook _44c2_s_p3_0 = {
  128686. 4, 625,
  128687. _vq_lengthlist__44c2_s_p3_0,
  128688. 1, -533725184, 1611661312, 3, 0,
  128689. _vq_quantlist__44c2_s_p3_0,
  128690. NULL,
  128691. &_vq_auxt__44c2_s_p3_0,
  128692. NULL,
  128693. 0
  128694. };
  128695. static long _vq_quantlist__44c2_s_p4_0[] = {
  128696. 4,
  128697. 3,
  128698. 5,
  128699. 2,
  128700. 6,
  128701. 1,
  128702. 7,
  128703. 0,
  128704. 8,
  128705. };
  128706. static long _vq_lengthlist__44c2_s_p4_0[] = {
  128707. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  128708. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  128709. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  128710. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  128711. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0,
  128713. };
  128714. static float _vq_quantthresh__44c2_s_p4_0[] = {
  128715. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128716. };
  128717. static long _vq_quantmap__44c2_s_p4_0[] = {
  128718. 7, 5, 3, 1, 0, 2, 4, 6,
  128719. 8,
  128720. };
  128721. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  128722. _vq_quantthresh__44c2_s_p4_0,
  128723. _vq_quantmap__44c2_s_p4_0,
  128724. 9,
  128725. 9
  128726. };
  128727. static static_codebook _44c2_s_p4_0 = {
  128728. 2, 81,
  128729. _vq_lengthlist__44c2_s_p4_0,
  128730. 1, -531628032, 1611661312, 4, 0,
  128731. _vq_quantlist__44c2_s_p4_0,
  128732. NULL,
  128733. &_vq_auxt__44c2_s_p4_0,
  128734. NULL,
  128735. 0
  128736. };
  128737. static long _vq_quantlist__44c2_s_p5_0[] = {
  128738. 4,
  128739. 3,
  128740. 5,
  128741. 2,
  128742. 6,
  128743. 1,
  128744. 7,
  128745. 0,
  128746. 8,
  128747. };
  128748. static long _vq_lengthlist__44c2_s_p5_0[] = {
  128749. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  128750. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  128751. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  128752. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  128753. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  128754. 11,
  128755. };
  128756. static float _vq_quantthresh__44c2_s_p5_0[] = {
  128757. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128758. };
  128759. static long _vq_quantmap__44c2_s_p5_0[] = {
  128760. 7, 5, 3, 1, 0, 2, 4, 6,
  128761. 8,
  128762. };
  128763. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  128764. _vq_quantthresh__44c2_s_p5_0,
  128765. _vq_quantmap__44c2_s_p5_0,
  128766. 9,
  128767. 9
  128768. };
  128769. static static_codebook _44c2_s_p5_0 = {
  128770. 2, 81,
  128771. _vq_lengthlist__44c2_s_p5_0,
  128772. 1, -531628032, 1611661312, 4, 0,
  128773. _vq_quantlist__44c2_s_p5_0,
  128774. NULL,
  128775. &_vq_auxt__44c2_s_p5_0,
  128776. NULL,
  128777. 0
  128778. };
  128779. static long _vq_quantlist__44c2_s_p6_0[] = {
  128780. 8,
  128781. 7,
  128782. 9,
  128783. 6,
  128784. 10,
  128785. 5,
  128786. 11,
  128787. 4,
  128788. 12,
  128789. 3,
  128790. 13,
  128791. 2,
  128792. 14,
  128793. 1,
  128794. 15,
  128795. 0,
  128796. 16,
  128797. };
  128798. static long _vq_lengthlist__44c2_s_p6_0[] = {
  128799. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  128800. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128801. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  128802. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  128803. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  128804. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  128805. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  128806. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  128807. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  128808. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128809. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128810. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  128811. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128812. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128813. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128814. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  128815. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128817. 14,
  128818. };
  128819. static float _vq_quantthresh__44c2_s_p6_0[] = {
  128820. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128821. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128822. };
  128823. static long _vq_quantmap__44c2_s_p6_0[] = {
  128824. 15, 13, 11, 9, 7, 5, 3, 1,
  128825. 0, 2, 4, 6, 8, 10, 12, 14,
  128826. 16,
  128827. };
  128828. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  128829. _vq_quantthresh__44c2_s_p6_0,
  128830. _vq_quantmap__44c2_s_p6_0,
  128831. 17,
  128832. 17
  128833. };
  128834. static static_codebook _44c2_s_p6_0 = {
  128835. 2, 289,
  128836. _vq_lengthlist__44c2_s_p6_0,
  128837. 1, -529530880, 1611661312, 5, 0,
  128838. _vq_quantlist__44c2_s_p6_0,
  128839. NULL,
  128840. &_vq_auxt__44c2_s_p6_0,
  128841. NULL,
  128842. 0
  128843. };
  128844. static long _vq_quantlist__44c2_s_p7_0[] = {
  128845. 1,
  128846. 0,
  128847. 2,
  128848. };
  128849. static long _vq_lengthlist__44c2_s_p7_0[] = {
  128850. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  128851. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  128852. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  128853. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  128854. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  128855. 11,
  128856. };
  128857. static float _vq_quantthresh__44c2_s_p7_0[] = {
  128858. -5.5, 5.5,
  128859. };
  128860. static long _vq_quantmap__44c2_s_p7_0[] = {
  128861. 1, 0, 2,
  128862. };
  128863. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  128864. _vq_quantthresh__44c2_s_p7_0,
  128865. _vq_quantmap__44c2_s_p7_0,
  128866. 3,
  128867. 3
  128868. };
  128869. static static_codebook _44c2_s_p7_0 = {
  128870. 4, 81,
  128871. _vq_lengthlist__44c2_s_p7_0,
  128872. 1, -529137664, 1618345984, 2, 0,
  128873. _vq_quantlist__44c2_s_p7_0,
  128874. NULL,
  128875. &_vq_auxt__44c2_s_p7_0,
  128876. NULL,
  128877. 0
  128878. };
  128879. static long _vq_quantlist__44c2_s_p7_1[] = {
  128880. 5,
  128881. 4,
  128882. 6,
  128883. 3,
  128884. 7,
  128885. 2,
  128886. 8,
  128887. 1,
  128888. 9,
  128889. 0,
  128890. 10,
  128891. };
  128892. static long _vq_lengthlist__44c2_s_p7_1[] = {
  128893. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  128894. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  128895. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128896. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  128897. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128898. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128899. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  128900. 10,10,10, 8, 8, 8, 8, 8, 8,
  128901. };
  128902. static float _vq_quantthresh__44c2_s_p7_1[] = {
  128903. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128904. 3.5, 4.5,
  128905. };
  128906. static long _vq_quantmap__44c2_s_p7_1[] = {
  128907. 9, 7, 5, 3, 1, 0, 2, 4,
  128908. 6, 8, 10,
  128909. };
  128910. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  128911. _vq_quantthresh__44c2_s_p7_1,
  128912. _vq_quantmap__44c2_s_p7_1,
  128913. 11,
  128914. 11
  128915. };
  128916. static static_codebook _44c2_s_p7_1 = {
  128917. 2, 121,
  128918. _vq_lengthlist__44c2_s_p7_1,
  128919. 1, -531365888, 1611661312, 4, 0,
  128920. _vq_quantlist__44c2_s_p7_1,
  128921. NULL,
  128922. &_vq_auxt__44c2_s_p7_1,
  128923. NULL,
  128924. 0
  128925. };
  128926. static long _vq_quantlist__44c2_s_p8_0[] = {
  128927. 6,
  128928. 5,
  128929. 7,
  128930. 4,
  128931. 8,
  128932. 3,
  128933. 9,
  128934. 2,
  128935. 10,
  128936. 1,
  128937. 11,
  128938. 0,
  128939. 12,
  128940. };
  128941. static long _vq_lengthlist__44c2_s_p8_0[] = {
  128942. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  128943. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  128944. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128945. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128946. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  128947. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  128948. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  128949. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  128950. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  128951. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  128952. 0,12,12,12,12,13,12,14,14,
  128953. };
  128954. static float _vq_quantthresh__44c2_s_p8_0[] = {
  128955. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128956. 12.5, 17.5, 22.5, 27.5,
  128957. };
  128958. static long _vq_quantmap__44c2_s_p8_0[] = {
  128959. 11, 9, 7, 5, 3, 1, 0, 2,
  128960. 4, 6, 8, 10, 12,
  128961. };
  128962. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  128963. _vq_quantthresh__44c2_s_p8_0,
  128964. _vq_quantmap__44c2_s_p8_0,
  128965. 13,
  128966. 13
  128967. };
  128968. static static_codebook _44c2_s_p8_0 = {
  128969. 2, 169,
  128970. _vq_lengthlist__44c2_s_p8_0,
  128971. 1, -526516224, 1616117760, 4, 0,
  128972. _vq_quantlist__44c2_s_p8_0,
  128973. NULL,
  128974. &_vq_auxt__44c2_s_p8_0,
  128975. NULL,
  128976. 0
  128977. };
  128978. static long _vq_quantlist__44c2_s_p8_1[] = {
  128979. 2,
  128980. 1,
  128981. 3,
  128982. 0,
  128983. 4,
  128984. };
  128985. static long _vq_lengthlist__44c2_s_p8_1[] = {
  128986. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  128987. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  128988. };
  128989. static float _vq_quantthresh__44c2_s_p8_1[] = {
  128990. -1.5, -0.5, 0.5, 1.5,
  128991. };
  128992. static long _vq_quantmap__44c2_s_p8_1[] = {
  128993. 3, 1, 0, 2, 4,
  128994. };
  128995. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  128996. _vq_quantthresh__44c2_s_p8_1,
  128997. _vq_quantmap__44c2_s_p8_1,
  128998. 5,
  128999. 5
  129000. };
  129001. static static_codebook _44c2_s_p8_1 = {
  129002. 2, 25,
  129003. _vq_lengthlist__44c2_s_p8_1,
  129004. 1, -533725184, 1611661312, 3, 0,
  129005. _vq_quantlist__44c2_s_p8_1,
  129006. NULL,
  129007. &_vq_auxt__44c2_s_p8_1,
  129008. NULL,
  129009. 0
  129010. };
  129011. static long _vq_quantlist__44c2_s_p9_0[] = {
  129012. 6,
  129013. 5,
  129014. 7,
  129015. 4,
  129016. 8,
  129017. 3,
  129018. 9,
  129019. 2,
  129020. 10,
  129021. 1,
  129022. 11,
  129023. 0,
  129024. 12,
  129025. };
  129026. static long _vq_lengthlist__44c2_s_p9_0[] = {
  129027. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129028. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  129029. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129030. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  129031. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129032. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129033. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129034. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129035. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129036. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129037. 11,11,11,11,11,11,11,11,11,
  129038. };
  129039. static float _vq_quantthresh__44c2_s_p9_0[] = {
  129040. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129041. 552.5, 773.5, 994.5, 1215.5,
  129042. };
  129043. static long _vq_quantmap__44c2_s_p9_0[] = {
  129044. 11, 9, 7, 5, 3, 1, 0, 2,
  129045. 4, 6, 8, 10, 12,
  129046. };
  129047. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129048. _vq_quantthresh__44c2_s_p9_0,
  129049. _vq_quantmap__44c2_s_p9_0,
  129050. 13,
  129051. 13
  129052. };
  129053. static static_codebook _44c2_s_p9_0 = {
  129054. 2, 169,
  129055. _vq_lengthlist__44c2_s_p9_0,
  129056. 1, -514541568, 1627103232, 4, 0,
  129057. _vq_quantlist__44c2_s_p9_0,
  129058. NULL,
  129059. &_vq_auxt__44c2_s_p9_0,
  129060. NULL,
  129061. 0
  129062. };
  129063. static long _vq_quantlist__44c2_s_p9_1[] = {
  129064. 6,
  129065. 5,
  129066. 7,
  129067. 4,
  129068. 8,
  129069. 3,
  129070. 9,
  129071. 2,
  129072. 10,
  129073. 1,
  129074. 11,
  129075. 0,
  129076. 12,
  129077. };
  129078. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129079. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129080. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129081. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129082. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129083. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129084. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129085. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129086. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129087. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129088. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129089. 17,13,12,12,10,13,11,14,14,
  129090. };
  129091. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129092. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129093. 42.5, 59.5, 76.5, 93.5,
  129094. };
  129095. static long _vq_quantmap__44c2_s_p9_1[] = {
  129096. 11, 9, 7, 5, 3, 1, 0, 2,
  129097. 4, 6, 8, 10, 12,
  129098. };
  129099. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129100. _vq_quantthresh__44c2_s_p9_1,
  129101. _vq_quantmap__44c2_s_p9_1,
  129102. 13,
  129103. 13
  129104. };
  129105. static static_codebook _44c2_s_p9_1 = {
  129106. 2, 169,
  129107. _vq_lengthlist__44c2_s_p9_1,
  129108. 1, -522616832, 1620115456, 4, 0,
  129109. _vq_quantlist__44c2_s_p9_1,
  129110. NULL,
  129111. &_vq_auxt__44c2_s_p9_1,
  129112. NULL,
  129113. 0
  129114. };
  129115. static long _vq_quantlist__44c2_s_p9_2[] = {
  129116. 8,
  129117. 7,
  129118. 9,
  129119. 6,
  129120. 10,
  129121. 5,
  129122. 11,
  129123. 4,
  129124. 12,
  129125. 3,
  129126. 13,
  129127. 2,
  129128. 14,
  129129. 1,
  129130. 15,
  129131. 0,
  129132. 16,
  129133. };
  129134. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129135. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129136. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129137. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129138. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129139. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129140. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129141. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129142. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129143. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129144. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129145. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129146. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129147. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129148. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129149. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129150. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129151. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129152. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129153. 10,
  129154. };
  129155. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129156. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129157. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129158. };
  129159. static long _vq_quantmap__44c2_s_p9_2[] = {
  129160. 15, 13, 11, 9, 7, 5, 3, 1,
  129161. 0, 2, 4, 6, 8, 10, 12, 14,
  129162. 16,
  129163. };
  129164. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129165. _vq_quantthresh__44c2_s_p9_2,
  129166. _vq_quantmap__44c2_s_p9_2,
  129167. 17,
  129168. 17
  129169. };
  129170. static static_codebook _44c2_s_p9_2 = {
  129171. 2, 289,
  129172. _vq_lengthlist__44c2_s_p9_2,
  129173. 1, -529530880, 1611661312, 5, 0,
  129174. _vq_quantlist__44c2_s_p9_2,
  129175. NULL,
  129176. &_vq_auxt__44c2_s_p9_2,
  129177. NULL,
  129178. 0
  129179. };
  129180. static long _huff_lengthlist__44c2_s_short[] = {
  129181. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129182. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129183. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129184. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129185. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129186. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129187. 6, 8, 9,12,
  129188. };
  129189. static static_codebook _huff_book__44c2_s_short = {
  129190. 2, 100,
  129191. _huff_lengthlist__44c2_s_short,
  129192. 0, 0, 0, 0, 0,
  129193. NULL,
  129194. NULL,
  129195. NULL,
  129196. NULL,
  129197. 0
  129198. };
  129199. static long _huff_lengthlist__44c3_s_long[] = {
  129200. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129201. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129202. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129203. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129204. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129205. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129206. 9, 8, 8, 8,
  129207. };
  129208. static static_codebook _huff_book__44c3_s_long = {
  129209. 2, 100,
  129210. _huff_lengthlist__44c3_s_long,
  129211. 0, 0, 0, 0, 0,
  129212. NULL,
  129213. NULL,
  129214. NULL,
  129215. NULL,
  129216. 0
  129217. };
  129218. static long _vq_quantlist__44c3_s_p1_0[] = {
  129219. 1,
  129220. 0,
  129221. 2,
  129222. };
  129223. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129224. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129225. 0, 0, 5, 6, 6, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129230. 0, 0, 0, 6, 7, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129235. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129270. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  129275. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  129280. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129315. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129316. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129321. 0, 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129326. 0, 0, 0, 0, 0, 0, 8, 9, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129634. 0,
  129635. };
  129636. static float _vq_quantthresh__44c3_s_p1_0[] = {
  129637. -0.5, 0.5,
  129638. };
  129639. static long _vq_quantmap__44c3_s_p1_0[] = {
  129640. 1, 0, 2,
  129641. };
  129642. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  129643. _vq_quantthresh__44c3_s_p1_0,
  129644. _vq_quantmap__44c3_s_p1_0,
  129645. 3,
  129646. 3
  129647. };
  129648. static static_codebook _44c3_s_p1_0 = {
  129649. 8, 6561,
  129650. _vq_lengthlist__44c3_s_p1_0,
  129651. 1, -535822336, 1611661312, 2, 0,
  129652. _vq_quantlist__44c3_s_p1_0,
  129653. NULL,
  129654. &_vq_auxt__44c3_s_p1_0,
  129655. NULL,
  129656. 0
  129657. };
  129658. static long _vq_quantlist__44c3_s_p2_0[] = {
  129659. 2,
  129660. 1,
  129661. 3,
  129662. 0,
  129663. 4,
  129664. };
  129665. static long _vq_lengthlist__44c3_s_p2_0[] = {
  129666. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  129667. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  129668. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129669. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  129670. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  129676. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  129677. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  129678. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  129684. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  129685. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  129692. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  129693. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0,
  129706. };
  129707. static float _vq_quantthresh__44c3_s_p2_0[] = {
  129708. -1.5, -0.5, 0.5, 1.5,
  129709. };
  129710. static long _vq_quantmap__44c3_s_p2_0[] = {
  129711. 3, 1, 0, 2, 4,
  129712. };
  129713. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  129714. _vq_quantthresh__44c3_s_p2_0,
  129715. _vq_quantmap__44c3_s_p2_0,
  129716. 5,
  129717. 5
  129718. };
  129719. static static_codebook _44c3_s_p2_0 = {
  129720. 4, 625,
  129721. _vq_lengthlist__44c3_s_p2_0,
  129722. 1, -533725184, 1611661312, 3, 0,
  129723. _vq_quantlist__44c3_s_p2_0,
  129724. NULL,
  129725. &_vq_auxt__44c3_s_p2_0,
  129726. NULL,
  129727. 0
  129728. };
  129729. static long _vq_quantlist__44c3_s_p3_0[] = {
  129730. 2,
  129731. 1,
  129732. 3,
  129733. 0,
  129734. 4,
  129735. };
  129736. static long _vq_lengthlist__44c3_s_p3_0[] = {
  129737. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0,
  129777. };
  129778. static float _vq_quantthresh__44c3_s_p3_0[] = {
  129779. -1.5, -0.5, 0.5, 1.5,
  129780. };
  129781. static long _vq_quantmap__44c3_s_p3_0[] = {
  129782. 3, 1, 0, 2, 4,
  129783. };
  129784. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  129785. _vq_quantthresh__44c3_s_p3_0,
  129786. _vq_quantmap__44c3_s_p3_0,
  129787. 5,
  129788. 5
  129789. };
  129790. static static_codebook _44c3_s_p3_0 = {
  129791. 4, 625,
  129792. _vq_lengthlist__44c3_s_p3_0,
  129793. 1, -533725184, 1611661312, 3, 0,
  129794. _vq_quantlist__44c3_s_p3_0,
  129795. NULL,
  129796. &_vq_auxt__44c3_s_p3_0,
  129797. NULL,
  129798. 0
  129799. };
  129800. static long _vq_quantlist__44c3_s_p4_0[] = {
  129801. 4,
  129802. 3,
  129803. 5,
  129804. 2,
  129805. 6,
  129806. 1,
  129807. 7,
  129808. 0,
  129809. 8,
  129810. };
  129811. static long _vq_lengthlist__44c3_s_p4_0[] = {
  129812. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  129813. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  129814. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  129815. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  129816. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0,
  129818. };
  129819. static float _vq_quantthresh__44c3_s_p4_0[] = {
  129820. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129821. };
  129822. static long _vq_quantmap__44c3_s_p4_0[] = {
  129823. 7, 5, 3, 1, 0, 2, 4, 6,
  129824. 8,
  129825. };
  129826. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  129827. _vq_quantthresh__44c3_s_p4_0,
  129828. _vq_quantmap__44c3_s_p4_0,
  129829. 9,
  129830. 9
  129831. };
  129832. static static_codebook _44c3_s_p4_0 = {
  129833. 2, 81,
  129834. _vq_lengthlist__44c3_s_p4_0,
  129835. 1, -531628032, 1611661312, 4, 0,
  129836. _vq_quantlist__44c3_s_p4_0,
  129837. NULL,
  129838. &_vq_auxt__44c3_s_p4_0,
  129839. NULL,
  129840. 0
  129841. };
  129842. static long _vq_quantlist__44c3_s_p5_0[] = {
  129843. 4,
  129844. 3,
  129845. 5,
  129846. 2,
  129847. 6,
  129848. 1,
  129849. 7,
  129850. 0,
  129851. 8,
  129852. };
  129853. static long _vq_lengthlist__44c3_s_p5_0[] = {
  129854. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  129855. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  129856. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  129857. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  129858. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  129859. 11,
  129860. };
  129861. static float _vq_quantthresh__44c3_s_p5_0[] = {
  129862. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129863. };
  129864. static long _vq_quantmap__44c3_s_p5_0[] = {
  129865. 7, 5, 3, 1, 0, 2, 4, 6,
  129866. 8,
  129867. };
  129868. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  129869. _vq_quantthresh__44c3_s_p5_0,
  129870. _vq_quantmap__44c3_s_p5_0,
  129871. 9,
  129872. 9
  129873. };
  129874. static static_codebook _44c3_s_p5_0 = {
  129875. 2, 81,
  129876. _vq_lengthlist__44c3_s_p5_0,
  129877. 1, -531628032, 1611661312, 4, 0,
  129878. _vq_quantlist__44c3_s_p5_0,
  129879. NULL,
  129880. &_vq_auxt__44c3_s_p5_0,
  129881. NULL,
  129882. 0
  129883. };
  129884. static long _vq_quantlist__44c3_s_p6_0[] = {
  129885. 8,
  129886. 7,
  129887. 9,
  129888. 6,
  129889. 10,
  129890. 5,
  129891. 11,
  129892. 4,
  129893. 12,
  129894. 3,
  129895. 13,
  129896. 2,
  129897. 14,
  129898. 1,
  129899. 15,
  129900. 0,
  129901. 16,
  129902. };
  129903. static long _vq_lengthlist__44c3_s_p6_0[] = {
  129904. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  129905. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  129906. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  129907. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  129908. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  129909. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129910. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  129911. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129912. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129913. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  129914. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  129915. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  129916. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  129917. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  129918. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  129919. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  129920. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  129922. 13,
  129923. };
  129924. static float _vq_quantthresh__44c3_s_p6_0[] = {
  129925. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129926. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129927. };
  129928. static long _vq_quantmap__44c3_s_p6_0[] = {
  129929. 15, 13, 11, 9, 7, 5, 3, 1,
  129930. 0, 2, 4, 6, 8, 10, 12, 14,
  129931. 16,
  129932. };
  129933. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  129934. _vq_quantthresh__44c3_s_p6_0,
  129935. _vq_quantmap__44c3_s_p6_0,
  129936. 17,
  129937. 17
  129938. };
  129939. static static_codebook _44c3_s_p6_0 = {
  129940. 2, 289,
  129941. _vq_lengthlist__44c3_s_p6_0,
  129942. 1, -529530880, 1611661312, 5, 0,
  129943. _vq_quantlist__44c3_s_p6_0,
  129944. NULL,
  129945. &_vq_auxt__44c3_s_p6_0,
  129946. NULL,
  129947. 0
  129948. };
  129949. static long _vq_quantlist__44c3_s_p7_0[] = {
  129950. 1,
  129951. 0,
  129952. 2,
  129953. };
  129954. static long _vq_lengthlist__44c3_s_p7_0[] = {
  129955. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129956. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  129957. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129958. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  129959. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  129960. 10,
  129961. };
  129962. static float _vq_quantthresh__44c3_s_p7_0[] = {
  129963. -5.5, 5.5,
  129964. };
  129965. static long _vq_quantmap__44c3_s_p7_0[] = {
  129966. 1, 0, 2,
  129967. };
  129968. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  129969. _vq_quantthresh__44c3_s_p7_0,
  129970. _vq_quantmap__44c3_s_p7_0,
  129971. 3,
  129972. 3
  129973. };
  129974. static static_codebook _44c3_s_p7_0 = {
  129975. 4, 81,
  129976. _vq_lengthlist__44c3_s_p7_0,
  129977. 1, -529137664, 1618345984, 2, 0,
  129978. _vq_quantlist__44c3_s_p7_0,
  129979. NULL,
  129980. &_vq_auxt__44c3_s_p7_0,
  129981. NULL,
  129982. 0
  129983. };
  129984. static long _vq_quantlist__44c3_s_p7_1[] = {
  129985. 5,
  129986. 4,
  129987. 6,
  129988. 3,
  129989. 7,
  129990. 2,
  129991. 8,
  129992. 1,
  129993. 9,
  129994. 0,
  129995. 10,
  129996. };
  129997. static long _vq_lengthlist__44c3_s_p7_1[] = {
  129998. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  129999. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130000. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130001. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  130002. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  130003. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130004. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130005. 10,10,10, 8, 8, 8, 8, 8, 8,
  130006. };
  130007. static float _vq_quantthresh__44c3_s_p7_1[] = {
  130008. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130009. 3.5, 4.5,
  130010. };
  130011. static long _vq_quantmap__44c3_s_p7_1[] = {
  130012. 9, 7, 5, 3, 1, 0, 2, 4,
  130013. 6, 8, 10,
  130014. };
  130015. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  130016. _vq_quantthresh__44c3_s_p7_1,
  130017. _vq_quantmap__44c3_s_p7_1,
  130018. 11,
  130019. 11
  130020. };
  130021. static static_codebook _44c3_s_p7_1 = {
  130022. 2, 121,
  130023. _vq_lengthlist__44c3_s_p7_1,
  130024. 1, -531365888, 1611661312, 4, 0,
  130025. _vq_quantlist__44c3_s_p7_1,
  130026. NULL,
  130027. &_vq_auxt__44c3_s_p7_1,
  130028. NULL,
  130029. 0
  130030. };
  130031. static long _vq_quantlist__44c3_s_p8_0[] = {
  130032. 6,
  130033. 5,
  130034. 7,
  130035. 4,
  130036. 8,
  130037. 3,
  130038. 9,
  130039. 2,
  130040. 10,
  130041. 1,
  130042. 11,
  130043. 0,
  130044. 12,
  130045. };
  130046. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130047. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130048. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130049. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130050. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130051. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130052. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130053. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130054. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130055. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130056. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130057. 0,13,13,12,12,13,12,14,13,
  130058. };
  130059. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130060. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130061. 12.5, 17.5, 22.5, 27.5,
  130062. };
  130063. static long _vq_quantmap__44c3_s_p8_0[] = {
  130064. 11, 9, 7, 5, 3, 1, 0, 2,
  130065. 4, 6, 8, 10, 12,
  130066. };
  130067. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130068. _vq_quantthresh__44c3_s_p8_0,
  130069. _vq_quantmap__44c3_s_p8_0,
  130070. 13,
  130071. 13
  130072. };
  130073. static static_codebook _44c3_s_p8_0 = {
  130074. 2, 169,
  130075. _vq_lengthlist__44c3_s_p8_0,
  130076. 1, -526516224, 1616117760, 4, 0,
  130077. _vq_quantlist__44c3_s_p8_0,
  130078. NULL,
  130079. &_vq_auxt__44c3_s_p8_0,
  130080. NULL,
  130081. 0
  130082. };
  130083. static long _vq_quantlist__44c3_s_p8_1[] = {
  130084. 2,
  130085. 1,
  130086. 3,
  130087. 0,
  130088. 4,
  130089. };
  130090. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130091. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130092. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130093. };
  130094. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130095. -1.5, -0.5, 0.5, 1.5,
  130096. };
  130097. static long _vq_quantmap__44c3_s_p8_1[] = {
  130098. 3, 1, 0, 2, 4,
  130099. };
  130100. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130101. _vq_quantthresh__44c3_s_p8_1,
  130102. _vq_quantmap__44c3_s_p8_1,
  130103. 5,
  130104. 5
  130105. };
  130106. static static_codebook _44c3_s_p8_1 = {
  130107. 2, 25,
  130108. _vq_lengthlist__44c3_s_p8_1,
  130109. 1, -533725184, 1611661312, 3, 0,
  130110. _vq_quantlist__44c3_s_p8_1,
  130111. NULL,
  130112. &_vq_auxt__44c3_s_p8_1,
  130113. NULL,
  130114. 0
  130115. };
  130116. static long _vq_quantlist__44c3_s_p9_0[] = {
  130117. 6,
  130118. 5,
  130119. 7,
  130120. 4,
  130121. 8,
  130122. 3,
  130123. 9,
  130124. 2,
  130125. 10,
  130126. 1,
  130127. 11,
  130128. 0,
  130129. 12,
  130130. };
  130131. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130132. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130133. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130134. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130135. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130136. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130137. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130138. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130139. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130140. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130141. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130142. 11,11,11,11,11,11,11,11,11,
  130143. };
  130144. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130145. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130146. 637.5, 892.5, 1147.5, 1402.5,
  130147. };
  130148. static long _vq_quantmap__44c3_s_p9_0[] = {
  130149. 11, 9, 7, 5, 3, 1, 0, 2,
  130150. 4, 6, 8, 10, 12,
  130151. };
  130152. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130153. _vq_quantthresh__44c3_s_p9_0,
  130154. _vq_quantmap__44c3_s_p9_0,
  130155. 13,
  130156. 13
  130157. };
  130158. static static_codebook _44c3_s_p9_0 = {
  130159. 2, 169,
  130160. _vq_lengthlist__44c3_s_p9_0,
  130161. 1, -514332672, 1627381760, 4, 0,
  130162. _vq_quantlist__44c3_s_p9_0,
  130163. NULL,
  130164. &_vq_auxt__44c3_s_p9_0,
  130165. NULL,
  130166. 0
  130167. };
  130168. static long _vq_quantlist__44c3_s_p9_1[] = {
  130169. 7,
  130170. 6,
  130171. 8,
  130172. 5,
  130173. 9,
  130174. 4,
  130175. 10,
  130176. 3,
  130177. 11,
  130178. 2,
  130179. 12,
  130180. 1,
  130181. 13,
  130182. 0,
  130183. 14,
  130184. };
  130185. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130186. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130187. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130188. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130189. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130190. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130191. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130192. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130193. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130194. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130195. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130196. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130197. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130198. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130199. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130200. 15,
  130201. };
  130202. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130203. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130204. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130205. };
  130206. static long _vq_quantmap__44c3_s_p9_1[] = {
  130207. 13, 11, 9, 7, 5, 3, 1, 0,
  130208. 2, 4, 6, 8, 10, 12, 14,
  130209. };
  130210. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130211. _vq_quantthresh__44c3_s_p9_1,
  130212. _vq_quantmap__44c3_s_p9_1,
  130213. 15,
  130214. 15
  130215. };
  130216. static static_codebook _44c3_s_p9_1 = {
  130217. 2, 225,
  130218. _vq_lengthlist__44c3_s_p9_1,
  130219. 1, -522338304, 1620115456, 4, 0,
  130220. _vq_quantlist__44c3_s_p9_1,
  130221. NULL,
  130222. &_vq_auxt__44c3_s_p9_1,
  130223. NULL,
  130224. 0
  130225. };
  130226. static long _vq_quantlist__44c3_s_p9_2[] = {
  130227. 8,
  130228. 7,
  130229. 9,
  130230. 6,
  130231. 10,
  130232. 5,
  130233. 11,
  130234. 4,
  130235. 12,
  130236. 3,
  130237. 13,
  130238. 2,
  130239. 14,
  130240. 1,
  130241. 15,
  130242. 0,
  130243. 16,
  130244. };
  130245. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130246. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130247. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130248. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130249. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130250. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130251. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130252. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130253. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130254. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130255. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130256. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130257. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130258. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130259. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130260. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130261. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130262. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130263. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130264. 10,
  130265. };
  130266. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130267. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130268. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130269. };
  130270. static long _vq_quantmap__44c3_s_p9_2[] = {
  130271. 15, 13, 11, 9, 7, 5, 3, 1,
  130272. 0, 2, 4, 6, 8, 10, 12, 14,
  130273. 16,
  130274. };
  130275. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130276. _vq_quantthresh__44c3_s_p9_2,
  130277. _vq_quantmap__44c3_s_p9_2,
  130278. 17,
  130279. 17
  130280. };
  130281. static static_codebook _44c3_s_p9_2 = {
  130282. 2, 289,
  130283. _vq_lengthlist__44c3_s_p9_2,
  130284. 1, -529530880, 1611661312, 5, 0,
  130285. _vq_quantlist__44c3_s_p9_2,
  130286. NULL,
  130287. &_vq_auxt__44c3_s_p9_2,
  130288. NULL,
  130289. 0
  130290. };
  130291. static long _huff_lengthlist__44c3_s_short[] = {
  130292. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130293. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130294. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130295. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130296. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130297. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130298. 6, 8, 9,11,
  130299. };
  130300. static static_codebook _huff_book__44c3_s_short = {
  130301. 2, 100,
  130302. _huff_lengthlist__44c3_s_short,
  130303. 0, 0, 0, 0, 0,
  130304. NULL,
  130305. NULL,
  130306. NULL,
  130307. NULL,
  130308. 0
  130309. };
  130310. static long _huff_lengthlist__44c4_s_long[] = {
  130311. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130312. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130313. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130314. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130315. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130316. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130317. 9, 8, 7, 7,
  130318. };
  130319. static static_codebook _huff_book__44c4_s_long = {
  130320. 2, 100,
  130321. _huff_lengthlist__44c4_s_long,
  130322. 0, 0, 0, 0, 0,
  130323. NULL,
  130324. NULL,
  130325. NULL,
  130326. NULL,
  130327. 0
  130328. };
  130329. static long _vq_quantlist__44c4_s_p1_0[] = {
  130330. 1,
  130331. 0,
  130332. 2,
  130333. };
  130334. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130335. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130336. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130341. 0, 0, 0, 6, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130346. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130381. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  130386. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  130391. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130393. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130398. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130426. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130427. 0, 0, 0, 0, 7, 8, 8, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130432. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130437. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130745. 0,
  130746. };
  130747. static float _vq_quantthresh__44c4_s_p1_0[] = {
  130748. -0.5, 0.5,
  130749. };
  130750. static long _vq_quantmap__44c4_s_p1_0[] = {
  130751. 1, 0, 2,
  130752. };
  130753. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  130754. _vq_quantthresh__44c4_s_p1_0,
  130755. _vq_quantmap__44c4_s_p1_0,
  130756. 3,
  130757. 3
  130758. };
  130759. static static_codebook _44c4_s_p1_0 = {
  130760. 8, 6561,
  130761. _vq_lengthlist__44c4_s_p1_0,
  130762. 1, -535822336, 1611661312, 2, 0,
  130763. _vq_quantlist__44c4_s_p1_0,
  130764. NULL,
  130765. &_vq_auxt__44c4_s_p1_0,
  130766. NULL,
  130767. 0
  130768. };
  130769. static long _vq_quantlist__44c4_s_p2_0[] = {
  130770. 2,
  130771. 1,
  130772. 3,
  130773. 0,
  130774. 4,
  130775. };
  130776. static long _vq_lengthlist__44c4_s_p2_0[] = {
  130777. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130778. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130779. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130780. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130781. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  130787. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130788. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130789. 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130795. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130796. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130803. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130804. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0,
  130817. };
  130818. static float _vq_quantthresh__44c4_s_p2_0[] = {
  130819. -1.5, -0.5, 0.5, 1.5,
  130820. };
  130821. static long _vq_quantmap__44c4_s_p2_0[] = {
  130822. 3, 1, 0, 2, 4,
  130823. };
  130824. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  130825. _vq_quantthresh__44c4_s_p2_0,
  130826. _vq_quantmap__44c4_s_p2_0,
  130827. 5,
  130828. 5
  130829. };
  130830. static static_codebook _44c4_s_p2_0 = {
  130831. 4, 625,
  130832. _vq_lengthlist__44c4_s_p2_0,
  130833. 1, -533725184, 1611661312, 3, 0,
  130834. _vq_quantlist__44c4_s_p2_0,
  130835. NULL,
  130836. &_vq_auxt__44c4_s_p2_0,
  130837. NULL,
  130838. 0
  130839. };
  130840. static long _vq_quantlist__44c4_s_p3_0[] = {
  130841. 2,
  130842. 1,
  130843. 3,
  130844. 0,
  130845. 4,
  130846. };
  130847. static long _vq_lengthlist__44c4_s_p3_0[] = {
  130848. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0,
  130888. };
  130889. static float _vq_quantthresh__44c4_s_p3_0[] = {
  130890. -1.5, -0.5, 0.5, 1.5,
  130891. };
  130892. static long _vq_quantmap__44c4_s_p3_0[] = {
  130893. 3, 1, 0, 2, 4,
  130894. };
  130895. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  130896. _vq_quantthresh__44c4_s_p3_0,
  130897. _vq_quantmap__44c4_s_p3_0,
  130898. 5,
  130899. 5
  130900. };
  130901. static static_codebook _44c4_s_p3_0 = {
  130902. 4, 625,
  130903. _vq_lengthlist__44c4_s_p3_0,
  130904. 1, -533725184, 1611661312, 3, 0,
  130905. _vq_quantlist__44c4_s_p3_0,
  130906. NULL,
  130907. &_vq_auxt__44c4_s_p3_0,
  130908. NULL,
  130909. 0
  130910. };
  130911. static long _vq_quantlist__44c4_s_p4_0[] = {
  130912. 4,
  130913. 3,
  130914. 5,
  130915. 2,
  130916. 6,
  130917. 1,
  130918. 7,
  130919. 0,
  130920. 8,
  130921. };
  130922. static long _vq_lengthlist__44c4_s_p4_0[] = {
  130923. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130924. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130925. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130926. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130927. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0,
  130929. };
  130930. static float _vq_quantthresh__44c4_s_p4_0[] = {
  130931. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130932. };
  130933. static long _vq_quantmap__44c4_s_p4_0[] = {
  130934. 7, 5, 3, 1, 0, 2, 4, 6,
  130935. 8,
  130936. };
  130937. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  130938. _vq_quantthresh__44c4_s_p4_0,
  130939. _vq_quantmap__44c4_s_p4_0,
  130940. 9,
  130941. 9
  130942. };
  130943. static static_codebook _44c4_s_p4_0 = {
  130944. 2, 81,
  130945. _vq_lengthlist__44c4_s_p4_0,
  130946. 1, -531628032, 1611661312, 4, 0,
  130947. _vq_quantlist__44c4_s_p4_0,
  130948. NULL,
  130949. &_vq_auxt__44c4_s_p4_0,
  130950. NULL,
  130951. 0
  130952. };
  130953. static long _vq_quantlist__44c4_s_p5_0[] = {
  130954. 4,
  130955. 3,
  130956. 5,
  130957. 2,
  130958. 6,
  130959. 1,
  130960. 7,
  130961. 0,
  130962. 8,
  130963. };
  130964. static long _vq_lengthlist__44c4_s_p5_0[] = {
  130965. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  130966. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  130967. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  130968. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  130969. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  130970. 10,
  130971. };
  130972. static float _vq_quantthresh__44c4_s_p5_0[] = {
  130973. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130974. };
  130975. static long _vq_quantmap__44c4_s_p5_0[] = {
  130976. 7, 5, 3, 1, 0, 2, 4, 6,
  130977. 8,
  130978. };
  130979. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  130980. _vq_quantthresh__44c4_s_p5_0,
  130981. _vq_quantmap__44c4_s_p5_0,
  130982. 9,
  130983. 9
  130984. };
  130985. static static_codebook _44c4_s_p5_0 = {
  130986. 2, 81,
  130987. _vq_lengthlist__44c4_s_p5_0,
  130988. 1, -531628032, 1611661312, 4, 0,
  130989. _vq_quantlist__44c4_s_p5_0,
  130990. NULL,
  130991. &_vq_auxt__44c4_s_p5_0,
  130992. NULL,
  130993. 0
  130994. };
  130995. static long _vq_quantlist__44c4_s_p6_0[] = {
  130996. 8,
  130997. 7,
  130998. 9,
  130999. 6,
  131000. 10,
  131001. 5,
  131002. 11,
  131003. 4,
  131004. 12,
  131005. 3,
  131006. 13,
  131007. 2,
  131008. 14,
  131009. 1,
  131010. 15,
  131011. 0,
  131012. 16,
  131013. };
  131014. static long _vq_lengthlist__44c4_s_p6_0[] = {
  131015. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  131016. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131017. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131018. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131019. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131020. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131021. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  131022. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131023. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131024. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131025. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  131026. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  131027. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  131028. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  131029. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  131030. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131031. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  131032. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  131033. 13,
  131034. };
  131035. static float _vq_quantthresh__44c4_s_p6_0[] = {
  131036. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131037. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131038. };
  131039. static long _vq_quantmap__44c4_s_p6_0[] = {
  131040. 15, 13, 11, 9, 7, 5, 3, 1,
  131041. 0, 2, 4, 6, 8, 10, 12, 14,
  131042. 16,
  131043. };
  131044. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131045. _vq_quantthresh__44c4_s_p6_0,
  131046. _vq_quantmap__44c4_s_p6_0,
  131047. 17,
  131048. 17
  131049. };
  131050. static static_codebook _44c4_s_p6_0 = {
  131051. 2, 289,
  131052. _vq_lengthlist__44c4_s_p6_0,
  131053. 1, -529530880, 1611661312, 5, 0,
  131054. _vq_quantlist__44c4_s_p6_0,
  131055. NULL,
  131056. &_vq_auxt__44c4_s_p6_0,
  131057. NULL,
  131058. 0
  131059. };
  131060. static long _vq_quantlist__44c4_s_p7_0[] = {
  131061. 1,
  131062. 0,
  131063. 2,
  131064. };
  131065. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131066. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131067. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131068. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131069. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131070. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131071. 10,
  131072. };
  131073. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131074. -5.5, 5.5,
  131075. };
  131076. static long _vq_quantmap__44c4_s_p7_0[] = {
  131077. 1, 0, 2,
  131078. };
  131079. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131080. _vq_quantthresh__44c4_s_p7_0,
  131081. _vq_quantmap__44c4_s_p7_0,
  131082. 3,
  131083. 3
  131084. };
  131085. static static_codebook _44c4_s_p7_0 = {
  131086. 4, 81,
  131087. _vq_lengthlist__44c4_s_p7_0,
  131088. 1, -529137664, 1618345984, 2, 0,
  131089. _vq_quantlist__44c4_s_p7_0,
  131090. NULL,
  131091. &_vq_auxt__44c4_s_p7_0,
  131092. NULL,
  131093. 0
  131094. };
  131095. static long _vq_quantlist__44c4_s_p7_1[] = {
  131096. 5,
  131097. 4,
  131098. 6,
  131099. 3,
  131100. 7,
  131101. 2,
  131102. 8,
  131103. 1,
  131104. 9,
  131105. 0,
  131106. 10,
  131107. };
  131108. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131109. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131110. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131111. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131112. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131113. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131114. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131115. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131116. 10,10,10, 8, 8, 8, 8, 9, 9,
  131117. };
  131118. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131119. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131120. 3.5, 4.5,
  131121. };
  131122. static long _vq_quantmap__44c4_s_p7_1[] = {
  131123. 9, 7, 5, 3, 1, 0, 2, 4,
  131124. 6, 8, 10,
  131125. };
  131126. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131127. _vq_quantthresh__44c4_s_p7_1,
  131128. _vq_quantmap__44c4_s_p7_1,
  131129. 11,
  131130. 11
  131131. };
  131132. static static_codebook _44c4_s_p7_1 = {
  131133. 2, 121,
  131134. _vq_lengthlist__44c4_s_p7_1,
  131135. 1, -531365888, 1611661312, 4, 0,
  131136. _vq_quantlist__44c4_s_p7_1,
  131137. NULL,
  131138. &_vq_auxt__44c4_s_p7_1,
  131139. NULL,
  131140. 0
  131141. };
  131142. static long _vq_quantlist__44c4_s_p8_0[] = {
  131143. 6,
  131144. 5,
  131145. 7,
  131146. 4,
  131147. 8,
  131148. 3,
  131149. 9,
  131150. 2,
  131151. 10,
  131152. 1,
  131153. 11,
  131154. 0,
  131155. 12,
  131156. };
  131157. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131158. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131159. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131160. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131161. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131162. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131163. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131164. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131165. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131166. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131167. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131168. 0,13,12,12,12,12,12,13,13,
  131169. };
  131170. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131171. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131172. 12.5, 17.5, 22.5, 27.5,
  131173. };
  131174. static long _vq_quantmap__44c4_s_p8_0[] = {
  131175. 11, 9, 7, 5, 3, 1, 0, 2,
  131176. 4, 6, 8, 10, 12,
  131177. };
  131178. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131179. _vq_quantthresh__44c4_s_p8_0,
  131180. _vq_quantmap__44c4_s_p8_0,
  131181. 13,
  131182. 13
  131183. };
  131184. static static_codebook _44c4_s_p8_0 = {
  131185. 2, 169,
  131186. _vq_lengthlist__44c4_s_p8_0,
  131187. 1, -526516224, 1616117760, 4, 0,
  131188. _vq_quantlist__44c4_s_p8_0,
  131189. NULL,
  131190. &_vq_auxt__44c4_s_p8_0,
  131191. NULL,
  131192. 0
  131193. };
  131194. static long _vq_quantlist__44c4_s_p8_1[] = {
  131195. 2,
  131196. 1,
  131197. 3,
  131198. 0,
  131199. 4,
  131200. };
  131201. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131202. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131203. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131204. };
  131205. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131206. -1.5, -0.5, 0.5, 1.5,
  131207. };
  131208. static long _vq_quantmap__44c4_s_p8_1[] = {
  131209. 3, 1, 0, 2, 4,
  131210. };
  131211. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131212. _vq_quantthresh__44c4_s_p8_1,
  131213. _vq_quantmap__44c4_s_p8_1,
  131214. 5,
  131215. 5
  131216. };
  131217. static static_codebook _44c4_s_p8_1 = {
  131218. 2, 25,
  131219. _vq_lengthlist__44c4_s_p8_1,
  131220. 1, -533725184, 1611661312, 3, 0,
  131221. _vq_quantlist__44c4_s_p8_1,
  131222. NULL,
  131223. &_vq_auxt__44c4_s_p8_1,
  131224. NULL,
  131225. 0
  131226. };
  131227. static long _vq_quantlist__44c4_s_p9_0[] = {
  131228. 6,
  131229. 5,
  131230. 7,
  131231. 4,
  131232. 8,
  131233. 3,
  131234. 9,
  131235. 2,
  131236. 10,
  131237. 1,
  131238. 11,
  131239. 0,
  131240. 12,
  131241. };
  131242. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131243. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131244. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131245. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131246. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131247. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131249. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131250. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131251. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131253. 12,12,12,12,12,12,12,12,12,
  131254. };
  131255. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131256. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131257. 787.5, 1102.5, 1417.5, 1732.5,
  131258. };
  131259. static long _vq_quantmap__44c4_s_p9_0[] = {
  131260. 11, 9, 7, 5, 3, 1, 0, 2,
  131261. 4, 6, 8, 10, 12,
  131262. };
  131263. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131264. _vq_quantthresh__44c4_s_p9_0,
  131265. _vq_quantmap__44c4_s_p9_0,
  131266. 13,
  131267. 13
  131268. };
  131269. static static_codebook _44c4_s_p9_0 = {
  131270. 2, 169,
  131271. _vq_lengthlist__44c4_s_p9_0,
  131272. 1, -513964032, 1628680192, 4, 0,
  131273. _vq_quantlist__44c4_s_p9_0,
  131274. NULL,
  131275. &_vq_auxt__44c4_s_p9_0,
  131276. NULL,
  131277. 0
  131278. };
  131279. static long _vq_quantlist__44c4_s_p9_1[] = {
  131280. 7,
  131281. 6,
  131282. 8,
  131283. 5,
  131284. 9,
  131285. 4,
  131286. 10,
  131287. 3,
  131288. 11,
  131289. 2,
  131290. 12,
  131291. 1,
  131292. 13,
  131293. 0,
  131294. 14,
  131295. };
  131296. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131297. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131298. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131299. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131300. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131301. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131302. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131303. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131304. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131305. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131306. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131307. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131308. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131309. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131310. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131311. 15,
  131312. };
  131313. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131314. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131315. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131316. };
  131317. static long _vq_quantmap__44c4_s_p9_1[] = {
  131318. 13, 11, 9, 7, 5, 3, 1, 0,
  131319. 2, 4, 6, 8, 10, 12, 14,
  131320. };
  131321. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131322. _vq_quantthresh__44c4_s_p9_1,
  131323. _vq_quantmap__44c4_s_p9_1,
  131324. 15,
  131325. 15
  131326. };
  131327. static static_codebook _44c4_s_p9_1 = {
  131328. 2, 225,
  131329. _vq_lengthlist__44c4_s_p9_1,
  131330. 1, -520986624, 1620377600, 4, 0,
  131331. _vq_quantlist__44c4_s_p9_1,
  131332. NULL,
  131333. &_vq_auxt__44c4_s_p9_1,
  131334. NULL,
  131335. 0
  131336. };
  131337. static long _vq_quantlist__44c4_s_p9_2[] = {
  131338. 10,
  131339. 9,
  131340. 11,
  131341. 8,
  131342. 12,
  131343. 7,
  131344. 13,
  131345. 6,
  131346. 14,
  131347. 5,
  131348. 15,
  131349. 4,
  131350. 16,
  131351. 3,
  131352. 17,
  131353. 2,
  131354. 18,
  131355. 1,
  131356. 19,
  131357. 0,
  131358. 20,
  131359. };
  131360. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131361. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131362. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131363. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131364. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131365. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131366. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131367. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131368. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131369. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131370. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131371. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131372. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131373. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131374. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131375. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131376. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131377. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131378. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131379. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131380. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131381. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131382. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131383. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131384. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131385. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131386. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131387. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131388. 10,10,10,10,10,10,10,10,10,
  131389. };
  131390. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131391. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131392. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131393. 6.5, 7.5, 8.5, 9.5,
  131394. };
  131395. static long _vq_quantmap__44c4_s_p9_2[] = {
  131396. 19, 17, 15, 13, 11, 9, 7, 5,
  131397. 3, 1, 0, 2, 4, 6, 8, 10,
  131398. 12, 14, 16, 18, 20,
  131399. };
  131400. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131401. _vq_quantthresh__44c4_s_p9_2,
  131402. _vq_quantmap__44c4_s_p9_2,
  131403. 21,
  131404. 21
  131405. };
  131406. static static_codebook _44c4_s_p9_2 = {
  131407. 2, 441,
  131408. _vq_lengthlist__44c4_s_p9_2,
  131409. 1, -529268736, 1611661312, 5, 0,
  131410. _vq_quantlist__44c4_s_p9_2,
  131411. NULL,
  131412. &_vq_auxt__44c4_s_p9_2,
  131413. NULL,
  131414. 0
  131415. };
  131416. static long _huff_lengthlist__44c4_s_short[] = {
  131417. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131418. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131419. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131420. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131421. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131422. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131423. 7, 9,12,17,
  131424. };
  131425. static static_codebook _huff_book__44c4_s_short = {
  131426. 2, 100,
  131427. _huff_lengthlist__44c4_s_short,
  131428. 0, 0, 0, 0, 0,
  131429. NULL,
  131430. NULL,
  131431. NULL,
  131432. NULL,
  131433. 0
  131434. };
  131435. static long _huff_lengthlist__44c5_s_long[] = {
  131436. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131437. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131438. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131439. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131440. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131441. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131442. 9, 8, 7, 7,
  131443. };
  131444. static static_codebook _huff_book__44c5_s_long = {
  131445. 2, 100,
  131446. _huff_lengthlist__44c5_s_long,
  131447. 0, 0, 0, 0, 0,
  131448. NULL,
  131449. NULL,
  131450. NULL,
  131451. NULL,
  131452. 0
  131453. };
  131454. static long _vq_quantlist__44c5_s_p1_0[] = {
  131455. 1,
  131456. 0,
  131457. 2,
  131458. };
  131459. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131460. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131461. 0, 0, 4, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131466. 0, 0, 0, 7, 8, 9, 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, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131471. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131506. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  131511. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  131516. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131551. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131552. 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131557. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131562. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131870. 0,
  131871. };
  131872. static float _vq_quantthresh__44c5_s_p1_0[] = {
  131873. -0.5, 0.5,
  131874. };
  131875. static long _vq_quantmap__44c5_s_p1_0[] = {
  131876. 1, 0, 2,
  131877. };
  131878. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  131879. _vq_quantthresh__44c5_s_p1_0,
  131880. _vq_quantmap__44c5_s_p1_0,
  131881. 3,
  131882. 3
  131883. };
  131884. static static_codebook _44c5_s_p1_0 = {
  131885. 8, 6561,
  131886. _vq_lengthlist__44c5_s_p1_0,
  131887. 1, -535822336, 1611661312, 2, 0,
  131888. _vq_quantlist__44c5_s_p1_0,
  131889. NULL,
  131890. &_vq_auxt__44c5_s_p1_0,
  131891. NULL,
  131892. 0
  131893. };
  131894. static long _vq_quantlist__44c5_s_p2_0[] = {
  131895. 2,
  131896. 1,
  131897. 3,
  131898. 0,
  131899. 4,
  131900. };
  131901. static long _vq_lengthlist__44c5_s_p2_0[] = {
  131902. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131903. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  131904. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131905. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  131906. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131911. 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  131912. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  131913. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  131914. 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  131920. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  131921. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 0, 0,
  131922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131927. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  131928. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  131929. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 0, 0, 0, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0,
  131942. };
  131943. static float _vq_quantthresh__44c5_s_p2_0[] = {
  131944. -1.5, -0.5, 0.5, 1.5,
  131945. };
  131946. static long _vq_quantmap__44c5_s_p2_0[] = {
  131947. 3, 1, 0, 2, 4,
  131948. };
  131949. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  131950. _vq_quantthresh__44c5_s_p2_0,
  131951. _vq_quantmap__44c5_s_p2_0,
  131952. 5,
  131953. 5
  131954. };
  131955. static static_codebook _44c5_s_p2_0 = {
  131956. 4, 625,
  131957. _vq_lengthlist__44c5_s_p2_0,
  131958. 1, -533725184, 1611661312, 3, 0,
  131959. _vq_quantlist__44c5_s_p2_0,
  131960. NULL,
  131961. &_vq_auxt__44c5_s_p2_0,
  131962. NULL,
  131963. 0
  131964. };
  131965. static long _vq_quantlist__44c5_s_p3_0[] = {
  131966. 2,
  131967. 1,
  131968. 3,
  131969. 0,
  131970. 4,
  131971. };
  131972. static long _vq_lengthlist__44c5_s_p3_0[] = {
  131973. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 5, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0,
  132013. };
  132014. static float _vq_quantthresh__44c5_s_p3_0[] = {
  132015. -1.5, -0.5, 0.5, 1.5,
  132016. };
  132017. static long _vq_quantmap__44c5_s_p3_0[] = {
  132018. 3, 1, 0, 2, 4,
  132019. };
  132020. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  132021. _vq_quantthresh__44c5_s_p3_0,
  132022. _vq_quantmap__44c5_s_p3_0,
  132023. 5,
  132024. 5
  132025. };
  132026. static static_codebook _44c5_s_p3_0 = {
  132027. 4, 625,
  132028. _vq_lengthlist__44c5_s_p3_0,
  132029. 1, -533725184, 1611661312, 3, 0,
  132030. _vq_quantlist__44c5_s_p3_0,
  132031. NULL,
  132032. &_vq_auxt__44c5_s_p3_0,
  132033. NULL,
  132034. 0
  132035. };
  132036. static long _vq_quantlist__44c5_s_p4_0[] = {
  132037. 4,
  132038. 3,
  132039. 5,
  132040. 2,
  132041. 6,
  132042. 1,
  132043. 7,
  132044. 0,
  132045. 8,
  132046. };
  132047. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132048. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132049. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132050. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132051. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132052. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132053. 0,
  132054. };
  132055. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132056. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132057. };
  132058. static long _vq_quantmap__44c5_s_p4_0[] = {
  132059. 7, 5, 3, 1, 0, 2, 4, 6,
  132060. 8,
  132061. };
  132062. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132063. _vq_quantthresh__44c5_s_p4_0,
  132064. _vq_quantmap__44c5_s_p4_0,
  132065. 9,
  132066. 9
  132067. };
  132068. static static_codebook _44c5_s_p4_0 = {
  132069. 2, 81,
  132070. _vq_lengthlist__44c5_s_p4_0,
  132071. 1, -531628032, 1611661312, 4, 0,
  132072. _vq_quantlist__44c5_s_p4_0,
  132073. NULL,
  132074. &_vq_auxt__44c5_s_p4_0,
  132075. NULL,
  132076. 0
  132077. };
  132078. static long _vq_quantlist__44c5_s_p5_0[] = {
  132079. 4,
  132080. 3,
  132081. 5,
  132082. 2,
  132083. 6,
  132084. 1,
  132085. 7,
  132086. 0,
  132087. 8,
  132088. };
  132089. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132090. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132091. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132092. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132093. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132094. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132095. 10,
  132096. };
  132097. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132098. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132099. };
  132100. static long _vq_quantmap__44c5_s_p5_0[] = {
  132101. 7, 5, 3, 1, 0, 2, 4, 6,
  132102. 8,
  132103. };
  132104. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132105. _vq_quantthresh__44c5_s_p5_0,
  132106. _vq_quantmap__44c5_s_p5_0,
  132107. 9,
  132108. 9
  132109. };
  132110. static static_codebook _44c5_s_p5_0 = {
  132111. 2, 81,
  132112. _vq_lengthlist__44c5_s_p5_0,
  132113. 1, -531628032, 1611661312, 4, 0,
  132114. _vq_quantlist__44c5_s_p5_0,
  132115. NULL,
  132116. &_vq_auxt__44c5_s_p5_0,
  132117. NULL,
  132118. 0
  132119. };
  132120. static long _vq_quantlist__44c5_s_p6_0[] = {
  132121. 8,
  132122. 7,
  132123. 9,
  132124. 6,
  132125. 10,
  132126. 5,
  132127. 11,
  132128. 4,
  132129. 12,
  132130. 3,
  132131. 13,
  132132. 2,
  132133. 14,
  132134. 1,
  132135. 15,
  132136. 0,
  132137. 16,
  132138. };
  132139. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132140. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132141. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132142. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132143. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132144. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132145. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132146. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132147. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132148. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132149. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132150. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132151. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132152. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132153. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132154. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132155. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132156. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132157. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132158. 13,
  132159. };
  132160. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132161. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132162. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132163. };
  132164. static long _vq_quantmap__44c5_s_p6_0[] = {
  132165. 15, 13, 11, 9, 7, 5, 3, 1,
  132166. 0, 2, 4, 6, 8, 10, 12, 14,
  132167. 16,
  132168. };
  132169. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132170. _vq_quantthresh__44c5_s_p6_0,
  132171. _vq_quantmap__44c5_s_p6_0,
  132172. 17,
  132173. 17
  132174. };
  132175. static static_codebook _44c5_s_p6_0 = {
  132176. 2, 289,
  132177. _vq_lengthlist__44c5_s_p6_0,
  132178. 1, -529530880, 1611661312, 5, 0,
  132179. _vq_quantlist__44c5_s_p6_0,
  132180. NULL,
  132181. &_vq_auxt__44c5_s_p6_0,
  132182. NULL,
  132183. 0
  132184. };
  132185. static long _vq_quantlist__44c5_s_p7_0[] = {
  132186. 1,
  132187. 0,
  132188. 2,
  132189. };
  132190. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132191. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132192. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132193. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132194. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132195. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132196. 10,
  132197. };
  132198. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132199. -5.5, 5.5,
  132200. };
  132201. static long _vq_quantmap__44c5_s_p7_0[] = {
  132202. 1, 0, 2,
  132203. };
  132204. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132205. _vq_quantthresh__44c5_s_p7_0,
  132206. _vq_quantmap__44c5_s_p7_0,
  132207. 3,
  132208. 3
  132209. };
  132210. static static_codebook _44c5_s_p7_0 = {
  132211. 4, 81,
  132212. _vq_lengthlist__44c5_s_p7_0,
  132213. 1, -529137664, 1618345984, 2, 0,
  132214. _vq_quantlist__44c5_s_p7_0,
  132215. NULL,
  132216. &_vq_auxt__44c5_s_p7_0,
  132217. NULL,
  132218. 0
  132219. };
  132220. static long _vq_quantlist__44c5_s_p7_1[] = {
  132221. 5,
  132222. 4,
  132223. 6,
  132224. 3,
  132225. 7,
  132226. 2,
  132227. 8,
  132228. 1,
  132229. 9,
  132230. 0,
  132231. 10,
  132232. };
  132233. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132234. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132235. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132236. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132237. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132238. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132239. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132240. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132241. 10,10,10, 8, 8, 8, 8, 8, 8,
  132242. };
  132243. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132244. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132245. 3.5, 4.5,
  132246. };
  132247. static long _vq_quantmap__44c5_s_p7_1[] = {
  132248. 9, 7, 5, 3, 1, 0, 2, 4,
  132249. 6, 8, 10,
  132250. };
  132251. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132252. _vq_quantthresh__44c5_s_p7_1,
  132253. _vq_quantmap__44c5_s_p7_1,
  132254. 11,
  132255. 11
  132256. };
  132257. static static_codebook _44c5_s_p7_1 = {
  132258. 2, 121,
  132259. _vq_lengthlist__44c5_s_p7_1,
  132260. 1, -531365888, 1611661312, 4, 0,
  132261. _vq_quantlist__44c5_s_p7_1,
  132262. NULL,
  132263. &_vq_auxt__44c5_s_p7_1,
  132264. NULL,
  132265. 0
  132266. };
  132267. static long _vq_quantlist__44c5_s_p8_0[] = {
  132268. 6,
  132269. 5,
  132270. 7,
  132271. 4,
  132272. 8,
  132273. 3,
  132274. 9,
  132275. 2,
  132276. 10,
  132277. 1,
  132278. 11,
  132279. 0,
  132280. 12,
  132281. };
  132282. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132283. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132284. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132285. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132286. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132287. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132288. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132289. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132290. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132291. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132292. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132293. 0,12,12,12,12,12,12,13,13,
  132294. };
  132295. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132296. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132297. 12.5, 17.5, 22.5, 27.5,
  132298. };
  132299. static long _vq_quantmap__44c5_s_p8_0[] = {
  132300. 11, 9, 7, 5, 3, 1, 0, 2,
  132301. 4, 6, 8, 10, 12,
  132302. };
  132303. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132304. _vq_quantthresh__44c5_s_p8_0,
  132305. _vq_quantmap__44c5_s_p8_0,
  132306. 13,
  132307. 13
  132308. };
  132309. static static_codebook _44c5_s_p8_0 = {
  132310. 2, 169,
  132311. _vq_lengthlist__44c5_s_p8_0,
  132312. 1, -526516224, 1616117760, 4, 0,
  132313. _vq_quantlist__44c5_s_p8_0,
  132314. NULL,
  132315. &_vq_auxt__44c5_s_p8_0,
  132316. NULL,
  132317. 0
  132318. };
  132319. static long _vq_quantlist__44c5_s_p8_1[] = {
  132320. 2,
  132321. 1,
  132322. 3,
  132323. 0,
  132324. 4,
  132325. };
  132326. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132327. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132328. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132329. };
  132330. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132331. -1.5, -0.5, 0.5, 1.5,
  132332. };
  132333. static long _vq_quantmap__44c5_s_p8_1[] = {
  132334. 3, 1, 0, 2, 4,
  132335. };
  132336. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132337. _vq_quantthresh__44c5_s_p8_1,
  132338. _vq_quantmap__44c5_s_p8_1,
  132339. 5,
  132340. 5
  132341. };
  132342. static static_codebook _44c5_s_p8_1 = {
  132343. 2, 25,
  132344. _vq_lengthlist__44c5_s_p8_1,
  132345. 1, -533725184, 1611661312, 3, 0,
  132346. _vq_quantlist__44c5_s_p8_1,
  132347. NULL,
  132348. &_vq_auxt__44c5_s_p8_1,
  132349. NULL,
  132350. 0
  132351. };
  132352. static long _vq_quantlist__44c5_s_p9_0[] = {
  132353. 7,
  132354. 6,
  132355. 8,
  132356. 5,
  132357. 9,
  132358. 4,
  132359. 10,
  132360. 3,
  132361. 11,
  132362. 2,
  132363. 12,
  132364. 1,
  132365. 13,
  132366. 0,
  132367. 14,
  132368. };
  132369. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132370. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132371. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132372. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132373. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132374. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132375. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132376. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132377. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132378. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132379. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132380. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132381. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132382. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132383. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132384. 12,
  132385. };
  132386. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132387. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132388. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132389. };
  132390. static long _vq_quantmap__44c5_s_p9_0[] = {
  132391. 13, 11, 9, 7, 5, 3, 1, 0,
  132392. 2, 4, 6, 8, 10, 12, 14,
  132393. };
  132394. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132395. _vq_quantthresh__44c5_s_p9_0,
  132396. _vq_quantmap__44c5_s_p9_0,
  132397. 15,
  132398. 15
  132399. };
  132400. static static_codebook _44c5_s_p9_0 = {
  132401. 2, 225,
  132402. _vq_lengthlist__44c5_s_p9_0,
  132403. 1, -512522752, 1628852224, 4, 0,
  132404. _vq_quantlist__44c5_s_p9_0,
  132405. NULL,
  132406. &_vq_auxt__44c5_s_p9_0,
  132407. NULL,
  132408. 0
  132409. };
  132410. static long _vq_quantlist__44c5_s_p9_1[] = {
  132411. 8,
  132412. 7,
  132413. 9,
  132414. 6,
  132415. 10,
  132416. 5,
  132417. 11,
  132418. 4,
  132419. 12,
  132420. 3,
  132421. 13,
  132422. 2,
  132423. 14,
  132424. 1,
  132425. 15,
  132426. 0,
  132427. 16,
  132428. };
  132429. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132430. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132431. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132432. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132433. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132434. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132435. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132436. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132437. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132438. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132439. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132440. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132441. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132442. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132443. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132444. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132445. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132446. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132447. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132448. 15,
  132449. };
  132450. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132451. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132452. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132453. };
  132454. static long _vq_quantmap__44c5_s_p9_1[] = {
  132455. 15, 13, 11, 9, 7, 5, 3, 1,
  132456. 0, 2, 4, 6, 8, 10, 12, 14,
  132457. 16,
  132458. };
  132459. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132460. _vq_quantthresh__44c5_s_p9_1,
  132461. _vq_quantmap__44c5_s_p9_1,
  132462. 17,
  132463. 17
  132464. };
  132465. static static_codebook _44c5_s_p9_1 = {
  132466. 2, 289,
  132467. _vq_lengthlist__44c5_s_p9_1,
  132468. 1, -520814592, 1620377600, 5, 0,
  132469. _vq_quantlist__44c5_s_p9_1,
  132470. NULL,
  132471. &_vq_auxt__44c5_s_p9_1,
  132472. NULL,
  132473. 0
  132474. };
  132475. static long _vq_quantlist__44c5_s_p9_2[] = {
  132476. 10,
  132477. 9,
  132478. 11,
  132479. 8,
  132480. 12,
  132481. 7,
  132482. 13,
  132483. 6,
  132484. 14,
  132485. 5,
  132486. 15,
  132487. 4,
  132488. 16,
  132489. 3,
  132490. 17,
  132491. 2,
  132492. 18,
  132493. 1,
  132494. 19,
  132495. 0,
  132496. 20,
  132497. };
  132498. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132499. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132500. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132501. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132502. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132503. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132504. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132505. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132506. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132507. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132508. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132509. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132510. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132511. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132512. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132513. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132514. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132515. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132516. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132517. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132518. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132519. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132520. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132521. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132522. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132523. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132524. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132525. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132526. 10,10,10,10,10,10,10,10,10,
  132527. };
  132528. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132529. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132530. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132531. 6.5, 7.5, 8.5, 9.5,
  132532. };
  132533. static long _vq_quantmap__44c5_s_p9_2[] = {
  132534. 19, 17, 15, 13, 11, 9, 7, 5,
  132535. 3, 1, 0, 2, 4, 6, 8, 10,
  132536. 12, 14, 16, 18, 20,
  132537. };
  132538. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132539. _vq_quantthresh__44c5_s_p9_2,
  132540. _vq_quantmap__44c5_s_p9_2,
  132541. 21,
  132542. 21
  132543. };
  132544. static static_codebook _44c5_s_p9_2 = {
  132545. 2, 441,
  132546. _vq_lengthlist__44c5_s_p9_2,
  132547. 1, -529268736, 1611661312, 5, 0,
  132548. _vq_quantlist__44c5_s_p9_2,
  132549. NULL,
  132550. &_vq_auxt__44c5_s_p9_2,
  132551. NULL,
  132552. 0
  132553. };
  132554. static long _huff_lengthlist__44c5_s_short[] = {
  132555. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132556. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132557. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132558. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132559. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132560. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132561. 6, 8,11,16,
  132562. };
  132563. static static_codebook _huff_book__44c5_s_short = {
  132564. 2, 100,
  132565. _huff_lengthlist__44c5_s_short,
  132566. 0, 0, 0, 0, 0,
  132567. NULL,
  132568. NULL,
  132569. NULL,
  132570. NULL,
  132571. 0
  132572. };
  132573. static long _huff_lengthlist__44c6_s_long[] = {
  132574. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  132575. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  132576. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  132577. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  132578. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  132579. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  132580. 11,10,10,12,
  132581. };
  132582. static static_codebook _huff_book__44c6_s_long = {
  132583. 2, 100,
  132584. _huff_lengthlist__44c6_s_long,
  132585. 0, 0, 0, 0, 0,
  132586. NULL,
  132587. NULL,
  132588. NULL,
  132589. NULL,
  132590. 0
  132591. };
  132592. static long _vq_quantlist__44c6_s_p1_0[] = {
  132593. 1,
  132594. 0,
  132595. 2,
  132596. };
  132597. static long _vq_lengthlist__44c6_s_p1_0[] = {
  132598. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  132599. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  132600. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  132601. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  132602. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  132603. 8,
  132604. };
  132605. static float _vq_quantthresh__44c6_s_p1_0[] = {
  132606. -0.5, 0.5,
  132607. };
  132608. static long _vq_quantmap__44c6_s_p1_0[] = {
  132609. 1, 0, 2,
  132610. };
  132611. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  132612. _vq_quantthresh__44c6_s_p1_0,
  132613. _vq_quantmap__44c6_s_p1_0,
  132614. 3,
  132615. 3
  132616. };
  132617. static static_codebook _44c6_s_p1_0 = {
  132618. 4, 81,
  132619. _vq_lengthlist__44c6_s_p1_0,
  132620. 1, -535822336, 1611661312, 2, 0,
  132621. _vq_quantlist__44c6_s_p1_0,
  132622. NULL,
  132623. &_vq_auxt__44c6_s_p1_0,
  132624. NULL,
  132625. 0
  132626. };
  132627. static long _vq_quantlist__44c6_s_p2_0[] = {
  132628. 2,
  132629. 1,
  132630. 3,
  132631. 0,
  132632. 4,
  132633. };
  132634. static long _vq_lengthlist__44c6_s_p2_0[] = {
  132635. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  132636. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  132637. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  132638. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  132639. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  132640. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  132641. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  132642. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  132643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132644. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  132645. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  132646. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  132647. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  132648. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  132649. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  132650. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  132651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132652. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  132653. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  132654. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  132655. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  132656. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  132657. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  132658. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132660. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  132661. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  132662. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  132663. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  132664. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  132665. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  132666. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  132671. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  132672. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  132673. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  132674. 13,
  132675. };
  132676. static float _vq_quantthresh__44c6_s_p2_0[] = {
  132677. -1.5, -0.5, 0.5, 1.5,
  132678. };
  132679. static long _vq_quantmap__44c6_s_p2_0[] = {
  132680. 3, 1, 0, 2, 4,
  132681. };
  132682. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  132683. _vq_quantthresh__44c6_s_p2_0,
  132684. _vq_quantmap__44c6_s_p2_0,
  132685. 5,
  132686. 5
  132687. };
  132688. static static_codebook _44c6_s_p2_0 = {
  132689. 4, 625,
  132690. _vq_lengthlist__44c6_s_p2_0,
  132691. 1, -533725184, 1611661312, 3, 0,
  132692. _vq_quantlist__44c6_s_p2_0,
  132693. NULL,
  132694. &_vq_auxt__44c6_s_p2_0,
  132695. NULL,
  132696. 0
  132697. };
  132698. static long _vq_quantlist__44c6_s_p3_0[] = {
  132699. 4,
  132700. 3,
  132701. 5,
  132702. 2,
  132703. 6,
  132704. 1,
  132705. 7,
  132706. 0,
  132707. 8,
  132708. };
  132709. static long _vq_lengthlist__44c6_s_p3_0[] = {
  132710. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132711. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  132712. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  132713. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  132714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132715. 0,
  132716. };
  132717. static float _vq_quantthresh__44c6_s_p3_0[] = {
  132718. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132719. };
  132720. static long _vq_quantmap__44c6_s_p3_0[] = {
  132721. 7, 5, 3, 1, 0, 2, 4, 6,
  132722. 8,
  132723. };
  132724. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  132725. _vq_quantthresh__44c6_s_p3_0,
  132726. _vq_quantmap__44c6_s_p3_0,
  132727. 9,
  132728. 9
  132729. };
  132730. static static_codebook _44c6_s_p3_0 = {
  132731. 2, 81,
  132732. _vq_lengthlist__44c6_s_p3_0,
  132733. 1, -531628032, 1611661312, 4, 0,
  132734. _vq_quantlist__44c6_s_p3_0,
  132735. NULL,
  132736. &_vq_auxt__44c6_s_p3_0,
  132737. NULL,
  132738. 0
  132739. };
  132740. static long _vq_quantlist__44c6_s_p4_0[] = {
  132741. 8,
  132742. 7,
  132743. 9,
  132744. 6,
  132745. 10,
  132746. 5,
  132747. 11,
  132748. 4,
  132749. 12,
  132750. 3,
  132751. 13,
  132752. 2,
  132753. 14,
  132754. 1,
  132755. 15,
  132756. 0,
  132757. 16,
  132758. };
  132759. static long _vq_lengthlist__44c6_s_p4_0[] = {
  132760. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  132761. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  132762. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  132763. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132764. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132765. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132766. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  132767. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  132768. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  132769. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  132770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132778. 0,
  132779. };
  132780. static float _vq_quantthresh__44c6_s_p4_0[] = {
  132781. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132782. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132783. };
  132784. static long _vq_quantmap__44c6_s_p4_0[] = {
  132785. 15, 13, 11, 9, 7, 5, 3, 1,
  132786. 0, 2, 4, 6, 8, 10, 12, 14,
  132787. 16,
  132788. };
  132789. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  132790. _vq_quantthresh__44c6_s_p4_0,
  132791. _vq_quantmap__44c6_s_p4_0,
  132792. 17,
  132793. 17
  132794. };
  132795. static static_codebook _44c6_s_p4_0 = {
  132796. 2, 289,
  132797. _vq_lengthlist__44c6_s_p4_0,
  132798. 1, -529530880, 1611661312, 5, 0,
  132799. _vq_quantlist__44c6_s_p4_0,
  132800. NULL,
  132801. &_vq_auxt__44c6_s_p4_0,
  132802. NULL,
  132803. 0
  132804. };
  132805. static long _vq_quantlist__44c6_s_p5_0[] = {
  132806. 1,
  132807. 0,
  132808. 2,
  132809. };
  132810. static long _vq_lengthlist__44c6_s_p5_0[] = {
  132811. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  132812. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  132813. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  132814. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  132815. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  132816. 12,
  132817. };
  132818. static float _vq_quantthresh__44c6_s_p5_0[] = {
  132819. -5.5, 5.5,
  132820. };
  132821. static long _vq_quantmap__44c6_s_p5_0[] = {
  132822. 1, 0, 2,
  132823. };
  132824. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  132825. _vq_quantthresh__44c6_s_p5_0,
  132826. _vq_quantmap__44c6_s_p5_0,
  132827. 3,
  132828. 3
  132829. };
  132830. static static_codebook _44c6_s_p5_0 = {
  132831. 4, 81,
  132832. _vq_lengthlist__44c6_s_p5_0,
  132833. 1, -529137664, 1618345984, 2, 0,
  132834. _vq_quantlist__44c6_s_p5_0,
  132835. NULL,
  132836. &_vq_auxt__44c6_s_p5_0,
  132837. NULL,
  132838. 0
  132839. };
  132840. static long _vq_quantlist__44c6_s_p5_1[] = {
  132841. 5,
  132842. 4,
  132843. 6,
  132844. 3,
  132845. 7,
  132846. 2,
  132847. 8,
  132848. 1,
  132849. 9,
  132850. 0,
  132851. 10,
  132852. };
  132853. static long _vq_lengthlist__44c6_s_p5_1[] = {
  132854. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  132855. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  132856. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  132857. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  132858. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  132859. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  132860. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  132861. 11,10,10, 7, 7, 8, 8, 8, 8,
  132862. };
  132863. static float _vq_quantthresh__44c6_s_p5_1[] = {
  132864. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132865. 3.5, 4.5,
  132866. };
  132867. static long _vq_quantmap__44c6_s_p5_1[] = {
  132868. 9, 7, 5, 3, 1, 0, 2, 4,
  132869. 6, 8, 10,
  132870. };
  132871. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  132872. _vq_quantthresh__44c6_s_p5_1,
  132873. _vq_quantmap__44c6_s_p5_1,
  132874. 11,
  132875. 11
  132876. };
  132877. static static_codebook _44c6_s_p5_1 = {
  132878. 2, 121,
  132879. _vq_lengthlist__44c6_s_p5_1,
  132880. 1, -531365888, 1611661312, 4, 0,
  132881. _vq_quantlist__44c6_s_p5_1,
  132882. NULL,
  132883. &_vq_auxt__44c6_s_p5_1,
  132884. NULL,
  132885. 0
  132886. };
  132887. static long _vq_quantlist__44c6_s_p6_0[] = {
  132888. 6,
  132889. 5,
  132890. 7,
  132891. 4,
  132892. 8,
  132893. 3,
  132894. 9,
  132895. 2,
  132896. 10,
  132897. 1,
  132898. 11,
  132899. 0,
  132900. 12,
  132901. };
  132902. static long _vq_lengthlist__44c6_s_p6_0[] = {
  132903. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  132904. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  132905. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  132906. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132907. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  132908. 12, 9, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  132909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132913. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132914. };
  132915. static float _vq_quantthresh__44c6_s_p6_0[] = {
  132916. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132917. 12.5, 17.5, 22.5, 27.5,
  132918. };
  132919. static long _vq_quantmap__44c6_s_p6_0[] = {
  132920. 11, 9, 7, 5, 3, 1, 0, 2,
  132921. 4, 6, 8, 10, 12,
  132922. };
  132923. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  132924. _vq_quantthresh__44c6_s_p6_0,
  132925. _vq_quantmap__44c6_s_p6_0,
  132926. 13,
  132927. 13
  132928. };
  132929. static static_codebook _44c6_s_p6_0 = {
  132930. 2, 169,
  132931. _vq_lengthlist__44c6_s_p6_0,
  132932. 1, -526516224, 1616117760, 4, 0,
  132933. _vq_quantlist__44c6_s_p6_0,
  132934. NULL,
  132935. &_vq_auxt__44c6_s_p6_0,
  132936. NULL,
  132937. 0
  132938. };
  132939. static long _vq_quantlist__44c6_s_p6_1[] = {
  132940. 2,
  132941. 1,
  132942. 3,
  132943. 0,
  132944. 4,
  132945. };
  132946. static long _vq_lengthlist__44c6_s_p6_1[] = {
  132947. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  132948. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132949. };
  132950. static float _vq_quantthresh__44c6_s_p6_1[] = {
  132951. -1.5, -0.5, 0.5, 1.5,
  132952. };
  132953. static long _vq_quantmap__44c6_s_p6_1[] = {
  132954. 3, 1, 0, 2, 4,
  132955. };
  132956. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  132957. _vq_quantthresh__44c6_s_p6_1,
  132958. _vq_quantmap__44c6_s_p6_1,
  132959. 5,
  132960. 5
  132961. };
  132962. static static_codebook _44c6_s_p6_1 = {
  132963. 2, 25,
  132964. _vq_lengthlist__44c6_s_p6_1,
  132965. 1, -533725184, 1611661312, 3, 0,
  132966. _vq_quantlist__44c6_s_p6_1,
  132967. NULL,
  132968. &_vq_auxt__44c6_s_p6_1,
  132969. NULL,
  132970. 0
  132971. };
  132972. static long _vq_quantlist__44c6_s_p7_0[] = {
  132973. 6,
  132974. 5,
  132975. 7,
  132976. 4,
  132977. 8,
  132978. 3,
  132979. 9,
  132980. 2,
  132981. 10,
  132982. 1,
  132983. 11,
  132984. 0,
  132985. 12,
  132986. };
  132987. static long _vq_lengthlist__44c6_s_p7_0[] = {
  132988. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  132989. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  132990. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  132991. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  132992. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  132993. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  132994. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  132995. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  132996. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  132997. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  132998. 20,13,13,13,13,13,13,14,14,
  132999. };
  133000. static float _vq_quantthresh__44c6_s_p7_0[] = {
  133001. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133002. 27.5, 38.5, 49.5, 60.5,
  133003. };
  133004. static long _vq_quantmap__44c6_s_p7_0[] = {
  133005. 11, 9, 7, 5, 3, 1, 0, 2,
  133006. 4, 6, 8, 10, 12,
  133007. };
  133008. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  133009. _vq_quantthresh__44c6_s_p7_0,
  133010. _vq_quantmap__44c6_s_p7_0,
  133011. 13,
  133012. 13
  133013. };
  133014. static static_codebook _44c6_s_p7_0 = {
  133015. 2, 169,
  133016. _vq_lengthlist__44c6_s_p7_0,
  133017. 1, -523206656, 1618345984, 4, 0,
  133018. _vq_quantlist__44c6_s_p7_0,
  133019. NULL,
  133020. &_vq_auxt__44c6_s_p7_0,
  133021. NULL,
  133022. 0
  133023. };
  133024. static long _vq_quantlist__44c6_s_p7_1[] = {
  133025. 5,
  133026. 4,
  133027. 6,
  133028. 3,
  133029. 7,
  133030. 2,
  133031. 8,
  133032. 1,
  133033. 9,
  133034. 0,
  133035. 10,
  133036. };
  133037. static long _vq_lengthlist__44c6_s_p7_1[] = {
  133038. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  133039. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  133040. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133041. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133042. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133043. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133044. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133045. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133046. };
  133047. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133048. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133049. 3.5, 4.5,
  133050. };
  133051. static long _vq_quantmap__44c6_s_p7_1[] = {
  133052. 9, 7, 5, 3, 1, 0, 2, 4,
  133053. 6, 8, 10,
  133054. };
  133055. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133056. _vq_quantthresh__44c6_s_p7_1,
  133057. _vq_quantmap__44c6_s_p7_1,
  133058. 11,
  133059. 11
  133060. };
  133061. static static_codebook _44c6_s_p7_1 = {
  133062. 2, 121,
  133063. _vq_lengthlist__44c6_s_p7_1,
  133064. 1, -531365888, 1611661312, 4, 0,
  133065. _vq_quantlist__44c6_s_p7_1,
  133066. NULL,
  133067. &_vq_auxt__44c6_s_p7_1,
  133068. NULL,
  133069. 0
  133070. };
  133071. static long _vq_quantlist__44c6_s_p8_0[] = {
  133072. 7,
  133073. 6,
  133074. 8,
  133075. 5,
  133076. 9,
  133077. 4,
  133078. 10,
  133079. 3,
  133080. 11,
  133081. 2,
  133082. 12,
  133083. 1,
  133084. 13,
  133085. 0,
  133086. 14,
  133087. };
  133088. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133089. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133090. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133091. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133092. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133093. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133094. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133095. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133096. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133097. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133098. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133099. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133100. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133101. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133102. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133103. 14,
  133104. };
  133105. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133106. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133107. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133108. };
  133109. static long _vq_quantmap__44c6_s_p8_0[] = {
  133110. 13, 11, 9, 7, 5, 3, 1, 0,
  133111. 2, 4, 6, 8, 10, 12, 14,
  133112. };
  133113. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133114. _vq_quantthresh__44c6_s_p8_0,
  133115. _vq_quantmap__44c6_s_p8_0,
  133116. 15,
  133117. 15
  133118. };
  133119. static static_codebook _44c6_s_p8_0 = {
  133120. 2, 225,
  133121. _vq_lengthlist__44c6_s_p8_0,
  133122. 1, -520986624, 1620377600, 4, 0,
  133123. _vq_quantlist__44c6_s_p8_0,
  133124. NULL,
  133125. &_vq_auxt__44c6_s_p8_0,
  133126. NULL,
  133127. 0
  133128. };
  133129. static long _vq_quantlist__44c6_s_p8_1[] = {
  133130. 10,
  133131. 9,
  133132. 11,
  133133. 8,
  133134. 12,
  133135. 7,
  133136. 13,
  133137. 6,
  133138. 14,
  133139. 5,
  133140. 15,
  133141. 4,
  133142. 16,
  133143. 3,
  133144. 17,
  133145. 2,
  133146. 18,
  133147. 1,
  133148. 19,
  133149. 0,
  133150. 20,
  133151. };
  133152. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133153. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133154. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133155. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133156. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133157. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133158. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133159. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133160. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133161. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133162. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133163. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133164. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133165. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133166. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133167. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133168. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133169. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133170. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133171. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133172. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133173. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133174. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133175. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133176. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133177. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133178. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133179. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133180. 10,10,10,10,10,10,10,10,10,
  133181. };
  133182. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133183. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133184. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133185. 6.5, 7.5, 8.5, 9.5,
  133186. };
  133187. static long _vq_quantmap__44c6_s_p8_1[] = {
  133188. 19, 17, 15, 13, 11, 9, 7, 5,
  133189. 3, 1, 0, 2, 4, 6, 8, 10,
  133190. 12, 14, 16, 18, 20,
  133191. };
  133192. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133193. _vq_quantthresh__44c6_s_p8_1,
  133194. _vq_quantmap__44c6_s_p8_1,
  133195. 21,
  133196. 21
  133197. };
  133198. static static_codebook _44c6_s_p8_1 = {
  133199. 2, 441,
  133200. _vq_lengthlist__44c6_s_p8_1,
  133201. 1, -529268736, 1611661312, 5, 0,
  133202. _vq_quantlist__44c6_s_p8_1,
  133203. NULL,
  133204. &_vq_auxt__44c6_s_p8_1,
  133205. NULL,
  133206. 0
  133207. };
  133208. static long _vq_quantlist__44c6_s_p9_0[] = {
  133209. 6,
  133210. 5,
  133211. 7,
  133212. 4,
  133213. 8,
  133214. 3,
  133215. 9,
  133216. 2,
  133217. 10,
  133218. 1,
  133219. 11,
  133220. 0,
  133221. 12,
  133222. };
  133223. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133224. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133225. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133226. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133227. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133228. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133229. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133230. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133231. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133232. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133233. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133234. 10,10,10,10,10,10,10,10,10,
  133235. };
  133236. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133237. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133238. 1592.5, 2229.5, 2866.5, 3503.5,
  133239. };
  133240. static long _vq_quantmap__44c6_s_p9_0[] = {
  133241. 11, 9, 7, 5, 3, 1, 0, 2,
  133242. 4, 6, 8, 10, 12,
  133243. };
  133244. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133245. _vq_quantthresh__44c6_s_p9_0,
  133246. _vq_quantmap__44c6_s_p9_0,
  133247. 13,
  133248. 13
  133249. };
  133250. static static_codebook _44c6_s_p9_0 = {
  133251. 2, 169,
  133252. _vq_lengthlist__44c6_s_p9_0,
  133253. 1, -511845376, 1630791680, 4, 0,
  133254. _vq_quantlist__44c6_s_p9_0,
  133255. NULL,
  133256. &_vq_auxt__44c6_s_p9_0,
  133257. NULL,
  133258. 0
  133259. };
  133260. static long _vq_quantlist__44c6_s_p9_1[] = {
  133261. 6,
  133262. 5,
  133263. 7,
  133264. 4,
  133265. 8,
  133266. 3,
  133267. 9,
  133268. 2,
  133269. 10,
  133270. 1,
  133271. 11,
  133272. 0,
  133273. 12,
  133274. };
  133275. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133276. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133277. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133278. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133279. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133280. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133281. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133282. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133283. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133284. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133285. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133286. 15,12,10,11,11,13,11,12,13,
  133287. };
  133288. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133289. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133290. 122.5, 171.5, 220.5, 269.5,
  133291. };
  133292. static long _vq_quantmap__44c6_s_p9_1[] = {
  133293. 11, 9, 7, 5, 3, 1, 0, 2,
  133294. 4, 6, 8, 10, 12,
  133295. };
  133296. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133297. _vq_quantthresh__44c6_s_p9_1,
  133298. _vq_quantmap__44c6_s_p9_1,
  133299. 13,
  133300. 13
  133301. };
  133302. static static_codebook _44c6_s_p9_1 = {
  133303. 2, 169,
  133304. _vq_lengthlist__44c6_s_p9_1,
  133305. 1, -518889472, 1622704128, 4, 0,
  133306. _vq_quantlist__44c6_s_p9_1,
  133307. NULL,
  133308. &_vq_auxt__44c6_s_p9_1,
  133309. NULL,
  133310. 0
  133311. };
  133312. static long _vq_quantlist__44c6_s_p9_2[] = {
  133313. 24,
  133314. 23,
  133315. 25,
  133316. 22,
  133317. 26,
  133318. 21,
  133319. 27,
  133320. 20,
  133321. 28,
  133322. 19,
  133323. 29,
  133324. 18,
  133325. 30,
  133326. 17,
  133327. 31,
  133328. 16,
  133329. 32,
  133330. 15,
  133331. 33,
  133332. 14,
  133333. 34,
  133334. 13,
  133335. 35,
  133336. 12,
  133337. 36,
  133338. 11,
  133339. 37,
  133340. 10,
  133341. 38,
  133342. 9,
  133343. 39,
  133344. 8,
  133345. 40,
  133346. 7,
  133347. 41,
  133348. 6,
  133349. 42,
  133350. 5,
  133351. 43,
  133352. 4,
  133353. 44,
  133354. 3,
  133355. 45,
  133356. 2,
  133357. 46,
  133358. 1,
  133359. 47,
  133360. 0,
  133361. 48,
  133362. };
  133363. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133364. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133365. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133366. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133367. 7,
  133368. };
  133369. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133370. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133371. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133372. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133373. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133374. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133375. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133376. };
  133377. static long _vq_quantmap__44c6_s_p9_2[] = {
  133378. 47, 45, 43, 41, 39, 37, 35, 33,
  133379. 31, 29, 27, 25, 23, 21, 19, 17,
  133380. 15, 13, 11, 9, 7, 5, 3, 1,
  133381. 0, 2, 4, 6, 8, 10, 12, 14,
  133382. 16, 18, 20, 22, 24, 26, 28, 30,
  133383. 32, 34, 36, 38, 40, 42, 44, 46,
  133384. 48,
  133385. };
  133386. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133387. _vq_quantthresh__44c6_s_p9_2,
  133388. _vq_quantmap__44c6_s_p9_2,
  133389. 49,
  133390. 49
  133391. };
  133392. static static_codebook _44c6_s_p9_2 = {
  133393. 1, 49,
  133394. _vq_lengthlist__44c6_s_p9_2,
  133395. 1, -526909440, 1611661312, 6, 0,
  133396. _vq_quantlist__44c6_s_p9_2,
  133397. NULL,
  133398. &_vq_auxt__44c6_s_p9_2,
  133399. NULL,
  133400. 0
  133401. };
  133402. static long _huff_lengthlist__44c6_s_short[] = {
  133403. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133404. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133405. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133406. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133407. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133408. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133409. 9,10,17,18,
  133410. };
  133411. static static_codebook _huff_book__44c6_s_short = {
  133412. 2, 100,
  133413. _huff_lengthlist__44c6_s_short,
  133414. 0, 0, 0, 0, 0,
  133415. NULL,
  133416. NULL,
  133417. NULL,
  133418. NULL,
  133419. 0
  133420. };
  133421. static long _huff_lengthlist__44c7_s_long[] = {
  133422. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133423. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133424. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133425. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133426. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133427. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133428. 11,10,10,12,
  133429. };
  133430. static static_codebook _huff_book__44c7_s_long = {
  133431. 2, 100,
  133432. _huff_lengthlist__44c7_s_long,
  133433. 0, 0, 0, 0, 0,
  133434. NULL,
  133435. NULL,
  133436. NULL,
  133437. NULL,
  133438. 0
  133439. };
  133440. static long _vq_quantlist__44c7_s_p1_0[] = {
  133441. 1,
  133442. 0,
  133443. 2,
  133444. };
  133445. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133446. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133447. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133448. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133449. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133450. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133451. 8,
  133452. };
  133453. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133454. -0.5, 0.5,
  133455. };
  133456. static long _vq_quantmap__44c7_s_p1_0[] = {
  133457. 1, 0, 2,
  133458. };
  133459. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133460. _vq_quantthresh__44c7_s_p1_0,
  133461. _vq_quantmap__44c7_s_p1_0,
  133462. 3,
  133463. 3
  133464. };
  133465. static static_codebook _44c7_s_p1_0 = {
  133466. 4, 81,
  133467. _vq_lengthlist__44c7_s_p1_0,
  133468. 1, -535822336, 1611661312, 2, 0,
  133469. _vq_quantlist__44c7_s_p1_0,
  133470. NULL,
  133471. &_vq_auxt__44c7_s_p1_0,
  133472. NULL,
  133473. 0
  133474. };
  133475. static long _vq_quantlist__44c7_s_p2_0[] = {
  133476. 2,
  133477. 1,
  133478. 3,
  133479. 0,
  133480. 4,
  133481. };
  133482. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133483. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133484. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133485. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133486. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133487. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133488. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133489. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133490. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133492. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133493. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133494. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133495. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133496. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133497. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133498. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133500. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133501. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133502. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133503. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133504. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133505. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133506. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133508. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133509. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133510. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133511. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133512. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133513. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133514. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133519. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133520. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133521. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133522. 13,
  133523. };
  133524. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133525. -1.5, -0.5, 0.5, 1.5,
  133526. };
  133527. static long _vq_quantmap__44c7_s_p2_0[] = {
  133528. 3, 1, 0, 2, 4,
  133529. };
  133530. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133531. _vq_quantthresh__44c7_s_p2_0,
  133532. _vq_quantmap__44c7_s_p2_0,
  133533. 5,
  133534. 5
  133535. };
  133536. static static_codebook _44c7_s_p2_0 = {
  133537. 4, 625,
  133538. _vq_lengthlist__44c7_s_p2_0,
  133539. 1, -533725184, 1611661312, 3, 0,
  133540. _vq_quantlist__44c7_s_p2_0,
  133541. NULL,
  133542. &_vq_auxt__44c7_s_p2_0,
  133543. NULL,
  133544. 0
  133545. };
  133546. static long _vq_quantlist__44c7_s_p3_0[] = {
  133547. 4,
  133548. 3,
  133549. 5,
  133550. 2,
  133551. 6,
  133552. 1,
  133553. 7,
  133554. 0,
  133555. 8,
  133556. };
  133557. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133558. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133559. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133560. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133561. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133563. 0,
  133564. };
  133565. static float _vq_quantthresh__44c7_s_p3_0[] = {
  133566. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133567. };
  133568. static long _vq_quantmap__44c7_s_p3_0[] = {
  133569. 7, 5, 3, 1, 0, 2, 4, 6,
  133570. 8,
  133571. };
  133572. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  133573. _vq_quantthresh__44c7_s_p3_0,
  133574. _vq_quantmap__44c7_s_p3_0,
  133575. 9,
  133576. 9
  133577. };
  133578. static static_codebook _44c7_s_p3_0 = {
  133579. 2, 81,
  133580. _vq_lengthlist__44c7_s_p3_0,
  133581. 1, -531628032, 1611661312, 4, 0,
  133582. _vq_quantlist__44c7_s_p3_0,
  133583. NULL,
  133584. &_vq_auxt__44c7_s_p3_0,
  133585. NULL,
  133586. 0
  133587. };
  133588. static long _vq_quantlist__44c7_s_p4_0[] = {
  133589. 8,
  133590. 7,
  133591. 9,
  133592. 6,
  133593. 10,
  133594. 5,
  133595. 11,
  133596. 4,
  133597. 12,
  133598. 3,
  133599. 13,
  133600. 2,
  133601. 14,
  133602. 1,
  133603. 15,
  133604. 0,
  133605. 16,
  133606. };
  133607. static long _vq_lengthlist__44c7_s_p4_0[] = {
  133608. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  133609. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  133610. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  133611. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  133612. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  133613. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  133614. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  133615. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133616. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  133617. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  133618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133626. 0,
  133627. };
  133628. static float _vq_quantthresh__44c7_s_p4_0[] = {
  133629. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133630. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133631. };
  133632. static long _vq_quantmap__44c7_s_p4_0[] = {
  133633. 15, 13, 11, 9, 7, 5, 3, 1,
  133634. 0, 2, 4, 6, 8, 10, 12, 14,
  133635. 16,
  133636. };
  133637. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  133638. _vq_quantthresh__44c7_s_p4_0,
  133639. _vq_quantmap__44c7_s_p4_0,
  133640. 17,
  133641. 17
  133642. };
  133643. static static_codebook _44c7_s_p4_0 = {
  133644. 2, 289,
  133645. _vq_lengthlist__44c7_s_p4_0,
  133646. 1, -529530880, 1611661312, 5, 0,
  133647. _vq_quantlist__44c7_s_p4_0,
  133648. NULL,
  133649. &_vq_auxt__44c7_s_p4_0,
  133650. NULL,
  133651. 0
  133652. };
  133653. static long _vq_quantlist__44c7_s_p5_0[] = {
  133654. 1,
  133655. 0,
  133656. 2,
  133657. };
  133658. static long _vq_lengthlist__44c7_s_p5_0[] = {
  133659. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  133660. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  133661. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  133662. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133663. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  133664. 12,
  133665. };
  133666. static float _vq_quantthresh__44c7_s_p5_0[] = {
  133667. -5.5, 5.5,
  133668. };
  133669. static long _vq_quantmap__44c7_s_p5_0[] = {
  133670. 1, 0, 2,
  133671. };
  133672. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  133673. _vq_quantthresh__44c7_s_p5_0,
  133674. _vq_quantmap__44c7_s_p5_0,
  133675. 3,
  133676. 3
  133677. };
  133678. static static_codebook _44c7_s_p5_0 = {
  133679. 4, 81,
  133680. _vq_lengthlist__44c7_s_p5_0,
  133681. 1, -529137664, 1618345984, 2, 0,
  133682. _vq_quantlist__44c7_s_p5_0,
  133683. NULL,
  133684. &_vq_auxt__44c7_s_p5_0,
  133685. NULL,
  133686. 0
  133687. };
  133688. static long _vq_quantlist__44c7_s_p5_1[] = {
  133689. 5,
  133690. 4,
  133691. 6,
  133692. 3,
  133693. 7,
  133694. 2,
  133695. 8,
  133696. 1,
  133697. 9,
  133698. 0,
  133699. 10,
  133700. };
  133701. static long _vq_lengthlist__44c7_s_p5_1[] = {
  133702. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133703. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  133704. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  133705. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  133706. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  133707. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  133708. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  133709. 11,11,11, 7, 7, 8, 8, 8, 8,
  133710. };
  133711. static float _vq_quantthresh__44c7_s_p5_1[] = {
  133712. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133713. 3.5, 4.5,
  133714. };
  133715. static long _vq_quantmap__44c7_s_p5_1[] = {
  133716. 9, 7, 5, 3, 1, 0, 2, 4,
  133717. 6, 8, 10,
  133718. };
  133719. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  133720. _vq_quantthresh__44c7_s_p5_1,
  133721. _vq_quantmap__44c7_s_p5_1,
  133722. 11,
  133723. 11
  133724. };
  133725. static static_codebook _44c7_s_p5_1 = {
  133726. 2, 121,
  133727. _vq_lengthlist__44c7_s_p5_1,
  133728. 1, -531365888, 1611661312, 4, 0,
  133729. _vq_quantlist__44c7_s_p5_1,
  133730. NULL,
  133731. &_vq_auxt__44c7_s_p5_1,
  133732. NULL,
  133733. 0
  133734. };
  133735. static long _vq_quantlist__44c7_s_p6_0[] = {
  133736. 6,
  133737. 5,
  133738. 7,
  133739. 4,
  133740. 8,
  133741. 3,
  133742. 9,
  133743. 2,
  133744. 10,
  133745. 1,
  133746. 11,
  133747. 0,
  133748. 12,
  133749. };
  133750. static long _vq_lengthlist__44c7_s_p6_0[] = {
  133751. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  133752. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  133753. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  133754. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  133755. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  133756. 12, 9, 9,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0,
  133757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133761. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133762. };
  133763. static float _vq_quantthresh__44c7_s_p6_0[] = {
  133764. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133765. 12.5, 17.5, 22.5, 27.5,
  133766. };
  133767. static long _vq_quantmap__44c7_s_p6_0[] = {
  133768. 11, 9, 7, 5, 3, 1, 0, 2,
  133769. 4, 6, 8, 10, 12,
  133770. };
  133771. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  133772. _vq_quantthresh__44c7_s_p6_0,
  133773. _vq_quantmap__44c7_s_p6_0,
  133774. 13,
  133775. 13
  133776. };
  133777. static static_codebook _44c7_s_p6_0 = {
  133778. 2, 169,
  133779. _vq_lengthlist__44c7_s_p6_0,
  133780. 1, -526516224, 1616117760, 4, 0,
  133781. _vq_quantlist__44c7_s_p6_0,
  133782. NULL,
  133783. &_vq_auxt__44c7_s_p6_0,
  133784. NULL,
  133785. 0
  133786. };
  133787. static long _vq_quantlist__44c7_s_p6_1[] = {
  133788. 2,
  133789. 1,
  133790. 3,
  133791. 0,
  133792. 4,
  133793. };
  133794. static long _vq_lengthlist__44c7_s_p6_1[] = {
  133795. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133796. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133797. };
  133798. static float _vq_quantthresh__44c7_s_p6_1[] = {
  133799. -1.5, -0.5, 0.5, 1.5,
  133800. };
  133801. static long _vq_quantmap__44c7_s_p6_1[] = {
  133802. 3, 1, 0, 2, 4,
  133803. };
  133804. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  133805. _vq_quantthresh__44c7_s_p6_1,
  133806. _vq_quantmap__44c7_s_p6_1,
  133807. 5,
  133808. 5
  133809. };
  133810. static static_codebook _44c7_s_p6_1 = {
  133811. 2, 25,
  133812. _vq_lengthlist__44c7_s_p6_1,
  133813. 1, -533725184, 1611661312, 3, 0,
  133814. _vq_quantlist__44c7_s_p6_1,
  133815. NULL,
  133816. &_vq_auxt__44c7_s_p6_1,
  133817. NULL,
  133818. 0
  133819. };
  133820. static long _vq_quantlist__44c7_s_p7_0[] = {
  133821. 6,
  133822. 5,
  133823. 7,
  133824. 4,
  133825. 8,
  133826. 3,
  133827. 9,
  133828. 2,
  133829. 10,
  133830. 1,
  133831. 11,
  133832. 0,
  133833. 12,
  133834. };
  133835. static long _vq_lengthlist__44c7_s_p7_0[] = {
  133836. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  133837. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  133838. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  133839. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  133840. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  133841. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  133842. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  133843. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  133844. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  133845. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  133846. 19,13,13,13,13,14,14,15,15,
  133847. };
  133848. static float _vq_quantthresh__44c7_s_p7_0[] = {
  133849. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133850. 27.5, 38.5, 49.5, 60.5,
  133851. };
  133852. static long _vq_quantmap__44c7_s_p7_0[] = {
  133853. 11, 9, 7, 5, 3, 1, 0, 2,
  133854. 4, 6, 8, 10, 12,
  133855. };
  133856. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  133857. _vq_quantthresh__44c7_s_p7_0,
  133858. _vq_quantmap__44c7_s_p7_0,
  133859. 13,
  133860. 13
  133861. };
  133862. static static_codebook _44c7_s_p7_0 = {
  133863. 2, 169,
  133864. _vq_lengthlist__44c7_s_p7_0,
  133865. 1, -523206656, 1618345984, 4, 0,
  133866. _vq_quantlist__44c7_s_p7_0,
  133867. NULL,
  133868. &_vq_auxt__44c7_s_p7_0,
  133869. NULL,
  133870. 0
  133871. };
  133872. static long _vq_quantlist__44c7_s_p7_1[] = {
  133873. 5,
  133874. 4,
  133875. 6,
  133876. 3,
  133877. 7,
  133878. 2,
  133879. 8,
  133880. 1,
  133881. 9,
  133882. 0,
  133883. 10,
  133884. };
  133885. static long _vq_lengthlist__44c7_s_p7_1[] = {
  133886. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  133887. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  133888. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  133889. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133890. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  133891. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  133892. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  133893. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  133894. };
  133895. static float _vq_quantthresh__44c7_s_p7_1[] = {
  133896. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133897. 3.5, 4.5,
  133898. };
  133899. static long _vq_quantmap__44c7_s_p7_1[] = {
  133900. 9, 7, 5, 3, 1, 0, 2, 4,
  133901. 6, 8, 10,
  133902. };
  133903. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  133904. _vq_quantthresh__44c7_s_p7_1,
  133905. _vq_quantmap__44c7_s_p7_1,
  133906. 11,
  133907. 11
  133908. };
  133909. static static_codebook _44c7_s_p7_1 = {
  133910. 2, 121,
  133911. _vq_lengthlist__44c7_s_p7_1,
  133912. 1, -531365888, 1611661312, 4, 0,
  133913. _vq_quantlist__44c7_s_p7_1,
  133914. NULL,
  133915. &_vq_auxt__44c7_s_p7_1,
  133916. NULL,
  133917. 0
  133918. };
  133919. static long _vq_quantlist__44c7_s_p8_0[] = {
  133920. 7,
  133921. 6,
  133922. 8,
  133923. 5,
  133924. 9,
  133925. 4,
  133926. 10,
  133927. 3,
  133928. 11,
  133929. 2,
  133930. 12,
  133931. 1,
  133932. 13,
  133933. 0,
  133934. 14,
  133935. };
  133936. static long _vq_lengthlist__44c7_s_p8_0[] = {
  133937. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  133938. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  133939. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  133940. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  133941. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  133942. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  133943. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  133944. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  133945. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  133946. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  133947. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  133948. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  133949. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  133950. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  133951. 14,
  133952. };
  133953. static float _vq_quantthresh__44c7_s_p8_0[] = {
  133954. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133955. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133956. };
  133957. static long _vq_quantmap__44c7_s_p8_0[] = {
  133958. 13, 11, 9, 7, 5, 3, 1, 0,
  133959. 2, 4, 6, 8, 10, 12, 14,
  133960. };
  133961. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  133962. _vq_quantthresh__44c7_s_p8_0,
  133963. _vq_quantmap__44c7_s_p8_0,
  133964. 15,
  133965. 15
  133966. };
  133967. static static_codebook _44c7_s_p8_0 = {
  133968. 2, 225,
  133969. _vq_lengthlist__44c7_s_p8_0,
  133970. 1, -520986624, 1620377600, 4, 0,
  133971. _vq_quantlist__44c7_s_p8_0,
  133972. NULL,
  133973. &_vq_auxt__44c7_s_p8_0,
  133974. NULL,
  133975. 0
  133976. };
  133977. static long _vq_quantlist__44c7_s_p8_1[] = {
  133978. 10,
  133979. 9,
  133980. 11,
  133981. 8,
  133982. 12,
  133983. 7,
  133984. 13,
  133985. 6,
  133986. 14,
  133987. 5,
  133988. 15,
  133989. 4,
  133990. 16,
  133991. 3,
  133992. 17,
  133993. 2,
  133994. 18,
  133995. 1,
  133996. 19,
  133997. 0,
  133998. 20,
  133999. };
  134000. static long _vq_lengthlist__44c7_s_p8_1[] = {
  134001. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134002. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134003. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134004. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134005. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134006. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134007. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134008. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134009. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134010. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134011. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  134012. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  134013. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  134014. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  134015. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  134016. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  134017. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  134018. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  134019. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  134020. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  134021. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  134022. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  134023. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  134024. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  134025. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  134026. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  134027. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  134028. 10,10,10,10,10,10,10,10,10,
  134029. };
  134030. static float _vq_quantthresh__44c7_s_p8_1[] = {
  134031. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134032. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134033. 6.5, 7.5, 8.5, 9.5,
  134034. };
  134035. static long _vq_quantmap__44c7_s_p8_1[] = {
  134036. 19, 17, 15, 13, 11, 9, 7, 5,
  134037. 3, 1, 0, 2, 4, 6, 8, 10,
  134038. 12, 14, 16, 18, 20,
  134039. };
  134040. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134041. _vq_quantthresh__44c7_s_p8_1,
  134042. _vq_quantmap__44c7_s_p8_1,
  134043. 21,
  134044. 21
  134045. };
  134046. static static_codebook _44c7_s_p8_1 = {
  134047. 2, 441,
  134048. _vq_lengthlist__44c7_s_p8_1,
  134049. 1, -529268736, 1611661312, 5, 0,
  134050. _vq_quantlist__44c7_s_p8_1,
  134051. NULL,
  134052. &_vq_auxt__44c7_s_p8_1,
  134053. NULL,
  134054. 0
  134055. };
  134056. static long _vq_quantlist__44c7_s_p9_0[] = {
  134057. 6,
  134058. 5,
  134059. 7,
  134060. 4,
  134061. 8,
  134062. 3,
  134063. 9,
  134064. 2,
  134065. 10,
  134066. 1,
  134067. 11,
  134068. 0,
  134069. 12,
  134070. };
  134071. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134072. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134073. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134074. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134075. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134076. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134077. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134078. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134079. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134080. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134081. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134082. 11,11,11,11,11,11,11,11,11,
  134083. };
  134084. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134085. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134086. 1592.5, 2229.5, 2866.5, 3503.5,
  134087. };
  134088. static long _vq_quantmap__44c7_s_p9_0[] = {
  134089. 11, 9, 7, 5, 3, 1, 0, 2,
  134090. 4, 6, 8, 10, 12,
  134091. };
  134092. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134093. _vq_quantthresh__44c7_s_p9_0,
  134094. _vq_quantmap__44c7_s_p9_0,
  134095. 13,
  134096. 13
  134097. };
  134098. static static_codebook _44c7_s_p9_0 = {
  134099. 2, 169,
  134100. _vq_lengthlist__44c7_s_p9_0,
  134101. 1, -511845376, 1630791680, 4, 0,
  134102. _vq_quantlist__44c7_s_p9_0,
  134103. NULL,
  134104. &_vq_auxt__44c7_s_p9_0,
  134105. NULL,
  134106. 0
  134107. };
  134108. static long _vq_quantlist__44c7_s_p9_1[] = {
  134109. 6,
  134110. 5,
  134111. 7,
  134112. 4,
  134113. 8,
  134114. 3,
  134115. 9,
  134116. 2,
  134117. 10,
  134118. 1,
  134119. 11,
  134120. 0,
  134121. 12,
  134122. };
  134123. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134124. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134125. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134126. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134127. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134128. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134129. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134130. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134131. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134132. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134133. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134134. 15,11,11,10,10,12,12,12,12,
  134135. };
  134136. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134137. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134138. 122.5, 171.5, 220.5, 269.5,
  134139. };
  134140. static long _vq_quantmap__44c7_s_p9_1[] = {
  134141. 11, 9, 7, 5, 3, 1, 0, 2,
  134142. 4, 6, 8, 10, 12,
  134143. };
  134144. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134145. _vq_quantthresh__44c7_s_p9_1,
  134146. _vq_quantmap__44c7_s_p9_1,
  134147. 13,
  134148. 13
  134149. };
  134150. static static_codebook _44c7_s_p9_1 = {
  134151. 2, 169,
  134152. _vq_lengthlist__44c7_s_p9_1,
  134153. 1, -518889472, 1622704128, 4, 0,
  134154. _vq_quantlist__44c7_s_p9_1,
  134155. NULL,
  134156. &_vq_auxt__44c7_s_p9_1,
  134157. NULL,
  134158. 0
  134159. };
  134160. static long _vq_quantlist__44c7_s_p9_2[] = {
  134161. 24,
  134162. 23,
  134163. 25,
  134164. 22,
  134165. 26,
  134166. 21,
  134167. 27,
  134168. 20,
  134169. 28,
  134170. 19,
  134171. 29,
  134172. 18,
  134173. 30,
  134174. 17,
  134175. 31,
  134176. 16,
  134177. 32,
  134178. 15,
  134179. 33,
  134180. 14,
  134181. 34,
  134182. 13,
  134183. 35,
  134184. 12,
  134185. 36,
  134186. 11,
  134187. 37,
  134188. 10,
  134189. 38,
  134190. 9,
  134191. 39,
  134192. 8,
  134193. 40,
  134194. 7,
  134195. 41,
  134196. 6,
  134197. 42,
  134198. 5,
  134199. 43,
  134200. 4,
  134201. 44,
  134202. 3,
  134203. 45,
  134204. 2,
  134205. 46,
  134206. 1,
  134207. 47,
  134208. 0,
  134209. 48,
  134210. };
  134211. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134212. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134213. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134214. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134215. 7,
  134216. };
  134217. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134218. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134219. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134220. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134221. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134222. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134223. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134224. };
  134225. static long _vq_quantmap__44c7_s_p9_2[] = {
  134226. 47, 45, 43, 41, 39, 37, 35, 33,
  134227. 31, 29, 27, 25, 23, 21, 19, 17,
  134228. 15, 13, 11, 9, 7, 5, 3, 1,
  134229. 0, 2, 4, 6, 8, 10, 12, 14,
  134230. 16, 18, 20, 22, 24, 26, 28, 30,
  134231. 32, 34, 36, 38, 40, 42, 44, 46,
  134232. 48,
  134233. };
  134234. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134235. _vq_quantthresh__44c7_s_p9_2,
  134236. _vq_quantmap__44c7_s_p9_2,
  134237. 49,
  134238. 49
  134239. };
  134240. static static_codebook _44c7_s_p9_2 = {
  134241. 1, 49,
  134242. _vq_lengthlist__44c7_s_p9_2,
  134243. 1, -526909440, 1611661312, 6, 0,
  134244. _vq_quantlist__44c7_s_p9_2,
  134245. NULL,
  134246. &_vq_auxt__44c7_s_p9_2,
  134247. NULL,
  134248. 0
  134249. };
  134250. static long _huff_lengthlist__44c7_s_short[] = {
  134251. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134252. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134253. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134254. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134255. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134256. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134257. 10, 9,11,14,
  134258. };
  134259. static static_codebook _huff_book__44c7_s_short = {
  134260. 2, 100,
  134261. _huff_lengthlist__44c7_s_short,
  134262. 0, 0, 0, 0, 0,
  134263. NULL,
  134264. NULL,
  134265. NULL,
  134266. NULL,
  134267. 0
  134268. };
  134269. static long _huff_lengthlist__44c8_s_long[] = {
  134270. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134271. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134272. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134273. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134274. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134275. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134276. 11, 9, 9,10,
  134277. };
  134278. static static_codebook _huff_book__44c8_s_long = {
  134279. 2, 100,
  134280. _huff_lengthlist__44c8_s_long,
  134281. 0, 0, 0, 0, 0,
  134282. NULL,
  134283. NULL,
  134284. NULL,
  134285. NULL,
  134286. 0
  134287. };
  134288. static long _vq_quantlist__44c8_s_p1_0[] = {
  134289. 1,
  134290. 0,
  134291. 2,
  134292. };
  134293. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134294. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134295. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134296. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134297. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134298. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134299. 8,
  134300. };
  134301. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134302. -0.5, 0.5,
  134303. };
  134304. static long _vq_quantmap__44c8_s_p1_0[] = {
  134305. 1, 0, 2,
  134306. };
  134307. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134308. _vq_quantthresh__44c8_s_p1_0,
  134309. _vq_quantmap__44c8_s_p1_0,
  134310. 3,
  134311. 3
  134312. };
  134313. static static_codebook _44c8_s_p1_0 = {
  134314. 4, 81,
  134315. _vq_lengthlist__44c8_s_p1_0,
  134316. 1, -535822336, 1611661312, 2, 0,
  134317. _vq_quantlist__44c8_s_p1_0,
  134318. NULL,
  134319. &_vq_auxt__44c8_s_p1_0,
  134320. NULL,
  134321. 0
  134322. };
  134323. static long _vq_quantlist__44c8_s_p2_0[] = {
  134324. 2,
  134325. 1,
  134326. 3,
  134327. 0,
  134328. 4,
  134329. };
  134330. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134331. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134332. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134333. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134334. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134335. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134336. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134337. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134338. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134340. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134341. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134342. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134343. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134344. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134345. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134346. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134348. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134349. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134350. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134351. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134352. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134353. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134354. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134356. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134357. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134358. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134359. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134360. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134361. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134362. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134367. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134368. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134369. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134370. 13,
  134371. };
  134372. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134373. -1.5, -0.5, 0.5, 1.5,
  134374. };
  134375. static long _vq_quantmap__44c8_s_p2_0[] = {
  134376. 3, 1, 0, 2, 4,
  134377. };
  134378. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134379. _vq_quantthresh__44c8_s_p2_0,
  134380. _vq_quantmap__44c8_s_p2_0,
  134381. 5,
  134382. 5
  134383. };
  134384. static static_codebook _44c8_s_p2_0 = {
  134385. 4, 625,
  134386. _vq_lengthlist__44c8_s_p2_0,
  134387. 1, -533725184, 1611661312, 3, 0,
  134388. _vq_quantlist__44c8_s_p2_0,
  134389. NULL,
  134390. &_vq_auxt__44c8_s_p2_0,
  134391. NULL,
  134392. 0
  134393. };
  134394. static long _vq_quantlist__44c8_s_p3_0[] = {
  134395. 4,
  134396. 3,
  134397. 5,
  134398. 2,
  134399. 6,
  134400. 1,
  134401. 7,
  134402. 0,
  134403. 8,
  134404. };
  134405. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134406. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134407. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134408. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134409. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134411. 0,
  134412. };
  134413. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134414. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134415. };
  134416. static long _vq_quantmap__44c8_s_p3_0[] = {
  134417. 7, 5, 3, 1, 0, 2, 4, 6,
  134418. 8,
  134419. };
  134420. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134421. _vq_quantthresh__44c8_s_p3_0,
  134422. _vq_quantmap__44c8_s_p3_0,
  134423. 9,
  134424. 9
  134425. };
  134426. static static_codebook _44c8_s_p3_0 = {
  134427. 2, 81,
  134428. _vq_lengthlist__44c8_s_p3_0,
  134429. 1, -531628032, 1611661312, 4, 0,
  134430. _vq_quantlist__44c8_s_p3_0,
  134431. NULL,
  134432. &_vq_auxt__44c8_s_p3_0,
  134433. NULL,
  134434. 0
  134435. };
  134436. static long _vq_quantlist__44c8_s_p4_0[] = {
  134437. 8,
  134438. 7,
  134439. 9,
  134440. 6,
  134441. 10,
  134442. 5,
  134443. 11,
  134444. 4,
  134445. 12,
  134446. 3,
  134447. 13,
  134448. 2,
  134449. 14,
  134450. 1,
  134451. 15,
  134452. 0,
  134453. 16,
  134454. };
  134455. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134456. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134457. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134458. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134459. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134460. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134461. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134462. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134463. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134464. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134465. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134474. 0,
  134475. };
  134476. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134477. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134478. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134479. };
  134480. static long _vq_quantmap__44c8_s_p4_0[] = {
  134481. 15, 13, 11, 9, 7, 5, 3, 1,
  134482. 0, 2, 4, 6, 8, 10, 12, 14,
  134483. 16,
  134484. };
  134485. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134486. _vq_quantthresh__44c8_s_p4_0,
  134487. _vq_quantmap__44c8_s_p4_0,
  134488. 17,
  134489. 17
  134490. };
  134491. static static_codebook _44c8_s_p4_0 = {
  134492. 2, 289,
  134493. _vq_lengthlist__44c8_s_p4_0,
  134494. 1, -529530880, 1611661312, 5, 0,
  134495. _vq_quantlist__44c8_s_p4_0,
  134496. NULL,
  134497. &_vq_auxt__44c8_s_p4_0,
  134498. NULL,
  134499. 0
  134500. };
  134501. static long _vq_quantlist__44c8_s_p5_0[] = {
  134502. 1,
  134503. 0,
  134504. 2,
  134505. };
  134506. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134507. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134508. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134509. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134510. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134511. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134512. 12,
  134513. };
  134514. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134515. -5.5, 5.5,
  134516. };
  134517. static long _vq_quantmap__44c8_s_p5_0[] = {
  134518. 1, 0, 2,
  134519. };
  134520. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134521. _vq_quantthresh__44c8_s_p5_0,
  134522. _vq_quantmap__44c8_s_p5_0,
  134523. 3,
  134524. 3
  134525. };
  134526. static static_codebook _44c8_s_p5_0 = {
  134527. 4, 81,
  134528. _vq_lengthlist__44c8_s_p5_0,
  134529. 1, -529137664, 1618345984, 2, 0,
  134530. _vq_quantlist__44c8_s_p5_0,
  134531. NULL,
  134532. &_vq_auxt__44c8_s_p5_0,
  134533. NULL,
  134534. 0
  134535. };
  134536. static long _vq_quantlist__44c8_s_p5_1[] = {
  134537. 5,
  134538. 4,
  134539. 6,
  134540. 3,
  134541. 7,
  134542. 2,
  134543. 8,
  134544. 1,
  134545. 9,
  134546. 0,
  134547. 10,
  134548. };
  134549. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134550. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134551. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134552. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134553. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134554. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134555. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134556. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134557. 11,11,11, 7, 7, 7, 7, 8, 8,
  134558. };
  134559. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134560. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134561. 3.5, 4.5,
  134562. };
  134563. static long _vq_quantmap__44c8_s_p5_1[] = {
  134564. 9, 7, 5, 3, 1, 0, 2, 4,
  134565. 6, 8, 10,
  134566. };
  134567. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  134568. _vq_quantthresh__44c8_s_p5_1,
  134569. _vq_quantmap__44c8_s_p5_1,
  134570. 11,
  134571. 11
  134572. };
  134573. static static_codebook _44c8_s_p5_1 = {
  134574. 2, 121,
  134575. _vq_lengthlist__44c8_s_p5_1,
  134576. 1, -531365888, 1611661312, 4, 0,
  134577. _vq_quantlist__44c8_s_p5_1,
  134578. NULL,
  134579. &_vq_auxt__44c8_s_p5_1,
  134580. NULL,
  134581. 0
  134582. };
  134583. static long _vq_quantlist__44c8_s_p6_0[] = {
  134584. 6,
  134585. 5,
  134586. 7,
  134587. 4,
  134588. 8,
  134589. 3,
  134590. 9,
  134591. 2,
  134592. 10,
  134593. 1,
  134594. 11,
  134595. 0,
  134596. 12,
  134597. };
  134598. static long _vq_lengthlist__44c8_s_p6_0[] = {
  134599. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  134600. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  134601. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  134602. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  134603. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  134604. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  134605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134609. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134610. };
  134611. static float _vq_quantthresh__44c8_s_p6_0[] = {
  134612. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134613. 12.5, 17.5, 22.5, 27.5,
  134614. };
  134615. static long _vq_quantmap__44c8_s_p6_0[] = {
  134616. 11, 9, 7, 5, 3, 1, 0, 2,
  134617. 4, 6, 8, 10, 12,
  134618. };
  134619. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  134620. _vq_quantthresh__44c8_s_p6_0,
  134621. _vq_quantmap__44c8_s_p6_0,
  134622. 13,
  134623. 13
  134624. };
  134625. static static_codebook _44c8_s_p6_0 = {
  134626. 2, 169,
  134627. _vq_lengthlist__44c8_s_p6_0,
  134628. 1, -526516224, 1616117760, 4, 0,
  134629. _vq_quantlist__44c8_s_p6_0,
  134630. NULL,
  134631. &_vq_auxt__44c8_s_p6_0,
  134632. NULL,
  134633. 0
  134634. };
  134635. static long _vq_quantlist__44c8_s_p6_1[] = {
  134636. 2,
  134637. 1,
  134638. 3,
  134639. 0,
  134640. 4,
  134641. };
  134642. static long _vq_lengthlist__44c8_s_p6_1[] = {
  134643. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134644. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134645. };
  134646. static float _vq_quantthresh__44c8_s_p6_1[] = {
  134647. -1.5, -0.5, 0.5, 1.5,
  134648. };
  134649. static long _vq_quantmap__44c8_s_p6_1[] = {
  134650. 3, 1, 0, 2, 4,
  134651. };
  134652. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  134653. _vq_quantthresh__44c8_s_p6_1,
  134654. _vq_quantmap__44c8_s_p6_1,
  134655. 5,
  134656. 5
  134657. };
  134658. static static_codebook _44c8_s_p6_1 = {
  134659. 2, 25,
  134660. _vq_lengthlist__44c8_s_p6_1,
  134661. 1, -533725184, 1611661312, 3, 0,
  134662. _vq_quantlist__44c8_s_p6_1,
  134663. NULL,
  134664. &_vq_auxt__44c8_s_p6_1,
  134665. NULL,
  134666. 0
  134667. };
  134668. static long _vq_quantlist__44c8_s_p7_0[] = {
  134669. 6,
  134670. 5,
  134671. 7,
  134672. 4,
  134673. 8,
  134674. 3,
  134675. 9,
  134676. 2,
  134677. 10,
  134678. 1,
  134679. 11,
  134680. 0,
  134681. 12,
  134682. };
  134683. static long _vq_lengthlist__44c8_s_p7_0[] = {
  134684. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  134685. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134686. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  134687. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  134688. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  134689. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  134690. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  134691. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  134692. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  134693. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  134694. 20,13,13,13,13,14,13,15,15,
  134695. };
  134696. static float _vq_quantthresh__44c8_s_p7_0[] = {
  134697. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134698. 27.5, 38.5, 49.5, 60.5,
  134699. };
  134700. static long _vq_quantmap__44c8_s_p7_0[] = {
  134701. 11, 9, 7, 5, 3, 1, 0, 2,
  134702. 4, 6, 8, 10, 12,
  134703. };
  134704. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  134705. _vq_quantthresh__44c8_s_p7_0,
  134706. _vq_quantmap__44c8_s_p7_0,
  134707. 13,
  134708. 13
  134709. };
  134710. static static_codebook _44c8_s_p7_0 = {
  134711. 2, 169,
  134712. _vq_lengthlist__44c8_s_p7_0,
  134713. 1, -523206656, 1618345984, 4, 0,
  134714. _vq_quantlist__44c8_s_p7_0,
  134715. NULL,
  134716. &_vq_auxt__44c8_s_p7_0,
  134717. NULL,
  134718. 0
  134719. };
  134720. static long _vq_quantlist__44c8_s_p7_1[] = {
  134721. 5,
  134722. 4,
  134723. 6,
  134724. 3,
  134725. 7,
  134726. 2,
  134727. 8,
  134728. 1,
  134729. 9,
  134730. 0,
  134731. 10,
  134732. };
  134733. static long _vq_lengthlist__44c8_s_p7_1[] = {
  134734. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  134735. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  134736. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134737. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134738. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134739. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134740. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134741. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134742. };
  134743. static float _vq_quantthresh__44c8_s_p7_1[] = {
  134744. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134745. 3.5, 4.5,
  134746. };
  134747. static long _vq_quantmap__44c8_s_p7_1[] = {
  134748. 9, 7, 5, 3, 1, 0, 2, 4,
  134749. 6, 8, 10,
  134750. };
  134751. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  134752. _vq_quantthresh__44c8_s_p7_1,
  134753. _vq_quantmap__44c8_s_p7_1,
  134754. 11,
  134755. 11
  134756. };
  134757. static static_codebook _44c8_s_p7_1 = {
  134758. 2, 121,
  134759. _vq_lengthlist__44c8_s_p7_1,
  134760. 1, -531365888, 1611661312, 4, 0,
  134761. _vq_quantlist__44c8_s_p7_1,
  134762. NULL,
  134763. &_vq_auxt__44c8_s_p7_1,
  134764. NULL,
  134765. 0
  134766. };
  134767. static long _vq_quantlist__44c8_s_p8_0[] = {
  134768. 7,
  134769. 6,
  134770. 8,
  134771. 5,
  134772. 9,
  134773. 4,
  134774. 10,
  134775. 3,
  134776. 11,
  134777. 2,
  134778. 12,
  134779. 1,
  134780. 13,
  134781. 0,
  134782. 14,
  134783. };
  134784. static long _vq_lengthlist__44c8_s_p8_0[] = {
  134785. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  134786. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  134787. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  134788. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  134789. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  134790. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  134791. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  134792. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  134793. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  134794. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  134795. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  134796. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134797. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  134798. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  134799. 15,
  134800. };
  134801. static float _vq_quantthresh__44c8_s_p8_0[] = {
  134802. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134803. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134804. };
  134805. static long _vq_quantmap__44c8_s_p8_0[] = {
  134806. 13, 11, 9, 7, 5, 3, 1, 0,
  134807. 2, 4, 6, 8, 10, 12, 14,
  134808. };
  134809. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  134810. _vq_quantthresh__44c8_s_p8_0,
  134811. _vq_quantmap__44c8_s_p8_0,
  134812. 15,
  134813. 15
  134814. };
  134815. static static_codebook _44c8_s_p8_0 = {
  134816. 2, 225,
  134817. _vq_lengthlist__44c8_s_p8_0,
  134818. 1, -520986624, 1620377600, 4, 0,
  134819. _vq_quantlist__44c8_s_p8_0,
  134820. NULL,
  134821. &_vq_auxt__44c8_s_p8_0,
  134822. NULL,
  134823. 0
  134824. };
  134825. static long _vq_quantlist__44c8_s_p8_1[] = {
  134826. 10,
  134827. 9,
  134828. 11,
  134829. 8,
  134830. 12,
  134831. 7,
  134832. 13,
  134833. 6,
  134834. 14,
  134835. 5,
  134836. 15,
  134837. 4,
  134838. 16,
  134839. 3,
  134840. 17,
  134841. 2,
  134842. 18,
  134843. 1,
  134844. 19,
  134845. 0,
  134846. 20,
  134847. };
  134848. static long _vq_lengthlist__44c8_s_p8_1[] = {
  134849. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134850. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134851. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134852. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134853. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134854. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134855. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134856. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134857. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134858. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134859. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  134860. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  134861. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  134862. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134863. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  134864. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  134865. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  134866. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  134867. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  134868. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  134869. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  134870. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  134871. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134872. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  134873. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  134874. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  134875. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  134876. 10, 9, 9,10,10, 9,10, 9, 9,
  134877. };
  134878. static float _vq_quantthresh__44c8_s_p8_1[] = {
  134879. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134880. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134881. 6.5, 7.5, 8.5, 9.5,
  134882. };
  134883. static long _vq_quantmap__44c8_s_p8_1[] = {
  134884. 19, 17, 15, 13, 11, 9, 7, 5,
  134885. 3, 1, 0, 2, 4, 6, 8, 10,
  134886. 12, 14, 16, 18, 20,
  134887. };
  134888. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  134889. _vq_quantthresh__44c8_s_p8_1,
  134890. _vq_quantmap__44c8_s_p8_1,
  134891. 21,
  134892. 21
  134893. };
  134894. static static_codebook _44c8_s_p8_1 = {
  134895. 2, 441,
  134896. _vq_lengthlist__44c8_s_p8_1,
  134897. 1, -529268736, 1611661312, 5, 0,
  134898. _vq_quantlist__44c8_s_p8_1,
  134899. NULL,
  134900. &_vq_auxt__44c8_s_p8_1,
  134901. NULL,
  134902. 0
  134903. };
  134904. static long _vq_quantlist__44c8_s_p9_0[] = {
  134905. 8,
  134906. 7,
  134907. 9,
  134908. 6,
  134909. 10,
  134910. 5,
  134911. 11,
  134912. 4,
  134913. 12,
  134914. 3,
  134915. 13,
  134916. 2,
  134917. 14,
  134918. 1,
  134919. 15,
  134920. 0,
  134921. 16,
  134922. };
  134923. static long _vq_lengthlist__44c8_s_p9_0[] = {
  134924. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134925. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  134926. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  134927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134930. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134931. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134932. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134933. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134934. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134935. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134936. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134937. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134938. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134939. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134940. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134941. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  134942. 10,
  134943. };
  134944. static float _vq_quantthresh__44c8_s_p9_0[] = {
  134945. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  134946. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  134947. };
  134948. static long _vq_quantmap__44c8_s_p9_0[] = {
  134949. 15, 13, 11, 9, 7, 5, 3, 1,
  134950. 0, 2, 4, 6, 8, 10, 12, 14,
  134951. 16,
  134952. };
  134953. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  134954. _vq_quantthresh__44c8_s_p9_0,
  134955. _vq_quantmap__44c8_s_p9_0,
  134956. 17,
  134957. 17
  134958. };
  134959. static static_codebook _44c8_s_p9_0 = {
  134960. 2, 289,
  134961. _vq_lengthlist__44c8_s_p9_0,
  134962. 1, -509798400, 1631393792, 5, 0,
  134963. _vq_quantlist__44c8_s_p9_0,
  134964. NULL,
  134965. &_vq_auxt__44c8_s_p9_0,
  134966. NULL,
  134967. 0
  134968. };
  134969. static long _vq_quantlist__44c8_s_p9_1[] = {
  134970. 9,
  134971. 8,
  134972. 10,
  134973. 7,
  134974. 11,
  134975. 6,
  134976. 12,
  134977. 5,
  134978. 13,
  134979. 4,
  134980. 14,
  134981. 3,
  134982. 15,
  134983. 2,
  134984. 16,
  134985. 1,
  134986. 17,
  134987. 0,
  134988. 18,
  134989. };
  134990. static long _vq_lengthlist__44c8_s_p9_1[] = {
  134991. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  134992. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  134993. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  134994. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  134995. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  134996. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  134997. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  134998. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  134999. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  135000. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  135001. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  135002. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  135003. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  135004. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  135005. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  135006. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  135007. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  135008. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  135009. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  135010. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  135011. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  135012. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  135013. 14,13,13,14,14,15,14,15,14,
  135014. };
  135015. static float _vq_quantthresh__44c8_s_p9_1[] = {
  135016. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135017. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135018. 367.5, 416.5,
  135019. };
  135020. static long _vq_quantmap__44c8_s_p9_1[] = {
  135021. 17, 15, 13, 11, 9, 7, 5, 3,
  135022. 1, 0, 2, 4, 6, 8, 10, 12,
  135023. 14, 16, 18,
  135024. };
  135025. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  135026. _vq_quantthresh__44c8_s_p9_1,
  135027. _vq_quantmap__44c8_s_p9_1,
  135028. 19,
  135029. 19
  135030. };
  135031. static static_codebook _44c8_s_p9_1 = {
  135032. 2, 361,
  135033. _vq_lengthlist__44c8_s_p9_1,
  135034. 1, -518287360, 1622704128, 5, 0,
  135035. _vq_quantlist__44c8_s_p9_1,
  135036. NULL,
  135037. &_vq_auxt__44c8_s_p9_1,
  135038. NULL,
  135039. 0
  135040. };
  135041. static long _vq_quantlist__44c8_s_p9_2[] = {
  135042. 24,
  135043. 23,
  135044. 25,
  135045. 22,
  135046. 26,
  135047. 21,
  135048. 27,
  135049. 20,
  135050. 28,
  135051. 19,
  135052. 29,
  135053. 18,
  135054. 30,
  135055. 17,
  135056. 31,
  135057. 16,
  135058. 32,
  135059. 15,
  135060. 33,
  135061. 14,
  135062. 34,
  135063. 13,
  135064. 35,
  135065. 12,
  135066. 36,
  135067. 11,
  135068. 37,
  135069. 10,
  135070. 38,
  135071. 9,
  135072. 39,
  135073. 8,
  135074. 40,
  135075. 7,
  135076. 41,
  135077. 6,
  135078. 42,
  135079. 5,
  135080. 43,
  135081. 4,
  135082. 44,
  135083. 3,
  135084. 45,
  135085. 2,
  135086. 46,
  135087. 1,
  135088. 47,
  135089. 0,
  135090. 48,
  135091. };
  135092. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135093. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135094. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135095. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135096. 7,
  135097. };
  135098. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135099. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135100. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135101. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135102. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135103. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135104. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135105. };
  135106. static long _vq_quantmap__44c8_s_p9_2[] = {
  135107. 47, 45, 43, 41, 39, 37, 35, 33,
  135108. 31, 29, 27, 25, 23, 21, 19, 17,
  135109. 15, 13, 11, 9, 7, 5, 3, 1,
  135110. 0, 2, 4, 6, 8, 10, 12, 14,
  135111. 16, 18, 20, 22, 24, 26, 28, 30,
  135112. 32, 34, 36, 38, 40, 42, 44, 46,
  135113. 48,
  135114. };
  135115. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135116. _vq_quantthresh__44c8_s_p9_2,
  135117. _vq_quantmap__44c8_s_p9_2,
  135118. 49,
  135119. 49
  135120. };
  135121. static static_codebook _44c8_s_p9_2 = {
  135122. 1, 49,
  135123. _vq_lengthlist__44c8_s_p9_2,
  135124. 1, -526909440, 1611661312, 6, 0,
  135125. _vq_quantlist__44c8_s_p9_2,
  135126. NULL,
  135127. &_vq_auxt__44c8_s_p9_2,
  135128. NULL,
  135129. 0
  135130. };
  135131. static long _huff_lengthlist__44c8_s_short[] = {
  135132. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135133. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135134. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135135. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135136. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135137. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135138. 10, 9,11,14,
  135139. };
  135140. static static_codebook _huff_book__44c8_s_short = {
  135141. 2, 100,
  135142. _huff_lengthlist__44c8_s_short,
  135143. 0, 0, 0, 0, 0,
  135144. NULL,
  135145. NULL,
  135146. NULL,
  135147. NULL,
  135148. 0
  135149. };
  135150. static long _huff_lengthlist__44c9_s_long[] = {
  135151. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135152. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135153. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135154. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135155. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135156. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135157. 10, 9, 8, 9,
  135158. };
  135159. static static_codebook _huff_book__44c9_s_long = {
  135160. 2, 100,
  135161. _huff_lengthlist__44c9_s_long,
  135162. 0, 0, 0, 0, 0,
  135163. NULL,
  135164. NULL,
  135165. NULL,
  135166. NULL,
  135167. 0
  135168. };
  135169. static long _vq_quantlist__44c9_s_p1_0[] = {
  135170. 1,
  135171. 0,
  135172. 2,
  135173. };
  135174. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135175. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135176. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135177. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135178. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135179. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135180. 7,
  135181. };
  135182. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135183. -0.5, 0.5,
  135184. };
  135185. static long _vq_quantmap__44c9_s_p1_0[] = {
  135186. 1, 0, 2,
  135187. };
  135188. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135189. _vq_quantthresh__44c9_s_p1_0,
  135190. _vq_quantmap__44c9_s_p1_0,
  135191. 3,
  135192. 3
  135193. };
  135194. static static_codebook _44c9_s_p1_0 = {
  135195. 4, 81,
  135196. _vq_lengthlist__44c9_s_p1_0,
  135197. 1, -535822336, 1611661312, 2, 0,
  135198. _vq_quantlist__44c9_s_p1_0,
  135199. NULL,
  135200. &_vq_auxt__44c9_s_p1_0,
  135201. NULL,
  135202. 0
  135203. };
  135204. static long _vq_quantlist__44c9_s_p2_0[] = {
  135205. 2,
  135206. 1,
  135207. 3,
  135208. 0,
  135209. 4,
  135210. };
  135211. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135212. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135213. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135214. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135215. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135216. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135217. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135218. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135219. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135221. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135222. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135223. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135224. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135225. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135226. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135227. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135229. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135230. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135231. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135232. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135233. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135234. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135235. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135237. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135238. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135239. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135240. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135241. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135242. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135243. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135248. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135249. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135250. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135251. 12,
  135252. };
  135253. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135254. -1.5, -0.5, 0.5, 1.5,
  135255. };
  135256. static long _vq_quantmap__44c9_s_p2_0[] = {
  135257. 3, 1, 0, 2, 4,
  135258. };
  135259. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135260. _vq_quantthresh__44c9_s_p2_0,
  135261. _vq_quantmap__44c9_s_p2_0,
  135262. 5,
  135263. 5
  135264. };
  135265. static static_codebook _44c9_s_p2_0 = {
  135266. 4, 625,
  135267. _vq_lengthlist__44c9_s_p2_0,
  135268. 1, -533725184, 1611661312, 3, 0,
  135269. _vq_quantlist__44c9_s_p2_0,
  135270. NULL,
  135271. &_vq_auxt__44c9_s_p2_0,
  135272. NULL,
  135273. 0
  135274. };
  135275. static long _vq_quantlist__44c9_s_p3_0[] = {
  135276. 4,
  135277. 3,
  135278. 5,
  135279. 2,
  135280. 6,
  135281. 1,
  135282. 7,
  135283. 0,
  135284. 8,
  135285. };
  135286. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135287. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135288. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135289. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135290. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135292. 0,
  135293. };
  135294. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135295. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135296. };
  135297. static long _vq_quantmap__44c9_s_p3_0[] = {
  135298. 7, 5, 3, 1, 0, 2, 4, 6,
  135299. 8,
  135300. };
  135301. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135302. _vq_quantthresh__44c9_s_p3_0,
  135303. _vq_quantmap__44c9_s_p3_0,
  135304. 9,
  135305. 9
  135306. };
  135307. static static_codebook _44c9_s_p3_0 = {
  135308. 2, 81,
  135309. _vq_lengthlist__44c9_s_p3_0,
  135310. 1, -531628032, 1611661312, 4, 0,
  135311. _vq_quantlist__44c9_s_p3_0,
  135312. NULL,
  135313. &_vq_auxt__44c9_s_p3_0,
  135314. NULL,
  135315. 0
  135316. };
  135317. static long _vq_quantlist__44c9_s_p4_0[] = {
  135318. 8,
  135319. 7,
  135320. 9,
  135321. 6,
  135322. 10,
  135323. 5,
  135324. 11,
  135325. 4,
  135326. 12,
  135327. 3,
  135328. 13,
  135329. 2,
  135330. 14,
  135331. 1,
  135332. 15,
  135333. 0,
  135334. 16,
  135335. };
  135336. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135337. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135338. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135339. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135340. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135341. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135342. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135343. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135344. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135345. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135346. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135347. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135348. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135352. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135353. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135355. 0,
  135356. };
  135357. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135358. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135359. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135360. };
  135361. static long _vq_quantmap__44c9_s_p4_0[] = {
  135362. 15, 13, 11, 9, 7, 5, 3, 1,
  135363. 0, 2, 4, 6, 8, 10, 12, 14,
  135364. 16,
  135365. };
  135366. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135367. _vq_quantthresh__44c9_s_p4_0,
  135368. _vq_quantmap__44c9_s_p4_0,
  135369. 17,
  135370. 17
  135371. };
  135372. static static_codebook _44c9_s_p4_0 = {
  135373. 2, 289,
  135374. _vq_lengthlist__44c9_s_p4_0,
  135375. 1, -529530880, 1611661312, 5, 0,
  135376. _vq_quantlist__44c9_s_p4_0,
  135377. NULL,
  135378. &_vq_auxt__44c9_s_p4_0,
  135379. NULL,
  135380. 0
  135381. };
  135382. static long _vq_quantlist__44c9_s_p5_0[] = {
  135383. 1,
  135384. 0,
  135385. 2,
  135386. };
  135387. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135388. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135389. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135390. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135391. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135392. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135393. 12,
  135394. };
  135395. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135396. -5.5, 5.5,
  135397. };
  135398. static long _vq_quantmap__44c9_s_p5_0[] = {
  135399. 1, 0, 2,
  135400. };
  135401. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135402. _vq_quantthresh__44c9_s_p5_0,
  135403. _vq_quantmap__44c9_s_p5_0,
  135404. 3,
  135405. 3
  135406. };
  135407. static static_codebook _44c9_s_p5_0 = {
  135408. 4, 81,
  135409. _vq_lengthlist__44c9_s_p5_0,
  135410. 1, -529137664, 1618345984, 2, 0,
  135411. _vq_quantlist__44c9_s_p5_0,
  135412. NULL,
  135413. &_vq_auxt__44c9_s_p5_0,
  135414. NULL,
  135415. 0
  135416. };
  135417. static long _vq_quantlist__44c9_s_p5_1[] = {
  135418. 5,
  135419. 4,
  135420. 6,
  135421. 3,
  135422. 7,
  135423. 2,
  135424. 8,
  135425. 1,
  135426. 9,
  135427. 0,
  135428. 10,
  135429. };
  135430. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135431. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135432. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135433. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135434. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135435. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135436. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135437. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135438. 11,11,11, 7, 7, 7, 7, 7, 7,
  135439. };
  135440. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135441. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135442. 3.5, 4.5,
  135443. };
  135444. static long _vq_quantmap__44c9_s_p5_1[] = {
  135445. 9, 7, 5, 3, 1, 0, 2, 4,
  135446. 6, 8, 10,
  135447. };
  135448. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135449. _vq_quantthresh__44c9_s_p5_1,
  135450. _vq_quantmap__44c9_s_p5_1,
  135451. 11,
  135452. 11
  135453. };
  135454. static static_codebook _44c9_s_p5_1 = {
  135455. 2, 121,
  135456. _vq_lengthlist__44c9_s_p5_1,
  135457. 1, -531365888, 1611661312, 4, 0,
  135458. _vq_quantlist__44c9_s_p5_1,
  135459. NULL,
  135460. &_vq_auxt__44c9_s_p5_1,
  135461. NULL,
  135462. 0
  135463. };
  135464. static long _vq_quantlist__44c9_s_p6_0[] = {
  135465. 6,
  135466. 5,
  135467. 7,
  135468. 4,
  135469. 8,
  135470. 3,
  135471. 9,
  135472. 2,
  135473. 10,
  135474. 1,
  135475. 11,
  135476. 0,
  135477. 12,
  135478. };
  135479. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135480. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135481. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135482. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135483. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135484. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135485. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135490. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135491. };
  135492. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135493. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135494. 12.5, 17.5, 22.5, 27.5,
  135495. };
  135496. static long _vq_quantmap__44c9_s_p6_0[] = {
  135497. 11, 9, 7, 5, 3, 1, 0, 2,
  135498. 4, 6, 8, 10, 12,
  135499. };
  135500. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135501. _vq_quantthresh__44c9_s_p6_0,
  135502. _vq_quantmap__44c9_s_p6_0,
  135503. 13,
  135504. 13
  135505. };
  135506. static static_codebook _44c9_s_p6_0 = {
  135507. 2, 169,
  135508. _vq_lengthlist__44c9_s_p6_0,
  135509. 1, -526516224, 1616117760, 4, 0,
  135510. _vq_quantlist__44c9_s_p6_0,
  135511. NULL,
  135512. &_vq_auxt__44c9_s_p6_0,
  135513. NULL,
  135514. 0
  135515. };
  135516. static long _vq_quantlist__44c9_s_p6_1[] = {
  135517. 2,
  135518. 1,
  135519. 3,
  135520. 0,
  135521. 4,
  135522. };
  135523. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135524. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135525. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135526. };
  135527. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135528. -1.5, -0.5, 0.5, 1.5,
  135529. };
  135530. static long _vq_quantmap__44c9_s_p6_1[] = {
  135531. 3, 1, 0, 2, 4,
  135532. };
  135533. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135534. _vq_quantthresh__44c9_s_p6_1,
  135535. _vq_quantmap__44c9_s_p6_1,
  135536. 5,
  135537. 5
  135538. };
  135539. static static_codebook _44c9_s_p6_1 = {
  135540. 2, 25,
  135541. _vq_lengthlist__44c9_s_p6_1,
  135542. 1, -533725184, 1611661312, 3, 0,
  135543. _vq_quantlist__44c9_s_p6_1,
  135544. NULL,
  135545. &_vq_auxt__44c9_s_p6_1,
  135546. NULL,
  135547. 0
  135548. };
  135549. static long _vq_quantlist__44c9_s_p7_0[] = {
  135550. 6,
  135551. 5,
  135552. 7,
  135553. 4,
  135554. 8,
  135555. 3,
  135556. 9,
  135557. 2,
  135558. 10,
  135559. 1,
  135560. 11,
  135561. 0,
  135562. 12,
  135563. };
  135564. static long _vq_lengthlist__44c9_s_p7_0[] = {
  135565. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  135566. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  135567. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  135568. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  135569. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  135570. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  135571. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  135572. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  135573. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  135574. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  135575. 19,12,12,12,12,13,13,14,14,
  135576. };
  135577. static float _vq_quantthresh__44c9_s_p7_0[] = {
  135578. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135579. 27.5, 38.5, 49.5, 60.5,
  135580. };
  135581. static long _vq_quantmap__44c9_s_p7_0[] = {
  135582. 11, 9, 7, 5, 3, 1, 0, 2,
  135583. 4, 6, 8, 10, 12,
  135584. };
  135585. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  135586. _vq_quantthresh__44c9_s_p7_0,
  135587. _vq_quantmap__44c9_s_p7_0,
  135588. 13,
  135589. 13
  135590. };
  135591. static static_codebook _44c9_s_p7_0 = {
  135592. 2, 169,
  135593. _vq_lengthlist__44c9_s_p7_0,
  135594. 1, -523206656, 1618345984, 4, 0,
  135595. _vq_quantlist__44c9_s_p7_0,
  135596. NULL,
  135597. &_vq_auxt__44c9_s_p7_0,
  135598. NULL,
  135599. 0
  135600. };
  135601. static long _vq_quantlist__44c9_s_p7_1[] = {
  135602. 5,
  135603. 4,
  135604. 6,
  135605. 3,
  135606. 7,
  135607. 2,
  135608. 8,
  135609. 1,
  135610. 9,
  135611. 0,
  135612. 10,
  135613. };
  135614. static long _vq_lengthlist__44c9_s_p7_1[] = {
  135615. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  135616. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135617. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  135618. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135619. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135620. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135621. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135622. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135623. };
  135624. static float _vq_quantthresh__44c9_s_p7_1[] = {
  135625. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135626. 3.5, 4.5,
  135627. };
  135628. static long _vq_quantmap__44c9_s_p7_1[] = {
  135629. 9, 7, 5, 3, 1, 0, 2, 4,
  135630. 6, 8, 10,
  135631. };
  135632. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  135633. _vq_quantthresh__44c9_s_p7_1,
  135634. _vq_quantmap__44c9_s_p7_1,
  135635. 11,
  135636. 11
  135637. };
  135638. static static_codebook _44c9_s_p7_1 = {
  135639. 2, 121,
  135640. _vq_lengthlist__44c9_s_p7_1,
  135641. 1, -531365888, 1611661312, 4, 0,
  135642. _vq_quantlist__44c9_s_p7_1,
  135643. NULL,
  135644. &_vq_auxt__44c9_s_p7_1,
  135645. NULL,
  135646. 0
  135647. };
  135648. static long _vq_quantlist__44c9_s_p8_0[] = {
  135649. 7,
  135650. 6,
  135651. 8,
  135652. 5,
  135653. 9,
  135654. 4,
  135655. 10,
  135656. 3,
  135657. 11,
  135658. 2,
  135659. 12,
  135660. 1,
  135661. 13,
  135662. 0,
  135663. 14,
  135664. };
  135665. static long _vq_lengthlist__44c9_s_p8_0[] = {
  135666. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  135667. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  135668. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  135669. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  135670. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  135671. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  135672. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  135673. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  135674. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  135675. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  135676. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  135677. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  135678. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  135679. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  135680. 14,
  135681. };
  135682. static float _vq_quantthresh__44c9_s_p8_0[] = {
  135683. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135684. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135685. };
  135686. static long _vq_quantmap__44c9_s_p8_0[] = {
  135687. 13, 11, 9, 7, 5, 3, 1, 0,
  135688. 2, 4, 6, 8, 10, 12, 14,
  135689. };
  135690. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  135691. _vq_quantthresh__44c9_s_p8_0,
  135692. _vq_quantmap__44c9_s_p8_0,
  135693. 15,
  135694. 15
  135695. };
  135696. static static_codebook _44c9_s_p8_0 = {
  135697. 2, 225,
  135698. _vq_lengthlist__44c9_s_p8_0,
  135699. 1, -520986624, 1620377600, 4, 0,
  135700. _vq_quantlist__44c9_s_p8_0,
  135701. NULL,
  135702. &_vq_auxt__44c9_s_p8_0,
  135703. NULL,
  135704. 0
  135705. };
  135706. static long _vq_quantlist__44c9_s_p8_1[] = {
  135707. 10,
  135708. 9,
  135709. 11,
  135710. 8,
  135711. 12,
  135712. 7,
  135713. 13,
  135714. 6,
  135715. 14,
  135716. 5,
  135717. 15,
  135718. 4,
  135719. 16,
  135720. 3,
  135721. 17,
  135722. 2,
  135723. 18,
  135724. 1,
  135725. 19,
  135726. 0,
  135727. 20,
  135728. };
  135729. static long _vq_lengthlist__44c9_s_p8_1[] = {
  135730. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135731. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135732. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135733. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135734. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135735. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135736. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  135737. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135738. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135739. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135740. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135741. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135742. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135743. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135744. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135745. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  135746. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  135747. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  135748. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  135749. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135750. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  135751. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  135752. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  135753. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  135754. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  135755. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  135756. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  135757. 9, 9, 9,10, 9, 9, 9, 9, 9,
  135758. };
  135759. static float _vq_quantthresh__44c9_s_p8_1[] = {
  135760. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135761. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135762. 6.5, 7.5, 8.5, 9.5,
  135763. };
  135764. static long _vq_quantmap__44c9_s_p8_1[] = {
  135765. 19, 17, 15, 13, 11, 9, 7, 5,
  135766. 3, 1, 0, 2, 4, 6, 8, 10,
  135767. 12, 14, 16, 18, 20,
  135768. };
  135769. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  135770. _vq_quantthresh__44c9_s_p8_1,
  135771. _vq_quantmap__44c9_s_p8_1,
  135772. 21,
  135773. 21
  135774. };
  135775. static static_codebook _44c9_s_p8_1 = {
  135776. 2, 441,
  135777. _vq_lengthlist__44c9_s_p8_1,
  135778. 1, -529268736, 1611661312, 5, 0,
  135779. _vq_quantlist__44c9_s_p8_1,
  135780. NULL,
  135781. &_vq_auxt__44c9_s_p8_1,
  135782. NULL,
  135783. 0
  135784. };
  135785. static long _vq_quantlist__44c9_s_p9_0[] = {
  135786. 9,
  135787. 8,
  135788. 10,
  135789. 7,
  135790. 11,
  135791. 6,
  135792. 12,
  135793. 5,
  135794. 13,
  135795. 4,
  135796. 14,
  135797. 3,
  135798. 15,
  135799. 2,
  135800. 16,
  135801. 1,
  135802. 17,
  135803. 0,
  135804. 18,
  135805. };
  135806. static long _vq_lengthlist__44c9_s_p9_0[] = {
  135807. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135808. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  135809. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  135810. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  135811. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135812. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135813. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135814. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135815. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135816. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135817. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135818. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135819. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135820. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135821. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135822. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  135823. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  135824. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135825. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135826. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135827. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135828. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135829. 11,11,11,11,11,11,11,11,11,
  135830. };
  135831. static float _vq_quantthresh__44c9_s_p9_0[] = {
  135832. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  135833. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  135834. 6982.5, 7913.5,
  135835. };
  135836. static long _vq_quantmap__44c9_s_p9_0[] = {
  135837. 17, 15, 13, 11, 9, 7, 5, 3,
  135838. 1, 0, 2, 4, 6, 8, 10, 12,
  135839. 14, 16, 18,
  135840. };
  135841. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  135842. _vq_quantthresh__44c9_s_p9_0,
  135843. _vq_quantmap__44c9_s_p9_0,
  135844. 19,
  135845. 19
  135846. };
  135847. static static_codebook _44c9_s_p9_0 = {
  135848. 2, 361,
  135849. _vq_lengthlist__44c9_s_p9_0,
  135850. 1, -508535424, 1631393792, 5, 0,
  135851. _vq_quantlist__44c9_s_p9_0,
  135852. NULL,
  135853. &_vq_auxt__44c9_s_p9_0,
  135854. NULL,
  135855. 0
  135856. };
  135857. static long _vq_quantlist__44c9_s_p9_1[] = {
  135858. 9,
  135859. 8,
  135860. 10,
  135861. 7,
  135862. 11,
  135863. 6,
  135864. 12,
  135865. 5,
  135866. 13,
  135867. 4,
  135868. 14,
  135869. 3,
  135870. 15,
  135871. 2,
  135872. 16,
  135873. 1,
  135874. 17,
  135875. 0,
  135876. 18,
  135877. };
  135878. static long _vq_lengthlist__44c9_s_p9_1[] = {
  135879. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  135880. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  135881. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  135882. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  135883. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  135884. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  135885. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  135886. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  135887. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  135888. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  135889. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  135890. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  135891. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  135892. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  135893. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  135894. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  135895. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  135896. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  135897. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  135898. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  135899. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  135900. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  135901. 13,13,13,14,13,14,15,15,15,
  135902. };
  135903. static float _vq_quantthresh__44c9_s_p9_1[] = {
  135904. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135905. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135906. 367.5, 416.5,
  135907. };
  135908. static long _vq_quantmap__44c9_s_p9_1[] = {
  135909. 17, 15, 13, 11, 9, 7, 5, 3,
  135910. 1, 0, 2, 4, 6, 8, 10, 12,
  135911. 14, 16, 18,
  135912. };
  135913. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  135914. _vq_quantthresh__44c9_s_p9_1,
  135915. _vq_quantmap__44c9_s_p9_1,
  135916. 19,
  135917. 19
  135918. };
  135919. static static_codebook _44c9_s_p9_1 = {
  135920. 2, 361,
  135921. _vq_lengthlist__44c9_s_p9_1,
  135922. 1, -518287360, 1622704128, 5, 0,
  135923. _vq_quantlist__44c9_s_p9_1,
  135924. NULL,
  135925. &_vq_auxt__44c9_s_p9_1,
  135926. NULL,
  135927. 0
  135928. };
  135929. static long _vq_quantlist__44c9_s_p9_2[] = {
  135930. 24,
  135931. 23,
  135932. 25,
  135933. 22,
  135934. 26,
  135935. 21,
  135936. 27,
  135937. 20,
  135938. 28,
  135939. 19,
  135940. 29,
  135941. 18,
  135942. 30,
  135943. 17,
  135944. 31,
  135945. 16,
  135946. 32,
  135947. 15,
  135948. 33,
  135949. 14,
  135950. 34,
  135951. 13,
  135952. 35,
  135953. 12,
  135954. 36,
  135955. 11,
  135956. 37,
  135957. 10,
  135958. 38,
  135959. 9,
  135960. 39,
  135961. 8,
  135962. 40,
  135963. 7,
  135964. 41,
  135965. 6,
  135966. 42,
  135967. 5,
  135968. 43,
  135969. 4,
  135970. 44,
  135971. 3,
  135972. 45,
  135973. 2,
  135974. 46,
  135975. 1,
  135976. 47,
  135977. 0,
  135978. 48,
  135979. };
  135980. static long _vq_lengthlist__44c9_s_p9_2[] = {
  135981. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135982. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135983. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135984. 7,
  135985. };
  135986. static float _vq_quantthresh__44c9_s_p9_2[] = {
  135987. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135988. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135989. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135990. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135991. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135992. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135993. };
  135994. static long _vq_quantmap__44c9_s_p9_2[] = {
  135995. 47, 45, 43, 41, 39, 37, 35, 33,
  135996. 31, 29, 27, 25, 23, 21, 19, 17,
  135997. 15, 13, 11, 9, 7, 5, 3, 1,
  135998. 0, 2, 4, 6, 8, 10, 12, 14,
  135999. 16, 18, 20, 22, 24, 26, 28, 30,
  136000. 32, 34, 36, 38, 40, 42, 44, 46,
  136001. 48,
  136002. };
  136003. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  136004. _vq_quantthresh__44c9_s_p9_2,
  136005. _vq_quantmap__44c9_s_p9_2,
  136006. 49,
  136007. 49
  136008. };
  136009. static static_codebook _44c9_s_p9_2 = {
  136010. 1, 49,
  136011. _vq_lengthlist__44c9_s_p9_2,
  136012. 1, -526909440, 1611661312, 6, 0,
  136013. _vq_quantlist__44c9_s_p9_2,
  136014. NULL,
  136015. &_vq_auxt__44c9_s_p9_2,
  136016. NULL,
  136017. 0
  136018. };
  136019. static long _huff_lengthlist__44c9_s_short[] = {
  136020. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  136021. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  136022. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  136023. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  136024. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  136025. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  136026. 9, 8,10,13,
  136027. };
  136028. static static_codebook _huff_book__44c9_s_short = {
  136029. 2, 100,
  136030. _huff_lengthlist__44c9_s_short,
  136031. 0, 0, 0, 0, 0,
  136032. NULL,
  136033. NULL,
  136034. NULL,
  136035. NULL,
  136036. 0
  136037. };
  136038. static long _huff_lengthlist__44c0_s_long[] = {
  136039. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  136040. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136041. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136042. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136043. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136044. 12,
  136045. };
  136046. static static_codebook _huff_book__44c0_s_long = {
  136047. 2, 81,
  136048. _huff_lengthlist__44c0_s_long,
  136049. 0, 0, 0, 0, 0,
  136050. NULL,
  136051. NULL,
  136052. NULL,
  136053. NULL,
  136054. 0
  136055. };
  136056. static long _vq_quantlist__44c0_s_p1_0[] = {
  136057. 1,
  136058. 0,
  136059. 2,
  136060. };
  136061. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136062. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136063. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136068. 0, 0, 0, 7, 9, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136073. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136108. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  136113. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  136118. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  136119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136153. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136154. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136159. 0, 0, 0, 0, 0, 9, 9,11, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136164. 0, 0, 0, 0, 0, 0, 9,11,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136472. 0,
  136473. };
  136474. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136475. -0.5, 0.5,
  136476. };
  136477. static long _vq_quantmap__44c0_s_p1_0[] = {
  136478. 1, 0, 2,
  136479. };
  136480. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136481. _vq_quantthresh__44c0_s_p1_0,
  136482. _vq_quantmap__44c0_s_p1_0,
  136483. 3,
  136484. 3
  136485. };
  136486. static static_codebook _44c0_s_p1_0 = {
  136487. 8, 6561,
  136488. _vq_lengthlist__44c0_s_p1_0,
  136489. 1, -535822336, 1611661312, 2, 0,
  136490. _vq_quantlist__44c0_s_p1_0,
  136491. NULL,
  136492. &_vq_auxt__44c0_s_p1_0,
  136493. NULL,
  136494. 0
  136495. };
  136496. static long _vq_quantlist__44c0_s_p2_0[] = {
  136497. 2,
  136498. 1,
  136499. 3,
  136500. 0,
  136501. 4,
  136502. };
  136503. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136504. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136510. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0,
  136544. };
  136545. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136546. -1.5, -0.5, 0.5, 1.5,
  136547. };
  136548. static long _vq_quantmap__44c0_s_p2_0[] = {
  136549. 3, 1, 0, 2, 4,
  136550. };
  136551. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136552. _vq_quantthresh__44c0_s_p2_0,
  136553. _vq_quantmap__44c0_s_p2_0,
  136554. 5,
  136555. 5
  136556. };
  136557. static static_codebook _44c0_s_p2_0 = {
  136558. 4, 625,
  136559. _vq_lengthlist__44c0_s_p2_0,
  136560. 1, -533725184, 1611661312, 3, 0,
  136561. _vq_quantlist__44c0_s_p2_0,
  136562. NULL,
  136563. &_vq_auxt__44c0_s_p2_0,
  136564. NULL,
  136565. 0
  136566. };
  136567. static long _vq_quantlist__44c0_s_p3_0[] = {
  136568. 4,
  136569. 3,
  136570. 5,
  136571. 2,
  136572. 6,
  136573. 1,
  136574. 7,
  136575. 0,
  136576. 8,
  136577. };
  136578. static long _vq_lengthlist__44c0_s_p3_0[] = {
  136579. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  136580. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  136581. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  136582. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  136583. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0,
  136585. };
  136586. static float _vq_quantthresh__44c0_s_p3_0[] = {
  136587. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136588. };
  136589. static long _vq_quantmap__44c0_s_p3_0[] = {
  136590. 7, 5, 3, 1, 0, 2, 4, 6,
  136591. 8,
  136592. };
  136593. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  136594. _vq_quantthresh__44c0_s_p3_0,
  136595. _vq_quantmap__44c0_s_p3_0,
  136596. 9,
  136597. 9
  136598. };
  136599. static static_codebook _44c0_s_p3_0 = {
  136600. 2, 81,
  136601. _vq_lengthlist__44c0_s_p3_0,
  136602. 1, -531628032, 1611661312, 4, 0,
  136603. _vq_quantlist__44c0_s_p3_0,
  136604. NULL,
  136605. &_vq_auxt__44c0_s_p3_0,
  136606. NULL,
  136607. 0
  136608. };
  136609. static long _vq_quantlist__44c0_s_p4_0[] = {
  136610. 4,
  136611. 3,
  136612. 5,
  136613. 2,
  136614. 6,
  136615. 1,
  136616. 7,
  136617. 0,
  136618. 8,
  136619. };
  136620. static long _vq_lengthlist__44c0_s_p4_0[] = {
  136621. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  136622. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  136623. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  136624. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  136625. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  136626. 10,
  136627. };
  136628. static float _vq_quantthresh__44c0_s_p4_0[] = {
  136629. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  136630. };
  136631. static long _vq_quantmap__44c0_s_p4_0[] = {
  136632. 7, 5, 3, 1, 0, 2, 4, 6,
  136633. 8,
  136634. };
  136635. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  136636. _vq_quantthresh__44c0_s_p4_0,
  136637. _vq_quantmap__44c0_s_p4_0,
  136638. 9,
  136639. 9
  136640. };
  136641. static static_codebook _44c0_s_p4_0 = {
  136642. 2, 81,
  136643. _vq_lengthlist__44c0_s_p4_0,
  136644. 1, -531628032, 1611661312, 4, 0,
  136645. _vq_quantlist__44c0_s_p4_0,
  136646. NULL,
  136647. &_vq_auxt__44c0_s_p4_0,
  136648. NULL,
  136649. 0
  136650. };
  136651. static long _vq_quantlist__44c0_s_p5_0[] = {
  136652. 8,
  136653. 7,
  136654. 9,
  136655. 6,
  136656. 10,
  136657. 5,
  136658. 11,
  136659. 4,
  136660. 12,
  136661. 3,
  136662. 13,
  136663. 2,
  136664. 14,
  136665. 1,
  136666. 15,
  136667. 0,
  136668. 16,
  136669. };
  136670. static long _vq_lengthlist__44c0_s_p5_0[] = {
  136671. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  136672. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  136673. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  136674. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  136675. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  136676. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  136677. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  136678. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  136679. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  136680. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  136681. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  136682. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  136683. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  136684. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  136685. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  136686. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  136687. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  136689. 14,
  136690. };
  136691. static float _vq_quantthresh__44c0_s_p5_0[] = {
  136692. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136693. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136694. };
  136695. static long _vq_quantmap__44c0_s_p5_0[] = {
  136696. 15, 13, 11, 9, 7, 5, 3, 1,
  136697. 0, 2, 4, 6, 8, 10, 12, 14,
  136698. 16,
  136699. };
  136700. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  136701. _vq_quantthresh__44c0_s_p5_0,
  136702. _vq_quantmap__44c0_s_p5_0,
  136703. 17,
  136704. 17
  136705. };
  136706. static static_codebook _44c0_s_p5_0 = {
  136707. 2, 289,
  136708. _vq_lengthlist__44c0_s_p5_0,
  136709. 1, -529530880, 1611661312, 5, 0,
  136710. _vq_quantlist__44c0_s_p5_0,
  136711. NULL,
  136712. &_vq_auxt__44c0_s_p5_0,
  136713. NULL,
  136714. 0
  136715. };
  136716. static long _vq_quantlist__44c0_s_p6_0[] = {
  136717. 1,
  136718. 0,
  136719. 2,
  136720. };
  136721. static long _vq_lengthlist__44c0_s_p6_0[] = {
  136722. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  136723. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  136724. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  136725. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  136726. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  136727. 10,
  136728. };
  136729. static float _vq_quantthresh__44c0_s_p6_0[] = {
  136730. -5.5, 5.5,
  136731. };
  136732. static long _vq_quantmap__44c0_s_p6_0[] = {
  136733. 1, 0, 2,
  136734. };
  136735. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  136736. _vq_quantthresh__44c0_s_p6_0,
  136737. _vq_quantmap__44c0_s_p6_0,
  136738. 3,
  136739. 3
  136740. };
  136741. static static_codebook _44c0_s_p6_0 = {
  136742. 4, 81,
  136743. _vq_lengthlist__44c0_s_p6_0,
  136744. 1, -529137664, 1618345984, 2, 0,
  136745. _vq_quantlist__44c0_s_p6_0,
  136746. NULL,
  136747. &_vq_auxt__44c0_s_p6_0,
  136748. NULL,
  136749. 0
  136750. };
  136751. static long _vq_quantlist__44c0_s_p6_1[] = {
  136752. 5,
  136753. 4,
  136754. 6,
  136755. 3,
  136756. 7,
  136757. 2,
  136758. 8,
  136759. 1,
  136760. 9,
  136761. 0,
  136762. 10,
  136763. };
  136764. static long _vq_lengthlist__44c0_s_p6_1[] = {
  136765. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  136766. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  136767. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  136768. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  136769. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  136770. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  136771. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  136772. 10,10,10, 8, 8, 8, 8, 8, 8,
  136773. };
  136774. static float _vq_quantthresh__44c0_s_p6_1[] = {
  136775. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136776. 3.5, 4.5,
  136777. };
  136778. static long _vq_quantmap__44c0_s_p6_1[] = {
  136779. 9, 7, 5, 3, 1, 0, 2, 4,
  136780. 6, 8, 10,
  136781. };
  136782. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  136783. _vq_quantthresh__44c0_s_p6_1,
  136784. _vq_quantmap__44c0_s_p6_1,
  136785. 11,
  136786. 11
  136787. };
  136788. static static_codebook _44c0_s_p6_1 = {
  136789. 2, 121,
  136790. _vq_lengthlist__44c0_s_p6_1,
  136791. 1, -531365888, 1611661312, 4, 0,
  136792. _vq_quantlist__44c0_s_p6_1,
  136793. NULL,
  136794. &_vq_auxt__44c0_s_p6_1,
  136795. NULL,
  136796. 0
  136797. };
  136798. static long _vq_quantlist__44c0_s_p7_0[] = {
  136799. 6,
  136800. 5,
  136801. 7,
  136802. 4,
  136803. 8,
  136804. 3,
  136805. 9,
  136806. 2,
  136807. 10,
  136808. 1,
  136809. 11,
  136810. 0,
  136811. 12,
  136812. };
  136813. static long _vq_lengthlist__44c0_s_p7_0[] = {
  136814. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  136815. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  136816. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  136817. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  136818. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  136819. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  136820. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  136821. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  136822. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  136823. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  136824. 0,12,12,11,11,12,12,13,13,
  136825. };
  136826. static float _vq_quantthresh__44c0_s_p7_0[] = {
  136827. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  136828. 12.5, 17.5, 22.5, 27.5,
  136829. };
  136830. static long _vq_quantmap__44c0_s_p7_0[] = {
  136831. 11, 9, 7, 5, 3, 1, 0, 2,
  136832. 4, 6, 8, 10, 12,
  136833. };
  136834. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  136835. _vq_quantthresh__44c0_s_p7_0,
  136836. _vq_quantmap__44c0_s_p7_0,
  136837. 13,
  136838. 13
  136839. };
  136840. static static_codebook _44c0_s_p7_0 = {
  136841. 2, 169,
  136842. _vq_lengthlist__44c0_s_p7_0,
  136843. 1, -526516224, 1616117760, 4, 0,
  136844. _vq_quantlist__44c0_s_p7_0,
  136845. NULL,
  136846. &_vq_auxt__44c0_s_p7_0,
  136847. NULL,
  136848. 0
  136849. };
  136850. static long _vq_quantlist__44c0_s_p7_1[] = {
  136851. 2,
  136852. 1,
  136853. 3,
  136854. 0,
  136855. 4,
  136856. };
  136857. static long _vq_lengthlist__44c0_s_p7_1[] = {
  136858. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  136859. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  136860. };
  136861. static float _vq_quantthresh__44c0_s_p7_1[] = {
  136862. -1.5, -0.5, 0.5, 1.5,
  136863. };
  136864. static long _vq_quantmap__44c0_s_p7_1[] = {
  136865. 3, 1, 0, 2, 4,
  136866. };
  136867. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  136868. _vq_quantthresh__44c0_s_p7_1,
  136869. _vq_quantmap__44c0_s_p7_1,
  136870. 5,
  136871. 5
  136872. };
  136873. static static_codebook _44c0_s_p7_1 = {
  136874. 2, 25,
  136875. _vq_lengthlist__44c0_s_p7_1,
  136876. 1, -533725184, 1611661312, 3, 0,
  136877. _vq_quantlist__44c0_s_p7_1,
  136878. NULL,
  136879. &_vq_auxt__44c0_s_p7_1,
  136880. NULL,
  136881. 0
  136882. };
  136883. static long _vq_quantlist__44c0_s_p8_0[] = {
  136884. 2,
  136885. 1,
  136886. 3,
  136887. 0,
  136888. 4,
  136889. };
  136890. static long _vq_lengthlist__44c0_s_p8_0[] = {
  136891. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  136892. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136893. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136894. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136895. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136896. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136897. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136898. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  136899. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136900. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136901. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136902. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  136903. 10,10,10,10,10,10,10,10,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,10,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,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136916. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136917. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136918. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136919. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136920. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136921. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136922. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136923. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136924. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136925. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136926. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136927. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136928. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136929. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136930. 11,
  136931. };
  136932. static float _vq_quantthresh__44c0_s_p8_0[] = {
  136933. -331.5, -110.5, 110.5, 331.5,
  136934. };
  136935. static long _vq_quantmap__44c0_s_p8_0[] = {
  136936. 3, 1, 0, 2, 4,
  136937. };
  136938. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  136939. _vq_quantthresh__44c0_s_p8_0,
  136940. _vq_quantmap__44c0_s_p8_0,
  136941. 5,
  136942. 5
  136943. };
  136944. static static_codebook _44c0_s_p8_0 = {
  136945. 4, 625,
  136946. _vq_lengthlist__44c0_s_p8_0,
  136947. 1, -518283264, 1627103232, 3, 0,
  136948. _vq_quantlist__44c0_s_p8_0,
  136949. NULL,
  136950. &_vq_auxt__44c0_s_p8_0,
  136951. NULL,
  136952. 0
  136953. };
  136954. static long _vq_quantlist__44c0_s_p8_1[] = {
  136955. 6,
  136956. 5,
  136957. 7,
  136958. 4,
  136959. 8,
  136960. 3,
  136961. 9,
  136962. 2,
  136963. 10,
  136964. 1,
  136965. 11,
  136966. 0,
  136967. 12,
  136968. };
  136969. static long _vq_lengthlist__44c0_s_p8_1[] = {
  136970. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  136971. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  136972. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  136973. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  136974. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  136975. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  136976. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  136977. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  136978. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  136979. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  136980. 16,13,13,12,12,14,14,15,13,
  136981. };
  136982. static float _vq_quantthresh__44c0_s_p8_1[] = {
  136983. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  136984. 42.5, 59.5, 76.5, 93.5,
  136985. };
  136986. static long _vq_quantmap__44c0_s_p8_1[] = {
  136987. 11, 9, 7, 5, 3, 1, 0, 2,
  136988. 4, 6, 8, 10, 12,
  136989. };
  136990. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  136991. _vq_quantthresh__44c0_s_p8_1,
  136992. _vq_quantmap__44c0_s_p8_1,
  136993. 13,
  136994. 13
  136995. };
  136996. static static_codebook _44c0_s_p8_1 = {
  136997. 2, 169,
  136998. _vq_lengthlist__44c0_s_p8_1,
  136999. 1, -522616832, 1620115456, 4, 0,
  137000. _vq_quantlist__44c0_s_p8_1,
  137001. NULL,
  137002. &_vq_auxt__44c0_s_p8_1,
  137003. NULL,
  137004. 0
  137005. };
  137006. static long _vq_quantlist__44c0_s_p8_2[] = {
  137007. 8,
  137008. 7,
  137009. 9,
  137010. 6,
  137011. 10,
  137012. 5,
  137013. 11,
  137014. 4,
  137015. 12,
  137016. 3,
  137017. 13,
  137018. 2,
  137019. 14,
  137020. 1,
  137021. 15,
  137022. 0,
  137023. 16,
  137024. };
  137025. static long _vq_lengthlist__44c0_s_p8_2[] = {
  137026. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137027. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  137028. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137029. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137030. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137031. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  137032. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  137033. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  137034. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  137035. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  137036. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  137037. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137038. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  137039. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  137040. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137041. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137042. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137043. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137044. 10,
  137045. };
  137046. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137047. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137048. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137049. };
  137050. static long _vq_quantmap__44c0_s_p8_2[] = {
  137051. 15, 13, 11, 9, 7, 5, 3, 1,
  137052. 0, 2, 4, 6, 8, 10, 12, 14,
  137053. 16,
  137054. };
  137055. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137056. _vq_quantthresh__44c0_s_p8_2,
  137057. _vq_quantmap__44c0_s_p8_2,
  137058. 17,
  137059. 17
  137060. };
  137061. static static_codebook _44c0_s_p8_2 = {
  137062. 2, 289,
  137063. _vq_lengthlist__44c0_s_p8_2,
  137064. 1, -529530880, 1611661312, 5, 0,
  137065. _vq_quantlist__44c0_s_p8_2,
  137066. NULL,
  137067. &_vq_auxt__44c0_s_p8_2,
  137068. NULL,
  137069. 0
  137070. };
  137071. static long _huff_lengthlist__44c0_s_short[] = {
  137072. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137073. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137074. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137075. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137076. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137077. 12,
  137078. };
  137079. static static_codebook _huff_book__44c0_s_short = {
  137080. 2, 81,
  137081. _huff_lengthlist__44c0_s_short,
  137082. 0, 0, 0, 0, 0,
  137083. NULL,
  137084. NULL,
  137085. NULL,
  137086. NULL,
  137087. 0
  137088. };
  137089. static long _huff_lengthlist__44c0_sm_long[] = {
  137090. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137091. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137092. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137093. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137094. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137095. 13,
  137096. };
  137097. static static_codebook _huff_book__44c0_sm_long = {
  137098. 2, 81,
  137099. _huff_lengthlist__44c0_sm_long,
  137100. 0, 0, 0, 0, 0,
  137101. NULL,
  137102. NULL,
  137103. NULL,
  137104. NULL,
  137105. 0
  137106. };
  137107. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137108. 1,
  137109. 0,
  137110. 2,
  137111. };
  137112. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137113. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137114. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137119. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137124. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137159. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  137164. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  137169. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137204. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137205. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137210. 0, 0, 0, 0, 0, 9, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137215. 0, 0, 0, 0, 0, 0, 9,10,10, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137523. 0,
  137524. };
  137525. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137526. -0.5, 0.5,
  137527. };
  137528. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137529. 1, 0, 2,
  137530. };
  137531. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137532. _vq_quantthresh__44c0_sm_p1_0,
  137533. _vq_quantmap__44c0_sm_p1_0,
  137534. 3,
  137535. 3
  137536. };
  137537. static static_codebook _44c0_sm_p1_0 = {
  137538. 8, 6561,
  137539. _vq_lengthlist__44c0_sm_p1_0,
  137540. 1, -535822336, 1611661312, 2, 0,
  137541. _vq_quantlist__44c0_sm_p1_0,
  137542. NULL,
  137543. &_vq_auxt__44c0_sm_p1_0,
  137544. NULL,
  137545. 0
  137546. };
  137547. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137548. 2,
  137549. 1,
  137550. 3,
  137551. 0,
  137552. 4,
  137553. };
  137554. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137555. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137561. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0,
  137595. };
  137596. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  137597. -1.5, -0.5, 0.5, 1.5,
  137598. };
  137599. static long _vq_quantmap__44c0_sm_p2_0[] = {
  137600. 3, 1, 0, 2, 4,
  137601. };
  137602. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  137603. _vq_quantthresh__44c0_sm_p2_0,
  137604. _vq_quantmap__44c0_sm_p2_0,
  137605. 5,
  137606. 5
  137607. };
  137608. static static_codebook _44c0_sm_p2_0 = {
  137609. 4, 625,
  137610. _vq_lengthlist__44c0_sm_p2_0,
  137611. 1, -533725184, 1611661312, 3, 0,
  137612. _vq_quantlist__44c0_sm_p2_0,
  137613. NULL,
  137614. &_vq_auxt__44c0_sm_p2_0,
  137615. NULL,
  137616. 0
  137617. };
  137618. static long _vq_quantlist__44c0_sm_p3_0[] = {
  137619. 4,
  137620. 3,
  137621. 5,
  137622. 2,
  137623. 6,
  137624. 1,
  137625. 7,
  137626. 0,
  137627. 8,
  137628. };
  137629. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  137630. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  137631. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  137632. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  137633. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  137634. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0,
  137636. };
  137637. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  137638. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137639. };
  137640. static long _vq_quantmap__44c0_sm_p3_0[] = {
  137641. 7, 5, 3, 1, 0, 2, 4, 6,
  137642. 8,
  137643. };
  137644. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  137645. _vq_quantthresh__44c0_sm_p3_0,
  137646. _vq_quantmap__44c0_sm_p3_0,
  137647. 9,
  137648. 9
  137649. };
  137650. static static_codebook _44c0_sm_p3_0 = {
  137651. 2, 81,
  137652. _vq_lengthlist__44c0_sm_p3_0,
  137653. 1, -531628032, 1611661312, 4, 0,
  137654. _vq_quantlist__44c0_sm_p3_0,
  137655. NULL,
  137656. &_vq_auxt__44c0_sm_p3_0,
  137657. NULL,
  137658. 0
  137659. };
  137660. static long _vq_quantlist__44c0_sm_p4_0[] = {
  137661. 4,
  137662. 3,
  137663. 5,
  137664. 2,
  137665. 6,
  137666. 1,
  137667. 7,
  137668. 0,
  137669. 8,
  137670. };
  137671. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  137672. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  137673. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  137674. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  137675. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  137676. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  137677. 11,
  137678. };
  137679. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  137680. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137681. };
  137682. static long _vq_quantmap__44c0_sm_p4_0[] = {
  137683. 7, 5, 3, 1, 0, 2, 4, 6,
  137684. 8,
  137685. };
  137686. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  137687. _vq_quantthresh__44c0_sm_p4_0,
  137688. _vq_quantmap__44c0_sm_p4_0,
  137689. 9,
  137690. 9
  137691. };
  137692. static static_codebook _44c0_sm_p4_0 = {
  137693. 2, 81,
  137694. _vq_lengthlist__44c0_sm_p4_0,
  137695. 1, -531628032, 1611661312, 4, 0,
  137696. _vq_quantlist__44c0_sm_p4_0,
  137697. NULL,
  137698. &_vq_auxt__44c0_sm_p4_0,
  137699. NULL,
  137700. 0
  137701. };
  137702. static long _vq_quantlist__44c0_sm_p5_0[] = {
  137703. 8,
  137704. 7,
  137705. 9,
  137706. 6,
  137707. 10,
  137708. 5,
  137709. 11,
  137710. 4,
  137711. 12,
  137712. 3,
  137713. 13,
  137714. 2,
  137715. 14,
  137716. 1,
  137717. 15,
  137718. 0,
  137719. 16,
  137720. };
  137721. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  137722. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  137723. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  137724. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137725. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  137726. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  137727. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  137728. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  137729. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137730. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  137731. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  137732. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137733. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137734. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  137735. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  137736. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  137737. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  137738. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137740. 14,
  137741. };
  137742. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  137743. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137744. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137745. };
  137746. static long _vq_quantmap__44c0_sm_p5_0[] = {
  137747. 15, 13, 11, 9, 7, 5, 3, 1,
  137748. 0, 2, 4, 6, 8, 10, 12, 14,
  137749. 16,
  137750. };
  137751. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  137752. _vq_quantthresh__44c0_sm_p5_0,
  137753. _vq_quantmap__44c0_sm_p5_0,
  137754. 17,
  137755. 17
  137756. };
  137757. static static_codebook _44c0_sm_p5_0 = {
  137758. 2, 289,
  137759. _vq_lengthlist__44c0_sm_p5_0,
  137760. 1, -529530880, 1611661312, 5, 0,
  137761. _vq_quantlist__44c0_sm_p5_0,
  137762. NULL,
  137763. &_vq_auxt__44c0_sm_p5_0,
  137764. NULL,
  137765. 0
  137766. };
  137767. static long _vq_quantlist__44c0_sm_p6_0[] = {
  137768. 1,
  137769. 0,
  137770. 2,
  137771. };
  137772. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  137773. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  137774. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  137775. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  137776. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  137777. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137778. 11,
  137779. };
  137780. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  137781. -5.5, 5.5,
  137782. };
  137783. static long _vq_quantmap__44c0_sm_p6_0[] = {
  137784. 1, 0, 2,
  137785. };
  137786. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  137787. _vq_quantthresh__44c0_sm_p6_0,
  137788. _vq_quantmap__44c0_sm_p6_0,
  137789. 3,
  137790. 3
  137791. };
  137792. static static_codebook _44c0_sm_p6_0 = {
  137793. 4, 81,
  137794. _vq_lengthlist__44c0_sm_p6_0,
  137795. 1, -529137664, 1618345984, 2, 0,
  137796. _vq_quantlist__44c0_sm_p6_0,
  137797. NULL,
  137798. &_vq_auxt__44c0_sm_p6_0,
  137799. NULL,
  137800. 0
  137801. };
  137802. static long _vq_quantlist__44c0_sm_p6_1[] = {
  137803. 5,
  137804. 4,
  137805. 6,
  137806. 3,
  137807. 7,
  137808. 2,
  137809. 8,
  137810. 1,
  137811. 9,
  137812. 0,
  137813. 10,
  137814. };
  137815. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  137816. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  137817. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  137818. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137819. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  137820. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  137821. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137822. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137823. 10,10,10, 8, 8, 8, 8, 8, 8,
  137824. };
  137825. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  137826. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137827. 3.5, 4.5,
  137828. };
  137829. static long _vq_quantmap__44c0_sm_p6_1[] = {
  137830. 9, 7, 5, 3, 1, 0, 2, 4,
  137831. 6, 8, 10,
  137832. };
  137833. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  137834. _vq_quantthresh__44c0_sm_p6_1,
  137835. _vq_quantmap__44c0_sm_p6_1,
  137836. 11,
  137837. 11
  137838. };
  137839. static static_codebook _44c0_sm_p6_1 = {
  137840. 2, 121,
  137841. _vq_lengthlist__44c0_sm_p6_1,
  137842. 1, -531365888, 1611661312, 4, 0,
  137843. _vq_quantlist__44c0_sm_p6_1,
  137844. NULL,
  137845. &_vq_auxt__44c0_sm_p6_1,
  137846. NULL,
  137847. 0
  137848. };
  137849. static long _vq_quantlist__44c0_sm_p7_0[] = {
  137850. 6,
  137851. 5,
  137852. 7,
  137853. 4,
  137854. 8,
  137855. 3,
  137856. 9,
  137857. 2,
  137858. 10,
  137859. 1,
  137860. 11,
  137861. 0,
  137862. 12,
  137863. };
  137864. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  137865. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137866. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  137867. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137868. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137869. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137870. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  137871. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137872. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137873. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137874. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  137875. 0,12,12,11,11,13,12,14,14,
  137876. };
  137877. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  137878. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137879. 12.5, 17.5, 22.5, 27.5,
  137880. };
  137881. static long _vq_quantmap__44c0_sm_p7_0[] = {
  137882. 11, 9, 7, 5, 3, 1, 0, 2,
  137883. 4, 6, 8, 10, 12,
  137884. };
  137885. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  137886. _vq_quantthresh__44c0_sm_p7_0,
  137887. _vq_quantmap__44c0_sm_p7_0,
  137888. 13,
  137889. 13
  137890. };
  137891. static static_codebook _44c0_sm_p7_0 = {
  137892. 2, 169,
  137893. _vq_lengthlist__44c0_sm_p7_0,
  137894. 1, -526516224, 1616117760, 4, 0,
  137895. _vq_quantlist__44c0_sm_p7_0,
  137896. NULL,
  137897. &_vq_auxt__44c0_sm_p7_0,
  137898. NULL,
  137899. 0
  137900. };
  137901. static long _vq_quantlist__44c0_sm_p7_1[] = {
  137902. 2,
  137903. 1,
  137904. 3,
  137905. 0,
  137906. 4,
  137907. };
  137908. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  137909. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  137910. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137911. };
  137912. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  137913. -1.5, -0.5, 0.5, 1.5,
  137914. };
  137915. static long _vq_quantmap__44c0_sm_p7_1[] = {
  137916. 3, 1, 0, 2, 4,
  137917. };
  137918. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  137919. _vq_quantthresh__44c0_sm_p7_1,
  137920. _vq_quantmap__44c0_sm_p7_1,
  137921. 5,
  137922. 5
  137923. };
  137924. static static_codebook _44c0_sm_p7_1 = {
  137925. 2, 25,
  137926. _vq_lengthlist__44c0_sm_p7_1,
  137927. 1, -533725184, 1611661312, 3, 0,
  137928. _vq_quantlist__44c0_sm_p7_1,
  137929. NULL,
  137930. &_vq_auxt__44c0_sm_p7_1,
  137931. NULL,
  137932. 0
  137933. };
  137934. static long _vq_quantlist__44c0_sm_p8_0[] = {
  137935. 4,
  137936. 3,
  137937. 5,
  137938. 2,
  137939. 6,
  137940. 1,
  137941. 7,
  137942. 0,
  137943. 8,
  137944. };
  137945. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  137946. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  137947. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  137948. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137949. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137950. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  137951. 12,
  137952. };
  137953. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  137954. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  137955. };
  137956. static long _vq_quantmap__44c0_sm_p8_0[] = {
  137957. 7, 5, 3, 1, 0, 2, 4, 6,
  137958. 8,
  137959. };
  137960. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  137961. _vq_quantthresh__44c0_sm_p8_0,
  137962. _vq_quantmap__44c0_sm_p8_0,
  137963. 9,
  137964. 9
  137965. };
  137966. static static_codebook _44c0_sm_p8_0 = {
  137967. 2, 81,
  137968. _vq_lengthlist__44c0_sm_p8_0,
  137969. 1, -516186112, 1627103232, 4, 0,
  137970. _vq_quantlist__44c0_sm_p8_0,
  137971. NULL,
  137972. &_vq_auxt__44c0_sm_p8_0,
  137973. NULL,
  137974. 0
  137975. };
  137976. static long _vq_quantlist__44c0_sm_p8_1[] = {
  137977. 6,
  137978. 5,
  137979. 7,
  137980. 4,
  137981. 8,
  137982. 3,
  137983. 9,
  137984. 2,
  137985. 10,
  137986. 1,
  137987. 11,
  137988. 0,
  137989. 12,
  137990. };
  137991. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  137992. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  137993. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  137994. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  137995. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  137996. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  137997. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  137998. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  137999. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  138000. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  138001. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  138002. 20,13,13,12,12,16,13,15,13,
  138003. };
  138004. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  138005. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138006. 42.5, 59.5, 76.5, 93.5,
  138007. };
  138008. static long _vq_quantmap__44c0_sm_p8_1[] = {
  138009. 11, 9, 7, 5, 3, 1, 0, 2,
  138010. 4, 6, 8, 10, 12,
  138011. };
  138012. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  138013. _vq_quantthresh__44c0_sm_p8_1,
  138014. _vq_quantmap__44c0_sm_p8_1,
  138015. 13,
  138016. 13
  138017. };
  138018. static static_codebook _44c0_sm_p8_1 = {
  138019. 2, 169,
  138020. _vq_lengthlist__44c0_sm_p8_1,
  138021. 1, -522616832, 1620115456, 4, 0,
  138022. _vq_quantlist__44c0_sm_p8_1,
  138023. NULL,
  138024. &_vq_auxt__44c0_sm_p8_1,
  138025. NULL,
  138026. 0
  138027. };
  138028. static long _vq_quantlist__44c0_sm_p8_2[] = {
  138029. 8,
  138030. 7,
  138031. 9,
  138032. 6,
  138033. 10,
  138034. 5,
  138035. 11,
  138036. 4,
  138037. 12,
  138038. 3,
  138039. 13,
  138040. 2,
  138041. 14,
  138042. 1,
  138043. 15,
  138044. 0,
  138045. 16,
  138046. };
  138047. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138048. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138049. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138050. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138051. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138052. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138053. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138054. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138055. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138056. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138057. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138058. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138059. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138060. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138061. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138062. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138063. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138064. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138065. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138066. 9,
  138067. };
  138068. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138069. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138070. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138071. };
  138072. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138073. 15, 13, 11, 9, 7, 5, 3, 1,
  138074. 0, 2, 4, 6, 8, 10, 12, 14,
  138075. 16,
  138076. };
  138077. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138078. _vq_quantthresh__44c0_sm_p8_2,
  138079. _vq_quantmap__44c0_sm_p8_2,
  138080. 17,
  138081. 17
  138082. };
  138083. static static_codebook _44c0_sm_p8_2 = {
  138084. 2, 289,
  138085. _vq_lengthlist__44c0_sm_p8_2,
  138086. 1, -529530880, 1611661312, 5, 0,
  138087. _vq_quantlist__44c0_sm_p8_2,
  138088. NULL,
  138089. &_vq_auxt__44c0_sm_p8_2,
  138090. NULL,
  138091. 0
  138092. };
  138093. static long _huff_lengthlist__44c0_sm_short[] = {
  138094. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138095. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138096. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138097. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138098. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138099. 12,
  138100. };
  138101. static static_codebook _huff_book__44c0_sm_short = {
  138102. 2, 81,
  138103. _huff_lengthlist__44c0_sm_short,
  138104. 0, 0, 0, 0, 0,
  138105. NULL,
  138106. NULL,
  138107. NULL,
  138108. NULL,
  138109. 0
  138110. };
  138111. static long _huff_lengthlist__44c1_s_long[] = {
  138112. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138113. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138114. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138115. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138116. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138117. 11,
  138118. };
  138119. static static_codebook _huff_book__44c1_s_long = {
  138120. 2, 81,
  138121. _huff_lengthlist__44c1_s_long,
  138122. 0, 0, 0, 0, 0,
  138123. NULL,
  138124. NULL,
  138125. NULL,
  138126. NULL,
  138127. 0
  138128. };
  138129. static long _vq_quantlist__44c1_s_p1_0[] = {
  138130. 1,
  138131. 0,
  138132. 2,
  138133. };
  138134. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138135. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138136. 0, 0, 5, 6, 7, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138141. 0, 0, 0, 7, 8, 8, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138146. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  138181. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 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, 7, 8, 8, 0, 0, 0,
  138186. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 6, 8, 8, 0, 0,
  138191. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138226. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138227. 0, 0, 0, 0, 7, 8, 9, 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, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138232. 0, 0, 0, 0, 0, 8, 8, 9, 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, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138237. 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138545. 0,
  138546. };
  138547. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138548. -0.5, 0.5,
  138549. };
  138550. static long _vq_quantmap__44c1_s_p1_0[] = {
  138551. 1, 0, 2,
  138552. };
  138553. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138554. _vq_quantthresh__44c1_s_p1_0,
  138555. _vq_quantmap__44c1_s_p1_0,
  138556. 3,
  138557. 3
  138558. };
  138559. static static_codebook _44c1_s_p1_0 = {
  138560. 8, 6561,
  138561. _vq_lengthlist__44c1_s_p1_0,
  138562. 1, -535822336, 1611661312, 2, 0,
  138563. _vq_quantlist__44c1_s_p1_0,
  138564. NULL,
  138565. &_vq_auxt__44c1_s_p1_0,
  138566. NULL,
  138567. 0
  138568. };
  138569. static long _vq_quantlist__44c1_s_p2_0[] = {
  138570. 2,
  138571. 1,
  138572. 3,
  138573. 0,
  138574. 4,
  138575. };
  138576. static long _vq_lengthlist__44c1_s_p2_0[] = {
  138577. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  138582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138583. 0, 0, 0, 0, 6, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0,
  138617. };
  138618. static float _vq_quantthresh__44c1_s_p2_0[] = {
  138619. -1.5, -0.5, 0.5, 1.5,
  138620. };
  138621. static long _vq_quantmap__44c1_s_p2_0[] = {
  138622. 3, 1, 0, 2, 4,
  138623. };
  138624. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  138625. _vq_quantthresh__44c1_s_p2_0,
  138626. _vq_quantmap__44c1_s_p2_0,
  138627. 5,
  138628. 5
  138629. };
  138630. static static_codebook _44c1_s_p2_0 = {
  138631. 4, 625,
  138632. _vq_lengthlist__44c1_s_p2_0,
  138633. 1, -533725184, 1611661312, 3, 0,
  138634. _vq_quantlist__44c1_s_p2_0,
  138635. NULL,
  138636. &_vq_auxt__44c1_s_p2_0,
  138637. NULL,
  138638. 0
  138639. };
  138640. static long _vq_quantlist__44c1_s_p3_0[] = {
  138641. 4,
  138642. 3,
  138643. 5,
  138644. 2,
  138645. 6,
  138646. 1,
  138647. 7,
  138648. 0,
  138649. 8,
  138650. };
  138651. static long _vq_lengthlist__44c1_s_p3_0[] = {
  138652. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  138653. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  138654. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  138655. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  138656. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0,
  138658. };
  138659. static float _vq_quantthresh__44c1_s_p3_0[] = {
  138660. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138661. };
  138662. static long _vq_quantmap__44c1_s_p3_0[] = {
  138663. 7, 5, 3, 1, 0, 2, 4, 6,
  138664. 8,
  138665. };
  138666. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  138667. _vq_quantthresh__44c1_s_p3_0,
  138668. _vq_quantmap__44c1_s_p3_0,
  138669. 9,
  138670. 9
  138671. };
  138672. static static_codebook _44c1_s_p3_0 = {
  138673. 2, 81,
  138674. _vq_lengthlist__44c1_s_p3_0,
  138675. 1, -531628032, 1611661312, 4, 0,
  138676. _vq_quantlist__44c1_s_p3_0,
  138677. NULL,
  138678. &_vq_auxt__44c1_s_p3_0,
  138679. NULL,
  138680. 0
  138681. };
  138682. static long _vq_quantlist__44c1_s_p4_0[] = {
  138683. 4,
  138684. 3,
  138685. 5,
  138686. 2,
  138687. 6,
  138688. 1,
  138689. 7,
  138690. 0,
  138691. 8,
  138692. };
  138693. static long _vq_lengthlist__44c1_s_p4_0[] = {
  138694. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  138695. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  138696. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  138697. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  138698. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138699. 11,
  138700. };
  138701. static float _vq_quantthresh__44c1_s_p4_0[] = {
  138702. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138703. };
  138704. static long _vq_quantmap__44c1_s_p4_0[] = {
  138705. 7, 5, 3, 1, 0, 2, 4, 6,
  138706. 8,
  138707. };
  138708. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  138709. _vq_quantthresh__44c1_s_p4_0,
  138710. _vq_quantmap__44c1_s_p4_0,
  138711. 9,
  138712. 9
  138713. };
  138714. static static_codebook _44c1_s_p4_0 = {
  138715. 2, 81,
  138716. _vq_lengthlist__44c1_s_p4_0,
  138717. 1, -531628032, 1611661312, 4, 0,
  138718. _vq_quantlist__44c1_s_p4_0,
  138719. NULL,
  138720. &_vq_auxt__44c1_s_p4_0,
  138721. NULL,
  138722. 0
  138723. };
  138724. static long _vq_quantlist__44c1_s_p5_0[] = {
  138725. 8,
  138726. 7,
  138727. 9,
  138728. 6,
  138729. 10,
  138730. 5,
  138731. 11,
  138732. 4,
  138733. 12,
  138734. 3,
  138735. 13,
  138736. 2,
  138737. 14,
  138738. 1,
  138739. 15,
  138740. 0,
  138741. 16,
  138742. };
  138743. static long _vq_lengthlist__44c1_s_p5_0[] = {
  138744. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  138745. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  138746. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138747. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  138748. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  138749. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  138750. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  138751. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138752. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  138753. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  138754. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138755. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138756. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  138757. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  138758. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  138759. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  138760. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138762. 14,
  138763. };
  138764. static float _vq_quantthresh__44c1_s_p5_0[] = {
  138765. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138766. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138767. };
  138768. static long _vq_quantmap__44c1_s_p5_0[] = {
  138769. 15, 13, 11, 9, 7, 5, 3, 1,
  138770. 0, 2, 4, 6, 8, 10, 12, 14,
  138771. 16,
  138772. };
  138773. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  138774. _vq_quantthresh__44c1_s_p5_0,
  138775. _vq_quantmap__44c1_s_p5_0,
  138776. 17,
  138777. 17
  138778. };
  138779. static static_codebook _44c1_s_p5_0 = {
  138780. 2, 289,
  138781. _vq_lengthlist__44c1_s_p5_0,
  138782. 1, -529530880, 1611661312, 5, 0,
  138783. _vq_quantlist__44c1_s_p5_0,
  138784. NULL,
  138785. &_vq_auxt__44c1_s_p5_0,
  138786. NULL,
  138787. 0
  138788. };
  138789. static long _vq_quantlist__44c1_s_p6_0[] = {
  138790. 1,
  138791. 0,
  138792. 2,
  138793. };
  138794. static long _vq_lengthlist__44c1_s_p6_0[] = {
  138795. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138796. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  138797. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  138798. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  138799. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  138800. 11,
  138801. };
  138802. static float _vq_quantthresh__44c1_s_p6_0[] = {
  138803. -5.5, 5.5,
  138804. };
  138805. static long _vq_quantmap__44c1_s_p6_0[] = {
  138806. 1, 0, 2,
  138807. };
  138808. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  138809. _vq_quantthresh__44c1_s_p6_0,
  138810. _vq_quantmap__44c1_s_p6_0,
  138811. 3,
  138812. 3
  138813. };
  138814. static static_codebook _44c1_s_p6_0 = {
  138815. 4, 81,
  138816. _vq_lengthlist__44c1_s_p6_0,
  138817. 1, -529137664, 1618345984, 2, 0,
  138818. _vq_quantlist__44c1_s_p6_0,
  138819. NULL,
  138820. &_vq_auxt__44c1_s_p6_0,
  138821. NULL,
  138822. 0
  138823. };
  138824. static long _vq_quantlist__44c1_s_p6_1[] = {
  138825. 5,
  138826. 4,
  138827. 6,
  138828. 3,
  138829. 7,
  138830. 2,
  138831. 8,
  138832. 1,
  138833. 9,
  138834. 0,
  138835. 10,
  138836. };
  138837. static long _vq_lengthlist__44c1_s_p6_1[] = {
  138838. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  138839. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  138840. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138841. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  138842. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  138843. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138844. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138845. 10,10,10, 8, 8, 8, 8, 8, 8,
  138846. };
  138847. static float _vq_quantthresh__44c1_s_p6_1[] = {
  138848. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138849. 3.5, 4.5,
  138850. };
  138851. static long _vq_quantmap__44c1_s_p6_1[] = {
  138852. 9, 7, 5, 3, 1, 0, 2, 4,
  138853. 6, 8, 10,
  138854. };
  138855. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  138856. _vq_quantthresh__44c1_s_p6_1,
  138857. _vq_quantmap__44c1_s_p6_1,
  138858. 11,
  138859. 11
  138860. };
  138861. static static_codebook _44c1_s_p6_1 = {
  138862. 2, 121,
  138863. _vq_lengthlist__44c1_s_p6_1,
  138864. 1, -531365888, 1611661312, 4, 0,
  138865. _vq_quantlist__44c1_s_p6_1,
  138866. NULL,
  138867. &_vq_auxt__44c1_s_p6_1,
  138868. NULL,
  138869. 0
  138870. };
  138871. static long _vq_quantlist__44c1_s_p7_0[] = {
  138872. 6,
  138873. 5,
  138874. 7,
  138875. 4,
  138876. 8,
  138877. 3,
  138878. 9,
  138879. 2,
  138880. 10,
  138881. 1,
  138882. 11,
  138883. 0,
  138884. 12,
  138885. };
  138886. static long _vq_lengthlist__44c1_s_p7_0[] = {
  138887. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  138888. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  138889. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138890. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138891. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  138892. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  138893. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  138894. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138895. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138896. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  138897. 0,12,11,11,11,13,10,14,13,
  138898. };
  138899. static float _vq_quantthresh__44c1_s_p7_0[] = {
  138900. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138901. 12.5, 17.5, 22.5, 27.5,
  138902. };
  138903. static long _vq_quantmap__44c1_s_p7_0[] = {
  138904. 11, 9, 7, 5, 3, 1, 0, 2,
  138905. 4, 6, 8, 10, 12,
  138906. };
  138907. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  138908. _vq_quantthresh__44c1_s_p7_0,
  138909. _vq_quantmap__44c1_s_p7_0,
  138910. 13,
  138911. 13
  138912. };
  138913. static static_codebook _44c1_s_p7_0 = {
  138914. 2, 169,
  138915. _vq_lengthlist__44c1_s_p7_0,
  138916. 1, -526516224, 1616117760, 4, 0,
  138917. _vq_quantlist__44c1_s_p7_0,
  138918. NULL,
  138919. &_vq_auxt__44c1_s_p7_0,
  138920. NULL,
  138921. 0
  138922. };
  138923. static long _vq_quantlist__44c1_s_p7_1[] = {
  138924. 2,
  138925. 1,
  138926. 3,
  138927. 0,
  138928. 4,
  138929. };
  138930. static long _vq_lengthlist__44c1_s_p7_1[] = {
  138931. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  138932. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138933. };
  138934. static float _vq_quantthresh__44c1_s_p7_1[] = {
  138935. -1.5, -0.5, 0.5, 1.5,
  138936. };
  138937. static long _vq_quantmap__44c1_s_p7_1[] = {
  138938. 3, 1, 0, 2, 4,
  138939. };
  138940. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  138941. _vq_quantthresh__44c1_s_p7_1,
  138942. _vq_quantmap__44c1_s_p7_1,
  138943. 5,
  138944. 5
  138945. };
  138946. static static_codebook _44c1_s_p7_1 = {
  138947. 2, 25,
  138948. _vq_lengthlist__44c1_s_p7_1,
  138949. 1, -533725184, 1611661312, 3, 0,
  138950. _vq_quantlist__44c1_s_p7_1,
  138951. NULL,
  138952. &_vq_auxt__44c1_s_p7_1,
  138953. NULL,
  138954. 0
  138955. };
  138956. static long _vq_quantlist__44c1_s_p8_0[] = {
  138957. 6,
  138958. 5,
  138959. 7,
  138960. 4,
  138961. 8,
  138962. 3,
  138963. 9,
  138964. 2,
  138965. 10,
  138966. 1,
  138967. 11,
  138968. 0,
  138969. 12,
  138970. };
  138971. static long _vq_lengthlist__44c1_s_p8_0[] = {
  138972. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  138973. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  138974. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138975. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138976. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138977. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138978. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138979. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138980. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138981. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  138982. 10,10,10,10,10,10,10,10,10,
  138983. };
  138984. static float _vq_quantthresh__44c1_s_p8_0[] = {
  138985. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  138986. 552.5, 773.5, 994.5, 1215.5,
  138987. };
  138988. static long _vq_quantmap__44c1_s_p8_0[] = {
  138989. 11, 9, 7, 5, 3, 1, 0, 2,
  138990. 4, 6, 8, 10, 12,
  138991. };
  138992. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  138993. _vq_quantthresh__44c1_s_p8_0,
  138994. _vq_quantmap__44c1_s_p8_0,
  138995. 13,
  138996. 13
  138997. };
  138998. static static_codebook _44c1_s_p8_0 = {
  138999. 2, 169,
  139000. _vq_lengthlist__44c1_s_p8_0,
  139001. 1, -514541568, 1627103232, 4, 0,
  139002. _vq_quantlist__44c1_s_p8_0,
  139003. NULL,
  139004. &_vq_auxt__44c1_s_p8_0,
  139005. NULL,
  139006. 0
  139007. };
  139008. static long _vq_quantlist__44c1_s_p8_1[] = {
  139009. 6,
  139010. 5,
  139011. 7,
  139012. 4,
  139013. 8,
  139014. 3,
  139015. 9,
  139016. 2,
  139017. 10,
  139018. 1,
  139019. 11,
  139020. 0,
  139021. 12,
  139022. };
  139023. static long _vq_lengthlist__44c1_s_p8_1[] = {
  139024. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  139025. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  139026. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  139027. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  139028. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  139029. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  139030. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  139031. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  139032. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  139033. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  139034. 16,13,12,12,11,14,12,15,13,
  139035. };
  139036. static float _vq_quantthresh__44c1_s_p8_1[] = {
  139037. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139038. 42.5, 59.5, 76.5, 93.5,
  139039. };
  139040. static long _vq_quantmap__44c1_s_p8_1[] = {
  139041. 11, 9, 7, 5, 3, 1, 0, 2,
  139042. 4, 6, 8, 10, 12,
  139043. };
  139044. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139045. _vq_quantthresh__44c1_s_p8_1,
  139046. _vq_quantmap__44c1_s_p8_1,
  139047. 13,
  139048. 13
  139049. };
  139050. static static_codebook _44c1_s_p8_1 = {
  139051. 2, 169,
  139052. _vq_lengthlist__44c1_s_p8_1,
  139053. 1, -522616832, 1620115456, 4, 0,
  139054. _vq_quantlist__44c1_s_p8_1,
  139055. NULL,
  139056. &_vq_auxt__44c1_s_p8_1,
  139057. NULL,
  139058. 0
  139059. };
  139060. static long _vq_quantlist__44c1_s_p8_2[] = {
  139061. 8,
  139062. 7,
  139063. 9,
  139064. 6,
  139065. 10,
  139066. 5,
  139067. 11,
  139068. 4,
  139069. 12,
  139070. 3,
  139071. 13,
  139072. 2,
  139073. 14,
  139074. 1,
  139075. 15,
  139076. 0,
  139077. 16,
  139078. };
  139079. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139080. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139081. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139082. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139083. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139084. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139085. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139086. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139087. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139088. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139089. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139090. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139091. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139092. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139093. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139094. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139095. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139096. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139097. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139098. 9,
  139099. };
  139100. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139101. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139102. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139103. };
  139104. static long _vq_quantmap__44c1_s_p8_2[] = {
  139105. 15, 13, 11, 9, 7, 5, 3, 1,
  139106. 0, 2, 4, 6, 8, 10, 12, 14,
  139107. 16,
  139108. };
  139109. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139110. _vq_quantthresh__44c1_s_p8_2,
  139111. _vq_quantmap__44c1_s_p8_2,
  139112. 17,
  139113. 17
  139114. };
  139115. static static_codebook _44c1_s_p8_2 = {
  139116. 2, 289,
  139117. _vq_lengthlist__44c1_s_p8_2,
  139118. 1, -529530880, 1611661312, 5, 0,
  139119. _vq_quantlist__44c1_s_p8_2,
  139120. NULL,
  139121. &_vq_auxt__44c1_s_p8_2,
  139122. NULL,
  139123. 0
  139124. };
  139125. static long _huff_lengthlist__44c1_s_short[] = {
  139126. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139127. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139128. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139129. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139130. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139131. 11,
  139132. };
  139133. static static_codebook _huff_book__44c1_s_short = {
  139134. 2, 81,
  139135. _huff_lengthlist__44c1_s_short,
  139136. 0, 0, 0, 0, 0,
  139137. NULL,
  139138. NULL,
  139139. NULL,
  139140. NULL,
  139141. 0
  139142. };
  139143. static long _huff_lengthlist__44c1_sm_long[] = {
  139144. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139145. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139146. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139147. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139148. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139149. 11,
  139150. };
  139151. static static_codebook _huff_book__44c1_sm_long = {
  139152. 2, 81,
  139153. _huff_lengthlist__44c1_sm_long,
  139154. 0, 0, 0, 0, 0,
  139155. NULL,
  139156. NULL,
  139157. NULL,
  139158. NULL,
  139159. 0
  139160. };
  139161. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139162. 1,
  139163. 0,
  139164. 2,
  139165. };
  139166. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139167. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139168. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139173. 0, 0, 0, 7, 8, 9, 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, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139178. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139213. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  139218. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  139223. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139258. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139259. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139264. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139269. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139577. 0,
  139578. };
  139579. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  139580. -0.5, 0.5,
  139581. };
  139582. static long _vq_quantmap__44c1_sm_p1_0[] = {
  139583. 1, 0, 2,
  139584. };
  139585. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  139586. _vq_quantthresh__44c1_sm_p1_0,
  139587. _vq_quantmap__44c1_sm_p1_0,
  139588. 3,
  139589. 3
  139590. };
  139591. static static_codebook _44c1_sm_p1_0 = {
  139592. 8, 6561,
  139593. _vq_lengthlist__44c1_sm_p1_0,
  139594. 1, -535822336, 1611661312, 2, 0,
  139595. _vq_quantlist__44c1_sm_p1_0,
  139596. NULL,
  139597. &_vq_auxt__44c1_sm_p1_0,
  139598. NULL,
  139599. 0
  139600. };
  139601. static long _vq_quantlist__44c1_sm_p2_0[] = {
  139602. 2,
  139603. 1,
  139604. 3,
  139605. 0,
  139606. 4,
  139607. };
  139608. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  139609. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  139614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139615. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0,
  139649. };
  139650. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  139651. -1.5, -0.5, 0.5, 1.5,
  139652. };
  139653. static long _vq_quantmap__44c1_sm_p2_0[] = {
  139654. 3, 1, 0, 2, 4,
  139655. };
  139656. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  139657. _vq_quantthresh__44c1_sm_p2_0,
  139658. _vq_quantmap__44c1_sm_p2_0,
  139659. 5,
  139660. 5
  139661. };
  139662. static static_codebook _44c1_sm_p2_0 = {
  139663. 4, 625,
  139664. _vq_lengthlist__44c1_sm_p2_0,
  139665. 1, -533725184, 1611661312, 3, 0,
  139666. _vq_quantlist__44c1_sm_p2_0,
  139667. NULL,
  139668. &_vq_auxt__44c1_sm_p2_0,
  139669. NULL,
  139670. 0
  139671. };
  139672. static long _vq_quantlist__44c1_sm_p3_0[] = {
  139673. 4,
  139674. 3,
  139675. 5,
  139676. 2,
  139677. 6,
  139678. 1,
  139679. 7,
  139680. 0,
  139681. 8,
  139682. };
  139683. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  139684. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  139685. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  139686. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139687. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139688. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0,
  139690. };
  139691. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  139692. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139693. };
  139694. static long _vq_quantmap__44c1_sm_p3_0[] = {
  139695. 7, 5, 3, 1, 0, 2, 4, 6,
  139696. 8,
  139697. };
  139698. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  139699. _vq_quantthresh__44c1_sm_p3_0,
  139700. _vq_quantmap__44c1_sm_p3_0,
  139701. 9,
  139702. 9
  139703. };
  139704. static static_codebook _44c1_sm_p3_0 = {
  139705. 2, 81,
  139706. _vq_lengthlist__44c1_sm_p3_0,
  139707. 1, -531628032, 1611661312, 4, 0,
  139708. _vq_quantlist__44c1_sm_p3_0,
  139709. NULL,
  139710. &_vq_auxt__44c1_sm_p3_0,
  139711. NULL,
  139712. 0
  139713. };
  139714. static long _vq_quantlist__44c1_sm_p4_0[] = {
  139715. 4,
  139716. 3,
  139717. 5,
  139718. 2,
  139719. 6,
  139720. 1,
  139721. 7,
  139722. 0,
  139723. 8,
  139724. };
  139725. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  139726. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  139727. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  139728. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  139729. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  139730. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139731. 11,
  139732. };
  139733. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  139734. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139735. };
  139736. static long _vq_quantmap__44c1_sm_p4_0[] = {
  139737. 7, 5, 3, 1, 0, 2, 4, 6,
  139738. 8,
  139739. };
  139740. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  139741. _vq_quantthresh__44c1_sm_p4_0,
  139742. _vq_quantmap__44c1_sm_p4_0,
  139743. 9,
  139744. 9
  139745. };
  139746. static static_codebook _44c1_sm_p4_0 = {
  139747. 2, 81,
  139748. _vq_lengthlist__44c1_sm_p4_0,
  139749. 1, -531628032, 1611661312, 4, 0,
  139750. _vq_quantlist__44c1_sm_p4_0,
  139751. NULL,
  139752. &_vq_auxt__44c1_sm_p4_0,
  139753. NULL,
  139754. 0
  139755. };
  139756. static long _vq_quantlist__44c1_sm_p5_0[] = {
  139757. 8,
  139758. 7,
  139759. 9,
  139760. 6,
  139761. 10,
  139762. 5,
  139763. 11,
  139764. 4,
  139765. 12,
  139766. 3,
  139767. 13,
  139768. 2,
  139769. 14,
  139770. 1,
  139771. 15,
  139772. 0,
  139773. 16,
  139774. };
  139775. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  139776. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139777. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139778. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  139779. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139780. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139781. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  139782. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  139783. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139784. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139785. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  139786. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139787. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139788. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139789. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139790. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  139791. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139792. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139794. 14,
  139795. };
  139796. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  139797. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139798. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139799. };
  139800. static long _vq_quantmap__44c1_sm_p5_0[] = {
  139801. 15, 13, 11, 9, 7, 5, 3, 1,
  139802. 0, 2, 4, 6, 8, 10, 12, 14,
  139803. 16,
  139804. };
  139805. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  139806. _vq_quantthresh__44c1_sm_p5_0,
  139807. _vq_quantmap__44c1_sm_p5_0,
  139808. 17,
  139809. 17
  139810. };
  139811. static static_codebook _44c1_sm_p5_0 = {
  139812. 2, 289,
  139813. _vq_lengthlist__44c1_sm_p5_0,
  139814. 1, -529530880, 1611661312, 5, 0,
  139815. _vq_quantlist__44c1_sm_p5_0,
  139816. NULL,
  139817. &_vq_auxt__44c1_sm_p5_0,
  139818. NULL,
  139819. 0
  139820. };
  139821. static long _vq_quantlist__44c1_sm_p6_0[] = {
  139822. 1,
  139823. 0,
  139824. 2,
  139825. };
  139826. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  139827. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139828. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  139829. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  139830. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  139831. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  139832. 11,
  139833. };
  139834. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  139835. -5.5, 5.5,
  139836. };
  139837. static long _vq_quantmap__44c1_sm_p6_0[] = {
  139838. 1, 0, 2,
  139839. };
  139840. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  139841. _vq_quantthresh__44c1_sm_p6_0,
  139842. _vq_quantmap__44c1_sm_p6_0,
  139843. 3,
  139844. 3
  139845. };
  139846. static static_codebook _44c1_sm_p6_0 = {
  139847. 4, 81,
  139848. _vq_lengthlist__44c1_sm_p6_0,
  139849. 1, -529137664, 1618345984, 2, 0,
  139850. _vq_quantlist__44c1_sm_p6_0,
  139851. NULL,
  139852. &_vq_auxt__44c1_sm_p6_0,
  139853. NULL,
  139854. 0
  139855. };
  139856. static long _vq_quantlist__44c1_sm_p6_1[] = {
  139857. 5,
  139858. 4,
  139859. 6,
  139860. 3,
  139861. 7,
  139862. 2,
  139863. 8,
  139864. 1,
  139865. 9,
  139866. 0,
  139867. 10,
  139868. };
  139869. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  139870. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  139871. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  139872. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  139873. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139874. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139875. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  139876. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139877. 10,10,10, 8, 8, 8, 8, 8, 8,
  139878. };
  139879. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  139880. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139881. 3.5, 4.5,
  139882. };
  139883. static long _vq_quantmap__44c1_sm_p6_1[] = {
  139884. 9, 7, 5, 3, 1, 0, 2, 4,
  139885. 6, 8, 10,
  139886. };
  139887. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  139888. _vq_quantthresh__44c1_sm_p6_1,
  139889. _vq_quantmap__44c1_sm_p6_1,
  139890. 11,
  139891. 11
  139892. };
  139893. static static_codebook _44c1_sm_p6_1 = {
  139894. 2, 121,
  139895. _vq_lengthlist__44c1_sm_p6_1,
  139896. 1, -531365888, 1611661312, 4, 0,
  139897. _vq_quantlist__44c1_sm_p6_1,
  139898. NULL,
  139899. &_vq_auxt__44c1_sm_p6_1,
  139900. NULL,
  139901. 0
  139902. };
  139903. static long _vq_quantlist__44c1_sm_p7_0[] = {
  139904. 6,
  139905. 5,
  139906. 7,
  139907. 4,
  139908. 8,
  139909. 3,
  139910. 9,
  139911. 2,
  139912. 10,
  139913. 1,
  139914. 11,
  139915. 0,
  139916. 12,
  139917. };
  139918. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  139919. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  139920. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  139921. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139922. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139923. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  139924. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  139925. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  139926. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139927. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139928. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  139929. 0,12,12,11,11,13,12,14,13,
  139930. };
  139931. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  139932. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139933. 12.5, 17.5, 22.5, 27.5,
  139934. };
  139935. static long _vq_quantmap__44c1_sm_p7_0[] = {
  139936. 11, 9, 7, 5, 3, 1, 0, 2,
  139937. 4, 6, 8, 10, 12,
  139938. };
  139939. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  139940. _vq_quantthresh__44c1_sm_p7_0,
  139941. _vq_quantmap__44c1_sm_p7_0,
  139942. 13,
  139943. 13
  139944. };
  139945. static static_codebook _44c1_sm_p7_0 = {
  139946. 2, 169,
  139947. _vq_lengthlist__44c1_sm_p7_0,
  139948. 1, -526516224, 1616117760, 4, 0,
  139949. _vq_quantlist__44c1_sm_p7_0,
  139950. NULL,
  139951. &_vq_auxt__44c1_sm_p7_0,
  139952. NULL,
  139953. 0
  139954. };
  139955. static long _vq_quantlist__44c1_sm_p7_1[] = {
  139956. 2,
  139957. 1,
  139958. 3,
  139959. 0,
  139960. 4,
  139961. };
  139962. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  139963. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  139964. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  139965. };
  139966. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  139967. -1.5, -0.5, 0.5, 1.5,
  139968. };
  139969. static long _vq_quantmap__44c1_sm_p7_1[] = {
  139970. 3, 1, 0, 2, 4,
  139971. };
  139972. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  139973. _vq_quantthresh__44c1_sm_p7_1,
  139974. _vq_quantmap__44c1_sm_p7_1,
  139975. 5,
  139976. 5
  139977. };
  139978. static static_codebook _44c1_sm_p7_1 = {
  139979. 2, 25,
  139980. _vq_lengthlist__44c1_sm_p7_1,
  139981. 1, -533725184, 1611661312, 3, 0,
  139982. _vq_quantlist__44c1_sm_p7_1,
  139983. NULL,
  139984. &_vq_auxt__44c1_sm_p7_1,
  139985. NULL,
  139986. 0
  139987. };
  139988. static long _vq_quantlist__44c1_sm_p8_0[] = {
  139989. 6,
  139990. 5,
  139991. 7,
  139992. 4,
  139993. 8,
  139994. 3,
  139995. 9,
  139996. 2,
  139997. 10,
  139998. 1,
  139999. 11,
  140000. 0,
  140001. 12,
  140002. };
  140003. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  140004. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  140005. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  140006. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140007. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140008. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140009. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140010. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140011. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140012. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140013. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140014. 13,13,13,13,13,13,13,13,13,
  140015. };
  140016. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  140017. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  140018. 552.5, 773.5, 994.5, 1215.5,
  140019. };
  140020. static long _vq_quantmap__44c1_sm_p8_0[] = {
  140021. 11, 9, 7, 5, 3, 1, 0, 2,
  140022. 4, 6, 8, 10, 12,
  140023. };
  140024. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  140025. _vq_quantthresh__44c1_sm_p8_0,
  140026. _vq_quantmap__44c1_sm_p8_0,
  140027. 13,
  140028. 13
  140029. };
  140030. static static_codebook _44c1_sm_p8_0 = {
  140031. 2, 169,
  140032. _vq_lengthlist__44c1_sm_p8_0,
  140033. 1, -514541568, 1627103232, 4, 0,
  140034. _vq_quantlist__44c1_sm_p8_0,
  140035. NULL,
  140036. &_vq_auxt__44c1_sm_p8_0,
  140037. NULL,
  140038. 0
  140039. };
  140040. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140041. 6,
  140042. 5,
  140043. 7,
  140044. 4,
  140045. 8,
  140046. 3,
  140047. 9,
  140048. 2,
  140049. 10,
  140050. 1,
  140051. 11,
  140052. 0,
  140053. 12,
  140054. };
  140055. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140056. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140057. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140058. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140059. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140060. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140061. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140062. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140063. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140064. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140065. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140066. 20,13,12,12,12,14,12,14,13,
  140067. };
  140068. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140069. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140070. 42.5, 59.5, 76.5, 93.5,
  140071. };
  140072. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140073. 11, 9, 7, 5, 3, 1, 0, 2,
  140074. 4, 6, 8, 10, 12,
  140075. };
  140076. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140077. _vq_quantthresh__44c1_sm_p8_1,
  140078. _vq_quantmap__44c1_sm_p8_1,
  140079. 13,
  140080. 13
  140081. };
  140082. static static_codebook _44c1_sm_p8_1 = {
  140083. 2, 169,
  140084. _vq_lengthlist__44c1_sm_p8_1,
  140085. 1, -522616832, 1620115456, 4, 0,
  140086. _vq_quantlist__44c1_sm_p8_1,
  140087. NULL,
  140088. &_vq_auxt__44c1_sm_p8_1,
  140089. NULL,
  140090. 0
  140091. };
  140092. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140093. 8,
  140094. 7,
  140095. 9,
  140096. 6,
  140097. 10,
  140098. 5,
  140099. 11,
  140100. 4,
  140101. 12,
  140102. 3,
  140103. 13,
  140104. 2,
  140105. 14,
  140106. 1,
  140107. 15,
  140108. 0,
  140109. 16,
  140110. };
  140111. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140112. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140113. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140114. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140115. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140116. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140117. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140118. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140119. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140120. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140121. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140122. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140123. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140124. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140125. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140126. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140127. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140128. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140129. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140130. 9,
  140131. };
  140132. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140133. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140134. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140135. };
  140136. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140137. 15, 13, 11, 9, 7, 5, 3, 1,
  140138. 0, 2, 4, 6, 8, 10, 12, 14,
  140139. 16,
  140140. };
  140141. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140142. _vq_quantthresh__44c1_sm_p8_2,
  140143. _vq_quantmap__44c1_sm_p8_2,
  140144. 17,
  140145. 17
  140146. };
  140147. static static_codebook _44c1_sm_p8_2 = {
  140148. 2, 289,
  140149. _vq_lengthlist__44c1_sm_p8_2,
  140150. 1, -529530880, 1611661312, 5, 0,
  140151. _vq_quantlist__44c1_sm_p8_2,
  140152. NULL,
  140153. &_vq_auxt__44c1_sm_p8_2,
  140154. NULL,
  140155. 0
  140156. };
  140157. static long _huff_lengthlist__44c1_sm_short[] = {
  140158. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140159. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140160. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140161. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140162. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140163. 11,
  140164. };
  140165. static static_codebook _huff_book__44c1_sm_short = {
  140166. 2, 81,
  140167. _huff_lengthlist__44c1_sm_short,
  140168. 0, 0, 0, 0, 0,
  140169. NULL,
  140170. NULL,
  140171. NULL,
  140172. NULL,
  140173. 0
  140174. };
  140175. static long _huff_lengthlist__44cn1_s_long[] = {
  140176. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140177. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140178. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140179. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140180. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140181. 20,
  140182. };
  140183. static static_codebook _huff_book__44cn1_s_long = {
  140184. 2, 81,
  140185. _huff_lengthlist__44cn1_s_long,
  140186. 0, 0, 0, 0, 0,
  140187. NULL,
  140188. NULL,
  140189. NULL,
  140190. NULL,
  140191. 0
  140192. };
  140193. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140194. 1,
  140195. 0,
  140196. 2,
  140197. };
  140198. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140199. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140200. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140205. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140210. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140245. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 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, 7,10,10, 0, 0, 0,
  140250. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 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, 7,10,10, 0, 0,
  140255. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140290. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140291. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140296. 0, 0, 0, 0, 0, 9, 9,11, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140301. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140609. 0,
  140610. };
  140611. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  140612. -0.5, 0.5,
  140613. };
  140614. static long _vq_quantmap__44cn1_s_p1_0[] = {
  140615. 1, 0, 2,
  140616. };
  140617. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  140618. _vq_quantthresh__44cn1_s_p1_0,
  140619. _vq_quantmap__44cn1_s_p1_0,
  140620. 3,
  140621. 3
  140622. };
  140623. static static_codebook _44cn1_s_p1_0 = {
  140624. 8, 6561,
  140625. _vq_lengthlist__44cn1_s_p1_0,
  140626. 1, -535822336, 1611661312, 2, 0,
  140627. _vq_quantlist__44cn1_s_p1_0,
  140628. NULL,
  140629. &_vq_auxt__44cn1_s_p1_0,
  140630. NULL,
  140631. 0
  140632. };
  140633. static long _vq_quantlist__44cn1_s_p2_0[] = {
  140634. 2,
  140635. 1,
  140636. 3,
  140637. 0,
  140638. 4,
  140639. };
  140640. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  140641. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  140646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140647. 0, 0, 0, 0, 6, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0,
  140681. };
  140682. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  140683. -1.5, -0.5, 0.5, 1.5,
  140684. };
  140685. static long _vq_quantmap__44cn1_s_p2_0[] = {
  140686. 3, 1, 0, 2, 4,
  140687. };
  140688. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  140689. _vq_quantthresh__44cn1_s_p2_0,
  140690. _vq_quantmap__44cn1_s_p2_0,
  140691. 5,
  140692. 5
  140693. };
  140694. static static_codebook _44cn1_s_p2_0 = {
  140695. 4, 625,
  140696. _vq_lengthlist__44cn1_s_p2_0,
  140697. 1, -533725184, 1611661312, 3, 0,
  140698. _vq_quantlist__44cn1_s_p2_0,
  140699. NULL,
  140700. &_vq_auxt__44cn1_s_p2_0,
  140701. NULL,
  140702. 0
  140703. };
  140704. static long _vq_quantlist__44cn1_s_p3_0[] = {
  140705. 4,
  140706. 3,
  140707. 5,
  140708. 2,
  140709. 6,
  140710. 1,
  140711. 7,
  140712. 0,
  140713. 8,
  140714. };
  140715. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  140716. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  140717. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  140718. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140719. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140720. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0,
  140722. };
  140723. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  140724. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140725. };
  140726. static long _vq_quantmap__44cn1_s_p3_0[] = {
  140727. 7, 5, 3, 1, 0, 2, 4, 6,
  140728. 8,
  140729. };
  140730. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  140731. _vq_quantthresh__44cn1_s_p3_0,
  140732. _vq_quantmap__44cn1_s_p3_0,
  140733. 9,
  140734. 9
  140735. };
  140736. static static_codebook _44cn1_s_p3_0 = {
  140737. 2, 81,
  140738. _vq_lengthlist__44cn1_s_p3_0,
  140739. 1, -531628032, 1611661312, 4, 0,
  140740. _vq_quantlist__44cn1_s_p3_0,
  140741. NULL,
  140742. &_vq_auxt__44cn1_s_p3_0,
  140743. NULL,
  140744. 0
  140745. };
  140746. static long _vq_quantlist__44cn1_s_p4_0[] = {
  140747. 4,
  140748. 3,
  140749. 5,
  140750. 2,
  140751. 6,
  140752. 1,
  140753. 7,
  140754. 0,
  140755. 8,
  140756. };
  140757. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  140758. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  140759. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  140760. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  140761. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  140762. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  140763. 11,
  140764. };
  140765. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  140766. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140767. };
  140768. static long _vq_quantmap__44cn1_s_p4_0[] = {
  140769. 7, 5, 3, 1, 0, 2, 4, 6,
  140770. 8,
  140771. };
  140772. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  140773. _vq_quantthresh__44cn1_s_p4_0,
  140774. _vq_quantmap__44cn1_s_p4_0,
  140775. 9,
  140776. 9
  140777. };
  140778. static static_codebook _44cn1_s_p4_0 = {
  140779. 2, 81,
  140780. _vq_lengthlist__44cn1_s_p4_0,
  140781. 1, -531628032, 1611661312, 4, 0,
  140782. _vq_quantlist__44cn1_s_p4_0,
  140783. NULL,
  140784. &_vq_auxt__44cn1_s_p4_0,
  140785. NULL,
  140786. 0
  140787. };
  140788. static long _vq_quantlist__44cn1_s_p5_0[] = {
  140789. 8,
  140790. 7,
  140791. 9,
  140792. 6,
  140793. 10,
  140794. 5,
  140795. 11,
  140796. 4,
  140797. 12,
  140798. 3,
  140799. 13,
  140800. 2,
  140801. 14,
  140802. 1,
  140803. 15,
  140804. 0,
  140805. 16,
  140806. };
  140807. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  140808. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  140809. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140810. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  140811. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140812. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140813. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  140814. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  140815. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  140816. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140817. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  140818. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140819. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140820. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  140821. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140822. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  140823. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  140824. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  140826. 14,
  140827. };
  140828. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  140829. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140830. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140831. };
  140832. static long _vq_quantmap__44cn1_s_p5_0[] = {
  140833. 15, 13, 11, 9, 7, 5, 3, 1,
  140834. 0, 2, 4, 6, 8, 10, 12, 14,
  140835. 16,
  140836. };
  140837. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  140838. _vq_quantthresh__44cn1_s_p5_0,
  140839. _vq_quantmap__44cn1_s_p5_0,
  140840. 17,
  140841. 17
  140842. };
  140843. static static_codebook _44cn1_s_p5_0 = {
  140844. 2, 289,
  140845. _vq_lengthlist__44cn1_s_p5_0,
  140846. 1, -529530880, 1611661312, 5, 0,
  140847. _vq_quantlist__44cn1_s_p5_0,
  140848. NULL,
  140849. &_vq_auxt__44cn1_s_p5_0,
  140850. NULL,
  140851. 0
  140852. };
  140853. static long _vq_quantlist__44cn1_s_p6_0[] = {
  140854. 1,
  140855. 0,
  140856. 2,
  140857. };
  140858. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  140859. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  140860. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  140861. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  140862. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  140863. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  140864. 10,
  140865. };
  140866. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  140867. -5.5, 5.5,
  140868. };
  140869. static long _vq_quantmap__44cn1_s_p6_0[] = {
  140870. 1, 0, 2,
  140871. };
  140872. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  140873. _vq_quantthresh__44cn1_s_p6_0,
  140874. _vq_quantmap__44cn1_s_p6_0,
  140875. 3,
  140876. 3
  140877. };
  140878. static static_codebook _44cn1_s_p6_0 = {
  140879. 4, 81,
  140880. _vq_lengthlist__44cn1_s_p6_0,
  140881. 1, -529137664, 1618345984, 2, 0,
  140882. _vq_quantlist__44cn1_s_p6_0,
  140883. NULL,
  140884. &_vq_auxt__44cn1_s_p6_0,
  140885. NULL,
  140886. 0
  140887. };
  140888. static long _vq_quantlist__44cn1_s_p6_1[] = {
  140889. 5,
  140890. 4,
  140891. 6,
  140892. 3,
  140893. 7,
  140894. 2,
  140895. 8,
  140896. 1,
  140897. 9,
  140898. 0,
  140899. 10,
  140900. };
  140901. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  140902. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  140903. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  140904. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140905. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  140906. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  140907. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  140908. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  140909. 10,10,10, 9, 9, 9, 9, 9, 9,
  140910. };
  140911. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  140912. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140913. 3.5, 4.5,
  140914. };
  140915. static long _vq_quantmap__44cn1_s_p6_1[] = {
  140916. 9, 7, 5, 3, 1, 0, 2, 4,
  140917. 6, 8, 10,
  140918. };
  140919. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  140920. _vq_quantthresh__44cn1_s_p6_1,
  140921. _vq_quantmap__44cn1_s_p6_1,
  140922. 11,
  140923. 11
  140924. };
  140925. static static_codebook _44cn1_s_p6_1 = {
  140926. 2, 121,
  140927. _vq_lengthlist__44cn1_s_p6_1,
  140928. 1, -531365888, 1611661312, 4, 0,
  140929. _vq_quantlist__44cn1_s_p6_1,
  140930. NULL,
  140931. &_vq_auxt__44cn1_s_p6_1,
  140932. NULL,
  140933. 0
  140934. };
  140935. static long _vq_quantlist__44cn1_s_p7_0[] = {
  140936. 6,
  140937. 5,
  140938. 7,
  140939. 4,
  140940. 8,
  140941. 3,
  140942. 9,
  140943. 2,
  140944. 10,
  140945. 1,
  140946. 11,
  140947. 0,
  140948. 12,
  140949. };
  140950. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  140951. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  140952. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  140953. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140954. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140955. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  140956. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  140957. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  140958. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  140959. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  140960. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  140961. 0,13,13,12,12,13,13,13,14,
  140962. };
  140963. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  140964. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140965. 12.5, 17.5, 22.5, 27.5,
  140966. };
  140967. static long _vq_quantmap__44cn1_s_p7_0[] = {
  140968. 11, 9, 7, 5, 3, 1, 0, 2,
  140969. 4, 6, 8, 10, 12,
  140970. };
  140971. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  140972. _vq_quantthresh__44cn1_s_p7_0,
  140973. _vq_quantmap__44cn1_s_p7_0,
  140974. 13,
  140975. 13
  140976. };
  140977. static static_codebook _44cn1_s_p7_0 = {
  140978. 2, 169,
  140979. _vq_lengthlist__44cn1_s_p7_0,
  140980. 1, -526516224, 1616117760, 4, 0,
  140981. _vq_quantlist__44cn1_s_p7_0,
  140982. NULL,
  140983. &_vq_auxt__44cn1_s_p7_0,
  140984. NULL,
  140985. 0
  140986. };
  140987. static long _vq_quantlist__44cn1_s_p7_1[] = {
  140988. 2,
  140989. 1,
  140990. 3,
  140991. 0,
  140992. 4,
  140993. };
  140994. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  140995. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  140996. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  140997. };
  140998. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  140999. -1.5, -0.5, 0.5, 1.5,
  141000. };
  141001. static long _vq_quantmap__44cn1_s_p7_1[] = {
  141002. 3, 1, 0, 2, 4,
  141003. };
  141004. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  141005. _vq_quantthresh__44cn1_s_p7_1,
  141006. _vq_quantmap__44cn1_s_p7_1,
  141007. 5,
  141008. 5
  141009. };
  141010. static static_codebook _44cn1_s_p7_1 = {
  141011. 2, 25,
  141012. _vq_lengthlist__44cn1_s_p7_1,
  141013. 1, -533725184, 1611661312, 3, 0,
  141014. _vq_quantlist__44cn1_s_p7_1,
  141015. NULL,
  141016. &_vq_auxt__44cn1_s_p7_1,
  141017. NULL,
  141018. 0
  141019. };
  141020. static long _vq_quantlist__44cn1_s_p8_0[] = {
  141021. 2,
  141022. 1,
  141023. 3,
  141024. 0,
  141025. 4,
  141026. };
  141027. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  141028. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  141029. 11,11,11,11,11,11,11,11,11,11,11,10,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,10,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, 7,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,10,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,10,
  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, 8,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,11,11,11,11,11,11,11,11,11,
  141047. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141048. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141049. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141050. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141051. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141052. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141053. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141054. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141055. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141056. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141057. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141058. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141059. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141060. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141061. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141062. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141063. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141064. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141065. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141066. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141067. 12,
  141068. };
  141069. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141070. -331.5, -110.5, 110.5, 331.5,
  141071. };
  141072. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141073. 3, 1, 0, 2, 4,
  141074. };
  141075. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141076. _vq_quantthresh__44cn1_s_p8_0,
  141077. _vq_quantmap__44cn1_s_p8_0,
  141078. 5,
  141079. 5
  141080. };
  141081. static static_codebook _44cn1_s_p8_0 = {
  141082. 4, 625,
  141083. _vq_lengthlist__44cn1_s_p8_0,
  141084. 1, -518283264, 1627103232, 3, 0,
  141085. _vq_quantlist__44cn1_s_p8_0,
  141086. NULL,
  141087. &_vq_auxt__44cn1_s_p8_0,
  141088. NULL,
  141089. 0
  141090. };
  141091. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141092. 6,
  141093. 5,
  141094. 7,
  141095. 4,
  141096. 8,
  141097. 3,
  141098. 9,
  141099. 2,
  141100. 10,
  141101. 1,
  141102. 11,
  141103. 0,
  141104. 12,
  141105. };
  141106. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141107. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141108. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141109. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141110. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141111. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141112. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141113. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141114. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141115. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141116. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141117. 15,12,12,11,11,14,12,13,14,
  141118. };
  141119. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141120. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141121. 42.5, 59.5, 76.5, 93.5,
  141122. };
  141123. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141124. 11, 9, 7, 5, 3, 1, 0, 2,
  141125. 4, 6, 8, 10, 12,
  141126. };
  141127. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141128. _vq_quantthresh__44cn1_s_p8_1,
  141129. _vq_quantmap__44cn1_s_p8_1,
  141130. 13,
  141131. 13
  141132. };
  141133. static static_codebook _44cn1_s_p8_1 = {
  141134. 2, 169,
  141135. _vq_lengthlist__44cn1_s_p8_1,
  141136. 1, -522616832, 1620115456, 4, 0,
  141137. _vq_quantlist__44cn1_s_p8_1,
  141138. NULL,
  141139. &_vq_auxt__44cn1_s_p8_1,
  141140. NULL,
  141141. 0
  141142. };
  141143. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141144. 8,
  141145. 7,
  141146. 9,
  141147. 6,
  141148. 10,
  141149. 5,
  141150. 11,
  141151. 4,
  141152. 12,
  141153. 3,
  141154. 13,
  141155. 2,
  141156. 14,
  141157. 1,
  141158. 15,
  141159. 0,
  141160. 16,
  141161. };
  141162. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141163. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141164. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141165. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141166. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141167. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141168. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141169. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141170. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141171. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141172. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141173. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141174. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141175. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141176. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141177. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141178. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141179. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141180. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141181. 9,
  141182. };
  141183. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141184. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141185. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141186. };
  141187. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141188. 15, 13, 11, 9, 7, 5, 3, 1,
  141189. 0, 2, 4, 6, 8, 10, 12, 14,
  141190. 16,
  141191. };
  141192. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141193. _vq_quantthresh__44cn1_s_p8_2,
  141194. _vq_quantmap__44cn1_s_p8_2,
  141195. 17,
  141196. 17
  141197. };
  141198. static static_codebook _44cn1_s_p8_2 = {
  141199. 2, 289,
  141200. _vq_lengthlist__44cn1_s_p8_2,
  141201. 1, -529530880, 1611661312, 5, 0,
  141202. _vq_quantlist__44cn1_s_p8_2,
  141203. NULL,
  141204. &_vq_auxt__44cn1_s_p8_2,
  141205. NULL,
  141206. 0
  141207. };
  141208. static long _huff_lengthlist__44cn1_s_short[] = {
  141209. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141210. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141211. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141212. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141213. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141214. 10,
  141215. };
  141216. static static_codebook _huff_book__44cn1_s_short = {
  141217. 2, 81,
  141218. _huff_lengthlist__44cn1_s_short,
  141219. 0, 0, 0, 0, 0,
  141220. NULL,
  141221. NULL,
  141222. NULL,
  141223. NULL,
  141224. 0
  141225. };
  141226. static long _huff_lengthlist__44cn1_sm_long[] = {
  141227. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141228. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141229. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141230. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141231. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141232. 17,
  141233. };
  141234. static static_codebook _huff_book__44cn1_sm_long = {
  141235. 2, 81,
  141236. _huff_lengthlist__44cn1_sm_long,
  141237. 0, 0, 0, 0, 0,
  141238. NULL,
  141239. NULL,
  141240. NULL,
  141241. NULL,
  141242. 0
  141243. };
  141244. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141245. 1,
  141246. 0,
  141247. 2,
  141248. };
  141249. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141250. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141251. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141256. 0, 0, 0, 7, 8, 9, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141261. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141296. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 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, 7,10, 9, 0, 0, 0,
  141301. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 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, 7, 9, 9, 0, 0,
  141306. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141307. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141308. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141309. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141310. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141311. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141312. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141313. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141314. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141315. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141316. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141317. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141318. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141319. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141320. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141321. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141322. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141323. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141324. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141325. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141326. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141327. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141328. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141329. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141330. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141331. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141332. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141333. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141334. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141335. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141336. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141337. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141338. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141339. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141340. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141341. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141342. 0, 0, 0, 0, 8, 9,10, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141347. 0, 0, 0, 0, 0, 8, 9,10, 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, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141352. 0, 0, 0, 0, 0, 0, 9,10, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141660. 0,
  141661. };
  141662. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  141663. -0.5, 0.5,
  141664. };
  141665. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  141666. 1, 0, 2,
  141667. };
  141668. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  141669. _vq_quantthresh__44cn1_sm_p1_0,
  141670. _vq_quantmap__44cn1_sm_p1_0,
  141671. 3,
  141672. 3
  141673. };
  141674. static static_codebook _44cn1_sm_p1_0 = {
  141675. 8, 6561,
  141676. _vq_lengthlist__44cn1_sm_p1_0,
  141677. 1, -535822336, 1611661312, 2, 0,
  141678. _vq_quantlist__44cn1_sm_p1_0,
  141679. NULL,
  141680. &_vq_auxt__44cn1_sm_p1_0,
  141681. NULL,
  141682. 0
  141683. };
  141684. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  141685. 2,
  141686. 1,
  141687. 3,
  141688. 0,
  141689. 4,
  141690. };
  141691. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  141692. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141698. 0, 0, 0, 0, 7, 7, 7, 9, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141731. 0,
  141732. };
  141733. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  141734. -1.5, -0.5, 0.5, 1.5,
  141735. };
  141736. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  141737. 3, 1, 0, 2, 4,
  141738. };
  141739. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  141740. _vq_quantthresh__44cn1_sm_p2_0,
  141741. _vq_quantmap__44cn1_sm_p2_0,
  141742. 5,
  141743. 5
  141744. };
  141745. static static_codebook _44cn1_sm_p2_0 = {
  141746. 4, 625,
  141747. _vq_lengthlist__44cn1_sm_p2_0,
  141748. 1, -533725184, 1611661312, 3, 0,
  141749. _vq_quantlist__44cn1_sm_p2_0,
  141750. NULL,
  141751. &_vq_auxt__44cn1_sm_p2_0,
  141752. NULL,
  141753. 0
  141754. };
  141755. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  141756. 4,
  141757. 3,
  141758. 5,
  141759. 2,
  141760. 6,
  141761. 1,
  141762. 7,
  141763. 0,
  141764. 8,
  141765. };
  141766. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  141767. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  141768. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  141769. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  141770. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  141771. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141772. 0,
  141773. };
  141774. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  141775. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141776. };
  141777. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  141778. 7, 5, 3, 1, 0, 2, 4, 6,
  141779. 8,
  141780. };
  141781. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  141782. _vq_quantthresh__44cn1_sm_p3_0,
  141783. _vq_quantmap__44cn1_sm_p3_0,
  141784. 9,
  141785. 9
  141786. };
  141787. static static_codebook _44cn1_sm_p3_0 = {
  141788. 2, 81,
  141789. _vq_lengthlist__44cn1_sm_p3_0,
  141790. 1, -531628032, 1611661312, 4, 0,
  141791. _vq_quantlist__44cn1_sm_p3_0,
  141792. NULL,
  141793. &_vq_auxt__44cn1_sm_p3_0,
  141794. NULL,
  141795. 0
  141796. };
  141797. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  141798. 4,
  141799. 3,
  141800. 5,
  141801. 2,
  141802. 6,
  141803. 1,
  141804. 7,
  141805. 0,
  141806. 8,
  141807. };
  141808. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  141809. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  141810. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  141811. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  141812. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141813. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141814. 11,
  141815. };
  141816. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  141817. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141818. };
  141819. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  141820. 7, 5, 3, 1, 0, 2, 4, 6,
  141821. 8,
  141822. };
  141823. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  141824. _vq_quantthresh__44cn1_sm_p4_0,
  141825. _vq_quantmap__44cn1_sm_p4_0,
  141826. 9,
  141827. 9
  141828. };
  141829. static static_codebook _44cn1_sm_p4_0 = {
  141830. 2, 81,
  141831. _vq_lengthlist__44cn1_sm_p4_0,
  141832. 1, -531628032, 1611661312, 4, 0,
  141833. _vq_quantlist__44cn1_sm_p4_0,
  141834. NULL,
  141835. &_vq_auxt__44cn1_sm_p4_0,
  141836. NULL,
  141837. 0
  141838. };
  141839. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  141840. 8,
  141841. 7,
  141842. 9,
  141843. 6,
  141844. 10,
  141845. 5,
  141846. 11,
  141847. 4,
  141848. 12,
  141849. 3,
  141850. 13,
  141851. 2,
  141852. 14,
  141853. 1,
  141854. 15,
  141855. 0,
  141856. 16,
  141857. };
  141858. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  141859. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  141860. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  141861. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  141862. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141863. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  141864. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  141865. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  141866. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  141867. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  141868. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  141869. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  141870. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  141871. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  141872. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  141873. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  141874. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  141875. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  141876. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  141877. 14,
  141878. };
  141879. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  141880. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141881. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141882. };
  141883. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  141884. 15, 13, 11, 9, 7, 5, 3, 1,
  141885. 0, 2, 4, 6, 8, 10, 12, 14,
  141886. 16,
  141887. };
  141888. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  141889. _vq_quantthresh__44cn1_sm_p5_0,
  141890. _vq_quantmap__44cn1_sm_p5_0,
  141891. 17,
  141892. 17
  141893. };
  141894. static static_codebook _44cn1_sm_p5_0 = {
  141895. 2, 289,
  141896. _vq_lengthlist__44cn1_sm_p5_0,
  141897. 1, -529530880, 1611661312, 5, 0,
  141898. _vq_quantlist__44cn1_sm_p5_0,
  141899. NULL,
  141900. &_vq_auxt__44cn1_sm_p5_0,
  141901. NULL,
  141902. 0
  141903. };
  141904. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  141905. 1,
  141906. 0,
  141907. 2,
  141908. };
  141909. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  141910. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  141911. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  141912. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  141913. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  141914. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  141915. 10,
  141916. };
  141917. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  141918. -5.5, 5.5,
  141919. };
  141920. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  141921. 1, 0, 2,
  141922. };
  141923. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  141924. _vq_quantthresh__44cn1_sm_p6_0,
  141925. _vq_quantmap__44cn1_sm_p6_0,
  141926. 3,
  141927. 3
  141928. };
  141929. static static_codebook _44cn1_sm_p6_0 = {
  141930. 4, 81,
  141931. _vq_lengthlist__44cn1_sm_p6_0,
  141932. 1, -529137664, 1618345984, 2, 0,
  141933. _vq_quantlist__44cn1_sm_p6_0,
  141934. NULL,
  141935. &_vq_auxt__44cn1_sm_p6_0,
  141936. NULL,
  141937. 0
  141938. };
  141939. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  141940. 5,
  141941. 4,
  141942. 6,
  141943. 3,
  141944. 7,
  141945. 2,
  141946. 8,
  141947. 1,
  141948. 9,
  141949. 0,
  141950. 10,
  141951. };
  141952. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  141953. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  141954. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  141955. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141956. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  141957. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  141958. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  141959. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  141960. 10,10,10, 8, 9, 8, 8, 9, 8,
  141961. };
  141962. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  141963. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141964. 3.5, 4.5,
  141965. };
  141966. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  141967. 9, 7, 5, 3, 1, 0, 2, 4,
  141968. 6, 8, 10,
  141969. };
  141970. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  141971. _vq_quantthresh__44cn1_sm_p6_1,
  141972. _vq_quantmap__44cn1_sm_p6_1,
  141973. 11,
  141974. 11
  141975. };
  141976. static static_codebook _44cn1_sm_p6_1 = {
  141977. 2, 121,
  141978. _vq_lengthlist__44cn1_sm_p6_1,
  141979. 1, -531365888, 1611661312, 4, 0,
  141980. _vq_quantlist__44cn1_sm_p6_1,
  141981. NULL,
  141982. &_vq_auxt__44cn1_sm_p6_1,
  141983. NULL,
  141984. 0
  141985. };
  141986. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  141987. 6,
  141988. 5,
  141989. 7,
  141990. 4,
  141991. 8,
  141992. 3,
  141993. 9,
  141994. 2,
  141995. 10,
  141996. 1,
  141997. 11,
  141998. 0,
  141999. 12,
  142000. };
  142001. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  142002. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  142003. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  142004. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  142005. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  142006. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  142007. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  142008. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  142009. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  142010. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  142011. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  142012. 0,13,12,12,12,13,13,13,14,
  142013. };
  142014. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  142015. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142016. 12.5, 17.5, 22.5, 27.5,
  142017. };
  142018. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  142019. 11, 9, 7, 5, 3, 1, 0, 2,
  142020. 4, 6, 8, 10, 12,
  142021. };
  142022. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  142023. _vq_quantthresh__44cn1_sm_p7_0,
  142024. _vq_quantmap__44cn1_sm_p7_0,
  142025. 13,
  142026. 13
  142027. };
  142028. static static_codebook _44cn1_sm_p7_0 = {
  142029. 2, 169,
  142030. _vq_lengthlist__44cn1_sm_p7_0,
  142031. 1, -526516224, 1616117760, 4, 0,
  142032. _vq_quantlist__44cn1_sm_p7_0,
  142033. NULL,
  142034. &_vq_auxt__44cn1_sm_p7_0,
  142035. NULL,
  142036. 0
  142037. };
  142038. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  142039. 2,
  142040. 1,
  142041. 3,
  142042. 0,
  142043. 4,
  142044. };
  142045. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142046. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142047. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142048. };
  142049. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142050. -1.5, -0.5, 0.5, 1.5,
  142051. };
  142052. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142053. 3, 1, 0, 2, 4,
  142054. };
  142055. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142056. _vq_quantthresh__44cn1_sm_p7_1,
  142057. _vq_quantmap__44cn1_sm_p7_1,
  142058. 5,
  142059. 5
  142060. };
  142061. static static_codebook _44cn1_sm_p7_1 = {
  142062. 2, 25,
  142063. _vq_lengthlist__44cn1_sm_p7_1,
  142064. 1, -533725184, 1611661312, 3, 0,
  142065. _vq_quantlist__44cn1_sm_p7_1,
  142066. NULL,
  142067. &_vq_auxt__44cn1_sm_p7_1,
  142068. NULL,
  142069. 0
  142070. };
  142071. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142072. 4,
  142073. 3,
  142074. 5,
  142075. 2,
  142076. 6,
  142077. 1,
  142078. 7,
  142079. 0,
  142080. 8,
  142081. };
  142082. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142083. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142084. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142085. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142086. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142087. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142088. 14,
  142089. };
  142090. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142091. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142092. };
  142093. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142094. 7, 5, 3, 1, 0, 2, 4, 6,
  142095. 8,
  142096. };
  142097. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142098. _vq_quantthresh__44cn1_sm_p8_0,
  142099. _vq_quantmap__44cn1_sm_p8_0,
  142100. 9,
  142101. 9
  142102. };
  142103. static static_codebook _44cn1_sm_p8_0 = {
  142104. 2, 81,
  142105. _vq_lengthlist__44cn1_sm_p8_0,
  142106. 1, -516186112, 1627103232, 4, 0,
  142107. _vq_quantlist__44cn1_sm_p8_0,
  142108. NULL,
  142109. &_vq_auxt__44cn1_sm_p8_0,
  142110. NULL,
  142111. 0
  142112. };
  142113. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142114. 6,
  142115. 5,
  142116. 7,
  142117. 4,
  142118. 8,
  142119. 3,
  142120. 9,
  142121. 2,
  142122. 10,
  142123. 1,
  142124. 11,
  142125. 0,
  142126. 12,
  142127. };
  142128. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142129. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142130. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142131. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142132. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142133. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142134. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142135. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142136. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142137. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142138. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142139. 17,12,12,11,10,13,11,13,13,
  142140. };
  142141. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142142. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142143. 42.5, 59.5, 76.5, 93.5,
  142144. };
  142145. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142146. 11, 9, 7, 5, 3, 1, 0, 2,
  142147. 4, 6, 8, 10, 12,
  142148. };
  142149. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142150. _vq_quantthresh__44cn1_sm_p8_1,
  142151. _vq_quantmap__44cn1_sm_p8_1,
  142152. 13,
  142153. 13
  142154. };
  142155. static static_codebook _44cn1_sm_p8_1 = {
  142156. 2, 169,
  142157. _vq_lengthlist__44cn1_sm_p8_1,
  142158. 1, -522616832, 1620115456, 4, 0,
  142159. _vq_quantlist__44cn1_sm_p8_1,
  142160. NULL,
  142161. &_vq_auxt__44cn1_sm_p8_1,
  142162. NULL,
  142163. 0
  142164. };
  142165. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142166. 8,
  142167. 7,
  142168. 9,
  142169. 6,
  142170. 10,
  142171. 5,
  142172. 11,
  142173. 4,
  142174. 12,
  142175. 3,
  142176. 13,
  142177. 2,
  142178. 14,
  142179. 1,
  142180. 15,
  142181. 0,
  142182. 16,
  142183. };
  142184. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142185. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142186. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142187. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142188. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142189. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142190. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142191. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142192. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142193. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142194. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142195. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142196. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142197. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142198. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142199. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142200. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142201. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142202. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142203. 9,
  142204. };
  142205. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142206. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142207. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142208. };
  142209. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142210. 15, 13, 11, 9, 7, 5, 3, 1,
  142211. 0, 2, 4, 6, 8, 10, 12, 14,
  142212. 16,
  142213. };
  142214. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142215. _vq_quantthresh__44cn1_sm_p8_2,
  142216. _vq_quantmap__44cn1_sm_p8_2,
  142217. 17,
  142218. 17
  142219. };
  142220. static static_codebook _44cn1_sm_p8_2 = {
  142221. 2, 289,
  142222. _vq_lengthlist__44cn1_sm_p8_2,
  142223. 1, -529530880, 1611661312, 5, 0,
  142224. _vq_quantlist__44cn1_sm_p8_2,
  142225. NULL,
  142226. &_vq_auxt__44cn1_sm_p8_2,
  142227. NULL,
  142228. 0
  142229. };
  142230. static long _huff_lengthlist__44cn1_sm_short[] = {
  142231. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142232. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142233. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142234. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142235. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142236. 9,
  142237. };
  142238. static static_codebook _huff_book__44cn1_sm_short = {
  142239. 2, 81,
  142240. _huff_lengthlist__44cn1_sm_short,
  142241. 0, 0, 0, 0, 0,
  142242. NULL,
  142243. NULL,
  142244. NULL,
  142245. NULL,
  142246. 0
  142247. };
  142248. /*** End of inlined file: res_books_stereo.h ***/
  142249. /***** residue backends *********************************************/
  142250. static vorbis_info_residue0 _residue_44_low={
  142251. 0,-1, -1, 9,-1,
  142252. /* 0 1 2 3 4 5 6 7 */
  142253. {0},
  142254. {-1},
  142255. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142256. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142257. };
  142258. static vorbis_info_residue0 _residue_44_mid={
  142259. 0,-1, -1, 10,-1,
  142260. /* 0 1 2 3 4 5 6 7 8 */
  142261. {0},
  142262. {-1},
  142263. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142264. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142265. };
  142266. static vorbis_info_residue0 _residue_44_high={
  142267. 0,-1, -1, 10,-1,
  142268. /* 0 1 2 3 4 5 6 7 8 */
  142269. {0},
  142270. {-1},
  142271. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142272. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142273. };
  142274. static static_bookblock _resbook_44s_n1={
  142275. {
  142276. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142277. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142278. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142279. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142280. }
  142281. };
  142282. static static_bookblock _resbook_44sm_n1={
  142283. {
  142284. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142285. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142286. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142287. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142288. }
  142289. };
  142290. static static_bookblock _resbook_44s_0={
  142291. {
  142292. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142293. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142294. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142295. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142296. }
  142297. };
  142298. static static_bookblock _resbook_44sm_0={
  142299. {
  142300. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142301. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142302. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142303. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142304. }
  142305. };
  142306. static static_bookblock _resbook_44s_1={
  142307. {
  142308. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142309. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142310. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142311. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142312. }
  142313. };
  142314. static static_bookblock _resbook_44sm_1={
  142315. {
  142316. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142317. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142318. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142319. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142320. }
  142321. };
  142322. static static_bookblock _resbook_44s_2={
  142323. {
  142324. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142325. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142326. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142327. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142328. }
  142329. };
  142330. static static_bookblock _resbook_44s_3={
  142331. {
  142332. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142333. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142334. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142335. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142336. }
  142337. };
  142338. static static_bookblock _resbook_44s_4={
  142339. {
  142340. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142341. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142342. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142343. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142344. }
  142345. };
  142346. static static_bookblock _resbook_44s_5={
  142347. {
  142348. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142349. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142350. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142351. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142352. }
  142353. };
  142354. static static_bookblock _resbook_44s_6={
  142355. {
  142356. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142357. {0,0,&_44c6_s_p4_0},
  142358. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142359. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142360. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142361. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142362. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142363. }
  142364. };
  142365. static static_bookblock _resbook_44s_7={
  142366. {
  142367. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142368. {0,0,&_44c7_s_p4_0},
  142369. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142370. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142371. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142372. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142373. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142374. }
  142375. };
  142376. static static_bookblock _resbook_44s_8={
  142377. {
  142378. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142379. {0,0,&_44c8_s_p4_0},
  142380. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142381. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142382. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142383. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142384. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142385. }
  142386. };
  142387. static static_bookblock _resbook_44s_9={
  142388. {
  142389. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142390. {0,0,&_44c9_s_p4_0},
  142391. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142392. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142393. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142394. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142395. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142396. }
  142397. };
  142398. static vorbis_residue_template _res_44s_n1[]={
  142399. {2,0, &_residue_44_low,
  142400. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142401. &_resbook_44s_n1,&_resbook_44sm_n1},
  142402. {2,0, &_residue_44_low,
  142403. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142404. &_resbook_44s_n1,&_resbook_44sm_n1}
  142405. };
  142406. static vorbis_residue_template _res_44s_0[]={
  142407. {2,0, &_residue_44_low,
  142408. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142409. &_resbook_44s_0,&_resbook_44sm_0},
  142410. {2,0, &_residue_44_low,
  142411. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142412. &_resbook_44s_0,&_resbook_44sm_0}
  142413. };
  142414. static vorbis_residue_template _res_44s_1[]={
  142415. {2,0, &_residue_44_low,
  142416. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142417. &_resbook_44s_1,&_resbook_44sm_1},
  142418. {2,0, &_residue_44_low,
  142419. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142420. &_resbook_44s_1,&_resbook_44sm_1}
  142421. };
  142422. static vorbis_residue_template _res_44s_2[]={
  142423. {2,0, &_residue_44_mid,
  142424. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142425. &_resbook_44s_2,&_resbook_44s_2},
  142426. {2,0, &_residue_44_mid,
  142427. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142428. &_resbook_44s_2,&_resbook_44s_2}
  142429. };
  142430. static vorbis_residue_template _res_44s_3[]={
  142431. {2,0, &_residue_44_mid,
  142432. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142433. &_resbook_44s_3,&_resbook_44s_3},
  142434. {2,0, &_residue_44_mid,
  142435. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142436. &_resbook_44s_3,&_resbook_44s_3}
  142437. };
  142438. static vorbis_residue_template _res_44s_4[]={
  142439. {2,0, &_residue_44_mid,
  142440. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142441. &_resbook_44s_4,&_resbook_44s_4},
  142442. {2,0, &_residue_44_mid,
  142443. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142444. &_resbook_44s_4,&_resbook_44s_4}
  142445. };
  142446. static vorbis_residue_template _res_44s_5[]={
  142447. {2,0, &_residue_44_mid,
  142448. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142449. &_resbook_44s_5,&_resbook_44s_5},
  142450. {2,0, &_residue_44_mid,
  142451. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142452. &_resbook_44s_5,&_resbook_44s_5}
  142453. };
  142454. static vorbis_residue_template _res_44s_6[]={
  142455. {2,0, &_residue_44_high,
  142456. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142457. &_resbook_44s_6,&_resbook_44s_6},
  142458. {2,0, &_residue_44_high,
  142459. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142460. &_resbook_44s_6,&_resbook_44s_6}
  142461. };
  142462. static vorbis_residue_template _res_44s_7[]={
  142463. {2,0, &_residue_44_high,
  142464. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142465. &_resbook_44s_7,&_resbook_44s_7},
  142466. {2,0, &_residue_44_high,
  142467. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142468. &_resbook_44s_7,&_resbook_44s_7}
  142469. };
  142470. static vorbis_residue_template _res_44s_8[]={
  142471. {2,0, &_residue_44_high,
  142472. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142473. &_resbook_44s_8,&_resbook_44s_8},
  142474. {2,0, &_residue_44_high,
  142475. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142476. &_resbook_44s_8,&_resbook_44s_8}
  142477. };
  142478. static vorbis_residue_template _res_44s_9[]={
  142479. {2,0, &_residue_44_high,
  142480. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142481. &_resbook_44s_9,&_resbook_44s_9},
  142482. {2,0, &_residue_44_high,
  142483. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142484. &_resbook_44s_9,&_resbook_44s_9}
  142485. };
  142486. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142487. { _map_nominal, _res_44s_n1 }, /* -1 */
  142488. { _map_nominal, _res_44s_0 }, /* 0 */
  142489. { _map_nominal, _res_44s_1 }, /* 1 */
  142490. { _map_nominal, _res_44s_2 }, /* 2 */
  142491. { _map_nominal, _res_44s_3 }, /* 3 */
  142492. { _map_nominal, _res_44s_4 }, /* 4 */
  142493. { _map_nominal, _res_44s_5 }, /* 5 */
  142494. { _map_nominal, _res_44s_6 }, /* 6 */
  142495. { _map_nominal, _res_44s_7 }, /* 7 */
  142496. { _map_nominal, _res_44s_8 }, /* 8 */
  142497. { _map_nominal, _res_44s_9 }, /* 9 */
  142498. };
  142499. /*** End of inlined file: residue_44.h ***/
  142500. /*** Start of inlined file: psych_44.h ***/
  142501. /* preecho trigger settings *****************************************/
  142502. static vorbis_info_psy_global _psy_global_44[5]={
  142503. {8, /* lines per eighth octave */
  142504. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142505. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142506. -6.f,
  142507. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142508. },
  142509. {8, /* lines per eighth octave */
  142510. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142511. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142512. -6.f,
  142513. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142514. },
  142515. {8, /* lines per eighth octave */
  142516. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142517. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142518. -6.f,
  142519. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142520. },
  142521. {8, /* lines per eighth octave */
  142522. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142523. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142524. -6.f,
  142525. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142526. },
  142527. {8, /* lines per eighth octave */
  142528. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142529. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142530. -6.f,
  142531. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142532. },
  142533. };
  142534. /* noise compander lookups * low, mid, high quality ****************/
  142535. static compandblock _psy_compand_44[6]={
  142536. /* sub-mode Z short */
  142537. {{
  142538. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142539. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142540. 16,17,18,19,20,21,22, 23, /* 23dB */
  142541. 24,25,26,27,28,29,30, 31, /* 31dB */
  142542. 32,33,34,35,36,37,38, 39, /* 39dB */
  142543. }},
  142544. /* mode_Z nominal short */
  142545. {{
  142546. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142547. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142548. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142549. 15,16,17,17,17,18,18, 19, /* 31dB */
  142550. 19,19,20,21,22,23,24, 25, /* 39dB */
  142551. }},
  142552. /* mode A short */
  142553. {{
  142554. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142555. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142556. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142557. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142558. 11,12,13,14,15,16,17, 18, /* 39dB */
  142559. }},
  142560. /* sub-mode Z long */
  142561. {{
  142562. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142563. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142564. 16,17,18,19,20,21,22, 23, /* 23dB */
  142565. 24,25,26,27,28,29,30, 31, /* 31dB */
  142566. 32,33,34,35,36,37,38, 39, /* 39dB */
  142567. }},
  142568. /* mode_Z nominal long */
  142569. {{
  142570. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142571. 8, 9,10,11,12,12,13, 13, /* 15dB */
  142572. 13,14,14,14,15,15,15, 15, /* 23dB */
  142573. 16,16,17,17,17,18,18, 19, /* 31dB */
  142574. 19,19,20,21,22,23,24, 25, /* 39dB */
  142575. }},
  142576. /* mode A long */
  142577. {{
  142578. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142579. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  142580. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142581. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142582. 11,12,13,14,15,16,17, 18, /* 39dB */
  142583. }}
  142584. };
  142585. /* tonal masking curve level adjustments *************************/
  142586. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  142587. /* 63 125 250 500 1 2 4 8 16 */
  142588. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  142589. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142590. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  142591. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142592. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  142593. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142594. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  142595. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142596. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  142597. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  142598. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142599. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142600. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142601. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142602. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142603. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142604. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142605. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142606. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142607. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142608. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142609. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142610. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142611. };
  142612. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  142613. /* 63 125 250 500 1 2 4 8 16 */
  142614. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  142615. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  142616. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  142617. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  142618. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  142619. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  142620. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  142621. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  142622. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  142623. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  142624. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  142625. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  142626. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  142627. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  142628. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  142629. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  142630. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  142631. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  142632. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  142633. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  142634. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  142635. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  142636. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  142637. };
  142638. /* noise bias (transition block) */
  142639. static noise3 _psy_noisebias_trans[12]={
  142640. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142641. /* -1 */
  142642. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142643. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142644. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142645. /* 0
  142646. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142647. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  142648. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142649. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142650. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  142651. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142652. /* 1
  142653. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142654. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142655. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142656. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142657. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142658. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142659. /* 2
  142660. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142661. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142662. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  142663. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142664. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142665. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  142666. /* 3
  142667. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142668. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142669. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142670. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142671. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142672. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142673. /* 4
  142674. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142675. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142676. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142677. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142678. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142679. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142680. /* 5
  142681. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142682. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142683. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  142684. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142685. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142686. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  142687. /* 6
  142688. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142689. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142690. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142691. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142692. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142693. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142694. /* 7
  142695. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142696. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  142697. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  142698. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  142699. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142700. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142701. /* 8
  142702. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142703. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  142704. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142705. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  142706. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142707. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142708. /* 9
  142709. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142710. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  142711. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142712. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142713. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  142714. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  142715. /* 10 */
  142716. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  142717. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  142718. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142719. };
  142720. /* noise bias (long block) */
  142721. static noise3 _psy_noisebias_long[12]={
  142722. /*63 125 250 500 1k 2k 4k 8k 16k*/
  142723. /* -1 */
  142724. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  142725. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  142726. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142727. /* 0 */
  142728. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142729. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  142730. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  142731. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  142732. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  142733. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  142734. /* 1 */
  142735. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142736. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  142737. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  142738. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  142739. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  142740. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  142741. /* 2 */
  142742. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142743. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  142744. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142745. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  142746. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  142747. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  142748. /* 3 */
  142749. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142750. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  142751. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142752. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  142753. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  142754. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  142755. /* 4 */
  142756. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142757. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  142758. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  142759. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142760. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  142761. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  142762. /* 5 */
  142763. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142764. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  142765. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  142766. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142767. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  142768. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  142769. /* 6 */
  142770. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142771. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  142772. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  142773. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142774. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  142775. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  142776. /* 7 */
  142777. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  142778. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  142779. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  142780. /* 8 */
  142781. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  142782. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  142783. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  142784. /* 9 */
  142785. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142786. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  142787. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142788. /* 10 */
  142789. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  142790. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  142791. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142792. };
  142793. /* noise bias (impulse block) */
  142794. static noise3 _psy_noisebias_impulse[12]={
  142795. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142796. /* -1 */
  142797. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142798. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142799. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142800. /* 0 */
  142801. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142802. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  142803. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  142804. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  142805. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  142806. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142807. /* 1 */
  142808. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142809. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  142810. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  142811. /* 2 */
  142812. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142813. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142814. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142815. /* 3 */
  142816. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142817. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142818. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142819. /* 4 */
  142820. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142821. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  142822. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  142823. /* 5 */
  142824. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142825. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  142826. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  142827. /* 6
  142828. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142829. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  142830. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  142831. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  142832. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  142833. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  142834. /* 7 */
  142835. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142836. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  142837. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  142838. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  142839. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  142840. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142841. /* 8 */
  142842. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142843. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  142844. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  142845. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  142846. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  142847. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  142848. /* 9 */
  142849. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142850. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  142851. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  142852. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  142853. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  142854. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  142855. /* 10 */
  142856. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  142857. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  142858. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142859. };
  142860. /* noise bias (padding block) */
  142861. static noise3 _psy_noisebias_padding[12]={
  142862. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  142863. /* -1 */
  142864. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142865. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  142866. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  142867. /* 0 */
  142868. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  142869. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  142870. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  142871. /* 1 */
  142872. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  142873. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142874. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  142875. /* 2 */
  142876. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142877. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  142878. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  142879. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  142880. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142881. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142882. /* 3 */
  142883. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  142884. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  142885. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142886. /* 4 */
  142887. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  142888. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  142889. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  142890. /* 5 */
  142891. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142892. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  142893. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  142894. /* 6 */
  142895. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142896. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  142897. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  142898. /* 7 */
  142899. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  142900. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  142901. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  142902. /* 8 */
  142903. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  142904. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  142905. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  142906. /* 9 */
  142907. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  142908. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  142909. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  142910. /* 10 */
  142911. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  142912. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  142913. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  142914. };
  142915. static noiseguard _psy_noiseguards_44[4]={
  142916. {3,3,15},
  142917. {3,3,15},
  142918. {10,10,100},
  142919. {10,10,100},
  142920. };
  142921. static int _psy_tone_suppress[12]={
  142922. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  142923. };
  142924. static int _psy_tone_0dB[12]={
  142925. 90,90,95,95,95,95,105,105,105,105,105,105,
  142926. };
  142927. static int _psy_noise_suppress[12]={
  142928. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  142929. };
  142930. static vorbis_info_psy _psy_info_template={
  142931. /* blockflag */
  142932. -1,
  142933. /* ath_adjatt, ath_maxatt */
  142934. -140.,-140.,
  142935. /* tonemask att boost/decay,suppr,curves */
  142936. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  142937. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  142938. 1, -0.f, .5f, .5f, 0,0,0,
  142939. /* noiseoffset*3, noisecompand, max_curve_dB */
  142940. {{-1},{-1},{-1}},{-1},105.f,
  142941. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  142942. 0,0,-1,-1,0.,
  142943. };
  142944. /* ath ****************/
  142945. static int _psy_ath_floater[12]={
  142946. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  142947. };
  142948. static int _psy_ath_abs[12]={
  142949. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  142950. };
  142951. /* stereo setup. These don't map directly to quality level, there's
  142952. an additional indirection as several of the below may be used in a
  142953. single bitmanaged stream
  142954. ****************/
  142955. /* various stereo possibilities */
  142956. /* stereo mode by base quality level */
  142957. static adj_stereo _psy_stereo_modes_44[12]={
  142958. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  142959. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142960. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142961. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  142962. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142963. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  142964. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  142965. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  142966. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  142967. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  142968. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  142969. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142970. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142971. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  142972. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  142973. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  142974. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  142975. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142976. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142977. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  142978. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  142979. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  142980. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142981. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  142982. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  142983. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142984. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  142985. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142986. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  142987. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  142988. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  142989. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  142990. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142991. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  142992. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142993. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  142994. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  142995. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  142996. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  142997. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  142998. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  142999. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143000. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143001. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143002. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  143003. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  143004. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143005. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  143006. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143007. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143008. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143009. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  143010. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143011. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143012. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143013. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143014. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  143015. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143016. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143017. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143018. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143019. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143020. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143021. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143022. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143023. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  143024. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143025. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143026. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143027. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143028. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143029. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143030. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143031. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143032. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  143033. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143034. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143035. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143036. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143037. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  143038. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143039. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143040. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143041. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143042. };
  143043. /* tone master attenuation by base quality mode and bitrate tweak */
  143044. static att3 _psy_tone_masteratt_44[12]={
  143045. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143046. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143047. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143048. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143049. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143050. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143051. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143052. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143053. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143054. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143055. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143056. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143057. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143058. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143059. };
  143060. /* lowpass by mode **************/
  143061. static double _psy_lowpass_44[12]={
  143062. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143063. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143064. };
  143065. /* noise normalization **********/
  143066. static int _noise_start_short_44[11]={
  143067. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143068. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143069. };
  143070. static int _noise_start_long_44[11]={
  143071. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143072. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143073. };
  143074. static int _noise_part_short_44[11]={
  143075. 8,8,8,8,8,8,8,8,8,8,8
  143076. };
  143077. static int _noise_part_long_44[11]={
  143078. 32,32,32,32,32,32,32,32,32,32,32
  143079. };
  143080. static double _noise_thresh_44[11]={
  143081. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143082. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143083. };
  143084. static double _noise_thresh_5only[2]={
  143085. .5,.5,
  143086. };
  143087. /*** End of inlined file: psych_44.h ***/
  143088. static double rate_mapping_44_stereo[12]={
  143089. 22500.,32000.,40000.,48000.,56000.,64000.,
  143090. 80000.,96000.,112000.,128000.,160000.,250001.
  143091. };
  143092. static double quality_mapping_44[12]={
  143093. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143094. };
  143095. static int blocksize_short_44[11]={
  143096. 512,256,256,256,256,256,256,256,256,256,256
  143097. };
  143098. static int blocksize_long_44[11]={
  143099. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143100. };
  143101. static double _psy_compand_short_mapping[12]={
  143102. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143103. };
  143104. static double _psy_compand_long_mapping[12]={
  143105. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143106. };
  143107. static double _global_mapping_44[12]={
  143108. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143109. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143110. };
  143111. static int _floor_short_mapping_44[11]={
  143112. 1,0,0,2,2,4,5,5,5,5,5
  143113. };
  143114. static int _floor_long_mapping_44[11]={
  143115. 8,7,7,7,7,7,7,7,7,7,7
  143116. };
  143117. ve_setup_data_template ve_setup_44_stereo={
  143118. 11,
  143119. rate_mapping_44_stereo,
  143120. quality_mapping_44,
  143121. 2,
  143122. 40000,
  143123. 50000,
  143124. blocksize_short_44,
  143125. blocksize_long_44,
  143126. _psy_tone_masteratt_44,
  143127. _psy_tone_0dB,
  143128. _psy_tone_suppress,
  143129. _vp_tonemask_adj_otherblock,
  143130. _vp_tonemask_adj_longblock,
  143131. _vp_tonemask_adj_otherblock,
  143132. _psy_noiseguards_44,
  143133. _psy_noisebias_impulse,
  143134. _psy_noisebias_padding,
  143135. _psy_noisebias_trans,
  143136. _psy_noisebias_long,
  143137. _psy_noise_suppress,
  143138. _psy_compand_44,
  143139. _psy_compand_short_mapping,
  143140. _psy_compand_long_mapping,
  143141. {_noise_start_short_44,_noise_start_long_44},
  143142. {_noise_part_short_44,_noise_part_long_44},
  143143. _noise_thresh_44,
  143144. _psy_ath_floater,
  143145. _psy_ath_abs,
  143146. _psy_lowpass_44,
  143147. _psy_global_44,
  143148. _global_mapping_44,
  143149. _psy_stereo_modes_44,
  143150. _floor_books,
  143151. _floor,
  143152. _floor_short_mapping_44,
  143153. _floor_long_mapping_44,
  143154. _mapres_template_44_stereo
  143155. };
  143156. /*** End of inlined file: setup_44.h ***/
  143157. /*** Start of inlined file: setup_44u.h ***/
  143158. /*** Start of inlined file: residue_44u.h ***/
  143159. /*** Start of inlined file: res_books_uncoupled.h ***/
  143160. static long _vq_quantlist__16u0__p1_0[] = {
  143161. 1,
  143162. 0,
  143163. 2,
  143164. };
  143165. static long _vq_lengthlist__16u0__p1_0[] = {
  143166. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143167. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143168. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143169. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143170. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143171. 12,
  143172. };
  143173. static float _vq_quantthresh__16u0__p1_0[] = {
  143174. -0.5, 0.5,
  143175. };
  143176. static long _vq_quantmap__16u0__p1_0[] = {
  143177. 1, 0, 2,
  143178. };
  143179. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143180. _vq_quantthresh__16u0__p1_0,
  143181. _vq_quantmap__16u0__p1_0,
  143182. 3,
  143183. 3
  143184. };
  143185. static static_codebook _16u0__p1_0 = {
  143186. 4, 81,
  143187. _vq_lengthlist__16u0__p1_0,
  143188. 1, -535822336, 1611661312, 2, 0,
  143189. _vq_quantlist__16u0__p1_0,
  143190. NULL,
  143191. &_vq_auxt__16u0__p1_0,
  143192. NULL,
  143193. 0
  143194. };
  143195. static long _vq_quantlist__16u0__p2_0[] = {
  143196. 1,
  143197. 0,
  143198. 2,
  143199. };
  143200. static long _vq_lengthlist__16u0__p2_0[] = {
  143201. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143202. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143203. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143204. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143205. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143206. 8,
  143207. };
  143208. static float _vq_quantthresh__16u0__p2_0[] = {
  143209. -0.5, 0.5,
  143210. };
  143211. static long _vq_quantmap__16u0__p2_0[] = {
  143212. 1, 0, 2,
  143213. };
  143214. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143215. _vq_quantthresh__16u0__p2_0,
  143216. _vq_quantmap__16u0__p2_0,
  143217. 3,
  143218. 3
  143219. };
  143220. static static_codebook _16u0__p2_0 = {
  143221. 4, 81,
  143222. _vq_lengthlist__16u0__p2_0,
  143223. 1, -535822336, 1611661312, 2, 0,
  143224. _vq_quantlist__16u0__p2_0,
  143225. NULL,
  143226. &_vq_auxt__16u0__p2_0,
  143227. NULL,
  143228. 0
  143229. };
  143230. static long _vq_quantlist__16u0__p3_0[] = {
  143231. 2,
  143232. 1,
  143233. 3,
  143234. 0,
  143235. 4,
  143236. };
  143237. static long _vq_lengthlist__16u0__p3_0[] = {
  143238. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143239. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143240. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143241. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143242. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143243. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143244. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143245. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143246. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143247. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143248. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143249. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143250. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143251. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143252. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143253. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143254. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143255. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143256. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143257. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143258. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143259. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143260. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143261. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143262. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143263. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143264. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143265. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143266. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143267. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143268. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143269. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143270. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143271. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143272. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143273. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143274. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143275. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143276. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143277. 18,
  143278. };
  143279. static float _vq_quantthresh__16u0__p3_0[] = {
  143280. -1.5, -0.5, 0.5, 1.5,
  143281. };
  143282. static long _vq_quantmap__16u0__p3_0[] = {
  143283. 3, 1, 0, 2, 4,
  143284. };
  143285. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143286. _vq_quantthresh__16u0__p3_0,
  143287. _vq_quantmap__16u0__p3_0,
  143288. 5,
  143289. 5
  143290. };
  143291. static static_codebook _16u0__p3_0 = {
  143292. 4, 625,
  143293. _vq_lengthlist__16u0__p3_0,
  143294. 1, -533725184, 1611661312, 3, 0,
  143295. _vq_quantlist__16u0__p3_0,
  143296. NULL,
  143297. &_vq_auxt__16u0__p3_0,
  143298. NULL,
  143299. 0
  143300. };
  143301. static long _vq_quantlist__16u0__p4_0[] = {
  143302. 2,
  143303. 1,
  143304. 3,
  143305. 0,
  143306. 4,
  143307. };
  143308. static long _vq_lengthlist__16u0__p4_0[] = {
  143309. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143310. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143311. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143312. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143313. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143314. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143315. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143316. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143317. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143318. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143319. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143320. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143321. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143322. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143323. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143324. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143325. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143326. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143327. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143328. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143329. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143330. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143331. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143332. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143333. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143334. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143335. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143336. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143337. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143338. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143339. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143340. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143341. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143342. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143343. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143344. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143345. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143346. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143347. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143348. 11,
  143349. };
  143350. static float _vq_quantthresh__16u0__p4_0[] = {
  143351. -1.5, -0.5, 0.5, 1.5,
  143352. };
  143353. static long _vq_quantmap__16u0__p4_0[] = {
  143354. 3, 1, 0, 2, 4,
  143355. };
  143356. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143357. _vq_quantthresh__16u0__p4_0,
  143358. _vq_quantmap__16u0__p4_0,
  143359. 5,
  143360. 5
  143361. };
  143362. static static_codebook _16u0__p4_0 = {
  143363. 4, 625,
  143364. _vq_lengthlist__16u0__p4_0,
  143365. 1, -533725184, 1611661312, 3, 0,
  143366. _vq_quantlist__16u0__p4_0,
  143367. NULL,
  143368. &_vq_auxt__16u0__p4_0,
  143369. NULL,
  143370. 0
  143371. };
  143372. static long _vq_quantlist__16u0__p5_0[] = {
  143373. 4,
  143374. 3,
  143375. 5,
  143376. 2,
  143377. 6,
  143378. 1,
  143379. 7,
  143380. 0,
  143381. 8,
  143382. };
  143383. static long _vq_lengthlist__16u0__p5_0[] = {
  143384. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143385. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143386. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143387. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143388. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143389. 12,
  143390. };
  143391. static float _vq_quantthresh__16u0__p5_0[] = {
  143392. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143393. };
  143394. static long _vq_quantmap__16u0__p5_0[] = {
  143395. 7, 5, 3, 1, 0, 2, 4, 6,
  143396. 8,
  143397. };
  143398. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143399. _vq_quantthresh__16u0__p5_0,
  143400. _vq_quantmap__16u0__p5_0,
  143401. 9,
  143402. 9
  143403. };
  143404. static static_codebook _16u0__p5_0 = {
  143405. 2, 81,
  143406. _vq_lengthlist__16u0__p5_0,
  143407. 1, -531628032, 1611661312, 4, 0,
  143408. _vq_quantlist__16u0__p5_0,
  143409. NULL,
  143410. &_vq_auxt__16u0__p5_0,
  143411. NULL,
  143412. 0
  143413. };
  143414. static long _vq_quantlist__16u0__p6_0[] = {
  143415. 6,
  143416. 5,
  143417. 7,
  143418. 4,
  143419. 8,
  143420. 3,
  143421. 9,
  143422. 2,
  143423. 10,
  143424. 1,
  143425. 11,
  143426. 0,
  143427. 12,
  143428. };
  143429. static long _vq_lengthlist__16u0__p6_0[] = {
  143430. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143431. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143432. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143433. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143434. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143435. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143436. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143437. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143438. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143439. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143440. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143441. };
  143442. static float _vq_quantthresh__16u0__p6_0[] = {
  143443. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143444. 12.5, 17.5, 22.5, 27.5,
  143445. };
  143446. static long _vq_quantmap__16u0__p6_0[] = {
  143447. 11, 9, 7, 5, 3, 1, 0, 2,
  143448. 4, 6, 8, 10, 12,
  143449. };
  143450. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143451. _vq_quantthresh__16u0__p6_0,
  143452. _vq_quantmap__16u0__p6_0,
  143453. 13,
  143454. 13
  143455. };
  143456. static static_codebook _16u0__p6_0 = {
  143457. 2, 169,
  143458. _vq_lengthlist__16u0__p6_0,
  143459. 1, -526516224, 1616117760, 4, 0,
  143460. _vq_quantlist__16u0__p6_0,
  143461. NULL,
  143462. &_vq_auxt__16u0__p6_0,
  143463. NULL,
  143464. 0
  143465. };
  143466. static long _vq_quantlist__16u0__p6_1[] = {
  143467. 2,
  143468. 1,
  143469. 3,
  143470. 0,
  143471. 4,
  143472. };
  143473. static long _vq_lengthlist__16u0__p6_1[] = {
  143474. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143475. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143476. };
  143477. static float _vq_quantthresh__16u0__p6_1[] = {
  143478. -1.5, -0.5, 0.5, 1.5,
  143479. };
  143480. static long _vq_quantmap__16u0__p6_1[] = {
  143481. 3, 1, 0, 2, 4,
  143482. };
  143483. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143484. _vq_quantthresh__16u0__p6_1,
  143485. _vq_quantmap__16u0__p6_1,
  143486. 5,
  143487. 5
  143488. };
  143489. static static_codebook _16u0__p6_1 = {
  143490. 2, 25,
  143491. _vq_lengthlist__16u0__p6_1,
  143492. 1, -533725184, 1611661312, 3, 0,
  143493. _vq_quantlist__16u0__p6_1,
  143494. NULL,
  143495. &_vq_auxt__16u0__p6_1,
  143496. NULL,
  143497. 0
  143498. };
  143499. static long _vq_quantlist__16u0__p7_0[] = {
  143500. 1,
  143501. 0,
  143502. 2,
  143503. };
  143504. static long _vq_lengthlist__16u0__p7_0[] = {
  143505. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143506. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143507. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143508. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143509. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143510. 7,
  143511. };
  143512. static float _vq_quantthresh__16u0__p7_0[] = {
  143513. -157.5, 157.5,
  143514. };
  143515. static long _vq_quantmap__16u0__p7_0[] = {
  143516. 1, 0, 2,
  143517. };
  143518. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143519. _vq_quantthresh__16u0__p7_0,
  143520. _vq_quantmap__16u0__p7_0,
  143521. 3,
  143522. 3
  143523. };
  143524. static static_codebook _16u0__p7_0 = {
  143525. 4, 81,
  143526. _vq_lengthlist__16u0__p7_0,
  143527. 1, -518803456, 1628680192, 2, 0,
  143528. _vq_quantlist__16u0__p7_0,
  143529. NULL,
  143530. &_vq_auxt__16u0__p7_0,
  143531. NULL,
  143532. 0
  143533. };
  143534. static long _vq_quantlist__16u0__p7_1[] = {
  143535. 7,
  143536. 6,
  143537. 8,
  143538. 5,
  143539. 9,
  143540. 4,
  143541. 10,
  143542. 3,
  143543. 11,
  143544. 2,
  143545. 12,
  143546. 1,
  143547. 13,
  143548. 0,
  143549. 14,
  143550. };
  143551. static long _vq_lengthlist__16u0__p7_1[] = {
  143552. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143553. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143554. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143555. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143556. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143557. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143558. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143559. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143560. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143561. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143562. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143563. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143564. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143565. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143566. 10,
  143567. };
  143568. static float _vq_quantthresh__16u0__p7_1[] = {
  143569. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  143570. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  143571. };
  143572. static long _vq_quantmap__16u0__p7_1[] = {
  143573. 13, 11, 9, 7, 5, 3, 1, 0,
  143574. 2, 4, 6, 8, 10, 12, 14,
  143575. };
  143576. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  143577. _vq_quantthresh__16u0__p7_1,
  143578. _vq_quantmap__16u0__p7_1,
  143579. 15,
  143580. 15
  143581. };
  143582. static static_codebook _16u0__p7_1 = {
  143583. 2, 225,
  143584. _vq_lengthlist__16u0__p7_1,
  143585. 1, -520986624, 1620377600, 4, 0,
  143586. _vq_quantlist__16u0__p7_1,
  143587. NULL,
  143588. &_vq_auxt__16u0__p7_1,
  143589. NULL,
  143590. 0
  143591. };
  143592. static long _vq_quantlist__16u0__p7_2[] = {
  143593. 10,
  143594. 9,
  143595. 11,
  143596. 8,
  143597. 12,
  143598. 7,
  143599. 13,
  143600. 6,
  143601. 14,
  143602. 5,
  143603. 15,
  143604. 4,
  143605. 16,
  143606. 3,
  143607. 17,
  143608. 2,
  143609. 18,
  143610. 1,
  143611. 19,
  143612. 0,
  143613. 20,
  143614. };
  143615. static long _vq_lengthlist__16u0__p7_2[] = {
  143616. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  143617. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  143618. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  143619. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  143620. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  143621. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  143622. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  143623. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  143624. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  143625. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  143626. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  143627. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  143628. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  143629. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  143630. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  143631. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  143632. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  143633. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  143634. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  143635. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  143636. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  143637. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  143638. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  143639. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  143640. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  143641. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  143642. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  143643. 10,10,12,11,10,11,11,11,10,
  143644. };
  143645. static float _vq_quantthresh__16u0__p7_2[] = {
  143646. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  143647. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  143648. 6.5, 7.5, 8.5, 9.5,
  143649. };
  143650. static long _vq_quantmap__16u0__p7_2[] = {
  143651. 19, 17, 15, 13, 11, 9, 7, 5,
  143652. 3, 1, 0, 2, 4, 6, 8, 10,
  143653. 12, 14, 16, 18, 20,
  143654. };
  143655. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  143656. _vq_quantthresh__16u0__p7_2,
  143657. _vq_quantmap__16u0__p7_2,
  143658. 21,
  143659. 21
  143660. };
  143661. static static_codebook _16u0__p7_2 = {
  143662. 2, 441,
  143663. _vq_lengthlist__16u0__p7_2,
  143664. 1, -529268736, 1611661312, 5, 0,
  143665. _vq_quantlist__16u0__p7_2,
  143666. NULL,
  143667. &_vq_auxt__16u0__p7_2,
  143668. NULL,
  143669. 0
  143670. };
  143671. static long _huff_lengthlist__16u0__single[] = {
  143672. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  143673. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  143674. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  143675. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  143676. };
  143677. static static_codebook _huff_book__16u0__single = {
  143678. 2, 64,
  143679. _huff_lengthlist__16u0__single,
  143680. 0, 0, 0, 0, 0,
  143681. NULL,
  143682. NULL,
  143683. NULL,
  143684. NULL,
  143685. 0
  143686. };
  143687. static long _huff_lengthlist__16u1__long[] = {
  143688. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  143689. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  143690. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  143691. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  143692. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  143693. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  143694. 16,13,16,18,
  143695. };
  143696. static static_codebook _huff_book__16u1__long = {
  143697. 2, 100,
  143698. _huff_lengthlist__16u1__long,
  143699. 0, 0, 0, 0, 0,
  143700. NULL,
  143701. NULL,
  143702. NULL,
  143703. NULL,
  143704. 0
  143705. };
  143706. static long _vq_quantlist__16u1__p1_0[] = {
  143707. 1,
  143708. 0,
  143709. 2,
  143710. };
  143711. static long _vq_lengthlist__16u1__p1_0[] = {
  143712. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  143713. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  143714. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  143715. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  143716. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  143717. 11,
  143718. };
  143719. static float _vq_quantthresh__16u1__p1_0[] = {
  143720. -0.5, 0.5,
  143721. };
  143722. static long _vq_quantmap__16u1__p1_0[] = {
  143723. 1, 0, 2,
  143724. };
  143725. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  143726. _vq_quantthresh__16u1__p1_0,
  143727. _vq_quantmap__16u1__p1_0,
  143728. 3,
  143729. 3
  143730. };
  143731. static static_codebook _16u1__p1_0 = {
  143732. 4, 81,
  143733. _vq_lengthlist__16u1__p1_0,
  143734. 1, -535822336, 1611661312, 2, 0,
  143735. _vq_quantlist__16u1__p1_0,
  143736. NULL,
  143737. &_vq_auxt__16u1__p1_0,
  143738. NULL,
  143739. 0
  143740. };
  143741. static long _vq_quantlist__16u1__p2_0[] = {
  143742. 1,
  143743. 0,
  143744. 2,
  143745. };
  143746. static long _vq_lengthlist__16u1__p2_0[] = {
  143747. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  143748. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  143749. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  143750. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  143751. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  143752. 8,
  143753. };
  143754. static float _vq_quantthresh__16u1__p2_0[] = {
  143755. -0.5, 0.5,
  143756. };
  143757. static long _vq_quantmap__16u1__p2_0[] = {
  143758. 1, 0, 2,
  143759. };
  143760. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  143761. _vq_quantthresh__16u1__p2_0,
  143762. _vq_quantmap__16u1__p2_0,
  143763. 3,
  143764. 3
  143765. };
  143766. static static_codebook _16u1__p2_0 = {
  143767. 4, 81,
  143768. _vq_lengthlist__16u1__p2_0,
  143769. 1, -535822336, 1611661312, 2, 0,
  143770. _vq_quantlist__16u1__p2_0,
  143771. NULL,
  143772. &_vq_auxt__16u1__p2_0,
  143773. NULL,
  143774. 0
  143775. };
  143776. static long _vq_quantlist__16u1__p3_0[] = {
  143777. 2,
  143778. 1,
  143779. 3,
  143780. 0,
  143781. 4,
  143782. };
  143783. static long _vq_lengthlist__16u1__p3_0[] = {
  143784. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  143785. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  143786. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  143787. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  143788. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  143789. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  143790. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  143791. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  143792. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  143793. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  143794. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  143795. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  143796. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  143797. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  143798. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  143799. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  143800. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  143801. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  143802. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  143803. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  143804. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  143805. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  143806. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  143807. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  143808. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  143809. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  143810. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  143811. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  143812. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  143813. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  143814. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  143815. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  143816. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  143817. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  143818. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  143819. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  143820. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  143821. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  143822. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  143823. 16,
  143824. };
  143825. static float _vq_quantthresh__16u1__p3_0[] = {
  143826. -1.5, -0.5, 0.5, 1.5,
  143827. };
  143828. static long _vq_quantmap__16u1__p3_0[] = {
  143829. 3, 1, 0, 2, 4,
  143830. };
  143831. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  143832. _vq_quantthresh__16u1__p3_0,
  143833. _vq_quantmap__16u1__p3_0,
  143834. 5,
  143835. 5
  143836. };
  143837. static static_codebook _16u1__p3_0 = {
  143838. 4, 625,
  143839. _vq_lengthlist__16u1__p3_0,
  143840. 1, -533725184, 1611661312, 3, 0,
  143841. _vq_quantlist__16u1__p3_0,
  143842. NULL,
  143843. &_vq_auxt__16u1__p3_0,
  143844. NULL,
  143845. 0
  143846. };
  143847. static long _vq_quantlist__16u1__p4_0[] = {
  143848. 2,
  143849. 1,
  143850. 3,
  143851. 0,
  143852. 4,
  143853. };
  143854. static long _vq_lengthlist__16u1__p4_0[] = {
  143855. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  143856. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  143857. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  143858. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  143859. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  143860. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  143861. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  143862. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  143863. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  143864. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  143865. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  143866. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  143867. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  143868. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  143869. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  143870. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  143871. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  143872. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  143873. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  143874. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  143875. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  143876. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  143877. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  143878. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  143879. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  143880. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  143881. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  143882. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  143883. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  143884. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  143885. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  143886. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  143887. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  143888. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  143889. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  143890. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  143891. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  143892. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  143893. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  143894. 11,
  143895. };
  143896. static float _vq_quantthresh__16u1__p4_0[] = {
  143897. -1.5, -0.5, 0.5, 1.5,
  143898. };
  143899. static long _vq_quantmap__16u1__p4_0[] = {
  143900. 3, 1, 0, 2, 4,
  143901. };
  143902. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  143903. _vq_quantthresh__16u1__p4_0,
  143904. _vq_quantmap__16u1__p4_0,
  143905. 5,
  143906. 5
  143907. };
  143908. static static_codebook _16u1__p4_0 = {
  143909. 4, 625,
  143910. _vq_lengthlist__16u1__p4_0,
  143911. 1, -533725184, 1611661312, 3, 0,
  143912. _vq_quantlist__16u1__p4_0,
  143913. NULL,
  143914. &_vq_auxt__16u1__p4_0,
  143915. NULL,
  143916. 0
  143917. };
  143918. static long _vq_quantlist__16u1__p5_0[] = {
  143919. 4,
  143920. 3,
  143921. 5,
  143922. 2,
  143923. 6,
  143924. 1,
  143925. 7,
  143926. 0,
  143927. 8,
  143928. };
  143929. static long _vq_lengthlist__16u1__p5_0[] = {
  143930. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143931. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  143932. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  143933. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  143934. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  143935. 13,
  143936. };
  143937. static float _vq_quantthresh__16u1__p5_0[] = {
  143938. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143939. };
  143940. static long _vq_quantmap__16u1__p5_0[] = {
  143941. 7, 5, 3, 1, 0, 2, 4, 6,
  143942. 8,
  143943. };
  143944. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  143945. _vq_quantthresh__16u1__p5_0,
  143946. _vq_quantmap__16u1__p5_0,
  143947. 9,
  143948. 9
  143949. };
  143950. static static_codebook _16u1__p5_0 = {
  143951. 2, 81,
  143952. _vq_lengthlist__16u1__p5_0,
  143953. 1, -531628032, 1611661312, 4, 0,
  143954. _vq_quantlist__16u1__p5_0,
  143955. NULL,
  143956. &_vq_auxt__16u1__p5_0,
  143957. NULL,
  143958. 0
  143959. };
  143960. static long _vq_quantlist__16u1__p6_0[] = {
  143961. 4,
  143962. 3,
  143963. 5,
  143964. 2,
  143965. 6,
  143966. 1,
  143967. 7,
  143968. 0,
  143969. 8,
  143970. };
  143971. static long _vq_lengthlist__16u1__p6_0[] = {
  143972. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  143973. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  143974. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  143975. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  143976. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  143977. 11,
  143978. };
  143979. static float _vq_quantthresh__16u1__p6_0[] = {
  143980. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143981. };
  143982. static long _vq_quantmap__16u1__p6_0[] = {
  143983. 7, 5, 3, 1, 0, 2, 4, 6,
  143984. 8,
  143985. };
  143986. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  143987. _vq_quantthresh__16u1__p6_0,
  143988. _vq_quantmap__16u1__p6_0,
  143989. 9,
  143990. 9
  143991. };
  143992. static static_codebook _16u1__p6_0 = {
  143993. 2, 81,
  143994. _vq_lengthlist__16u1__p6_0,
  143995. 1, -531628032, 1611661312, 4, 0,
  143996. _vq_quantlist__16u1__p6_0,
  143997. NULL,
  143998. &_vq_auxt__16u1__p6_0,
  143999. NULL,
  144000. 0
  144001. };
  144002. static long _vq_quantlist__16u1__p7_0[] = {
  144003. 1,
  144004. 0,
  144005. 2,
  144006. };
  144007. static long _vq_lengthlist__16u1__p7_0[] = {
  144008. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  144009. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  144010. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  144011. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  144012. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  144013. 13,
  144014. };
  144015. static float _vq_quantthresh__16u1__p7_0[] = {
  144016. -5.5, 5.5,
  144017. };
  144018. static long _vq_quantmap__16u1__p7_0[] = {
  144019. 1, 0, 2,
  144020. };
  144021. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  144022. _vq_quantthresh__16u1__p7_0,
  144023. _vq_quantmap__16u1__p7_0,
  144024. 3,
  144025. 3
  144026. };
  144027. static static_codebook _16u1__p7_0 = {
  144028. 4, 81,
  144029. _vq_lengthlist__16u1__p7_0,
  144030. 1, -529137664, 1618345984, 2, 0,
  144031. _vq_quantlist__16u1__p7_0,
  144032. NULL,
  144033. &_vq_auxt__16u1__p7_0,
  144034. NULL,
  144035. 0
  144036. };
  144037. static long _vq_quantlist__16u1__p7_1[] = {
  144038. 5,
  144039. 4,
  144040. 6,
  144041. 3,
  144042. 7,
  144043. 2,
  144044. 8,
  144045. 1,
  144046. 9,
  144047. 0,
  144048. 10,
  144049. };
  144050. static long _vq_lengthlist__16u1__p7_1[] = {
  144051. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144052. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144053. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144054. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144055. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144056. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144057. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144058. 8, 9, 9,10,10,10,10,10,10,
  144059. };
  144060. static float _vq_quantthresh__16u1__p7_1[] = {
  144061. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144062. 3.5, 4.5,
  144063. };
  144064. static long _vq_quantmap__16u1__p7_1[] = {
  144065. 9, 7, 5, 3, 1, 0, 2, 4,
  144066. 6, 8, 10,
  144067. };
  144068. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144069. _vq_quantthresh__16u1__p7_1,
  144070. _vq_quantmap__16u1__p7_1,
  144071. 11,
  144072. 11
  144073. };
  144074. static static_codebook _16u1__p7_1 = {
  144075. 2, 121,
  144076. _vq_lengthlist__16u1__p7_1,
  144077. 1, -531365888, 1611661312, 4, 0,
  144078. _vq_quantlist__16u1__p7_1,
  144079. NULL,
  144080. &_vq_auxt__16u1__p7_1,
  144081. NULL,
  144082. 0
  144083. };
  144084. static long _vq_quantlist__16u1__p8_0[] = {
  144085. 5,
  144086. 4,
  144087. 6,
  144088. 3,
  144089. 7,
  144090. 2,
  144091. 8,
  144092. 1,
  144093. 9,
  144094. 0,
  144095. 10,
  144096. };
  144097. static long _vq_lengthlist__16u1__p8_0[] = {
  144098. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144099. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144100. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144101. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144102. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144103. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144104. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144105. 13,14,14,15,15,16,16,15,16,
  144106. };
  144107. static float _vq_quantthresh__16u1__p8_0[] = {
  144108. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144109. 38.5, 49.5,
  144110. };
  144111. static long _vq_quantmap__16u1__p8_0[] = {
  144112. 9, 7, 5, 3, 1, 0, 2, 4,
  144113. 6, 8, 10,
  144114. };
  144115. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144116. _vq_quantthresh__16u1__p8_0,
  144117. _vq_quantmap__16u1__p8_0,
  144118. 11,
  144119. 11
  144120. };
  144121. static static_codebook _16u1__p8_0 = {
  144122. 2, 121,
  144123. _vq_lengthlist__16u1__p8_0,
  144124. 1, -524582912, 1618345984, 4, 0,
  144125. _vq_quantlist__16u1__p8_0,
  144126. NULL,
  144127. &_vq_auxt__16u1__p8_0,
  144128. NULL,
  144129. 0
  144130. };
  144131. static long _vq_quantlist__16u1__p8_1[] = {
  144132. 5,
  144133. 4,
  144134. 6,
  144135. 3,
  144136. 7,
  144137. 2,
  144138. 8,
  144139. 1,
  144140. 9,
  144141. 0,
  144142. 10,
  144143. };
  144144. static long _vq_lengthlist__16u1__p8_1[] = {
  144145. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144146. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144147. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144148. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144149. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144150. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144151. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144152. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144153. };
  144154. static float _vq_quantthresh__16u1__p8_1[] = {
  144155. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144156. 3.5, 4.5,
  144157. };
  144158. static long _vq_quantmap__16u1__p8_1[] = {
  144159. 9, 7, 5, 3, 1, 0, 2, 4,
  144160. 6, 8, 10,
  144161. };
  144162. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144163. _vq_quantthresh__16u1__p8_1,
  144164. _vq_quantmap__16u1__p8_1,
  144165. 11,
  144166. 11
  144167. };
  144168. static static_codebook _16u1__p8_1 = {
  144169. 2, 121,
  144170. _vq_lengthlist__16u1__p8_1,
  144171. 1, -531365888, 1611661312, 4, 0,
  144172. _vq_quantlist__16u1__p8_1,
  144173. NULL,
  144174. &_vq_auxt__16u1__p8_1,
  144175. NULL,
  144176. 0
  144177. };
  144178. static long _vq_quantlist__16u1__p9_0[] = {
  144179. 7,
  144180. 6,
  144181. 8,
  144182. 5,
  144183. 9,
  144184. 4,
  144185. 10,
  144186. 3,
  144187. 11,
  144188. 2,
  144189. 12,
  144190. 1,
  144191. 13,
  144192. 0,
  144193. 14,
  144194. };
  144195. static long _vq_lengthlist__16u1__p9_0[] = {
  144196. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144197. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144198. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144199. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144200. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144201. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144202. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144203. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144204. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144205. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144206. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144207. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144208. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144209. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144210. 8,
  144211. };
  144212. static float _vq_quantthresh__16u1__p9_0[] = {
  144213. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144214. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144215. };
  144216. static long _vq_quantmap__16u1__p9_0[] = {
  144217. 13, 11, 9, 7, 5, 3, 1, 0,
  144218. 2, 4, 6, 8, 10, 12, 14,
  144219. };
  144220. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144221. _vq_quantthresh__16u1__p9_0,
  144222. _vq_quantmap__16u1__p9_0,
  144223. 15,
  144224. 15
  144225. };
  144226. static static_codebook _16u1__p9_0 = {
  144227. 2, 225,
  144228. _vq_lengthlist__16u1__p9_0,
  144229. 1, -514071552, 1627381760, 4, 0,
  144230. _vq_quantlist__16u1__p9_0,
  144231. NULL,
  144232. &_vq_auxt__16u1__p9_0,
  144233. NULL,
  144234. 0
  144235. };
  144236. static long _vq_quantlist__16u1__p9_1[] = {
  144237. 7,
  144238. 6,
  144239. 8,
  144240. 5,
  144241. 9,
  144242. 4,
  144243. 10,
  144244. 3,
  144245. 11,
  144246. 2,
  144247. 12,
  144248. 1,
  144249. 13,
  144250. 0,
  144251. 14,
  144252. };
  144253. static long _vq_lengthlist__16u1__p9_1[] = {
  144254. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144255. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144256. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144257. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144258. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144259. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144260. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144261. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144262. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144263. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144264. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144265. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144266. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144267. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144268. 9,
  144269. };
  144270. static float _vq_quantthresh__16u1__p9_1[] = {
  144271. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144272. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144273. };
  144274. static long _vq_quantmap__16u1__p9_1[] = {
  144275. 13, 11, 9, 7, 5, 3, 1, 0,
  144276. 2, 4, 6, 8, 10, 12, 14,
  144277. };
  144278. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144279. _vq_quantthresh__16u1__p9_1,
  144280. _vq_quantmap__16u1__p9_1,
  144281. 15,
  144282. 15
  144283. };
  144284. static static_codebook _16u1__p9_1 = {
  144285. 2, 225,
  144286. _vq_lengthlist__16u1__p9_1,
  144287. 1, -522338304, 1620115456, 4, 0,
  144288. _vq_quantlist__16u1__p9_1,
  144289. NULL,
  144290. &_vq_auxt__16u1__p9_1,
  144291. NULL,
  144292. 0
  144293. };
  144294. static long _vq_quantlist__16u1__p9_2[] = {
  144295. 8,
  144296. 7,
  144297. 9,
  144298. 6,
  144299. 10,
  144300. 5,
  144301. 11,
  144302. 4,
  144303. 12,
  144304. 3,
  144305. 13,
  144306. 2,
  144307. 14,
  144308. 1,
  144309. 15,
  144310. 0,
  144311. 16,
  144312. };
  144313. static long _vq_lengthlist__16u1__p9_2[] = {
  144314. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144315. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144316. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144317. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144318. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144319. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144320. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144321. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144322. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144323. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144324. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144325. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144326. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144327. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144328. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144329. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144330. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144331. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144332. 10,
  144333. };
  144334. static float _vq_quantthresh__16u1__p9_2[] = {
  144335. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144336. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144337. };
  144338. static long _vq_quantmap__16u1__p9_2[] = {
  144339. 15, 13, 11, 9, 7, 5, 3, 1,
  144340. 0, 2, 4, 6, 8, 10, 12, 14,
  144341. 16,
  144342. };
  144343. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144344. _vq_quantthresh__16u1__p9_2,
  144345. _vq_quantmap__16u1__p9_2,
  144346. 17,
  144347. 17
  144348. };
  144349. static static_codebook _16u1__p9_2 = {
  144350. 2, 289,
  144351. _vq_lengthlist__16u1__p9_2,
  144352. 1, -529530880, 1611661312, 5, 0,
  144353. _vq_quantlist__16u1__p9_2,
  144354. NULL,
  144355. &_vq_auxt__16u1__p9_2,
  144356. NULL,
  144357. 0
  144358. };
  144359. static long _huff_lengthlist__16u1__short[] = {
  144360. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144361. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144362. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144363. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144364. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144365. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144366. 16,16,16,16,
  144367. };
  144368. static static_codebook _huff_book__16u1__short = {
  144369. 2, 100,
  144370. _huff_lengthlist__16u1__short,
  144371. 0, 0, 0, 0, 0,
  144372. NULL,
  144373. NULL,
  144374. NULL,
  144375. NULL,
  144376. 0
  144377. };
  144378. static long _huff_lengthlist__16u2__long[] = {
  144379. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144380. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144381. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144382. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144383. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144384. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144385. 13,14,18,18,
  144386. };
  144387. static static_codebook _huff_book__16u2__long = {
  144388. 2, 100,
  144389. _huff_lengthlist__16u2__long,
  144390. 0, 0, 0, 0, 0,
  144391. NULL,
  144392. NULL,
  144393. NULL,
  144394. NULL,
  144395. 0
  144396. };
  144397. static long _huff_lengthlist__16u2__short[] = {
  144398. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144399. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144400. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144401. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144402. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144403. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144404. 16,16,16,16,
  144405. };
  144406. static static_codebook _huff_book__16u2__short = {
  144407. 2, 100,
  144408. _huff_lengthlist__16u2__short,
  144409. 0, 0, 0, 0, 0,
  144410. NULL,
  144411. NULL,
  144412. NULL,
  144413. NULL,
  144414. 0
  144415. };
  144416. static long _vq_quantlist__16u2_p1_0[] = {
  144417. 1,
  144418. 0,
  144419. 2,
  144420. };
  144421. static long _vq_lengthlist__16u2_p1_0[] = {
  144422. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144423. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144424. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144425. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144426. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144427. 10,
  144428. };
  144429. static float _vq_quantthresh__16u2_p1_0[] = {
  144430. -0.5, 0.5,
  144431. };
  144432. static long _vq_quantmap__16u2_p1_0[] = {
  144433. 1, 0, 2,
  144434. };
  144435. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144436. _vq_quantthresh__16u2_p1_0,
  144437. _vq_quantmap__16u2_p1_0,
  144438. 3,
  144439. 3
  144440. };
  144441. static static_codebook _16u2_p1_0 = {
  144442. 4, 81,
  144443. _vq_lengthlist__16u2_p1_0,
  144444. 1, -535822336, 1611661312, 2, 0,
  144445. _vq_quantlist__16u2_p1_0,
  144446. NULL,
  144447. &_vq_auxt__16u2_p1_0,
  144448. NULL,
  144449. 0
  144450. };
  144451. static long _vq_quantlist__16u2_p2_0[] = {
  144452. 2,
  144453. 1,
  144454. 3,
  144455. 0,
  144456. 4,
  144457. };
  144458. static long _vq_lengthlist__16u2_p2_0[] = {
  144459. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144460. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144461. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144462. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144463. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144464. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144465. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144466. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144467. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144468. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144469. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144470. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144471. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144472. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144473. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144474. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144475. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144476. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144477. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144478. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144479. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144480. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144481. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144482. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144483. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144484. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144485. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144486. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144487. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144488. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144489. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144490. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144491. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144492. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144493. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144494. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144495. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144496. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144497. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144498. 13,
  144499. };
  144500. static float _vq_quantthresh__16u2_p2_0[] = {
  144501. -1.5, -0.5, 0.5, 1.5,
  144502. };
  144503. static long _vq_quantmap__16u2_p2_0[] = {
  144504. 3, 1, 0, 2, 4,
  144505. };
  144506. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144507. _vq_quantthresh__16u2_p2_0,
  144508. _vq_quantmap__16u2_p2_0,
  144509. 5,
  144510. 5
  144511. };
  144512. static static_codebook _16u2_p2_0 = {
  144513. 4, 625,
  144514. _vq_lengthlist__16u2_p2_0,
  144515. 1, -533725184, 1611661312, 3, 0,
  144516. _vq_quantlist__16u2_p2_0,
  144517. NULL,
  144518. &_vq_auxt__16u2_p2_0,
  144519. NULL,
  144520. 0
  144521. };
  144522. static long _vq_quantlist__16u2_p3_0[] = {
  144523. 4,
  144524. 3,
  144525. 5,
  144526. 2,
  144527. 6,
  144528. 1,
  144529. 7,
  144530. 0,
  144531. 8,
  144532. };
  144533. static long _vq_lengthlist__16u2_p3_0[] = {
  144534. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144535. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144536. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144537. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144538. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144539. 11,
  144540. };
  144541. static float _vq_quantthresh__16u2_p3_0[] = {
  144542. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144543. };
  144544. static long _vq_quantmap__16u2_p3_0[] = {
  144545. 7, 5, 3, 1, 0, 2, 4, 6,
  144546. 8,
  144547. };
  144548. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144549. _vq_quantthresh__16u2_p3_0,
  144550. _vq_quantmap__16u2_p3_0,
  144551. 9,
  144552. 9
  144553. };
  144554. static static_codebook _16u2_p3_0 = {
  144555. 2, 81,
  144556. _vq_lengthlist__16u2_p3_0,
  144557. 1, -531628032, 1611661312, 4, 0,
  144558. _vq_quantlist__16u2_p3_0,
  144559. NULL,
  144560. &_vq_auxt__16u2_p3_0,
  144561. NULL,
  144562. 0
  144563. };
  144564. static long _vq_quantlist__16u2_p4_0[] = {
  144565. 8,
  144566. 7,
  144567. 9,
  144568. 6,
  144569. 10,
  144570. 5,
  144571. 11,
  144572. 4,
  144573. 12,
  144574. 3,
  144575. 13,
  144576. 2,
  144577. 14,
  144578. 1,
  144579. 15,
  144580. 0,
  144581. 16,
  144582. };
  144583. static long _vq_lengthlist__16u2_p4_0[] = {
  144584. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  144585. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  144586. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  144587. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  144588. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  144589. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  144590. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  144591. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  144592. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  144593. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  144594. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  144595. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  144596. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  144597. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  144598. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  144599. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  144600. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  144601. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  144602. 14,
  144603. };
  144604. static float _vq_quantthresh__16u2_p4_0[] = {
  144605. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144606. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144607. };
  144608. static long _vq_quantmap__16u2_p4_0[] = {
  144609. 15, 13, 11, 9, 7, 5, 3, 1,
  144610. 0, 2, 4, 6, 8, 10, 12, 14,
  144611. 16,
  144612. };
  144613. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  144614. _vq_quantthresh__16u2_p4_0,
  144615. _vq_quantmap__16u2_p4_0,
  144616. 17,
  144617. 17
  144618. };
  144619. static static_codebook _16u2_p4_0 = {
  144620. 2, 289,
  144621. _vq_lengthlist__16u2_p4_0,
  144622. 1, -529530880, 1611661312, 5, 0,
  144623. _vq_quantlist__16u2_p4_0,
  144624. NULL,
  144625. &_vq_auxt__16u2_p4_0,
  144626. NULL,
  144627. 0
  144628. };
  144629. static long _vq_quantlist__16u2_p5_0[] = {
  144630. 1,
  144631. 0,
  144632. 2,
  144633. };
  144634. static long _vq_lengthlist__16u2_p5_0[] = {
  144635. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  144636. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  144637. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  144638. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  144639. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  144640. 10,
  144641. };
  144642. static float _vq_quantthresh__16u2_p5_0[] = {
  144643. -5.5, 5.5,
  144644. };
  144645. static long _vq_quantmap__16u2_p5_0[] = {
  144646. 1, 0, 2,
  144647. };
  144648. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  144649. _vq_quantthresh__16u2_p5_0,
  144650. _vq_quantmap__16u2_p5_0,
  144651. 3,
  144652. 3
  144653. };
  144654. static static_codebook _16u2_p5_0 = {
  144655. 4, 81,
  144656. _vq_lengthlist__16u2_p5_0,
  144657. 1, -529137664, 1618345984, 2, 0,
  144658. _vq_quantlist__16u2_p5_0,
  144659. NULL,
  144660. &_vq_auxt__16u2_p5_0,
  144661. NULL,
  144662. 0
  144663. };
  144664. static long _vq_quantlist__16u2_p5_1[] = {
  144665. 5,
  144666. 4,
  144667. 6,
  144668. 3,
  144669. 7,
  144670. 2,
  144671. 8,
  144672. 1,
  144673. 9,
  144674. 0,
  144675. 10,
  144676. };
  144677. static long _vq_lengthlist__16u2_p5_1[] = {
  144678. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  144679. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  144680. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  144681. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144682. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144683. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144684. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144685. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  144686. };
  144687. static float _vq_quantthresh__16u2_p5_1[] = {
  144688. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144689. 3.5, 4.5,
  144690. };
  144691. static long _vq_quantmap__16u2_p5_1[] = {
  144692. 9, 7, 5, 3, 1, 0, 2, 4,
  144693. 6, 8, 10,
  144694. };
  144695. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  144696. _vq_quantthresh__16u2_p5_1,
  144697. _vq_quantmap__16u2_p5_1,
  144698. 11,
  144699. 11
  144700. };
  144701. static static_codebook _16u2_p5_1 = {
  144702. 2, 121,
  144703. _vq_lengthlist__16u2_p5_1,
  144704. 1, -531365888, 1611661312, 4, 0,
  144705. _vq_quantlist__16u2_p5_1,
  144706. NULL,
  144707. &_vq_auxt__16u2_p5_1,
  144708. NULL,
  144709. 0
  144710. };
  144711. static long _vq_quantlist__16u2_p6_0[] = {
  144712. 6,
  144713. 5,
  144714. 7,
  144715. 4,
  144716. 8,
  144717. 3,
  144718. 9,
  144719. 2,
  144720. 10,
  144721. 1,
  144722. 11,
  144723. 0,
  144724. 12,
  144725. };
  144726. static long _vq_lengthlist__16u2_p6_0[] = {
  144727. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  144728. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  144729. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  144730. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  144731. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  144732. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  144733. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  144734. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  144735. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  144736. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  144737. 12,13,13,14,14,14,14,15,15,
  144738. };
  144739. static float _vq_quantthresh__16u2_p6_0[] = {
  144740. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  144741. 12.5, 17.5, 22.5, 27.5,
  144742. };
  144743. static long _vq_quantmap__16u2_p6_0[] = {
  144744. 11, 9, 7, 5, 3, 1, 0, 2,
  144745. 4, 6, 8, 10, 12,
  144746. };
  144747. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  144748. _vq_quantthresh__16u2_p6_0,
  144749. _vq_quantmap__16u2_p6_0,
  144750. 13,
  144751. 13
  144752. };
  144753. static static_codebook _16u2_p6_0 = {
  144754. 2, 169,
  144755. _vq_lengthlist__16u2_p6_0,
  144756. 1, -526516224, 1616117760, 4, 0,
  144757. _vq_quantlist__16u2_p6_0,
  144758. NULL,
  144759. &_vq_auxt__16u2_p6_0,
  144760. NULL,
  144761. 0
  144762. };
  144763. static long _vq_quantlist__16u2_p6_1[] = {
  144764. 2,
  144765. 1,
  144766. 3,
  144767. 0,
  144768. 4,
  144769. };
  144770. static long _vq_lengthlist__16u2_p6_1[] = {
  144771. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  144772. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  144773. };
  144774. static float _vq_quantthresh__16u2_p6_1[] = {
  144775. -1.5, -0.5, 0.5, 1.5,
  144776. };
  144777. static long _vq_quantmap__16u2_p6_1[] = {
  144778. 3, 1, 0, 2, 4,
  144779. };
  144780. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  144781. _vq_quantthresh__16u2_p6_1,
  144782. _vq_quantmap__16u2_p6_1,
  144783. 5,
  144784. 5
  144785. };
  144786. static static_codebook _16u2_p6_1 = {
  144787. 2, 25,
  144788. _vq_lengthlist__16u2_p6_1,
  144789. 1, -533725184, 1611661312, 3, 0,
  144790. _vq_quantlist__16u2_p6_1,
  144791. NULL,
  144792. &_vq_auxt__16u2_p6_1,
  144793. NULL,
  144794. 0
  144795. };
  144796. static long _vq_quantlist__16u2_p7_0[] = {
  144797. 6,
  144798. 5,
  144799. 7,
  144800. 4,
  144801. 8,
  144802. 3,
  144803. 9,
  144804. 2,
  144805. 10,
  144806. 1,
  144807. 11,
  144808. 0,
  144809. 12,
  144810. };
  144811. static long _vq_lengthlist__16u2_p7_0[] = {
  144812. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  144813. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  144814. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  144815. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  144816. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  144817. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  144818. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  144819. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  144820. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  144821. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  144822. 12,13,13,13,14,14,14,15,14,
  144823. };
  144824. static float _vq_quantthresh__16u2_p7_0[] = {
  144825. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  144826. 27.5, 38.5, 49.5, 60.5,
  144827. };
  144828. static long _vq_quantmap__16u2_p7_0[] = {
  144829. 11, 9, 7, 5, 3, 1, 0, 2,
  144830. 4, 6, 8, 10, 12,
  144831. };
  144832. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  144833. _vq_quantthresh__16u2_p7_0,
  144834. _vq_quantmap__16u2_p7_0,
  144835. 13,
  144836. 13
  144837. };
  144838. static static_codebook _16u2_p7_0 = {
  144839. 2, 169,
  144840. _vq_lengthlist__16u2_p7_0,
  144841. 1, -523206656, 1618345984, 4, 0,
  144842. _vq_quantlist__16u2_p7_0,
  144843. NULL,
  144844. &_vq_auxt__16u2_p7_0,
  144845. NULL,
  144846. 0
  144847. };
  144848. static long _vq_quantlist__16u2_p7_1[] = {
  144849. 5,
  144850. 4,
  144851. 6,
  144852. 3,
  144853. 7,
  144854. 2,
  144855. 8,
  144856. 1,
  144857. 9,
  144858. 0,
  144859. 10,
  144860. };
  144861. static long _vq_lengthlist__16u2_p7_1[] = {
  144862. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  144863. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  144864. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  144865. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  144866. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  144867. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  144868. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  144869. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144870. };
  144871. static float _vq_quantthresh__16u2_p7_1[] = {
  144872. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144873. 3.5, 4.5,
  144874. };
  144875. static long _vq_quantmap__16u2_p7_1[] = {
  144876. 9, 7, 5, 3, 1, 0, 2, 4,
  144877. 6, 8, 10,
  144878. };
  144879. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  144880. _vq_quantthresh__16u2_p7_1,
  144881. _vq_quantmap__16u2_p7_1,
  144882. 11,
  144883. 11
  144884. };
  144885. static static_codebook _16u2_p7_1 = {
  144886. 2, 121,
  144887. _vq_lengthlist__16u2_p7_1,
  144888. 1, -531365888, 1611661312, 4, 0,
  144889. _vq_quantlist__16u2_p7_1,
  144890. NULL,
  144891. &_vq_auxt__16u2_p7_1,
  144892. NULL,
  144893. 0
  144894. };
  144895. static long _vq_quantlist__16u2_p8_0[] = {
  144896. 7,
  144897. 6,
  144898. 8,
  144899. 5,
  144900. 9,
  144901. 4,
  144902. 10,
  144903. 3,
  144904. 11,
  144905. 2,
  144906. 12,
  144907. 1,
  144908. 13,
  144909. 0,
  144910. 14,
  144911. };
  144912. static long _vq_lengthlist__16u2_p8_0[] = {
  144913. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  144914. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  144915. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  144916. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  144917. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  144918. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  144919. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  144920. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  144921. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  144922. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  144923. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  144924. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  144925. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  144926. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  144927. 14,
  144928. };
  144929. static float _vq_quantthresh__16u2_p8_0[] = {
  144930. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144931. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144932. };
  144933. static long _vq_quantmap__16u2_p8_0[] = {
  144934. 13, 11, 9, 7, 5, 3, 1, 0,
  144935. 2, 4, 6, 8, 10, 12, 14,
  144936. };
  144937. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  144938. _vq_quantthresh__16u2_p8_0,
  144939. _vq_quantmap__16u2_p8_0,
  144940. 15,
  144941. 15
  144942. };
  144943. static static_codebook _16u2_p8_0 = {
  144944. 2, 225,
  144945. _vq_lengthlist__16u2_p8_0,
  144946. 1, -520986624, 1620377600, 4, 0,
  144947. _vq_quantlist__16u2_p8_0,
  144948. NULL,
  144949. &_vq_auxt__16u2_p8_0,
  144950. NULL,
  144951. 0
  144952. };
  144953. static long _vq_quantlist__16u2_p8_1[] = {
  144954. 10,
  144955. 9,
  144956. 11,
  144957. 8,
  144958. 12,
  144959. 7,
  144960. 13,
  144961. 6,
  144962. 14,
  144963. 5,
  144964. 15,
  144965. 4,
  144966. 16,
  144967. 3,
  144968. 17,
  144969. 2,
  144970. 18,
  144971. 1,
  144972. 19,
  144973. 0,
  144974. 20,
  144975. };
  144976. static long _vq_lengthlist__16u2_p8_1[] = {
  144977. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  144978. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  144979. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  144980. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  144981. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  144982. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  144983. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  144984. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  144985. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  144986. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  144987. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  144988. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  144989. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  144990. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  144991. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  144992. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  144993. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  144994. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  144995. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  144996. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  144997. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  144998. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  144999. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  145000. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  145001. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  145002. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  145003. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  145004. 11,11,10,11,11,11,10,11,11,
  145005. };
  145006. static float _vq_quantthresh__16u2_p8_1[] = {
  145007. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145008. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145009. 6.5, 7.5, 8.5, 9.5,
  145010. };
  145011. static long _vq_quantmap__16u2_p8_1[] = {
  145012. 19, 17, 15, 13, 11, 9, 7, 5,
  145013. 3, 1, 0, 2, 4, 6, 8, 10,
  145014. 12, 14, 16, 18, 20,
  145015. };
  145016. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  145017. _vq_quantthresh__16u2_p8_1,
  145018. _vq_quantmap__16u2_p8_1,
  145019. 21,
  145020. 21
  145021. };
  145022. static static_codebook _16u2_p8_1 = {
  145023. 2, 441,
  145024. _vq_lengthlist__16u2_p8_1,
  145025. 1, -529268736, 1611661312, 5, 0,
  145026. _vq_quantlist__16u2_p8_1,
  145027. NULL,
  145028. &_vq_auxt__16u2_p8_1,
  145029. NULL,
  145030. 0
  145031. };
  145032. static long _vq_quantlist__16u2_p9_0[] = {
  145033. 5586,
  145034. 4655,
  145035. 6517,
  145036. 3724,
  145037. 7448,
  145038. 2793,
  145039. 8379,
  145040. 1862,
  145041. 9310,
  145042. 931,
  145043. 10241,
  145044. 0,
  145045. 11172,
  145046. 5521,
  145047. 5651,
  145048. };
  145049. static long _vq_lengthlist__16u2_p9_0[] = {
  145050. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145051. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145052. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145053. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145054. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145055. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145056. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145057. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145058. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145059. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145060. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145061. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145062. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145063. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145064. 5,
  145065. };
  145066. static float _vq_quantthresh__16u2_p9_0[] = {
  145067. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145068. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145069. };
  145070. static long _vq_quantmap__16u2_p9_0[] = {
  145071. 11, 9, 7, 5, 3, 1, 13, 0,
  145072. 14, 2, 4, 6, 8, 10, 12,
  145073. };
  145074. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145075. _vq_quantthresh__16u2_p9_0,
  145076. _vq_quantmap__16u2_p9_0,
  145077. 15,
  145078. 15
  145079. };
  145080. static static_codebook _16u2_p9_0 = {
  145081. 2, 225,
  145082. _vq_lengthlist__16u2_p9_0,
  145083. 1, -510275072, 1611661312, 14, 0,
  145084. _vq_quantlist__16u2_p9_0,
  145085. NULL,
  145086. &_vq_auxt__16u2_p9_0,
  145087. NULL,
  145088. 0
  145089. };
  145090. static long _vq_quantlist__16u2_p9_1[] = {
  145091. 392,
  145092. 343,
  145093. 441,
  145094. 294,
  145095. 490,
  145096. 245,
  145097. 539,
  145098. 196,
  145099. 588,
  145100. 147,
  145101. 637,
  145102. 98,
  145103. 686,
  145104. 49,
  145105. 735,
  145106. 0,
  145107. 784,
  145108. 388,
  145109. 396,
  145110. };
  145111. static long _vq_lengthlist__16u2_p9_1[] = {
  145112. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145113. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145114. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145115. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145116. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145117. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145118. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145119. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145120. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145121. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145122. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145123. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145124. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145125. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145126. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145127. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145128. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145129. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145130. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145131. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145132. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145133. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145134. 11,11,11,11,11,11,11, 5, 4,
  145135. };
  145136. static float _vq_quantthresh__16u2_p9_1[] = {
  145137. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145138. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145139. 318.5, 367.5,
  145140. };
  145141. static long _vq_quantmap__16u2_p9_1[] = {
  145142. 15, 13, 11, 9, 7, 5, 3, 1,
  145143. 17, 0, 18, 2, 4, 6, 8, 10,
  145144. 12, 14, 16,
  145145. };
  145146. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145147. _vq_quantthresh__16u2_p9_1,
  145148. _vq_quantmap__16u2_p9_1,
  145149. 19,
  145150. 19
  145151. };
  145152. static static_codebook _16u2_p9_1 = {
  145153. 2, 361,
  145154. _vq_lengthlist__16u2_p9_1,
  145155. 1, -518488064, 1611661312, 10, 0,
  145156. _vq_quantlist__16u2_p9_1,
  145157. NULL,
  145158. &_vq_auxt__16u2_p9_1,
  145159. NULL,
  145160. 0
  145161. };
  145162. static long _vq_quantlist__16u2_p9_2[] = {
  145163. 24,
  145164. 23,
  145165. 25,
  145166. 22,
  145167. 26,
  145168. 21,
  145169. 27,
  145170. 20,
  145171. 28,
  145172. 19,
  145173. 29,
  145174. 18,
  145175. 30,
  145176. 17,
  145177. 31,
  145178. 16,
  145179. 32,
  145180. 15,
  145181. 33,
  145182. 14,
  145183. 34,
  145184. 13,
  145185. 35,
  145186. 12,
  145187. 36,
  145188. 11,
  145189. 37,
  145190. 10,
  145191. 38,
  145192. 9,
  145193. 39,
  145194. 8,
  145195. 40,
  145196. 7,
  145197. 41,
  145198. 6,
  145199. 42,
  145200. 5,
  145201. 43,
  145202. 4,
  145203. 44,
  145204. 3,
  145205. 45,
  145206. 2,
  145207. 46,
  145208. 1,
  145209. 47,
  145210. 0,
  145211. 48,
  145212. };
  145213. static long _vq_lengthlist__16u2_p9_2[] = {
  145214. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145215. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145216. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145217. 11,
  145218. };
  145219. static float _vq_quantthresh__16u2_p9_2[] = {
  145220. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145221. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145222. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145223. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145224. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145225. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145226. };
  145227. static long _vq_quantmap__16u2_p9_2[] = {
  145228. 47, 45, 43, 41, 39, 37, 35, 33,
  145229. 31, 29, 27, 25, 23, 21, 19, 17,
  145230. 15, 13, 11, 9, 7, 5, 3, 1,
  145231. 0, 2, 4, 6, 8, 10, 12, 14,
  145232. 16, 18, 20, 22, 24, 26, 28, 30,
  145233. 32, 34, 36, 38, 40, 42, 44, 46,
  145234. 48,
  145235. };
  145236. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145237. _vq_quantthresh__16u2_p9_2,
  145238. _vq_quantmap__16u2_p9_2,
  145239. 49,
  145240. 49
  145241. };
  145242. static static_codebook _16u2_p9_2 = {
  145243. 1, 49,
  145244. _vq_lengthlist__16u2_p9_2,
  145245. 1, -526909440, 1611661312, 6, 0,
  145246. _vq_quantlist__16u2_p9_2,
  145247. NULL,
  145248. &_vq_auxt__16u2_p9_2,
  145249. NULL,
  145250. 0
  145251. };
  145252. static long _vq_quantlist__8u0__p1_0[] = {
  145253. 1,
  145254. 0,
  145255. 2,
  145256. };
  145257. static long _vq_lengthlist__8u0__p1_0[] = {
  145258. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145259. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145260. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145261. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145262. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145263. 11,
  145264. };
  145265. static float _vq_quantthresh__8u0__p1_0[] = {
  145266. -0.5, 0.5,
  145267. };
  145268. static long _vq_quantmap__8u0__p1_0[] = {
  145269. 1, 0, 2,
  145270. };
  145271. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145272. _vq_quantthresh__8u0__p1_0,
  145273. _vq_quantmap__8u0__p1_0,
  145274. 3,
  145275. 3
  145276. };
  145277. static static_codebook _8u0__p1_0 = {
  145278. 4, 81,
  145279. _vq_lengthlist__8u0__p1_0,
  145280. 1, -535822336, 1611661312, 2, 0,
  145281. _vq_quantlist__8u0__p1_0,
  145282. NULL,
  145283. &_vq_auxt__8u0__p1_0,
  145284. NULL,
  145285. 0
  145286. };
  145287. static long _vq_quantlist__8u0__p2_0[] = {
  145288. 1,
  145289. 0,
  145290. 2,
  145291. };
  145292. static long _vq_lengthlist__8u0__p2_0[] = {
  145293. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145294. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145295. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145296. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145297. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145298. 8,
  145299. };
  145300. static float _vq_quantthresh__8u0__p2_0[] = {
  145301. -0.5, 0.5,
  145302. };
  145303. static long _vq_quantmap__8u0__p2_0[] = {
  145304. 1, 0, 2,
  145305. };
  145306. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145307. _vq_quantthresh__8u0__p2_0,
  145308. _vq_quantmap__8u0__p2_0,
  145309. 3,
  145310. 3
  145311. };
  145312. static static_codebook _8u0__p2_0 = {
  145313. 4, 81,
  145314. _vq_lengthlist__8u0__p2_0,
  145315. 1, -535822336, 1611661312, 2, 0,
  145316. _vq_quantlist__8u0__p2_0,
  145317. NULL,
  145318. &_vq_auxt__8u0__p2_0,
  145319. NULL,
  145320. 0
  145321. };
  145322. static long _vq_quantlist__8u0__p3_0[] = {
  145323. 2,
  145324. 1,
  145325. 3,
  145326. 0,
  145327. 4,
  145328. };
  145329. static long _vq_lengthlist__8u0__p3_0[] = {
  145330. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145331. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145332. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145333. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145334. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145335. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145336. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145337. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145338. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145339. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145340. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145341. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145342. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145343. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145344. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145345. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145346. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145347. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145348. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145349. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145350. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145351. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145352. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145353. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145354. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145355. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145356. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145357. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145358. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145359. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145360. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145361. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145362. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145363. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145364. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145365. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145366. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145367. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145368. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145369. 16,
  145370. };
  145371. static float _vq_quantthresh__8u0__p3_0[] = {
  145372. -1.5, -0.5, 0.5, 1.5,
  145373. };
  145374. static long _vq_quantmap__8u0__p3_0[] = {
  145375. 3, 1, 0, 2, 4,
  145376. };
  145377. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145378. _vq_quantthresh__8u0__p3_0,
  145379. _vq_quantmap__8u0__p3_0,
  145380. 5,
  145381. 5
  145382. };
  145383. static static_codebook _8u0__p3_0 = {
  145384. 4, 625,
  145385. _vq_lengthlist__8u0__p3_0,
  145386. 1, -533725184, 1611661312, 3, 0,
  145387. _vq_quantlist__8u0__p3_0,
  145388. NULL,
  145389. &_vq_auxt__8u0__p3_0,
  145390. NULL,
  145391. 0
  145392. };
  145393. static long _vq_quantlist__8u0__p4_0[] = {
  145394. 2,
  145395. 1,
  145396. 3,
  145397. 0,
  145398. 4,
  145399. };
  145400. static long _vq_lengthlist__8u0__p4_0[] = {
  145401. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145402. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145403. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145404. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145405. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145406. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145407. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145408. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145409. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145410. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145411. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145412. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145413. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145414. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145415. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145416. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145417. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145418. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145419. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145420. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145421. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145422. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145423. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145424. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145425. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145426. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145427. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145428. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145429. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145430. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145431. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145432. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145433. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145434. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145435. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145436. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145437. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145438. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145439. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145440. 12,
  145441. };
  145442. static float _vq_quantthresh__8u0__p4_0[] = {
  145443. -1.5, -0.5, 0.5, 1.5,
  145444. };
  145445. static long _vq_quantmap__8u0__p4_0[] = {
  145446. 3, 1, 0, 2, 4,
  145447. };
  145448. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145449. _vq_quantthresh__8u0__p4_0,
  145450. _vq_quantmap__8u0__p4_0,
  145451. 5,
  145452. 5
  145453. };
  145454. static static_codebook _8u0__p4_0 = {
  145455. 4, 625,
  145456. _vq_lengthlist__8u0__p4_0,
  145457. 1, -533725184, 1611661312, 3, 0,
  145458. _vq_quantlist__8u0__p4_0,
  145459. NULL,
  145460. &_vq_auxt__8u0__p4_0,
  145461. NULL,
  145462. 0
  145463. };
  145464. static long _vq_quantlist__8u0__p5_0[] = {
  145465. 4,
  145466. 3,
  145467. 5,
  145468. 2,
  145469. 6,
  145470. 1,
  145471. 7,
  145472. 0,
  145473. 8,
  145474. };
  145475. static long _vq_lengthlist__8u0__p5_0[] = {
  145476. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145477. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145478. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145479. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145480. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145481. 12,
  145482. };
  145483. static float _vq_quantthresh__8u0__p5_0[] = {
  145484. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145485. };
  145486. static long _vq_quantmap__8u0__p5_0[] = {
  145487. 7, 5, 3, 1, 0, 2, 4, 6,
  145488. 8,
  145489. };
  145490. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145491. _vq_quantthresh__8u0__p5_0,
  145492. _vq_quantmap__8u0__p5_0,
  145493. 9,
  145494. 9
  145495. };
  145496. static static_codebook _8u0__p5_0 = {
  145497. 2, 81,
  145498. _vq_lengthlist__8u0__p5_0,
  145499. 1, -531628032, 1611661312, 4, 0,
  145500. _vq_quantlist__8u0__p5_0,
  145501. NULL,
  145502. &_vq_auxt__8u0__p5_0,
  145503. NULL,
  145504. 0
  145505. };
  145506. static long _vq_quantlist__8u0__p6_0[] = {
  145507. 6,
  145508. 5,
  145509. 7,
  145510. 4,
  145511. 8,
  145512. 3,
  145513. 9,
  145514. 2,
  145515. 10,
  145516. 1,
  145517. 11,
  145518. 0,
  145519. 12,
  145520. };
  145521. static long _vq_lengthlist__8u0__p6_0[] = {
  145522. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145523. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145524. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145525. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145526. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145527. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145528. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145529. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145530. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145531. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145532. 16, 0,15, 0,17, 0, 0, 0, 0,
  145533. };
  145534. static float _vq_quantthresh__8u0__p6_0[] = {
  145535. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145536. 12.5, 17.5, 22.5, 27.5,
  145537. };
  145538. static long _vq_quantmap__8u0__p6_0[] = {
  145539. 11, 9, 7, 5, 3, 1, 0, 2,
  145540. 4, 6, 8, 10, 12,
  145541. };
  145542. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145543. _vq_quantthresh__8u0__p6_0,
  145544. _vq_quantmap__8u0__p6_0,
  145545. 13,
  145546. 13
  145547. };
  145548. static static_codebook _8u0__p6_0 = {
  145549. 2, 169,
  145550. _vq_lengthlist__8u0__p6_0,
  145551. 1, -526516224, 1616117760, 4, 0,
  145552. _vq_quantlist__8u0__p6_0,
  145553. NULL,
  145554. &_vq_auxt__8u0__p6_0,
  145555. NULL,
  145556. 0
  145557. };
  145558. static long _vq_quantlist__8u0__p6_1[] = {
  145559. 2,
  145560. 1,
  145561. 3,
  145562. 0,
  145563. 4,
  145564. };
  145565. static long _vq_lengthlist__8u0__p6_1[] = {
  145566. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  145567. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  145568. };
  145569. static float _vq_quantthresh__8u0__p6_1[] = {
  145570. -1.5, -0.5, 0.5, 1.5,
  145571. };
  145572. static long _vq_quantmap__8u0__p6_1[] = {
  145573. 3, 1, 0, 2, 4,
  145574. };
  145575. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  145576. _vq_quantthresh__8u0__p6_1,
  145577. _vq_quantmap__8u0__p6_1,
  145578. 5,
  145579. 5
  145580. };
  145581. static static_codebook _8u0__p6_1 = {
  145582. 2, 25,
  145583. _vq_lengthlist__8u0__p6_1,
  145584. 1, -533725184, 1611661312, 3, 0,
  145585. _vq_quantlist__8u0__p6_1,
  145586. NULL,
  145587. &_vq_auxt__8u0__p6_1,
  145588. NULL,
  145589. 0
  145590. };
  145591. static long _vq_quantlist__8u0__p7_0[] = {
  145592. 1,
  145593. 0,
  145594. 2,
  145595. };
  145596. static long _vq_lengthlist__8u0__p7_0[] = {
  145597. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145598. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145599. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145600. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145601. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  145602. 7,
  145603. };
  145604. static float _vq_quantthresh__8u0__p7_0[] = {
  145605. -157.5, 157.5,
  145606. };
  145607. static long _vq_quantmap__8u0__p7_0[] = {
  145608. 1, 0, 2,
  145609. };
  145610. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  145611. _vq_quantthresh__8u0__p7_0,
  145612. _vq_quantmap__8u0__p7_0,
  145613. 3,
  145614. 3
  145615. };
  145616. static static_codebook _8u0__p7_0 = {
  145617. 4, 81,
  145618. _vq_lengthlist__8u0__p7_0,
  145619. 1, -518803456, 1628680192, 2, 0,
  145620. _vq_quantlist__8u0__p7_0,
  145621. NULL,
  145622. &_vq_auxt__8u0__p7_0,
  145623. NULL,
  145624. 0
  145625. };
  145626. static long _vq_quantlist__8u0__p7_1[] = {
  145627. 7,
  145628. 6,
  145629. 8,
  145630. 5,
  145631. 9,
  145632. 4,
  145633. 10,
  145634. 3,
  145635. 11,
  145636. 2,
  145637. 12,
  145638. 1,
  145639. 13,
  145640. 0,
  145641. 14,
  145642. };
  145643. static long _vq_lengthlist__8u0__p7_1[] = {
  145644. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  145645. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  145646. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  145647. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  145648. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  145649. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  145650. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145651. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145652. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145653. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145654. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145655. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145656. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  145657. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145658. 10,
  145659. };
  145660. static float _vq_quantthresh__8u0__p7_1[] = {
  145661. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145662. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145663. };
  145664. static long _vq_quantmap__8u0__p7_1[] = {
  145665. 13, 11, 9, 7, 5, 3, 1, 0,
  145666. 2, 4, 6, 8, 10, 12, 14,
  145667. };
  145668. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  145669. _vq_quantthresh__8u0__p7_1,
  145670. _vq_quantmap__8u0__p7_1,
  145671. 15,
  145672. 15
  145673. };
  145674. static static_codebook _8u0__p7_1 = {
  145675. 2, 225,
  145676. _vq_lengthlist__8u0__p7_1,
  145677. 1, -520986624, 1620377600, 4, 0,
  145678. _vq_quantlist__8u0__p7_1,
  145679. NULL,
  145680. &_vq_auxt__8u0__p7_1,
  145681. NULL,
  145682. 0
  145683. };
  145684. static long _vq_quantlist__8u0__p7_2[] = {
  145685. 10,
  145686. 9,
  145687. 11,
  145688. 8,
  145689. 12,
  145690. 7,
  145691. 13,
  145692. 6,
  145693. 14,
  145694. 5,
  145695. 15,
  145696. 4,
  145697. 16,
  145698. 3,
  145699. 17,
  145700. 2,
  145701. 18,
  145702. 1,
  145703. 19,
  145704. 0,
  145705. 20,
  145706. };
  145707. static long _vq_lengthlist__8u0__p7_2[] = {
  145708. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  145709. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  145710. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  145711. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  145712. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  145713. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  145714. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  145715. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  145716. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  145717. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  145718. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  145719. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  145720. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  145721. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  145722. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  145723. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  145724. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  145725. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  145726. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  145727. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  145728. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  145729. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  145730. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  145731. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  145732. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  145733. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  145734. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  145735. 11,12,11,11,11,10,10,11,11,
  145736. };
  145737. static float _vq_quantthresh__8u0__p7_2[] = {
  145738. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145739. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145740. 6.5, 7.5, 8.5, 9.5,
  145741. };
  145742. static long _vq_quantmap__8u0__p7_2[] = {
  145743. 19, 17, 15, 13, 11, 9, 7, 5,
  145744. 3, 1, 0, 2, 4, 6, 8, 10,
  145745. 12, 14, 16, 18, 20,
  145746. };
  145747. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  145748. _vq_quantthresh__8u0__p7_2,
  145749. _vq_quantmap__8u0__p7_2,
  145750. 21,
  145751. 21
  145752. };
  145753. static static_codebook _8u0__p7_2 = {
  145754. 2, 441,
  145755. _vq_lengthlist__8u0__p7_2,
  145756. 1, -529268736, 1611661312, 5, 0,
  145757. _vq_quantlist__8u0__p7_2,
  145758. NULL,
  145759. &_vq_auxt__8u0__p7_2,
  145760. NULL,
  145761. 0
  145762. };
  145763. static long _huff_lengthlist__8u0__single[] = {
  145764. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  145765. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  145766. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  145767. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  145768. };
  145769. static static_codebook _huff_book__8u0__single = {
  145770. 2, 64,
  145771. _huff_lengthlist__8u0__single,
  145772. 0, 0, 0, 0, 0,
  145773. NULL,
  145774. NULL,
  145775. NULL,
  145776. NULL,
  145777. 0
  145778. };
  145779. static long _vq_quantlist__8u1__p1_0[] = {
  145780. 1,
  145781. 0,
  145782. 2,
  145783. };
  145784. static long _vq_lengthlist__8u1__p1_0[] = {
  145785. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  145786. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  145787. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  145788. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  145789. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  145790. 10,
  145791. };
  145792. static float _vq_quantthresh__8u1__p1_0[] = {
  145793. -0.5, 0.5,
  145794. };
  145795. static long _vq_quantmap__8u1__p1_0[] = {
  145796. 1, 0, 2,
  145797. };
  145798. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  145799. _vq_quantthresh__8u1__p1_0,
  145800. _vq_quantmap__8u1__p1_0,
  145801. 3,
  145802. 3
  145803. };
  145804. static static_codebook _8u1__p1_0 = {
  145805. 4, 81,
  145806. _vq_lengthlist__8u1__p1_0,
  145807. 1, -535822336, 1611661312, 2, 0,
  145808. _vq_quantlist__8u1__p1_0,
  145809. NULL,
  145810. &_vq_auxt__8u1__p1_0,
  145811. NULL,
  145812. 0
  145813. };
  145814. static long _vq_quantlist__8u1__p2_0[] = {
  145815. 1,
  145816. 0,
  145817. 2,
  145818. };
  145819. static long _vq_lengthlist__8u1__p2_0[] = {
  145820. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  145821. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  145822. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  145823. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  145824. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  145825. 7,
  145826. };
  145827. static float _vq_quantthresh__8u1__p2_0[] = {
  145828. -0.5, 0.5,
  145829. };
  145830. static long _vq_quantmap__8u1__p2_0[] = {
  145831. 1, 0, 2,
  145832. };
  145833. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  145834. _vq_quantthresh__8u1__p2_0,
  145835. _vq_quantmap__8u1__p2_0,
  145836. 3,
  145837. 3
  145838. };
  145839. static static_codebook _8u1__p2_0 = {
  145840. 4, 81,
  145841. _vq_lengthlist__8u1__p2_0,
  145842. 1, -535822336, 1611661312, 2, 0,
  145843. _vq_quantlist__8u1__p2_0,
  145844. NULL,
  145845. &_vq_auxt__8u1__p2_0,
  145846. NULL,
  145847. 0
  145848. };
  145849. static long _vq_quantlist__8u1__p3_0[] = {
  145850. 2,
  145851. 1,
  145852. 3,
  145853. 0,
  145854. 4,
  145855. };
  145856. static long _vq_lengthlist__8u1__p3_0[] = {
  145857. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145858. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145859. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  145860. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  145861. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  145862. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  145863. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  145864. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  145865. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  145866. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  145867. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  145868. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  145869. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  145870. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  145871. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  145872. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  145873. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  145874. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  145875. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  145876. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  145877. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  145878. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  145879. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  145880. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  145881. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  145882. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  145883. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  145884. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  145885. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  145886. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  145887. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  145888. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  145889. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  145890. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  145891. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  145892. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  145893. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  145894. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  145895. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  145896. 16,
  145897. };
  145898. static float _vq_quantthresh__8u1__p3_0[] = {
  145899. -1.5, -0.5, 0.5, 1.5,
  145900. };
  145901. static long _vq_quantmap__8u1__p3_0[] = {
  145902. 3, 1, 0, 2, 4,
  145903. };
  145904. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  145905. _vq_quantthresh__8u1__p3_0,
  145906. _vq_quantmap__8u1__p3_0,
  145907. 5,
  145908. 5
  145909. };
  145910. static static_codebook _8u1__p3_0 = {
  145911. 4, 625,
  145912. _vq_lengthlist__8u1__p3_0,
  145913. 1, -533725184, 1611661312, 3, 0,
  145914. _vq_quantlist__8u1__p3_0,
  145915. NULL,
  145916. &_vq_auxt__8u1__p3_0,
  145917. NULL,
  145918. 0
  145919. };
  145920. static long _vq_quantlist__8u1__p4_0[] = {
  145921. 2,
  145922. 1,
  145923. 3,
  145924. 0,
  145925. 4,
  145926. };
  145927. static long _vq_lengthlist__8u1__p4_0[] = {
  145928. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  145929. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  145930. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  145931. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  145932. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  145933. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  145934. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  145935. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  145936. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  145937. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  145938. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  145939. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  145940. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  145941. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  145942. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  145943. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  145944. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  145945. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  145946. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  145947. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  145948. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  145949. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  145950. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  145951. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  145952. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  145953. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  145954. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  145955. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  145956. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  145957. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  145958. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  145959. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  145960. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  145961. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  145962. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  145963. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  145964. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  145965. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  145966. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  145967. 10,
  145968. };
  145969. static float _vq_quantthresh__8u1__p4_0[] = {
  145970. -1.5, -0.5, 0.5, 1.5,
  145971. };
  145972. static long _vq_quantmap__8u1__p4_0[] = {
  145973. 3, 1, 0, 2, 4,
  145974. };
  145975. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  145976. _vq_quantthresh__8u1__p4_0,
  145977. _vq_quantmap__8u1__p4_0,
  145978. 5,
  145979. 5
  145980. };
  145981. static static_codebook _8u1__p4_0 = {
  145982. 4, 625,
  145983. _vq_lengthlist__8u1__p4_0,
  145984. 1, -533725184, 1611661312, 3, 0,
  145985. _vq_quantlist__8u1__p4_0,
  145986. NULL,
  145987. &_vq_auxt__8u1__p4_0,
  145988. NULL,
  145989. 0
  145990. };
  145991. static long _vq_quantlist__8u1__p5_0[] = {
  145992. 4,
  145993. 3,
  145994. 5,
  145995. 2,
  145996. 6,
  145997. 1,
  145998. 7,
  145999. 0,
  146000. 8,
  146001. };
  146002. static long _vq_lengthlist__8u1__p5_0[] = {
  146003. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146004. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146005. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146006. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146007. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  146008. 13,
  146009. };
  146010. static float _vq_quantthresh__8u1__p5_0[] = {
  146011. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146012. };
  146013. static long _vq_quantmap__8u1__p5_0[] = {
  146014. 7, 5, 3, 1, 0, 2, 4, 6,
  146015. 8,
  146016. };
  146017. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  146018. _vq_quantthresh__8u1__p5_0,
  146019. _vq_quantmap__8u1__p5_0,
  146020. 9,
  146021. 9
  146022. };
  146023. static static_codebook _8u1__p5_0 = {
  146024. 2, 81,
  146025. _vq_lengthlist__8u1__p5_0,
  146026. 1, -531628032, 1611661312, 4, 0,
  146027. _vq_quantlist__8u1__p5_0,
  146028. NULL,
  146029. &_vq_auxt__8u1__p5_0,
  146030. NULL,
  146031. 0
  146032. };
  146033. static long _vq_quantlist__8u1__p6_0[] = {
  146034. 4,
  146035. 3,
  146036. 5,
  146037. 2,
  146038. 6,
  146039. 1,
  146040. 7,
  146041. 0,
  146042. 8,
  146043. };
  146044. static long _vq_lengthlist__8u1__p6_0[] = {
  146045. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146046. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146047. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146048. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146049. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146050. 10,
  146051. };
  146052. static float _vq_quantthresh__8u1__p6_0[] = {
  146053. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146054. };
  146055. static long _vq_quantmap__8u1__p6_0[] = {
  146056. 7, 5, 3, 1, 0, 2, 4, 6,
  146057. 8,
  146058. };
  146059. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146060. _vq_quantthresh__8u1__p6_0,
  146061. _vq_quantmap__8u1__p6_0,
  146062. 9,
  146063. 9
  146064. };
  146065. static static_codebook _8u1__p6_0 = {
  146066. 2, 81,
  146067. _vq_lengthlist__8u1__p6_0,
  146068. 1, -531628032, 1611661312, 4, 0,
  146069. _vq_quantlist__8u1__p6_0,
  146070. NULL,
  146071. &_vq_auxt__8u1__p6_0,
  146072. NULL,
  146073. 0
  146074. };
  146075. static long _vq_quantlist__8u1__p7_0[] = {
  146076. 1,
  146077. 0,
  146078. 2,
  146079. };
  146080. static long _vq_lengthlist__8u1__p7_0[] = {
  146081. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146082. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146083. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146084. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146085. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146086. 11,
  146087. };
  146088. static float _vq_quantthresh__8u1__p7_0[] = {
  146089. -5.5, 5.5,
  146090. };
  146091. static long _vq_quantmap__8u1__p7_0[] = {
  146092. 1, 0, 2,
  146093. };
  146094. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146095. _vq_quantthresh__8u1__p7_0,
  146096. _vq_quantmap__8u1__p7_0,
  146097. 3,
  146098. 3
  146099. };
  146100. static static_codebook _8u1__p7_0 = {
  146101. 4, 81,
  146102. _vq_lengthlist__8u1__p7_0,
  146103. 1, -529137664, 1618345984, 2, 0,
  146104. _vq_quantlist__8u1__p7_0,
  146105. NULL,
  146106. &_vq_auxt__8u1__p7_0,
  146107. NULL,
  146108. 0
  146109. };
  146110. static long _vq_quantlist__8u1__p7_1[] = {
  146111. 5,
  146112. 4,
  146113. 6,
  146114. 3,
  146115. 7,
  146116. 2,
  146117. 8,
  146118. 1,
  146119. 9,
  146120. 0,
  146121. 10,
  146122. };
  146123. static long _vq_lengthlist__8u1__p7_1[] = {
  146124. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146125. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146126. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146127. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146128. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146129. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146130. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146131. 9, 9, 9, 9, 9,10,10,10,10,
  146132. };
  146133. static float _vq_quantthresh__8u1__p7_1[] = {
  146134. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146135. 3.5, 4.5,
  146136. };
  146137. static long _vq_quantmap__8u1__p7_1[] = {
  146138. 9, 7, 5, 3, 1, 0, 2, 4,
  146139. 6, 8, 10,
  146140. };
  146141. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146142. _vq_quantthresh__8u1__p7_1,
  146143. _vq_quantmap__8u1__p7_1,
  146144. 11,
  146145. 11
  146146. };
  146147. static static_codebook _8u1__p7_1 = {
  146148. 2, 121,
  146149. _vq_lengthlist__8u1__p7_1,
  146150. 1, -531365888, 1611661312, 4, 0,
  146151. _vq_quantlist__8u1__p7_1,
  146152. NULL,
  146153. &_vq_auxt__8u1__p7_1,
  146154. NULL,
  146155. 0
  146156. };
  146157. static long _vq_quantlist__8u1__p8_0[] = {
  146158. 5,
  146159. 4,
  146160. 6,
  146161. 3,
  146162. 7,
  146163. 2,
  146164. 8,
  146165. 1,
  146166. 9,
  146167. 0,
  146168. 10,
  146169. };
  146170. static long _vq_lengthlist__8u1__p8_0[] = {
  146171. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146172. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146173. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146174. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146175. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146176. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146177. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146178. 12,13,13,14,14,15,15,15,15,
  146179. };
  146180. static float _vq_quantthresh__8u1__p8_0[] = {
  146181. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146182. 38.5, 49.5,
  146183. };
  146184. static long _vq_quantmap__8u1__p8_0[] = {
  146185. 9, 7, 5, 3, 1, 0, 2, 4,
  146186. 6, 8, 10,
  146187. };
  146188. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146189. _vq_quantthresh__8u1__p8_0,
  146190. _vq_quantmap__8u1__p8_0,
  146191. 11,
  146192. 11
  146193. };
  146194. static static_codebook _8u1__p8_0 = {
  146195. 2, 121,
  146196. _vq_lengthlist__8u1__p8_0,
  146197. 1, -524582912, 1618345984, 4, 0,
  146198. _vq_quantlist__8u1__p8_0,
  146199. NULL,
  146200. &_vq_auxt__8u1__p8_0,
  146201. NULL,
  146202. 0
  146203. };
  146204. static long _vq_quantlist__8u1__p8_1[] = {
  146205. 5,
  146206. 4,
  146207. 6,
  146208. 3,
  146209. 7,
  146210. 2,
  146211. 8,
  146212. 1,
  146213. 9,
  146214. 0,
  146215. 10,
  146216. };
  146217. static long _vq_lengthlist__8u1__p8_1[] = {
  146218. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146219. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146220. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146221. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146222. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146223. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146224. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146225. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146226. };
  146227. static float _vq_quantthresh__8u1__p8_1[] = {
  146228. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146229. 3.5, 4.5,
  146230. };
  146231. static long _vq_quantmap__8u1__p8_1[] = {
  146232. 9, 7, 5, 3, 1, 0, 2, 4,
  146233. 6, 8, 10,
  146234. };
  146235. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146236. _vq_quantthresh__8u1__p8_1,
  146237. _vq_quantmap__8u1__p8_1,
  146238. 11,
  146239. 11
  146240. };
  146241. static static_codebook _8u1__p8_1 = {
  146242. 2, 121,
  146243. _vq_lengthlist__8u1__p8_1,
  146244. 1, -531365888, 1611661312, 4, 0,
  146245. _vq_quantlist__8u1__p8_1,
  146246. NULL,
  146247. &_vq_auxt__8u1__p8_1,
  146248. NULL,
  146249. 0
  146250. };
  146251. static long _vq_quantlist__8u1__p9_0[] = {
  146252. 7,
  146253. 6,
  146254. 8,
  146255. 5,
  146256. 9,
  146257. 4,
  146258. 10,
  146259. 3,
  146260. 11,
  146261. 2,
  146262. 12,
  146263. 1,
  146264. 13,
  146265. 0,
  146266. 14,
  146267. };
  146268. static long _vq_lengthlist__8u1__p9_0[] = {
  146269. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146270. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146271. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146281. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146283. 10,
  146284. };
  146285. static float _vq_quantthresh__8u1__p9_0[] = {
  146286. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146287. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146288. };
  146289. static long _vq_quantmap__8u1__p9_0[] = {
  146290. 13, 11, 9, 7, 5, 3, 1, 0,
  146291. 2, 4, 6, 8, 10, 12, 14,
  146292. };
  146293. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146294. _vq_quantthresh__8u1__p9_0,
  146295. _vq_quantmap__8u1__p9_0,
  146296. 15,
  146297. 15
  146298. };
  146299. static static_codebook _8u1__p9_0 = {
  146300. 2, 225,
  146301. _vq_lengthlist__8u1__p9_0,
  146302. 1, -514071552, 1627381760, 4, 0,
  146303. _vq_quantlist__8u1__p9_0,
  146304. NULL,
  146305. &_vq_auxt__8u1__p9_0,
  146306. NULL,
  146307. 0
  146308. };
  146309. static long _vq_quantlist__8u1__p9_1[] = {
  146310. 7,
  146311. 6,
  146312. 8,
  146313. 5,
  146314. 9,
  146315. 4,
  146316. 10,
  146317. 3,
  146318. 11,
  146319. 2,
  146320. 12,
  146321. 1,
  146322. 13,
  146323. 0,
  146324. 14,
  146325. };
  146326. static long _vq_lengthlist__8u1__p9_1[] = {
  146327. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146328. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146329. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146330. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146331. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146332. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146333. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146334. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146335. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146336. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146337. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146338. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146339. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146340. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146341. 13,
  146342. };
  146343. static float _vq_quantthresh__8u1__p9_1[] = {
  146344. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146345. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146346. };
  146347. static long _vq_quantmap__8u1__p9_1[] = {
  146348. 13, 11, 9, 7, 5, 3, 1, 0,
  146349. 2, 4, 6, 8, 10, 12, 14,
  146350. };
  146351. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146352. _vq_quantthresh__8u1__p9_1,
  146353. _vq_quantmap__8u1__p9_1,
  146354. 15,
  146355. 15
  146356. };
  146357. static static_codebook _8u1__p9_1 = {
  146358. 2, 225,
  146359. _vq_lengthlist__8u1__p9_1,
  146360. 1, -522338304, 1620115456, 4, 0,
  146361. _vq_quantlist__8u1__p9_1,
  146362. NULL,
  146363. &_vq_auxt__8u1__p9_1,
  146364. NULL,
  146365. 0
  146366. };
  146367. static long _vq_quantlist__8u1__p9_2[] = {
  146368. 8,
  146369. 7,
  146370. 9,
  146371. 6,
  146372. 10,
  146373. 5,
  146374. 11,
  146375. 4,
  146376. 12,
  146377. 3,
  146378. 13,
  146379. 2,
  146380. 14,
  146381. 1,
  146382. 15,
  146383. 0,
  146384. 16,
  146385. };
  146386. static long _vq_lengthlist__8u1__p9_2[] = {
  146387. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146388. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146389. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146390. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146391. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146392. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146393. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146394. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146395. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146396. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146397. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146398. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146399. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146400. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146401. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146402. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146403. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146404. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146405. 10,
  146406. };
  146407. static float _vq_quantthresh__8u1__p9_2[] = {
  146408. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146409. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146410. };
  146411. static long _vq_quantmap__8u1__p9_2[] = {
  146412. 15, 13, 11, 9, 7, 5, 3, 1,
  146413. 0, 2, 4, 6, 8, 10, 12, 14,
  146414. 16,
  146415. };
  146416. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146417. _vq_quantthresh__8u1__p9_2,
  146418. _vq_quantmap__8u1__p9_2,
  146419. 17,
  146420. 17
  146421. };
  146422. static static_codebook _8u1__p9_2 = {
  146423. 2, 289,
  146424. _vq_lengthlist__8u1__p9_2,
  146425. 1, -529530880, 1611661312, 5, 0,
  146426. _vq_quantlist__8u1__p9_2,
  146427. NULL,
  146428. &_vq_auxt__8u1__p9_2,
  146429. NULL,
  146430. 0
  146431. };
  146432. static long _huff_lengthlist__8u1__single[] = {
  146433. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146434. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146435. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146436. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146437. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146438. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146439. 13, 8, 8,15,
  146440. };
  146441. static static_codebook _huff_book__8u1__single = {
  146442. 2, 100,
  146443. _huff_lengthlist__8u1__single,
  146444. 0, 0, 0, 0, 0,
  146445. NULL,
  146446. NULL,
  146447. NULL,
  146448. NULL,
  146449. 0
  146450. };
  146451. static long _huff_lengthlist__44u0__long[] = {
  146452. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146453. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146454. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146455. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146456. };
  146457. static static_codebook _huff_book__44u0__long = {
  146458. 2, 64,
  146459. _huff_lengthlist__44u0__long,
  146460. 0, 0, 0, 0, 0,
  146461. NULL,
  146462. NULL,
  146463. NULL,
  146464. NULL,
  146465. 0
  146466. };
  146467. static long _vq_quantlist__44u0__p1_0[] = {
  146468. 1,
  146469. 0,
  146470. 2,
  146471. };
  146472. static long _vq_lengthlist__44u0__p1_0[] = {
  146473. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146474. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146475. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146476. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146477. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146478. 13,
  146479. };
  146480. static float _vq_quantthresh__44u0__p1_0[] = {
  146481. -0.5, 0.5,
  146482. };
  146483. static long _vq_quantmap__44u0__p1_0[] = {
  146484. 1, 0, 2,
  146485. };
  146486. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146487. _vq_quantthresh__44u0__p1_0,
  146488. _vq_quantmap__44u0__p1_0,
  146489. 3,
  146490. 3
  146491. };
  146492. static static_codebook _44u0__p1_0 = {
  146493. 4, 81,
  146494. _vq_lengthlist__44u0__p1_0,
  146495. 1, -535822336, 1611661312, 2, 0,
  146496. _vq_quantlist__44u0__p1_0,
  146497. NULL,
  146498. &_vq_auxt__44u0__p1_0,
  146499. NULL,
  146500. 0
  146501. };
  146502. static long _vq_quantlist__44u0__p2_0[] = {
  146503. 1,
  146504. 0,
  146505. 2,
  146506. };
  146507. static long _vq_lengthlist__44u0__p2_0[] = {
  146508. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146509. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146510. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146511. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146512. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146513. 9,
  146514. };
  146515. static float _vq_quantthresh__44u0__p2_0[] = {
  146516. -0.5, 0.5,
  146517. };
  146518. static long _vq_quantmap__44u0__p2_0[] = {
  146519. 1, 0, 2,
  146520. };
  146521. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146522. _vq_quantthresh__44u0__p2_0,
  146523. _vq_quantmap__44u0__p2_0,
  146524. 3,
  146525. 3
  146526. };
  146527. static static_codebook _44u0__p2_0 = {
  146528. 4, 81,
  146529. _vq_lengthlist__44u0__p2_0,
  146530. 1, -535822336, 1611661312, 2, 0,
  146531. _vq_quantlist__44u0__p2_0,
  146532. NULL,
  146533. &_vq_auxt__44u0__p2_0,
  146534. NULL,
  146535. 0
  146536. };
  146537. static long _vq_quantlist__44u0__p3_0[] = {
  146538. 2,
  146539. 1,
  146540. 3,
  146541. 0,
  146542. 4,
  146543. };
  146544. static long _vq_lengthlist__44u0__p3_0[] = {
  146545. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146546. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146547. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146548. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146549. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146550. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146551. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146552. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146553. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146554. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146555. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146556. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146557. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146558. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146559. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146560. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146561. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146562. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  146563. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  146564. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  146565. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  146566. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  146567. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  146568. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  146569. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  146570. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  146571. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  146572. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  146573. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  146574. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  146575. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  146576. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  146577. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  146578. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  146579. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  146580. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  146581. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  146582. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  146583. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  146584. 19,
  146585. };
  146586. static float _vq_quantthresh__44u0__p3_0[] = {
  146587. -1.5, -0.5, 0.5, 1.5,
  146588. };
  146589. static long _vq_quantmap__44u0__p3_0[] = {
  146590. 3, 1, 0, 2, 4,
  146591. };
  146592. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  146593. _vq_quantthresh__44u0__p3_0,
  146594. _vq_quantmap__44u0__p3_0,
  146595. 5,
  146596. 5
  146597. };
  146598. static static_codebook _44u0__p3_0 = {
  146599. 4, 625,
  146600. _vq_lengthlist__44u0__p3_0,
  146601. 1, -533725184, 1611661312, 3, 0,
  146602. _vq_quantlist__44u0__p3_0,
  146603. NULL,
  146604. &_vq_auxt__44u0__p3_0,
  146605. NULL,
  146606. 0
  146607. };
  146608. static long _vq_quantlist__44u0__p4_0[] = {
  146609. 2,
  146610. 1,
  146611. 3,
  146612. 0,
  146613. 4,
  146614. };
  146615. static long _vq_lengthlist__44u0__p4_0[] = {
  146616. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  146617. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  146618. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  146619. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  146620. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  146621. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  146622. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  146623. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  146624. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  146625. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  146626. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  146627. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  146628. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  146629. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  146630. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  146631. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  146632. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  146633. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  146634. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  146635. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  146636. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  146637. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  146638. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  146639. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  146640. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  146641. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  146642. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  146643. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  146644. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  146645. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  146646. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  146647. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  146648. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  146649. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  146650. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  146651. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  146652. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  146653. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  146654. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  146655. 12,
  146656. };
  146657. static float _vq_quantthresh__44u0__p4_0[] = {
  146658. -1.5, -0.5, 0.5, 1.5,
  146659. };
  146660. static long _vq_quantmap__44u0__p4_0[] = {
  146661. 3, 1, 0, 2, 4,
  146662. };
  146663. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  146664. _vq_quantthresh__44u0__p4_0,
  146665. _vq_quantmap__44u0__p4_0,
  146666. 5,
  146667. 5
  146668. };
  146669. static static_codebook _44u0__p4_0 = {
  146670. 4, 625,
  146671. _vq_lengthlist__44u0__p4_0,
  146672. 1, -533725184, 1611661312, 3, 0,
  146673. _vq_quantlist__44u0__p4_0,
  146674. NULL,
  146675. &_vq_auxt__44u0__p4_0,
  146676. NULL,
  146677. 0
  146678. };
  146679. static long _vq_quantlist__44u0__p5_0[] = {
  146680. 4,
  146681. 3,
  146682. 5,
  146683. 2,
  146684. 6,
  146685. 1,
  146686. 7,
  146687. 0,
  146688. 8,
  146689. };
  146690. static long _vq_lengthlist__44u0__p5_0[] = {
  146691. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  146692. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  146693. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  146694. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  146695. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  146696. 12,
  146697. };
  146698. static float _vq_quantthresh__44u0__p5_0[] = {
  146699. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146700. };
  146701. static long _vq_quantmap__44u0__p5_0[] = {
  146702. 7, 5, 3, 1, 0, 2, 4, 6,
  146703. 8,
  146704. };
  146705. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  146706. _vq_quantthresh__44u0__p5_0,
  146707. _vq_quantmap__44u0__p5_0,
  146708. 9,
  146709. 9
  146710. };
  146711. static static_codebook _44u0__p5_0 = {
  146712. 2, 81,
  146713. _vq_lengthlist__44u0__p5_0,
  146714. 1, -531628032, 1611661312, 4, 0,
  146715. _vq_quantlist__44u0__p5_0,
  146716. NULL,
  146717. &_vq_auxt__44u0__p5_0,
  146718. NULL,
  146719. 0
  146720. };
  146721. static long _vq_quantlist__44u0__p6_0[] = {
  146722. 6,
  146723. 5,
  146724. 7,
  146725. 4,
  146726. 8,
  146727. 3,
  146728. 9,
  146729. 2,
  146730. 10,
  146731. 1,
  146732. 11,
  146733. 0,
  146734. 12,
  146735. };
  146736. static long _vq_lengthlist__44u0__p6_0[] = {
  146737. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  146738. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  146739. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  146740. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  146741. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  146742. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  146743. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  146744. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  146745. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  146746. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  146747. 15,17,16,17,18,17,17,18, 0,
  146748. };
  146749. static float _vq_quantthresh__44u0__p6_0[] = {
  146750. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  146751. 12.5, 17.5, 22.5, 27.5,
  146752. };
  146753. static long _vq_quantmap__44u0__p6_0[] = {
  146754. 11, 9, 7, 5, 3, 1, 0, 2,
  146755. 4, 6, 8, 10, 12,
  146756. };
  146757. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  146758. _vq_quantthresh__44u0__p6_0,
  146759. _vq_quantmap__44u0__p6_0,
  146760. 13,
  146761. 13
  146762. };
  146763. static static_codebook _44u0__p6_0 = {
  146764. 2, 169,
  146765. _vq_lengthlist__44u0__p6_0,
  146766. 1, -526516224, 1616117760, 4, 0,
  146767. _vq_quantlist__44u0__p6_0,
  146768. NULL,
  146769. &_vq_auxt__44u0__p6_0,
  146770. NULL,
  146771. 0
  146772. };
  146773. static long _vq_quantlist__44u0__p6_1[] = {
  146774. 2,
  146775. 1,
  146776. 3,
  146777. 0,
  146778. 4,
  146779. };
  146780. static long _vq_lengthlist__44u0__p6_1[] = {
  146781. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  146782. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  146783. };
  146784. static float _vq_quantthresh__44u0__p6_1[] = {
  146785. -1.5, -0.5, 0.5, 1.5,
  146786. };
  146787. static long _vq_quantmap__44u0__p6_1[] = {
  146788. 3, 1, 0, 2, 4,
  146789. };
  146790. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  146791. _vq_quantthresh__44u0__p6_1,
  146792. _vq_quantmap__44u0__p6_1,
  146793. 5,
  146794. 5
  146795. };
  146796. static static_codebook _44u0__p6_1 = {
  146797. 2, 25,
  146798. _vq_lengthlist__44u0__p6_1,
  146799. 1, -533725184, 1611661312, 3, 0,
  146800. _vq_quantlist__44u0__p6_1,
  146801. NULL,
  146802. &_vq_auxt__44u0__p6_1,
  146803. NULL,
  146804. 0
  146805. };
  146806. static long _vq_quantlist__44u0__p7_0[] = {
  146807. 2,
  146808. 1,
  146809. 3,
  146810. 0,
  146811. 4,
  146812. };
  146813. static long _vq_lengthlist__44u0__p7_0[] = {
  146814. 1, 4, 4,11,11, 9,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, 9,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,10,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,11,11,11,11,11,11,11,11,11,11,
  146830. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146831. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146832. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146833. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146834. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146835. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146836. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146837. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146838. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146839. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146840. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146841. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146842. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146843. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146844. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  146845. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146846. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146847. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146848. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146849. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146850. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146851. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146852. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146853. 10,
  146854. };
  146855. static float _vq_quantthresh__44u0__p7_0[] = {
  146856. -253.5, -84.5, 84.5, 253.5,
  146857. };
  146858. static long _vq_quantmap__44u0__p7_0[] = {
  146859. 3, 1, 0, 2, 4,
  146860. };
  146861. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  146862. _vq_quantthresh__44u0__p7_0,
  146863. _vq_quantmap__44u0__p7_0,
  146864. 5,
  146865. 5
  146866. };
  146867. static static_codebook _44u0__p7_0 = {
  146868. 4, 625,
  146869. _vq_lengthlist__44u0__p7_0,
  146870. 1, -518709248, 1626677248, 3, 0,
  146871. _vq_quantlist__44u0__p7_0,
  146872. NULL,
  146873. &_vq_auxt__44u0__p7_0,
  146874. NULL,
  146875. 0
  146876. };
  146877. static long _vq_quantlist__44u0__p7_1[] = {
  146878. 6,
  146879. 5,
  146880. 7,
  146881. 4,
  146882. 8,
  146883. 3,
  146884. 9,
  146885. 2,
  146886. 10,
  146887. 1,
  146888. 11,
  146889. 0,
  146890. 12,
  146891. };
  146892. static long _vq_lengthlist__44u0__p7_1[] = {
  146893. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  146894. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  146895. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  146896. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  146897. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  146898. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  146899. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  146900. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  146901. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  146902. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  146903. 15,15,15,15,15,15,15,15,15,
  146904. };
  146905. static float _vq_quantthresh__44u0__p7_1[] = {
  146906. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  146907. 32.5, 45.5, 58.5, 71.5,
  146908. };
  146909. static long _vq_quantmap__44u0__p7_1[] = {
  146910. 11, 9, 7, 5, 3, 1, 0, 2,
  146911. 4, 6, 8, 10, 12,
  146912. };
  146913. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  146914. _vq_quantthresh__44u0__p7_1,
  146915. _vq_quantmap__44u0__p7_1,
  146916. 13,
  146917. 13
  146918. };
  146919. static static_codebook _44u0__p7_1 = {
  146920. 2, 169,
  146921. _vq_lengthlist__44u0__p7_1,
  146922. 1, -523010048, 1618608128, 4, 0,
  146923. _vq_quantlist__44u0__p7_1,
  146924. NULL,
  146925. &_vq_auxt__44u0__p7_1,
  146926. NULL,
  146927. 0
  146928. };
  146929. static long _vq_quantlist__44u0__p7_2[] = {
  146930. 6,
  146931. 5,
  146932. 7,
  146933. 4,
  146934. 8,
  146935. 3,
  146936. 9,
  146937. 2,
  146938. 10,
  146939. 1,
  146940. 11,
  146941. 0,
  146942. 12,
  146943. };
  146944. static long _vq_lengthlist__44u0__p7_2[] = {
  146945. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  146946. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  146947. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  146948. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  146949. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  146950. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  146951. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  146952. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146953. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  146954. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  146955. 9, 9, 9,10, 9, 9,10,10, 9,
  146956. };
  146957. static float _vq_quantthresh__44u0__p7_2[] = {
  146958. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  146959. 2.5, 3.5, 4.5, 5.5,
  146960. };
  146961. static long _vq_quantmap__44u0__p7_2[] = {
  146962. 11, 9, 7, 5, 3, 1, 0, 2,
  146963. 4, 6, 8, 10, 12,
  146964. };
  146965. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  146966. _vq_quantthresh__44u0__p7_2,
  146967. _vq_quantmap__44u0__p7_2,
  146968. 13,
  146969. 13
  146970. };
  146971. static static_codebook _44u0__p7_2 = {
  146972. 2, 169,
  146973. _vq_lengthlist__44u0__p7_2,
  146974. 1, -531103744, 1611661312, 4, 0,
  146975. _vq_quantlist__44u0__p7_2,
  146976. NULL,
  146977. &_vq_auxt__44u0__p7_2,
  146978. NULL,
  146979. 0
  146980. };
  146981. static long _huff_lengthlist__44u0__short[] = {
  146982. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  146983. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  146984. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  146985. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  146986. };
  146987. static static_codebook _huff_book__44u0__short = {
  146988. 2, 64,
  146989. _huff_lengthlist__44u0__short,
  146990. 0, 0, 0, 0, 0,
  146991. NULL,
  146992. NULL,
  146993. NULL,
  146994. NULL,
  146995. 0
  146996. };
  146997. static long _huff_lengthlist__44u1__long[] = {
  146998. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146999. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  147000. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  147001. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  147002. };
  147003. static static_codebook _huff_book__44u1__long = {
  147004. 2, 64,
  147005. _huff_lengthlist__44u1__long,
  147006. 0, 0, 0, 0, 0,
  147007. NULL,
  147008. NULL,
  147009. NULL,
  147010. NULL,
  147011. 0
  147012. };
  147013. static long _vq_quantlist__44u1__p1_0[] = {
  147014. 1,
  147015. 0,
  147016. 2,
  147017. };
  147018. static long _vq_lengthlist__44u1__p1_0[] = {
  147019. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147020. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147021. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  147022. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  147023. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  147024. 13,
  147025. };
  147026. static float _vq_quantthresh__44u1__p1_0[] = {
  147027. -0.5, 0.5,
  147028. };
  147029. static long _vq_quantmap__44u1__p1_0[] = {
  147030. 1, 0, 2,
  147031. };
  147032. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  147033. _vq_quantthresh__44u1__p1_0,
  147034. _vq_quantmap__44u1__p1_0,
  147035. 3,
  147036. 3
  147037. };
  147038. static static_codebook _44u1__p1_0 = {
  147039. 4, 81,
  147040. _vq_lengthlist__44u1__p1_0,
  147041. 1, -535822336, 1611661312, 2, 0,
  147042. _vq_quantlist__44u1__p1_0,
  147043. NULL,
  147044. &_vq_auxt__44u1__p1_0,
  147045. NULL,
  147046. 0
  147047. };
  147048. static long _vq_quantlist__44u1__p2_0[] = {
  147049. 1,
  147050. 0,
  147051. 2,
  147052. };
  147053. static long _vq_lengthlist__44u1__p2_0[] = {
  147054. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147055. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147056. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147057. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147058. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147059. 9,
  147060. };
  147061. static float _vq_quantthresh__44u1__p2_0[] = {
  147062. -0.5, 0.5,
  147063. };
  147064. static long _vq_quantmap__44u1__p2_0[] = {
  147065. 1, 0, 2,
  147066. };
  147067. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147068. _vq_quantthresh__44u1__p2_0,
  147069. _vq_quantmap__44u1__p2_0,
  147070. 3,
  147071. 3
  147072. };
  147073. static static_codebook _44u1__p2_0 = {
  147074. 4, 81,
  147075. _vq_lengthlist__44u1__p2_0,
  147076. 1, -535822336, 1611661312, 2, 0,
  147077. _vq_quantlist__44u1__p2_0,
  147078. NULL,
  147079. &_vq_auxt__44u1__p2_0,
  147080. NULL,
  147081. 0
  147082. };
  147083. static long _vq_quantlist__44u1__p3_0[] = {
  147084. 2,
  147085. 1,
  147086. 3,
  147087. 0,
  147088. 4,
  147089. };
  147090. static long _vq_lengthlist__44u1__p3_0[] = {
  147091. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147092. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147093. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147094. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147095. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147096. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147097. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147098. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147099. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147100. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147101. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147102. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147103. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147104. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147105. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147106. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147107. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147108. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147109. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147110. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147111. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147112. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147113. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147114. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147115. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147116. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147117. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147118. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147119. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147120. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147121. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147122. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147123. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147124. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147125. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147126. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147127. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147128. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147129. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147130. 19,
  147131. };
  147132. static float _vq_quantthresh__44u1__p3_0[] = {
  147133. -1.5, -0.5, 0.5, 1.5,
  147134. };
  147135. static long _vq_quantmap__44u1__p3_0[] = {
  147136. 3, 1, 0, 2, 4,
  147137. };
  147138. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147139. _vq_quantthresh__44u1__p3_0,
  147140. _vq_quantmap__44u1__p3_0,
  147141. 5,
  147142. 5
  147143. };
  147144. static static_codebook _44u1__p3_0 = {
  147145. 4, 625,
  147146. _vq_lengthlist__44u1__p3_0,
  147147. 1, -533725184, 1611661312, 3, 0,
  147148. _vq_quantlist__44u1__p3_0,
  147149. NULL,
  147150. &_vq_auxt__44u1__p3_0,
  147151. NULL,
  147152. 0
  147153. };
  147154. static long _vq_quantlist__44u1__p4_0[] = {
  147155. 2,
  147156. 1,
  147157. 3,
  147158. 0,
  147159. 4,
  147160. };
  147161. static long _vq_lengthlist__44u1__p4_0[] = {
  147162. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147163. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147164. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147165. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147166. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147167. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147168. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147169. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147170. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147171. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147172. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147173. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147174. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147175. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147176. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147177. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147178. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147179. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147180. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147181. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147182. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147183. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147184. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147185. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147186. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147187. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147188. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147189. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147190. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147191. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147192. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147193. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147194. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147195. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147196. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147197. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147198. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147199. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147200. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147201. 12,
  147202. };
  147203. static float _vq_quantthresh__44u1__p4_0[] = {
  147204. -1.5, -0.5, 0.5, 1.5,
  147205. };
  147206. static long _vq_quantmap__44u1__p4_0[] = {
  147207. 3, 1, 0, 2, 4,
  147208. };
  147209. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147210. _vq_quantthresh__44u1__p4_0,
  147211. _vq_quantmap__44u1__p4_0,
  147212. 5,
  147213. 5
  147214. };
  147215. static static_codebook _44u1__p4_0 = {
  147216. 4, 625,
  147217. _vq_lengthlist__44u1__p4_0,
  147218. 1, -533725184, 1611661312, 3, 0,
  147219. _vq_quantlist__44u1__p4_0,
  147220. NULL,
  147221. &_vq_auxt__44u1__p4_0,
  147222. NULL,
  147223. 0
  147224. };
  147225. static long _vq_quantlist__44u1__p5_0[] = {
  147226. 4,
  147227. 3,
  147228. 5,
  147229. 2,
  147230. 6,
  147231. 1,
  147232. 7,
  147233. 0,
  147234. 8,
  147235. };
  147236. static long _vq_lengthlist__44u1__p5_0[] = {
  147237. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147238. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147239. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147240. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147241. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147242. 12,
  147243. };
  147244. static float _vq_quantthresh__44u1__p5_0[] = {
  147245. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147246. };
  147247. static long _vq_quantmap__44u1__p5_0[] = {
  147248. 7, 5, 3, 1, 0, 2, 4, 6,
  147249. 8,
  147250. };
  147251. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147252. _vq_quantthresh__44u1__p5_0,
  147253. _vq_quantmap__44u1__p5_0,
  147254. 9,
  147255. 9
  147256. };
  147257. static static_codebook _44u1__p5_0 = {
  147258. 2, 81,
  147259. _vq_lengthlist__44u1__p5_0,
  147260. 1, -531628032, 1611661312, 4, 0,
  147261. _vq_quantlist__44u1__p5_0,
  147262. NULL,
  147263. &_vq_auxt__44u1__p5_0,
  147264. NULL,
  147265. 0
  147266. };
  147267. static long _vq_quantlist__44u1__p6_0[] = {
  147268. 6,
  147269. 5,
  147270. 7,
  147271. 4,
  147272. 8,
  147273. 3,
  147274. 9,
  147275. 2,
  147276. 10,
  147277. 1,
  147278. 11,
  147279. 0,
  147280. 12,
  147281. };
  147282. static long _vq_lengthlist__44u1__p6_0[] = {
  147283. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147284. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147285. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147286. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147287. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147288. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147289. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147290. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147291. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147292. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147293. 15,17,16,17,18,17,17,18, 0,
  147294. };
  147295. static float _vq_quantthresh__44u1__p6_0[] = {
  147296. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147297. 12.5, 17.5, 22.5, 27.5,
  147298. };
  147299. static long _vq_quantmap__44u1__p6_0[] = {
  147300. 11, 9, 7, 5, 3, 1, 0, 2,
  147301. 4, 6, 8, 10, 12,
  147302. };
  147303. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147304. _vq_quantthresh__44u1__p6_0,
  147305. _vq_quantmap__44u1__p6_0,
  147306. 13,
  147307. 13
  147308. };
  147309. static static_codebook _44u1__p6_0 = {
  147310. 2, 169,
  147311. _vq_lengthlist__44u1__p6_0,
  147312. 1, -526516224, 1616117760, 4, 0,
  147313. _vq_quantlist__44u1__p6_0,
  147314. NULL,
  147315. &_vq_auxt__44u1__p6_0,
  147316. NULL,
  147317. 0
  147318. };
  147319. static long _vq_quantlist__44u1__p6_1[] = {
  147320. 2,
  147321. 1,
  147322. 3,
  147323. 0,
  147324. 4,
  147325. };
  147326. static long _vq_lengthlist__44u1__p6_1[] = {
  147327. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147328. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147329. };
  147330. static float _vq_quantthresh__44u1__p6_1[] = {
  147331. -1.5, -0.5, 0.5, 1.5,
  147332. };
  147333. static long _vq_quantmap__44u1__p6_1[] = {
  147334. 3, 1, 0, 2, 4,
  147335. };
  147336. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147337. _vq_quantthresh__44u1__p6_1,
  147338. _vq_quantmap__44u1__p6_1,
  147339. 5,
  147340. 5
  147341. };
  147342. static static_codebook _44u1__p6_1 = {
  147343. 2, 25,
  147344. _vq_lengthlist__44u1__p6_1,
  147345. 1, -533725184, 1611661312, 3, 0,
  147346. _vq_quantlist__44u1__p6_1,
  147347. NULL,
  147348. &_vq_auxt__44u1__p6_1,
  147349. NULL,
  147350. 0
  147351. };
  147352. static long _vq_quantlist__44u1__p7_0[] = {
  147353. 3,
  147354. 2,
  147355. 4,
  147356. 1,
  147357. 5,
  147358. 0,
  147359. 6,
  147360. };
  147361. static long _vq_lengthlist__44u1__p7_0[] = {
  147362. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147363. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147364. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147365. 8,
  147366. };
  147367. static float _vq_quantthresh__44u1__p7_0[] = {
  147368. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147369. };
  147370. static long _vq_quantmap__44u1__p7_0[] = {
  147371. 5, 3, 1, 0, 2, 4, 6,
  147372. };
  147373. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147374. _vq_quantthresh__44u1__p7_0,
  147375. _vq_quantmap__44u1__p7_0,
  147376. 7,
  147377. 7
  147378. };
  147379. static static_codebook _44u1__p7_0 = {
  147380. 2, 49,
  147381. _vq_lengthlist__44u1__p7_0,
  147382. 1, -518017024, 1626677248, 3, 0,
  147383. _vq_quantlist__44u1__p7_0,
  147384. NULL,
  147385. &_vq_auxt__44u1__p7_0,
  147386. NULL,
  147387. 0
  147388. };
  147389. static long _vq_quantlist__44u1__p7_1[] = {
  147390. 6,
  147391. 5,
  147392. 7,
  147393. 4,
  147394. 8,
  147395. 3,
  147396. 9,
  147397. 2,
  147398. 10,
  147399. 1,
  147400. 11,
  147401. 0,
  147402. 12,
  147403. };
  147404. static long _vq_lengthlist__44u1__p7_1[] = {
  147405. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147406. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147407. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147408. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147409. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147410. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147411. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147412. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147413. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147414. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147415. 15,15,15,15,15,15,15,15,15,
  147416. };
  147417. static float _vq_quantthresh__44u1__p7_1[] = {
  147418. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147419. 32.5, 45.5, 58.5, 71.5,
  147420. };
  147421. static long _vq_quantmap__44u1__p7_1[] = {
  147422. 11, 9, 7, 5, 3, 1, 0, 2,
  147423. 4, 6, 8, 10, 12,
  147424. };
  147425. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147426. _vq_quantthresh__44u1__p7_1,
  147427. _vq_quantmap__44u1__p7_1,
  147428. 13,
  147429. 13
  147430. };
  147431. static static_codebook _44u1__p7_1 = {
  147432. 2, 169,
  147433. _vq_lengthlist__44u1__p7_1,
  147434. 1, -523010048, 1618608128, 4, 0,
  147435. _vq_quantlist__44u1__p7_1,
  147436. NULL,
  147437. &_vq_auxt__44u1__p7_1,
  147438. NULL,
  147439. 0
  147440. };
  147441. static long _vq_quantlist__44u1__p7_2[] = {
  147442. 6,
  147443. 5,
  147444. 7,
  147445. 4,
  147446. 8,
  147447. 3,
  147448. 9,
  147449. 2,
  147450. 10,
  147451. 1,
  147452. 11,
  147453. 0,
  147454. 12,
  147455. };
  147456. static long _vq_lengthlist__44u1__p7_2[] = {
  147457. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147458. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147459. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147460. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147461. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147462. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147463. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147464. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147465. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147466. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147467. 9, 9, 9,10, 9, 9,10,10, 9,
  147468. };
  147469. static float _vq_quantthresh__44u1__p7_2[] = {
  147470. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147471. 2.5, 3.5, 4.5, 5.5,
  147472. };
  147473. static long _vq_quantmap__44u1__p7_2[] = {
  147474. 11, 9, 7, 5, 3, 1, 0, 2,
  147475. 4, 6, 8, 10, 12,
  147476. };
  147477. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147478. _vq_quantthresh__44u1__p7_2,
  147479. _vq_quantmap__44u1__p7_2,
  147480. 13,
  147481. 13
  147482. };
  147483. static static_codebook _44u1__p7_2 = {
  147484. 2, 169,
  147485. _vq_lengthlist__44u1__p7_2,
  147486. 1, -531103744, 1611661312, 4, 0,
  147487. _vq_quantlist__44u1__p7_2,
  147488. NULL,
  147489. &_vq_auxt__44u1__p7_2,
  147490. NULL,
  147491. 0
  147492. };
  147493. static long _huff_lengthlist__44u1__short[] = {
  147494. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147495. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147496. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147497. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147498. };
  147499. static static_codebook _huff_book__44u1__short = {
  147500. 2, 64,
  147501. _huff_lengthlist__44u1__short,
  147502. 0, 0, 0, 0, 0,
  147503. NULL,
  147504. NULL,
  147505. NULL,
  147506. NULL,
  147507. 0
  147508. };
  147509. static long _huff_lengthlist__44u2__long[] = {
  147510. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147511. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147512. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147513. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147514. };
  147515. static static_codebook _huff_book__44u2__long = {
  147516. 2, 64,
  147517. _huff_lengthlist__44u2__long,
  147518. 0, 0, 0, 0, 0,
  147519. NULL,
  147520. NULL,
  147521. NULL,
  147522. NULL,
  147523. 0
  147524. };
  147525. static long _vq_quantlist__44u2__p1_0[] = {
  147526. 1,
  147527. 0,
  147528. 2,
  147529. };
  147530. static long _vq_lengthlist__44u2__p1_0[] = {
  147531. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147532. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147533. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147534. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147535. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147536. 13,
  147537. };
  147538. static float _vq_quantthresh__44u2__p1_0[] = {
  147539. -0.5, 0.5,
  147540. };
  147541. static long _vq_quantmap__44u2__p1_0[] = {
  147542. 1, 0, 2,
  147543. };
  147544. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147545. _vq_quantthresh__44u2__p1_0,
  147546. _vq_quantmap__44u2__p1_0,
  147547. 3,
  147548. 3
  147549. };
  147550. static static_codebook _44u2__p1_0 = {
  147551. 4, 81,
  147552. _vq_lengthlist__44u2__p1_0,
  147553. 1, -535822336, 1611661312, 2, 0,
  147554. _vq_quantlist__44u2__p1_0,
  147555. NULL,
  147556. &_vq_auxt__44u2__p1_0,
  147557. NULL,
  147558. 0
  147559. };
  147560. static long _vq_quantlist__44u2__p2_0[] = {
  147561. 1,
  147562. 0,
  147563. 2,
  147564. };
  147565. static long _vq_lengthlist__44u2__p2_0[] = {
  147566. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  147567. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  147568. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147569. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  147570. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147571. 9,
  147572. };
  147573. static float _vq_quantthresh__44u2__p2_0[] = {
  147574. -0.5, 0.5,
  147575. };
  147576. static long _vq_quantmap__44u2__p2_0[] = {
  147577. 1, 0, 2,
  147578. };
  147579. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  147580. _vq_quantthresh__44u2__p2_0,
  147581. _vq_quantmap__44u2__p2_0,
  147582. 3,
  147583. 3
  147584. };
  147585. static static_codebook _44u2__p2_0 = {
  147586. 4, 81,
  147587. _vq_lengthlist__44u2__p2_0,
  147588. 1, -535822336, 1611661312, 2, 0,
  147589. _vq_quantlist__44u2__p2_0,
  147590. NULL,
  147591. &_vq_auxt__44u2__p2_0,
  147592. NULL,
  147593. 0
  147594. };
  147595. static long _vq_quantlist__44u2__p3_0[] = {
  147596. 2,
  147597. 1,
  147598. 3,
  147599. 0,
  147600. 4,
  147601. };
  147602. static long _vq_lengthlist__44u2__p3_0[] = {
  147603. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  147604. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  147605. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  147606. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  147607. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  147608. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  147609. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  147610. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  147611. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  147612. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  147613. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  147614. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  147615. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  147616. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  147617. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  147618. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  147619. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  147620. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  147621. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  147622. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  147623. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  147624. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  147625. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  147626. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  147627. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  147628. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  147629. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  147630. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  147631. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  147632. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  147633. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  147634. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  147635. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  147636. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  147637. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  147638. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  147639. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  147640. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  147641. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  147642. 0,
  147643. };
  147644. static float _vq_quantthresh__44u2__p3_0[] = {
  147645. -1.5, -0.5, 0.5, 1.5,
  147646. };
  147647. static long _vq_quantmap__44u2__p3_0[] = {
  147648. 3, 1, 0, 2, 4,
  147649. };
  147650. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  147651. _vq_quantthresh__44u2__p3_0,
  147652. _vq_quantmap__44u2__p3_0,
  147653. 5,
  147654. 5
  147655. };
  147656. static static_codebook _44u2__p3_0 = {
  147657. 4, 625,
  147658. _vq_lengthlist__44u2__p3_0,
  147659. 1, -533725184, 1611661312, 3, 0,
  147660. _vq_quantlist__44u2__p3_0,
  147661. NULL,
  147662. &_vq_auxt__44u2__p3_0,
  147663. NULL,
  147664. 0
  147665. };
  147666. static long _vq_quantlist__44u2__p4_0[] = {
  147667. 2,
  147668. 1,
  147669. 3,
  147670. 0,
  147671. 4,
  147672. };
  147673. static long _vq_lengthlist__44u2__p4_0[] = {
  147674. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  147675. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  147676. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  147677. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  147678. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  147679. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  147680. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  147681. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  147682. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  147683. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  147684. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  147685. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147686. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  147687. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  147688. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  147689. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  147690. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  147691. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  147692. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  147693. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  147694. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  147695. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  147696. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  147697. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  147698. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  147699. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  147700. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  147701. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  147702. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  147703. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  147704. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  147705. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  147706. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  147707. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  147708. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  147709. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  147710. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  147711. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  147712. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  147713. 13,
  147714. };
  147715. static float _vq_quantthresh__44u2__p4_0[] = {
  147716. -1.5, -0.5, 0.5, 1.5,
  147717. };
  147718. static long _vq_quantmap__44u2__p4_0[] = {
  147719. 3, 1, 0, 2, 4,
  147720. };
  147721. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  147722. _vq_quantthresh__44u2__p4_0,
  147723. _vq_quantmap__44u2__p4_0,
  147724. 5,
  147725. 5
  147726. };
  147727. static static_codebook _44u2__p4_0 = {
  147728. 4, 625,
  147729. _vq_lengthlist__44u2__p4_0,
  147730. 1, -533725184, 1611661312, 3, 0,
  147731. _vq_quantlist__44u2__p4_0,
  147732. NULL,
  147733. &_vq_auxt__44u2__p4_0,
  147734. NULL,
  147735. 0
  147736. };
  147737. static long _vq_quantlist__44u2__p5_0[] = {
  147738. 4,
  147739. 3,
  147740. 5,
  147741. 2,
  147742. 6,
  147743. 1,
  147744. 7,
  147745. 0,
  147746. 8,
  147747. };
  147748. static long _vq_lengthlist__44u2__p5_0[] = {
  147749. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  147750. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  147751. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  147752. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  147753. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  147754. 13,
  147755. };
  147756. static float _vq_quantthresh__44u2__p5_0[] = {
  147757. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147758. };
  147759. static long _vq_quantmap__44u2__p5_0[] = {
  147760. 7, 5, 3, 1, 0, 2, 4, 6,
  147761. 8,
  147762. };
  147763. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  147764. _vq_quantthresh__44u2__p5_0,
  147765. _vq_quantmap__44u2__p5_0,
  147766. 9,
  147767. 9
  147768. };
  147769. static static_codebook _44u2__p5_0 = {
  147770. 2, 81,
  147771. _vq_lengthlist__44u2__p5_0,
  147772. 1, -531628032, 1611661312, 4, 0,
  147773. _vq_quantlist__44u2__p5_0,
  147774. NULL,
  147775. &_vq_auxt__44u2__p5_0,
  147776. NULL,
  147777. 0
  147778. };
  147779. static long _vq_quantlist__44u2__p6_0[] = {
  147780. 6,
  147781. 5,
  147782. 7,
  147783. 4,
  147784. 8,
  147785. 3,
  147786. 9,
  147787. 2,
  147788. 10,
  147789. 1,
  147790. 11,
  147791. 0,
  147792. 12,
  147793. };
  147794. static long _vq_lengthlist__44u2__p6_0[] = {
  147795. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  147796. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  147797. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  147798. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  147799. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  147800. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  147801. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  147802. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  147803. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  147804. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  147805. 15,17,17,16,18,17,18, 0, 0,
  147806. };
  147807. static float _vq_quantthresh__44u2__p6_0[] = {
  147808. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147809. 12.5, 17.5, 22.5, 27.5,
  147810. };
  147811. static long _vq_quantmap__44u2__p6_0[] = {
  147812. 11, 9, 7, 5, 3, 1, 0, 2,
  147813. 4, 6, 8, 10, 12,
  147814. };
  147815. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  147816. _vq_quantthresh__44u2__p6_0,
  147817. _vq_quantmap__44u2__p6_0,
  147818. 13,
  147819. 13
  147820. };
  147821. static static_codebook _44u2__p6_0 = {
  147822. 2, 169,
  147823. _vq_lengthlist__44u2__p6_0,
  147824. 1, -526516224, 1616117760, 4, 0,
  147825. _vq_quantlist__44u2__p6_0,
  147826. NULL,
  147827. &_vq_auxt__44u2__p6_0,
  147828. NULL,
  147829. 0
  147830. };
  147831. static long _vq_quantlist__44u2__p6_1[] = {
  147832. 2,
  147833. 1,
  147834. 3,
  147835. 0,
  147836. 4,
  147837. };
  147838. static long _vq_lengthlist__44u2__p6_1[] = {
  147839. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  147840. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  147841. };
  147842. static float _vq_quantthresh__44u2__p6_1[] = {
  147843. -1.5, -0.5, 0.5, 1.5,
  147844. };
  147845. static long _vq_quantmap__44u2__p6_1[] = {
  147846. 3, 1, 0, 2, 4,
  147847. };
  147848. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  147849. _vq_quantthresh__44u2__p6_1,
  147850. _vq_quantmap__44u2__p6_1,
  147851. 5,
  147852. 5
  147853. };
  147854. static static_codebook _44u2__p6_1 = {
  147855. 2, 25,
  147856. _vq_lengthlist__44u2__p6_1,
  147857. 1, -533725184, 1611661312, 3, 0,
  147858. _vq_quantlist__44u2__p6_1,
  147859. NULL,
  147860. &_vq_auxt__44u2__p6_1,
  147861. NULL,
  147862. 0
  147863. };
  147864. static long _vq_quantlist__44u2__p7_0[] = {
  147865. 4,
  147866. 3,
  147867. 5,
  147868. 2,
  147869. 6,
  147870. 1,
  147871. 7,
  147872. 0,
  147873. 8,
  147874. };
  147875. static long _vq_lengthlist__44u2__p7_0[] = {
  147876. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  147877. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  147878. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147879. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147880. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147881. 11,
  147882. };
  147883. static float _vq_quantthresh__44u2__p7_0[] = {
  147884. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  147885. };
  147886. static long _vq_quantmap__44u2__p7_0[] = {
  147887. 7, 5, 3, 1, 0, 2, 4, 6,
  147888. 8,
  147889. };
  147890. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  147891. _vq_quantthresh__44u2__p7_0,
  147892. _vq_quantmap__44u2__p7_0,
  147893. 9,
  147894. 9
  147895. };
  147896. static static_codebook _44u2__p7_0 = {
  147897. 2, 81,
  147898. _vq_lengthlist__44u2__p7_0,
  147899. 1, -516612096, 1626677248, 4, 0,
  147900. _vq_quantlist__44u2__p7_0,
  147901. NULL,
  147902. &_vq_auxt__44u2__p7_0,
  147903. NULL,
  147904. 0
  147905. };
  147906. static long _vq_quantlist__44u2__p7_1[] = {
  147907. 6,
  147908. 5,
  147909. 7,
  147910. 4,
  147911. 8,
  147912. 3,
  147913. 9,
  147914. 2,
  147915. 10,
  147916. 1,
  147917. 11,
  147918. 0,
  147919. 12,
  147920. };
  147921. static long _vq_lengthlist__44u2__p7_1[] = {
  147922. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  147923. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  147924. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  147925. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  147926. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  147927. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  147928. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  147929. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  147930. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  147931. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  147932. 14,14,14,17,15,17,17,17,17,
  147933. };
  147934. static float _vq_quantthresh__44u2__p7_1[] = {
  147935. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147936. 32.5, 45.5, 58.5, 71.5,
  147937. };
  147938. static long _vq_quantmap__44u2__p7_1[] = {
  147939. 11, 9, 7, 5, 3, 1, 0, 2,
  147940. 4, 6, 8, 10, 12,
  147941. };
  147942. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  147943. _vq_quantthresh__44u2__p7_1,
  147944. _vq_quantmap__44u2__p7_1,
  147945. 13,
  147946. 13
  147947. };
  147948. static static_codebook _44u2__p7_1 = {
  147949. 2, 169,
  147950. _vq_lengthlist__44u2__p7_1,
  147951. 1, -523010048, 1618608128, 4, 0,
  147952. _vq_quantlist__44u2__p7_1,
  147953. NULL,
  147954. &_vq_auxt__44u2__p7_1,
  147955. NULL,
  147956. 0
  147957. };
  147958. static long _vq_quantlist__44u2__p7_2[] = {
  147959. 6,
  147960. 5,
  147961. 7,
  147962. 4,
  147963. 8,
  147964. 3,
  147965. 9,
  147966. 2,
  147967. 10,
  147968. 1,
  147969. 11,
  147970. 0,
  147971. 12,
  147972. };
  147973. static long _vq_lengthlist__44u2__p7_2[] = {
  147974. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  147975. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  147976. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  147977. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147978. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  147979. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  147980. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  147981. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147982. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  147983. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  147984. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147985. };
  147986. static float _vq_quantthresh__44u2__p7_2[] = {
  147987. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147988. 2.5, 3.5, 4.5, 5.5,
  147989. };
  147990. static long _vq_quantmap__44u2__p7_2[] = {
  147991. 11, 9, 7, 5, 3, 1, 0, 2,
  147992. 4, 6, 8, 10, 12,
  147993. };
  147994. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  147995. _vq_quantthresh__44u2__p7_2,
  147996. _vq_quantmap__44u2__p7_2,
  147997. 13,
  147998. 13
  147999. };
  148000. static static_codebook _44u2__p7_2 = {
  148001. 2, 169,
  148002. _vq_lengthlist__44u2__p7_2,
  148003. 1, -531103744, 1611661312, 4, 0,
  148004. _vq_quantlist__44u2__p7_2,
  148005. NULL,
  148006. &_vq_auxt__44u2__p7_2,
  148007. NULL,
  148008. 0
  148009. };
  148010. static long _huff_lengthlist__44u2__short[] = {
  148011. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  148012. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  148013. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  148014. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  148015. };
  148016. static static_codebook _huff_book__44u2__short = {
  148017. 2, 64,
  148018. _huff_lengthlist__44u2__short,
  148019. 0, 0, 0, 0, 0,
  148020. NULL,
  148021. NULL,
  148022. NULL,
  148023. NULL,
  148024. 0
  148025. };
  148026. static long _huff_lengthlist__44u3__long[] = {
  148027. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  148028. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  148029. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  148030. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  148031. };
  148032. static static_codebook _huff_book__44u3__long = {
  148033. 2, 64,
  148034. _huff_lengthlist__44u3__long,
  148035. 0, 0, 0, 0, 0,
  148036. NULL,
  148037. NULL,
  148038. NULL,
  148039. NULL,
  148040. 0
  148041. };
  148042. static long _vq_quantlist__44u3__p1_0[] = {
  148043. 1,
  148044. 0,
  148045. 2,
  148046. };
  148047. static long _vq_lengthlist__44u3__p1_0[] = {
  148048. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148049. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148050. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148051. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148052. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148053. 13,
  148054. };
  148055. static float _vq_quantthresh__44u3__p1_0[] = {
  148056. -0.5, 0.5,
  148057. };
  148058. static long _vq_quantmap__44u3__p1_0[] = {
  148059. 1, 0, 2,
  148060. };
  148061. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148062. _vq_quantthresh__44u3__p1_0,
  148063. _vq_quantmap__44u3__p1_0,
  148064. 3,
  148065. 3
  148066. };
  148067. static static_codebook _44u3__p1_0 = {
  148068. 4, 81,
  148069. _vq_lengthlist__44u3__p1_0,
  148070. 1, -535822336, 1611661312, 2, 0,
  148071. _vq_quantlist__44u3__p1_0,
  148072. NULL,
  148073. &_vq_auxt__44u3__p1_0,
  148074. NULL,
  148075. 0
  148076. };
  148077. static long _vq_quantlist__44u3__p2_0[] = {
  148078. 1,
  148079. 0,
  148080. 2,
  148081. };
  148082. static long _vq_lengthlist__44u3__p2_0[] = {
  148083. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148084. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148085. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148086. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148087. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148088. 9,
  148089. };
  148090. static float _vq_quantthresh__44u3__p2_0[] = {
  148091. -0.5, 0.5,
  148092. };
  148093. static long _vq_quantmap__44u3__p2_0[] = {
  148094. 1, 0, 2,
  148095. };
  148096. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148097. _vq_quantthresh__44u3__p2_0,
  148098. _vq_quantmap__44u3__p2_0,
  148099. 3,
  148100. 3
  148101. };
  148102. static static_codebook _44u3__p2_0 = {
  148103. 4, 81,
  148104. _vq_lengthlist__44u3__p2_0,
  148105. 1, -535822336, 1611661312, 2, 0,
  148106. _vq_quantlist__44u3__p2_0,
  148107. NULL,
  148108. &_vq_auxt__44u3__p2_0,
  148109. NULL,
  148110. 0
  148111. };
  148112. static long _vq_quantlist__44u3__p3_0[] = {
  148113. 2,
  148114. 1,
  148115. 3,
  148116. 0,
  148117. 4,
  148118. };
  148119. static long _vq_lengthlist__44u3__p3_0[] = {
  148120. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148121. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148122. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148123. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148124. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148125. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148126. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148127. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148128. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148129. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148130. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148131. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148132. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148133. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148134. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148135. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148136. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148137. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148138. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148139. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148140. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148141. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148142. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148143. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148144. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148145. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148146. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148147. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148148. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148149. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148150. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148151. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148152. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148153. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148154. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148155. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148156. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148157. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148158. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148159. 0,
  148160. };
  148161. static float _vq_quantthresh__44u3__p3_0[] = {
  148162. -1.5, -0.5, 0.5, 1.5,
  148163. };
  148164. static long _vq_quantmap__44u3__p3_0[] = {
  148165. 3, 1, 0, 2, 4,
  148166. };
  148167. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148168. _vq_quantthresh__44u3__p3_0,
  148169. _vq_quantmap__44u3__p3_0,
  148170. 5,
  148171. 5
  148172. };
  148173. static static_codebook _44u3__p3_0 = {
  148174. 4, 625,
  148175. _vq_lengthlist__44u3__p3_0,
  148176. 1, -533725184, 1611661312, 3, 0,
  148177. _vq_quantlist__44u3__p3_0,
  148178. NULL,
  148179. &_vq_auxt__44u3__p3_0,
  148180. NULL,
  148181. 0
  148182. };
  148183. static long _vq_quantlist__44u3__p4_0[] = {
  148184. 2,
  148185. 1,
  148186. 3,
  148187. 0,
  148188. 4,
  148189. };
  148190. static long _vq_lengthlist__44u3__p4_0[] = {
  148191. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148192. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148193. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148194. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148195. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148196. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148197. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148198. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148199. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148200. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148201. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148202. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148203. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148204. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148205. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148206. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148207. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148208. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148209. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148210. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148211. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148212. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148213. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148214. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148215. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148216. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148217. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148218. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148219. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148220. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148221. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148222. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148223. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148224. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148225. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148226. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148227. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148228. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148229. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148230. 13,
  148231. };
  148232. static float _vq_quantthresh__44u3__p4_0[] = {
  148233. -1.5, -0.5, 0.5, 1.5,
  148234. };
  148235. static long _vq_quantmap__44u3__p4_0[] = {
  148236. 3, 1, 0, 2, 4,
  148237. };
  148238. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148239. _vq_quantthresh__44u3__p4_0,
  148240. _vq_quantmap__44u3__p4_0,
  148241. 5,
  148242. 5
  148243. };
  148244. static static_codebook _44u3__p4_0 = {
  148245. 4, 625,
  148246. _vq_lengthlist__44u3__p4_0,
  148247. 1, -533725184, 1611661312, 3, 0,
  148248. _vq_quantlist__44u3__p4_0,
  148249. NULL,
  148250. &_vq_auxt__44u3__p4_0,
  148251. NULL,
  148252. 0
  148253. };
  148254. static long _vq_quantlist__44u3__p5_0[] = {
  148255. 4,
  148256. 3,
  148257. 5,
  148258. 2,
  148259. 6,
  148260. 1,
  148261. 7,
  148262. 0,
  148263. 8,
  148264. };
  148265. static long _vq_lengthlist__44u3__p5_0[] = {
  148266. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148267. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148268. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148269. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148270. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148271. 12,
  148272. };
  148273. static float _vq_quantthresh__44u3__p5_0[] = {
  148274. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148275. };
  148276. static long _vq_quantmap__44u3__p5_0[] = {
  148277. 7, 5, 3, 1, 0, 2, 4, 6,
  148278. 8,
  148279. };
  148280. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148281. _vq_quantthresh__44u3__p5_0,
  148282. _vq_quantmap__44u3__p5_0,
  148283. 9,
  148284. 9
  148285. };
  148286. static static_codebook _44u3__p5_0 = {
  148287. 2, 81,
  148288. _vq_lengthlist__44u3__p5_0,
  148289. 1, -531628032, 1611661312, 4, 0,
  148290. _vq_quantlist__44u3__p5_0,
  148291. NULL,
  148292. &_vq_auxt__44u3__p5_0,
  148293. NULL,
  148294. 0
  148295. };
  148296. static long _vq_quantlist__44u3__p6_0[] = {
  148297. 6,
  148298. 5,
  148299. 7,
  148300. 4,
  148301. 8,
  148302. 3,
  148303. 9,
  148304. 2,
  148305. 10,
  148306. 1,
  148307. 11,
  148308. 0,
  148309. 12,
  148310. };
  148311. static long _vq_lengthlist__44u3__p6_0[] = {
  148312. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148313. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148314. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148315. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148316. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148317. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148318. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148319. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148320. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148321. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148322. 15,16,16,16,17,18,16,20,18,
  148323. };
  148324. static float _vq_quantthresh__44u3__p6_0[] = {
  148325. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148326. 12.5, 17.5, 22.5, 27.5,
  148327. };
  148328. static long _vq_quantmap__44u3__p6_0[] = {
  148329. 11, 9, 7, 5, 3, 1, 0, 2,
  148330. 4, 6, 8, 10, 12,
  148331. };
  148332. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148333. _vq_quantthresh__44u3__p6_0,
  148334. _vq_quantmap__44u3__p6_0,
  148335. 13,
  148336. 13
  148337. };
  148338. static static_codebook _44u3__p6_0 = {
  148339. 2, 169,
  148340. _vq_lengthlist__44u3__p6_0,
  148341. 1, -526516224, 1616117760, 4, 0,
  148342. _vq_quantlist__44u3__p6_0,
  148343. NULL,
  148344. &_vq_auxt__44u3__p6_0,
  148345. NULL,
  148346. 0
  148347. };
  148348. static long _vq_quantlist__44u3__p6_1[] = {
  148349. 2,
  148350. 1,
  148351. 3,
  148352. 0,
  148353. 4,
  148354. };
  148355. static long _vq_lengthlist__44u3__p6_1[] = {
  148356. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148357. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148358. };
  148359. static float _vq_quantthresh__44u3__p6_1[] = {
  148360. -1.5, -0.5, 0.5, 1.5,
  148361. };
  148362. static long _vq_quantmap__44u3__p6_1[] = {
  148363. 3, 1, 0, 2, 4,
  148364. };
  148365. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148366. _vq_quantthresh__44u3__p6_1,
  148367. _vq_quantmap__44u3__p6_1,
  148368. 5,
  148369. 5
  148370. };
  148371. static static_codebook _44u3__p6_1 = {
  148372. 2, 25,
  148373. _vq_lengthlist__44u3__p6_1,
  148374. 1, -533725184, 1611661312, 3, 0,
  148375. _vq_quantlist__44u3__p6_1,
  148376. NULL,
  148377. &_vq_auxt__44u3__p6_1,
  148378. NULL,
  148379. 0
  148380. };
  148381. static long _vq_quantlist__44u3__p7_0[] = {
  148382. 4,
  148383. 3,
  148384. 5,
  148385. 2,
  148386. 6,
  148387. 1,
  148388. 7,
  148389. 0,
  148390. 8,
  148391. };
  148392. static long _vq_lengthlist__44u3__p7_0[] = {
  148393. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148394. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148395. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148396. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148397. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148398. 9,
  148399. };
  148400. static float _vq_quantthresh__44u3__p7_0[] = {
  148401. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148402. };
  148403. static long _vq_quantmap__44u3__p7_0[] = {
  148404. 7, 5, 3, 1, 0, 2, 4, 6,
  148405. 8,
  148406. };
  148407. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148408. _vq_quantthresh__44u3__p7_0,
  148409. _vq_quantmap__44u3__p7_0,
  148410. 9,
  148411. 9
  148412. };
  148413. static static_codebook _44u3__p7_0 = {
  148414. 2, 81,
  148415. _vq_lengthlist__44u3__p7_0,
  148416. 1, -515907584, 1627381760, 4, 0,
  148417. _vq_quantlist__44u3__p7_0,
  148418. NULL,
  148419. &_vq_auxt__44u3__p7_0,
  148420. NULL,
  148421. 0
  148422. };
  148423. static long _vq_quantlist__44u3__p7_1[] = {
  148424. 7,
  148425. 6,
  148426. 8,
  148427. 5,
  148428. 9,
  148429. 4,
  148430. 10,
  148431. 3,
  148432. 11,
  148433. 2,
  148434. 12,
  148435. 1,
  148436. 13,
  148437. 0,
  148438. 14,
  148439. };
  148440. static long _vq_lengthlist__44u3__p7_1[] = {
  148441. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148442. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148443. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148444. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148445. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148446. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148447. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148448. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148449. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148450. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148451. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148452. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148453. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148454. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148455. 17,
  148456. };
  148457. static float _vq_quantthresh__44u3__p7_1[] = {
  148458. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148459. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148460. };
  148461. static long _vq_quantmap__44u3__p7_1[] = {
  148462. 13, 11, 9, 7, 5, 3, 1, 0,
  148463. 2, 4, 6, 8, 10, 12, 14,
  148464. };
  148465. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148466. _vq_quantthresh__44u3__p7_1,
  148467. _vq_quantmap__44u3__p7_1,
  148468. 15,
  148469. 15
  148470. };
  148471. static static_codebook _44u3__p7_1 = {
  148472. 2, 225,
  148473. _vq_lengthlist__44u3__p7_1,
  148474. 1, -522338304, 1620115456, 4, 0,
  148475. _vq_quantlist__44u3__p7_1,
  148476. NULL,
  148477. &_vq_auxt__44u3__p7_1,
  148478. NULL,
  148479. 0
  148480. };
  148481. static long _vq_quantlist__44u3__p7_2[] = {
  148482. 8,
  148483. 7,
  148484. 9,
  148485. 6,
  148486. 10,
  148487. 5,
  148488. 11,
  148489. 4,
  148490. 12,
  148491. 3,
  148492. 13,
  148493. 2,
  148494. 14,
  148495. 1,
  148496. 15,
  148497. 0,
  148498. 16,
  148499. };
  148500. static long _vq_lengthlist__44u3__p7_2[] = {
  148501. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148502. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148503. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148504. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148505. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148506. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148507. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148508. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148509. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148510. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148511. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148512. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148513. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148514. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148515. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148516. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148517. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148518. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148519. 11,
  148520. };
  148521. static float _vq_quantthresh__44u3__p7_2[] = {
  148522. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148523. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148524. };
  148525. static long _vq_quantmap__44u3__p7_2[] = {
  148526. 15, 13, 11, 9, 7, 5, 3, 1,
  148527. 0, 2, 4, 6, 8, 10, 12, 14,
  148528. 16,
  148529. };
  148530. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148531. _vq_quantthresh__44u3__p7_2,
  148532. _vq_quantmap__44u3__p7_2,
  148533. 17,
  148534. 17
  148535. };
  148536. static static_codebook _44u3__p7_2 = {
  148537. 2, 289,
  148538. _vq_lengthlist__44u3__p7_2,
  148539. 1, -529530880, 1611661312, 5, 0,
  148540. _vq_quantlist__44u3__p7_2,
  148541. NULL,
  148542. &_vq_auxt__44u3__p7_2,
  148543. NULL,
  148544. 0
  148545. };
  148546. static long _huff_lengthlist__44u3__short[] = {
  148547. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148548. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148549. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148550. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148551. };
  148552. static static_codebook _huff_book__44u3__short = {
  148553. 2, 64,
  148554. _huff_lengthlist__44u3__short,
  148555. 0, 0, 0, 0, 0,
  148556. NULL,
  148557. NULL,
  148558. NULL,
  148559. NULL,
  148560. 0
  148561. };
  148562. static long _huff_lengthlist__44u4__long[] = {
  148563. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  148564. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  148565. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  148566. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  148567. };
  148568. static static_codebook _huff_book__44u4__long = {
  148569. 2, 64,
  148570. _huff_lengthlist__44u4__long,
  148571. 0, 0, 0, 0, 0,
  148572. NULL,
  148573. NULL,
  148574. NULL,
  148575. NULL,
  148576. 0
  148577. };
  148578. static long _vq_quantlist__44u4__p1_0[] = {
  148579. 1,
  148580. 0,
  148581. 2,
  148582. };
  148583. static long _vq_lengthlist__44u4__p1_0[] = {
  148584. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148585. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148586. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  148587. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148588. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  148589. 13,
  148590. };
  148591. static float _vq_quantthresh__44u4__p1_0[] = {
  148592. -0.5, 0.5,
  148593. };
  148594. static long _vq_quantmap__44u4__p1_0[] = {
  148595. 1, 0, 2,
  148596. };
  148597. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  148598. _vq_quantthresh__44u4__p1_0,
  148599. _vq_quantmap__44u4__p1_0,
  148600. 3,
  148601. 3
  148602. };
  148603. static static_codebook _44u4__p1_0 = {
  148604. 4, 81,
  148605. _vq_lengthlist__44u4__p1_0,
  148606. 1, -535822336, 1611661312, 2, 0,
  148607. _vq_quantlist__44u4__p1_0,
  148608. NULL,
  148609. &_vq_auxt__44u4__p1_0,
  148610. NULL,
  148611. 0
  148612. };
  148613. static long _vq_quantlist__44u4__p2_0[] = {
  148614. 1,
  148615. 0,
  148616. 2,
  148617. };
  148618. static long _vq_lengthlist__44u4__p2_0[] = {
  148619. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148620. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  148621. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148622. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  148623. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148624. 9,
  148625. };
  148626. static float _vq_quantthresh__44u4__p2_0[] = {
  148627. -0.5, 0.5,
  148628. };
  148629. static long _vq_quantmap__44u4__p2_0[] = {
  148630. 1, 0, 2,
  148631. };
  148632. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  148633. _vq_quantthresh__44u4__p2_0,
  148634. _vq_quantmap__44u4__p2_0,
  148635. 3,
  148636. 3
  148637. };
  148638. static static_codebook _44u4__p2_0 = {
  148639. 4, 81,
  148640. _vq_lengthlist__44u4__p2_0,
  148641. 1, -535822336, 1611661312, 2, 0,
  148642. _vq_quantlist__44u4__p2_0,
  148643. NULL,
  148644. &_vq_auxt__44u4__p2_0,
  148645. NULL,
  148646. 0
  148647. };
  148648. static long _vq_quantlist__44u4__p3_0[] = {
  148649. 2,
  148650. 1,
  148651. 3,
  148652. 0,
  148653. 4,
  148654. };
  148655. static long _vq_lengthlist__44u4__p3_0[] = {
  148656. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148657. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  148658. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  148659. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  148660. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  148661. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  148662. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  148663. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  148664. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  148665. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  148666. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  148667. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  148668. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  148669. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  148670. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  148671. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  148672. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  148673. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  148674. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  148675. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  148676. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  148677. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  148678. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  148679. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  148680. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  148681. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  148682. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  148683. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  148684. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  148685. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  148686. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  148687. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  148688. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  148689. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  148690. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  148691. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  148692. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  148693. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  148694. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  148695. 0,
  148696. };
  148697. static float _vq_quantthresh__44u4__p3_0[] = {
  148698. -1.5, -0.5, 0.5, 1.5,
  148699. };
  148700. static long _vq_quantmap__44u4__p3_0[] = {
  148701. 3, 1, 0, 2, 4,
  148702. };
  148703. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  148704. _vq_quantthresh__44u4__p3_0,
  148705. _vq_quantmap__44u4__p3_0,
  148706. 5,
  148707. 5
  148708. };
  148709. static static_codebook _44u4__p3_0 = {
  148710. 4, 625,
  148711. _vq_lengthlist__44u4__p3_0,
  148712. 1, -533725184, 1611661312, 3, 0,
  148713. _vq_quantlist__44u4__p3_0,
  148714. NULL,
  148715. &_vq_auxt__44u4__p3_0,
  148716. NULL,
  148717. 0
  148718. };
  148719. static long _vq_quantlist__44u4__p4_0[] = {
  148720. 2,
  148721. 1,
  148722. 3,
  148723. 0,
  148724. 4,
  148725. };
  148726. static long _vq_lengthlist__44u4__p4_0[] = {
  148727. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148728. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148729. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148730. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148731. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148732. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  148733. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  148734. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  148735. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148736. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148737. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148738. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148739. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148740. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  148741. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148742. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148743. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148744. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148745. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148746. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148747. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148748. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148749. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148750. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148751. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148752. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  148753. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  148754. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  148755. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  148756. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  148757. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  148758. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148759. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148760. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  148761. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148762. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  148763. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148764. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  148765. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  148766. 13,
  148767. };
  148768. static float _vq_quantthresh__44u4__p4_0[] = {
  148769. -1.5, -0.5, 0.5, 1.5,
  148770. };
  148771. static long _vq_quantmap__44u4__p4_0[] = {
  148772. 3, 1, 0, 2, 4,
  148773. };
  148774. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  148775. _vq_quantthresh__44u4__p4_0,
  148776. _vq_quantmap__44u4__p4_0,
  148777. 5,
  148778. 5
  148779. };
  148780. static static_codebook _44u4__p4_0 = {
  148781. 4, 625,
  148782. _vq_lengthlist__44u4__p4_0,
  148783. 1, -533725184, 1611661312, 3, 0,
  148784. _vq_quantlist__44u4__p4_0,
  148785. NULL,
  148786. &_vq_auxt__44u4__p4_0,
  148787. NULL,
  148788. 0
  148789. };
  148790. static long _vq_quantlist__44u4__p5_0[] = {
  148791. 4,
  148792. 3,
  148793. 5,
  148794. 2,
  148795. 6,
  148796. 1,
  148797. 7,
  148798. 0,
  148799. 8,
  148800. };
  148801. static long _vq_lengthlist__44u4__p5_0[] = {
  148802. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148803. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148804. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  148805. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148806. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  148807. 12,
  148808. };
  148809. static float _vq_quantthresh__44u4__p5_0[] = {
  148810. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148811. };
  148812. static long _vq_quantmap__44u4__p5_0[] = {
  148813. 7, 5, 3, 1, 0, 2, 4, 6,
  148814. 8,
  148815. };
  148816. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  148817. _vq_quantthresh__44u4__p5_0,
  148818. _vq_quantmap__44u4__p5_0,
  148819. 9,
  148820. 9
  148821. };
  148822. static static_codebook _44u4__p5_0 = {
  148823. 2, 81,
  148824. _vq_lengthlist__44u4__p5_0,
  148825. 1, -531628032, 1611661312, 4, 0,
  148826. _vq_quantlist__44u4__p5_0,
  148827. NULL,
  148828. &_vq_auxt__44u4__p5_0,
  148829. NULL,
  148830. 0
  148831. };
  148832. static long _vq_quantlist__44u4__p6_0[] = {
  148833. 6,
  148834. 5,
  148835. 7,
  148836. 4,
  148837. 8,
  148838. 3,
  148839. 9,
  148840. 2,
  148841. 10,
  148842. 1,
  148843. 11,
  148844. 0,
  148845. 12,
  148846. };
  148847. static long _vq_lengthlist__44u4__p6_0[] = {
  148848. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  148849. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148850. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148851. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148852. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  148853. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  148854. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  148855. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  148856. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  148857. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  148858. 16,16,16,17,17,18,17,20,21,
  148859. };
  148860. static float _vq_quantthresh__44u4__p6_0[] = {
  148861. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148862. 12.5, 17.5, 22.5, 27.5,
  148863. };
  148864. static long _vq_quantmap__44u4__p6_0[] = {
  148865. 11, 9, 7, 5, 3, 1, 0, 2,
  148866. 4, 6, 8, 10, 12,
  148867. };
  148868. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  148869. _vq_quantthresh__44u4__p6_0,
  148870. _vq_quantmap__44u4__p6_0,
  148871. 13,
  148872. 13
  148873. };
  148874. static static_codebook _44u4__p6_0 = {
  148875. 2, 169,
  148876. _vq_lengthlist__44u4__p6_0,
  148877. 1, -526516224, 1616117760, 4, 0,
  148878. _vq_quantlist__44u4__p6_0,
  148879. NULL,
  148880. &_vq_auxt__44u4__p6_0,
  148881. NULL,
  148882. 0
  148883. };
  148884. static long _vq_quantlist__44u4__p6_1[] = {
  148885. 2,
  148886. 1,
  148887. 3,
  148888. 0,
  148889. 4,
  148890. };
  148891. static long _vq_lengthlist__44u4__p6_1[] = {
  148892. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148893. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148894. };
  148895. static float _vq_quantthresh__44u4__p6_1[] = {
  148896. -1.5, -0.5, 0.5, 1.5,
  148897. };
  148898. static long _vq_quantmap__44u4__p6_1[] = {
  148899. 3, 1, 0, 2, 4,
  148900. };
  148901. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  148902. _vq_quantthresh__44u4__p6_1,
  148903. _vq_quantmap__44u4__p6_1,
  148904. 5,
  148905. 5
  148906. };
  148907. static static_codebook _44u4__p6_1 = {
  148908. 2, 25,
  148909. _vq_lengthlist__44u4__p6_1,
  148910. 1, -533725184, 1611661312, 3, 0,
  148911. _vq_quantlist__44u4__p6_1,
  148912. NULL,
  148913. &_vq_auxt__44u4__p6_1,
  148914. NULL,
  148915. 0
  148916. };
  148917. static long _vq_quantlist__44u4__p7_0[] = {
  148918. 6,
  148919. 5,
  148920. 7,
  148921. 4,
  148922. 8,
  148923. 3,
  148924. 9,
  148925. 2,
  148926. 10,
  148927. 1,
  148928. 11,
  148929. 0,
  148930. 12,
  148931. };
  148932. static long _vq_lengthlist__44u4__p7_0[] = {
  148933. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  148934. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  148935. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148936. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148937. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  148938. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148939. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148940. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148941. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148942. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148943. 11,11,11,11,11,11,11,11,11,
  148944. };
  148945. static float _vq_quantthresh__44u4__p7_0[] = {
  148946. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  148947. 637.5, 892.5, 1147.5, 1402.5,
  148948. };
  148949. static long _vq_quantmap__44u4__p7_0[] = {
  148950. 11, 9, 7, 5, 3, 1, 0, 2,
  148951. 4, 6, 8, 10, 12,
  148952. };
  148953. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  148954. _vq_quantthresh__44u4__p7_0,
  148955. _vq_quantmap__44u4__p7_0,
  148956. 13,
  148957. 13
  148958. };
  148959. static static_codebook _44u4__p7_0 = {
  148960. 2, 169,
  148961. _vq_lengthlist__44u4__p7_0,
  148962. 1, -514332672, 1627381760, 4, 0,
  148963. _vq_quantlist__44u4__p7_0,
  148964. NULL,
  148965. &_vq_auxt__44u4__p7_0,
  148966. NULL,
  148967. 0
  148968. };
  148969. static long _vq_quantlist__44u4__p7_1[] = {
  148970. 7,
  148971. 6,
  148972. 8,
  148973. 5,
  148974. 9,
  148975. 4,
  148976. 10,
  148977. 3,
  148978. 11,
  148979. 2,
  148980. 12,
  148981. 1,
  148982. 13,
  148983. 0,
  148984. 14,
  148985. };
  148986. static long _vq_lengthlist__44u4__p7_1[] = {
  148987. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  148988. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  148989. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  148990. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  148991. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  148992. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  148993. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  148994. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  148995. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  148996. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  148997. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  148998. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  148999. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  149000. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  149001. 16,
  149002. };
  149003. static float _vq_quantthresh__44u4__p7_1[] = {
  149004. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149005. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149006. };
  149007. static long _vq_quantmap__44u4__p7_1[] = {
  149008. 13, 11, 9, 7, 5, 3, 1, 0,
  149009. 2, 4, 6, 8, 10, 12, 14,
  149010. };
  149011. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  149012. _vq_quantthresh__44u4__p7_1,
  149013. _vq_quantmap__44u4__p7_1,
  149014. 15,
  149015. 15
  149016. };
  149017. static static_codebook _44u4__p7_1 = {
  149018. 2, 225,
  149019. _vq_lengthlist__44u4__p7_1,
  149020. 1, -522338304, 1620115456, 4, 0,
  149021. _vq_quantlist__44u4__p7_1,
  149022. NULL,
  149023. &_vq_auxt__44u4__p7_1,
  149024. NULL,
  149025. 0
  149026. };
  149027. static long _vq_quantlist__44u4__p7_2[] = {
  149028. 8,
  149029. 7,
  149030. 9,
  149031. 6,
  149032. 10,
  149033. 5,
  149034. 11,
  149035. 4,
  149036. 12,
  149037. 3,
  149038. 13,
  149039. 2,
  149040. 14,
  149041. 1,
  149042. 15,
  149043. 0,
  149044. 16,
  149045. };
  149046. static long _vq_lengthlist__44u4__p7_2[] = {
  149047. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149048. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149049. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149050. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149051. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149052. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149053. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149054. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149055. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149056. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149057. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149058. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149059. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149060. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149061. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149062. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149063. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149064. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149065. 10,
  149066. };
  149067. static float _vq_quantthresh__44u4__p7_2[] = {
  149068. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149069. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149070. };
  149071. static long _vq_quantmap__44u4__p7_2[] = {
  149072. 15, 13, 11, 9, 7, 5, 3, 1,
  149073. 0, 2, 4, 6, 8, 10, 12, 14,
  149074. 16,
  149075. };
  149076. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149077. _vq_quantthresh__44u4__p7_2,
  149078. _vq_quantmap__44u4__p7_2,
  149079. 17,
  149080. 17
  149081. };
  149082. static static_codebook _44u4__p7_2 = {
  149083. 2, 289,
  149084. _vq_lengthlist__44u4__p7_2,
  149085. 1, -529530880, 1611661312, 5, 0,
  149086. _vq_quantlist__44u4__p7_2,
  149087. NULL,
  149088. &_vq_auxt__44u4__p7_2,
  149089. NULL,
  149090. 0
  149091. };
  149092. static long _huff_lengthlist__44u4__short[] = {
  149093. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149094. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149095. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149096. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149097. };
  149098. static static_codebook _huff_book__44u4__short = {
  149099. 2, 64,
  149100. _huff_lengthlist__44u4__short,
  149101. 0, 0, 0, 0, 0,
  149102. NULL,
  149103. NULL,
  149104. NULL,
  149105. NULL,
  149106. 0
  149107. };
  149108. static long _huff_lengthlist__44u5__long[] = {
  149109. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149110. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149111. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149112. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149113. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149114. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149115. 14, 8, 7, 8,
  149116. };
  149117. static static_codebook _huff_book__44u5__long = {
  149118. 2, 100,
  149119. _huff_lengthlist__44u5__long,
  149120. 0, 0, 0, 0, 0,
  149121. NULL,
  149122. NULL,
  149123. NULL,
  149124. NULL,
  149125. 0
  149126. };
  149127. static long _vq_quantlist__44u5__p1_0[] = {
  149128. 1,
  149129. 0,
  149130. 2,
  149131. };
  149132. static long _vq_lengthlist__44u5__p1_0[] = {
  149133. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149134. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149135. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149136. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149137. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149138. 12,
  149139. };
  149140. static float _vq_quantthresh__44u5__p1_0[] = {
  149141. -0.5, 0.5,
  149142. };
  149143. static long _vq_quantmap__44u5__p1_0[] = {
  149144. 1, 0, 2,
  149145. };
  149146. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149147. _vq_quantthresh__44u5__p1_0,
  149148. _vq_quantmap__44u5__p1_0,
  149149. 3,
  149150. 3
  149151. };
  149152. static static_codebook _44u5__p1_0 = {
  149153. 4, 81,
  149154. _vq_lengthlist__44u5__p1_0,
  149155. 1, -535822336, 1611661312, 2, 0,
  149156. _vq_quantlist__44u5__p1_0,
  149157. NULL,
  149158. &_vq_auxt__44u5__p1_0,
  149159. NULL,
  149160. 0
  149161. };
  149162. static long _vq_quantlist__44u5__p2_0[] = {
  149163. 1,
  149164. 0,
  149165. 2,
  149166. };
  149167. static long _vq_lengthlist__44u5__p2_0[] = {
  149168. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149169. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149170. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149171. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149172. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149173. 9,
  149174. };
  149175. static float _vq_quantthresh__44u5__p2_0[] = {
  149176. -0.5, 0.5,
  149177. };
  149178. static long _vq_quantmap__44u5__p2_0[] = {
  149179. 1, 0, 2,
  149180. };
  149181. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149182. _vq_quantthresh__44u5__p2_0,
  149183. _vq_quantmap__44u5__p2_0,
  149184. 3,
  149185. 3
  149186. };
  149187. static static_codebook _44u5__p2_0 = {
  149188. 4, 81,
  149189. _vq_lengthlist__44u5__p2_0,
  149190. 1, -535822336, 1611661312, 2, 0,
  149191. _vq_quantlist__44u5__p2_0,
  149192. NULL,
  149193. &_vq_auxt__44u5__p2_0,
  149194. NULL,
  149195. 0
  149196. };
  149197. static long _vq_quantlist__44u5__p3_0[] = {
  149198. 2,
  149199. 1,
  149200. 3,
  149201. 0,
  149202. 4,
  149203. };
  149204. static long _vq_lengthlist__44u5__p3_0[] = {
  149205. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149206. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149207. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149208. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149209. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149210. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149211. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149212. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149213. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149214. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149215. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149216. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149217. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149218. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149219. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149220. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149221. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149222. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149223. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149224. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149225. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149226. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149227. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149228. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149229. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149230. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149231. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149232. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149233. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149234. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149235. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149236. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149237. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149238. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149239. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149240. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149241. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149242. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149243. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149244. 0,
  149245. };
  149246. static float _vq_quantthresh__44u5__p3_0[] = {
  149247. -1.5, -0.5, 0.5, 1.5,
  149248. };
  149249. static long _vq_quantmap__44u5__p3_0[] = {
  149250. 3, 1, 0, 2, 4,
  149251. };
  149252. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149253. _vq_quantthresh__44u5__p3_0,
  149254. _vq_quantmap__44u5__p3_0,
  149255. 5,
  149256. 5
  149257. };
  149258. static static_codebook _44u5__p3_0 = {
  149259. 4, 625,
  149260. _vq_lengthlist__44u5__p3_0,
  149261. 1, -533725184, 1611661312, 3, 0,
  149262. _vq_quantlist__44u5__p3_0,
  149263. NULL,
  149264. &_vq_auxt__44u5__p3_0,
  149265. NULL,
  149266. 0
  149267. };
  149268. static long _vq_quantlist__44u5__p4_0[] = {
  149269. 2,
  149270. 1,
  149271. 3,
  149272. 0,
  149273. 4,
  149274. };
  149275. static long _vq_lengthlist__44u5__p4_0[] = {
  149276. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149277. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149278. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149279. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149280. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149281. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149282. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149283. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149284. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149285. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149286. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149287. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149288. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149289. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149290. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149291. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149292. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149293. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149294. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149295. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149296. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149297. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149298. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149299. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149300. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149301. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149302. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149303. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149304. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149305. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149306. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149307. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149308. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149309. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149310. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149311. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149312. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149313. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149314. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149315. 12,
  149316. };
  149317. static float _vq_quantthresh__44u5__p4_0[] = {
  149318. -1.5, -0.5, 0.5, 1.5,
  149319. };
  149320. static long _vq_quantmap__44u5__p4_0[] = {
  149321. 3, 1, 0, 2, 4,
  149322. };
  149323. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149324. _vq_quantthresh__44u5__p4_0,
  149325. _vq_quantmap__44u5__p4_0,
  149326. 5,
  149327. 5
  149328. };
  149329. static static_codebook _44u5__p4_0 = {
  149330. 4, 625,
  149331. _vq_lengthlist__44u5__p4_0,
  149332. 1, -533725184, 1611661312, 3, 0,
  149333. _vq_quantlist__44u5__p4_0,
  149334. NULL,
  149335. &_vq_auxt__44u5__p4_0,
  149336. NULL,
  149337. 0
  149338. };
  149339. static long _vq_quantlist__44u5__p5_0[] = {
  149340. 4,
  149341. 3,
  149342. 5,
  149343. 2,
  149344. 6,
  149345. 1,
  149346. 7,
  149347. 0,
  149348. 8,
  149349. };
  149350. static long _vq_lengthlist__44u5__p5_0[] = {
  149351. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149352. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149353. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149354. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149355. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149356. 14,
  149357. };
  149358. static float _vq_quantthresh__44u5__p5_0[] = {
  149359. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149360. };
  149361. static long _vq_quantmap__44u5__p5_0[] = {
  149362. 7, 5, 3, 1, 0, 2, 4, 6,
  149363. 8,
  149364. };
  149365. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149366. _vq_quantthresh__44u5__p5_0,
  149367. _vq_quantmap__44u5__p5_0,
  149368. 9,
  149369. 9
  149370. };
  149371. static static_codebook _44u5__p5_0 = {
  149372. 2, 81,
  149373. _vq_lengthlist__44u5__p5_0,
  149374. 1, -531628032, 1611661312, 4, 0,
  149375. _vq_quantlist__44u5__p5_0,
  149376. NULL,
  149377. &_vq_auxt__44u5__p5_0,
  149378. NULL,
  149379. 0
  149380. };
  149381. static long _vq_quantlist__44u5__p6_0[] = {
  149382. 4,
  149383. 3,
  149384. 5,
  149385. 2,
  149386. 6,
  149387. 1,
  149388. 7,
  149389. 0,
  149390. 8,
  149391. };
  149392. static long _vq_lengthlist__44u5__p6_0[] = {
  149393. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149394. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149395. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149396. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149397. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149398. 11,
  149399. };
  149400. static float _vq_quantthresh__44u5__p6_0[] = {
  149401. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149402. };
  149403. static long _vq_quantmap__44u5__p6_0[] = {
  149404. 7, 5, 3, 1, 0, 2, 4, 6,
  149405. 8,
  149406. };
  149407. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149408. _vq_quantthresh__44u5__p6_0,
  149409. _vq_quantmap__44u5__p6_0,
  149410. 9,
  149411. 9
  149412. };
  149413. static static_codebook _44u5__p6_0 = {
  149414. 2, 81,
  149415. _vq_lengthlist__44u5__p6_0,
  149416. 1, -531628032, 1611661312, 4, 0,
  149417. _vq_quantlist__44u5__p6_0,
  149418. NULL,
  149419. &_vq_auxt__44u5__p6_0,
  149420. NULL,
  149421. 0
  149422. };
  149423. static long _vq_quantlist__44u5__p7_0[] = {
  149424. 1,
  149425. 0,
  149426. 2,
  149427. };
  149428. static long _vq_lengthlist__44u5__p7_0[] = {
  149429. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149430. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149431. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149432. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149433. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149434. 12,
  149435. };
  149436. static float _vq_quantthresh__44u5__p7_0[] = {
  149437. -5.5, 5.5,
  149438. };
  149439. static long _vq_quantmap__44u5__p7_0[] = {
  149440. 1, 0, 2,
  149441. };
  149442. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149443. _vq_quantthresh__44u5__p7_0,
  149444. _vq_quantmap__44u5__p7_0,
  149445. 3,
  149446. 3
  149447. };
  149448. static static_codebook _44u5__p7_0 = {
  149449. 4, 81,
  149450. _vq_lengthlist__44u5__p7_0,
  149451. 1, -529137664, 1618345984, 2, 0,
  149452. _vq_quantlist__44u5__p7_0,
  149453. NULL,
  149454. &_vq_auxt__44u5__p7_0,
  149455. NULL,
  149456. 0
  149457. };
  149458. static long _vq_quantlist__44u5__p7_1[] = {
  149459. 5,
  149460. 4,
  149461. 6,
  149462. 3,
  149463. 7,
  149464. 2,
  149465. 8,
  149466. 1,
  149467. 9,
  149468. 0,
  149469. 10,
  149470. };
  149471. static long _vq_lengthlist__44u5__p7_1[] = {
  149472. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149473. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149474. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149475. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149476. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149477. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149478. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149479. 9, 9, 9, 9, 9,10,10,10,10,
  149480. };
  149481. static float _vq_quantthresh__44u5__p7_1[] = {
  149482. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149483. 3.5, 4.5,
  149484. };
  149485. static long _vq_quantmap__44u5__p7_1[] = {
  149486. 9, 7, 5, 3, 1, 0, 2, 4,
  149487. 6, 8, 10,
  149488. };
  149489. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149490. _vq_quantthresh__44u5__p7_1,
  149491. _vq_quantmap__44u5__p7_1,
  149492. 11,
  149493. 11
  149494. };
  149495. static static_codebook _44u5__p7_1 = {
  149496. 2, 121,
  149497. _vq_lengthlist__44u5__p7_1,
  149498. 1, -531365888, 1611661312, 4, 0,
  149499. _vq_quantlist__44u5__p7_1,
  149500. NULL,
  149501. &_vq_auxt__44u5__p7_1,
  149502. NULL,
  149503. 0
  149504. };
  149505. static long _vq_quantlist__44u5__p8_0[] = {
  149506. 5,
  149507. 4,
  149508. 6,
  149509. 3,
  149510. 7,
  149511. 2,
  149512. 8,
  149513. 1,
  149514. 9,
  149515. 0,
  149516. 10,
  149517. };
  149518. static long _vq_lengthlist__44u5__p8_0[] = {
  149519. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149520. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149521. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149522. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149523. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149524. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149525. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149526. 12,13,13,14,14,14,14,15,15,
  149527. };
  149528. static float _vq_quantthresh__44u5__p8_0[] = {
  149529. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149530. 38.5, 49.5,
  149531. };
  149532. static long _vq_quantmap__44u5__p8_0[] = {
  149533. 9, 7, 5, 3, 1, 0, 2, 4,
  149534. 6, 8, 10,
  149535. };
  149536. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149537. _vq_quantthresh__44u5__p8_0,
  149538. _vq_quantmap__44u5__p8_0,
  149539. 11,
  149540. 11
  149541. };
  149542. static static_codebook _44u5__p8_0 = {
  149543. 2, 121,
  149544. _vq_lengthlist__44u5__p8_0,
  149545. 1, -524582912, 1618345984, 4, 0,
  149546. _vq_quantlist__44u5__p8_0,
  149547. NULL,
  149548. &_vq_auxt__44u5__p8_0,
  149549. NULL,
  149550. 0
  149551. };
  149552. static long _vq_quantlist__44u5__p8_1[] = {
  149553. 5,
  149554. 4,
  149555. 6,
  149556. 3,
  149557. 7,
  149558. 2,
  149559. 8,
  149560. 1,
  149561. 9,
  149562. 0,
  149563. 10,
  149564. };
  149565. static long _vq_lengthlist__44u5__p8_1[] = {
  149566. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  149567. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  149568. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  149569. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  149570. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  149571. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  149572. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149573. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  149574. };
  149575. static float _vq_quantthresh__44u5__p8_1[] = {
  149576. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149577. 3.5, 4.5,
  149578. };
  149579. static long _vq_quantmap__44u5__p8_1[] = {
  149580. 9, 7, 5, 3, 1, 0, 2, 4,
  149581. 6, 8, 10,
  149582. };
  149583. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  149584. _vq_quantthresh__44u5__p8_1,
  149585. _vq_quantmap__44u5__p8_1,
  149586. 11,
  149587. 11
  149588. };
  149589. static static_codebook _44u5__p8_1 = {
  149590. 2, 121,
  149591. _vq_lengthlist__44u5__p8_1,
  149592. 1, -531365888, 1611661312, 4, 0,
  149593. _vq_quantlist__44u5__p8_1,
  149594. NULL,
  149595. &_vq_auxt__44u5__p8_1,
  149596. NULL,
  149597. 0
  149598. };
  149599. static long _vq_quantlist__44u5__p9_0[] = {
  149600. 6,
  149601. 5,
  149602. 7,
  149603. 4,
  149604. 8,
  149605. 3,
  149606. 9,
  149607. 2,
  149608. 10,
  149609. 1,
  149610. 11,
  149611. 0,
  149612. 12,
  149613. };
  149614. static long _vq_lengthlist__44u5__p9_0[] = {
  149615. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  149616. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  149617. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  149618. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  149619. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149620. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149621. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149622. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  149623. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  149624. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149625. 12,12,12,12,12,12,12,12,12,
  149626. };
  149627. static float _vq_quantthresh__44u5__p9_0[] = {
  149628. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149629. 637.5, 892.5, 1147.5, 1402.5,
  149630. };
  149631. static long _vq_quantmap__44u5__p9_0[] = {
  149632. 11, 9, 7, 5, 3, 1, 0, 2,
  149633. 4, 6, 8, 10, 12,
  149634. };
  149635. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  149636. _vq_quantthresh__44u5__p9_0,
  149637. _vq_quantmap__44u5__p9_0,
  149638. 13,
  149639. 13
  149640. };
  149641. static static_codebook _44u5__p9_0 = {
  149642. 2, 169,
  149643. _vq_lengthlist__44u5__p9_0,
  149644. 1, -514332672, 1627381760, 4, 0,
  149645. _vq_quantlist__44u5__p9_0,
  149646. NULL,
  149647. &_vq_auxt__44u5__p9_0,
  149648. NULL,
  149649. 0
  149650. };
  149651. static long _vq_quantlist__44u5__p9_1[] = {
  149652. 7,
  149653. 6,
  149654. 8,
  149655. 5,
  149656. 9,
  149657. 4,
  149658. 10,
  149659. 3,
  149660. 11,
  149661. 2,
  149662. 12,
  149663. 1,
  149664. 13,
  149665. 0,
  149666. 14,
  149667. };
  149668. static long _vq_lengthlist__44u5__p9_1[] = {
  149669. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  149670. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  149671. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  149672. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  149673. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  149674. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  149675. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  149676. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  149677. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  149678. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  149679. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  149680. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  149681. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  149682. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  149683. 14,
  149684. };
  149685. static float _vq_quantthresh__44u5__p9_1[] = {
  149686. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149687. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149688. };
  149689. static long _vq_quantmap__44u5__p9_1[] = {
  149690. 13, 11, 9, 7, 5, 3, 1, 0,
  149691. 2, 4, 6, 8, 10, 12, 14,
  149692. };
  149693. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  149694. _vq_quantthresh__44u5__p9_1,
  149695. _vq_quantmap__44u5__p9_1,
  149696. 15,
  149697. 15
  149698. };
  149699. static static_codebook _44u5__p9_1 = {
  149700. 2, 225,
  149701. _vq_lengthlist__44u5__p9_1,
  149702. 1, -522338304, 1620115456, 4, 0,
  149703. _vq_quantlist__44u5__p9_1,
  149704. NULL,
  149705. &_vq_auxt__44u5__p9_1,
  149706. NULL,
  149707. 0
  149708. };
  149709. static long _vq_quantlist__44u5__p9_2[] = {
  149710. 8,
  149711. 7,
  149712. 9,
  149713. 6,
  149714. 10,
  149715. 5,
  149716. 11,
  149717. 4,
  149718. 12,
  149719. 3,
  149720. 13,
  149721. 2,
  149722. 14,
  149723. 1,
  149724. 15,
  149725. 0,
  149726. 16,
  149727. };
  149728. static long _vq_lengthlist__44u5__p9_2[] = {
  149729. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149730. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149731. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149732. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149733. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149734. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  149735. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  149736. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  149737. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149738. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  149739. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  149740. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  149741. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149742. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  149743. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149744. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149745. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  149746. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  149747. 10,
  149748. };
  149749. static float _vq_quantthresh__44u5__p9_2[] = {
  149750. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149751. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149752. };
  149753. static long _vq_quantmap__44u5__p9_2[] = {
  149754. 15, 13, 11, 9, 7, 5, 3, 1,
  149755. 0, 2, 4, 6, 8, 10, 12, 14,
  149756. 16,
  149757. };
  149758. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  149759. _vq_quantthresh__44u5__p9_2,
  149760. _vq_quantmap__44u5__p9_2,
  149761. 17,
  149762. 17
  149763. };
  149764. static static_codebook _44u5__p9_2 = {
  149765. 2, 289,
  149766. _vq_lengthlist__44u5__p9_2,
  149767. 1, -529530880, 1611661312, 5, 0,
  149768. _vq_quantlist__44u5__p9_2,
  149769. NULL,
  149770. &_vq_auxt__44u5__p9_2,
  149771. NULL,
  149772. 0
  149773. };
  149774. static long _huff_lengthlist__44u5__short[] = {
  149775. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  149776. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  149777. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  149778. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  149779. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  149780. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  149781. 6, 8,15,17,
  149782. };
  149783. static static_codebook _huff_book__44u5__short = {
  149784. 2, 100,
  149785. _huff_lengthlist__44u5__short,
  149786. 0, 0, 0, 0, 0,
  149787. NULL,
  149788. NULL,
  149789. NULL,
  149790. NULL,
  149791. 0
  149792. };
  149793. static long _huff_lengthlist__44u6__long[] = {
  149794. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  149795. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  149796. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  149797. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  149798. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  149799. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  149800. 13, 8, 7, 7,
  149801. };
  149802. static static_codebook _huff_book__44u6__long = {
  149803. 2, 100,
  149804. _huff_lengthlist__44u6__long,
  149805. 0, 0, 0, 0, 0,
  149806. NULL,
  149807. NULL,
  149808. NULL,
  149809. NULL,
  149810. 0
  149811. };
  149812. static long _vq_quantlist__44u6__p1_0[] = {
  149813. 1,
  149814. 0,
  149815. 2,
  149816. };
  149817. static long _vq_lengthlist__44u6__p1_0[] = {
  149818. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149819. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149820. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149821. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  149822. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149823. 12,
  149824. };
  149825. static float _vq_quantthresh__44u6__p1_0[] = {
  149826. -0.5, 0.5,
  149827. };
  149828. static long _vq_quantmap__44u6__p1_0[] = {
  149829. 1, 0, 2,
  149830. };
  149831. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  149832. _vq_quantthresh__44u6__p1_0,
  149833. _vq_quantmap__44u6__p1_0,
  149834. 3,
  149835. 3
  149836. };
  149837. static static_codebook _44u6__p1_0 = {
  149838. 4, 81,
  149839. _vq_lengthlist__44u6__p1_0,
  149840. 1, -535822336, 1611661312, 2, 0,
  149841. _vq_quantlist__44u6__p1_0,
  149842. NULL,
  149843. &_vq_auxt__44u6__p1_0,
  149844. NULL,
  149845. 0
  149846. };
  149847. static long _vq_quantlist__44u6__p2_0[] = {
  149848. 1,
  149849. 0,
  149850. 2,
  149851. };
  149852. static long _vq_lengthlist__44u6__p2_0[] = {
  149853. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149854. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149855. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  149856. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149857. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149858. 9,
  149859. };
  149860. static float _vq_quantthresh__44u6__p2_0[] = {
  149861. -0.5, 0.5,
  149862. };
  149863. static long _vq_quantmap__44u6__p2_0[] = {
  149864. 1, 0, 2,
  149865. };
  149866. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  149867. _vq_quantthresh__44u6__p2_0,
  149868. _vq_quantmap__44u6__p2_0,
  149869. 3,
  149870. 3
  149871. };
  149872. static static_codebook _44u6__p2_0 = {
  149873. 4, 81,
  149874. _vq_lengthlist__44u6__p2_0,
  149875. 1, -535822336, 1611661312, 2, 0,
  149876. _vq_quantlist__44u6__p2_0,
  149877. NULL,
  149878. &_vq_auxt__44u6__p2_0,
  149879. NULL,
  149880. 0
  149881. };
  149882. static long _vq_quantlist__44u6__p3_0[] = {
  149883. 2,
  149884. 1,
  149885. 3,
  149886. 0,
  149887. 4,
  149888. };
  149889. static long _vq_lengthlist__44u6__p3_0[] = {
  149890. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149891. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  149892. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149893. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  149894. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  149895. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  149896. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  149897. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  149898. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  149899. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149900. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  149901. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149902. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  149903. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  149904. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  149905. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  149906. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149907. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  149908. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  149909. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  149910. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  149911. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  149912. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  149913. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  149914. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  149915. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  149916. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  149917. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  149918. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  149919. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  149920. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  149921. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  149922. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  149923. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  149924. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  149925. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  149926. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  149927. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  149928. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  149929. 19,
  149930. };
  149931. static float _vq_quantthresh__44u6__p3_0[] = {
  149932. -1.5, -0.5, 0.5, 1.5,
  149933. };
  149934. static long _vq_quantmap__44u6__p3_0[] = {
  149935. 3, 1, 0, 2, 4,
  149936. };
  149937. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  149938. _vq_quantthresh__44u6__p3_0,
  149939. _vq_quantmap__44u6__p3_0,
  149940. 5,
  149941. 5
  149942. };
  149943. static static_codebook _44u6__p3_0 = {
  149944. 4, 625,
  149945. _vq_lengthlist__44u6__p3_0,
  149946. 1, -533725184, 1611661312, 3, 0,
  149947. _vq_quantlist__44u6__p3_0,
  149948. NULL,
  149949. &_vq_auxt__44u6__p3_0,
  149950. NULL,
  149951. 0
  149952. };
  149953. static long _vq_quantlist__44u6__p4_0[] = {
  149954. 2,
  149955. 1,
  149956. 3,
  149957. 0,
  149958. 4,
  149959. };
  149960. static long _vq_lengthlist__44u6__p4_0[] = {
  149961. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149962. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149963. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  149964. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  149965. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  149966. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  149967. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149968. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  149969. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  149970. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  149971. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  149972. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  149973. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149974. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  149975. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  149976. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  149977. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  149978. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  149979. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149980. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  149981. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  149982. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  149983. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  149984. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  149985. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  149986. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  149987. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  149988. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  149989. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  149990. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  149991. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  149992. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  149993. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  149994. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  149995. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  149996. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  149997. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  149998. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  149999. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  150000. 13,
  150001. };
  150002. static float _vq_quantthresh__44u6__p4_0[] = {
  150003. -1.5, -0.5, 0.5, 1.5,
  150004. };
  150005. static long _vq_quantmap__44u6__p4_0[] = {
  150006. 3, 1, 0, 2, 4,
  150007. };
  150008. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  150009. _vq_quantthresh__44u6__p4_0,
  150010. _vq_quantmap__44u6__p4_0,
  150011. 5,
  150012. 5
  150013. };
  150014. static static_codebook _44u6__p4_0 = {
  150015. 4, 625,
  150016. _vq_lengthlist__44u6__p4_0,
  150017. 1, -533725184, 1611661312, 3, 0,
  150018. _vq_quantlist__44u6__p4_0,
  150019. NULL,
  150020. &_vq_auxt__44u6__p4_0,
  150021. NULL,
  150022. 0
  150023. };
  150024. static long _vq_quantlist__44u6__p5_0[] = {
  150025. 4,
  150026. 3,
  150027. 5,
  150028. 2,
  150029. 6,
  150030. 1,
  150031. 7,
  150032. 0,
  150033. 8,
  150034. };
  150035. static long _vq_lengthlist__44u6__p5_0[] = {
  150036. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150037. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  150038. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  150039. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  150040. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150041. 14,
  150042. };
  150043. static float _vq_quantthresh__44u6__p5_0[] = {
  150044. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150045. };
  150046. static long _vq_quantmap__44u6__p5_0[] = {
  150047. 7, 5, 3, 1, 0, 2, 4, 6,
  150048. 8,
  150049. };
  150050. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150051. _vq_quantthresh__44u6__p5_0,
  150052. _vq_quantmap__44u6__p5_0,
  150053. 9,
  150054. 9
  150055. };
  150056. static static_codebook _44u6__p5_0 = {
  150057. 2, 81,
  150058. _vq_lengthlist__44u6__p5_0,
  150059. 1, -531628032, 1611661312, 4, 0,
  150060. _vq_quantlist__44u6__p5_0,
  150061. NULL,
  150062. &_vq_auxt__44u6__p5_0,
  150063. NULL,
  150064. 0
  150065. };
  150066. static long _vq_quantlist__44u6__p6_0[] = {
  150067. 4,
  150068. 3,
  150069. 5,
  150070. 2,
  150071. 6,
  150072. 1,
  150073. 7,
  150074. 0,
  150075. 8,
  150076. };
  150077. static long _vq_lengthlist__44u6__p6_0[] = {
  150078. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150079. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150080. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150081. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150082. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150083. 12,
  150084. };
  150085. static float _vq_quantthresh__44u6__p6_0[] = {
  150086. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150087. };
  150088. static long _vq_quantmap__44u6__p6_0[] = {
  150089. 7, 5, 3, 1, 0, 2, 4, 6,
  150090. 8,
  150091. };
  150092. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150093. _vq_quantthresh__44u6__p6_0,
  150094. _vq_quantmap__44u6__p6_0,
  150095. 9,
  150096. 9
  150097. };
  150098. static static_codebook _44u6__p6_0 = {
  150099. 2, 81,
  150100. _vq_lengthlist__44u6__p6_0,
  150101. 1, -531628032, 1611661312, 4, 0,
  150102. _vq_quantlist__44u6__p6_0,
  150103. NULL,
  150104. &_vq_auxt__44u6__p6_0,
  150105. NULL,
  150106. 0
  150107. };
  150108. static long _vq_quantlist__44u6__p7_0[] = {
  150109. 1,
  150110. 0,
  150111. 2,
  150112. };
  150113. static long _vq_lengthlist__44u6__p7_0[] = {
  150114. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150115. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150116. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150117. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150118. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150119. 10,
  150120. };
  150121. static float _vq_quantthresh__44u6__p7_0[] = {
  150122. -5.5, 5.5,
  150123. };
  150124. static long _vq_quantmap__44u6__p7_0[] = {
  150125. 1, 0, 2,
  150126. };
  150127. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150128. _vq_quantthresh__44u6__p7_0,
  150129. _vq_quantmap__44u6__p7_0,
  150130. 3,
  150131. 3
  150132. };
  150133. static static_codebook _44u6__p7_0 = {
  150134. 4, 81,
  150135. _vq_lengthlist__44u6__p7_0,
  150136. 1, -529137664, 1618345984, 2, 0,
  150137. _vq_quantlist__44u6__p7_0,
  150138. NULL,
  150139. &_vq_auxt__44u6__p7_0,
  150140. NULL,
  150141. 0
  150142. };
  150143. static long _vq_quantlist__44u6__p7_1[] = {
  150144. 5,
  150145. 4,
  150146. 6,
  150147. 3,
  150148. 7,
  150149. 2,
  150150. 8,
  150151. 1,
  150152. 9,
  150153. 0,
  150154. 10,
  150155. };
  150156. static long _vq_lengthlist__44u6__p7_1[] = {
  150157. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150158. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150159. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150160. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150161. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150162. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150163. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150164. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150165. };
  150166. static float _vq_quantthresh__44u6__p7_1[] = {
  150167. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150168. 3.5, 4.5,
  150169. };
  150170. static long _vq_quantmap__44u6__p7_1[] = {
  150171. 9, 7, 5, 3, 1, 0, 2, 4,
  150172. 6, 8, 10,
  150173. };
  150174. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150175. _vq_quantthresh__44u6__p7_1,
  150176. _vq_quantmap__44u6__p7_1,
  150177. 11,
  150178. 11
  150179. };
  150180. static static_codebook _44u6__p7_1 = {
  150181. 2, 121,
  150182. _vq_lengthlist__44u6__p7_1,
  150183. 1, -531365888, 1611661312, 4, 0,
  150184. _vq_quantlist__44u6__p7_1,
  150185. NULL,
  150186. &_vq_auxt__44u6__p7_1,
  150187. NULL,
  150188. 0
  150189. };
  150190. static long _vq_quantlist__44u6__p8_0[] = {
  150191. 5,
  150192. 4,
  150193. 6,
  150194. 3,
  150195. 7,
  150196. 2,
  150197. 8,
  150198. 1,
  150199. 9,
  150200. 0,
  150201. 10,
  150202. };
  150203. static long _vq_lengthlist__44u6__p8_0[] = {
  150204. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150205. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150206. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150207. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150208. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150209. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150210. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150211. 12,13,13,14,14,14,15,15,15,
  150212. };
  150213. static float _vq_quantthresh__44u6__p8_0[] = {
  150214. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150215. 38.5, 49.5,
  150216. };
  150217. static long _vq_quantmap__44u6__p8_0[] = {
  150218. 9, 7, 5, 3, 1, 0, 2, 4,
  150219. 6, 8, 10,
  150220. };
  150221. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150222. _vq_quantthresh__44u6__p8_0,
  150223. _vq_quantmap__44u6__p8_0,
  150224. 11,
  150225. 11
  150226. };
  150227. static static_codebook _44u6__p8_0 = {
  150228. 2, 121,
  150229. _vq_lengthlist__44u6__p8_0,
  150230. 1, -524582912, 1618345984, 4, 0,
  150231. _vq_quantlist__44u6__p8_0,
  150232. NULL,
  150233. &_vq_auxt__44u6__p8_0,
  150234. NULL,
  150235. 0
  150236. };
  150237. static long _vq_quantlist__44u6__p8_1[] = {
  150238. 5,
  150239. 4,
  150240. 6,
  150241. 3,
  150242. 7,
  150243. 2,
  150244. 8,
  150245. 1,
  150246. 9,
  150247. 0,
  150248. 10,
  150249. };
  150250. static long _vq_lengthlist__44u6__p8_1[] = {
  150251. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150252. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150253. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150254. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150255. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150256. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150257. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150258. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150259. };
  150260. static float _vq_quantthresh__44u6__p8_1[] = {
  150261. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150262. 3.5, 4.5,
  150263. };
  150264. static long _vq_quantmap__44u6__p8_1[] = {
  150265. 9, 7, 5, 3, 1, 0, 2, 4,
  150266. 6, 8, 10,
  150267. };
  150268. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150269. _vq_quantthresh__44u6__p8_1,
  150270. _vq_quantmap__44u6__p8_1,
  150271. 11,
  150272. 11
  150273. };
  150274. static static_codebook _44u6__p8_1 = {
  150275. 2, 121,
  150276. _vq_lengthlist__44u6__p8_1,
  150277. 1, -531365888, 1611661312, 4, 0,
  150278. _vq_quantlist__44u6__p8_1,
  150279. NULL,
  150280. &_vq_auxt__44u6__p8_1,
  150281. NULL,
  150282. 0
  150283. };
  150284. static long _vq_quantlist__44u6__p9_0[] = {
  150285. 7,
  150286. 6,
  150287. 8,
  150288. 5,
  150289. 9,
  150290. 4,
  150291. 10,
  150292. 3,
  150293. 11,
  150294. 2,
  150295. 12,
  150296. 1,
  150297. 13,
  150298. 0,
  150299. 14,
  150300. };
  150301. static long _vq_lengthlist__44u6__p9_0[] = {
  150302. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150303. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150304. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150305. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150306. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150307. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150308. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150309. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150310. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150311. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150312. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150313. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150314. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150315. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150316. 14,
  150317. };
  150318. static float _vq_quantthresh__44u6__p9_0[] = {
  150319. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150320. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150321. };
  150322. static long _vq_quantmap__44u6__p9_0[] = {
  150323. 13, 11, 9, 7, 5, 3, 1, 0,
  150324. 2, 4, 6, 8, 10, 12, 14,
  150325. };
  150326. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150327. _vq_quantthresh__44u6__p9_0,
  150328. _vq_quantmap__44u6__p9_0,
  150329. 15,
  150330. 15
  150331. };
  150332. static static_codebook _44u6__p9_0 = {
  150333. 2, 225,
  150334. _vq_lengthlist__44u6__p9_0,
  150335. 1, -514071552, 1627381760, 4, 0,
  150336. _vq_quantlist__44u6__p9_0,
  150337. NULL,
  150338. &_vq_auxt__44u6__p9_0,
  150339. NULL,
  150340. 0
  150341. };
  150342. static long _vq_quantlist__44u6__p9_1[] = {
  150343. 7,
  150344. 6,
  150345. 8,
  150346. 5,
  150347. 9,
  150348. 4,
  150349. 10,
  150350. 3,
  150351. 11,
  150352. 2,
  150353. 12,
  150354. 1,
  150355. 13,
  150356. 0,
  150357. 14,
  150358. };
  150359. static long _vq_lengthlist__44u6__p9_1[] = {
  150360. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150361. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150362. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150363. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150364. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150365. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150366. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150367. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150368. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150369. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150370. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150371. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150372. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150373. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150374. 13,
  150375. };
  150376. static float _vq_quantthresh__44u6__p9_1[] = {
  150377. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150378. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150379. };
  150380. static long _vq_quantmap__44u6__p9_1[] = {
  150381. 13, 11, 9, 7, 5, 3, 1, 0,
  150382. 2, 4, 6, 8, 10, 12, 14,
  150383. };
  150384. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150385. _vq_quantthresh__44u6__p9_1,
  150386. _vq_quantmap__44u6__p9_1,
  150387. 15,
  150388. 15
  150389. };
  150390. static static_codebook _44u6__p9_1 = {
  150391. 2, 225,
  150392. _vq_lengthlist__44u6__p9_1,
  150393. 1, -522338304, 1620115456, 4, 0,
  150394. _vq_quantlist__44u6__p9_1,
  150395. NULL,
  150396. &_vq_auxt__44u6__p9_1,
  150397. NULL,
  150398. 0
  150399. };
  150400. static long _vq_quantlist__44u6__p9_2[] = {
  150401. 8,
  150402. 7,
  150403. 9,
  150404. 6,
  150405. 10,
  150406. 5,
  150407. 11,
  150408. 4,
  150409. 12,
  150410. 3,
  150411. 13,
  150412. 2,
  150413. 14,
  150414. 1,
  150415. 15,
  150416. 0,
  150417. 16,
  150418. };
  150419. static long _vq_lengthlist__44u6__p9_2[] = {
  150420. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150421. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150422. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150423. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150424. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150425. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150426. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150427. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150428. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150429. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150430. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150431. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150432. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150433. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150434. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150435. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150436. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150437. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150438. 10,
  150439. };
  150440. static float _vq_quantthresh__44u6__p9_2[] = {
  150441. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150442. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150443. };
  150444. static long _vq_quantmap__44u6__p9_2[] = {
  150445. 15, 13, 11, 9, 7, 5, 3, 1,
  150446. 0, 2, 4, 6, 8, 10, 12, 14,
  150447. 16,
  150448. };
  150449. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150450. _vq_quantthresh__44u6__p9_2,
  150451. _vq_quantmap__44u6__p9_2,
  150452. 17,
  150453. 17
  150454. };
  150455. static static_codebook _44u6__p9_2 = {
  150456. 2, 289,
  150457. _vq_lengthlist__44u6__p9_2,
  150458. 1, -529530880, 1611661312, 5, 0,
  150459. _vq_quantlist__44u6__p9_2,
  150460. NULL,
  150461. &_vq_auxt__44u6__p9_2,
  150462. NULL,
  150463. 0
  150464. };
  150465. static long _huff_lengthlist__44u6__short[] = {
  150466. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150467. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150468. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150469. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150470. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150471. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150472. 7, 6, 9,16,
  150473. };
  150474. static static_codebook _huff_book__44u6__short = {
  150475. 2, 100,
  150476. _huff_lengthlist__44u6__short,
  150477. 0, 0, 0, 0, 0,
  150478. NULL,
  150479. NULL,
  150480. NULL,
  150481. NULL,
  150482. 0
  150483. };
  150484. static long _huff_lengthlist__44u7__long[] = {
  150485. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150486. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150487. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150488. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150489. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150490. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150491. 12, 8, 6, 7,
  150492. };
  150493. static static_codebook _huff_book__44u7__long = {
  150494. 2, 100,
  150495. _huff_lengthlist__44u7__long,
  150496. 0, 0, 0, 0, 0,
  150497. NULL,
  150498. NULL,
  150499. NULL,
  150500. NULL,
  150501. 0
  150502. };
  150503. static long _vq_quantlist__44u7__p1_0[] = {
  150504. 1,
  150505. 0,
  150506. 2,
  150507. };
  150508. static long _vq_lengthlist__44u7__p1_0[] = {
  150509. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150510. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150511. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150512. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150513. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150514. 12,
  150515. };
  150516. static float _vq_quantthresh__44u7__p1_0[] = {
  150517. -0.5, 0.5,
  150518. };
  150519. static long _vq_quantmap__44u7__p1_0[] = {
  150520. 1, 0, 2,
  150521. };
  150522. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150523. _vq_quantthresh__44u7__p1_0,
  150524. _vq_quantmap__44u7__p1_0,
  150525. 3,
  150526. 3
  150527. };
  150528. static static_codebook _44u7__p1_0 = {
  150529. 4, 81,
  150530. _vq_lengthlist__44u7__p1_0,
  150531. 1, -535822336, 1611661312, 2, 0,
  150532. _vq_quantlist__44u7__p1_0,
  150533. NULL,
  150534. &_vq_auxt__44u7__p1_0,
  150535. NULL,
  150536. 0
  150537. };
  150538. static long _vq_quantlist__44u7__p2_0[] = {
  150539. 1,
  150540. 0,
  150541. 2,
  150542. };
  150543. static long _vq_lengthlist__44u7__p2_0[] = {
  150544. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150545. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150546. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150547. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150548. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150549. 9,
  150550. };
  150551. static float _vq_quantthresh__44u7__p2_0[] = {
  150552. -0.5, 0.5,
  150553. };
  150554. static long _vq_quantmap__44u7__p2_0[] = {
  150555. 1, 0, 2,
  150556. };
  150557. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150558. _vq_quantthresh__44u7__p2_0,
  150559. _vq_quantmap__44u7__p2_0,
  150560. 3,
  150561. 3
  150562. };
  150563. static static_codebook _44u7__p2_0 = {
  150564. 4, 81,
  150565. _vq_lengthlist__44u7__p2_0,
  150566. 1, -535822336, 1611661312, 2, 0,
  150567. _vq_quantlist__44u7__p2_0,
  150568. NULL,
  150569. &_vq_auxt__44u7__p2_0,
  150570. NULL,
  150571. 0
  150572. };
  150573. static long _vq_quantlist__44u7__p3_0[] = {
  150574. 2,
  150575. 1,
  150576. 3,
  150577. 0,
  150578. 4,
  150579. };
  150580. static long _vq_lengthlist__44u7__p3_0[] = {
  150581. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150582. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150583. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150584. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  150585. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  150586. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  150587. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  150588. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  150589. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  150590. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  150591. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  150592. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  150593. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  150594. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  150595. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  150596. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  150597. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  150598. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150599. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  150600. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  150601. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  150602. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  150603. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  150604. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  150605. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  150606. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  150607. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  150608. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  150609. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  150610. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  150611. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  150612. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  150613. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  150614. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  150615. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  150616. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  150617. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  150618. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  150619. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  150620. 0,
  150621. };
  150622. static float _vq_quantthresh__44u7__p3_0[] = {
  150623. -1.5, -0.5, 0.5, 1.5,
  150624. };
  150625. static long _vq_quantmap__44u7__p3_0[] = {
  150626. 3, 1, 0, 2, 4,
  150627. };
  150628. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  150629. _vq_quantthresh__44u7__p3_0,
  150630. _vq_quantmap__44u7__p3_0,
  150631. 5,
  150632. 5
  150633. };
  150634. static static_codebook _44u7__p3_0 = {
  150635. 4, 625,
  150636. _vq_lengthlist__44u7__p3_0,
  150637. 1, -533725184, 1611661312, 3, 0,
  150638. _vq_quantlist__44u7__p3_0,
  150639. NULL,
  150640. &_vq_auxt__44u7__p3_0,
  150641. NULL,
  150642. 0
  150643. };
  150644. static long _vq_quantlist__44u7__p4_0[] = {
  150645. 2,
  150646. 1,
  150647. 3,
  150648. 0,
  150649. 4,
  150650. };
  150651. static long _vq_lengthlist__44u7__p4_0[] = {
  150652. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150653. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  150654. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  150655. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  150656. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150657. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  150658. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  150659. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  150660. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150661. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150662. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  150663. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150664. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150665. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  150666. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  150667. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150668. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  150669. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150670. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  150671. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  150672. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150673. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150674. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  150675. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150676. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  150677. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  150678. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150679. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  150680. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  150681. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  150682. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  150683. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150684. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  150685. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150686. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  150687. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150688. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  150689. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  150690. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  150691. 14,
  150692. };
  150693. static float _vq_quantthresh__44u7__p4_0[] = {
  150694. -1.5, -0.5, 0.5, 1.5,
  150695. };
  150696. static long _vq_quantmap__44u7__p4_0[] = {
  150697. 3, 1, 0, 2, 4,
  150698. };
  150699. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  150700. _vq_quantthresh__44u7__p4_0,
  150701. _vq_quantmap__44u7__p4_0,
  150702. 5,
  150703. 5
  150704. };
  150705. static static_codebook _44u7__p4_0 = {
  150706. 4, 625,
  150707. _vq_lengthlist__44u7__p4_0,
  150708. 1, -533725184, 1611661312, 3, 0,
  150709. _vq_quantlist__44u7__p4_0,
  150710. NULL,
  150711. &_vq_auxt__44u7__p4_0,
  150712. NULL,
  150713. 0
  150714. };
  150715. static long _vq_quantlist__44u7__p5_0[] = {
  150716. 4,
  150717. 3,
  150718. 5,
  150719. 2,
  150720. 6,
  150721. 1,
  150722. 7,
  150723. 0,
  150724. 8,
  150725. };
  150726. static long _vq_lengthlist__44u7__p5_0[] = {
  150727. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150728. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  150729. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  150730. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  150731. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  150732. 14,
  150733. };
  150734. static float _vq_quantthresh__44u7__p5_0[] = {
  150735. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150736. };
  150737. static long _vq_quantmap__44u7__p5_0[] = {
  150738. 7, 5, 3, 1, 0, 2, 4, 6,
  150739. 8,
  150740. };
  150741. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  150742. _vq_quantthresh__44u7__p5_0,
  150743. _vq_quantmap__44u7__p5_0,
  150744. 9,
  150745. 9
  150746. };
  150747. static static_codebook _44u7__p5_0 = {
  150748. 2, 81,
  150749. _vq_lengthlist__44u7__p5_0,
  150750. 1, -531628032, 1611661312, 4, 0,
  150751. _vq_quantlist__44u7__p5_0,
  150752. NULL,
  150753. &_vq_auxt__44u7__p5_0,
  150754. NULL,
  150755. 0
  150756. };
  150757. static long _vq_quantlist__44u7__p6_0[] = {
  150758. 4,
  150759. 3,
  150760. 5,
  150761. 2,
  150762. 6,
  150763. 1,
  150764. 7,
  150765. 0,
  150766. 8,
  150767. };
  150768. static long _vq_lengthlist__44u7__p6_0[] = {
  150769. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  150770. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  150771. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150772. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  150773. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  150774. 12,
  150775. };
  150776. static float _vq_quantthresh__44u7__p6_0[] = {
  150777. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150778. };
  150779. static long _vq_quantmap__44u7__p6_0[] = {
  150780. 7, 5, 3, 1, 0, 2, 4, 6,
  150781. 8,
  150782. };
  150783. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  150784. _vq_quantthresh__44u7__p6_0,
  150785. _vq_quantmap__44u7__p6_0,
  150786. 9,
  150787. 9
  150788. };
  150789. static static_codebook _44u7__p6_0 = {
  150790. 2, 81,
  150791. _vq_lengthlist__44u7__p6_0,
  150792. 1, -531628032, 1611661312, 4, 0,
  150793. _vq_quantlist__44u7__p6_0,
  150794. NULL,
  150795. &_vq_auxt__44u7__p6_0,
  150796. NULL,
  150797. 0
  150798. };
  150799. static long _vq_quantlist__44u7__p7_0[] = {
  150800. 1,
  150801. 0,
  150802. 2,
  150803. };
  150804. static long _vq_lengthlist__44u7__p7_0[] = {
  150805. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  150806. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  150807. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  150808. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  150809. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  150810. 10,
  150811. };
  150812. static float _vq_quantthresh__44u7__p7_0[] = {
  150813. -5.5, 5.5,
  150814. };
  150815. static long _vq_quantmap__44u7__p7_0[] = {
  150816. 1, 0, 2,
  150817. };
  150818. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  150819. _vq_quantthresh__44u7__p7_0,
  150820. _vq_quantmap__44u7__p7_0,
  150821. 3,
  150822. 3
  150823. };
  150824. static static_codebook _44u7__p7_0 = {
  150825. 4, 81,
  150826. _vq_lengthlist__44u7__p7_0,
  150827. 1, -529137664, 1618345984, 2, 0,
  150828. _vq_quantlist__44u7__p7_0,
  150829. NULL,
  150830. &_vq_auxt__44u7__p7_0,
  150831. NULL,
  150832. 0
  150833. };
  150834. static long _vq_quantlist__44u7__p7_1[] = {
  150835. 5,
  150836. 4,
  150837. 6,
  150838. 3,
  150839. 7,
  150840. 2,
  150841. 8,
  150842. 1,
  150843. 9,
  150844. 0,
  150845. 10,
  150846. };
  150847. static long _vq_lengthlist__44u7__p7_1[] = {
  150848. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  150849. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  150850. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  150851. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  150852. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  150853. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150854. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  150855. 8, 9, 9, 9, 9, 9,10,10,10,
  150856. };
  150857. static float _vq_quantthresh__44u7__p7_1[] = {
  150858. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150859. 3.5, 4.5,
  150860. };
  150861. static long _vq_quantmap__44u7__p7_1[] = {
  150862. 9, 7, 5, 3, 1, 0, 2, 4,
  150863. 6, 8, 10,
  150864. };
  150865. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  150866. _vq_quantthresh__44u7__p7_1,
  150867. _vq_quantmap__44u7__p7_1,
  150868. 11,
  150869. 11
  150870. };
  150871. static static_codebook _44u7__p7_1 = {
  150872. 2, 121,
  150873. _vq_lengthlist__44u7__p7_1,
  150874. 1, -531365888, 1611661312, 4, 0,
  150875. _vq_quantlist__44u7__p7_1,
  150876. NULL,
  150877. &_vq_auxt__44u7__p7_1,
  150878. NULL,
  150879. 0
  150880. };
  150881. static long _vq_quantlist__44u7__p8_0[] = {
  150882. 5,
  150883. 4,
  150884. 6,
  150885. 3,
  150886. 7,
  150887. 2,
  150888. 8,
  150889. 1,
  150890. 9,
  150891. 0,
  150892. 10,
  150893. };
  150894. static long _vq_lengthlist__44u7__p8_0[] = {
  150895. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  150896. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  150897. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  150898. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  150899. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  150900. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  150901. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  150902. 12,13,13,14,14,15,15,15,16,
  150903. };
  150904. static float _vq_quantthresh__44u7__p8_0[] = {
  150905. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150906. 38.5, 49.5,
  150907. };
  150908. static long _vq_quantmap__44u7__p8_0[] = {
  150909. 9, 7, 5, 3, 1, 0, 2, 4,
  150910. 6, 8, 10,
  150911. };
  150912. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  150913. _vq_quantthresh__44u7__p8_0,
  150914. _vq_quantmap__44u7__p8_0,
  150915. 11,
  150916. 11
  150917. };
  150918. static static_codebook _44u7__p8_0 = {
  150919. 2, 121,
  150920. _vq_lengthlist__44u7__p8_0,
  150921. 1, -524582912, 1618345984, 4, 0,
  150922. _vq_quantlist__44u7__p8_0,
  150923. NULL,
  150924. &_vq_auxt__44u7__p8_0,
  150925. NULL,
  150926. 0
  150927. };
  150928. static long _vq_quantlist__44u7__p8_1[] = {
  150929. 5,
  150930. 4,
  150931. 6,
  150932. 3,
  150933. 7,
  150934. 2,
  150935. 8,
  150936. 1,
  150937. 9,
  150938. 0,
  150939. 10,
  150940. };
  150941. static long _vq_lengthlist__44u7__p8_1[] = {
  150942. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  150943. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  150944. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  150945. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  150946. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  150947. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  150948. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  150949. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  150950. };
  150951. static float _vq_quantthresh__44u7__p8_1[] = {
  150952. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150953. 3.5, 4.5,
  150954. };
  150955. static long _vq_quantmap__44u7__p8_1[] = {
  150956. 9, 7, 5, 3, 1, 0, 2, 4,
  150957. 6, 8, 10,
  150958. };
  150959. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  150960. _vq_quantthresh__44u7__p8_1,
  150961. _vq_quantmap__44u7__p8_1,
  150962. 11,
  150963. 11
  150964. };
  150965. static static_codebook _44u7__p8_1 = {
  150966. 2, 121,
  150967. _vq_lengthlist__44u7__p8_1,
  150968. 1, -531365888, 1611661312, 4, 0,
  150969. _vq_quantlist__44u7__p8_1,
  150970. NULL,
  150971. &_vq_auxt__44u7__p8_1,
  150972. NULL,
  150973. 0
  150974. };
  150975. static long _vq_quantlist__44u7__p9_0[] = {
  150976. 5,
  150977. 4,
  150978. 6,
  150979. 3,
  150980. 7,
  150981. 2,
  150982. 8,
  150983. 1,
  150984. 9,
  150985. 0,
  150986. 10,
  150987. };
  150988. static long _vq_lengthlist__44u7__p9_0[] = {
  150989. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  150990. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  150991. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150992. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150993. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150994. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  150995. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150996. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150997. };
  150998. static float _vq_quantthresh__44u7__p9_0[] = {
  150999. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  151000. 2229.5, 2866.5,
  151001. };
  151002. static long _vq_quantmap__44u7__p9_0[] = {
  151003. 9, 7, 5, 3, 1, 0, 2, 4,
  151004. 6, 8, 10,
  151005. };
  151006. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  151007. _vq_quantthresh__44u7__p9_0,
  151008. _vq_quantmap__44u7__p9_0,
  151009. 11,
  151010. 11
  151011. };
  151012. static static_codebook _44u7__p9_0 = {
  151013. 2, 121,
  151014. _vq_lengthlist__44u7__p9_0,
  151015. 1, -512171520, 1630791680, 4, 0,
  151016. _vq_quantlist__44u7__p9_0,
  151017. NULL,
  151018. &_vq_auxt__44u7__p9_0,
  151019. NULL,
  151020. 0
  151021. };
  151022. static long _vq_quantlist__44u7__p9_1[] = {
  151023. 6,
  151024. 5,
  151025. 7,
  151026. 4,
  151027. 8,
  151028. 3,
  151029. 9,
  151030. 2,
  151031. 10,
  151032. 1,
  151033. 11,
  151034. 0,
  151035. 12,
  151036. };
  151037. static long _vq_lengthlist__44u7__p9_1[] = {
  151038. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  151039. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  151040. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151041. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151042. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151043. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151044. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151045. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151046. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151047. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151048. 15,15,15,15,17,17,16,17,16,
  151049. };
  151050. static float _vq_quantthresh__44u7__p9_1[] = {
  151051. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151052. 122.5, 171.5, 220.5, 269.5,
  151053. };
  151054. static long _vq_quantmap__44u7__p9_1[] = {
  151055. 11, 9, 7, 5, 3, 1, 0, 2,
  151056. 4, 6, 8, 10, 12,
  151057. };
  151058. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151059. _vq_quantthresh__44u7__p9_1,
  151060. _vq_quantmap__44u7__p9_1,
  151061. 13,
  151062. 13
  151063. };
  151064. static static_codebook _44u7__p9_1 = {
  151065. 2, 169,
  151066. _vq_lengthlist__44u7__p9_1,
  151067. 1, -518889472, 1622704128, 4, 0,
  151068. _vq_quantlist__44u7__p9_1,
  151069. NULL,
  151070. &_vq_auxt__44u7__p9_1,
  151071. NULL,
  151072. 0
  151073. };
  151074. static long _vq_quantlist__44u7__p9_2[] = {
  151075. 24,
  151076. 23,
  151077. 25,
  151078. 22,
  151079. 26,
  151080. 21,
  151081. 27,
  151082. 20,
  151083. 28,
  151084. 19,
  151085. 29,
  151086. 18,
  151087. 30,
  151088. 17,
  151089. 31,
  151090. 16,
  151091. 32,
  151092. 15,
  151093. 33,
  151094. 14,
  151095. 34,
  151096. 13,
  151097. 35,
  151098. 12,
  151099. 36,
  151100. 11,
  151101. 37,
  151102. 10,
  151103. 38,
  151104. 9,
  151105. 39,
  151106. 8,
  151107. 40,
  151108. 7,
  151109. 41,
  151110. 6,
  151111. 42,
  151112. 5,
  151113. 43,
  151114. 4,
  151115. 44,
  151116. 3,
  151117. 45,
  151118. 2,
  151119. 46,
  151120. 1,
  151121. 47,
  151122. 0,
  151123. 48,
  151124. };
  151125. static long _vq_lengthlist__44u7__p9_2[] = {
  151126. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151127. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151128. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151129. 8,
  151130. };
  151131. static float _vq_quantthresh__44u7__p9_2[] = {
  151132. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151133. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151134. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151135. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151136. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151137. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151138. };
  151139. static long _vq_quantmap__44u7__p9_2[] = {
  151140. 47, 45, 43, 41, 39, 37, 35, 33,
  151141. 31, 29, 27, 25, 23, 21, 19, 17,
  151142. 15, 13, 11, 9, 7, 5, 3, 1,
  151143. 0, 2, 4, 6, 8, 10, 12, 14,
  151144. 16, 18, 20, 22, 24, 26, 28, 30,
  151145. 32, 34, 36, 38, 40, 42, 44, 46,
  151146. 48,
  151147. };
  151148. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151149. _vq_quantthresh__44u7__p9_2,
  151150. _vq_quantmap__44u7__p9_2,
  151151. 49,
  151152. 49
  151153. };
  151154. static static_codebook _44u7__p9_2 = {
  151155. 1, 49,
  151156. _vq_lengthlist__44u7__p9_2,
  151157. 1, -526909440, 1611661312, 6, 0,
  151158. _vq_quantlist__44u7__p9_2,
  151159. NULL,
  151160. &_vq_auxt__44u7__p9_2,
  151161. NULL,
  151162. 0
  151163. };
  151164. static long _huff_lengthlist__44u7__short[] = {
  151165. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151166. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151167. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151168. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151169. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151170. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151171. 6, 8, 5, 9,
  151172. };
  151173. static static_codebook _huff_book__44u7__short = {
  151174. 2, 100,
  151175. _huff_lengthlist__44u7__short,
  151176. 0, 0, 0, 0, 0,
  151177. NULL,
  151178. NULL,
  151179. NULL,
  151180. NULL,
  151181. 0
  151182. };
  151183. static long _huff_lengthlist__44u8__long[] = {
  151184. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151185. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151186. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151187. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151188. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151189. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151190. 10, 8, 8, 9,
  151191. };
  151192. static static_codebook _huff_book__44u8__long = {
  151193. 2, 100,
  151194. _huff_lengthlist__44u8__long,
  151195. 0, 0, 0, 0, 0,
  151196. NULL,
  151197. NULL,
  151198. NULL,
  151199. NULL,
  151200. 0
  151201. };
  151202. static long _huff_lengthlist__44u8__short[] = {
  151203. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151204. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151205. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151206. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151207. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151208. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151209. 10,10,15,17,
  151210. };
  151211. static static_codebook _huff_book__44u8__short = {
  151212. 2, 100,
  151213. _huff_lengthlist__44u8__short,
  151214. 0, 0, 0, 0, 0,
  151215. NULL,
  151216. NULL,
  151217. NULL,
  151218. NULL,
  151219. 0
  151220. };
  151221. static long _vq_quantlist__44u8_p1_0[] = {
  151222. 1,
  151223. 0,
  151224. 2,
  151225. };
  151226. static long _vq_lengthlist__44u8_p1_0[] = {
  151227. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151228. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151229. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151230. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151231. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151232. 10,
  151233. };
  151234. static float _vq_quantthresh__44u8_p1_0[] = {
  151235. -0.5, 0.5,
  151236. };
  151237. static long _vq_quantmap__44u8_p1_0[] = {
  151238. 1, 0, 2,
  151239. };
  151240. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151241. _vq_quantthresh__44u8_p1_0,
  151242. _vq_quantmap__44u8_p1_0,
  151243. 3,
  151244. 3
  151245. };
  151246. static static_codebook _44u8_p1_0 = {
  151247. 4, 81,
  151248. _vq_lengthlist__44u8_p1_0,
  151249. 1, -535822336, 1611661312, 2, 0,
  151250. _vq_quantlist__44u8_p1_0,
  151251. NULL,
  151252. &_vq_auxt__44u8_p1_0,
  151253. NULL,
  151254. 0
  151255. };
  151256. static long _vq_quantlist__44u8_p2_0[] = {
  151257. 2,
  151258. 1,
  151259. 3,
  151260. 0,
  151261. 4,
  151262. };
  151263. static long _vq_lengthlist__44u8_p2_0[] = {
  151264. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151265. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151266. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151267. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151268. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151269. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151270. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151271. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151272. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151273. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151274. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151275. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151276. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151277. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151278. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151279. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151280. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151281. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151282. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151283. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151284. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151285. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151286. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151287. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151288. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151289. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151290. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151291. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151292. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151293. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151294. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151295. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151296. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151297. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151298. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151299. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151300. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151301. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151302. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151303. 14,
  151304. };
  151305. static float _vq_quantthresh__44u8_p2_0[] = {
  151306. -1.5, -0.5, 0.5, 1.5,
  151307. };
  151308. static long _vq_quantmap__44u8_p2_0[] = {
  151309. 3, 1, 0, 2, 4,
  151310. };
  151311. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151312. _vq_quantthresh__44u8_p2_0,
  151313. _vq_quantmap__44u8_p2_0,
  151314. 5,
  151315. 5
  151316. };
  151317. static static_codebook _44u8_p2_0 = {
  151318. 4, 625,
  151319. _vq_lengthlist__44u8_p2_0,
  151320. 1, -533725184, 1611661312, 3, 0,
  151321. _vq_quantlist__44u8_p2_0,
  151322. NULL,
  151323. &_vq_auxt__44u8_p2_0,
  151324. NULL,
  151325. 0
  151326. };
  151327. static long _vq_quantlist__44u8_p3_0[] = {
  151328. 4,
  151329. 3,
  151330. 5,
  151331. 2,
  151332. 6,
  151333. 1,
  151334. 7,
  151335. 0,
  151336. 8,
  151337. };
  151338. static long _vq_lengthlist__44u8_p3_0[] = {
  151339. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151340. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151341. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151342. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151343. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151344. 12,
  151345. };
  151346. static float _vq_quantthresh__44u8_p3_0[] = {
  151347. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151348. };
  151349. static long _vq_quantmap__44u8_p3_0[] = {
  151350. 7, 5, 3, 1, 0, 2, 4, 6,
  151351. 8,
  151352. };
  151353. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151354. _vq_quantthresh__44u8_p3_0,
  151355. _vq_quantmap__44u8_p3_0,
  151356. 9,
  151357. 9
  151358. };
  151359. static static_codebook _44u8_p3_0 = {
  151360. 2, 81,
  151361. _vq_lengthlist__44u8_p3_0,
  151362. 1, -531628032, 1611661312, 4, 0,
  151363. _vq_quantlist__44u8_p3_0,
  151364. NULL,
  151365. &_vq_auxt__44u8_p3_0,
  151366. NULL,
  151367. 0
  151368. };
  151369. static long _vq_quantlist__44u8_p4_0[] = {
  151370. 8,
  151371. 7,
  151372. 9,
  151373. 6,
  151374. 10,
  151375. 5,
  151376. 11,
  151377. 4,
  151378. 12,
  151379. 3,
  151380. 13,
  151381. 2,
  151382. 14,
  151383. 1,
  151384. 15,
  151385. 0,
  151386. 16,
  151387. };
  151388. static long _vq_lengthlist__44u8_p4_0[] = {
  151389. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151390. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151391. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151392. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151393. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151394. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151395. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151396. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151397. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151398. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151399. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151400. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151401. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151402. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151403. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151404. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151405. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151406. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151407. 14,
  151408. };
  151409. static float _vq_quantthresh__44u8_p4_0[] = {
  151410. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151411. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151412. };
  151413. static long _vq_quantmap__44u8_p4_0[] = {
  151414. 15, 13, 11, 9, 7, 5, 3, 1,
  151415. 0, 2, 4, 6, 8, 10, 12, 14,
  151416. 16,
  151417. };
  151418. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151419. _vq_quantthresh__44u8_p4_0,
  151420. _vq_quantmap__44u8_p4_0,
  151421. 17,
  151422. 17
  151423. };
  151424. static static_codebook _44u8_p4_0 = {
  151425. 2, 289,
  151426. _vq_lengthlist__44u8_p4_0,
  151427. 1, -529530880, 1611661312, 5, 0,
  151428. _vq_quantlist__44u8_p4_0,
  151429. NULL,
  151430. &_vq_auxt__44u8_p4_0,
  151431. NULL,
  151432. 0
  151433. };
  151434. static long _vq_quantlist__44u8_p5_0[] = {
  151435. 1,
  151436. 0,
  151437. 2,
  151438. };
  151439. static long _vq_lengthlist__44u8_p5_0[] = {
  151440. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151441. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151442. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151443. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151444. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151445. 10,
  151446. };
  151447. static float _vq_quantthresh__44u8_p5_0[] = {
  151448. -5.5, 5.5,
  151449. };
  151450. static long _vq_quantmap__44u8_p5_0[] = {
  151451. 1, 0, 2,
  151452. };
  151453. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151454. _vq_quantthresh__44u8_p5_0,
  151455. _vq_quantmap__44u8_p5_0,
  151456. 3,
  151457. 3
  151458. };
  151459. static static_codebook _44u8_p5_0 = {
  151460. 4, 81,
  151461. _vq_lengthlist__44u8_p5_0,
  151462. 1, -529137664, 1618345984, 2, 0,
  151463. _vq_quantlist__44u8_p5_0,
  151464. NULL,
  151465. &_vq_auxt__44u8_p5_0,
  151466. NULL,
  151467. 0
  151468. };
  151469. static long _vq_quantlist__44u8_p5_1[] = {
  151470. 5,
  151471. 4,
  151472. 6,
  151473. 3,
  151474. 7,
  151475. 2,
  151476. 8,
  151477. 1,
  151478. 9,
  151479. 0,
  151480. 10,
  151481. };
  151482. static long _vq_lengthlist__44u8_p5_1[] = {
  151483. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151484. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151485. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151486. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151487. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151488. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151489. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151490. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151491. };
  151492. static float _vq_quantthresh__44u8_p5_1[] = {
  151493. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151494. 3.5, 4.5,
  151495. };
  151496. static long _vq_quantmap__44u8_p5_1[] = {
  151497. 9, 7, 5, 3, 1, 0, 2, 4,
  151498. 6, 8, 10,
  151499. };
  151500. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151501. _vq_quantthresh__44u8_p5_1,
  151502. _vq_quantmap__44u8_p5_1,
  151503. 11,
  151504. 11
  151505. };
  151506. static static_codebook _44u8_p5_1 = {
  151507. 2, 121,
  151508. _vq_lengthlist__44u8_p5_1,
  151509. 1, -531365888, 1611661312, 4, 0,
  151510. _vq_quantlist__44u8_p5_1,
  151511. NULL,
  151512. &_vq_auxt__44u8_p5_1,
  151513. NULL,
  151514. 0
  151515. };
  151516. static long _vq_quantlist__44u8_p6_0[] = {
  151517. 6,
  151518. 5,
  151519. 7,
  151520. 4,
  151521. 8,
  151522. 3,
  151523. 9,
  151524. 2,
  151525. 10,
  151526. 1,
  151527. 11,
  151528. 0,
  151529. 12,
  151530. };
  151531. static long _vq_lengthlist__44u8_p6_0[] = {
  151532. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151533. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151534. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151535. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151536. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151537. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151538. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151539. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151540. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151541. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151542. 11,11,11,11,11,12,11,12,12,
  151543. };
  151544. static float _vq_quantthresh__44u8_p6_0[] = {
  151545. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151546. 12.5, 17.5, 22.5, 27.5,
  151547. };
  151548. static long _vq_quantmap__44u8_p6_0[] = {
  151549. 11, 9, 7, 5, 3, 1, 0, 2,
  151550. 4, 6, 8, 10, 12,
  151551. };
  151552. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151553. _vq_quantthresh__44u8_p6_0,
  151554. _vq_quantmap__44u8_p6_0,
  151555. 13,
  151556. 13
  151557. };
  151558. static static_codebook _44u8_p6_0 = {
  151559. 2, 169,
  151560. _vq_lengthlist__44u8_p6_0,
  151561. 1, -526516224, 1616117760, 4, 0,
  151562. _vq_quantlist__44u8_p6_0,
  151563. NULL,
  151564. &_vq_auxt__44u8_p6_0,
  151565. NULL,
  151566. 0
  151567. };
  151568. static long _vq_quantlist__44u8_p6_1[] = {
  151569. 2,
  151570. 1,
  151571. 3,
  151572. 0,
  151573. 4,
  151574. };
  151575. static long _vq_lengthlist__44u8_p6_1[] = {
  151576. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  151577. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  151578. };
  151579. static float _vq_quantthresh__44u8_p6_1[] = {
  151580. -1.5, -0.5, 0.5, 1.5,
  151581. };
  151582. static long _vq_quantmap__44u8_p6_1[] = {
  151583. 3, 1, 0, 2, 4,
  151584. };
  151585. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  151586. _vq_quantthresh__44u8_p6_1,
  151587. _vq_quantmap__44u8_p6_1,
  151588. 5,
  151589. 5
  151590. };
  151591. static static_codebook _44u8_p6_1 = {
  151592. 2, 25,
  151593. _vq_lengthlist__44u8_p6_1,
  151594. 1, -533725184, 1611661312, 3, 0,
  151595. _vq_quantlist__44u8_p6_1,
  151596. NULL,
  151597. &_vq_auxt__44u8_p6_1,
  151598. NULL,
  151599. 0
  151600. };
  151601. static long _vq_quantlist__44u8_p7_0[] = {
  151602. 6,
  151603. 5,
  151604. 7,
  151605. 4,
  151606. 8,
  151607. 3,
  151608. 9,
  151609. 2,
  151610. 10,
  151611. 1,
  151612. 11,
  151613. 0,
  151614. 12,
  151615. };
  151616. static long _vq_lengthlist__44u8_p7_0[] = {
  151617. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  151618. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  151619. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  151620. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  151621. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  151622. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  151623. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  151624. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  151625. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  151626. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  151627. 13,13,14,14,14,15,15,15,16,
  151628. };
  151629. static float _vq_quantthresh__44u8_p7_0[] = {
  151630. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  151631. 27.5, 38.5, 49.5, 60.5,
  151632. };
  151633. static long _vq_quantmap__44u8_p7_0[] = {
  151634. 11, 9, 7, 5, 3, 1, 0, 2,
  151635. 4, 6, 8, 10, 12,
  151636. };
  151637. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  151638. _vq_quantthresh__44u8_p7_0,
  151639. _vq_quantmap__44u8_p7_0,
  151640. 13,
  151641. 13
  151642. };
  151643. static static_codebook _44u8_p7_0 = {
  151644. 2, 169,
  151645. _vq_lengthlist__44u8_p7_0,
  151646. 1, -523206656, 1618345984, 4, 0,
  151647. _vq_quantlist__44u8_p7_0,
  151648. NULL,
  151649. &_vq_auxt__44u8_p7_0,
  151650. NULL,
  151651. 0
  151652. };
  151653. static long _vq_quantlist__44u8_p7_1[] = {
  151654. 5,
  151655. 4,
  151656. 6,
  151657. 3,
  151658. 7,
  151659. 2,
  151660. 8,
  151661. 1,
  151662. 9,
  151663. 0,
  151664. 10,
  151665. };
  151666. static long _vq_lengthlist__44u8_p7_1[] = {
  151667. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151668. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  151669. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151670. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  151671. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  151672. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151673. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151674. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151675. };
  151676. static float _vq_quantthresh__44u8_p7_1[] = {
  151677. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151678. 3.5, 4.5,
  151679. };
  151680. static long _vq_quantmap__44u8_p7_1[] = {
  151681. 9, 7, 5, 3, 1, 0, 2, 4,
  151682. 6, 8, 10,
  151683. };
  151684. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  151685. _vq_quantthresh__44u8_p7_1,
  151686. _vq_quantmap__44u8_p7_1,
  151687. 11,
  151688. 11
  151689. };
  151690. static static_codebook _44u8_p7_1 = {
  151691. 2, 121,
  151692. _vq_lengthlist__44u8_p7_1,
  151693. 1, -531365888, 1611661312, 4, 0,
  151694. _vq_quantlist__44u8_p7_1,
  151695. NULL,
  151696. &_vq_auxt__44u8_p7_1,
  151697. NULL,
  151698. 0
  151699. };
  151700. static long _vq_quantlist__44u8_p8_0[] = {
  151701. 7,
  151702. 6,
  151703. 8,
  151704. 5,
  151705. 9,
  151706. 4,
  151707. 10,
  151708. 3,
  151709. 11,
  151710. 2,
  151711. 12,
  151712. 1,
  151713. 13,
  151714. 0,
  151715. 14,
  151716. };
  151717. static long _vq_lengthlist__44u8_p8_0[] = {
  151718. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  151719. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  151720. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  151721. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  151722. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  151723. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  151724. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  151725. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  151726. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  151727. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  151728. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  151729. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  151730. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  151731. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  151732. 17,
  151733. };
  151734. static float _vq_quantthresh__44u8_p8_0[] = {
  151735. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  151736. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  151737. };
  151738. static long _vq_quantmap__44u8_p8_0[] = {
  151739. 13, 11, 9, 7, 5, 3, 1, 0,
  151740. 2, 4, 6, 8, 10, 12, 14,
  151741. };
  151742. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  151743. _vq_quantthresh__44u8_p8_0,
  151744. _vq_quantmap__44u8_p8_0,
  151745. 15,
  151746. 15
  151747. };
  151748. static static_codebook _44u8_p8_0 = {
  151749. 2, 225,
  151750. _vq_lengthlist__44u8_p8_0,
  151751. 1, -520986624, 1620377600, 4, 0,
  151752. _vq_quantlist__44u8_p8_0,
  151753. NULL,
  151754. &_vq_auxt__44u8_p8_0,
  151755. NULL,
  151756. 0
  151757. };
  151758. static long _vq_quantlist__44u8_p8_1[] = {
  151759. 10,
  151760. 9,
  151761. 11,
  151762. 8,
  151763. 12,
  151764. 7,
  151765. 13,
  151766. 6,
  151767. 14,
  151768. 5,
  151769. 15,
  151770. 4,
  151771. 16,
  151772. 3,
  151773. 17,
  151774. 2,
  151775. 18,
  151776. 1,
  151777. 19,
  151778. 0,
  151779. 20,
  151780. };
  151781. static long _vq_lengthlist__44u8_p8_1[] = {
  151782. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  151783. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  151784. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  151785. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  151786. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151787. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  151788. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  151789. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  151790. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151791. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151792. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  151793. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  151794. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151795. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  151796. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  151797. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  151798. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  151799. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  151800. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  151801. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  151802. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151803. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151804. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  151805. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  151806. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  151807. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  151808. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  151809. 10,10,10,10,10,10,10,10,10,
  151810. };
  151811. static float _vq_quantthresh__44u8_p8_1[] = {
  151812. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  151813. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  151814. 6.5, 7.5, 8.5, 9.5,
  151815. };
  151816. static long _vq_quantmap__44u8_p8_1[] = {
  151817. 19, 17, 15, 13, 11, 9, 7, 5,
  151818. 3, 1, 0, 2, 4, 6, 8, 10,
  151819. 12, 14, 16, 18, 20,
  151820. };
  151821. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  151822. _vq_quantthresh__44u8_p8_1,
  151823. _vq_quantmap__44u8_p8_1,
  151824. 21,
  151825. 21
  151826. };
  151827. static static_codebook _44u8_p8_1 = {
  151828. 2, 441,
  151829. _vq_lengthlist__44u8_p8_1,
  151830. 1, -529268736, 1611661312, 5, 0,
  151831. _vq_quantlist__44u8_p8_1,
  151832. NULL,
  151833. &_vq_auxt__44u8_p8_1,
  151834. NULL,
  151835. 0
  151836. };
  151837. static long _vq_quantlist__44u8_p9_0[] = {
  151838. 4,
  151839. 3,
  151840. 5,
  151841. 2,
  151842. 6,
  151843. 1,
  151844. 7,
  151845. 0,
  151846. 8,
  151847. };
  151848. static long _vq_lengthlist__44u8_p9_0[] = {
  151849. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  151850. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151851. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151852. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151853. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151854. 8,
  151855. };
  151856. static float _vq_quantthresh__44u8_p9_0[] = {
  151857. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  151858. };
  151859. static long _vq_quantmap__44u8_p9_0[] = {
  151860. 7, 5, 3, 1, 0, 2, 4, 6,
  151861. 8,
  151862. };
  151863. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  151864. _vq_quantthresh__44u8_p9_0,
  151865. _vq_quantmap__44u8_p9_0,
  151866. 9,
  151867. 9
  151868. };
  151869. static static_codebook _44u8_p9_0 = {
  151870. 2, 81,
  151871. _vq_lengthlist__44u8_p9_0,
  151872. 1, -511895552, 1631393792, 4, 0,
  151873. _vq_quantlist__44u8_p9_0,
  151874. NULL,
  151875. &_vq_auxt__44u8_p9_0,
  151876. NULL,
  151877. 0
  151878. };
  151879. static long _vq_quantlist__44u8_p9_1[] = {
  151880. 9,
  151881. 8,
  151882. 10,
  151883. 7,
  151884. 11,
  151885. 6,
  151886. 12,
  151887. 5,
  151888. 13,
  151889. 4,
  151890. 14,
  151891. 3,
  151892. 15,
  151893. 2,
  151894. 16,
  151895. 1,
  151896. 17,
  151897. 0,
  151898. 18,
  151899. };
  151900. static long _vq_lengthlist__44u8_p9_1[] = {
  151901. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  151902. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  151903. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  151904. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  151905. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  151906. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  151907. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  151908. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  151909. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  151910. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  151911. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  151912. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  151913. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  151914. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  151915. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  151916. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  151917. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  151918. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  151919. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  151920. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  151921. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  151922. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  151923. 16,15,16,16,16,16,16,16,16,
  151924. };
  151925. static float _vq_quantthresh__44u8_p9_1[] = {
  151926. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  151927. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  151928. 367.5, 416.5,
  151929. };
  151930. static long _vq_quantmap__44u8_p9_1[] = {
  151931. 17, 15, 13, 11, 9, 7, 5, 3,
  151932. 1, 0, 2, 4, 6, 8, 10, 12,
  151933. 14, 16, 18,
  151934. };
  151935. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  151936. _vq_quantthresh__44u8_p9_1,
  151937. _vq_quantmap__44u8_p9_1,
  151938. 19,
  151939. 19
  151940. };
  151941. static static_codebook _44u8_p9_1 = {
  151942. 2, 361,
  151943. _vq_lengthlist__44u8_p9_1,
  151944. 1, -518287360, 1622704128, 5, 0,
  151945. _vq_quantlist__44u8_p9_1,
  151946. NULL,
  151947. &_vq_auxt__44u8_p9_1,
  151948. NULL,
  151949. 0
  151950. };
  151951. static long _vq_quantlist__44u8_p9_2[] = {
  151952. 24,
  151953. 23,
  151954. 25,
  151955. 22,
  151956. 26,
  151957. 21,
  151958. 27,
  151959. 20,
  151960. 28,
  151961. 19,
  151962. 29,
  151963. 18,
  151964. 30,
  151965. 17,
  151966. 31,
  151967. 16,
  151968. 32,
  151969. 15,
  151970. 33,
  151971. 14,
  151972. 34,
  151973. 13,
  151974. 35,
  151975. 12,
  151976. 36,
  151977. 11,
  151978. 37,
  151979. 10,
  151980. 38,
  151981. 9,
  151982. 39,
  151983. 8,
  151984. 40,
  151985. 7,
  151986. 41,
  151987. 6,
  151988. 42,
  151989. 5,
  151990. 43,
  151991. 4,
  151992. 44,
  151993. 3,
  151994. 45,
  151995. 2,
  151996. 46,
  151997. 1,
  151998. 47,
  151999. 0,
  152000. 48,
  152001. };
  152002. static long _vq_lengthlist__44u8_p9_2[] = {
  152003. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  152004. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152005. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152006. 7,
  152007. };
  152008. static float _vq_quantthresh__44u8_p9_2[] = {
  152009. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152010. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152011. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152012. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152013. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152014. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152015. };
  152016. static long _vq_quantmap__44u8_p9_2[] = {
  152017. 47, 45, 43, 41, 39, 37, 35, 33,
  152018. 31, 29, 27, 25, 23, 21, 19, 17,
  152019. 15, 13, 11, 9, 7, 5, 3, 1,
  152020. 0, 2, 4, 6, 8, 10, 12, 14,
  152021. 16, 18, 20, 22, 24, 26, 28, 30,
  152022. 32, 34, 36, 38, 40, 42, 44, 46,
  152023. 48,
  152024. };
  152025. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  152026. _vq_quantthresh__44u8_p9_2,
  152027. _vq_quantmap__44u8_p9_2,
  152028. 49,
  152029. 49
  152030. };
  152031. static static_codebook _44u8_p9_2 = {
  152032. 1, 49,
  152033. _vq_lengthlist__44u8_p9_2,
  152034. 1, -526909440, 1611661312, 6, 0,
  152035. _vq_quantlist__44u8_p9_2,
  152036. NULL,
  152037. &_vq_auxt__44u8_p9_2,
  152038. NULL,
  152039. 0
  152040. };
  152041. static long _huff_lengthlist__44u9__long[] = {
  152042. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152043. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152044. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152045. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152046. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152047. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152048. 10, 8, 8, 9,
  152049. };
  152050. static static_codebook _huff_book__44u9__long = {
  152051. 2, 100,
  152052. _huff_lengthlist__44u9__long,
  152053. 0, 0, 0, 0, 0,
  152054. NULL,
  152055. NULL,
  152056. NULL,
  152057. NULL,
  152058. 0
  152059. };
  152060. static long _huff_lengthlist__44u9__short[] = {
  152061. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152062. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152063. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152064. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152065. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152066. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152067. 9, 9,12,15,
  152068. };
  152069. static static_codebook _huff_book__44u9__short = {
  152070. 2, 100,
  152071. _huff_lengthlist__44u9__short,
  152072. 0, 0, 0, 0, 0,
  152073. NULL,
  152074. NULL,
  152075. NULL,
  152076. NULL,
  152077. 0
  152078. };
  152079. static long _vq_quantlist__44u9_p1_0[] = {
  152080. 1,
  152081. 0,
  152082. 2,
  152083. };
  152084. static long _vq_lengthlist__44u9_p1_0[] = {
  152085. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152086. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152087. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152088. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152089. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152090. 10,
  152091. };
  152092. static float _vq_quantthresh__44u9_p1_0[] = {
  152093. -0.5, 0.5,
  152094. };
  152095. static long _vq_quantmap__44u9_p1_0[] = {
  152096. 1, 0, 2,
  152097. };
  152098. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152099. _vq_quantthresh__44u9_p1_0,
  152100. _vq_quantmap__44u9_p1_0,
  152101. 3,
  152102. 3
  152103. };
  152104. static static_codebook _44u9_p1_0 = {
  152105. 4, 81,
  152106. _vq_lengthlist__44u9_p1_0,
  152107. 1, -535822336, 1611661312, 2, 0,
  152108. _vq_quantlist__44u9_p1_0,
  152109. NULL,
  152110. &_vq_auxt__44u9_p1_0,
  152111. NULL,
  152112. 0
  152113. };
  152114. static long _vq_quantlist__44u9_p2_0[] = {
  152115. 2,
  152116. 1,
  152117. 3,
  152118. 0,
  152119. 4,
  152120. };
  152121. static long _vq_lengthlist__44u9_p2_0[] = {
  152122. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152123. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152124. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152125. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152126. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152127. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152128. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152129. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152130. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152131. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152132. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152133. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152134. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152135. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152136. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152137. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152138. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152139. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152140. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152141. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152142. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152143. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152144. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152145. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152146. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152147. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152148. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152149. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152150. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152151. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152152. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152153. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152154. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152155. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152156. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152157. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152158. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152159. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152160. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152161. 14,
  152162. };
  152163. static float _vq_quantthresh__44u9_p2_0[] = {
  152164. -1.5, -0.5, 0.5, 1.5,
  152165. };
  152166. static long _vq_quantmap__44u9_p2_0[] = {
  152167. 3, 1, 0, 2, 4,
  152168. };
  152169. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152170. _vq_quantthresh__44u9_p2_0,
  152171. _vq_quantmap__44u9_p2_0,
  152172. 5,
  152173. 5
  152174. };
  152175. static static_codebook _44u9_p2_0 = {
  152176. 4, 625,
  152177. _vq_lengthlist__44u9_p2_0,
  152178. 1, -533725184, 1611661312, 3, 0,
  152179. _vq_quantlist__44u9_p2_0,
  152180. NULL,
  152181. &_vq_auxt__44u9_p2_0,
  152182. NULL,
  152183. 0
  152184. };
  152185. static long _vq_quantlist__44u9_p3_0[] = {
  152186. 4,
  152187. 3,
  152188. 5,
  152189. 2,
  152190. 6,
  152191. 1,
  152192. 7,
  152193. 0,
  152194. 8,
  152195. };
  152196. static long _vq_lengthlist__44u9_p3_0[] = {
  152197. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152198. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152199. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152200. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152201. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152202. 11,
  152203. };
  152204. static float _vq_quantthresh__44u9_p3_0[] = {
  152205. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152206. };
  152207. static long _vq_quantmap__44u9_p3_0[] = {
  152208. 7, 5, 3, 1, 0, 2, 4, 6,
  152209. 8,
  152210. };
  152211. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152212. _vq_quantthresh__44u9_p3_0,
  152213. _vq_quantmap__44u9_p3_0,
  152214. 9,
  152215. 9
  152216. };
  152217. static static_codebook _44u9_p3_0 = {
  152218. 2, 81,
  152219. _vq_lengthlist__44u9_p3_0,
  152220. 1, -531628032, 1611661312, 4, 0,
  152221. _vq_quantlist__44u9_p3_0,
  152222. NULL,
  152223. &_vq_auxt__44u9_p3_0,
  152224. NULL,
  152225. 0
  152226. };
  152227. static long _vq_quantlist__44u9_p4_0[] = {
  152228. 8,
  152229. 7,
  152230. 9,
  152231. 6,
  152232. 10,
  152233. 5,
  152234. 11,
  152235. 4,
  152236. 12,
  152237. 3,
  152238. 13,
  152239. 2,
  152240. 14,
  152241. 1,
  152242. 15,
  152243. 0,
  152244. 16,
  152245. };
  152246. static long _vq_lengthlist__44u9_p4_0[] = {
  152247. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152248. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152249. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152250. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152251. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152252. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152253. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152254. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152255. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152256. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152257. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152258. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152259. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152260. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152261. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152262. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152263. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152264. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152265. 14,
  152266. };
  152267. static float _vq_quantthresh__44u9_p4_0[] = {
  152268. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152269. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152270. };
  152271. static long _vq_quantmap__44u9_p4_0[] = {
  152272. 15, 13, 11, 9, 7, 5, 3, 1,
  152273. 0, 2, 4, 6, 8, 10, 12, 14,
  152274. 16,
  152275. };
  152276. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152277. _vq_quantthresh__44u9_p4_0,
  152278. _vq_quantmap__44u9_p4_0,
  152279. 17,
  152280. 17
  152281. };
  152282. static static_codebook _44u9_p4_0 = {
  152283. 2, 289,
  152284. _vq_lengthlist__44u9_p4_0,
  152285. 1, -529530880, 1611661312, 5, 0,
  152286. _vq_quantlist__44u9_p4_0,
  152287. NULL,
  152288. &_vq_auxt__44u9_p4_0,
  152289. NULL,
  152290. 0
  152291. };
  152292. static long _vq_quantlist__44u9_p5_0[] = {
  152293. 1,
  152294. 0,
  152295. 2,
  152296. };
  152297. static long _vq_lengthlist__44u9_p5_0[] = {
  152298. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152299. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152300. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152301. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152302. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152303. 10,
  152304. };
  152305. static float _vq_quantthresh__44u9_p5_0[] = {
  152306. -5.5, 5.5,
  152307. };
  152308. static long _vq_quantmap__44u9_p5_0[] = {
  152309. 1, 0, 2,
  152310. };
  152311. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152312. _vq_quantthresh__44u9_p5_0,
  152313. _vq_quantmap__44u9_p5_0,
  152314. 3,
  152315. 3
  152316. };
  152317. static static_codebook _44u9_p5_0 = {
  152318. 4, 81,
  152319. _vq_lengthlist__44u9_p5_0,
  152320. 1, -529137664, 1618345984, 2, 0,
  152321. _vq_quantlist__44u9_p5_0,
  152322. NULL,
  152323. &_vq_auxt__44u9_p5_0,
  152324. NULL,
  152325. 0
  152326. };
  152327. static long _vq_quantlist__44u9_p5_1[] = {
  152328. 5,
  152329. 4,
  152330. 6,
  152331. 3,
  152332. 7,
  152333. 2,
  152334. 8,
  152335. 1,
  152336. 9,
  152337. 0,
  152338. 10,
  152339. };
  152340. static long _vq_lengthlist__44u9_p5_1[] = {
  152341. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152342. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152343. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152344. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152345. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152346. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152347. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152348. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152349. };
  152350. static float _vq_quantthresh__44u9_p5_1[] = {
  152351. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152352. 3.5, 4.5,
  152353. };
  152354. static long _vq_quantmap__44u9_p5_1[] = {
  152355. 9, 7, 5, 3, 1, 0, 2, 4,
  152356. 6, 8, 10,
  152357. };
  152358. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152359. _vq_quantthresh__44u9_p5_1,
  152360. _vq_quantmap__44u9_p5_1,
  152361. 11,
  152362. 11
  152363. };
  152364. static static_codebook _44u9_p5_1 = {
  152365. 2, 121,
  152366. _vq_lengthlist__44u9_p5_1,
  152367. 1, -531365888, 1611661312, 4, 0,
  152368. _vq_quantlist__44u9_p5_1,
  152369. NULL,
  152370. &_vq_auxt__44u9_p5_1,
  152371. NULL,
  152372. 0
  152373. };
  152374. static long _vq_quantlist__44u9_p6_0[] = {
  152375. 6,
  152376. 5,
  152377. 7,
  152378. 4,
  152379. 8,
  152380. 3,
  152381. 9,
  152382. 2,
  152383. 10,
  152384. 1,
  152385. 11,
  152386. 0,
  152387. 12,
  152388. };
  152389. static long _vq_lengthlist__44u9_p6_0[] = {
  152390. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152391. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152392. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152393. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152394. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152395. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152396. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152397. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152398. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152399. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152400. 10,11,11,11,11,12,11,12,12,
  152401. };
  152402. static float _vq_quantthresh__44u9_p6_0[] = {
  152403. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152404. 12.5, 17.5, 22.5, 27.5,
  152405. };
  152406. static long _vq_quantmap__44u9_p6_0[] = {
  152407. 11, 9, 7, 5, 3, 1, 0, 2,
  152408. 4, 6, 8, 10, 12,
  152409. };
  152410. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152411. _vq_quantthresh__44u9_p6_0,
  152412. _vq_quantmap__44u9_p6_0,
  152413. 13,
  152414. 13
  152415. };
  152416. static static_codebook _44u9_p6_0 = {
  152417. 2, 169,
  152418. _vq_lengthlist__44u9_p6_0,
  152419. 1, -526516224, 1616117760, 4, 0,
  152420. _vq_quantlist__44u9_p6_0,
  152421. NULL,
  152422. &_vq_auxt__44u9_p6_0,
  152423. NULL,
  152424. 0
  152425. };
  152426. static long _vq_quantlist__44u9_p6_1[] = {
  152427. 2,
  152428. 1,
  152429. 3,
  152430. 0,
  152431. 4,
  152432. };
  152433. static long _vq_lengthlist__44u9_p6_1[] = {
  152434. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152435. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152436. };
  152437. static float _vq_quantthresh__44u9_p6_1[] = {
  152438. -1.5, -0.5, 0.5, 1.5,
  152439. };
  152440. static long _vq_quantmap__44u9_p6_1[] = {
  152441. 3, 1, 0, 2, 4,
  152442. };
  152443. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152444. _vq_quantthresh__44u9_p6_1,
  152445. _vq_quantmap__44u9_p6_1,
  152446. 5,
  152447. 5
  152448. };
  152449. static static_codebook _44u9_p6_1 = {
  152450. 2, 25,
  152451. _vq_lengthlist__44u9_p6_1,
  152452. 1, -533725184, 1611661312, 3, 0,
  152453. _vq_quantlist__44u9_p6_1,
  152454. NULL,
  152455. &_vq_auxt__44u9_p6_1,
  152456. NULL,
  152457. 0
  152458. };
  152459. static long _vq_quantlist__44u9_p7_0[] = {
  152460. 6,
  152461. 5,
  152462. 7,
  152463. 4,
  152464. 8,
  152465. 3,
  152466. 9,
  152467. 2,
  152468. 10,
  152469. 1,
  152470. 11,
  152471. 0,
  152472. 12,
  152473. };
  152474. static long _vq_lengthlist__44u9_p7_0[] = {
  152475. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152476. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152477. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152478. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152479. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152480. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152481. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152482. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152483. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152484. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152485. 12,13,13,14,14,14,15,15,15,
  152486. };
  152487. static float _vq_quantthresh__44u9_p7_0[] = {
  152488. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152489. 27.5, 38.5, 49.5, 60.5,
  152490. };
  152491. static long _vq_quantmap__44u9_p7_0[] = {
  152492. 11, 9, 7, 5, 3, 1, 0, 2,
  152493. 4, 6, 8, 10, 12,
  152494. };
  152495. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152496. _vq_quantthresh__44u9_p7_0,
  152497. _vq_quantmap__44u9_p7_0,
  152498. 13,
  152499. 13
  152500. };
  152501. static static_codebook _44u9_p7_0 = {
  152502. 2, 169,
  152503. _vq_lengthlist__44u9_p7_0,
  152504. 1, -523206656, 1618345984, 4, 0,
  152505. _vq_quantlist__44u9_p7_0,
  152506. NULL,
  152507. &_vq_auxt__44u9_p7_0,
  152508. NULL,
  152509. 0
  152510. };
  152511. static long _vq_quantlist__44u9_p7_1[] = {
  152512. 5,
  152513. 4,
  152514. 6,
  152515. 3,
  152516. 7,
  152517. 2,
  152518. 8,
  152519. 1,
  152520. 9,
  152521. 0,
  152522. 10,
  152523. };
  152524. static long _vq_lengthlist__44u9_p7_1[] = {
  152525. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152526. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152527. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152528. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152529. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152530. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152531. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152532. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152533. };
  152534. static float _vq_quantthresh__44u9_p7_1[] = {
  152535. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152536. 3.5, 4.5,
  152537. };
  152538. static long _vq_quantmap__44u9_p7_1[] = {
  152539. 9, 7, 5, 3, 1, 0, 2, 4,
  152540. 6, 8, 10,
  152541. };
  152542. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152543. _vq_quantthresh__44u9_p7_1,
  152544. _vq_quantmap__44u9_p7_1,
  152545. 11,
  152546. 11
  152547. };
  152548. static static_codebook _44u9_p7_1 = {
  152549. 2, 121,
  152550. _vq_lengthlist__44u9_p7_1,
  152551. 1, -531365888, 1611661312, 4, 0,
  152552. _vq_quantlist__44u9_p7_1,
  152553. NULL,
  152554. &_vq_auxt__44u9_p7_1,
  152555. NULL,
  152556. 0
  152557. };
  152558. static long _vq_quantlist__44u9_p8_0[] = {
  152559. 7,
  152560. 6,
  152561. 8,
  152562. 5,
  152563. 9,
  152564. 4,
  152565. 10,
  152566. 3,
  152567. 11,
  152568. 2,
  152569. 12,
  152570. 1,
  152571. 13,
  152572. 0,
  152573. 14,
  152574. };
  152575. static long _vq_lengthlist__44u9_p8_0[] = {
  152576. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  152577. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152578. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  152579. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  152580. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  152581. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  152582. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  152583. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  152584. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  152585. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  152586. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  152587. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  152588. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  152589. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  152590. 15,
  152591. };
  152592. static float _vq_quantthresh__44u9_p8_0[] = {
  152593. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152594. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152595. };
  152596. static long _vq_quantmap__44u9_p8_0[] = {
  152597. 13, 11, 9, 7, 5, 3, 1, 0,
  152598. 2, 4, 6, 8, 10, 12, 14,
  152599. };
  152600. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  152601. _vq_quantthresh__44u9_p8_0,
  152602. _vq_quantmap__44u9_p8_0,
  152603. 15,
  152604. 15
  152605. };
  152606. static static_codebook _44u9_p8_0 = {
  152607. 2, 225,
  152608. _vq_lengthlist__44u9_p8_0,
  152609. 1, -520986624, 1620377600, 4, 0,
  152610. _vq_quantlist__44u9_p8_0,
  152611. NULL,
  152612. &_vq_auxt__44u9_p8_0,
  152613. NULL,
  152614. 0
  152615. };
  152616. static long _vq_quantlist__44u9_p8_1[] = {
  152617. 10,
  152618. 9,
  152619. 11,
  152620. 8,
  152621. 12,
  152622. 7,
  152623. 13,
  152624. 6,
  152625. 14,
  152626. 5,
  152627. 15,
  152628. 4,
  152629. 16,
  152630. 3,
  152631. 17,
  152632. 2,
  152633. 18,
  152634. 1,
  152635. 19,
  152636. 0,
  152637. 20,
  152638. };
  152639. static long _vq_lengthlist__44u9_p8_1[] = {
  152640. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152641. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152642. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  152643. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152644. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  152645. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152646. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152647. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  152648. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152649. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152650. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  152651. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  152652. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152653. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152654. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152655. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152656. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152657. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152658. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  152659. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152660. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152661. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  152662. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  152663. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  152664. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152665. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  152666. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152667. 10,10,10,10,10,10,10,10,10,
  152668. };
  152669. static float _vq_quantthresh__44u9_p8_1[] = {
  152670. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152671. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152672. 6.5, 7.5, 8.5, 9.5,
  152673. };
  152674. static long _vq_quantmap__44u9_p8_1[] = {
  152675. 19, 17, 15, 13, 11, 9, 7, 5,
  152676. 3, 1, 0, 2, 4, 6, 8, 10,
  152677. 12, 14, 16, 18, 20,
  152678. };
  152679. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  152680. _vq_quantthresh__44u9_p8_1,
  152681. _vq_quantmap__44u9_p8_1,
  152682. 21,
  152683. 21
  152684. };
  152685. static static_codebook _44u9_p8_1 = {
  152686. 2, 441,
  152687. _vq_lengthlist__44u9_p8_1,
  152688. 1, -529268736, 1611661312, 5, 0,
  152689. _vq_quantlist__44u9_p8_1,
  152690. NULL,
  152691. &_vq_auxt__44u9_p8_1,
  152692. NULL,
  152693. 0
  152694. };
  152695. static long _vq_quantlist__44u9_p9_0[] = {
  152696. 7,
  152697. 6,
  152698. 8,
  152699. 5,
  152700. 9,
  152701. 4,
  152702. 10,
  152703. 3,
  152704. 11,
  152705. 2,
  152706. 12,
  152707. 1,
  152708. 13,
  152709. 0,
  152710. 14,
  152711. };
  152712. static long _vq_lengthlist__44u9_p9_0[] = {
  152713. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  152714. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  152715. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152718. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152722. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  152725. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152726. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152727. 10,
  152728. };
  152729. static float _vq_quantthresh__44u9_p9_0[] = {
  152730. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  152731. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  152732. };
  152733. static long _vq_quantmap__44u9_p9_0[] = {
  152734. 13, 11, 9, 7, 5, 3, 1, 0,
  152735. 2, 4, 6, 8, 10, 12, 14,
  152736. };
  152737. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  152738. _vq_quantthresh__44u9_p9_0,
  152739. _vq_quantmap__44u9_p9_0,
  152740. 15,
  152741. 15
  152742. };
  152743. static static_codebook _44u9_p9_0 = {
  152744. 2, 225,
  152745. _vq_lengthlist__44u9_p9_0,
  152746. 1, -510036736, 1631393792, 4, 0,
  152747. _vq_quantlist__44u9_p9_0,
  152748. NULL,
  152749. &_vq_auxt__44u9_p9_0,
  152750. NULL,
  152751. 0
  152752. };
  152753. static long _vq_quantlist__44u9_p9_1[] = {
  152754. 9,
  152755. 8,
  152756. 10,
  152757. 7,
  152758. 11,
  152759. 6,
  152760. 12,
  152761. 5,
  152762. 13,
  152763. 4,
  152764. 14,
  152765. 3,
  152766. 15,
  152767. 2,
  152768. 16,
  152769. 1,
  152770. 17,
  152771. 0,
  152772. 18,
  152773. };
  152774. static long _vq_lengthlist__44u9_p9_1[] = {
  152775. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  152776. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  152777. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  152778. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  152779. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  152780. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  152781. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  152782. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  152783. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  152784. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  152785. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  152786. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  152787. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  152788. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  152789. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  152790. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  152791. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  152792. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  152793. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  152794. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  152795. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  152796. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  152797. 17,17,15,17,15,17,16,16,17,
  152798. };
  152799. static float _vq_quantthresh__44u9_p9_1[] = {
  152800. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152801. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152802. 367.5, 416.5,
  152803. };
  152804. static long _vq_quantmap__44u9_p9_1[] = {
  152805. 17, 15, 13, 11, 9, 7, 5, 3,
  152806. 1, 0, 2, 4, 6, 8, 10, 12,
  152807. 14, 16, 18,
  152808. };
  152809. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  152810. _vq_quantthresh__44u9_p9_1,
  152811. _vq_quantmap__44u9_p9_1,
  152812. 19,
  152813. 19
  152814. };
  152815. static static_codebook _44u9_p9_1 = {
  152816. 2, 361,
  152817. _vq_lengthlist__44u9_p9_1,
  152818. 1, -518287360, 1622704128, 5, 0,
  152819. _vq_quantlist__44u9_p9_1,
  152820. NULL,
  152821. &_vq_auxt__44u9_p9_1,
  152822. NULL,
  152823. 0
  152824. };
  152825. static long _vq_quantlist__44u9_p9_2[] = {
  152826. 24,
  152827. 23,
  152828. 25,
  152829. 22,
  152830. 26,
  152831. 21,
  152832. 27,
  152833. 20,
  152834. 28,
  152835. 19,
  152836. 29,
  152837. 18,
  152838. 30,
  152839. 17,
  152840. 31,
  152841. 16,
  152842. 32,
  152843. 15,
  152844. 33,
  152845. 14,
  152846. 34,
  152847. 13,
  152848. 35,
  152849. 12,
  152850. 36,
  152851. 11,
  152852. 37,
  152853. 10,
  152854. 38,
  152855. 9,
  152856. 39,
  152857. 8,
  152858. 40,
  152859. 7,
  152860. 41,
  152861. 6,
  152862. 42,
  152863. 5,
  152864. 43,
  152865. 4,
  152866. 44,
  152867. 3,
  152868. 45,
  152869. 2,
  152870. 46,
  152871. 1,
  152872. 47,
  152873. 0,
  152874. 48,
  152875. };
  152876. static long _vq_lengthlist__44u9_p9_2[] = {
  152877. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  152878. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152879. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152880. 7,
  152881. };
  152882. static float _vq_quantthresh__44u9_p9_2[] = {
  152883. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152884. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152885. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152886. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152887. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152888. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152889. };
  152890. static long _vq_quantmap__44u9_p9_2[] = {
  152891. 47, 45, 43, 41, 39, 37, 35, 33,
  152892. 31, 29, 27, 25, 23, 21, 19, 17,
  152893. 15, 13, 11, 9, 7, 5, 3, 1,
  152894. 0, 2, 4, 6, 8, 10, 12, 14,
  152895. 16, 18, 20, 22, 24, 26, 28, 30,
  152896. 32, 34, 36, 38, 40, 42, 44, 46,
  152897. 48,
  152898. };
  152899. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  152900. _vq_quantthresh__44u9_p9_2,
  152901. _vq_quantmap__44u9_p9_2,
  152902. 49,
  152903. 49
  152904. };
  152905. static static_codebook _44u9_p9_2 = {
  152906. 1, 49,
  152907. _vq_lengthlist__44u9_p9_2,
  152908. 1, -526909440, 1611661312, 6, 0,
  152909. _vq_quantlist__44u9_p9_2,
  152910. NULL,
  152911. &_vq_auxt__44u9_p9_2,
  152912. NULL,
  152913. 0
  152914. };
  152915. static long _huff_lengthlist__44un1__long[] = {
  152916. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  152917. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  152918. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  152919. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  152920. };
  152921. static static_codebook _huff_book__44un1__long = {
  152922. 2, 64,
  152923. _huff_lengthlist__44un1__long,
  152924. 0, 0, 0, 0, 0,
  152925. NULL,
  152926. NULL,
  152927. NULL,
  152928. NULL,
  152929. 0
  152930. };
  152931. static long _vq_quantlist__44un1__p1_0[] = {
  152932. 1,
  152933. 0,
  152934. 2,
  152935. };
  152936. static long _vq_lengthlist__44un1__p1_0[] = {
  152937. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  152938. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  152939. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  152940. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  152941. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  152942. 12,
  152943. };
  152944. static float _vq_quantthresh__44un1__p1_0[] = {
  152945. -0.5, 0.5,
  152946. };
  152947. static long _vq_quantmap__44un1__p1_0[] = {
  152948. 1, 0, 2,
  152949. };
  152950. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  152951. _vq_quantthresh__44un1__p1_0,
  152952. _vq_quantmap__44un1__p1_0,
  152953. 3,
  152954. 3
  152955. };
  152956. static static_codebook _44un1__p1_0 = {
  152957. 4, 81,
  152958. _vq_lengthlist__44un1__p1_0,
  152959. 1, -535822336, 1611661312, 2, 0,
  152960. _vq_quantlist__44un1__p1_0,
  152961. NULL,
  152962. &_vq_auxt__44un1__p1_0,
  152963. NULL,
  152964. 0
  152965. };
  152966. static long _vq_quantlist__44un1__p2_0[] = {
  152967. 1,
  152968. 0,
  152969. 2,
  152970. };
  152971. static long _vq_lengthlist__44un1__p2_0[] = {
  152972. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  152973. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  152974. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  152975. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  152976. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  152977. 8,
  152978. };
  152979. static float _vq_quantthresh__44un1__p2_0[] = {
  152980. -0.5, 0.5,
  152981. };
  152982. static long _vq_quantmap__44un1__p2_0[] = {
  152983. 1, 0, 2,
  152984. };
  152985. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  152986. _vq_quantthresh__44un1__p2_0,
  152987. _vq_quantmap__44un1__p2_0,
  152988. 3,
  152989. 3
  152990. };
  152991. static static_codebook _44un1__p2_0 = {
  152992. 4, 81,
  152993. _vq_lengthlist__44un1__p2_0,
  152994. 1, -535822336, 1611661312, 2, 0,
  152995. _vq_quantlist__44un1__p2_0,
  152996. NULL,
  152997. &_vq_auxt__44un1__p2_0,
  152998. NULL,
  152999. 0
  153000. };
  153001. static long _vq_quantlist__44un1__p3_0[] = {
  153002. 2,
  153003. 1,
  153004. 3,
  153005. 0,
  153006. 4,
  153007. };
  153008. static long _vq_lengthlist__44un1__p3_0[] = {
  153009. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  153010. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  153011. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  153012. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  153013. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  153014. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  153015. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  153016. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  153017. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  153018. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  153019. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  153020. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  153021. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  153022. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  153023. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  153024. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  153025. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  153026. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  153027. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  153028. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  153029. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  153030. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  153031. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  153032. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  153033. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  153034. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  153035. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  153036. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  153037. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  153038. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  153039. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  153040. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153041. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153042. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153043. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153044. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153045. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153046. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153047. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153048. 17,
  153049. };
  153050. static float _vq_quantthresh__44un1__p3_0[] = {
  153051. -1.5, -0.5, 0.5, 1.5,
  153052. };
  153053. static long _vq_quantmap__44un1__p3_0[] = {
  153054. 3, 1, 0, 2, 4,
  153055. };
  153056. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153057. _vq_quantthresh__44un1__p3_0,
  153058. _vq_quantmap__44un1__p3_0,
  153059. 5,
  153060. 5
  153061. };
  153062. static static_codebook _44un1__p3_0 = {
  153063. 4, 625,
  153064. _vq_lengthlist__44un1__p3_0,
  153065. 1, -533725184, 1611661312, 3, 0,
  153066. _vq_quantlist__44un1__p3_0,
  153067. NULL,
  153068. &_vq_auxt__44un1__p3_0,
  153069. NULL,
  153070. 0
  153071. };
  153072. static long _vq_quantlist__44un1__p4_0[] = {
  153073. 2,
  153074. 1,
  153075. 3,
  153076. 0,
  153077. 4,
  153078. };
  153079. static long _vq_lengthlist__44un1__p4_0[] = {
  153080. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153081. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153082. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153083. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153084. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153085. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153086. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153087. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153088. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153089. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153090. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153091. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153092. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153093. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153094. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153095. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153096. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153097. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153098. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153099. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153100. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153101. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153102. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153103. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153104. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153105. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153106. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153107. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153108. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153109. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153110. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153111. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153112. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153113. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153114. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153115. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153116. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153117. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153118. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153119. 12,
  153120. };
  153121. static float _vq_quantthresh__44un1__p4_0[] = {
  153122. -1.5, -0.5, 0.5, 1.5,
  153123. };
  153124. static long _vq_quantmap__44un1__p4_0[] = {
  153125. 3, 1, 0, 2, 4,
  153126. };
  153127. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153128. _vq_quantthresh__44un1__p4_0,
  153129. _vq_quantmap__44un1__p4_0,
  153130. 5,
  153131. 5
  153132. };
  153133. static static_codebook _44un1__p4_0 = {
  153134. 4, 625,
  153135. _vq_lengthlist__44un1__p4_0,
  153136. 1, -533725184, 1611661312, 3, 0,
  153137. _vq_quantlist__44un1__p4_0,
  153138. NULL,
  153139. &_vq_auxt__44un1__p4_0,
  153140. NULL,
  153141. 0
  153142. };
  153143. static long _vq_quantlist__44un1__p5_0[] = {
  153144. 4,
  153145. 3,
  153146. 5,
  153147. 2,
  153148. 6,
  153149. 1,
  153150. 7,
  153151. 0,
  153152. 8,
  153153. };
  153154. static long _vq_lengthlist__44un1__p5_0[] = {
  153155. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153156. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153157. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153158. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153159. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153160. 12,
  153161. };
  153162. static float _vq_quantthresh__44un1__p5_0[] = {
  153163. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153164. };
  153165. static long _vq_quantmap__44un1__p5_0[] = {
  153166. 7, 5, 3, 1, 0, 2, 4, 6,
  153167. 8,
  153168. };
  153169. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153170. _vq_quantthresh__44un1__p5_0,
  153171. _vq_quantmap__44un1__p5_0,
  153172. 9,
  153173. 9
  153174. };
  153175. static static_codebook _44un1__p5_0 = {
  153176. 2, 81,
  153177. _vq_lengthlist__44un1__p5_0,
  153178. 1, -531628032, 1611661312, 4, 0,
  153179. _vq_quantlist__44un1__p5_0,
  153180. NULL,
  153181. &_vq_auxt__44un1__p5_0,
  153182. NULL,
  153183. 0
  153184. };
  153185. static long _vq_quantlist__44un1__p6_0[] = {
  153186. 6,
  153187. 5,
  153188. 7,
  153189. 4,
  153190. 8,
  153191. 3,
  153192. 9,
  153193. 2,
  153194. 10,
  153195. 1,
  153196. 11,
  153197. 0,
  153198. 12,
  153199. };
  153200. static long _vq_lengthlist__44un1__p6_0[] = {
  153201. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153202. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153203. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153204. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153205. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153206. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153207. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153208. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153209. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153210. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153211. 16, 0,15,18,18, 0,16, 0, 0,
  153212. };
  153213. static float _vq_quantthresh__44un1__p6_0[] = {
  153214. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153215. 12.5, 17.5, 22.5, 27.5,
  153216. };
  153217. static long _vq_quantmap__44un1__p6_0[] = {
  153218. 11, 9, 7, 5, 3, 1, 0, 2,
  153219. 4, 6, 8, 10, 12,
  153220. };
  153221. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153222. _vq_quantthresh__44un1__p6_0,
  153223. _vq_quantmap__44un1__p6_0,
  153224. 13,
  153225. 13
  153226. };
  153227. static static_codebook _44un1__p6_0 = {
  153228. 2, 169,
  153229. _vq_lengthlist__44un1__p6_0,
  153230. 1, -526516224, 1616117760, 4, 0,
  153231. _vq_quantlist__44un1__p6_0,
  153232. NULL,
  153233. &_vq_auxt__44un1__p6_0,
  153234. NULL,
  153235. 0
  153236. };
  153237. static long _vq_quantlist__44un1__p6_1[] = {
  153238. 2,
  153239. 1,
  153240. 3,
  153241. 0,
  153242. 4,
  153243. };
  153244. static long _vq_lengthlist__44un1__p6_1[] = {
  153245. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153246. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153247. };
  153248. static float _vq_quantthresh__44un1__p6_1[] = {
  153249. -1.5, -0.5, 0.5, 1.5,
  153250. };
  153251. static long _vq_quantmap__44un1__p6_1[] = {
  153252. 3, 1, 0, 2, 4,
  153253. };
  153254. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153255. _vq_quantthresh__44un1__p6_1,
  153256. _vq_quantmap__44un1__p6_1,
  153257. 5,
  153258. 5
  153259. };
  153260. static static_codebook _44un1__p6_1 = {
  153261. 2, 25,
  153262. _vq_lengthlist__44un1__p6_1,
  153263. 1, -533725184, 1611661312, 3, 0,
  153264. _vq_quantlist__44un1__p6_1,
  153265. NULL,
  153266. &_vq_auxt__44un1__p6_1,
  153267. NULL,
  153268. 0
  153269. };
  153270. static long _vq_quantlist__44un1__p7_0[] = {
  153271. 2,
  153272. 1,
  153273. 3,
  153274. 0,
  153275. 4,
  153276. };
  153277. static long _vq_lengthlist__44un1__p7_0[] = {
  153278. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153279. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153281. 11,11,10,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, 8,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,10,
  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, 7,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,10,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. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153300. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153301. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153302. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153303. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153304. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153305. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153306. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153307. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153308. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153309. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153310. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153311. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153312. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153313. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153314. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153315. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153316. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153317. 10,
  153318. };
  153319. static float _vq_quantthresh__44un1__p7_0[] = {
  153320. -253.5, -84.5, 84.5, 253.5,
  153321. };
  153322. static long _vq_quantmap__44un1__p7_0[] = {
  153323. 3, 1, 0, 2, 4,
  153324. };
  153325. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153326. _vq_quantthresh__44un1__p7_0,
  153327. _vq_quantmap__44un1__p7_0,
  153328. 5,
  153329. 5
  153330. };
  153331. static static_codebook _44un1__p7_0 = {
  153332. 4, 625,
  153333. _vq_lengthlist__44un1__p7_0,
  153334. 1, -518709248, 1626677248, 3, 0,
  153335. _vq_quantlist__44un1__p7_0,
  153336. NULL,
  153337. &_vq_auxt__44un1__p7_0,
  153338. NULL,
  153339. 0
  153340. };
  153341. static long _vq_quantlist__44un1__p7_1[] = {
  153342. 6,
  153343. 5,
  153344. 7,
  153345. 4,
  153346. 8,
  153347. 3,
  153348. 9,
  153349. 2,
  153350. 10,
  153351. 1,
  153352. 11,
  153353. 0,
  153354. 12,
  153355. };
  153356. static long _vq_lengthlist__44un1__p7_1[] = {
  153357. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153358. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153359. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153360. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153361. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153362. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153363. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153364. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153365. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153366. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153367. 12,13,13,12,13,13,14,14,14,
  153368. };
  153369. static float _vq_quantthresh__44un1__p7_1[] = {
  153370. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153371. 32.5, 45.5, 58.5, 71.5,
  153372. };
  153373. static long _vq_quantmap__44un1__p7_1[] = {
  153374. 11, 9, 7, 5, 3, 1, 0, 2,
  153375. 4, 6, 8, 10, 12,
  153376. };
  153377. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153378. _vq_quantthresh__44un1__p7_1,
  153379. _vq_quantmap__44un1__p7_1,
  153380. 13,
  153381. 13
  153382. };
  153383. static static_codebook _44un1__p7_1 = {
  153384. 2, 169,
  153385. _vq_lengthlist__44un1__p7_1,
  153386. 1, -523010048, 1618608128, 4, 0,
  153387. _vq_quantlist__44un1__p7_1,
  153388. NULL,
  153389. &_vq_auxt__44un1__p7_1,
  153390. NULL,
  153391. 0
  153392. };
  153393. static long _vq_quantlist__44un1__p7_2[] = {
  153394. 6,
  153395. 5,
  153396. 7,
  153397. 4,
  153398. 8,
  153399. 3,
  153400. 9,
  153401. 2,
  153402. 10,
  153403. 1,
  153404. 11,
  153405. 0,
  153406. 12,
  153407. };
  153408. static long _vq_lengthlist__44un1__p7_2[] = {
  153409. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153410. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153411. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153412. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153413. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153414. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153415. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153416. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153417. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153418. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153419. 9, 9, 9,10,10,10,10,10,10,
  153420. };
  153421. static float _vq_quantthresh__44un1__p7_2[] = {
  153422. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153423. 2.5, 3.5, 4.5, 5.5,
  153424. };
  153425. static long _vq_quantmap__44un1__p7_2[] = {
  153426. 11, 9, 7, 5, 3, 1, 0, 2,
  153427. 4, 6, 8, 10, 12,
  153428. };
  153429. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153430. _vq_quantthresh__44un1__p7_2,
  153431. _vq_quantmap__44un1__p7_2,
  153432. 13,
  153433. 13
  153434. };
  153435. static static_codebook _44un1__p7_2 = {
  153436. 2, 169,
  153437. _vq_lengthlist__44un1__p7_2,
  153438. 1, -531103744, 1611661312, 4, 0,
  153439. _vq_quantlist__44un1__p7_2,
  153440. NULL,
  153441. &_vq_auxt__44un1__p7_2,
  153442. NULL,
  153443. 0
  153444. };
  153445. static long _huff_lengthlist__44un1__short[] = {
  153446. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153447. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153448. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153449. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153450. };
  153451. static static_codebook _huff_book__44un1__short = {
  153452. 2, 64,
  153453. _huff_lengthlist__44un1__short,
  153454. 0, 0, 0, 0, 0,
  153455. NULL,
  153456. NULL,
  153457. NULL,
  153458. NULL,
  153459. 0
  153460. };
  153461. /*** End of inlined file: res_books_uncoupled.h ***/
  153462. /***** residue backends *********************************************/
  153463. static vorbis_info_residue0 _residue_44_low_un={
  153464. 0,-1, -1, 8,-1,
  153465. {0},
  153466. {-1},
  153467. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153468. { -1, 25, -1, 45, -1, -1, -1}
  153469. };
  153470. static vorbis_info_residue0 _residue_44_mid_un={
  153471. 0,-1, -1, 10,-1,
  153472. /* 0 1 2 3 4 5 6 7 8 9 */
  153473. {0},
  153474. {-1},
  153475. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153476. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153477. };
  153478. static vorbis_info_residue0 _residue_44_hi_un={
  153479. 0,-1, -1, 10,-1,
  153480. /* 0 1 2 3 4 5 6 7 8 9 */
  153481. {0},
  153482. {-1},
  153483. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153484. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153485. };
  153486. /* mapping conventions:
  153487. only one submap (this would change for efficient 5.1 support for example)*/
  153488. /* Four psychoacoustic profiles are used, one for each blocktype */
  153489. static vorbis_info_mapping0 _map_nominal_u[2]={
  153490. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153491. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153492. };
  153493. static static_bookblock _resbook_44u_n1={
  153494. {
  153495. {0},
  153496. {0,0,&_44un1__p1_0},
  153497. {0,0,&_44un1__p2_0},
  153498. {0,0,&_44un1__p3_0},
  153499. {0,0,&_44un1__p4_0},
  153500. {0,0,&_44un1__p5_0},
  153501. {&_44un1__p6_0,&_44un1__p6_1},
  153502. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153503. }
  153504. };
  153505. static static_bookblock _resbook_44u_0={
  153506. {
  153507. {0},
  153508. {0,0,&_44u0__p1_0},
  153509. {0,0,&_44u0__p2_0},
  153510. {0,0,&_44u0__p3_0},
  153511. {0,0,&_44u0__p4_0},
  153512. {0,0,&_44u0__p5_0},
  153513. {&_44u0__p6_0,&_44u0__p6_1},
  153514. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153515. }
  153516. };
  153517. static static_bookblock _resbook_44u_1={
  153518. {
  153519. {0},
  153520. {0,0,&_44u1__p1_0},
  153521. {0,0,&_44u1__p2_0},
  153522. {0,0,&_44u1__p3_0},
  153523. {0,0,&_44u1__p4_0},
  153524. {0,0,&_44u1__p5_0},
  153525. {&_44u1__p6_0,&_44u1__p6_1},
  153526. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153527. }
  153528. };
  153529. static static_bookblock _resbook_44u_2={
  153530. {
  153531. {0},
  153532. {0,0,&_44u2__p1_0},
  153533. {0,0,&_44u2__p2_0},
  153534. {0,0,&_44u2__p3_0},
  153535. {0,0,&_44u2__p4_0},
  153536. {0,0,&_44u2__p5_0},
  153537. {&_44u2__p6_0,&_44u2__p6_1},
  153538. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153539. }
  153540. };
  153541. static static_bookblock _resbook_44u_3={
  153542. {
  153543. {0},
  153544. {0,0,&_44u3__p1_0},
  153545. {0,0,&_44u3__p2_0},
  153546. {0,0,&_44u3__p3_0},
  153547. {0,0,&_44u3__p4_0},
  153548. {0,0,&_44u3__p5_0},
  153549. {&_44u3__p6_0,&_44u3__p6_1},
  153550. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153551. }
  153552. };
  153553. static static_bookblock _resbook_44u_4={
  153554. {
  153555. {0},
  153556. {0,0,&_44u4__p1_0},
  153557. {0,0,&_44u4__p2_0},
  153558. {0,0,&_44u4__p3_0},
  153559. {0,0,&_44u4__p4_0},
  153560. {0,0,&_44u4__p5_0},
  153561. {&_44u4__p6_0,&_44u4__p6_1},
  153562. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  153563. }
  153564. };
  153565. static static_bookblock _resbook_44u_5={
  153566. {
  153567. {0},
  153568. {0,0,&_44u5__p1_0},
  153569. {0,0,&_44u5__p2_0},
  153570. {0,0,&_44u5__p3_0},
  153571. {0,0,&_44u5__p4_0},
  153572. {0,0,&_44u5__p5_0},
  153573. {0,0,&_44u5__p6_0},
  153574. {&_44u5__p7_0,&_44u5__p7_1},
  153575. {&_44u5__p8_0,&_44u5__p8_1},
  153576. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  153577. }
  153578. };
  153579. static static_bookblock _resbook_44u_6={
  153580. {
  153581. {0},
  153582. {0,0,&_44u6__p1_0},
  153583. {0,0,&_44u6__p2_0},
  153584. {0,0,&_44u6__p3_0},
  153585. {0,0,&_44u6__p4_0},
  153586. {0,0,&_44u6__p5_0},
  153587. {0,0,&_44u6__p6_0},
  153588. {&_44u6__p7_0,&_44u6__p7_1},
  153589. {&_44u6__p8_0,&_44u6__p8_1},
  153590. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  153591. }
  153592. };
  153593. static static_bookblock _resbook_44u_7={
  153594. {
  153595. {0},
  153596. {0,0,&_44u7__p1_0},
  153597. {0,0,&_44u7__p2_0},
  153598. {0,0,&_44u7__p3_0},
  153599. {0,0,&_44u7__p4_0},
  153600. {0,0,&_44u7__p5_0},
  153601. {0,0,&_44u7__p6_0},
  153602. {&_44u7__p7_0,&_44u7__p7_1},
  153603. {&_44u7__p8_0,&_44u7__p8_1},
  153604. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  153605. }
  153606. };
  153607. static static_bookblock _resbook_44u_8={
  153608. {
  153609. {0},
  153610. {0,0,&_44u8_p1_0},
  153611. {0,0,&_44u8_p2_0},
  153612. {0,0,&_44u8_p3_0},
  153613. {0,0,&_44u8_p4_0},
  153614. {&_44u8_p5_0,&_44u8_p5_1},
  153615. {&_44u8_p6_0,&_44u8_p6_1},
  153616. {&_44u8_p7_0,&_44u8_p7_1},
  153617. {&_44u8_p8_0,&_44u8_p8_1},
  153618. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  153619. }
  153620. };
  153621. static static_bookblock _resbook_44u_9={
  153622. {
  153623. {0},
  153624. {0,0,&_44u9_p1_0},
  153625. {0,0,&_44u9_p2_0},
  153626. {0,0,&_44u9_p3_0},
  153627. {0,0,&_44u9_p4_0},
  153628. {&_44u9_p5_0,&_44u9_p5_1},
  153629. {&_44u9_p6_0,&_44u9_p6_1},
  153630. {&_44u9_p7_0,&_44u9_p7_1},
  153631. {&_44u9_p8_0,&_44u9_p8_1},
  153632. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  153633. }
  153634. };
  153635. static vorbis_residue_template _res_44u_n1[]={
  153636. {1,0, &_residue_44_low_un,
  153637. &_huff_book__44un1__short,&_huff_book__44un1__short,
  153638. &_resbook_44u_n1,&_resbook_44u_n1},
  153639. {1,0, &_residue_44_low_un,
  153640. &_huff_book__44un1__long,&_huff_book__44un1__long,
  153641. &_resbook_44u_n1,&_resbook_44u_n1}
  153642. };
  153643. static vorbis_residue_template _res_44u_0[]={
  153644. {1,0, &_residue_44_low_un,
  153645. &_huff_book__44u0__short,&_huff_book__44u0__short,
  153646. &_resbook_44u_0,&_resbook_44u_0},
  153647. {1,0, &_residue_44_low_un,
  153648. &_huff_book__44u0__long,&_huff_book__44u0__long,
  153649. &_resbook_44u_0,&_resbook_44u_0}
  153650. };
  153651. static vorbis_residue_template _res_44u_1[]={
  153652. {1,0, &_residue_44_low_un,
  153653. &_huff_book__44u1__short,&_huff_book__44u1__short,
  153654. &_resbook_44u_1,&_resbook_44u_1},
  153655. {1,0, &_residue_44_low_un,
  153656. &_huff_book__44u1__long,&_huff_book__44u1__long,
  153657. &_resbook_44u_1,&_resbook_44u_1}
  153658. };
  153659. static vorbis_residue_template _res_44u_2[]={
  153660. {1,0, &_residue_44_low_un,
  153661. &_huff_book__44u2__short,&_huff_book__44u2__short,
  153662. &_resbook_44u_2,&_resbook_44u_2},
  153663. {1,0, &_residue_44_low_un,
  153664. &_huff_book__44u2__long,&_huff_book__44u2__long,
  153665. &_resbook_44u_2,&_resbook_44u_2}
  153666. };
  153667. static vorbis_residue_template _res_44u_3[]={
  153668. {1,0, &_residue_44_low_un,
  153669. &_huff_book__44u3__short,&_huff_book__44u3__short,
  153670. &_resbook_44u_3,&_resbook_44u_3},
  153671. {1,0, &_residue_44_low_un,
  153672. &_huff_book__44u3__long,&_huff_book__44u3__long,
  153673. &_resbook_44u_3,&_resbook_44u_3}
  153674. };
  153675. static vorbis_residue_template _res_44u_4[]={
  153676. {1,0, &_residue_44_low_un,
  153677. &_huff_book__44u4__short,&_huff_book__44u4__short,
  153678. &_resbook_44u_4,&_resbook_44u_4},
  153679. {1,0, &_residue_44_low_un,
  153680. &_huff_book__44u4__long,&_huff_book__44u4__long,
  153681. &_resbook_44u_4,&_resbook_44u_4}
  153682. };
  153683. static vorbis_residue_template _res_44u_5[]={
  153684. {1,0, &_residue_44_mid_un,
  153685. &_huff_book__44u5__short,&_huff_book__44u5__short,
  153686. &_resbook_44u_5,&_resbook_44u_5},
  153687. {1,0, &_residue_44_mid_un,
  153688. &_huff_book__44u5__long,&_huff_book__44u5__long,
  153689. &_resbook_44u_5,&_resbook_44u_5}
  153690. };
  153691. static vorbis_residue_template _res_44u_6[]={
  153692. {1,0, &_residue_44_mid_un,
  153693. &_huff_book__44u6__short,&_huff_book__44u6__short,
  153694. &_resbook_44u_6,&_resbook_44u_6},
  153695. {1,0, &_residue_44_mid_un,
  153696. &_huff_book__44u6__long,&_huff_book__44u6__long,
  153697. &_resbook_44u_6,&_resbook_44u_6}
  153698. };
  153699. static vorbis_residue_template _res_44u_7[]={
  153700. {1,0, &_residue_44_mid_un,
  153701. &_huff_book__44u7__short,&_huff_book__44u7__short,
  153702. &_resbook_44u_7,&_resbook_44u_7},
  153703. {1,0, &_residue_44_mid_un,
  153704. &_huff_book__44u7__long,&_huff_book__44u7__long,
  153705. &_resbook_44u_7,&_resbook_44u_7}
  153706. };
  153707. static vorbis_residue_template _res_44u_8[]={
  153708. {1,0, &_residue_44_hi_un,
  153709. &_huff_book__44u8__short,&_huff_book__44u8__short,
  153710. &_resbook_44u_8,&_resbook_44u_8},
  153711. {1,0, &_residue_44_hi_un,
  153712. &_huff_book__44u8__long,&_huff_book__44u8__long,
  153713. &_resbook_44u_8,&_resbook_44u_8}
  153714. };
  153715. static vorbis_residue_template _res_44u_9[]={
  153716. {1,0, &_residue_44_hi_un,
  153717. &_huff_book__44u9__short,&_huff_book__44u9__short,
  153718. &_resbook_44u_9,&_resbook_44u_9},
  153719. {1,0, &_residue_44_hi_un,
  153720. &_huff_book__44u9__long,&_huff_book__44u9__long,
  153721. &_resbook_44u_9,&_resbook_44u_9}
  153722. };
  153723. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  153724. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  153725. { _map_nominal_u, _res_44u_0 }, /* 0 */
  153726. { _map_nominal_u, _res_44u_1 }, /* 1 */
  153727. { _map_nominal_u, _res_44u_2 }, /* 2 */
  153728. { _map_nominal_u, _res_44u_3 }, /* 3 */
  153729. { _map_nominal_u, _res_44u_4 }, /* 4 */
  153730. { _map_nominal_u, _res_44u_5 }, /* 5 */
  153731. { _map_nominal_u, _res_44u_6 }, /* 6 */
  153732. { _map_nominal_u, _res_44u_7 }, /* 7 */
  153733. { _map_nominal_u, _res_44u_8 }, /* 8 */
  153734. { _map_nominal_u, _res_44u_9 }, /* 9 */
  153735. };
  153736. /*** End of inlined file: residue_44u.h ***/
  153737. static double rate_mapping_44_un[12]={
  153738. 32000.,48000.,60000.,70000.,80000.,86000.,
  153739. 96000.,110000.,120000.,140000.,160000.,240001.
  153740. };
  153741. ve_setup_data_template ve_setup_44_uncoupled={
  153742. 11,
  153743. rate_mapping_44_un,
  153744. quality_mapping_44,
  153745. -1,
  153746. 40000,
  153747. 50000,
  153748. blocksize_short_44,
  153749. blocksize_long_44,
  153750. _psy_tone_masteratt_44,
  153751. _psy_tone_0dB,
  153752. _psy_tone_suppress,
  153753. _vp_tonemask_adj_otherblock,
  153754. _vp_tonemask_adj_longblock,
  153755. _vp_tonemask_adj_otherblock,
  153756. _psy_noiseguards_44,
  153757. _psy_noisebias_impulse,
  153758. _psy_noisebias_padding,
  153759. _psy_noisebias_trans,
  153760. _psy_noisebias_long,
  153761. _psy_noise_suppress,
  153762. _psy_compand_44,
  153763. _psy_compand_short_mapping,
  153764. _psy_compand_long_mapping,
  153765. {_noise_start_short_44,_noise_start_long_44},
  153766. {_noise_part_short_44,_noise_part_long_44},
  153767. _noise_thresh_44,
  153768. _psy_ath_floater,
  153769. _psy_ath_abs,
  153770. _psy_lowpass_44,
  153771. _psy_global_44,
  153772. _global_mapping_44,
  153773. NULL,
  153774. _floor_books,
  153775. _floor,
  153776. _floor_short_mapping_44,
  153777. _floor_long_mapping_44,
  153778. _mapres_template_44_uncoupled
  153779. };
  153780. /*** End of inlined file: setup_44u.h ***/
  153781. /*** Start of inlined file: setup_32.h ***/
  153782. static double rate_mapping_32[12]={
  153783. 18000.,28000.,35000.,45000.,56000.,60000.,
  153784. 75000.,90000.,100000.,115000.,150000.,190000.,
  153785. };
  153786. static double rate_mapping_32_un[12]={
  153787. 30000.,42000.,52000.,64000.,72000.,78000.,
  153788. 86000.,92000.,110000.,120000.,140000.,190000.,
  153789. };
  153790. static double _psy_lowpass_32[12]={
  153791. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  153792. };
  153793. ve_setup_data_template ve_setup_32_stereo={
  153794. 11,
  153795. rate_mapping_32,
  153796. quality_mapping_44,
  153797. 2,
  153798. 26000,
  153799. 40000,
  153800. blocksize_short_44,
  153801. blocksize_long_44,
  153802. _psy_tone_masteratt_44,
  153803. _psy_tone_0dB,
  153804. _psy_tone_suppress,
  153805. _vp_tonemask_adj_otherblock,
  153806. _vp_tonemask_adj_longblock,
  153807. _vp_tonemask_adj_otherblock,
  153808. _psy_noiseguards_44,
  153809. _psy_noisebias_impulse,
  153810. _psy_noisebias_padding,
  153811. _psy_noisebias_trans,
  153812. _psy_noisebias_long,
  153813. _psy_noise_suppress,
  153814. _psy_compand_44,
  153815. _psy_compand_short_mapping,
  153816. _psy_compand_long_mapping,
  153817. {_noise_start_short_44,_noise_start_long_44},
  153818. {_noise_part_short_44,_noise_part_long_44},
  153819. _noise_thresh_44,
  153820. _psy_ath_floater,
  153821. _psy_ath_abs,
  153822. _psy_lowpass_32,
  153823. _psy_global_44,
  153824. _global_mapping_44,
  153825. _psy_stereo_modes_44,
  153826. _floor_books,
  153827. _floor,
  153828. _floor_short_mapping_44,
  153829. _floor_long_mapping_44,
  153830. _mapres_template_44_stereo
  153831. };
  153832. ve_setup_data_template ve_setup_32_uncoupled={
  153833. 11,
  153834. rate_mapping_32_un,
  153835. quality_mapping_44,
  153836. -1,
  153837. 26000,
  153838. 40000,
  153839. blocksize_short_44,
  153840. blocksize_long_44,
  153841. _psy_tone_masteratt_44,
  153842. _psy_tone_0dB,
  153843. _psy_tone_suppress,
  153844. _vp_tonemask_adj_otherblock,
  153845. _vp_tonemask_adj_longblock,
  153846. _vp_tonemask_adj_otherblock,
  153847. _psy_noiseguards_44,
  153848. _psy_noisebias_impulse,
  153849. _psy_noisebias_padding,
  153850. _psy_noisebias_trans,
  153851. _psy_noisebias_long,
  153852. _psy_noise_suppress,
  153853. _psy_compand_44,
  153854. _psy_compand_short_mapping,
  153855. _psy_compand_long_mapping,
  153856. {_noise_start_short_44,_noise_start_long_44},
  153857. {_noise_part_short_44,_noise_part_long_44},
  153858. _noise_thresh_44,
  153859. _psy_ath_floater,
  153860. _psy_ath_abs,
  153861. _psy_lowpass_32,
  153862. _psy_global_44,
  153863. _global_mapping_44,
  153864. NULL,
  153865. _floor_books,
  153866. _floor,
  153867. _floor_short_mapping_44,
  153868. _floor_long_mapping_44,
  153869. _mapres_template_44_uncoupled
  153870. };
  153871. /*** End of inlined file: setup_32.h ***/
  153872. /*** Start of inlined file: setup_8.h ***/
  153873. /*** Start of inlined file: psych_8.h ***/
  153874. static att3 _psy_tone_masteratt_8[3]={
  153875. {{ 32, 25, 12}, 0, 0}, /* 0 */
  153876. {{ 30, 25, 12}, 0, 0}, /* 0 */
  153877. {{ 20, 0, -14}, 0, 0}, /* 0 */
  153878. };
  153879. static vp_adjblock _vp_tonemask_adj_8[3]={
  153880. /* adjust for mode zero */
  153881. /* 63 125 250 500 1 2 4 8 16 */
  153882. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153883. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  153884. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  153885. };
  153886. static noise3 _psy_noisebias_8[3]={
  153887. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  153888. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153889. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  153890. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153891. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  153892. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  153893. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  153894. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  153895. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  153896. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  153897. };
  153898. /* stereo mode by base quality level */
  153899. static adj_stereo _psy_stereo_modes_8[3]={
  153900. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  153901. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153902. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153903. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153904. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153905. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153906. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153907. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153908. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153909. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  153910. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  153911. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  153912. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  153913. };
  153914. static noiseguard _psy_noiseguards_8[2]={
  153915. {10,10,-1},
  153916. {10,10,-1},
  153917. };
  153918. static compandblock _psy_compand_8[2]={
  153919. {{
  153920. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  153921. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  153922. 12,12,13,13,14,14,15, 15, /* 23dB */
  153923. 16,16,17,17,17,18,18, 19, /* 31dB */
  153924. 19,19,20,21,22,23,24, 25, /* 39dB */
  153925. }},
  153926. {{
  153927. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  153928. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  153929. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  153930. 9,10,11,12,13,14,15, 16, /* 31dB */
  153931. 17,18,19,20,21,22,23, 24, /* 39dB */
  153932. }},
  153933. };
  153934. static double _psy_lowpass_8[3]={3.,4.,4.};
  153935. static int _noise_start_8[2]={
  153936. 64,64,
  153937. };
  153938. static int _noise_part_8[2]={
  153939. 8,8,
  153940. };
  153941. static int _psy_ath_floater_8[3]={
  153942. -100,-100,-105,
  153943. };
  153944. static int _psy_ath_abs_8[3]={
  153945. -130,-130,-140,
  153946. };
  153947. /*** End of inlined file: psych_8.h ***/
  153948. /*** Start of inlined file: residue_8.h ***/
  153949. /***** residue backends *********************************************/
  153950. static static_bookblock _resbook_8s_0={
  153951. {
  153952. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  153953. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  153954. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  153955. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  153956. }
  153957. };
  153958. static static_bookblock _resbook_8s_1={
  153959. {
  153960. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  153961. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  153962. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  153963. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  153964. }
  153965. };
  153966. static vorbis_residue_template _res_8s_0[]={
  153967. {2,0, &_residue_44_mid,
  153968. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  153969. &_resbook_8s_0,&_resbook_8s_0},
  153970. };
  153971. static vorbis_residue_template _res_8s_1[]={
  153972. {2,0, &_residue_44_mid,
  153973. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  153974. &_resbook_8s_1,&_resbook_8s_1},
  153975. };
  153976. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  153977. { _map_nominal, _res_8s_0 }, /* 0 */
  153978. { _map_nominal, _res_8s_1 }, /* 1 */
  153979. };
  153980. static static_bookblock _resbook_8u_0={
  153981. {
  153982. {0},
  153983. {0,0,&_8u0__p1_0},
  153984. {0,0,&_8u0__p2_0},
  153985. {0,0,&_8u0__p3_0},
  153986. {0,0,&_8u0__p4_0},
  153987. {0,0,&_8u0__p5_0},
  153988. {&_8u0__p6_0,&_8u0__p6_1},
  153989. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  153990. }
  153991. };
  153992. static static_bookblock _resbook_8u_1={
  153993. {
  153994. {0},
  153995. {0,0,&_8u1__p1_0},
  153996. {0,0,&_8u1__p2_0},
  153997. {0,0,&_8u1__p3_0},
  153998. {0,0,&_8u1__p4_0},
  153999. {0,0,&_8u1__p5_0},
  154000. {0,0,&_8u1__p6_0},
  154001. {&_8u1__p7_0,&_8u1__p7_1},
  154002. {&_8u1__p8_0,&_8u1__p8_1},
  154003. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  154004. }
  154005. };
  154006. static vorbis_residue_template _res_8u_0[]={
  154007. {1,0, &_residue_44_low_un,
  154008. &_huff_book__8u0__single,&_huff_book__8u0__single,
  154009. &_resbook_8u_0,&_resbook_8u_0},
  154010. };
  154011. static vorbis_residue_template _res_8u_1[]={
  154012. {1,0, &_residue_44_mid_un,
  154013. &_huff_book__8u1__single,&_huff_book__8u1__single,
  154014. &_resbook_8u_1,&_resbook_8u_1},
  154015. };
  154016. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  154017. { _map_nominal_u, _res_8u_0 }, /* 0 */
  154018. { _map_nominal_u, _res_8u_1 }, /* 1 */
  154019. };
  154020. /*** End of inlined file: residue_8.h ***/
  154021. static int blocksize_8[2]={
  154022. 512,512
  154023. };
  154024. static int _floor_mapping_8[2]={
  154025. 6,6,
  154026. };
  154027. static double rate_mapping_8[3]={
  154028. 6000.,9000.,32000.,
  154029. };
  154030. static double rate_mapping_8_uncoupled[3]={
  154031. 8000.,14000.,42000.,
  154032. };
  154033. static double quality_mapping_8[3]={
  154034. -.1,.0,1.
  154035. };
  154036. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  154037. static double _global_mapping_8[3]={ 1., 2., 3. };
  154038. ve_setup_data_template ve_setup_8_stereo={
  154039. 2,
  154040. rate_mapping_8,
  154041. quality_mapping_8,
  154042. 2,
  154043. 8000,
  154044. 9000,
  154045. blocksize_8,
  154046. blocksize_8,
  154047. _psy_tone_masteratt_8,
  154048. _psy_tone_0dB,
  154049. _psy_tone_suppress,
  154050. _vp_tonemask_adj_8,
  154051. NULL,
  154052. _vp_tonemask_adj_8,
  154053. _psy_noiseguards_8,
  154054. _psy_noisebias_8,
  154055. _psy_noisebias_8,
  154056. NULL,
  154057. NULL,
  154058. _psy_noise_suppress,
  154059. _psy_compand_8,
  154060. _psy_compand_8_mapping,
  154061. NULL,
  154062. {_noise_start_8,_noise_start_8},
  154063. {_noise_part_8,_noise_part_8},
  154064. _noise_thresh_5only,
  154065. _psy_ath_floater_8,
  154066. _psy_ath_abs_8,
  154067. _psy_lowpass_8,
  154068. _psy_global_44,
  154069. _global_mapping_8,
  154070. _psy_stereo_modes_8,
  154071. _floor_books,
  154072. _floor,
  154073. _floor_mapping_8,
  154074. NULL,
  154075. _mapres_template_8_stereo
  154076. };
  154077. ve_setup_data_template ve_setup_8_uncoupled={
  154078. 2,
  154079. rate_mapping_8_uncoupled,
  154080. quality_mapping_8,
  154081. -1,
  154082. 8000,
  154083. 9000,
  154084. blocksize_8,
  154085. blocksize_8,
  154086. _psy_tone_masteratt_8,
  154087. _psy_tone_0dB,
  154088. _psy_tone_suppress,
  154089. _vp_tonemask_adj_8,
  154090. NULL,
  154091. _vp_tonemask_adj_8,
  154092. _psy_noiseguards_8,
  154093. _psy_noisebias_8,
  154094. _psy_noisebias_8,
  154095. NULL,
  154096. NULL,
  154097. _psy_noise_suppress,
  154098. _psy_compand_8,
  154099. _psy_compand_8_mapping,
  154100. NULL,
  154101. {_noise_start_8,_noise_start_8},
  154102. {_noise_part_8,_noise_part_8},
  154103. _noise_thresh_5only,
  154104. _psy_ath_floater_8,
  154105. _psy_ath_abs_8,
  154106. _psy_lowpass_8,
  154107. _psy_global_44,
  154108. _global_mapping_8,
  154109. _psy_stereo_modes_8,
  154110. _floor_books,
  154111. _floor,
  154112. _floor_mapping_8,
  154113. NULL,
  154114. _mapres_template_8_uncoupled
  154115. };
  154116. /*** End of inlined file: setup_8.h ***/
  154117. /*** Start of inlined file: setup_11.h ***/
  154118. /*** Start of inlined file: psych_11.h ***/
  154119. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154120. static att3 _psy_tone_masteratt_11[3]={
  154121. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154122. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154123. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154124. };
  154125. static vp_adjblock _vp_tonemask_adj_11[3]={
  154126. /* adjust for mode zero */
  154127. /* 63 125 250 500 1 2 4 8 16 */
  154128. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154129. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154130. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154131. };
  154132. static noise3 _psy_noisebias_11[3]={
  154133. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154134. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154135. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154136. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154137. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154138. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154139. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154140. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154141. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154142. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154143. };
  154144. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154145. /*** End of inlined file: psych_11.h ***/
  154146. static int blocksize_11[2]={
  154147. 512,512
  154148. };
  154149. static int _floor_mapping_11[2]={
  154150. 6,6,
  154151. };
  154152. static double rate_mapping_11[3]={
  154153. 8000.,13000.,44000.,
  154154. };
  154155. static double rate_mapping_11_uncoupled[3]={
  154156. 12000.,20000.,50000.,
  154157. };
  154158. static double quality_mapping_11[3]={
  154159. -.1,.0,1.
  154160. };
  154161. ve_setup_data_template ve_setup_11_stereo={
  154162. 2,
  154163. rate_mapping_11,
  154164. quality_mapping_11,
  154165. 2,
  154166. 9000,
  154167. 15000,
  154168. blocksize_11,
  154169. blocksize_11,
  154170. _psy_tone_masteratt_11,
  154171. _psy_tone_0dB,
  154172. _psy_tone_suppress,
  154173. _vp_tonemask_adj_11,
  154174. NULL,
  154175. _vp_tonemask_adj_11,
  154176. _psy_noiseguards_8,
  154177. _psy_noisebias_11,
  154178. _psy_noisebias_11,
  154179. NULL,
  154180. NULL,
  154181. _psy_noise_suppress,
  154182. _psy_compand_8,
  154183. _psy_compand_8_mapping,
  154184. NULL,
  154185. {_noise_start_8,_noise_start_8},
  154186. {_noise_part_8,_noise_part_8},
  154187. _noise_thresh_11,
  154188. _psy_ath_floater_8,
  154189. _psy_ath_abs_8,
  154190. _psy_lowpass_11,
  154191. _psy_global_44,
  154192. _global_mapping_8,
  154193. _psy_stereo_modes_8,
  154194. _floor_books,
  154195. _floor,
  154196. _floor_mapping_11,
  154197. NULL,
  154198. _mapres_template_8_stereo
  154199. };
  154200. ve_setup_data_template ve_setup_11_uncoupled={
  154201. 2,
  154202. rate_mapping_11_uncoupled,
  154203. quality_mapping_11,
  154204. -1,
  154205. 9000,
  154206. 15000,
  154207. blocksize_11,
  154208. blocksize_11,
  154209. _psy_tone_masteratt_11,
  154210. _psy_tone_0dB,
  154211. _psy_tone_suppress,
  154212. _vp_tonemask_adj_11,
  154213. NULL,
  154214. _vp_tonemask_adj_11,
  154215. _psy_noiseguards_8,
  154216. _psy_noisebias_11,
  154217. _psy_noisebias_11,
  154218. NULL,
  154219. NULL,
  154220. _psy_noise_suppress,
  154221. _psy_compand_8,
  154222. _psy_compand_8_mapping,
  154223. NULL,
  154224. {_noise_start_8,_noise_start_8},
  154225. {_noise_part_8,_noise_part_8},
  154226. _noise_thresh_11,
  154227. _psy_ath_floater_8,
  154228. _psy_ath_abs_8,
  154229. _psy_lowpass_11,
  154230. _psy_global_44,
  154231. _global_mapping_8,
  154232. _psy_stereo_modes_8,
  154233. _floor_books,
  154234. _floor,
  154235. _floor_mapping_11,
  154236. NULL,
  154237. _mapres_template_8_uncoupled
  154238. };
  154239. /*** End of inlined file: setup_11.h ***/
  154240. /*** Start of inlined file: setup_16.h ***/
  154241. /*** Start of inlined file: psych_16.h ***/
  154242. /* stereo mode by base quality level */
  154243. static adj_stereo _psy_stereo_modes_16[4]={
  154244. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154245. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154246. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154247. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154248. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154249. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154250. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154251. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154252. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154253. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154254. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154255. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154256. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154257. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154258. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154259. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154260. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154261. };
  154262. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154263. static att3 _psy_tone_masteratt_16[4]={
  154264. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154265. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154266. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154267. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154268. };
  154269. static vp_adjblock _vp_tonemask_adj_16[4]={
  154270. /* adjust for mode zero */
  154271. /* 63 125 250 500 1 2 4 8 16 */
  154272. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154273. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154274. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154275. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154276. };
  154277. static noise3 _psy_noisebias_16_short[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, 6, 6, 6, 6, 8, 10, 12, 20},
  154283. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  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, 2, 4, 4, 5, 5, 5, 8, 12},
  154286. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 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,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  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_impulse[4]={
  154293. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154294. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154295. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154296. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154297. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154298. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154299. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154300. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154301. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -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,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154305. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154306. };
  154307. static noise3 _psy_noisebias_16[4]={
  154308. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154309. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154310. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154311. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154312. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154313. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154314. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154315. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154316. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154317. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154318. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154319. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154320. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154321. };
  154322. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154323. static int _noise_start_16[3]={ 256,256,9999 };
  154324. static int _noise_part_16[4]={ 8,8,8,8 };
  154325. static int _psy_ath_floater_16[4]={
  154326. -100,-100,-100,-105,
  154327. };
  154328. static int _psy_ath_abs_16[4]={
  154329. -130,-130,-130,-140,
  154330. };
  154331. /*** End of inlined file: psych_16.h ***/
  154332. /*** Start of inlined file: residue_16.h ***/
  154333. /***** residue backends *********************************************/
  154334. static static_bookblock _resbook_16s_0={
  154335. {
  154336. {0},
  154337. {0,0,&_16c0_s_p1_0},
  154338. {0,0,&_16c0_s_p2_0},
  154339. {0,0,&_16c0_s_p3_0},
  154340. {0,0,&_16c0_s_p4_0},
  154341. {0,0,&_16c0_s_p5_0},
  154342. {0,0,&_16c0_s_p6_0},
  154343. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154344. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154345. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154346. }
  154347. };
  154348. static static_bookblock _resbook_16s_1={
  154349. {
  154350. {0},
  154351. {0,0,&_16c1_s_p1_0},
  154352. {0,0,&_16c1_s_p2_0},
  154353. {0,0,&_16c1_s_p3_0},
  154354. {0,0,&_16c1_s_p4_0},
  154355. {0,0,&_16c1_s_p5_0},
  154356. {0,0,&_16c1_s_p6_0},
  154357. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154358. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154359. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154360. }
  154361. };
  154362. static static_bookblock _resbook_16s_2={
  154363. {
  154364. {0},
  154365. {0,0,&_16c2_s_p1_0},
  154366. {0,0,&_16c2_s_p2_0},
  154367. {0,0,&_16c2_s_p3_0},
  154368. {0,0,&_16c2_s_p4_0},
  154369. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154370. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154371. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154372. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154373. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154374. }
  154375. };
  154376. static vorbis_residue_template _res_16s_0[]={
  154377. {2,0, &_residue_44_mid,
  154378. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154379. &_resbook_16s_0,&_resbook_16s_0},
  154380. };
  154381. static vorbis_residue_template _res_16s_1[]={
  154382. {2,0, &_residue_44_mid,
  154383. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154384. &_resbook_16s_1,&_resbook_16s_1},
  154385. {2,0, &_residue_44_mid,
  154386. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154387. &_resbook_16s_1,&_resbook_16s_1}
  154388. };
  154389. static vorbis_residue_template _res_16s_2[]={
  154390. {2,0, &_residue_44_high,
  154391. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154392. &_resbook_16s_2,&_resbook_16s_2},
  154393. {2,0, &_residue_44_high,
  154394. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154395. &_resbook_16s_2,&_resbook_16s_2}
  154396. };
  154397. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154398. { _map_nominal, _res_16s_0 }, /* 0 */
  154399. { _map_nominal, _res_16s_1 }, /* 1 */
  154400. { _map_nominal, _res_16s_2 }, /* 2 */
  154401. };
  154402. static static_bookblock _resbook_16u_0={
  154403. {
  154404. {0},
  154405. {0,0,&_16u0__p1_0},
  154406. {0,0,&_16u0__p2_0},
  154407. {0,0,&_16u0__p3_0},
  154408. {0,0,&_16u0__p4_0},
  154409. {0,0,&_16u0__p5_0},
  154410. {&_16u0__p6_0,&_16u0__p6_1},
  154411. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154412. }
  154413. };
  154414. static static_bookblock _resbook_16u_1={
  154415. {
  154416. {0},
  154417. {0,0,&_16u1__p1_0},
  154418. {0,0,&_16u1__p2_0},
  154419. {0,0,&_16u1__p3_0},
  154420. {0,0,&_16u1__p4_0},
  154421. {0,0,&_16u1__p5_0},
  154422. {0,0,&_16u1__p6_0},
  154423. {&_16u1__p7_0,&_16u1__p7_1},
  154424. {&_16u1__p8_0,&_16u1__p8_1},
  154425. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154426. }
  154427. };
  154428. static static_bookblock _resbook_16u_2={
  154429. {
  154430. {0},
  154431. {0,0,&_16u2_p1_0},
  154432. {0,0,&_16u2_p2_0},
  154433. {0,0,&_16u2_p3_0},
  154434. {0,0,&_16u2_p4_0},
  154435. {&_16u2_p5_0,&_16u2_p5_1},
  154436. {&_16u2_p6_0,&_16u2_p6_1},
  154437. {&_16u2_p7_0,&_16u2_p7_1},
  154438. {&_16u2_p8_0,&_16u2_p8_1},
  154439. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154440. }
  154441. };
  154442. static vorbis_residue_template _res_16u_0[]={
  154443. {1,0, &_residue_44_low_un,
  154444. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154445. &_resbook_16u_0,&_resbook_16u_0},
  154446. };
  154447. static vorbis_residue_template _res_16u_1[]={
  154448. {1,0, &_residue_44_mid_un,
  154449. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154450. &_resbook_16u_1,&_resbook_16u_1},
  154451. {1,0, &_residue_44_mid_un,
  154452. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154453. &_resbook_16u_1,&_resbook_16u_1}
  154454. };
  154455. static vorbis_residue_template _res_16u_2[]={
  154456. {1,0, &_residue_44_hi_un,
  154457. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154458. &_resbook_16u_2,&_resbook_16u_2},
  154459. {1,0, &_residue_44_hi_un,
  154460. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154461. &_resbook_16u_2,&_resbook_16u_2}
  154462. };
  154463. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154464. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154465. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154466. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154467. };
  154468. /*** End of inlined file: residue_16.h ***/
  154469. static int blocksize_16_short[3]={
  154470. 1024,512,512
  154471. };
  154472. static int blocksize_16_long[3]={
  154473. 1024,1024,1024
  154474. };
  154475. static int _floor_mapping_16_short[3]={
  154476. 9,3,3
  154477. };
  154478. static int _floor_mapping_16[3]={
  154479. 9,9,9
  154480. };
  154481. static double rate_mapping_16[4]={
  154482. 12000.,20000.,44000.,86000.
  154483. };
  154484. static double rate_mapping_16_uncoupled[4]={
  154485. 16000.,28000.,64000.,100000.
  154486. };
  154487. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154488. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154489. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154490. ve_setup_data_template ve_setup_16_stereo={
  154491. 3,
  154492. rate_mapping_16,
  154493. quality_mapping_16,
  154494. 2,
  154495. 15000,
  154496. 19000,
  154497. blocksize_16_short,
  154498. blocksize_16_long,
  154499. _psy_tone_masteratt_16,
  154500. _psy_tone_0dB,
  154501. _psy_tone_suppress,
  154502. _vp_tonemask_adj_16,
  154503. _vp_tonemask_adj_16,
  154504. _vp_tonemask_adj_16,
  154505. _psy_noiseguards_8,
  154506. _psy_noisebias_16_impulse,
  154507. _psy_noisebias_16_short,
  154508. _psy_noisebias_16_short,
  154509. _psy_noisebias_16,
  154510. _psy_noise_suppress,
  154511. _psy_compand_8,
  154512. _psy_compand_16_mapping,
  154513. _psy_compand_16_mapping,
  154514. {_noise_start_16,_noise_start_16},
  154515. { _noise_part_16, _noise_part_16},
  154516. _noise_thresh_16,
  154517. _psy_ath_floater_16,
  154518. _psy_ath_abs_16,
  154519. _psy_lowpass_16,
  154520. _psy_global_44,
  154521. _global_mapping_16,
  154522. _psy_stereo_modes_16,
  154523. _floor_books,
  154524. _floor,
  154525. _floor_mapping_16_short,
  154526. _floor_mapping_16,
  154527. _mapres_template_16_stereo
  154528. };
  154529. ve_setup_data_template ve_setup_16_uncoupled={
  154530. 3,
  154531. rate_mapping_16_uncoupled,
  154532. quality_mapping_16,
  154533. -1,
  154534. 15000,
  154535. 19000,
  154536. blocksize_16_short,
  154537. blocksize_16_long,
  154538. _psy_tone_masteratt_16,
  154539. _psy_tone_0dB,
  154540. _psy_tone_suppress,
  154541. _vp_tonemask_adj_16,
  154542. _vp_tonemask_adj_16,
  154543. _vp_tonemask_adj_16,
  154544. _psy_noiseguards_8,
  154545. _psy_noisebias_16_impulse,
  154546. _psy_noisebias_16_short,
  154547. _psy_noisebias_16_short,
  154548. _psy_noisebias_16,
  154549. _psy_noise_suppress,
  154550. _psy_compand_8,
  154551. _psy_compand_16_mapping,
  154552. _psy_compand_16_mapping,
  154553. {_noise_start_16,_noise_start_16},
  154554. { _noise_part_16, _noise_part_16},
  154555. _noise_thresh_16,
  154556. _psy_ath_floater_16,
  154557. _psy_ath_abs_16,
  154558. _psy_lowpass_16,
  154559. _psy_global_44,
  154560. _global_mapping_16,
  154561. _psy_stereo_modes_16,
  154562. _floor_books,
  154563. _floor,
  154564. _floor_mapping_16_short,
  154565. _floor_mapping_16,
  154566. _mapres_template_16_uncoupled
  154567. };
  154568. /*** End of inlined file: setup_16.h ***/
  154569. /*** Start of inlined file: setup_22.h ***/
  154570. static double rate_mapping_22[4]={
  154571. 15000.,20000.,44000.,86000.
  154572. };
  154573. static double rate_mapping_22_uncoupled[4]={
  154574. 16000.,28000.,50000.,90000.
  154575. };
  154576. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  154577. ve_setup_data_template ve_setup_22_stereo={
  154578. 3,
  154579. rate_mapping_22,
  154580. quality_mapping_16,
  154581. 2,
  154582. 19000,
  154583. 26000,
  154584. blocksize_16_short,
  154585. blocksize_16_long,
  154586. _psy_tone_masteratt_16,
  154587. _psy_tone_0dB,
  154588. _psy_tone_suppress,
  154589. _vp_tonemask_adj_16,
  154590. _vp_tonemask_adj_16,
  154591. _vp_tonemask_adj_16,
  154592. _psy_noiseguards_8,
  154593. _psy_noisebias_16_impulse,
  154594. _psy_noisebias_16_short,
  154595. _psy_noisebias_16_short,
  154596. _psy_noisebias_16,
  154597. _psy_noise_suppress,
  154598. _psy_compand_8,
  154599. _psy_compand_8_mapping,
  154600. _psy_compand_8_mapping,
  154601. {_noise_start_16,_noise_start_16},
  154602. { _noise_part_16, _noise_part_16},
  154603. _noise_thresh_16,
  154604. _psy_ath_floater_16,
  154605. _psy_ath_abs_16,
  154606. _psy_lowpass_22,
  154607. _psy_global_44,
  154608. _global_mapping_16,
  154609. _psy_stereo_modes_16,
  154610. _floor_books,
  154611. _floor,
  154612. _floor_mapping_16_short,
  154613. _floor_mapping_16,
  154614. _mapres_template_16_stereo
  154615. };
  154616. ve_setup_data_template ve_setup_22_uncoupled={
  154617. 3,
  154618. rate_mapping_22_uncoupled,
  154619. quality_mapping_16,
  154620. -1,
  154621. 19000,
  154622. 26000,
  154623. blocksize_16_short,
  154624. blocksize_16_long,
  154625. _psy_tone_masteratt_16,
  154626. _psy_tone_0dB,
  154627. _psy_tone_suppress,
  154628. _vp_tonemask_adj_16,
  154629. _vp_tonemask_adj_16,
  154630. _vp_tonemask_adj_16,
  154631. _psy_noiseguards_8,
  154632. _psy_noisebias_16_impulse,
  154633. _psy_noisebias_16_short,
  154634. _psy_noisebias_16_short,
  154635. _psy_noisebias_16,
  154636. _psy_noise_suppress,
  154637. _psy_compand_8,
  154638. _psy_compand_8_mapping,
  154639. _psy_compand_8_mapping,
  154640. {_noise_start_16,_noise_start_16},
  154641. { _noise_part_16, _noise_part_16},
  154642. _noise_thresh_16,
  154643. _psy_ath_floater_16,
  154644. _psy_ath_abs_16,
  154645. _psy_lowpass_22,
  154646. _psy_global_44,
  154647. _global_mapping_16,
  154648. _psy_stereo_modes_16,
  154649. _floor_books,
  154650. _floor,
  154651. _floor_mapping_16_short,
  154652. _floor_mapping_16,
  154653. _mapres_template_16_uncoupled
  154654. };
  154655. /*** End of inlined file: setup_22.h ***/
  154656. /*** Start of inlined file: setup_X.h ***/
  154657. static double rate_mapping_X[12]={
  154658. -1.,-1.,-1.,-1.,-1.,-1.,
  154659. -1.,-1.,-1.,-1.,-1.,-1.
  154660. };
  154661. ve_setup_data_template ve_setup_X_stereo={
  154662. 11,
  154663. rate_mapping_X,
  154664. quality_mapping_44,
  154665. 2,
  154666. 50000,
  154667. 200000,
  154668. blocksize_short_44,
  154669. blocksize_long_44,
  154670. _psy_tone_masteratt_44,
  154671. _psy_tone_0dB,
  154672. _psy_tone_suppress,
  154673. _vp_tonemask_adj_otherblock,
  154674. _vp_tonemask_adj_longblock,
  154675. _vp_tonemask_adj_otherblock,
  154676. _psy_noiseguards_44,
  154677. _psy_noisebias_impulse,
  154678. _psy_noisebias_padding,
  154679. _psy_noisebias_trans,
  154680. _psy_noisebias_long,
  154681. _psy_noise_suppress,
  154682. _psy_compand_44,
  154683. _psy_compand_short_mapping,
  154684. _psy_compand_long_mapping,
  154685. {_noise_start_short_44,_noise_start_long_44},
  154686. {_noise_part_short_44,_noise_part_long_44},
  154687. _noise_thresh_44,
  154688. _psy_ath_floater,
  154689. _psy_ath_abs,
  154690. _psy_lowpass_44,
  154691. _psy_global_44,
  154692. _global_mapping_44,
  154693. _psy_stereo_modes_44,
  154694. _floor_books,
  154695. _floor,
  154696. _floor_short_mapping_44,
  154697. _floor_long_mapping_44,
  154698. _mapres_template_44_stereo
  154699. };
  154700. ve_setup_data_template ve_setup_X_uncoupled={
  154701. 11,
  154702. rate_mapping_X,
  154703. quality_mapping_44,
  154704. -1,
  154705. 50000,
  154706. 200000,
  154707. blocksize_short_44,
  154708. blocksize_long_44,
  154709. _psy_tone_masteratt_44,
  154710. _psy_tone_0dB,
  154711. _psy_tone_suppress,
  154712. _vp_tonemask_adj_otherblock,
  154713. _vp_tonemask_adj_longblock,
  154714. _vp_tonemask_adj_otherblock,
  154715. _psy_noiseguards_44,
  154716. _psy_noisebias_impulse,
  154717. _psy_noisebias_padding,
  154718. _psy_noisebias_trans,
  154719. _psy_noisebias_long,
  154720. _psy_noise_suppress,
  154721. _psy_compand_44,
  154722. _psy_compand_short_mapping,
  154723. _psy_compand_long_mapping,
  154724. {_noise_start_short_44,_noise_start_long_44},
  154725. {_noise_part_short_44,_noise_part_long_44},
  154726. _noise_thresh_44,
  154727. _psy_ath_floater,
  154728. _psy_ath_abs,
  154729. _psy_lowpass_44,
  154730. _psy_global_44,
  154731. _global_mapping_44,
  154732. NULL,
  154733. _floor_books,
  154734. _floor,
  154735. _floor_short_mapping_44,
  154736. _floor_long_mapping_44,
  154737. _mapres_template_44_uncoupled
  154738. };
  154739. ve_setup_data_template ve_setup_XX_stereo={
  154740. 2,
  154741. rate_mapping_X,
  154742. quality_mapping_8,
  154743. 2,
  154744. 0,
  154745. 8000,
  154746. blocksize_8,
  154747. blocksize_8,
  154748. _psy_tone_masteratt_8,
  154749. _psy_tone_0dB,
  154750. _psy_tone_suppress,
  154751. _vp_tonemask_adj_8,
  154752. NULL,
  154753. _vp_tonemask_adj_8,
  154754. _psy_noiseguards_8,
  154755. _psy_noisebias_8,
  154756. _psy_noisebias_8,
  154757. NULL,
  154758. NULL,
  154759. _psy_noise_suppress,
  154760. _psy_compand_8,
  154761. _psy_compand_8_mapping,
  154762. NULL,
  154763. {_noise_start_8,_noise_start_8},
  154764. {_noise_part_8,_noise_part_8},
  154765. _noise_thresh_5only,
  154766. _psy_ath_floater_8,
  154767. _psy_ath_abs_8,
  154768. _psy_lowpass_8,
  154769. _psy_global_44,
  154770. _global_mapping_8,
  154771. _psy_stereo_modes_8,
  154772. _floor_books,
  154773. _floor,
  154774. _floor_mapping_8,
  154775. NULL,
  154776. _mapres_template_8_stereo
  154777. };
  154778. ve_setup_data_template ve_setup_XX_uncoupled={
  154779. 2,
  154780. rate_mapping_X,
  154781. quality_mapping_8,
  154782. -1,
  154783. 0,
  154784. 8000,
  154785. blocksize_8,
  154786. blocksize_8,
  154787. _psy_tone_masteratt_8,
  154788. _psy_tone_0dB,
  154789. _psy_tone_suppress,
  154790. _vp_tonemask_adj_8,
  154791. NULL,
  154792. _vp_tonemask_adj_8,
  154793. _psy_noiseguards_8,
  154794. _psy_noisebias_8,
  154795. _psy_noisebias_8,
  154796. NULL,
  154797. NULL,
  154798. _psy_noise_suppress,
  154799. _psy_compand_8,
  154800. _psy_compand_8_mapping,
  154801. NULL,
  154802. {_noise_start_8,_noise_start_8},
  154803. {_noise_part_8,_noise_part_8},
  154804. _noise_thresh_5only,
  154805. _psy_ath_floater_8,
  154806. _psy_ath_abs_8,
  154807. _psy_lowpass_8,
  154808. _psy_global_44,
  154809. _global_mapping_8,
  154810. _psy_stereo_modes_8,
  154811. _floor_books,
  154812. _floor,
  154813. _floor_mapping_8,
  154814. NULL,
  154815. _mapres_template_8_uncoupled
  154816. };
  154817. /*** End of inlined file: setup_X.h ***/
  154818. static ve_setup_data_template *setup_list[]={
  154819. &ve_setup_44_stereo,
  154820. &ve_setup_44_uncoupled,
  154821. &ve_setup_32_stereo,
  154822. &ve_setup_32_uncoupled,
  154823. &ve_setup_22_stereo,
  154824. &ve_setup_22_uncoupled,
  154825. &ve_setup_16_stereo,
  154826. &ve_setup_16_uncoupled,
  154827. &ve_setup_11_stereo,
  154828. &ve_setup_11_uncoupled,
  154829. &ve_setup_8_stereo,
  154830. &ve_setup_8_uncoupled,
  154831. &ve_setup_X_stereo,
  154832. &ve_setup_X_uncoupled,
  154833. &ve_setup_XX_stereo,
  154834. &ve_setup_XX_uncoupled,
  154835. 0
  154836. };
  154837. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  154838. if(vi && vi->codec_setup){
  154839. vi->version=0;
  154840. vi->channels=ch;
  154841. vi->rate=rate;
  154842. return(0);
  154843. }
  154844. return(OV_EINVAL);
  154845. }
  154846. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  154847. static_codebook ***books,
  154848. vorbis_info_floor1 *in,
  154849. int *x){
  154850. int i,k,is=s;
  154851. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  154852. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154853. memcpy(f,in+x[is],sizeof(*f));
  154854. /* fill in the lowpass field, even if it's temporary */
  154855. f->n=ci->blocksizes[block]>>1;
  154856. /* books */
  154857. {
  154858. int partitions=f->partitions;
  154859. int maxclass=-1;
  154860. int maxbook=-1;
  154861. for(i=0;i<partitions;i++)
  154862. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  154863. for(i=0;i<=maxclass;i++){
  154864. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  154865. f->class_book[i]+=ci->books;
  154866. for(k=0;k<(1<<f->class_subs[i]);k++){
  154867. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  154868. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  154869. }
  154870. }
  154871. for(i=0;i<=maxbook;i++)
  154872. ci->book_param[ci->books++]=books[x[is]][i];
  154873. }
  154874. /* for now, we're only using floor 1 */
  154875. ci->floor_type[ci->floors]=1;
  154876. ci->floor_param[ci->floors]=f;
  154877. ci->floors++;
  154878. return;
  154879. }
  154880. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  154881. vorbis_info_psy_global *in,
  154882. double *x){
  154883. int i,is=s;
  154884. double ds=s-is;
  154885. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154886. vorbis_info_psy_global *g=&ci->psy_g_param;
  154887. memcpy(g,in+(int)x[is],sizeof(*g));
  154888. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154889. is=(int)ds;
  154890. ds-=is;
  154891. if(ds==0 && is>0){
  154892. is--;
  154893. ds=1.;
  154894. }
  154895. /* interpolate the trigger threshholds */
  154896. for(i=0;i<4;i++){
  154897. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  154898. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  154899. }
  154900. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  154901. return;
  154902. }
  154903. static void vorbis_encode_global_stereo(vorbis_info *vi,
  154904. highlevel_encode_setup *hi,
  154905. adj_stereo *p){
  154906. float s=hi->stereo_point_setting;
  154907. int i,is=s;
  154908. double ds=s-is;
  154909. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154910. vorbis_info_psy_global *g=&ci->psy_g_param;
  154911. if(p){
  154912. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  154913. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  154914. if(hi->managed){
  154915. /* interpolate the kHz threshholds */
  154916. for(i=0;i<PACKETBLOBS;i++){
  154917. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  154918. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154919. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154920. g->coupling_pkHz[i]=kHz;
  154921. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  154922. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154923. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154924. }
  154925. }else{
  154926. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  154927. for(i=0;i<PACKETBLOBS;i++){
  154928. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154929. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154930. g->coupling_pkHz[i]=kHz;
  154931. }
  154932. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  154933. for(i=0;i<PACKETBLOBS;i++){
  154934. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  154935. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  154936. }
  154937. }
  154938. }else{
  154939. for(i=0;i<PACKETBLOBS;i++){
  154940. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  154941. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  154942. }
  154943. }
  154944. return;
  154945. }
  154946. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  154947. int *nn_start,
  154948. int *nn_partition,
  154949. double *nn_thresh,
  154950. int block){
  154951. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154952. vorbis_info_psy *p=ci->psy_param[block];
  154953. highlevel_encode_setup *hi=&ci->hi;
  154954. int is=s;
  154955. if(block>=ci->psys)
  154956. ci->psys=block+1;
  154957. if(!p){
  154958. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  154959. ci->psy_param[block]=p;
  154960. }
  154961. memcpy(p,&_psy_info_template,sizeof(*p));
  154962. p->blockflag=block>>1;
  154963. if(hi->noise_normalize_p){
  154964. p->normal_channel_p=1;
  154965. p->normal_point_p=1;
  154966. p->normal_start=nn_start[is];
  154967. p->normal_partition=nn_partition[is];
  154968. p->normal_thresh=nn_thresh[is];
  154969. }
  154970. return;
  154971. }
  154972. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  154973. att3 *att,
  154974. int *max,
  154975. vp_adjblock *in){
  154976. int i,is=s;
  154977. double ds=s-is;
  154978. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  154979. vorbis_info_psy *p=ci->psy_param[block];
  154980. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  154981. filling the values in here */
  154982. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  154983. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  154984. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  154985. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  154986. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  154987. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  154988. for(i=0;i<P_BANDS;i++)
  154989. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  154990. return;
  154991. }
  154992. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  154993. compandblock *in, double *x){
  154994. int i,is=s;
  154995. double ds=s-is;
  154996. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  154997. vorbis_info_psy *p=ci->psy_param[block];
  154998. ds=x[is]*(1.-ds)+x[is+1]*ds;
  154999. is=(int)ds;
  155000. ds-=is;
  155001. if(ds==0 && is>0){
  155002. is--;
  155003. ds=1.;
  155004. }
  155005. /* interpolate the compander settings */
  155006. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  155007. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  155008. return;
  155009. }
  155010. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  155011. int *suppress){
  155012. int is=s;
  155013. double ds=s-is;
  155014. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155015. vorbis_info_psy *p=ci->psy_param[block];
  155016. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155017. return;
  155018. }
  155019. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  155020. int *suppress,
  155021. noise3 *in,
  155022. noiseguard *guard,
  155023. double userbias){
  155024. int i,is=s,j;
  155025. double ds=s-is;
  155026. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155027. vorbis_info_psy *p=ci->psy_param[block];
  155028. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155029. p->noisewindowlomin=guard[block].lo;
  155030. p->noisewindowhimin=guard[block].hi;
  155031. p->noisewindowfixed=guard[block].fixed;
  155032. for(j=0;j<P_NOISECURVES;j++)
  155033. for(i=0;i<P_BANDS;i++)
  155034. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  155035. /* impulse blocks may take a user specified bias to boost the
  155036. nominal/high noise encoding depth */
  155037. for(j=0;j<P_NOISECURVES;j++){
  155038. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  155039. for(i=0;i<P_BANDS;i++){
  155040. p->noiseoff[j][i]+=userbias;
  155041. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155042. }
  155043. }
  155044. return;
  155045. }
  155046. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155047. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155048. vorbis_info_psy *p=ci->psy_param[block];
  155049. p->ath_adjatt=ci->hi.ath_floating_dB;
  155050. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155051. return;
  155052. }
  155053. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155054. int i;
  155055. for(i=0;i<ci->books;i++)
  155056. if(ci->book_param[i]==book)return(i);
  155057. return(ci->books++);
  155058. }
  155059. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155060. int *shortb,int *longb){
  155061. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155062. int is=s;
  155063. int blockshort=shortb[is];
  155064. int blocklong=longb[is];
  155065. ci->blocksizes[0]=blockshort;
  155066. ci->blocksizes[1]=blocklong;
  155067. }
  155068. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155069. int number, int block,
  155070. vorbis_residue_template *res){
  155071. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155072. int i,n;
  155073. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155074. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155075. memcpy(r,res->res,sizeof(*r));
  155076. if(ci->residues<=number)ci->residues=number+1;
  155077. switch(ci->blocksizes[block]){
  155078. case 64:case 128:case 256:
  155079. r->grouping=16;
  155080. break;
  155081. default:
  155082. r->grouping=32;
  155083. break;
  155084. }
  155085. ci->residue_type[number]=res->res_type;
  155086. /* to be adjusted by lowpass/pointlimit later */
  155087. n=r->end=ci->blocksizes[block]>>1;
  155088. if(res->res_type==2)
  155089. n=r->end*=vi->channels;
  155090. /* fill in all the books */
  155091. {
  155092. int booklist=0,k;
  155093. if(ci->hi.managed){
  155094. for(i=0;i<r->partitions;i++)
  155095. for(k=0;k<3;k++)
  155096. if(res->books_base_managed->books[i][k])
  155097. r->secondstages[i]|=(1<<k);
  155098. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155099. ci->book_param[r->groupbook]=res->book_aux_managed;
  155100. for(i=0;i<r->partitions;i++){
  155101. for(k=0;k<3;k++){
  155102. if(res->books_base_managed->books[i][k]){
  155103. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155104. r->booklist[booklist++]=bookid;
  155105. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155106. }
  155107. }
  155108. }
  155109. }else{
  155110. for(i=0;i<r->partitions;i++)
  155111. for(k=0;k<3;k++)
  155112. if(res->books_base->books[i][k])
  155113. r->secondstages[i]|=(1<<k);
  155114. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155115. ci->book_param[r->groupbook]=res->book_aux;
  155116. for(i=0;i<r->partitions;i++){
  155117. for(k=0;k<3;k++){
  155118. if(res->books_base->books[i][k]){
  155119. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155120. r->booklist[booklist++]=bookid;
  155121. ci->book_param[bookid]=res->books_base->books[i][k];
  155122. }
  155123. }
  155124. }
  155125. }
  155126. }
  155127. /* lowpass setup/pointlimit */
  155128. {
  155129. double freq=ci->hi.lowpass_kHz*1000.;
  155130. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155131. double nyq=vi->rate/2.;
  155132. long blocksize=ci->blocksizes[block]>>1;
  155133. /* lowpass needs to be set in the floor and the residue. */
  155134. if(freq>nyq)freq=nyq;
  155135. /* in the floor, the granularity can be very fine; it doesn't alter
  155136. the encoding structure, only the samples used to fit the floor
  155137. approximation */
  155138. f->n=freq/nyq*blocksize;
  155139. /* this res may by limited by the maximum pointlimit of the mode,
  155140. not the lowpass. the floor is always lowpass limited. */
  155141. if(res->limit_type){
  155142. if(ci->hi.managed)
  155143. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155144. else
  155145. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155146. if(freq>nyq)freq=nyq;
  155147. }
  155148. /* in the residue, we're constrained, physically, by partition
  155149. boundaries. We still lowpass 'wherever', but we have to round up
  155150. here to next boundary, or the vorbis spec will round it *down* to
  155151. previous boundary in encode/decode */
  155152. if(ci->residue_type[block]==2)
  155153. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155154. r->grouping;
  155155. else
  155156. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155157. r->grouping;
  155158. }
  155159. }
  155160. /* we assume two maps in this encoder */
  155161. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155162. vorbis_mapping_template *maps){
  155163. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155164. int i,j,is=s,modes=2;
  155165. vorbis_info_mapping0 *map=maps[is].map;
  155166. vorbis_info_mode *mode=_mode_template;
  155167. vorbis_residue_template *res=maps[is].res;
  155168. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155169. for(i=0;i<modes;i++){
  155170. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155171. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155172. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155173. if(i>=ci->modes)ci->modes=i+1;
  155174. ci->map_type[i]=0;
  155175. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155176. if(i>=ci->maps)ci->maps=i+1;
  155177. for(j=0;j<map[i].submaps;j++)
  155178. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155179. ,res+map[i].residuesubmap[j]);
  155180. }
  155181. }
  155182. static double setting_to_approx_bitrate(vorbis_info *vi){
  155183. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155184. highlevel_encode_setup *hi=&ci->hi;
  155185. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155186. int is=hi->base_setting;
  155187. double ds=hi->base_setting-is;
  155188. int ch=vi->channels;
  155189. double *r=setup->rate_mapping;
  155190. if(r==NULL)
  155191. return(-1);
  155192. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155193. }
  155194. static void get_setup_template(vorbis_info *vi,
  155195. long ch,long srate,
  155196. double req,int q_or_bitrate){
  155197. int i=0,j;
  155198. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155199. highlevel_encode_setup *hi=&ci->hi;
  155200. if(q_or_bitrate)req/=ch;
  155201. while(setup_list[i]){
  155202. if(setup_list[i]->coupling_restriction==-1 ||
  155203. setup_list[i]->coupling_restriction==ch){
  155204. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155205. srate<=setup_list[i]->samplerate_max_restriction){
  155206. int mappings=setup_list[i]->mappings;
  155207. double *map=(q_or_bitrate?
  155208. setup_list[i]->rate_mapping:
  155209. setup_list[i]->quality_mapping);
  155210. /* the template matches. Does the requested quality mode
  155211. fall within this template's modes? */
  155212. if(req<map[0]){++i;continue;}
  155213. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155214. for(j=0;j<mappings;j++)
  155215. if(req>=map[j] && req<map[j+1])break;
  155216. /* an all-points match */
  155217. hi->setup=setup_list[i];
  155218. if(j==mappings)
  155219. hi->base_setting=j-.001;
  155220. else{
  155221. float low=map[j];
  155222. float high=map[j+1];
  155223. float del=(req-low)/(high-low);
  155224. hi->base_setting=j+del;
  155225. }
  155226. return;
  155227. }
  155228. }
  155229. i++;
  155230. }
  155231. hi->setup=NULL;
  155232. }
  155233. /* encoders will need to use vorbis_info_init beforehand and call
  155234. vorbis_info clear when all done */
  155235. /* two interfaces; this, more detailed one, and later a convenience
  155236. layer on top */
  155237. /* the final setup call */
  155238. int vorbis_encode_setup_init(vorbis_info *vi){
  155239. int i0=0,singleblock=0;
  155240. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155241. ve_setup_data_template *setup=NULL;
  155242. highlevel_encode_setup *hi=&ci->hi;
  155243. if(ci==NULL)return(OV_EINVAL);
  155244. if(!hi->impulse_block_p)i0=1;
  155245. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155246. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155247. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155248. /* again, bound this to avoid the app shooting itself int he foot
  155249. too badly */
  155250. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155251. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155252. /* get the appropriate setup template; matches the fetch in previous
  155253. stages */
  155254. setup=(ve_setup_data_template *)hi->setup;
  155255. if(setup==NULL)return(OV_EINVAL);
  155256. hi->set_in_stone=1;
  155257. /* choose block sizes from configured sizes as well as paying
  155258. attention to long_block_p and short_block_p. If the configured
  155259. short and long blocks are the same length, we set long_block_p
  155260. and unset short_block_p */
  155261. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155262. setup->blocksize_short,
  155263. setup->blocksize_long);
  155264. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155265. /* floor setup; choose proper floor params. Allocated on the floor
  155266. stack in order; if we alloc only long floor, it's 0 */
  155267. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155268. setup->floor_books,
  155269. setup->floor_params,
  155270. setup->floor_short_mapping);
  155271. if(!singleblock)
  155272. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155273. setup->floor_books,
  155274. setup->floor_params,
  155275. setup->floor_long_mapping);
  155276. /* setup of [mostly] short block detection and stereo*/
  155277. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155278. setup->global_params,
  155279. setup->global_mapping);
  155280. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155281. /* basic psych setup and noise normalization */
  155282. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155283. setup->psy_noise_normal_start[0],
  155284. setup->psy_noise_normal_partition[0],
  155285. setup->psy_noise_normal_thresh,
  155286. 0);
  155287. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155288. setup->psy_noise_normal_start[0],
  155289. setup->psy_noise_normal_partition[0],
  155290. setup->psy_noise_normal_thresh,
  155291. 1);
  155292. if(!singleblock){
  155293. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155294. setup->psy_noise_normal_start[1],
  155295. setup->psy_noise_normal_partition[1],
  155296. setup->psy_noise_normal_thresh,
  155297. 2);
  155298. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155299. setup->psy_noise_normal_start[1],
  155300. setup->psy_noise_normal_partition[1],
  155301. setup->psy_noise_normal_thresh,
  155302. 3);
  155303. }
  155304. /* tone masking setup */
  155305. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155306. setup->psy_tone_masteratt,
  155307. setup->psy_tone_0dB,
  155308. setup->psy_tone_adj_impulse);
  155309. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155310. setup->psy_tone_masteratt,
  155311. setup->psy_tone_0dB,
  155312. setup->psy_tone_adj_other);
  155313. if(!singleblock){
  155314. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155315. setup->psy_tone_masteratt,
  155316. setup->psy_tone_0dB,
  155317. setup->psy_tone_adj_other);
  155318. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155319. setup->psy_tone_masteratt,
  155320. setup->psy_tone_0dB,
  155321. setup->psy_tone_adj_long);
  155322. }
  155323. /* noise companding setup */
  155324. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155325. setup->psy_noise_compand,
  155326. setup->psy_noise_compand_short_mapping);
  155327. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155328. setup->psy_noise_compand,
  155329. setup->psy_noise_compand_short_mapping);
  155330. if(!singleblock){
  155331. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155332. setup->psy_noise_compand,
  155333. setup->psy_noise_compand_long_mapping);
  155334. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155335. setup->psy_noise_compand,
  155336. setup->psy_noise_compand_long_mapping);
  155337. }
  155338. /* peak guarding setup */
  155339. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155340. setup->psy_tone_dBsuppress);
  155341. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155342. setup->psy_tone_dBsuppress);
  155343. if(!singleblock){
  155344. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155345. setup->psy_tone_dBsuppress);
  155346. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155347. setup->psy_tone_dBsuppress);
  155348. }
  155349. /* noise bias setup */
  155350. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155351. setup->psy_noise_dBsuppress,
  155352. setup->psy_noise_bias_impulse,
  155353. setup->psy_noiseguards,
  155354. (i0==0?hi->impulse_noisetune:0.));
  155355. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155356. setup->psy_noise_dBsuppress,
  155357. setup->psy_noise_bias_padding,
  155358. setup->psy_noiseguards,0.);
  155359. if(!singleblock){
  155360. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155361. setup->psy_noise_dBsuppress,
  155362. setup->psy_noise_bias_trans,
  155363. setup->psy_noiseguards,0.);
  155364. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155365. setup->psy_noise_dBsuppress,
  155366. setup->psy_noise_bias_long,
  155367. setup->psy_noiseguards,0.);
  155368. }
  155369. vorbis_encode_ath_setup(vi,0);
  155370. vorbis_encode_ath_setup(vi,1);
  155371. if(!singleblock){
  155372. vorbis_encode_ath_setup(vi,2);
  155373. vorbis_encode_ath_setup(vi,3);
  155374. }
  155375. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155376. /* set bitrate readonlies and management */
  155377. if(hi->bitrate_av>0)
  155378. vi->bitrate_nominal=hi->bitrate_av;
  155379. else{
  155380. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155381. }
  155382. vi->bitrate_lower=hi->bitrate_min;
  155383. vi->bitrate_upper=hi->bitrate_max;
  155384. if(hi->bitrate_av)
  155385. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155386. else
  155387. vi->bitrate_window=0.;
  155388. if(hi->managed){
  155389. ci->bi.avg_rate=hi->bitrate_av;
  155390. ci->bi.min_rate=hi->bitrate_min;
  155391. ci->bi.max_rate=hi->bitrate_max;
  155392. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155393. ci->bi.reservoir_bias=
  155394. hi->bitrate_reservoir_bias;
  155395. ci->bi.slew_damp=hi->bitrate_av_damp;
  155396. }
  155397. return(0);
  155398. }
  155399. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155400. long channels,
  155401. long rate){
  155402. int ret=0,i,is;
  155403. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155404. highlevel_encode_setup *hi=&ci->hi;
  155405. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155406. double ds;
  155407. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155408. if(ret)return(ret);
  155409. is=hi->base_setting;
  155410. ds=hi->base_setting-is;
  155411. hi->short_setting=hi->base_setting;
  155412. hi->long_setting=hi->base_setting;
  155413. hi->managed=0;
  155414. hi->impulse_block_p=1;
  155415. hi->noise_normalize_p=1;
  155416. hi->stereo_point_setting=hi->base_setting;
  155417. hi->lowpass_kHz=
  155418. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155419. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155420. setup->psy_ath_float[is+1]*ds;
  155421. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155422. setup->psy_ath_abs[is+1]*ds;
  155423. hi->amplitude_track_dBpersec=-6.;
  155424. hi->trigger_setting=hi->base_setting;
  155425. for(i=0;i<4;i++){
  155426. hi->block[i].tone_mask_setting=hi->base_setting;
  155427. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155428. hi->block[i].noise_bias_setting=hi->base_setting;
  155429. hi->block[i].noise_compand_setting=hi->base_setting;
  155430. }
  155431. return(ret);
  155432. }
  155433. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155434. long channels,
  155435. long rate,
  155436. float quality){
  155437. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155438. highlevel_encode_setup *hi=&ci->hi;
  155439. quality+=.0000001;
  155440. if(quality>=1.)quality=.9999;
  155441. get_setup_template(vi,channels,rate,quality,0);
  155442. if(!hi->setup)return OV_EIMPL;
  155443. return vorbis_encode_setup_setting(vi,channels,rate);
  155444. }
  155445. int vorbis_encode_init_vbr(vorbis_info *vi,
  155446. long channels,
  155447. long rate,
  155448. float base_quality /* 0. to 1. */
  155449. ){
  155450. int ret=0;
  155451. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155452. if(ret){
  155453. vorbis_info_clear(vi);
  155454. return ret;
  155455. }
  155456. ret=vorbis_encode_setup_init(vi);
  155457. if(ret)
  155458. vorbis_info_clear(vi);
  155459. return(ret);
  155460. }
  155461. int vorbis_encode_setup_managed(vorbis_info *vi,
  155462. long channels,
  155463. long rate,
  155464. long max_bitrate,
  155465. long nominal_bitrate,
  155466. long min_bitrate){
  155467. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155468. highlevel_encode_setup *hi=&ci->hi;
  155469. double tnominal=nominal_bitrate;
  155470. int ret=0;
  155471. if(nominal_bitrate<=0.){
  155472. if(max_bitrate>0.){
  155473. if(min_bitrate>0.)
  155474. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155475. else
  155476. nominal_bitrate=max_bitrate*.875;
  155477. }else{
  155478. if(min_bitrate>0.){
  155479. nominal_bitrate=min_bitrate;
  155480. }else{
  155481. return(OV_EINVAL);
  155482. }
  155483. }
  155484. }
  155485. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155486. if(!hi->setup)return OV_EIMPL;
  155487. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155488. if(ret){
  155489. vorbis_info_clear(vi);
  155490. return ret;
  155491. }
  155492. /* initialize management with sane defaults */
  155493. hi->managed=1;
  155494. hi->bitrate_min=min_bitrate;
  155495. hi->bitrate_max=max_bitrate;
  155496. hi->bitrate_av=tnominal;
  155497. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155498. hi->bitrate_reservoir=nominal_bitrate*2;
  155499. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155500. return(ret);
  155501. }
  155502. int vorbis_encode_init(vorbis_info *vi,
  155503. long channels,
  155504. long rate,
  155505. long max_bitrate,
  155506. long nominal_bitrate,
  155507. long min_bitrate){
  155508. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155509. max_bitrate,
  155510. nominal_bitrate,
  155511. min_bitrate);
  155512. if(ret){
  155513. vorbis_info_clear(vi);
  155514. return(ret);
  155515. }
  155516. ret=vorbis_encode_setup_init(vi);
  155517. if(ret)
  155518. vorbis_info_clear(vi);
  155519. return(ret);
  155520. }
  155521. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155522. if(vi){
  155523. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155524. highlevel_encode_setup *hi=&ci->hi;
  155525. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155526. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155527. switch(number){
  155528. /* now deprecated *****************/
  155529. case OV_ECTL_RATEMANAGE_GET:
  155530. {
  155531. struct ovectl_ratemanage_arg *ai=
  155532. (struct ovectl_ratemanage_arg *)arg;
  155533. ai->management_active=hi->managed;
  155534. ai->bitrate_hard_window=ai->bitrate_av_window=
  155535. (double)hi->bitrate_reservoir/vi->rate;
  155536. ai->bitrate_av_window_center=1.;
  155537. ai->bitrate_hard_min=hi->bitrate_min;
  155538. ai->bitrate_hard_max=hi->bitrate_max;
  155539. ai->bitrate_av_lo=hi->bitrate_av;
  155540. ai->bitrate_av_hi=hi->bitrate_av;
  155541. }
  155542. return(0);
  155543. /* now deprecated *****************/
  155544. case OV_ECTL_RATEMANAGE_SET:
  155545. {
  155546. struct ovectl_ratemanage_arg *ai=
  155547. (struct ovectl_ratemanage_arg *)arg;
  155548. if(ai==NULL){
  155549. hi->managed=0;
  155550. }else{
  155551. hi->managed=ai->management_active;
  155552. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155553. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155554. }
  155555. }
  155556. return 0;
  155557. /* now deprecated *****************/
  155558. case OV_ECTL_RATEMANAGE_AVG:
  155559. {
  155560. struct ovectl_ratemanage_arg *ai=
  155561. (struct ovectl_ratemanage_arg *)arg;
  155562. if(ai==NULL){
  155563. hi->bitrate_av=0;
  155564. }else{
  155565. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  155566. }
  155567. }
  155568. return(0);
  155569. /* now deprecated *****************/
  155570. case OV_ECTL_RATEMANAGE_HARD:
  155571. {
  155572. struct ovectl_ratemanage_arg *ai=
  155573. (struct ovectl_ratemanage_arg *)arg;
  155574. if(ai==NULL){
  155575. hi->bitrate_min=0;
  155576. hi->bitrate_max=0;
  155577. }else{
  155578. hi->bitrate_min=ai->bitrate_hard_min;
  155579. hi->bitrate_max=ai->bitrate_hard_max;
  155580. hi->bitrate_reservoir=ai->bitrate_hard_window*
  155581. (hi->bitrate_max+hi->bitrate_min)*.5;
  155582. }
  155583. if(hi->bitrate_reservoir<128.)
  155584. hi->bitrate_reservoir=128.;
  155585. }
  155586. return(0);
  155587. /* replacement ratemanage interface */
  155588. case OV_ECTL_RATEMANAGE2_GET:
  155589. {
  155590. struct ovectl_ratemanage2_arg *ai=
  155591. (struct ovectl_ratemanage2_arg *)arg;
  155592. if(ai==NULL)return OV_EINVAL;
  155593. ai->management_active=hi->managed;
  155594. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  155595. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  155596. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  155597. ai->bitrate_average_damping=hi->bitrate_av_damp;
  155598. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  155599. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  155600. }
  155601. return (0);
  155602. case OV_ECTL_RATEMANAGE2_SET:
  155603. {
  155604. struct ovectl_ratemanage2_arg *ai=
  155605. (struct ovectl_ratemanage2_arg *)arg;
  155606. if(ai==NULL){
  155607. hi->managed=0;
  155608. }else{
  155609. /* sanity check; only catch invariant violations */
  155610. if(ai->bitrate_limit_min_kbps>0 &&
  155611. ai->bitrate_average_kbps>0 &&
  155612. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  155613. return OV_EINVAL;
  155614. if(ai->bitrate_limit_max_kbps>0 &&
  155615. ai->bitrate_average_kbps>0 &&
  155616. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  155617. return OV_EINVAL;
  155618. if(ai->bitrate_limit_min_kbps>0 &&
  155619. ai->bitrate_limit_max_kbps>0 &&
  155620. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  155621. return OV_EINVAL;
  155622. if(ai->bitrate_average_damping <= 0.)
  155623. return OV_EINVAL;
  155624. if(ai->bitrate_limit_reservoir_bits < 0)
  155625. return OV_EINVAL;
  155626. if(ai->bitrate_limit_reservoir_bias < 0.)
  155627. return OV_EINVAL;
  155628. if(ai->bitrate_limit_reservoir_bias > 1.)
  155629. return OV_EINVAL;
  155630. hi->managed=ai->management_active;
  155631. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  155632. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  155633. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  155634. hi->bitrate_av_damp=ai->bitrate_average_damping;
  155635. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  155636. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  155637. }
  155638. }
  155639. return 0;
  155640. case OV_ECTL_LOWPASS_GET:
  155641. {
  155642. double *farg=(double *)arg;
  155643. *farg=hi->lowpass_kHz;
  155644. }
  155645. return(0);
  155646. case OV_ECTL_LOWPASS_SET:
  155647. {
  155648. double *farg=(double *)arg;
  155649. hi->lowpass_kHz=*farg;
  155650. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  155651. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  155652. }
  155653. return(0);
  155654. case OV_ECTL_IBLOCK_GET:
  155655. {
  155656. double *farg=(double *)arg;
  155657. *farg=hi->impulse_noisetune;
  155658. }
  155659. return(0);
  155660. case OV_ECTL_IBLOCK_SET:
  155661. {
  155662. double *farg=(double *)arg;
  155663. hi->impulse_noisetune=*farg;
  155664. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  155665. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  155666. }
  155667. return(0);
  155668. }
  155669. return(OV_EIMPL);
  155670. }
  155671. return(OV_EINVAL);
  155672. }
  155673. #endif
  155674. /*** End of inlined file: vorbisenc.c ***/
  155675. /*** Start of inlined file: vorbisfile.c ***/
  155676. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  155677. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  155678. // tasks..
  155679. #if JUCE_MSVC
  155680. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  155681. #endif
  155682. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  155683. #if JUCE_USE_OGGVORBIS
  155684. #include <stdlib.h>
  155685. #include <stdio.h>
  155686. #include <errno.h>
  155687. #include <string.h>
  155688. #include <math.h>
  155689. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  155690. one logical bitstream arranged end to end (the only form of Ogg
  155691. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  155692. multiplexing] is not allowed in Vorbis) */
  155693. /* A Vorbis file can be played beginning to end (streamed) without
  155694. worrying ahead of time about chaining (see decoder_example.c). If
  155695. we have the whole file, however, and want random access
  155696. (seeking/scrubbing) or desire to know the total length/time of a
  155697. file, we need to account for the possibility of chaining. */
  155698. /* We can handle things a number of ways; we can determine the entire
  155699. bitstream structure right off the bat, or find pieces on demand.
  155700. This example determines and caches structure for the entire
  155701. bitstream, but builds a virtual decoder on the fly when moving
  155702. between links in the chain. */
  155703. /* There are also different ways to implement seeking. Enough
  155704. information exists in an Ogg bitstream to seek to
  155705. sample-granularity positions in the output. Or, one can seek by
  155706. picking some portion of the stream roughly in the desired area if
  155707. we only want coarse navigation through the stream. */
  155708. /*************************************************************************
  155709. * Many, many internal helpers. The intention is not to be confusing;
  155710. * rampant duplication and monolithic function implementation would be
  155711. * harder to understand anyway. The high level functions are last. Begin
  155712. * grokking near the end of the file */
  155713. /* read a little more data from the file/pipe into the ogg_sync framer
  155714. */
  155715. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  155716. over 8k gets what they deserve */
  155717. static long _get_data(OggVorbis_File *vf){
  155718. errno=0;
  155719. if(vf->datasource){
  155720. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  155721. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  155722. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  155723. if(bytes==0 && errno)return(-1);
  155724. return(bytes);
  155725. }else
  155726. return(0);
  155727. }
  155728. /* save a tiny smidge of verbosity to make the code more readable */
  155729. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  155730. if(vf->datasource){
  155731. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  155732. vf->offset=offset;
  155733. ogg_sync_reset(&vf->oy);
  155734. }else{
  155735. /* shouldn't happen unless someone writes a broken callback */
  155736. return;
  155737. }
  155738. }
  155739. /* The read/seek functions track absolute position within the stream */
  155740. /* from the head of the stream, get the next page. boundary specifies
  155741. if the function is allowed to fetch more data from the stream (and
  155742. how much) or only use internally buffered data.
  155743. boundary: -1) unbounded search
  155744. 0) read no additional data; use cached only
  155745. n) search for a new page beginning for n bytes
  155746. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  155747. n) found a page at absolute offset n */
  155748. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  155749. ogg_int64_t boundary){
  155750. if(boundary>0)boundary+=vf->offset;
  155751. while(1){
  155752. long more;
  155753. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  155754. more=ogg_sync_pageseek(&vf->oy,og);
  155755. if(more<0){
  155756. /* skipped n bytes */
  155757. vf->offset-=more;
  155758. }else{
  155759. if(more==0){
  155760. /* send more paramedics */
  155761. if(!boundary)return(OV_FALSE);
  155762. {
  155763. long ret=_get_data(vf);
  155764. if(ret==0)return(OV_EOF);
  155765. if(ret<0)return(OV_EREAD);
  155766. }
  155767. }else{
  155768. /* got a page. Return the offset at the page beginning,
  155769. advance the internal offset past the page end */
  155770. ogg_int64_t ret=vf->offset;
  155771. vf->offset+=more;
  155772. return(ret);
  155773. }
  155774. }
  155775. }
  155776. }
  155777. /* find the latest page beginning before the current stream cursor
  155778. position. Much dirtier than the above as Ogg doesn't have any
  155779. backward search linkage. no 'readp' as it will certainly have to
  155780. read. */
  155781. /* returns offset or OV_EREAD, OV_FAULT */
  155782. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  155783. ogg_int64_t begin=vf->offset;
  155784. ogg_int64_t end=begin;
  155785. ogg_int64_t ret;
  155786. ogg_int64_t offset=-1;
  155787. while(offset==-1){
  155788. begin-=CHUNKSIZE;
  155789. if(begin<0)
  155790. begin=0;
  155791. _seek_helper(vf,begin);
  155792. while(vf->offset<end){
  155793. ret=_get_next_page(vf,og,end-vf->offset);
  155794. if(ret==OV_EREAD)return(OV_EREAD);
  155795. if(ret<0){
  155796. break;
  155797. }else{
  155798. offset=ret;
  155799. }
  155800. }
  155801. }
  155802. /* we have the offset. Actually snork and hold the page now */
  155803. _seek_helper(vf,offset);
  155804. ret=_get_next_page(vf,og,CHUNKSIZE);
  155805. if(ret<0)
  155806. /* this shouldn't be possible */
  155807. return(OV_EFAULT);
  155808. return(offset);
  155809. }
  155810. /* finds each bitstream link one at a time using a bisection search
  155811. (has to begin by knowing the offset of the lb's initial page).
  155812. Recurses for each link so it can alloc the link storage after
  155813. finding them all, then unroll and fill the cache at the same time */
  155814. static int _bisect_forward_serialno(OggVorbis_File *vf,
  155815. ogg_int64_t begin,
  155816. ogg_int64_t searched,
  155817. ogg_int64_t end,
  155818. long currentno,
  155819. long m){
  155820. ogg_int64_t endsearched=end;
  155821. ogg_int64_t next=end;
  155822. ogg_page og;
  155823. ogg_int64_t ret;
  155824. /* the below guards against garbage seperating the last and
  155825. first pages of two links. */
  155826. while(searched<endsearched){
  155827. ogg_int64_t bisect;
  155828. if(endsearched-searched<CHUNKSIZE){
  155829. bisect=searched;
  155830. }else{
  155831. bisect=(searched+endsearched)/2;
  155832. }
  155833. _seek_helper(vf,bisect);
  155834. ret=_get_next_page(vf,&og,-1);
  155835. if(ret==OV_EREAD)return(OV_EREAD);
  155836. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  155837. endsearched=bisect;
  155838. if(ret>=0)next=ret;
  155839. }else{
  155840. searched=ret+og.header_len+og.body_len;
  155841. }
  155842. }
  155843. _seek_helper(vf,next);
  155844. ret=_get_next_page(vf,&og,-1);
  155845. if(ret==OV_EREAD)return(OV_EREAD);
  155846. if(searched>=end || ret<0){
  155847. vf->links=m+1;
  155848. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  155849. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  155850. vf->offsets[m+1]=searched;
  155851. }else{
  155852. ret=_bisect_forward_serialno(vf,next,vf->offset,
  155853. end,ogg_page_serialno(&og),m+1);
  155854. if(ret==OV_EREAD)return(OV_EREAD);
  155855. }
  155856. vf->offsets[m]=begin;
  155857. vf->serialnos[m]=currentno;
  155858. return(0);
  155859. }
  155860. /* uses the local ogg_stream storage in vf; this is important for
  155861. non-streaming input sources */
  155862. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  155863. long *serialno,ogg_page *og_ptr){
  155864. ogg_page og;
  155865. ogg_packet op;
  155866. int i,ret;
  155867. if(!og_ptr){
  155868. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  155869. if(llret==OV_EREAD)return(OV_EREAD);
  155870. if(llret<0)return OV_ENOTVORBIS;
  155871. og_ptr=&og;
  155872. }
  155873. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  155874. if(serialno)*serialno=vf->os.serialno;
  155875. vf->ready_state=STREAMSET;
  155876. /* extract the initial header from the first page and verify that the
  155877. Ogg bitstream is in fact Vorbis data */
  155878. vorbis_info_init(vi);
  155879. vorbis_comment_init(vc);
  155880. i=0;
  155881. while(i<3){
  155882. ogg_stream_pagein(&vf->os,og_ptr);
  155883. while(i<3){
  155884. int result=ogg_stream_packetout(&vf->os,&op);
  155885. if(result==0)break;
  155886. if(result==-1){
  155887. ret=OV_EBADHEADER;
  155888. goto bail_header;
  155889. }
  155890. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  155891. goto bail_header;
  155892. }
  155893. i++;
  155894. }
  155895. if(i<3)
  155896. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  155897. ret=OV_EBADHEADER;
  155898. goto bail_header;
  155899. }
  155900. }
  155901. return 0;
  155902. bail_header:
  155903. vorbis_info_clear(vi);
  155904. vorbis_comment_clear(vc);
  155905. vf->ready_state=OPENED;
  155906. return ret;
  155907. }
  155908. /* last step of the OggVorbis_File initialization; get all the
  155909. vorbis_info structs and PCM positions. Only called by the seekable
  155910. initialization (local stream storage is hacked slightly; pay
  155911. attention to how that's done) */
  155912. /* this is void and does not propogate errors up because we want to be
  155913. able to open and use damaged bitstreams as well as we can. Just
  155914. watch out for missing information for links in the OggVorbis_File
  155915. struct */
  155916. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  155917. ogg_page og;
  155918. int i;
  155919. ogg_int64_t ret;
  155920. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  155921. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  155922. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  155923. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  155924. for(i=0;i<vf->links;i++){
  155925. if(i==0){
  155926. /* we already grabbed the initial header earlier. Just set the offset */
  155927. vf->dataoffsets[i]=dataoffset;
  155928. _seek_helper(vf,dataoffset);
  155929. }else{
  155930. /* seek to the location of the initial header */
  155931. _seek_helper(vf,vf->offsets[i]);
  155932. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  155933. vf->dataoffsets[i]=-1;
  155934. }else{
  155935. vf->dataoffsets[i]=vf->offset;
  155936. }
  155937. }
  155938. /* fetch beginning PCM offset */
  155939. if(vf->dataoffsets[i]!=-1){
  155940. ogg_int64_t accumulated=0;
  155941. long lastblock=-1;
  155942. int result;
  155943. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  155944. while(1){
  155945. ogg_packet op;
  155946. ret=_get_next_page(vf,&og,-1);
  155947. if(ret<0)
  155948. /* this should not be possible unless the file is
  155949. truncated/mangled */
  155950. break;
  155951. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  155952. break;
  155953. /* count blocksizes of all frames in the page */
  155954. ogg_stream_pagein(&vf->os,&og);
  155955. while((result=ogg_stream_packetout(&vf->os,&op))){
  155956. if(result>0){ /* ignore holes */
  155957. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  155958. if(lastblock!=-1)
  155959. accumulated+=(lastblock+thisblock)>>2;
  155960. lastblock=thisblock;
  155961. }
  155962. }
  155963. if(ogg_page_granulepos(&og)!=-1){
  155964. /* pcm offset of last packet on the first audio page */
  155965. accumulated= ogg_page_granulepos(&og)-accumulated;
  155966. break;
  155967. }
  155968. }
  155969. /* less than zero? This is a stream with samples trimmed off
  155970. the beginning, a normal occurrence; set the offset to zero */
  155971. if(accumulated<0)accumulated=0;
  155972. vf->pcmlengths[i*2]=accumulated;
  155973. }
  155974. /* get the PCM length of this link. To do this,
  155975. get the last page of the stream */
  155976. {
  155977. ogg_int64_t end=vf->offsets[i+1];
  155978. _seek_helper(vf,end);
  155979. while(1){
  155980. ret=_get_prev_page(vf,&og);
  155981. if(ret<0){
  155982. /* this should not be possible */
  155983. vorbis_info_clear(vf->vi+i);
  155984. vorbis_comment_clear(vf->vc+i);
  155985. break;
  155986. }
  155987. if(ogg_page_granulepos(&og)!=-1){
  155988. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  155989. break;
  155990. }
  155991. vf->offset=ret;
  155992. }
  155993. }
  155994. }
  155995. }
  155996. static int _make_decode_ready(OggVorbis_File *vf){
  155997. if(vf->ready_state>STREAMSET)return 0;
  155998. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  155999. if(vf->seekable){
  156000. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  156001. return OV_EBADLINK;
  156002. }else{
  156003. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  156004. return OV_EBADLINK;
  156005. }
  156006. vorbis_block_init(&vf->vd,&vf->vb);
  156007. vf->ready_state=INITSET;
  156008. vf->bittrack=0.f;
  156009. vf->samptrack=0.f;
  156010. return 0;
  156011. }
  156012. static int _open_seekable2(OggVorbis_File *vf){
  156013. long serialno=vf->current_serialno;
  156014. ogg_int64_t dataoffset=vf->offset, end;
  156015. ogg_page og;
  156016. /* we're partially open and have a first link header state in
  156017. storage in vf */
  156018. /* we can seek, so set out learning all about this file */
  156019. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  156020. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  156021. /* We get the offset for the last page of the physical bitstream.
  156022. Most OggVorbis files will contain a single logical bitstream */
  156023. end=_get_prev_page(vf,&og);
  156024. if(end<0)return(end);
  156025. /* more than one logical bitstream? */
  156026. if(ogg_page_serialno(&og)!=serialno){
  156027. /* Chained bitstream. Bisect-search each logical bitstream
  156028. section. Do so based on serial number only */
  156029. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  156030. }else{
  156031. /* Only one logical bitstream */
  156032. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  156033. }
  156034. /* the initial header memory is referenced by vf after; don't free it */
  156035. _prefetch_all_headers(vf,dataoffset);
  156036. return(ov_raw_seek(vf,0));
  156037. }
  156038. /* clear out the current logical bitstream decoder */
  156039. static void _decode_clear(OggVorbis_File *vf){
  156040. vorbis_dsp_clear(&vf->vd);
  156041. vorbis_block_clear(&vf->vb);
  156042. vf->ready_state=OPENED;
  156043. }
  156044. /* fetch and process a packet. Handles the case where we're at a
  156045. bitstream boundary and dumps the decoding machine. If the decoding
  156046. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156047. date (seek and read both use this. seek uses a special hack with
  156048. readp).
  156049. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156050. 0) need more data (only if readp==0)
  156051. 1) got a packet
  156052. */
  156053. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156054. ogg_packet *op_in,
  156055. int readp,
  156056. int spanp){
  156057. ogg_page og;
  156058. /* handle one packet. Try to fetch it from current stream state */
  156059. /* extract packets from page */
  156060. while(1){
  156061. /* process a packet if we can. If the machine isn't loaded,
  156062. neither is a page */
  156063. if(vf->ready_state==INITSET){
  156064. while(1) {
  156065. ogg_packet op;
  156066. ogg_packet *op_ptr=(op_in?op_in:&op);
  156067. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156068. ogg_int64_t granulepos;
  156069. op_in=NULL;
  156070. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156071. if(result>0){
  156072. /* got a packet. process it */
  156073. granulepos=op_ptr->granulepos;
  156074. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156075. header handling. The
  156076. header packets aren't
  156077. audio, so if/when we
  156078. submit them,
  156079. vorbis_synthesis will
  156080. reject them */
  156081. /* suck in the synthesis data and track bitrate */
  156082. {
  156083. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156084. /* for proper use of libvorbis within libvorbisfile,
  156085. oldsamples will always be zero. */
  156086. if(oldsamples)return(OV_EFAULT);
  156087. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156088. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156089. vf->bittrack+=op_ptr->bytes*8;
  156090. }
  156091. /* update the pcm offset. */
  156092. if(granulepos!=-1 && !op_ptr->e_o_s){
  156093. int link=(vf->seekable?vf->current_link:0);
  156094. int i,samples;
  156095. /* this packet has a pcm_offset on it (the last packet
  156096. completed on a page carries the offset) After processing
  156097. (above), we know the pcm position of the *last* sample
  156098. ready to be returned. Find the offset of the *first*
  156099. As an aside, this trick is inaccurate if we begin
  156100. reading anew right at the last page; the end-of-stream
  156101. granulepos declares the last frame in the stream, and the
  156102. last packet of the last page may be a partial frame.
  156103. So, we need a previous granulepos from an in-sequence page
  156104. to have a reference point. Thus the !op_ptr->e_o_s clause
  156105. above */
  156106. if(vf->seekable && link>0)
  156107. granulepos-=vf->pcmlengths[link*2];
  156108. if(granulepos<0)granulepos=0; /* actually, this
  156109. shouldn't be possible
  156110. here unless the stream
  156111. is very broken */
  156112. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156113. granulepos-=samples;
  156114. for(i=0;i<link;i++)
  156115. granulepos+=vf->pcmlengths[i*2+1];
  156116. vf->pcm_offset=granulepos;
  156117. }
  156118. return(1);
  156119. }
  156120. }
  156121. else
  156122. break;
  156123. }
  156124. }
  156125. if(vf->ready_state>=OPENED){
  156126. ogg_int64_t ret;
  156127. if(!readp)return(0);
  156128. if((ret=_get_next_page(vf,&og,-1))<0){
  156129. return(OV_EOF); /* eof.
  156130. leave unitialized */
  156131. }
  156132. /* bitrate tracking; add the header's bytes here, the body bytes
  156133. are done by packet above */
  156134. vf->bittrack+=og.header_len*8;
  156135. /* has our decoding just traversed a bitstream boundary? */
  156136. if(vf->ready_state==INITSET){
  156137. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156138. if(!spanp)
  156139. return(OV_EOF);
  156140. _decode_clear(vf);
  156141. if(!vf->seekable){
  156142. vorbis_info_clear(vf->vi);
  156143. vorbis_comment_clear(vf->vc);
  156144. }
  156145. }
  156146. }
  156147. }
  156148. /* Do we need to load a new machine before submitting the page? */
  156149. /* This is different in the seekable and non-seekable cases.
  156150. In the seekable case, we already have all the header
  156151. information loaded and cached; we just initialize the machine
  156152. with it and continue on our merry way.
  156153. In the non-seekable (streaming) case, we'll only be at a
  156154. boundary if we just left the previous logical bitstream and
  156155. we're now nominally at the header of the next bitstream
  156156. */
  156157. if(vf->ready_state!=INITSET){
  156158. int link;
  156159. if(vf->ready_state<STREAMSET){
  156160. if(vf->seekable){
  156161. vf->current_serialno=ogg_page_serialno(&og);
  156162. /* match the serialno to bitstream section. We use this rather than
  156163. offset positions to avoid problems near logical bitstream
  156164. boundaries */
  156165. for(link=0;link<vf->links;link++)
  156166. if(vf->serialnos[link]==vf->current_serialno)break;
  156167. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156168. stream. error out,
  156169. leave machine
  156170. uninitialized */
  156171. vf->current_link=link;
  156172. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156173. vf->ready_state=STREAMSET;
  156174. }else{
  156175. /* we're streaming */
  156176. /* fetch the three header packets, build the info struct */
  156177. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156178. if(ret)return(ret);
  156179. vf->current_link++;
  156180. link=0;
  156181. }
  156182. }
  156183. {
  156184. int ret=_make_decode_ready(vf);
  156185. if(ret<0)return ret;
  156186. }
  156187. }
  156188. ogg_stream_pagein(&vf->os,&og);
  156189. }
  156190. }
  156191. /* if, eg, 64 bit stdio is configured by default, this will build with
  156192. fseek64 */
  156193. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156194. if(f==NULL)return(-1);
  156195. return fseek(f,off,whence);
  156196. }
  156197. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156198. long ibytes, ov_callbacks callbacks){
  156199. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156200. int ret;
  156201. memset(vf,0,sizeof(*vf));
  156202. vf->datasource=f;
  156203. vf->callbacks = callbacks;
  156204. /* init the framing state */
  156205. ogg_sync_init(&vf->oy);
  156206. /* perhaps some data was previously read into a buffer for testing
  156207. against other stream types. Allow initialization from this
  156208. previously read data (as we may be reading from a non-seekable
  156209. stream) */
  156210. if(initial){
  156211. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156212. memcpy(buffer,initial,ibytes);
  156213. ogg_sync_wrote(&vf->oy,ibytes);
  156214. }
  156215. /* can we seek? Stevens suggests the seek test was portable */
  156216. if(offsettest!=-1)vf->seekable=1;
  156217. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156218. entry for partial open */
  156219. vf->links=1;
  156220. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156221. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156222. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156223. /* Try to fetch the headers, maintaining all the storage */
  156224. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156225. vf->datasource=NULL;
  156226. ov_clear(vf);
  156227. }else
  156228. vf->ready_state=PARTOPEN;
  156229. return(ret);
  156230. }
  156231. static int _ov_open2(OggVorbis_File *vf){
  156232. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156233. vf->ready_state=OPENED;
  156234. if(vf->seekable){
  156235. int ret=_open_seekable2(vf);
  156236. if(ret){
  156237. vf->datasource=NULL;
  156238. ov_clear(vf);
  156239. }
  156240. return(ret);
  156241. }else
  156242. vf->ready_state=STREAMSET;
  156243. return 0;
  156244. }
  156245. /* clear out the OggVorbis_File struct */
  156246. int ov_clear(OggVorbis_File *vf){
  156247. if(vf){
  156248. vorbis_block_clear(&vf->vb);
  156249. vorbis_dsp_clear(&vf->vd);
  156250. ogg_stream_clear(&vf->os);
  156251. if(vf->vi && vf->links){
  156252. int i;
  156253. for(i=0;i<vf->links;i++){
  156254. vorbis_info_clear(vf->vi+i);
  156255. vorbis_comment_clear(vf->vc+i);
  156256. }
  156257. _ogg_free(vf->vi);
  156258. _ogg_free(vf->vc);
  156259. }
  156260. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156261. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156262. if(vf->serialnos)_ogg_free(vf->serialnos);
  156263. if(vf->offsets)_ogg_free(vf->offsets);
  156264. ogg_sync_clear(&vf->oy);
  156265. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156266. memset(vf,0,sizeof(*vf));
  156267. }
  156268. #ifdef DEBUG_LEAKS
  156269. _VDBG_dump();
  156270. #endif
  156271. return(0);
  156272. }
  156273. /* inspects the OggVorbis file and finds/documents all the logical
  156274. bitstreams contained in it. Tries to be tolerant of logical
  156275. bitstream sections that are truncated/woogie.
  156276. return: -1) error
  156277. 0) OK
  156278. */
  156279. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156280. ov_callbacks callbacks){
  156281. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156282. if(ret)return ret;
  156283. return _ov_open2(vf);
  156284. }
  156285. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156286. ov_callbacks callbacks = {
  156287. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156288. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156289. (int (*)(void *)) fclose,
  156290. (long (*)(void *)) ftell
  156291. };
  156292. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156293. }
  156294. /* cheap hack for game usage where downsampling is desirable; there's
  156295. no need for SRC as we can just do it cheaply in libvorbis. */
  156296. int ov_halfrate(OggVorbis_File *vf,int flag){
  156297. int i;
  156298. if(vf->vi==NULL)return OV_EINVAL;
  156299. if(!vf->seekable)return OV_EINVAL;
  156300. if(vf->ready_state>=STREAMSET)
  156301. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156302. will be able to swap this on the fly, but
  156303. for now dumping the decode machine is needed
  156304. to reinit the MDCT lookups. 1.1 libvorbis
  156305. is planned to be able to switch on the fly */
  156306. for(i=0;i<vf->links;i++){
  156307. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156308. ov_halfrate(vf,0);
  156309. return OV_EINVAL;
  156310. }
  156311. }
  156312. return 0;
  156313. }
  156314. int ov_halfrate_p(OggVorbis_File *vf){
  156315. if(vf->vi==NULL)return OV_EINVAL;
  156316. return vorbis_synthesis_halfrate_p(vf->vi);
  156317. }
  156318. /* Only partially open the vorbis file; test for Vorbisness, and load
  156319. the headers for the first chain. Do not seek (although test for
  156320. seekability). Use ov_test_open to finish opening the file, else
  156321. ov_clear to close/free it. Same return codes as open. */
  156322. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156323. ov_callbacks callbacks)
  156324. {
  156325. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156326. }
  156327. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156328. ov_callbacks callbacks = {
  156329. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156330. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156331. (int (*)(void *)) fclose,
  156332. (long (*)(void *)) ftell
  156333. };
  156334. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156335. }
  156336. int ov_test_open(OggVorbis_File *vf){
  156337. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156338. return _ov_open2(vf);
  156339. }
  156340. /* How many logical bitstreams in this physical bitstream? */
  156341. long ov_streams(OggVorbis_File *vf){
  156342. return vf->links;
  156343. }
  156344. /* Is the FILE * associated with vf seekable? */
  156345. long ov_seekable(OggVorbis_File *vf){
  156346. return vf->seekable;
  156347. }
  156348. /* returns the bitrate for a given logical bitstream or the entire
  156349. physical bitstream. If the file is open for random access, it will
  156350. find the *actual* average bitrate. If the file is streaming, it
  156351. returns the nominal bitrate (if set) else the average of the
  156352. upper/lower bounds (if set) else -1 (unset).
  156353. If you want the actual bitrate field settings, get them from the
  156354. vorbis_info structs */
  156355. long ov_bitrate(OggVorbis_File *vf,int i){
  156356. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156357. if(i>=vf->links)return(OV_EINVAL);
  156358. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156359. if(i<0){
  156360. ogg_int64_t bits=0;
  156361. int i;
  156362. float br;
  156363. for(i=0;i<vf->links;i++)
  156364. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156365. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156366. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156367. * so this is slightly transformed to make it work.
  156368. */
  156369. br = bits/ov_time_total(vf,-1);
  156370. return(rint(br));
  156371. }else{
  156372. if(vf->seekable){
  156373. /* return the actual bitrate */
  156374. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156375. }else{
  156376. /* return nominal if set */
  156377. if(vf->vi[i].bitrate_nominal>0){
  156378. return vf->vi[i].bitrate_nominal;
  156379. }else{
  156380. if(vf->vi[i].bitrate_upper>0){
  156381. if(vf->vi[i].bitrate_lower>0){
  156382. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156383. }else{
  156384. return vf->vi[i].bitrate_upper;
  156385. }
  156386. }
  156387. return(OV_FALSE);
  156388. }
  156389. }
  156390. }
  156391. }
  156392. /* returns the actual bitrate since last call. returns -1 if no
  156393. additional data to offer since last call (or at beginning of stream),
  156394. EINVAL if stream is only partially open
  156395. */
  156396. long ov_bitrate_instant(OggVorbis_File *vf){
  156397. int link=(vf->seekable?vf->current_link:0);
  156398. long ret;
  156399. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156400. if(vf->samptrack==0)return(OV_FALSE);
  156401. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156402. vf->bittrack=0.f;
  156403. vf->samptrack=0.f;
  156404. return(ret);
  156405. }
  156406. /* Guess */
  156407. long ov_serialnumber(OggVorbis_File *vf,int i){
  156408. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  156409. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  156410. if(i<0){
  156411. return(vf->current_serialno);
  156412. }else{
  156413. return(vf->serialnos[i]);
  156414. }
  156415. }
  156416. /* returns: total raw (compressed) length of content if i==-1
  156417. raw (compressed) length of that logical bitstream for i==0 to n
  156418. OV_EINVAL if the stream is not seekable (we can't know the length)
  156419. or if stream is only partially open
  156420. */
  156421. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  156422. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156423. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156424. if(i<0){
  156425. ogg_int64_t acc=0;
  156426. int i;
  156427. for(i=0;i<vf->links;i++)
  156428. acc+=ov_raw_total(vf,i);
  156429. return(acc);
  156430. }else{
  156431. return(vf->offsets[i+1]-vf->offsets[i]);
  156432. }
  156433. }
  156434. /* returns: total PCM length (samples) of content if i==-1 PCM length
  156435. (samples) of that logical bitstream for i==0 to n
  156436. OV_EINVAL if the stream is not seekable (we can't know the
  156437. length) or only partially open
  156438. */
  156439. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  156440. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156441. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156442. if(i<0){
  156443. ogg_int64_t acc=0;
  156444. int i;
  156445. for(i=0;i<vf->links;i++)
  156446. acc+=ov_pcm_total(vf,i);
  156447. return(acc);
  156448. }else{
  156449. return(vf->pcmlengths[i*2+1]);
  156450. }
  156451. }
  156452. /* returns: total seconds of content if i==-1
  156453. seconds in that logical bitstream for i==0 to n
  156454. OV_EINVAL if the stream is not seekable (we can't know the
  156455. length) or only partially open
  156456. */
  156457. double ov_time_total(OggVorbis_File *vf,int i){
  156458. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156459. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  156460. if(i<0){
  156461. double acc=0;
  156462. int i;
  156463. for(i=0;i<vf->links;i++)
  156464. acc+=ov_time_total(vf,i);
  156465. return(acc);
  156466. }else{
  156467. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  156468. }
  156469. }
  156470. /* seek to an offset relative to the *compressed* data. This also
  156471. scans packets to update the PCM cursor. It will cross a logical
  156472. bitstream boundary, but only if it can't get any packets out of the
  156473. tail of the bitstream we seek to (so no surprises).
  156474. returns zero on success, nonzero on failure */
  156475. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156476. ogg_stream_state work_os;
  156477. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156478. if(!vf->seekable)
  156479. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  156480. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  156481. /* don't yet clear out decoding machine (if it's initialized), in
  156482. the case we're in the same link. Restart the decode lapping, and
  156483. let _fetch_and_process_packet deal with a potential bitstream
  156484. boundary */
  156485. vf->pcm_offset=-1;
  156486. ogg_stream_reset_serialno(&vf->os,
  156487. vf->current_serialno); /* must set serialno */
  156488. vorbis_synthesis_restart(&vf->vd);
  156489. _seek_helper(vf,pos);
  156490. /* we need to make sure the pcm_offset is set, but we don't want to
  156491. advance the raw cursor past good packets just to get to the first
  156492. with a granulepos. That's not equivalent behavior to beginning
  156493. decoding as immediately after the seek position as possible.
  156494. So, a hack. We use two stream states; a local scratch state and
  156495. the shared vf->os stream state. We use the local state to
  156496. scan, and the shared state as a buffer for later decode.
  156497. Unfortuantely, on the last page we still advance to last packet
  156498. because the granulepos on the last page is not necessarily on a
  156499. packet boundary, and we need to make sure the granpos is
  156500. correct.
  156501. */
  156502. {
  156503. ogg_page og;
  156504. ogg_packet op;
  156505. int lastblock=0;
  156506. int accblock=0;
  156507. int thisblock;
  156508. int eosflag;
  156509. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  156510. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  156511. return from not necessarily
  156512. starting from the beginning */
  156513. while(1){
  156514. if(vf->ready_state>=STREAMSET){
  156515. /* snarf/scan a packet if we can */
  156516. int result=ogg_stream_packetout(&work_os,&op);
  156517. if(result>0){
  156518. if(vf->vi[vf->current_link].codec_setup){
  156519. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156520. if(thisblock<0){
  156521. ogg_stream_packetout(&vf->os,NULL);
  156522. thisblock=0;
  156523. }else{
  156524. if(eosflag)
  156525. ogg_stream_packetout(&vf->os,NULL);
  156526. else
  156527. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  156528. }
  156529. if(op.granulepos!=-1){
  156530. int i,link=vf->current_link;
  156531. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  156532. if(granulepos<0)granulepos=0;
  156533. for(i=0;i<link;i++)
  156534. granulepos+=vf->pcmlengths[i*2+1];
  156535. vf->pcm_offset=granulepos-accblock;
  156536. break;
  156537. }
  156538. lastblock=thisblock;
  156539. continue;
  156540. }else
  156541. ogg_stream_packetout(&vf->os,NULL);
  156542. }
  156543. }
  156544. if(!lastblock){
  156545. if(_get_next_page(vf,&og,-1)<0){
  156546. vf->pcm_offset=ov_pcm_total(vf,-1);
  156547. break;
  156548. }
  156549. }else{
  156550. /* huh? Bogus stream with packets but no granulepos */
  156551. vf->pcm_offset=-1;
  156552. break;
  156553. }
  156554. /* has our decoding just traversed a bitstream boundary? */
  156555. if(vf->ready_state>=STREAMSET)
  156556. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156557. _decode_clear(vf); /* clear out stream state */
  156558. ogg_stream_clear(&work_os);
  156559. }
  156560. if(vf->ready_state<STREAMSET){
  156561. int link;
  156562. vf->current_serialno=ogg_page_serialno(&og);
  156563. for(link=0;link<vf->links;link++)
  156564. if(vf->serialnos[link]==vf->current_serialno)break;
  156565. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  156566. error out, leave
  156567. machine uninitialized */
  156568. vf->current_link=link;
  156569. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156570. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  156571. vf->ready_state=STREAMSET;
  156572. }
  156573. ogg_stream_pagein(&vf->os,&og);
  156574. ogg_stream_pagein(&work_os,&og);
  156575. eosflag=ogg_page_eos(&og);
  156576. }
  156577. }
  156578. ogg_stream_clear(&work_os);
  156579. vf->bittrack=0.f;
  156580. vf->samptrack=0.f;
  156581. return(0);
  156582. seek_error:
  156583. /* dump the machine so we're in a known state */
  156584. vf->pcm_offset=-1;
  156585. ogg_stream_clear(&work_os);
  156586. _decode_clear(vf);
  156587. return OV_EBADLINK;
  156588. }
  156589. /* Page granularity seek (faster than sample granularity because we
  156590. don't do the last bit of decode to find a specific sample).
  156591. Seek to the last [granule marked] page preceeding the specified pos
  156592. location, such that decoding past the returned point will quickly
  156593. arrive at the requested position. */
  156594. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  156595. int link=-1;
  156596. ogg_int64_t result=0;
  156597. ogg_int64_t total=ov_pcm_total(vf,-1);
  156598. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156599. if(!vf->seekable)return(OV_ENOSEEK);
  156600. if(pos<0 || pos>total)return(OV_EINVAL);
  156601. /* which bitstream section does this pcm offset occur in? */
  156602. for(link=vf->links-1;link>=0;link--){
  156603. total-=vf->pcmlengths[link*2+1];
  156604. if(pos>=total)break;
  156605. }
  156606. /* search within the logical bitstream for the page with the highest
  156607. pcm_pos preceeding (or equal to) pos. There is a danger here;
  156608. missing pages or incorrect frame number information in the
  156609. bitstream could make our task impossible. Account for that (it
  156610. would be an error condition) */
  156611. /* new search algorithm by HB (Nicholas Vinen) */
  156612. {
  156613. ogg_int64_t end=vf->offsets[link+1];
  156614. ogg_int64_t begin=vf->offsets[link];
  156615. ogg_int64_t begintime = vf->pcmlengths[link*2];
  156616. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  156617. ogg_int64_t target=pos-total+begintime;
  156618. ogg_int64_t best=begin;
  156619. ogg_page og;
  156620. while(begin<end){
  156621. ogg_int64_t bisect;
  156622. if(end-begin<CHUNKSIZE){
  156623. bisect=begin;
  156624. }else{
  156625. /* take a (pretty decent) guess. */
  156626. bisect=begin +
  156627. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  156628. if(bisect<=begin)
  156629. bisect=begin+1;
  156630. }
  156631. _seek_helper(vf,bisect);
  156632. while(begin<end){
  156633. result=_get_next_page(vf,&og,end-vf->offset);
  156634. if(result==OV_EREAD) goto seek_error;
  156635. if(result<0){
  156636. if(bisect<=begin+1)
  156637. end=begin; /* found it */
  156638. else{
  156639. if(bisect==0) goto seek_error;
  156640. bisect-=CHUNKSIZE;
  156641. if(bisect<=begin)bisect=begin+1;
  156642. _seek_helper(vf,bisect);
  156643. }
  156644. }else{
  156645. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  156646. if(granulepos==-1)continue;
  156647. if(granulepos<target){
  156648. best=result; /* raw offset of packet with granulepos */
  156649. begin=vf->offset; /* raw offset of next page */
  156650. begintime=granulepos;
  156651. if(target-begintime>44100)break;
  156652. bisect=begin; /* *not* begin + 1 */
  156653. }else{
  156654. if(bisect<=begin+1)
  156655. end=begin; /* found it */
  156656. else{
  156657. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  156658. end=result;
  156659. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  156660. if(bisect<=begin)bisect=begin+1;
  156661. _seek_helper(vf,bisect);
  156662. }else{
  156663. end=result;
  156664. endtime=granulepos;
  156665. break;
  156666. }
  156667. }
  156668. }
  156669. }
  156670. }
  156671. }
  156672. /* found our page. seek to it, update pcm offset. Easier case than
  156673. raw_seek, don't keep packets preceeding granulepos. */
  156674. {
  156675. ogg_page og;
  156676. ogg_packet op;
  156677. /* seek */
  156678. _seek_helper(vf,best);
  156679. vf->pcm_offset=-1;
  156680. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  156681. if(link!=vf->current_link){
  156682. /* Different link; dump entire decode machine */
  156683. _decode_clear(vf);
  156684. vf->current_link=link;
  156685. vf->current_serialno=ogg_page_serialno(&og);
  156686. vf->ready_state=STREAMSET;
  156687. }else{
  156688. vorbis_synthesis_restart(&vf->vd);
  156689. }
  156690. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156691. ogg_stream_pagein(&vf->os,&og);
  156692. /* pull out all but last packet; the one with granulepos */
  156693. while(1){
  156694. result=ogg_stream_packetpeek(&vf->os,&op);
  156695. if(result==0){
  156696. /* !!! the packet finishing this page originated on a
  156697. preceeding page. Keep fetching previous pages until we
  156698. get one with a granulepos or without the 'continued' flag
  156699. set. Then just use raw_seek for simplicity. */
  156700. _seek_helper(vf,best);
  156701. while(1){
  156702. result=_get_prev_page(vf,&og);
  156703. if(result<0) goto seek_error;
  156704. if(ogg_page_granulepos(&og)>-1 ||
  156705. !ogg_page_continued(&og)){
  156706. return ov_raw_seek(vf,result);
  156707. }
  156708. vf->offset=result;
  156709. }
  156710. }
  156711. if(result<0){
  156712. result = OV_EBADPACKET;
  156713. goto seek_error;
  156714. }
  156715. if(op.granulepos!=-1){
  156716. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156717. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156718. vf->pcm_offset+=total;
  156719. break;
  156720. }else
  156721. result=ogg_stream_packetout(&vf->os,NULL);
  156722. }
  156723. }
  156724. }
  156725. /* verify result */
  156726. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  156727. result=OV_EFAULT;
  156728. goto seek_error;
  156729. }
  156730. vf->bittrack=0.f;
  156731. vf->samptrack=0.f;
  156732. return(0);
  156733. seek_error:
  156734. /* dump machine so we're in a known state */
  156735. vf->pcm_offset=-1;
  156736. _decode_clear(vf);
  156737. return (int)result;
  156738. }
  156739. /* seek to a sample offset relative to the decompressed pcm stream
  156740. returns zero on success, nonzero on failure */
  156741. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  156742. int thisblock,lastblock=0;
  156743. int ret=ov_pcm_seek_page(vf,pos);
  156744. if(ret<0)return(ret);
  156745. if((ret=_make_decode_ready(vf)))return ret;
  156746. /* discard leading packets we don't need for the lapping of the
  156747. position we want; don't decode them */
  156748. while(1){
  156749. ogg_packet op;
  156750. ogg_page og;
  156751. int ret=ogg_stream_packetpeek(&vf->os,&op);
  156752. if(ret>0){
  156753. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  156754. if(thisblock<0){
  156755. ogg_stream_packetout(&vf->os,NULL);
  156756. continue; /* non audio packet */
  156757. }
  156758. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  156759. if(vf->pcm_offset+((thisblock+
  156760. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  156761. /* remove the packet from packet queue and track its granulepos */
  156762. ogg_stream_packetout(&vf->os,NULL);
  156763. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  156764. only tracking, no
  156765. pcm_decode */
  156766. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156767. /* end of logical stream case is hard, especially with exact
  156768. length positioning. */
  156769. if(op.granulepos>-1){
  156770. int i;
  156771. /* always believe the stream markers */
  156772. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  156773. if(vf->pcm_offset<0)vf->pcm_offset=0;
  156774. for(i=0;i<vf->current_link;i++)
  156775. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  156776. }
  156777. lastblock=thisblock;
  156778. }else{
  156779. if(ret<0 && ret!=OV_HOLE)break;
  156780. /* suck in a new page */
  156781. if(_get_next_page(vf,&og,-1)<0)break;
  156782. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  156783. if(vf->ready_state<STREAMSET){
  156784. int link;
  156785. vf->current_serialno=ogg_page_serialno(&og);
  156786. for(link=0;link<vf->links;link++)
  156787. if(vf->serialnos[link]==vf->current_serialno)break;
  156788. if(link==vf->links)return(OV_EBADLINK);
  156789. vf->current_link=link;
  156790. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156791. vf->ready_state=STREAMSET;
  156792. ret=_make_decode_ready(vf);
  156793. if(ret)return ret;
  156794. lastblock=0;
  156795. }
  156796. ogg_stream_pagein(&vf->os,&og);
  156797. }
  156798. }
  156799. vf->bittrack=0.f;
  156800. vf->samptrack=0.f;
  156801. /* discard samples until we reach the desired position. Crossing a
  156802. logical bitstream boundary with abandon is OK. */
  156803. while(vf->pcm_offset<pos){
  156804. ogg_int64_t target=pos-vf->pcm_offset;
  156805. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156806. if(samples>target)samples=target;
  156807. vorbis_synthesis_read(&vf->vd,samples);
  156808. vf->pcm_offset+=samples;
  156809. if(samples<target)
  156810. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  156811. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  156812. }
  156813. return 0;
  156814. }
  156815. /* seek to a playback time relative to the decompressed pcm stream
  156816. returns zero on success, nonzero on failure */
  156817. int ov_time_seek(OggVorbis_File *vf,double seconds){
  156818. /* translate time to PCM position and call ov_pcm_seek */
  156819. int link=-1;
  156820. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156821. double time_total=ov_time_total(vf,-1);
  156822. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156823. if(!vf->seekable)return(OV_ENOSEEK);
  156824. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156825. /* which bitstream section does this time offset occur in? */
  156826. for(link=vf->links-1;link>=0;link--){
  156827. pcm_total-=vf->pcmlengths[link*2+1];
  156828. time_total-=ov_time_total(vf,link);
  156829. if(seconds>=time_total)break;
  156830. }
  156831. /* enough information to convert time offset to pcm offset */
  156832. {
  156833. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156834. return(ov_pcm_seek(vf,target));
  156835. }
  156836. }
  156837. /* page-granularity version of ov_time_seek
  156838. returns zero on success, nonzero on failure */
  156839. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  156840. /* translate time to PCM position and call ov_pcm_seek */
  156841. int link=-1;
  156842. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  156843. double time_total=ov_time_total(vf,-1);
  156844. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156845. if(!vf->seekable)return(OV_ENOSEEK);
  156846. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  156847. /* which bitstream section does this time offset occur in? */
  156848. for(link=vf->links-1;link>=0;link--){
  156849. pcm_total-=vf->pcmlengths[link*2+1];
  156850. time_total-=ov_time_total(vf,link);
  156851. if(seconds>=time_total)break;
  156852. }
  156853. /* enough information to convert time offset to pcm offset */
  156854. {
  156855. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  156856. return(ov_pcm_seek_page(vf,target));
  156857. }
  156858. }
  156859. /* tell the current stream offset cursor. Note that seek followed by
  156860. tell will likely not give the set offset due to caching */
  156861. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  156862. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156863. return(vf->offset);
  156864. }
  156865. /* return PCM offset (sample) of next PCM sample to be read */
  156866. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  156867. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156868. return(vf->pcm_offset);
  156869. }
  156870. /* return time offset (seconds) of next PCM sample to be read */
  156871. double ov_time_tell(OggVorbis_File *vf){
  156872. int link=0;
  156873. ogg_int64_t pcm_total=0;
  156874. double time_total=0.f;
  156875. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156876. if(vf->seekable){
  156877. pcm_total=ov_pcm_total(vf,-1);
  156878. time_total=ov_time_total(vf,-1);
  156879. /* which bitstream section does this time offset occur in? */
  156880. for(link=vf->links-1;link>=0;link--){
  156881. pcm_total-=vf->pcmlengths[link*2+1];
  156882. time_total-=ov_time_total(vf,link);
  156883. if(vf->pcm_offset>=pcm_total)break;
  156884. }
  156885. }
  156886. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  156887. }
  156888. /* link: -1) return the vorbis_info struct for the bitstream section
  156889. currently being decoded
  156890. 0-n) to request information for a specific bitstream section
  156891. In the case of a non-seekable bitstream, any call returns the
  156892. current bitstream. NULL in the case that the machine is not
  156893. initialized */
  156894. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  156895. if(vf->seekable){
  156896. if(link<0)
  156897. if(vf->ready_state>=STREAMSET)
  156898. return vf->vi+vf->current_link;
  156899. else
  156900. return vf->vi;
  156901. else
  156902. if(link>=vf->links)
  156903. return NULL;
  156904. else
  156905. return vf->vi+link;
  156906. }else{
  156907. return vf->vi;
  156908. }
  156909. }
  156910. /* grr, strong typing, grr, no templates/inheritence, grr */
  156911. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  156912. if(vf->seekable){
  156913. if(link<0)
  156914. if(vf->ready_state>=STREAMSET)
  156915. return vf->vc+vf->current_link;
  156916. else
  156917. return vf->vc;
  156918. else
  156919. if(link>=vf->links)
  156920. return NULL;
  156921. else
  156922. return vf->vc+link;
  156923. }else{
  156924. return vf->vc;
  156925. }
  156926. }
  156927. static int host_is_big_endian() {
  156928. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  156929. unsigned char *bytewise = (unsigned char *)&pattern;
  156930. if (bytewise[0] == 0xfe) return 1;
  156931. return 0;
  156932. }
  156933. /* up to this point, everything could more or less hide the multiple
  156934. logical bitstream nature of chaining from the toplevel application
  156935. if the toplevel application didn't particularly care. However, at
  156936. the point that we actually read audio back, the multiple-section
  156937. nature must surface: Multiple bitstream sections do not necessarily
  156938. have to have the same number of channels or sampling rate.
  156939. ov_read returns the sequential logical bitstream number currently
  156940. being decoded along with the PCM data in order that the toplevel
  156941. application can take action on channel/sample rate changes. This
  156942. number will be incremented even for streamed (non-seekable) streams
  156943. (for seekable streams, it represents the actual logical bitstream
  156944. index within the physical bitstream. Note that the accessor
  156945. functions above are aware of this dichotomy).
  156946. input values: buffer) a buffer to hold packed PCM data for return
  156947. length) the byte length requested to be placed into buffer
  156948. bigendianp) should the data be packed LSB first (0) or
  156949. MSB first (1)
  156950. word) word size for output. currently 1 (byte) or
  156951. 2 (16 bit short)
  156952. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  156953. 0) EOF
  156954. n) number of bytes of PCM actually returned. The
  156955. below works on a packet-by-packet basis, so the
  156956. return length is not related to the 'length' passed
  156957. in, just guaranteed to fit.
  156958. *section) set to the logical bitstream number */
  156959. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  156960. int bigendianp,int word,int sgned,int *bitstream){
  156961. int i,j;
  156962. int host_endian = host_is_big_endian();
  156963. float **pcm;
  156964. long samples;
  156965. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156966. while(1){
  156967. if(vf->ready_state==INITSET){
  156968. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  156969. if(samples)break;
  156970. }
  156971. /* suck in another packet */
  156972. {
  156973. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  156974. if(ret==OV_EOF)
  156975. return(0);
  156976. if(ret<=0)
  156977. return(ret);
  156978. }
  156979. }
  156980. if(samples>0){
  156981. /* yay! proceed to pack data into the byte buffer */
  156982. long channels=ov_info(vf,-1)->channels;
  156983. long bytespersample=word * channels;
  156984. vorbis_fpu_control fpu;
  156985. (void) fpu; // (to avoid a warning about it being unused)
  156986. if(samples>length/bytespersample)samples=length/bytespersample;
  156987. if(samples <= 0)
  156988. return OV_EINVAL;
  156989. /* a tight loop to pack each size */
  156990. {
  156991. int val;
  156992. if(word==1){
  156993. int off=(sgned?0:128);
  156994. vorbis_fpu_setround(&fpu);
  156995. for(j=0;j<samples;j++)
  156996. for(i=0;i<channels;i++){
  156997. val=vorbis_ftoi(pcm[i][j]*128.f);
  156998. if(val>127)val=127;
  156999. else if(val<-128)val=-128;
  157000. *buffer++=val+off;
  157001. }
  157002. vorbis_fpu_restore(fpu);
  157003. }else{
  157004. int off=(sgned?0:32768);
  157005. if(host_endian==bigendianp){
  157006. if(sgned){
  157007. vorbis_fpu_setround(&fpu);
  157008. for(i=0;i<channels;i++) { /* It's faster in this order */
  157009. float *src=pcm[i];
  157010. short *dest=((short *)buffer)+i;
  157011. for(j=0;j<samples;j++) {
  157012. val=vorbis_ftoi(src[j]*32768.f);
  157013. if(val>32767)val=32767;
  157014. else if(val<-32768)val=-32768;
  157015. *dest=val;
  157016. dest+=channels;
  157017. }
  157018. }
  157019. vorbis_fpu_restore(fpu);
  157020. }else{
  157021. vorbis_fpu_setround(&fpu);
  157022. for(i=0;i<channels;i++) {
  157023. float *src=pcm[i];
  157024. short *dest=((short *)buffer)+i;
  157025. for(j=0;j<samples;j++) {
  157026. val=vorbis_ftoi(src[j]*32768.f);
  157027. if(val>32767)val=32767;
  157028. else if(val<-32768)val=-32768;
  157029. *dest=val+off;
  157030. dest+=channels;
  157031. }
  157032. }
  157033. vorbis_fpu_restore(fpu);
  157034. }
  157035. }else if(bigendianp){
  157036. vorbis_fpu_setround(&fpu);
  157037. for(j=0;j<samples;j++)
  157038. for(i=0;i<channels;i++){
  157039. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157040. if(val>32767)val=32767;
  157041. else if(val<-32768)val=-32768;
  157042. val+=off;
  157043. *buffer++=(val>>8);
  157044. *buffer++=(val&0xff);
  157045. }
  157046. vorbis_fpu_restore(fpu);
  157047. }else{
  157048. int val;
  157049. vorbis_fpu_setround(&fpu);
  157050. for(j=0;j<samples;j++)
  157051. for(i=0;i<channels;i++){
  157052. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157053. if(val>32767)val=32767;
  157054. else if(val<-32768)val=-32768;
  157055. val+=off;
  157056. *buffer++=(val&0xff);
  157057. *buffer++=(val>>8);
  157058. }
  157059. vorbis_fpu_restore(fpu);
  157060. }
  157061. }
  157062. }
  157063. vorbis_synthesis_read(&vf->vd,samples);
  157064. vf->pcm_offset+=samples;
  157065. if(bitstream)*bitstream=vf->current_link;
  157066. return(samples*bytespersample);
  157067. }else{
  157068. return(samples);
  157069. }
  157070. }
  157071. /* input values: pcm_channels) a float vector per channel of output
  157072. length) the sample length being read by the app
  157073. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157074. 0) EOF
  157075. n) number of samples of PCM actually returned. The
  157076. below works on a packet-by-packet basis, so the
  157077. return length is not related to the 'length' passed
  157078. in, just guaranteed to fit.
  157079. *section) set to the logical bitstream number */
  157080. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157081. int *bitstream){
  157082. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157083. while(1){
  157084. if(vf->ready_state==INITSET){
  157085. float **pcm;
  157086. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157087. if(samples){
  157088. if(pcm_channels)*pcm_channels=pcm;
  157089. if(samples>length)samples=length;
  157090. vorbis_synthesis_read(&vf->vd,samples);
  157091. vf->pcm_offset+=samples;
  157092. if(bitstream)*bitstream=vf->current_link;
  157093. return samples;
  157094. }
  157095. }
  157096. /* suck in another packet */
  157097. {
  157098. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157099. if(ret==OV_EOF)return(0);
  157100. if(ret<=0)return(ret);
  157101. }
  157102. }
  157103. }
  157104. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157105. extern void _analysis_output_always(const char *base,int i,float *v,int n,int bark,int dB,
  157106. ogg_int64_t off);
  157107. static void _ov_splice(float **pcm,float **lappcm,
  157108. int n1, int n2,
  157109. int ch1, int ch2,
  157110. float *w1, float *w2){
  157111. int i,j;
  157112. float *w=w1;
  157113. int n=n1;
  157114. if(n1>n2){
  157115. n=n2;
  157116. w=w2;
  157117. }
  157118. /* splice */
  157119. for(j=0;j<ch1 && j<ch2;j++){
  157120. float *s=lappcm[j];
  157121. float *d=pcm[j];
  157122. for(i=0;i<n;i++){
  157123. float wd=w[i]*w[i];
  157124. float ws=1.-wd;
  157125. d[i]=d[i]*wd + s[i]*ws;
  157126. }
  157127. }
  157128. /* window from zero */
  157129. for(;j<ch2;j++){
  157130. float *d=pcm[j];
  157131. for(i=0;i<n;i++){
  157132. float wd=w[i]*w[i];
  157133. d[i]=d[i]*wd;
  157134. }
  157135. }
  157136. }
  157137. /* make sure vf is INITSET */
  157138. static int _ov_initset(OggVorbis_File *vf){
  157139. while(1){
  157140. if(vf->ready_state==INITSET)break;
  157141. /* suck in another packet */
  157142. {
  157143. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157144. if(ret<0 && ret!=OV_HOLE)return(ret);
  157145. }
  157146. }
  157147. return 0;
  157148. }
  157149. /* make sure vf is INITSET and that we have a primed buffer; if
  157150. we're crosslapping at a stream section boundary, this also makes
  157151. sure we're sanity checking against the right stream information */
  157152. static int _ov_initprime(OggVorbis_File *vf){
  157153. vorbis_dsp_state *vd=&vf->vd;
  157154. while(1){
  157155. if(vf->ready_state==INITSET)
  157156. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157157. /* suck in another packet */
  157158. {
  157159. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157160. if(ret<0 && ret!=OV_HOLE)return(ret);
  157161. }
  157162. }
  157163. return 0;
  157164. }
  157165. /* grab enough data for lapping from vf; this may be in the form of
  157166. unreturned, already-decoded pcm, remaining PCM we will need to
  157167. decode, or synthetic postextrapolation from last packets. */
  157168. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157169. float **lappcm,int lapsize){
  157170. int lapcount=0,i;
  157171. float **pcm;
  157172. /* try first to decode the lapping data */
  157173. while(lapcount<lapsize){
  157174. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157175. if(samples){
  157176. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157177. for(i=0;i<vi->channels;i++)
  157178. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157179. lapcount+=samples;
  157180. vorbis_synthesis_read(vd,samples);
  157181. }else{
  157182. /* suck in another packet */
  157183. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157184. if(ret==OV_EOF)break;
  157185. }
  157186. }
  157187. if(lapcount<lapsize){
  157188. /* failed to get lapping data from normal decode; pry it from the
  157189. postextrapolation buffering, or the second half of the MDCT
  157190. from the last packet */
  157191. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157192. if(samples==0){
  157193. for(i=0;i<vi->channels;i++)
  157194. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157195. lapcount=lapsize;
  157196. }else{
  157197. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157198. for(i=0;i<vi->channels;i++)
  157199. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157200. lapcount+=samples;
  157201. }
  157202. }
  157203. }
  157204. /* this sets up crosslapping of a sample by using trailing data from
  157205. sample 1 and lapping it into the windowing buffer of sample 2 */
  157206. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157207. vorbis_info *vi1,*vi2;
  157208. float **lappcm;
  157209. float **pcm;
  157210. float *w1,*w2;
  157211. int n1,n2,i,ret,hs1,hs2;
  157212. if(vf1==vf2)return(0); /* degenerate case */
  157213. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157214. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157215. /* the relevant overlap buffers must be pre-checked and pre-primed
  157216. before looking at settings in the event that priming would cross
  157217. a bitstream boundary. So, do it now */
  157218. ret=_ov_initset(vf1);
  157219. if(ret)return(ret);
  157220. ret=_ov_initprime(vf2);
  157221. if(ret)return(ret);
  157222. vi1=ov_info(vf1,-1);
  157223. vi2=ov_info(vf2,-1);
  157224. hs1=ov_halfrate_p(vf1);
  157225. hs2=ov_halfrate_p(vf2);
  157226. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157227. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157228. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157229. w1=vorbis_window(&vf1->vd,0);
  157230. w2=vorbis_window(&vf2->vd,0);
  157231. for(i=0;i<vi1->channels;i++)
  157232. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157233. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157234. /* have a lapping buffer from vf1; now to splice it into the lapping
  157235. buffer of vf2 */
  157236. /* consolidate and expose the buffer. */
  157237. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157238. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157239. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157240. /* splice */
  157241. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157242. /* done */
  157243. return(0);
  157244. }
  157245. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157246. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157247. vorbis_info *vi;
  157248. float **lappcm;
  157249. float **pcm;
  157250. float *w1,*w2;
  157251. int n1,n2,ch1,ch2,hs;
  157252. int i,ret;
  157253. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157254. ret=_ov_initset(vf);
  157255. if(ret)return(ret);
  157256. vi=ov_info(vf,-1);
  157257. hs=ov_halfrate_p(vf);
  157258. ch1=vi->channels;
  157259. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157260. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157261. persistent; even if the decode state
  157262. from this link gets dumped, this
  157263. window array continues to exist */
  157264. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157265. for(i=0;i<ch1;i++)
  157266. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157267. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157268. /* have lapping data; seek and prime the buffer */
  157269. ret=localseek(vf,pos);
  157270. if(ret)return ret;
  157271. ret=_ov_initprime(vf);
  157272. if(ret)return(ret);
  157273. /* Guard against cross-link changes; they're perfectly legal */
  157274. vi=ov_info(vf,-1);
  157275. ch2=vi->channels;
  157276. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157277. w2=vorbis_window(&vf->vd,0);
  157278. /* consolidate and expose the buffer. */
  157279. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157280. /* splice */
  157281. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157282. /* done */
  157283. return(0);
  157284. }
  157285. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157286. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157287. }
  157288. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157289. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157290. }
  157291. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157292. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157293. }
  157294. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157295. int (*localseek)(OggVorbis_File *,double)){
  157296. vorbis_info *vi;
  157297. float **lappcm;
  157298. float **pcm;
  157299. float *w1,*w2;
  157300. int n1,n2,ch1,ch2,hs;
  157301. int i,ret;
  157302. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157303. ret=_ov_initset(vf);
  157304. if(ret)return(ret);
  157305. vi=ov_info(vf,-1);
  157306. hs=ov_halfrate_p(vf);
  157307. ch1=vi->channels;
  157308. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157309. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157310. persistent; even if the decode state
  157311. from this link gets dumped, this
  157312. window array continues to exist */
  157313. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157314. for(i=0;i<ch1;i++)
  157315. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157316. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157317. /* have lapping data; seek and prime the buffer */
  157318. ret=localseek(vf,pos);
  157319. if(ret)return ret;
  157320. ret=_ov_initprime(vf);
  157321. if(ret)return(ret);
  157322. /* Guard against cross-link changes; they're perfectly legal */
  157323. vi=ov_info(vf,-1);
  157324. ch2=vi->channels;
  157325. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157326. w2=vorbis_window(&vf->vd,0);
  157327. /* consolidate and expose the buffer. */
  157328. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157329. /* splice */
  157330. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157331. /* done */
  157332. return(0);
  157333. }
  157334. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157335. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157336. }
  157337. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157338. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157339. }
  157340. #endif
  157341. /*** End of inlined file: vorbisfile.c ***/
  157342. /*** Start of inlined file: window.c ***/
  157343. /*** Start of inlined file: juce_OggVorbisHeader.h ***/
  157344. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157345. // tasks..
  157346. #if JUCE_MSVC
  157347. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  157348. #endif
  157349. /*** End of inlined file: juce_OggVorbisHeader.h ***/
  157350. #if JUCE_USE_OGGVORBIS
  157351. #include <stdlib.h>
  157352. #include <math.h>
  157353. static float vwin64[32] = {
  157354. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  157355. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  157356. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  157357. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  157358. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  157359. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  157360. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  157361. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  157362. };
  157363. static float vwin128[64] = {
  157364. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  157365. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  157366. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  157367. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  157368. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  157369. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  157370. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  157371. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  157372. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  157373. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  157374. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  157375. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  157376. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  157377. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  157378. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  157379. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  157380. };
  157381. static float vwin256[128] = {
  157382. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  157383. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  157384. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  157385. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  157386. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  157387. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  157388. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  157389. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  157390. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  157391. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  157392. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  157393. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  157394. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  157395. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  157396. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  157397. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  157398. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  157399. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  157400. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  157401. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  157402. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  157403. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  157404. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  157405. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  157406. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  157407. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  157408. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  157409. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  157410. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  157411. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  157412. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  157413. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  157414. };
  157415. static float vwin512[256] = {
  157416. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  157417. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  157418. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  157419. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  157420. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  157421. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  157422. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  157423. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  157424. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  157425. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  157426. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  157427. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  157428. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  157429. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  157430. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  157431. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  157432. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  157433. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  157434. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  157435. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  157436. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  157437. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  157438. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  157439. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  157440. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  157441. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  157442. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  157443. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  157444. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  157445. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  157446. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  157447. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  157448. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  157449. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  157450. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  157451. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  157452. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  157453. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  157454. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  157455. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  157456. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  157457. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  157458. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  157459. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  157460. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  157461. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  157462. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  157463. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  157464. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  157465. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  157466. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  157467. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  157468. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  157469. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  157470. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  157471. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  157472. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  157473. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  157474. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  157475. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  157476. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  157477. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  157478. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  157479. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  157480. };
  157481. static float vwin1024[512] = {
  157482. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  157483. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  157484. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  157485. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  157486. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  157487. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  157488. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  157489. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  157490. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  157491. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  157492. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  157493. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  157494. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  157495. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  157496. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  157497. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  157498. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  157499. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  157500. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  157501. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  157502. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  157503. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  157504. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  157505. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  157506. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  157507. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  157508. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  157509. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  157510. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  157511. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  157512. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  157513. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  157514. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  157515. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  157516. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  157517. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  157518. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  157519. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  157520. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  157521. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  157522. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  157523. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  157524. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  157525. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  157526. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  157527. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  157528. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  157529. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  157530. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  157531. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  157532. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  157533. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  157534. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  157535. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  157536. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  157537. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  157538. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  157539. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  157540. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  157541. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  157542. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  157543. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  157544. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  157545. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  157546. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  157547. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  157548. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  157549. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  157550. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  157551. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  157552. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  157553. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  157554. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  157555. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  157556. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  157557. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  157558. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  157559. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  157560. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  157561. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  157562. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  157563. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  157564. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  157565. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  157566. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  157567. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  157568. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  157569. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  157570. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  157571. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  157572. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  157573. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  157574. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  157575. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  157576. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  157577. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  157578. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  157579. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  157580. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  157581. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  157582. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  157583. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  157584. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  157585. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  157586. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  157587. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  157588. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  157589. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  157590. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  157591. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  157592. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  157593. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  157594. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  157595. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  157596. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  157597. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  157598. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  157599. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  157600. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  157601. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  157602. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  157603. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  157604. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  157605. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  157606. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  157607. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  157608. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  157609. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  157610. };
  157611. static float vwin2048[1024] = {
  157612. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  157613. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  157614. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  157615. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  157616. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  157617. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  157618. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  157619. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  157620. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  157621. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  157622. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  157623. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  157624. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  157625. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  157626. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  157627. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  157628. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  157629. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  157630. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  157631. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  157632. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  157633. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  157634. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  157635. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  157636. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  157637. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  157638. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  157639. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  157640. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  157641. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  157642. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  157643. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  157644. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  157645. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  157646. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  157647. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  157648. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  157649. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  157650. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  157651. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  157652. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  157653. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  157654. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  157655. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  157656. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  157657. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  157658. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  157659. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  157660. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  157661. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  157662. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  157663. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  157664. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  157665. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  157666. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  157667. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  157668. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  157669. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  157670. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  157671. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  157672. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  157673. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  157674. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  157675. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  157676. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  157677. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  157678. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  157679. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  157680. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  157681. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  157682. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  157683. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  157684. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  157685. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  157686. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  157687. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  157688. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  157689. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  157690. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  157691. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  157692. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  157693. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  157694. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  157695. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  157696. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  157697. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  157698. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  157699. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  157700. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  157701. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  157702. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  157703. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  157704. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  157705. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  157706. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  157707. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  157708. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  157709. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  157710. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  157711. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  157712. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  157713. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  157714. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  157715. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  157716. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  157717. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  157718. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  157719. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  157720. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  157721. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  157722. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  157723. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  157724. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  157725. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  157726. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  157727. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  157728. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  157729. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  157730. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  157731. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  157732. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  157733. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  157734. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  157735. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  157736. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  157737. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  157738. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  157739. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  157740. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  157741. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  157742. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  157743. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  157744. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  157745. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  157746. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  157747. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  157748. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  157749. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  157750. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  157751. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  157752. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  157753. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  157754. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  157755. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  157756. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  157757. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  157758. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  157759. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  157760. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  157761. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  157762. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  157763. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  157764. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  157765. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  157766. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  157767. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  157768. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  157769. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  157770. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  157771. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  157772. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  157773. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  157774. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  157775. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  157776. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  157777. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  157778. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  157779. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  157780. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  157781. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  157782. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  157783. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  157784. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  157785. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  157786. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  157787. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  157788. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  157789. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  157790. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  157791. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  157792. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  157793. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  157794. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  157795. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  157796. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  157797. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  157798. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  157799. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  157800. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  157801. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  157802. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  157803. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  157804. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  157805. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  157806. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  157807. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  157808. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  157809. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  157810. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  157811. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  157812. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  157813. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  157814. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  157815. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  157816. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  157817. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  157818. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  157819. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  157820. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  157821. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  157822. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  157823. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  157824. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  157825. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  157826. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  157827. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  157828. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  157829. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  157830. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  157831. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  157832. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  157833. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  157834. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  157835. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  157836. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  157837. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  157838. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  157839. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  157840. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  157841. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  157842. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  157843. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  157844. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  157845. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  157846. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  157847. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  157848. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  157849. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  157850. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  157851. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  157852. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  157853. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  157854. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  157855. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  157856. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  157857. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  157858. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  157859. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  157860. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  157861. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  157862. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  157863. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  157864. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  157865. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  157866. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  157867. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  157868. };
  157869. static float vwin4096[2048] = {
  157870. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  157871. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  157872. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  157873. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  157874. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  157875. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  157876. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  157877. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  157878. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  157879. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  157880. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  157881. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  157882. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  157883. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  157884. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  157885. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  157886. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  157887. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  157888. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  157889. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  157890. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  157891. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  157892. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  157893. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  157894. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  157895. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  157896. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  157897. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  157898. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  157899. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  157900. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  157901. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  157902. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  157903. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  157904. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  157905. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  157906. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  157907. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  157908. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  157909. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  157910. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  157911. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  157912. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  157913. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  157914. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  157915. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  157916. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  157917. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  157918. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  157919. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  157920. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  157921. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  157922. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  157923. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  157924. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  157925. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  157926. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  157927. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  157928. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  157929. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  157930. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  157931. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  157932. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  157933. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  157934. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  157935. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  157936. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  157937. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  157938. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  157939. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  157940. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  157941. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  157942. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  157943. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  157944. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  157945. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  157946. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  157947. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  157948. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  157949. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  157950. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  157951. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  157952. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  157953. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  157954. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  157955. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  157956. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  157957. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  157958. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  157959. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  157960. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  157961. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  157962. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  157963. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  157964. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  157965. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  157966. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  157967. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  157968. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  157969. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  157970. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  157971. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  157972. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  157973. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  157974. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  157975. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  157976. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  157977. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  157978. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  157979. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  157980. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  157981. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  157982. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  157983. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  157984. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  157985. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  157986. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  157987. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  157988. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  157989. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  157990. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  157991. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  157992. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  157993. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  157994. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  157995. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  157996. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  157997. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  157998. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  157999. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  158000. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  158001. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  158002. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  158003. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  158004. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  158005. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  158006. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  158007. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  158008. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  158009. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  158010. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  158011. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  158012. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  158013. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  158014. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  158015. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  158016. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  158017. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  158018. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  158019. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  158020. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  158021. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  158022. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  158023. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  158024. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  158025. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  158026. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  158027. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  158028. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  158029. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  158030. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  158031. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  158032. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  158033. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  158034. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  158035. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  158036. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  158037. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  158038. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  158039. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  158040. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158041. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158042. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158043. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158044. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158045. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158046. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158047. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158048. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158049. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158050. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158051. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158052. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158053. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158054. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158055. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158056. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158057. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158058. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158059. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158060. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158061. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158062. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158063. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158064. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158065. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158066. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158067. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158068. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158069. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158070. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158071. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158072. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158073. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158074. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158075. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158076. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158077. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158078. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158079. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158080. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158081. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158082. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158083. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158084. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158085. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158086. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158087. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158088. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158089. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158090. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158091. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158092. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158093. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158094. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158095. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158096. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158097. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158098. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158099. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158100. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158101. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158102. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158103. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158104. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158105. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158106. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158107. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158108. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158109. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158110. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158111. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158112. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158113. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158114. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158115. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158116. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158117. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158118. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158119. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158120. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158121. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158122. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158123. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158124. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158125. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158126. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158127. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158128. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158129. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158130. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158131. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158132. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158133. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158134. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158135. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158136. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158137. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158138. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158139. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158140. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158141. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158142. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158143. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158144. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158145. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158146. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158147. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158148. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158149. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158150. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158151. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158152. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158153. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158154. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158155. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158156. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158157. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158158. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158159. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158160. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158161. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158162. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158163. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158164. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158165. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158166. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158167. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158168. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158169. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158170. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158171. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158172. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158173. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158174. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158175. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158176. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158177. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158178. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158179. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158180. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158181. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158182. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158183. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158184. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158185. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158186. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158187. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158188. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158189. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158190. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158191. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158192. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158193. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158194. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158195. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158196. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158197. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158198. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158199. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158200. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158201. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158202. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158203. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158204. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158205. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158206. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158207. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158208. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158209. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158210. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158211. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158212. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158213. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158214. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158215. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158216. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158217. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158218. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158219. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158220. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158221. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158222. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158223. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158224. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158225. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158226. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158227. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158228. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158229. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158230. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158231. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158232. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158233. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158234. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158235. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158236. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158237. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158238. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158239. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158240. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158241. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158242. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158243. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158244. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158245. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158246. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  158247. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  158248. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  158249. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  158250. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  158251. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  158252. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  158253. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  158254. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  158255. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  158256. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  158257. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  158258. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  158259. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  158260. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  158261. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  158262. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  158263. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  158264. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  158265. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  158266. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  158267. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  158268. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  158269. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  158270. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  158271. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  158272. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  158273. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  158274. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  158275. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  158276. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  158277. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  158278. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  158279. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  158280. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  158281. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  158282. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  158283. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  158284. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  158285. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  158286. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  158287. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  158288. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  158289. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  158290. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  158291. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  158292. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  158293. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  158294. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  158295. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  158296. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  158297. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  158298. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  158299. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  158300. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  158301. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  158302. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  158303. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  158304. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  158305. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  158306. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  158307. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  158308. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  158309. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  158310. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  158311. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  158312. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  158313. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  158314. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  158315. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  158316. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  158317. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  158318. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  158319. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  158320. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  158321. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  158322. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  158323. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  158324. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  158325. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  158326. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  158327. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  158328. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  158329. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  158330. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  158331. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  158332. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  158333. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  158334. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  158335. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  158336. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  158337. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  158338. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  158339. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  158340. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  158341. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  158342. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  158343. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  158344. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  158345. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  158346. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  158347. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  158348. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  158349. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  158350. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  158351. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  158352. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  158353. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  158354. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  158355. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  158356. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  158357. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  158358. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  158359. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  158360. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  158361. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  158362. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  158363. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  158364. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  158365. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  158366. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  158367. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  158368. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  158369. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  158370. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  158371. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  158372. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  158373. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  158374. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  158375. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  158376. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  158377. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  158378. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  158379. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  158380. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  158381. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  158382. };
  158383. static float vwin8192[4096] = {
  158384. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  158385. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  158386. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  158387. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  158388. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  158389. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  158390. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  158391. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  158392. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  158393. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  158394. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  158395. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  158396. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  158397. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  158398. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  158399. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  158400. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  158401. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  158402. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  158403. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  158404. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  158405. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  158406. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  158407. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  158408. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  158409. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  158410. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  158411. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  158412. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  158413. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  158414. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  158415. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  158416. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  158417. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  158418. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  158419. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  158420. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  158421. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  158422. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  158423. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  158424. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  158425. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  158426. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  158427. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  158428. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  158429. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  158430. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  158431. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  158432. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  158433. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  158434. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  158435. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  158436. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  158437. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  158438. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  158439. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  158440. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  158441. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  158442. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  158443. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  158444. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  158445. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  158446. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  158447. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  158448. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  158449. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  158450. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  158451. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  158452. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  158453. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  158454. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  158455. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  158456. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  158457. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  158458. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  158459. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  158460. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  158461. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  158462. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  158463. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  158464. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  158465. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  158466. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  158467. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  158468. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  158469. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  158470. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  158471. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  158472. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  158473. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  158474. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  158475. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  158476. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  158477. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  158478. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  158479. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  158480. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  158481. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  158482. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  158483. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  158484. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  158485. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  158486. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  158487. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  158488. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  158489. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  158490. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  158491. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  158492. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  158493. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  158494. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  158495. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  158496. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  158497. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  158498. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  158499. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  158500. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  158501. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  158502. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  158503. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  158504. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  158505. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  158506. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  158507. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  158508. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  158509. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  158510. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  158511. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  158512. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  158513. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  158514. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  158515. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  158516. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  158517. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  158518. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  158519. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  158520. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  158521. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  158522. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  158523. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  158524. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  158525. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  158526. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  158527. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  158528. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  158529. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  158530. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  158531. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  158532. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  158533. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  158534. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  158535. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  158536. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  158537. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  158538. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  158539. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  158540. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  158541. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  158542. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  158543. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  158544. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  158545. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  158546. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  158547. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  158548. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  158549. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  158550. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  158551. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  158552. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  158553. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  158554. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  158555. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  158556. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  158557. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  158558. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  158559. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  158560. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  158561. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  158562. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  158563. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  158564. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  158565. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  158566. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  158567. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  158568. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  158569. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  158570. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  158571. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  158572. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  158573. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  158574. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  158575. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  158576. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  158577. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  158578. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  158579. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  158580. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  158581. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  158582. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  158583. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  158584. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  158585. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  158586. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  158587. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  158588. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  158589. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  158590. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  158591. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  158592. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  158593. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  158594. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  158595. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  158596. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  158597. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  158598. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  158599. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  158600. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  158601. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  158602. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  158603. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  158604. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  158605. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  158606. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  158607. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  158608. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  158609. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  158610. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  158611. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  158612. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  158613. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  158614. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  158615. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  158616. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  158617. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  158618. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  158619. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  158620. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  158621. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  158622. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  158623. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  158624. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  158625. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  158626. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  158627. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  158628. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  158629. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  158630. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  158631. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  158632. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  158633. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  158634. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  158635. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  158636. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  158637. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  158638. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  158639. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  158640. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  158641. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  158642. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  158643. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  158644. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  158645. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  158646. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  158647. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  158648. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  158649. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  158650. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  158651. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  158652. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  158653. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  158654. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  158655. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  158656. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  158657. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  158658. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  158659. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  158660. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  158661. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  158662. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  158663. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  158664. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  158665. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  158666. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  158667. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  158668. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  158669. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  158670. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  158671. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  158672. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  158673. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  158674. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  158675. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  158676. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  158677. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  158678. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  158679. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  158680. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  158681. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  158682. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  158683. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  158684. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  158685. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  158686. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  158687. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  158688. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  158689. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  158690. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  158691. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  158692. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  158693. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  158694. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  158695. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  158696. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  158697. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  158698. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  158699. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  158700. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  158701. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  158702. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  158703. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  158704. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  158705. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  158706. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  158707. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  158708. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  158709. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  158710. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  158711. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  158712. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  158713. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  158714. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  158715. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  158716. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  158717. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  158718. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  158719. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  158720. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  158721. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  158722. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  158723. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  158724. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  158725. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  158726. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  158727. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  158728. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  158729. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  158730. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  158731. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  158732. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  158733. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  158734. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  158735. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  158736. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  158737. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  158738. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  158739. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  158740. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  158741. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  158742. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  158743. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  158744. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  158745. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  158746. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  158747. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  158748. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  158749. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  158750. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  158751. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  158752. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  158753. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  158754. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  158755. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  158756. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  158757. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  158758. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  158759. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  158760. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  158761. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  158762. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  158763. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  158764. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  158765. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  158766. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  158767. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  158768. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  158769. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  158770. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  158771. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  158772. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  158773. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  158774. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  158775. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  158776. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  158777. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  158778. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  158779. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  158780. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  158781. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  158782. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  158783. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  158784. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  158785. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  158786. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  158787. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  158788. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  158789. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  158790. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  158791. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  158792. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  158793. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  158794. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  158795. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  158796. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  158797. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  158798. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  158799. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  158800. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  158801. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  158802. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  158803. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  158804. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  158805. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  158806. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  158807. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  158808. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  158809. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  158810. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  158811. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  158812. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  158813. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  158814. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  158815. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  158816. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  158817. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  158818. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  158819. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  158820. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  158821. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  158822. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  158823. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  158824. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  158825. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  158826. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  158827. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  158828. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  158829. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  158830. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  158831. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  158832. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  158833. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  158834. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  158835. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  158836. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  158837. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  158838. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  158839. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  158840. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  158841. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  158842. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  158843. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  158844. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  158845. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  158846. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  158847. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  158848. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  158849. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  158850. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  158851. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  158852. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  158853. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  158854. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  158855. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  158856. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  158857. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  158858. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  158859. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  158860. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  158861. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  158862. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  158863. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  158864. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  158865. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  158866. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  158867. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  158868. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  158869. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  158870. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  158871. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  158872. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  158873. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  158874. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  158875. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  158876. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  158877. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  158878. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  158879. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  158880. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  158881. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  158882. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  158883. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  158884. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  158885. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  158886. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  158887. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  158888. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  158889. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  158890. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  158891. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  158892. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  158893. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  158894. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  158895. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  158896. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  158897. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  158898. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  158899. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  158900. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  158901. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  158902. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  158903. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  158904. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  158905. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  158906. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  158907. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  158908. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  158909. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  158910. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  158911. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  158912. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  158913. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  158914. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  158915. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  158916. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  158917. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  158918. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  158919. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  158920. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  158921. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  158922. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  158923. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  158924. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  158925. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  158926. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  158927. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  158928. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  158929. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  158930. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  158931. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  158932. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  158933. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  158934. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  158935. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  158936. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  158937. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  158938. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  158939. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  158940. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  158941. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  158942. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  158943. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  158944. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  158945. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  158946. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  158947. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  158948. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  158949. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  158950. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  158951. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  158952. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  158953. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  158954. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  158955. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  158956. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  158957. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  158958. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  158959. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  158960. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  158961. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  158962. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  158963. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  158964. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  158965. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  158966. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  158967. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  158968. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  158969. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  158970. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  158971. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  158972. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  158973. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  158974. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  158975. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  158976. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  158977. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  158978. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  158979. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  158980. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  158981. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  158982. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  158983. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  158984. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  158985. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  158986. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  158987. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  158988. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  158989. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  158990. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  158991. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  158992. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  158993. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  158994. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  158995. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  158996. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  158997. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  158998. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  158999. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  159000. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  159001. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  159002. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  159003. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  159004. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  159005. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  159006. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  159007. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  159008. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  159009. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  159010. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  159011. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  159012. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  159013. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  159014. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  159015. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  159016. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  159017. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  159018. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  159019. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  159020. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  159021. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  159022. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  159023. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  159024. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  159025. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  159026. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  159027. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  159028. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  159029. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  159030. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  159031. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  159032. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  159033. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  159034. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  159035. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  159036. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  159037. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  159038. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  159039. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  159040. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159041. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159042. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159043. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159044. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159045. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159046. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159047. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159048. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159049. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159050. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159051. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159052. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159053. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159054. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159055. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159056. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159057. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159058. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159059. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159060. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159061. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159062. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159063. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159064. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159065. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159066. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159067. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159068. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159069. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159070. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159071. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159072. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159073. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159074. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159075. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159076. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159077. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159078. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159079. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159080. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159081. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159082. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159083. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159084. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159085. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159086. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159087. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159088. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159089. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159090. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159091. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159092. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159093. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159094. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159095. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159096. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159097. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159098. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159099. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159100. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159101. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159102. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159103. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159104. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159105. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159106. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159107. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159108. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159109. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159110. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159111. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159112. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159113. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159114. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159115. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159116. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159117. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159118. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159119. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159120. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159121. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159122. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159123. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159124. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159125. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159126. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159127. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159128. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159129. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159130. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159131. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159132. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159133. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159134. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159135. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159136. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159137. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159138. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159139. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159140. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159141. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159142. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159143. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159144. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159145. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159146. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159147. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159148. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159149. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159150. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159151. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159152. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159153. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159154. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159155. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159156. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159157. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159158. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159159. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159160. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159161. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159162. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159163. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159164. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159165. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159166. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159167. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159168. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159169. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159170. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159171. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159172. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159173. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159174. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159175. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159176. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159177. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159178. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159179. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159180. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159181. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159182. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159183. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159184. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159185. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159186. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159187. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159188. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159189. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159190. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159191. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159192. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159193. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159194. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159195. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159196. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159197. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159198. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159199. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159200. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159201. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159202. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159203. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159204. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159205. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159206. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159207. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159208. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159209. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159210. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159211. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159212. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159213. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159214. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159215. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159216. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159217. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159218. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159219. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159220. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159221. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159222. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159223. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159224. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159225. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159226. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159227. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159228. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159229. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159230. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159231. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159232. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159233. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159234. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159235. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159236. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159237. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159238. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159239. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159240. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159241. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159242. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159243. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159244. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159245. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159246. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  159247. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  159248. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  159249. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  159250. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  159251. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  159252. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  159253. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  159254. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  159255. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  159256. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  159257. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  159258. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  159259. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  159260. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  159261. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  159262. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  159263. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  159264. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  159265. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  159266. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  159267. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  159268. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  159269. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  159270. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  159271. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  159272. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  159273. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  159274. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  159275. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  159276. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  159277. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  159278. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  159279. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  159280. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  159281. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  159282. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  159283. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  159284. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  159285. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  159286. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  159287. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  159288. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  159289. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  159290. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  159291. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  159292. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  159293. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  159294. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  159295. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  159296. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  159297. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  159298. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  159299. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  159300. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  159301. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  159302. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  159303. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  159304. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  159305. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  159306. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  159307. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  159308. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  159309. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  159310. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  159311. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  159312. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  159313. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  159314. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  159315. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  159316. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  159317. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  159318. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  159319. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  159320. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  159321. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  159322. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  159323. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  159324. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  159325. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  159326. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  159327. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  159328. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  159329. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  159330. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  159331. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  159332. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  159333. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  159334. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  159335. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  159336. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  159337. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  159338. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  159339. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  159340. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  159341. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  159342. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  159343. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  159344. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  159345. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  159346. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  159347. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  159348. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  159349. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  159350. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  159351. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  159352. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  159353. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  159354. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  159355. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  159356. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  159357. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  159358. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  159359. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  159360. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  159361. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  159362. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  159363. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  159364. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  159365. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  159366. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  159367. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  159368. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  159369. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  159370. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  159371. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  159372. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  159373. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  159374. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  159375. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  159376. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  159377. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  159378. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  159379. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  159380. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  159381. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  159382. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  159383. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  159384. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  159385. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  159386. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  159387. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  159388. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  159389. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  159390. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  159391. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  159392. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  159393. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  159394. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  159395. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  159396. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  159397. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  159398. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  159399. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  159400. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  159401. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  159402. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  159403. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  159404. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  159405. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  159406. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159407. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159408. };
  159409. static float *vwin[8] = {
  159410. vwin64,
  159411. vwin128,
  159412. vwin256,
  159413. vwin512,
  159414. vwin1024,
  159415. vwin2048,
  159416. vwin4096,
  159417. vwin8192,
  159418. };
  159419. float *_vorbis_window_get(int n){
  159420. return vwin[n];
  159421. }
  159422. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  159423. int lW,int W,int nW){
  159424. lW=(W?lW:0);
  159425. nW=(W?nW:0);
  159426. {
  159427. float *windowLW=vwin[winno[lW]];
  159428. float *windowNW=vwin[winno[nW]];
  159429. long n=blocksizes[W];
  159430. long ln=blocksizes[lW];
  159431. long rn=blocksizes[nW];
  159432. long leftbegin=n/4-ln/4;
  159433. long leftend=leftbegin+ln/2;
  159434. long rightbegin=n/2+n/4-rn/4;
  159435. long rightend=rightbegin+rn/2;
  159436. int i,p;
  159437. for(i=0;i<leftbegin;i++)
  159438. d[i]=0.f;
  159439. for(p=0;i<leftend;i++,p++)
  159440. d[i]*=windowLW[p];
  159441. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  159442. d[i]*=windowNW[p];
  159443. for(;i<n;i++)
  159444. d[i]=0.f;
  159445. }
  159446. }
  159447. #endif
  159448. /*** End of inlined file: window.c ***/
  159449. #else
  159450. #include <vorbis/vorbisenc.h>
  159451. #include <vorbis/codec.h>
  159452. #include <vorbis/vorbisfile.h>
  159453. #endif
  159454. }
  159455. #undef max
  159456. #undef min
  159457. BEGIN_JUCE_NAMESPACE
  159458. static const char* const oggFormatName = "Ogg-Vorbis file";
  159459. static const char* const oggExtensions[] = { ".ogg", 0 };
  159460. class OggReader : public AudioFormatReader
  159461. {
  159462. OggVorbisNamespace::OggVorbis_File ovFile;
  159463. OggVorbisNamespace::ov_callbacks callbacks;
  159464. AudioSampleBuffer reservoir;
  159465. int reservoirStart, samplesInReservoir;
  159466. public:
  159467. OggReader (InputStream* const inp)
  159468. : AudioFormatReader (inp, TRANS (oggFormatName)),
  159469. reservoir (2, 4096),
  159470. reservoirStart (0),
  159471. samplesInReservoir (0)
  159472. {
  159473. using namespace OggVorbisNamespace;
  159474. sampleRate = 0;
  159475. usesFloatingPointData = true;
  159476. callbacks.read_func = &oggReadCallback;
  159477. callbacks.seek_func = &oggSeekCallback;
  159478. callbacks.close_func = &oggCloseCallback;
  159479. callbacks.tell_func = &oggTellCallback;
  159480. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  159481. if (err == 0)
  159482. {
  159483. vorbis_info* info = ov_info (&ovFile, -1);
  159484. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  159485. numChannels = info->channels;
  159486. bitsPerSample = 16;
  159487. sampleRate = info->rate;
  159488. reservoir.setSize (numChannels,
  159489. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  159490. }
  159491. }
  159492. ~OggReader()
  159493. {
  159494. OggVorbisNamespace::ov_clear (&ovFile);
  159495. }
  159496. bool readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  159497. int64 startSampleInFile, int numSamples)
  159498. {
  159499. while (numSamples > 0)
  159500. {
  159501. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  159502. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  159503. {
  159504. // got a few samples overlapping, so use them before seeking..
  159505. const int numToUse = jmin (numSamples, numAvailable);
  159506. for (int i = jmin (numDestChannels, reservoir.getNumChannels()); --i >= 0;)
  159507. if (destSamples[i] != 0)
  159508. memcpy (destSamples[i] + startOffsetInDestBuffer,
  159509. reservoir.getSampleData (i, (int) (startSampleInFile - reservoirStart)),
  159510. sizeof (float) * numToUse);
  159511. startSampleInFile += numToUse;
  159512. numSamples -= numToUse;
  159513. startOffsetInDestBuffer += numToUse;
  159514. if (numSamples == 0)
  159515. break;
  159516. }
  159517. if (startSampleInFile < reservoirStart
  159518. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  159519. {
  159520. // buffer miss, so refill the reservoir
  159521. int bitStream = 0;
  159522. reservoirStart = jmax (0, (int) startSampleInFile);
  159523. samplesInReservoir = reservoir.getNumSamples();
  159524. if (reservoirStart != (int) OggVorbisNamespace::ov_pcm_tell (&ovFile))
  159525. OggVorbisNamespace::ov_pcm_seek (&ovFile, reservoirStart);
  159526. int offset = 0;
  159527. int numToRead = samplesInReservoir;
  159528. while (numToRead > 0)
  159529. {
  159530. float** dataIn = 0;
  159531. const int samps = OggVorbisNamespace::ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  159532. if (samps <= 0)
  159533. break;
  159534. jassert (samps <= numToRead);
  159535. for (int i = jmin ((int) numChannels, reservoir.getNumChannels()); --i >= 0;)
  159536. {
  159537. memcpy (reservoir.getSampleData (i, offset),
  159538. dataIn[i],
  159539. sizeof (float) * samps);
  159540. }
  159541. numToRead -= samps;
  159542. offset += samps;
  159543. }
  159544. if (numToRead > 0)
  159545. reservoir.clear (offset, numToRead);
  159546. }
  159547. }
  159548. if (numSamples > 0)
  159549. {
  159550. for (int i = numDestChannels; --i >= 0;)
  159551. if (destSamples[i] != 0)
  159552. zeromem (destSamples[i] + startOffsetInDestBuffer,
  159553. sizeof (int) * numSamples);
  159554. }
  159555. return true;
  159556. }
  159557. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  159558. {
  159559. return (size_t) (static_cast <InputStream*> (datasource)->read (ptr, (int) (size * nmemb)) / size);
  159560. }
  159561. static int oggSeekCallback (void* datasource, OggVorbisNamespace::ogg_int64_t offset, int whence)
  159562. {
  159563. InputStream* const in = static_cast <InputStream*> (datasource);
  159564. if (whence == SEEK_CUR)
  159565. offset += in->getPosition();
  159566. else if (whence == SEEK_END)
  159567. offset += in->getTotalLength();
  159568. in->setPosition (offset);
  159569. return 0;
  159570. }
  159571. static int oggCloseCallback (void*)
  159572. {
  159573. return 0;
  159574. }
  159575. static long oggTellCallback (void* datasource)
  159576. {
  159577. return (long) static_cast <InputStream*> (datasource)->getPosition();
  159578. }
  159579. juce_UseDebuggingNewOperator
  159580. };
  159581. class OggWriter : public AudioFormatWriter
  159582. {
  159583. OggVorbisNamespace::ogg_stream_state os;
  159584. OggVorbisNamespace::ogg_page og;
  159585. OggVorbisNamespace::ogg_packet op;
  159586. OggVorbisNamespace::vorbis_info vi;
  159587. OggVorbisNamespace::vorbis_comment vc;
  159588. OggVorbisNamespace::vorbis_dsp_state vd;
  159589. OggVorbisNamespace::vorbis_block vb;
  159590. public:
  159591. bool ok;
  159592. OggWriter (OutputStream* const out,
  159593. const double sampleRate,
  159594. const int numChannels,
  159595. const int bitsPerSample,
  159596. const int qualityIndex)
  159597. : AudioFormatWriter (out, TRANS (oggFormatName),
  159598. sampleRate,
  159599. numChannels,
  159600. bitsPerSample)
  159601. {
  159602. using namespace OggVorbisNamespace;
  159603. ok = false;
  159604. vorbis_info_init (&vi);
  159605. if (vorbis_encode_init_vbr (&vi,
  159606. numChannels,
  159607. (int) sampleRate,
  159608. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  159609. {
  159610. vorbis_comment_init (&vc);
  159611. if (JUCEApplication::getInstance() != 0)
  159612. vorbis_comment_add_tag (&vc, "ENCODER", const_cast <char*> (JUCEApplication::getInstance()->getApplicationName().toUTF8()));
  159613. vorbis_analysis_init (&vd, &vi);
  159614. vorbis_block_init (&vd, &vb);
  159615. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  159616. ogg_packet header;
  159617. ogg_packet header_comm;
  159618. ogg_packet header_code;
  159619. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  159620. ogg_stream_packetin (&os, &header);
  159621. ogg_stream_packetin (&os, &header_comm);
  159622. ogg_stream_packetin (&os, &header_code);
  159623. for (;;)
  159624. {
  159625. if (ogg_stream_flush (&os, &og) == 0)
  159626. break;
  159627. output->write (og.header, og.header_len);
  159628. output->write (og.body, og.body_len);
  159629. }
  159630. ok = true;
  159631. }
  159632. }
  159633. ~OggWriter()
  159634. {
  159635. using namespace OggVorbisNamespace;
  159636. if (ok)
  159637. {
  159638. // write a zero-length packet to show ogg that we're finished..
  159639. write (0, 0);
  159640. ogg_stream_clear (&os);
  159641. vorbis_block_clear (&vb);
  159642. vorbis_dsp_clear (&vd);
  159643. vorbis_comment_clear (&vc);
  159644. vorbis_info_clear (&vi);
  159645. output->flush();
  159646. }
  159647. else
  159648. {
  159649. vorbis_info_clear (&vi);
  159650. output = 0; // to stop the base class deleting this, as it needs to be returned
  159651. // to the caller of createWriter()
  159652. }
  159653. }
  159654. bool write (const int** samplesToWrite, int numSamples)
  159655. {
  159656. using namespace OggVorbisNamespace;
  159657. if (! ok)
  159658. return false;
  159659. if (numSamples > 0)
  159660. {
  159661. const double gain = 1.0 / 0x80000000u;
  159662. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  159663. for (int i = numChannels; --i >= 0;)
  159664. {
  159665. float* const dst = vorbisBuffer[i];
  159666. const int* const src = samplesToWrite [i];
  159667. if (src != 0 && dst != 0)
  159668. {
  159669. for (int j = 0; j < numSamples; ++j)
  159670. dst[j] = (float) (src[j] * gain);
  159671. }
  159672. }
  159673. }
  159674. vorbis_analysis_wrote (&vd, numSamples);
  159675. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  159676. {
  159677. vorbis_analysis (&vb, 0);
  159678. vorbis_bitrate_addblock (&vb);
  159679. while (vorbis_bitrate_flushpacket (&vd, &op))
  159680. {
  159681. ogg_stream_packetin (&os, &op);
  159682. for (;;)
  159683. {
  159684. if (ogg_stream_pageout (&os, &og) == 0)
  159685. break;
  159686. output->write (og.header, og.header_len);
  159687. output->write (og.body, og.body_len);
  159688. if (ogg_page_eos (&og))
  159689. break;
  159690. }
  159691. }
  159692. }
  159693. return true;
  159694. }
  159695. juce_UseDebuggingNewOperator
  159696. };
  159697. OggVorbisAudioFormat::OggVorbisAudioFormat()
  159698. : AudioFormat (TRANS (oggFormatName), StringArray (oggExtensions))
  159699. {
  159700. }
  159701. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  159702. {
  159703. }
  159704. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  159705. {
  159706. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  159707. return Array <int> (rates);
  159708. }
  159709. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  159710. {
  159711. const int depths[] = { 32, 0 };
  159712. return Array <int> (depths);
  159713. }
  159714. bool OggVorbisAudioFormat::canDoStereo() { return true; }
  159715. bool OggVorbisAudioFormat::canDoMono() { return true; }
  159716. bool OggVorbisAudioFormat::isCompressed() { return true; }
  159717. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  159718. const bool deleteStreamIfOpeningFails)
  159719. {
  159720. ScopedPointer <OggReader> r (new OggReader (in));
  159721. if (r->sampleRate != 0)
  159722. return r.release();
  159723. if (! deleteStreamIfOpeningFails)
  159724. r->input = 0;
  159725. return 0;
  159726. }
  159727. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  159728. double sampleRate,
  159729. unsigned int numChannels,
  159730. int bitsPerSample,
  159731. const StringPairArray& /*metadataValues*/,
  159732. int qualityOptionIndex)
  159733. {
  159734. ScopedPointer <OggWriter> w (new OggWriter (out,
  159735. sampleRate,
  159736. numChannels,
  159737. bitsPerSample,
  159738. qualityOptionIndex));
  159739. return w->ok ? w.release() : 0;
  159740. }
  159741. const StringArray OggVorbisAudioFormat::getQualityOptions()
  159742. {
  159743. StringArray s;
  159744. s.add ("Low Quality");
  159745. s.add ("Medium Quality");
  159746. s.add ("High Quality");
  159747. return s;
  159748. }
  159749. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  159750. {
  159751. FileInputStream* const in = source.createInputStream();
  159752. if (in != 0)
  159753. {
  159754. ScopedPointer <AudioFormatReader> r (createReaderFor (in, true));
  159755. if (r != 0)
  159756. {
  159757. const int64 numSamps = r->lengthInSamples;
  159758. r = 0;
  159759. const int64 fileNumSamps = source.getSize() / 4;
  159760. const double ratio = numSamps / (double) fileNumSamps;
  159761. if (ratio > 12.0)
  159762. return 0;
  159763. else if (ratio > 6.0)
  159764. return 1;
  159765. else
  159766. return 2;
  159767. }
  159768. }
  159769. return 1;
  159770. }
  159771. END_JUCE_NAMESPACE
  159772. #endif
  159773. /*** End of inlined file: juce_OggVorbisAudioFormat.cpp ***/
  159774. #endif
  159775. #if JUCE_BUILD_CORE && ! JUCE_ONLY_BUILD_CORE_LIBRARY // do these in the core section to help balance the sizes
  159776. /*** Start of inlined file: juce_JPEGLoader.cpp ***/
  159777. #if JUCE_MSVC
  159778. #pragma warning (push)
  159779. #endif
  159780. namespace jpeglibNamespace
  159781. {
  159782. #if JUCE_INCLUDE_JPEGLIB_CODE
  159783. #if JUCE_MINGW
  159784. typedef unsigned char boolean;
  159785. #endif
  159786. #define JPEG_INTERNALS
  159787. #undef FAR
  159788. /*** Start of inlined file: jpeglib.h ***/
  159789. #ifndef JPEGLIB_H
  159790. #define JPEGLIB_H
  159791. /*
  159792. * First we include the configuration files that record how this
  159793. * installation of the JPEG library is set up. jconfig.h can be
  159794. * generated automatically for many systems. jmorecfg.h contains
  159795. * manual configuration options that most people need not worry about.
  159796. */
  159797. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  159798. /*** Start of inlined file: jconfig.h ***/
  159799. /* see jconfig.doc for explanations */
  159800. // disable all the warnings under MSVC
  159801. #ifdef _MSC_VER
  159802. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  159803. #endif
  159804. #ifdef __BORLANDC__
  159805. #pragma warn -8057
  159806. #pragma warn -8019
  159807. #pragma warn -8004
  159808. #pragma warn -8008
  159809. #endif
  159810. #define HAVE_PROTOTYPES
  159811. #define HAVE_UNSIGNED_CHAR
  159812. #define HAVE_UNSIGNED_SHORT
  159813. /* #define void char */
  159814. /* #define const */
  159815. #undef CHAR_IS_UNSIGNED
  159816. #define HAVE_STDDEF_H
  159817. #define HAVE_STDLIB_H
  159818. #undef NEED_BSD_STRINGS
  159819. #undef NEED_SYS_TYPES_H
  159820. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  159821. #undef NEED_SHORT_EXTERNAL_NAMES
  159822. #undef INCOMPLETE_TYPES_BROKEN
  159823. /* Define "boolean" as unsigned char, not int, per Windows custom */
  159824. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  159825. typedef unsigned char boolean;
  159826. #endif
  159827. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  159828. #ifdef JPEG_INTERNALS
  159829. #undef RIGHT_SHIFT_IS_UNSIGNED
  159830. #endif /* JPEG_INTERNALS */
  159831. #ifdef JPEG_CJPEG_DJPEG
  159832. #define BMP_SUPPORTED /* BMP image file format */
  159833. #define GIF_SUPPORTED /* GIF image file format */
  159834. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  159835. #undef RLE_SUPPORTED /* Utah RLE image file format */
  159836. #define TARGA_SUPPORTED /* Targa image file format */
  159837. #define TWO_FILE_COMMANDLINE /* optional */
  159838. #define USE_SETMODE /* Microsoft has setmode() */
  159839. #undef NEED_SIGNAL_CATCHER
  159840. #undef DONT_USE_B_MODE
  159841. #undef PROGRESS_REPORT /* optional */
  159842. #endif /* JPEG_CJPEG_DJPEG */
  159843. /*** End of inlined file: jconfig.h ***/
  159844. /* widely used configuration options */
  159845. #endif
  159846. /*** Start of inlined file: jmorecfg.h ***/
  159847. /*
  159848. * Define BITS_IN_JSAMPLE as either
  159849. * 8 for 8-bit sample values (the usual setting)
  159850. * 12 for 12-bit sample values
  159851. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  159852. * JPEG standard, and the IJG code does not support anything else!
  159853. * We do not support run-time selection of data precision, sorry.
  159854. */
  159855. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  159856. /*
  159857. * Maximum number of components (color channels) allowed in JPEG image.
  159858. * To meet the letter of the JPEG spec, set this to 255. However, darn
  159859. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  159860. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  159861. * really short on memory. (Each allowed component costs a hundred or so
  159862. * bytes of storage, whether actually used in an image or not.)
  159863. */
  159864. #define MAX_COMPONENTS 10 /* maximum number of image components */
  159865. /*
  159866. * Basic data types.
  159867. * You may need to change these if you have a machine with unusual data
  159868. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  159869. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  159870. * but it had better be at least 16.
  159871. */
  159872. /* Representation of a single sample (pixel element value).
  159873. * We frequently allocate large arrays of these, so it's important to keep
  159874. * them small. But if you have memory to burn and access to char or short
  159875. * arrays is very slow on your hardware, you might want to change these.
  159876. */
  159877. #if BITS_IN_JSAMPLE == 8
  159878. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  159879. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  159880. */
  159881. #ifdef HAVE_UNSIGNED_CHAR
  159882. typedef unsigned char JSAMPLE;
  159883. #define GETJSAMPLE(value) ((int) (value))
  159884. #else /* not HAVE_UNSIGNED_CHAR */
  159885. typedef char JSAMPLE;
  159886. #ifdef CHAR_IS_UNSIGNED
  159887. #define GETJSAMPLE(value) ((int) (value))
  159888. #else
  159889. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  159890. #endif /* CHAR_IS_UNSIGNED */
  159891. #endif /* HAVE_UNSIGNED_CHAR */
  159892. #define MAXJSAMPLE 255
  159893. #define CENTERJSAMPLE 128
  159894. #endif /* BITS_IN_JSAMPLE == 8 */
  159895. #if BITS_IN_JSAMPLE == 12
  159896. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  159897. * On nearly all machines "short" will do nicely.
  159898. */
  159899. typedef short JSAMPLE;
  159900. #define GETJSAMPLE(value) ((int) (value))
  159901. #define MAXJSAMPLE 4095
  159902. #define CENTERJSAMPLE 2048
  159903. #endif /* BITS_IN_JSAMPLE == 12 */
  159904. /* Representation of a DCT frequency coefficient.
  159905. * This should be a signed value of at least 16 bits; "short" is usually OK.
  159906. * Again, we allocate large arrays of these, but you can change to int
  159907. * if you have memory to burn and "short" is really slow.
  159908. */
  159909. typedef short JCOEF;
  159910. /* Compressed datastreams are represented as arrays of JOCTET.
  159911. * These must be EXACTLY 8 bits wide, at least once they are written to
  159912. * external storage. Note that when using the stdio data source/destination
  159913. * managers, this is also the data type passed to fread/fwrite.
  159914. */
  159915. #ifdef HAVE_UNSIGNED_CHAR
  159916. typedef unsigned char JOCTET;
  159917. #define GETJOCTET(value) (value)
  159918. #else /* not HAVE_UNSIGNED_CHAR */
  159919. typedef char JOCTET;
  159920. #ifdef CHAR_IS_UNSIGNED
  159921. #define GETJOCTET(value) (value)
  159922. #else
  159923. #define GETJOCTET(value) ((value) & 0xFF)
  159924. #endif /* CHAR_IS_UNSIGNED */
  159925. #endif /* HAVE_UNSIGNED_CHAR */
  159926. /* These typedefs are used for various table entries and so forth.
  159927. * They must be at least as wide as specified; but making them too big
  159928. * won't cost a huge amount of memory, so we don't provide special
  159929. * extraction code like we did for JSAMPLE. (In other words, these
  159930. * typedefs live at a different point on the speed/space tradeoff curve.)
  159931. */
  159932. /* UINT8 must hold at least the values 0..255. */
  159933. #ifdef HAVE_UNSIGNED_CHAR
  159934. typedef unsigned char UINT8;
  159935. #else /* not HAVE_UNSIGNED_CHAR */
  159936. #ifdef CHAR_IS_UNSIGNED
  159937. typedef char UINT8;
  159938. #else /* not CHAR_IS_UNSIGNED */
  159939. typedef short UINT8;
  159940. #endif /* CHAR_IS_UNSIGNED */
  159941. #endif /* HAVE_UNSIGNED_CHAR */
  159942. /* UINT16 must hold at least the values 0..65535. */
  159943. #ifdef HAVE_UNSIGNED_SHORT
  159944. typedef unsigned short UINT16;
  159945. #else /* not HAVE_UNSIGNED_SHORT */
  159946. typedef unsigned int UINT16;
  159947. #endif /* HAVE_UNSIGNED_SHORT */
  159948. /* INT16 must hold at least the values -32768..32767. */
  159949. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  159950. typedef short INT16;
  159951. #endif
  159952. /* INT32 must hold at least signed 32-bit values. */
  159953. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  159954. typedef long INT32;
  159955. #endif
  159956. /* Datatype used for image dimensions. The JPEG standard only supports
  159957. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  159958. * "unsigned int" is sufficient on all machines. However, if you need to
  159959. * handle larger images and you don't mind deviating from the spec, you
  159960. * can change this datatype.
  159961. */
  159962. typedef unsigned int JDIMENSION;
  159963. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  159964. /* These macros are used in all function definitions and extern declarations.
  159965. * You could modify them if you need to change function linkage conventions;
  159966. * in particular, you'll need to do that to make the library a Windows DLL.
  159967. * Another application is to make all functions global for use with debuggers
  159968. * or code profilers that require it.
  159969. */
  159970. /* a function called through method pointers: */
  159971. #define METHODDEF(type) static type
  159972. /* a function used only in its module: */
  159973. #define LOCAL(type) static type
  159974. /* a function referenced thru EXTERNs: */
  159975. #define GLOBAL(type) type
  159976. /* a reference to a GLOBAL function: */
  159977. #define EXTERN(type) extern type
  159978. /* This macro is used to declare a "method", that is, a function pointer.
  159979. * We want to supply prototype parameters if the compiler can cope.
  159980. * Note that the arglist parameter must be parenthesized!
  159981. * Again, you can customize this if you need special linkage keywords.
  159982. */
  159983. #ifdef HAVE_PROTOTYPES
  159984. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  159985. #else
  159986. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  159987. #endif
  159988. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  159989. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  159990. * by just saying "FAR *" where such a pointer is needed. In a few places
  159991. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  159992. */
  159993. #ifdef NEED_FAR_POINTERS
  159994. #define FAR far
  159995. #else
  159996. #define FAR
  159997. #endif
  159998. /*
  159999. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  160000. * in standard header files. Or you may have conflicts with application-
  160001. * specific header files that you want to include together with these files.
  160002. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  160003. */
  160004. #ifndef HAVE_BOOLEAN
  160005. typedef int boolean;
  160006. #endif
  160007. #ifndef FALSE /* in case these macros already exist */
  160008. #define FALSE 0 /* values of boolean */
  160009. #endif
  160010. #ifndef TRUE
  160011. #define TRUE 1
  160012. #endif
  160013. /*
  160014. * The remaining options affect code selection within the JPEG library,
  160015. * but they don't need to be visible to most applications using the library.
  160016. * To minimize application namespace pollution, the symbols won't be
  160017. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  160018. */
  160019. #ifdef JPEG_INTERNALS
  160020. #define JPEG_INTERNAL_OPTIONS
  160021. #endif
  160022. #ifdef JPEG_INTERNAL_OPTIONS
  160023. /*
  160024. * These defines indicate whether to include various optional functions.
  160025. * Undefining some of these symbols will produce a smaller but less capable
  160026. * library. Note that you can leave certain source files out of the
  160027. * compilation/linking process if you've #undef'd the corresponding symbols.
  160028. * (You may HAVE to do that if your compiler doesn't like null source files.)
  160029. */
  160030. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  160031. /* Capability options common to encoder and decoder: */
  160032. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  160033. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160034. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160035. /* Encoder capability options: */
  160036. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160037. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160038. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160039. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160040. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160041. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160042. * precision, so jchuff.c normally uses entropy optimization to compute
  160043. * usable tables for higher precision. If you don't want to do optimization,
  160044. * you'll have to supply different default Huffman tables.
  160045. * The exact same statements apply for progressive JPEG: the default tables
  160046. * don't work for progressive mode. (This may get fixed, however.)
  160047. */
  160048. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160049. /* Decoder capability options: */
  160050. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160051. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160052. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160053. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160054. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160055. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160056. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160057. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160058. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160059. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160060. /* more capability options later, no doubt */
  160061. /*
  160062. * Ordering of RGB data in scanlines passed to or from the application.
  160063. * If your application wants to deal with data in the order B,G,R, just
  160064. * change these macros. You can also deal with formats such as R,G,B,X
  160065. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160066. * the offsets will also change the order in which colormap data is organized.
  160067. * RESTRICTIONS:
  160068. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160069. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160070. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160071. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160072. * is not 3 (they don't understand about dummy color components!). So you
  160073. * can't use color quantization if you change that value.
  160074. */
  160075. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160076. #define RGB_GREEN 1 /* Offset of Green */
  160077. #define RGB_BLUE 2 /* Offset of Blue */
  160078. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160079. /* Definitions for speed-related optimizations. */
  160080. /* If your compiler supports inline functions, define INLINE
  160081. * as the inline keyword; otherwise define it as empty.
  160082. */
  160083. #ifndef INLINE
  160084. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160085. #define INLINE __inline__
  160086. #endif
  160087. #ifndef INLINE
  160088. #define INLINE /* default is to define it as empty */
  160089. #endif
  160090. #endif
  160091. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160092. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160093. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160094. */
  160095. #ifndef MULTIPLIER
  160096. #define MULTIPLIER int /* type for fastest integer multiply */
  160097. #endif
  160098. /* FAST_FLOAT should be either float or double, whichever is done faster
  160099. * by your compiler. (Note that this type is only used in the floating point
  160100. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160101. * Typically, float is faster in ANSI C compilers, while double is faster in
  160102. * pre-ANSI compilers (because they insist on converting to double anyway).
  160103. * The code below therefore chooses float if we have ANSI-style prototypes.
  160104. */
  160105. #ifndef FAST_FLOAT
  160106. #ifdef HAVE_PROTOTYPES
  160107. #define FAST_FLOAT float
  160108. #else
  160109. #define FAST_FLOAT double
  160110. #endif
  160111. #endif
  160112. #endif /* JPEG_INTERNAL_OPTIONS */
  160113. /*** End of inlined file: jmorecfg.h ***/
  160114. /* seldom changed options */
  160115. /* Version ID for the JPEG library.
  160116. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160117. */
  160118. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160119. /* Various constants determining the sizes of things.
  160120. * All of these are specified by the JPEG standard, so don't change them
  160121. * if you want to be compatible.
  160122. */
  160123. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160124. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160125. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160126. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160127. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160128. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160129. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160130. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160131. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160132. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160133. * to handle it. We even let you do this from the jconfig.h file. However,
  160134. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160135. * sometimes emits noncompliant files doesn't mean you should too.
  160136. */
  160137. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160138. #ifndef D_MAX_BLOCKS_IN_MCU
  160139. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160140. #endif
  160141. /* Data structures for images (arrays of samples and of DCT coefficients).
  160142. * On 80x86 machines, the image arrays are too big for near pointers,
  160143. * but the pointer arrays can fit in near memory.
  160144. */
  160145. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160146. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160147. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160148. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160149. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160150. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160151. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160152. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160153. /* Types for JPEG compression parameters and working tables. */
  160154. /* DCT coefficient quantization tables. */
  160155. typedef struct {
  160156. /* This array gives the coefficient quantizers in natural array order
  160157. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160158. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160159. */
  160160. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160161. /* This field is used only during compression. It's initialized FALSE when
  160162. * the table is created, and set TRUE when it's been output to the file.
  160163. * You could suppress output of a table by setting this to TRUE.
  160164. * (See jpeg_suppress_tables for an example.)
  160165. */
  160166. boolean sent_table; /* TRUE when table has been output */
  160167. } JQUANT_TBL;
  160168. /* Huffman coding tables. */
  160169. typedef struct {
  160170. /* These two fields directly represent the contents of a JPEG DHT marker */
  160171. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160172. /* length k bits; bits[0] is unused */
  160173. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160174. /* This field is used only during compression. It's initialized FALSE when
  160175. * the table is created, and set TRUE when it's been output to the file.
  160176. * You could suppress output of a table by setting this to TRUE.
  160177. * (See jpeg_suppress_tables for an example.)
  160178. */
  160179. boolean sent_table; /* TRUE when table has been output */
  160180. } JHUFF_TBL;
  160181. /* Basic info about one component (color channel). */
  160182. typedef struct {
  160183. /* These values are fixed over the whole image. */
  160184. /* For compression, they must be supplied by parameter setup; */
  160185. /* for decompression, they are read from the SOF marker. */
  160186. int component_id; /* identifier for this component (0..255) */
  160187. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160188. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160189. int v_samp_factor; /* vertical sampling factor (1..4) */
  160190. int quant_tbl_no; /* quantization table selector (0..3) */
  160191. /* These values may vary between scans. */
  160192. /* For compression, they must be supplied by parameter setup; */
  160193. /* for decompression, they are read from the SOS marker. */
  160194. /* The decompressor output side may not use these variables. */
  160195. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160196. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160197. /* Remaining fields should be treated as private by applications. */
  160198. /* These values are computed during compression or decompression startup: */
  160199. /* Component's size in DCT blocks.
  160200. * Any dummy blocks added to complete an MCU are not counted; therefore
  160201. * these values do not depend on whether a scan is interleaved or not.
  160202. */
  160203. JDIMENSION width_in_blocks;
  160204. JDIMENSION height_in_blocks;
  160205. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160206. * For decompression this is the size of the output from one DCT block,
  160207. * reflecting any scaling we choose to apply during the IDCT step.
  160208. * Values of 1,2,4,8 are likely to be supported. Note that different
  160209. * components may receive different IDCT scalings.
  160210. */
  160211. int DCT_scaled_size;
  160212. /* The downsampled dimensions are the component's actual, unpadded number
  160213. * of samples at the main buffer (preprocessing/compression interface), thus
  160214. * downsampled_width = ceil(image_width * Hi/Hmax)
  160215. * and similarly for height. For decompression, IDCT scaling is included, so
  160216. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160217. */
  160218. JDIMENSION downsampled_width; /* actual width in samples */
  160219. JDIMENSION downsampled_height; /* actual height in samples */
  160220. /* This flag is used only for decompression. In cases where some of the
  160221. * components will be ignored (eg grayscale output from YCbCr image),
  160222. * we can skip most computations for the unused components.
  160223. */
  160224. boolean component_needed; /* do we need the value of this component? */
  160225. /* These values are computed before starting a scan of the component. */
  160226. /* The decompressor output side may not use these variables. */
  160227. int MCU_width; /* number of blocks per MCU, horizontally */
  160228. int MCU_height; /* number of blocks per MCU, vertically */
  160229. int MCU_blocks; /* MCU_width * MCU_height */
  160230. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  160231. int last_col_width; /* # of non-dummy blocks across in last MCU */
  160232. int last_row_height; /* # of non-dummy blocks down in last MCU */
  160233. /* Saved quantization table for component; NULL if none yet saved.
  160234. * See jdinput.c comments about the need for this information.
  160235. * This field is currently used only for decompression.
  160236. */
  160237. JQUANT_TBL * quant_table;
  160238. /* Private per-component storage for DCT or IDCT subsystem. */
  160239. void * dct_table;
  160240. } jpeg_component_info;
  160241. /* The script for encoding a multiple-scan file is an array of these: */
  160242. typedef struct {
  160243. int comps_in_scan; /* number of components encoded in this scan */
  160244. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  160245. int Ss, Se; /* progressive JPEG spectral selection parms */
  160246. int Ah, Al; /* progressive JPEG successive approx. parms */
  160247. } jpeg_scan_info;
  160248. /* The decompressor can save APPn and COM markers in a list of these: */
  160249. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  160250. struct jpeg_marker_struct {
  160251. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  160252. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  160253. unsigned int original_length; /* # bytes of data in the file */
  160254. unsigned int data_length; /* # bytes of data saved at data[] */
  160255. JOCTET FAR * data; /* the data contained in the marker */
  160256. /* the marker length word is not counted in data_length or original_length */
  160257. };
  160258. /* Known color spaces. */
  160259. typedef enum {
  160260. JCS_UNKNOWN, /* error/unspecified */
  160261. JCS_GRAYSCALE, /* monochrome */
  160262. JCS_RGB, /* red/green/blue */
  160263. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  160264. JCS_CMYK, /* C/M/Y/K */
  160265. JCS_YCCK /* Y/Cb/Cr/K */
  160266. } J_COLOR_SPACE;
  160267. /* DCT/IDCT algorithm options. */
  160268. typedef enum {
  160269. JDCT_ISLOW, /* slow but accurate integer algorithm */
  160270. JDCT_IFAST, /* faster, less accurate integer method */
  160271. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  160272. } J_DCT_METHOD;
  160273. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  160274. #define JDCT_DEFAULT JDCT_ISLOW
  160275. #endif
  160276. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  160277. #define JDCT_FASTEST JDCT_IFAST
  160278. #endif
  160279. /* Dithering options for decompression. */
  160280. typedef enum {
  160281. JDITHER_NONE, /* no dithering */
  160282. JDITHER_ORDERED, /* simple ordered dither */
  160283. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  160284. } J_DITHER_MODE;
  160285. /* Common fields between JPEG compression and decompression master structs. */
  160286. #define jpeg_common_fields \
  160287. struct jpeg_error_mgr * err; /* Error handler module */\
  160288. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  160289. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  160290. void * client_data; /* Available for use by application */\
  160291. boolean is_decompressor; /* So common code can tell which is which */\
  160292. int global_state /* For checking call sequence validity */
  160293. /* Routines that are to be used by both halves of the library are declared
  160294. * to receive a pointer to this structure. There are no actual instances of
  160295. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  160296. */
  160297. struct jpeg_common_struct {
  160298. jpeg_common_fields; /* Fields common to both master struct types */
  160299. /* Additional fields follow in an actual jpeg_compress_struct or
  160300. * jpeg_decompress_struct. All three structs must agree on these
  160301. * initial fields! (This would be a lot cleaner in C++.)
  160302. */
  160303. };
  160304. typedef struct jpeg_common_struct * j_common_ptr;
  160305. typedef struct jpeg_compress_struct * j_compress_ptr;
  160306. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  160307. /* Master record for a compression instance */
  160308. struct jpeg_compress_struct {
  160309. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  160310. /* Destination for compressed data */
  160311. struct jpeg_destination_mgr * dest;
  160312. /* Description of source image --- these fields must be filled in by
  160313. * outer application before starting compression. in_color_space must
  160314. * be correct before you can even call jpeg_set_defaults().
  160315. */
  160316. JDIMENSION image_width; /* input image width */
  160317. JDIMENSION image_height; /* input image height */
  160318. int input_components; /* # of color components in input image */
  160319. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  160320. double input_gamma; /* image gamma of input image */
  160321. /* Compression parameters --- these fields must be set before calling
  160322. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  160323. * initialize everything to reasonable defaults, then changing anything
  160324. * the application specifically wants to change. That way you won't get
  160325. * burnt when new parameters are added. Also note that there are several
  160326. * helper routines to simplify changing parameters.
  160327. */
  160328. int data_precision; /* bits of precision in image data */
  160329. int num_components; /* # of color components in JPEG image */
  160330. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160331. jpeg_component_info * comp_info;
  160332. /* comp_info[i] describes component that appears i'th in SOF */
  160333. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160334. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160335. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160336. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160337. /* ptrs to Huffman coding tables, or NULL if not defined */
  160338. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160339. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160340. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160341. int num_scans; /* # of entries in scan_info array */
  160342. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  160343. /* The default value of scan_info is NULL, which causes a single-scan
  160344. * sequential JPEG file to be emitted. To create a multi-scan file,
  160345. * set num_scans and scan_info to point to an array of scan definitions.
  160346. */
  160347. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  160348. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160349. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  160350. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160351. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  160352. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  160353. /* The restart interval can be specified in absolute MCUs by setting
  160354. * restart_interval, or in MCU rows by setting restart_in_rows
  160355. * (in which case the correct restart_interval will be figured
  160356. * for each scan).
  160357. */
  160358. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  160359. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  160360. /* Parameters controlling emission of special markers. */
  160361. boolean write_JFIF_header; /* should a JFIF marker be written? */
  160362. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  160363. UINT8 JFIF_minor_version;
  160364. /* These three values are not used by the JPEG code, merely copied */
  160365. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  160366. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  160367. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  160368. UINT8 density_unit; /* JFIF code for pixel size units */
  160369. UINT16 X_density; /* Horizontal pixel density */
  160370. UINT16 Y_density; /* Vertical pixel density */
  160371. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  160372. /* State variable: index of next scanline to be written to
  160373. * jpeg_write_scanlines(). Application may use this to control its
  160374. * processing loop, e.g., "while (next_scanline < image_height)".
  160375. */
  160376. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  160377. /* Remaining fields are known throughout compressor, but generally
  160378. * should not be touched by a surrounding application.
  160379. */
  160380. /*
  160381. * These fields are computed during compression startup
  160382. */
  160383. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  160384. int max_h_samp_factor; /* largest h_samp_factor */
  160385. int max_v_samp_factor; /* largest v_samp_factor */
  160386. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  160387. /* The coefficient controller receives data in units of MCU rows as defined
  160388. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  160389. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  160390. * "iMCU" (interleaved MCU) row.
  160391. */
  160392. /*
  160393. * These fields are valid during any one scan.
  160394. * They describe the components and MCUs actually appearing in the scan.
  160395. */
  160396. int comps_in_scan; /* # of JPEG components in this scan */
  160397. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160398. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160399. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160400. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160401. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160402. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  160403. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160404. /* i'th block in an MCU */
  160405. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160406. /*
  160407. * Links to compression subobjects (methods and private variables of modules)
  160408. */
  160409. struct jpeg_comp_master * master;
  160410. struct jpeg_c_main_controller * main;
  160411. struct jpeg_c_prep_controller * prep;
  160412. struct jpeg_c_coef_controller * coef;
  160413. struct jpeg_marker_writer * marker;
  160414. struct jpeg_color_converter * cconvert;
  160415. struct jpeg_downsampler * downsample;
  160416. struct jpeg_forward_dct * fdct;
  160417. struct jpeg_entropy_encoder * entropy;
  160418. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  160419. int script_space_size;
  160420. };
  160421. /* Master record for a decompression instance */
  160422. struct jpeg_decompress_struct {
  160423. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  160424. /* Source of compressed data */
  160425. struct jpeg_source_mgr * src;
  160426. /* Basic description of image --- filled in by jpeg_read_header(). */
  160427. /* Application may inspect these values to decide how to process image. */
  160428. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  160429. JDIMENSION image_height; /* nominal image height */
  160430. int num_components; /* # of color components in JPEG image */
  160431. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  160432. /* Decompression processing parameters --- these fields must be set before
  160433. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  160434. * them to default values.
  160435. */
  160436. J_COLOR_SPACE out_color_space; /* colorspace for output */
  160437. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  160438. double output_gamma; /* image gamma wanted in output */
  160439. boolean buffered_image; /* TRUE=multiple output passes */
  160440. boolean raw_data_out; /* TRUE=downsampled data wanted */
  160441. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  160442. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  160443. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  160444. boolean quantize_colors; /* TRUE=colormapped output wanted */
  160445. /* the following are ignored if not quantize_colors: */
  160446. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  160447. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  160448. int desired_number_of_colors; /* max # colors to use in created colormap */
  160449. /* these are significant only in buffered-image mode: */
  160450. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  160451. boolean enable_external_quant;/* enable future use of external colormap */
  160452. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  160453. /* Description of actual output image that will be returned to application.
  160454. * These fields are computed by jpeg_start_decompress().
  160455. * You can also use jpeg_calc_output_dimensions() to determine these values
  160456. * in advance of calling jpeg_start_decompress().
  160457. */
  160458. JDIMENSION output_width; /* scaled image width */
  160459. JDIMENSION output_height; /* scaled image height */
  160460. int out_color_components; /* # of color components in out_color_space */
  160461. int output_components; /* # of color components returned */
  160462. /* output_components is 1 (a colormap index) when quantizing colors;
  160463. * otherwise it equals out_color_components.
  160464. */
  160465. int rec_outbuf_height; /* min recommended height of scanline buffer */
  160466. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  160467. * high, space and time will be wasted due to unnecessary data copying.
  160468. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  160469. */
  160470. /* When quantizing colors, the output colormap is described by these fields.
  160471. * The application can supply a colormap by setting colormap non-NULL before
  160472. * calling jpeg_start_decompress; otherwise a colormap is created during
  160473. * jpeg_start_decompress or jpeg_start_output.
  160474. * The map has out_color_components rows and actual_number_of_colors columns.
  160475. */
  160476. int actual_number_of_colors; /* number of entries in use */
  160477. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  160478. /* State variables: these variables indicate the progress of decompression.
  160479. * The application may examine these but must not modify them.
  160480. */
  160481. /* Row index of next scanline to be read from jpeg_read_scanlines().
  160482. * Application may use this to control its processing loop, e.g.,
  160483. * "while (output_scanline < output_height)".
  160484. */
  160485. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  160486. /* Current input scan number and number of iMCU rows completed in scan.
  160487. * These indicate the progress of the decompressor input side.
  160488. */
  160489. int input_scan_number; /* Number of SOS markers seen so far */
  160490. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  160491. /* The "output scan number" is the notional scan being displayed by the
  160492. * output side. The decompressor will not allow output scan/row number
  160493. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  160494. */
  160495. int output_scan_number; /* Nominal scan number being displayed */
  160496. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  160497. /* Current progression status. coef_bits[c][i] indicates the precision
  160498. * with which component c's DCT coefficient i (in zigzag order) is known.
  160499. * It is -1 when no data has yet been received, otherwise it is the point
  160500. * transform (shift) value for the most recent scan of the coefficient
  160501. * (thus, 0 at completion of the progression).
  160502. * This pointer is NULL when reading a non-progressive file.
  160503. */
  160504. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  160505. /* Internal JPEG parameters --- the application usually need not look at
  160506. * these fields. Note that the decompressor output side may not use
  160507. * any parameters that can change between scans.
  160508. */
  160509. /* Quantization and Huffman tables are carried forward across input
  160510. * datastreams when processing abbreviated JPEG datastreams.
  160511. */
  160512. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  160513. /* ptrs to coefficient quantization tables, or NULL if not defined */
  160514. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160515. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  160516. /* ptrs to Huffman coding tables, or NULL if not defined */
  160517. /* These parameters are never carried across datastreams, since they
  160518. * are given in SOF/SOS markers or defined to be reset by SOI.
  160519. */
  160520. int data_precision; /* bits of precision in image data */
  160521. jpeg_component_info * comp_info;
  160522. /* comp_info[i] describes component that appears i'th in SOF */
  160523. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  160524. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  160525. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  160526. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  160527. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  160528. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  160529. /* These fields record data obtained from optional markers recognized by
  160530. * the JPEG library.
  160531. */
  160532. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  160533. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  160534. UINT8 JFIF_major_version; /* JFIF version number */
  160535. UINT8 JFIF_minor_version;
  160536. UINT8 density_unit; /* JFIF code for pixel size units */
  160537. UINT16 X_density; /* Horizontal pixel density */
  160538. UINT16 Y_density; /* Vertical pixel density */
  160539. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  160540. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  160541. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  160542. /* Aside from the specific data retained from APPn markers known to the
  160543. * library, the uninterpreted contents of any or all APPn and COM markers
  160544. * can be saved in a list for examination by the application.
  160545. */
  160546. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  160547. /* Remaining fields are known throughout decompressor, but generally
  160548. * should not be touched by a surrounding application.
  160549. */
  160550. /*
  160551. * These fields are computed during decompression startup
  160552. */
  160553. int max_h_samp_factor; /* largest h_samp_factor */
  160554. int max_v_samp_factor; /* largest v_samp_factor */
  160555. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  160556. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  160557. /* The coefficient controller's input and output progress is measured in
  160558. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  160559. * in fully interleaved JPEG scans, but are used whether the scan is
  160560. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  160561. * rows of each component. Therefore, the IDCT output contains
  160562. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  160563. */
  160564. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  160565. /*
  160566. * These fields are valid during any one scan.
  160567. * They describe the components and MCUs actually appearing in the scan.
  160568. * Note that the decompressor output side must not use these fields.
  160569. */
  160570. int comps_in_scan; /* # of JPEG components in this scan */
  160571. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  160572. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  160573. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  160574. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  160575. int blocks_in_MCU; /* # of DCT blocks per MCU */
  160576. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  160577. /* MCU_membership[i] is index in cur_comp_info of component owning */
  160578. /* i'th block in an MCU */
  160579. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  160580. /* This field is shared between entropy decoder and marker parser.
  160581. * It is either zero or the code of a JPEG marker that has been
  160582. * read from the data source, but has not yet been processed.
  160583. */
  160584. int unread_marker;
  160585. /*
  160586. * Links to decompression subobjects (methods, private variables of modules)
  160587. */
  160588. struct jpeg_decomp_master * master;
  160589. struct jpeg_d_main_controller * main;
  160590. struct jpeg_d_coef_controller * coef;
  160591. struct jpeg_d_post_controller * post;
  160592. struct jpeg_input_controller * inputctl;
  160593. struct jpeg_marker_reader * marker;
  160594. struct jpeg_entropy_decoder * entropy;
  160595. struct jpeg_inverse_dct * idct;
  160596. struct jpeg_upsampler * upsample;
  160597. struct jpeg_color_deconverter * cconvert;
  160598. struct jpeg_color_quantizer * cquantize;
  160599. };
  160600. /* "Object" declarations for JPEG modules that may be supplied or called
  160601. * directly by the surrounding application.
  160602. * As with all objects in the JPEG library, these structs only define the
  160603. * publicly visible methods and state variables of a module. Additional
  160604. * private fields may exist after the public ones.
  160605. */
  160606. /* Error handler object */
  160607. struct jpeg_error_mgr {
  160608. /* Error exit handler: does not return to caller */
  160609. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  160610. /* Conditionally emit a trace or warning message */
  160611. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  160612. /* Routine that actually outputs a trace or error message */
  160613. JMETHOD(void, output_message, (j_common_ptr cinfo));
  160614. /* Format a message string for the most recent JPEG error or message */
  160615. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  160616. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  160617. /* Reset error state variables at start of a new image */
  160618. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  160619. /* The message ID code and any parameters are saved here.
  160620. * A message can have one string parameter or up to 8 int parameters.
  160621. */
  160622. int msg_code;
  160623. #define JMSG_STR_PARM_MAX 80
  160624. union {
  160625. int i[8];
  160626. char s[JMSG_STR_PARM_MAX];
  160627. } msg_parm;
  160628. /* Standard state variables for error facility */
  160629. int trace_level; /* max msg_level that will be displayed */
  160630. /* For recoverable corrupt-data errors, we emit a warning message,
  160631. * but keep going unless emit_message chooses to abort. emit_message
  160632. * should count warnings in num_warnings. The surrounding application
  160633. * can check for bad data by seeing if num_warnings is nonzero at the
  160634. * end of processing.
  160635. */
  160636. long num_warnings; /* number of corrupt-data warnings */
  160637. /* These fields point to the table(s) of error message strings.
  160638. * An application can change the table pointer to switch to a different
  160639. * message list (typically, to change the language in which errors are
  160640. * reported). Some applications may wish to add additional error codes
  160641. * that will be handled by the JPEG library error mechanism; the second
  160642. * table pointer is used for this purpose.
  160643. *
  160644. * First table includes all errors generated by JPEG library itself.
  160645. * Error code 0 is reserved for a "no such error string" message.
  160646. */
  160647. const char * const * jpeg_message_table; /* Library errors */
  160648. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  160649. /* Second table can be added by application (see cjpeg/djpeg for example).
  160650. * It contains strings numbered first_addon_message..last_addon_message.
  160651. */
  160652. const char * const * addon_message_table; /* Non-library errors */
  160653. int first_addon_message; /* code for first string in addon table */
  160654. int last_addon_message; /* code for last string in addon table */
  160655. };
  160656. /* Progress monitor object */
  160657. struct jpeg_progress_mgr {
  160658. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  160659. long pass_counter; /* work units completed in this pass */
  160660. long pass_limit; /* total number of work units in this pass */
  160661. int completed_passes; /* passes completed so far */
  160662. int total_passes; /* total number of passes expected */
  160663. };
  160664. /* Data destination object for compression */
  160665. struct jpeg_destination_mgr {
  160666. JOCTET * next_output_byte; /* => next byte to write in buffer */
  160667. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  160668. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  160669. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  160670. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  160671. };
  160672. /* Data source object for decompression */
  160673. struct jpeg_source_mgr {
  160674. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  160675. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  160676. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  160677. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  160678. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  160679. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  160680. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  160681. };
  160682. /* Memory manager object.
  160683. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  160684. * and "really big" objects (virtual arrays with backing store if needed).
  160685. * The memory manager does not allow individual objects to be freed; rather,
  160686. * each created object is assigned to a pool, and whole pools can be freed
  160687. * at once. This is faster and more convenient than remembering exactly what
  160688. * to free, especially where malloc()/free() are not too speedy.
  160689. * NB: alloc routines never return NULL. They exit to error_exit if not
  160690. * successful.
  160691. */
  160692. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  160693. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  160694. #define JPOOL_NUMPOOLS 2
  160695. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  160696. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  160697. struct jpeg_memory_mgr {
  160698. /* Method pointers */
  160699. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  160700. size_t sizeofobject));
  160701. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  160702. size_t sizeofobject));
  160703. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  160704. JDIMENSION samplesperrow,
  160705. JDIMENSION numrows));
  160706. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  160707. JDIMENSION blocksperrow,
  160708. JDIMENSION numrows));
  160709. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  160710. int pool_id,
  160711. boolean pre_zero,
  160712. JDIMENSION samplesperrow,
  160713. JDIMENSION numrows,
  160714. JDIMENSION maxaccess));
  160715. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  160716. int pool_id,
  160717. boolean pre_zero,
  160718. JDIMENSION blocksperrow,
  160719. JDIMENSION numrows,
  160720. JDIMENSION maxaccess));
  160721. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  160722. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  160723. jvirt_sarray_ptr ptr,
  160724. JDIMENSION start_row,
  160725. JDIMENSION num_rows,
  160726. boolean writable));
  160727. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  160728. jvirt_barray_ptr ptr,
  160729. JDIMENSION start_row,
  160730. JDIMENSION num_rows,
  160731. boolean writable));
  160732. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  160733. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  160734. /* Limit on memory allocation for this JPEG object. (Note that this is
  160735. * merely advisory, not a guaranteed maximum; it only affects the space
  160736. * used for virtual-array buffers.) May be changed by outer application
  160737. * after creating the JPEG object.
  160738. */
  160739. long max_memory_to_use;
  160740. /* Maximum allocation request accepted by alloc_large. */
  160741. long max_alloc_chunk;
  160742. };
  160743. /* Routine signature for application-supplied marker processing methods.
  160744. * Need not pass marker code since it is stored in cinfo->unread_marker.
  160745. */
  160746. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  160747. /* Declarations for routines called by application.
  160748. * The JPP macro hides prototype parameters from compilers that can't cope.
  160749. * Note JPP requires double parentheses.
  160750. */
  160751. #ifdef HAVE_PROTOTYPES
  160752. #define JPP(arglist) arglist
  160753. #else
  160754. #define JPP(arglist) ()
  160755. #endif
  160756. /* Short forms of external names for systems with brain-damaged linkers.
  160757. * We shorten external names to be unique in the first six letters, which
  160758. * is good enough for all known systems.
  160759. * (If your compiler itself needs names to be unique in less than 15
  160760. * characters, you are out of luck. Get a better compiler.)
  160761. */
  160762. #ifdef NEED_SHORT_EXTERNAL_NAMES
  160763. #define jpeg_std_error jStdError
  160764. #define jpeg_CreateCompress jCreaCompress
  160765. #define jpeg_CreateDecompress jCreaDecompress
  160766. #define jpeg_destroy_compress jDestCompress
  160767. #define jpeg_destroy_decompress jDestDecompress
  160768. #define jpeg_stdio_dest jStdDest
  160769. #define jpeg_stdio_src jStdSrc
  160770. #define jpeg_set_defaults jSetDefaults
  160771. #define jpeg_set_colorspace jSetColorspace
  160772. #define jpeg_default_colorspace jDefColorspace
  160773. #define jpeg_set_quality jSetQuality
  160774. #define jpeg_set_linear_quality jSetLQuality
  160775. #define jpeg_add_quant_table jAddQuantTable
  160776. #define jpeg_quality_scaling jQualityScaling
  160777. #define jpeg_simple_progression jSimProgress
  160778. #define jpeg_suppress_tables jSuppressTables
  160779. #define jpeg_alloc_quant_table jAlcQTable
  160780. #define jpeg_alloc_huff_table jAlcHTable
  160781. #define jpeg_start_compress jStrtCompress
  160782. #define jpeg_write_scanlines jWrtScanlines
  160783. #define jpeg_finish_compress jFinCompress
  160784. #define jpeg_write_raw_data jWrtRawData
  160785. #define jpeg_write_marker jWrtMarker
  160786. #define jpeg_write_m_header jWrtMHeader
  160787. #define jpeg_write_m_byte jWrtMByte
  160788. #define jpeg_write_tables jWrtTables
  160789. #define jpeg_read_header jReadHeader
  160790. #define jpeg_start_decompress jStrtDecompress
  160791. #define jpeg_read_scanlines jReadScanlines
  160792. #define jpeg_finish_decompress jFinDecompress
  160793. #define jpeg_read_raw_data jReadRawData
  160794. #define jpeg_has_multiple_scans jHasMultScn
  160795. #define jpeg_start_output jStrtOutput
  160796. #define jpeg_finish_output jFinOutput
  160797. #define jpeg_input_complete jInComplete
  160798. #define jpeg_new_colormap jNewCMap
  160799. #define jpeg_consume_input jConsumeInput
  160800. #define jpeg_calc_output_dimensions jCalcDimensions
  160801. #define jpeg_save_markers jSaveMarkers
  160802. #define jpeg_set_marker_processor jSetMarker
  160803. #define jpeg_read_coefficients jReadCoefs
  160804. #define jpeg_write_coefficients jWrtCoefs
  160805. #define jpeg_copy_critical_parameters jCopyCrit
  160806. #define jpeg_abort_compress jAbrtCompress
  160807. #define jpeg_abort_decompress jAbrtDecompress
  160808. #define jpeg_abort jAbort
  160809. #define jpeg_destroy jDestroy
  160810. #define jpeg_resync_to_restart jResyncRestart
  160811. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  160812. /* Default error-management setup */
  160813. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  160814. JPP((struct jpeg_error_mgr * err));
  160815. /* Initialization of JPEG compression objects.
  160816. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  160817. * names that applications should call. These expand to calls on
  160818. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  160819. * passed for version mismatch checking.
  160820. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  160821. */
  160822. #define jpeg_create_compress(cinfo) \
  160823. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  160824. (size_t) sizeof(struct jpeg_compress_struct))
  160825. #define jpeg_create_decompress(cinfo) \
  160826. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  160827. (size_t) sizeof(struct jpeg_decompress_struct))
  160828. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  160829. int version, size_t structsize));
  160830. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  160831. int version, size_t structsize));
  160832. /* Destruction of JPEG compression objects */
  160833. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  160834. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  160835. /* Standard data source and destination managers: stdio streams. */
  160836. /* Caller is responsible for opening the file before and closing after. */
  160837. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  160838. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  160839. /* Default parameter setup for compression */
  160840. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  160841. /* Compression parameter setup aids */
  160842. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  160843. J_COLOR_SPACE colorspace));
  160844. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  160845. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  160846. boolean force_baseline));
  160847. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  160848. int scale_factor,
  160849. boolean force_baseline));
  160850. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  160851. const unsigned int *basic_table,
  160852. int scale_factor,
  160853. boolean force_baseline));
  160854. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  160855. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  160856. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  160857. boolean suppress));
  160858. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  160859. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  160860. /* Main entry points for compression */
  160861. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  160862. boolean write_all_tables));
  160863. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  160864. JSAMPARRAY scanlines,
  160865. JDIMENSION num_lines));
  160866. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  160867. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  160868. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  160869. JSAMPIMAGE data,
  160870. JDIMENSION num_lines));
  160871. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  160872. EXTERN(void) jpeg_write_marker
  160873. JPP((j_compress_ptr cinfo, int marker,
  160874. const JOCTET * dataptr, unsigned int datalen));
  160875. /* Same, but piecemeal. */
  160876. EXTERN(void) jpeg_write_m_header
  160877. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  160878. EXTERN(void) jpeg_write_m_byte
  160879. JPP((j_compress_ptr cinfo, int val));
  160880. /* Alternate compression function: just write an abbreviated table file */
  160881. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  160882. /* Decompression startup: read start of JPEG datastream to see what's there */
  160883. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  160884. boolean require_image));
  160885. /* Return value is one of: */
  160886. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  160887. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  160888. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  160889. /* If you pass require_image = TRUE (normal case), you need not check for
  160890. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  160891. * JPEG_SUSPENDED is only possible if you use a data source module that can
  160892. * give a suspension return (the stdio source module doesn't).
  160893. */
  160894. /* Main entry points for decompression */
  160895. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  160896. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  160897. JSAMPARRAY scanlines,
  160898. JDIMENSION max_lines));
  160899. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  160900. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  160901. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  160902. JSAMPIMAGE data,
  160903. JDIMENSION max_lines));
  160904. /* Additional entry points for buffered-image mode. */
  160905. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  160906. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  160907. int scan_number));
  160908. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  160909. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  160910. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  160911. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  160912. /* Return value is one of: */
  160913. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  160914. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  160915. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  160916. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  160917. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  160918. /* Precalculate output dimensions for current decompression parameters. */
  160919. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  160920. /* Control saving of COM and APPn markers into marker_list. */
  160921. EXTERN(void) jpeg_save_markers
  160922. JPP((j_decompress_ptr cinfo, int marker_code,
  160923. unsigned int length_limit));
  160924. /* Install a special processing method for COM or APPn markers. */
  160925. EXTERN(void) jpeg_set_marker_processor
  160926. JPP((j_decompress_ptr cinfo, int marker_code,
  160927. jpeg_marker_parser_method routine));
  160928. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  160929. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  160930. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  160931. jvirt_barray_ptr * coef_arrays));
  160932. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  160933. j_compress_ptr dstinfo));
  160934. /* If you choose to abort compression or decompression before completing
  160935. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  160936. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  160937. * if you're done with the JPEG object, but if you want to clean it up and
  160938. * reuse it, call this:
  160939. */
  160940. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  160941. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  160942. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  160943. * flavor of JPEG object. These may be more convenient in some places.
  160944. */
  160945. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  160946. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  160947. /* Default restart-marker-resync procedure for use by data source modules */
  160948. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  160949. int desired));
  160950. /* These marker codes are exported since applications and data source modules
  160951. * are likely to want to use them.
  160952. */
  160953. #define JPEG_RST0 0xD0 /* RST0 marker code */
  160954. #define JPEG_EOI 0xD9 /* EOI marker code */
  160955. #define JPEG_APP0 0xE0 /* APP0 marker code */
  160956. #define JPEG_COM 0xFE /* COM marker code */
  160957. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  160958. * for structure definitions that are never filled in, keep it quiet by
  160959. * supplying dummy definitions for the various substructures.
  160960. */
  160961. #ifdef INCOMPLETE_TYPES_BROKEN
  160962. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  160963. struct jvirt_sarray_control { long dummy; };
  160964. struct jvirt_barray_control { long dummy; };
  160965. struct jpeg_comp_master { long dummy; };
  160966. struct jpeg_c_main_controller { long dummy; };
  160967. struct jpeg_c_prep_controller { long dummy; };
  160968. struct jpeg_c_coef_controller { long dummy; };
  160969. struct jpeg_marker_writer { long dummy; };
  160970. struct jpeg_color_converter { long dummy; };
  160971. struct jpeg_downsampler { long dummy; };
  160972. struct jpeg_forward_dct { long dummy; };
  160973. struct jpeg_entropy_encoder { long dummy; };
  160974. struct jpeg_decomp_master { long dummy; };
  160975. struct jpeg_d_main_controller { long dummy; };
  160976. struct jpeg_d_coef_controller { long dummy; };
  160977. struct jpeg_d_post_controller { long dummy; };
  160978. struct jpeg_input_controller { long dummy; };
  160979. struct jpeg_marker_reader { long dummy; };
  160980. struct jpeg_entropy_decoder { long dummy; };
  160981. struct jpeg_inverse_dct { long dummy; };
  160982. struct jpeg_upsampler { long dummy; };
  160983. struct jpeg_color_deconverter { long dummy; };
  160984. struct jpeg_color_quantizer { long dummy; };
  160985. #endif /* JPEG_INTERNALS */
  160986. #endif /* INCOMPLETE_TYPES_BROKEN */
  160987. /*
  160988. * The JPEG library modules define JPEG_INTERNALS before including this file.
  160989. * The internal structure declarations are read only when that is true.
  160990. * Applications using the library should not include jpegint.h, but may wish
  160991. * to include jerror.h.
  160992. */
  160993. #ifdef JPEG_INTERNALS
  160994. /*** Start of inlined file: jpegint.h ***/
  160995. /* Declarations for both compression & decompression */
  160996. typedef enum { /* Operating modes for buffer controllers */
  160997. JBUF_PASS_THRU, /* Plain stripwise operation */
  160998. /* Remaining modes require a full-image buffer to have been created */
  160999. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  161000. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  161001. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  161002. } J_BUF_MODE;
  161003. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  161004. #define CSTATE_START 100 /* after create_compress */
  161005. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  161006. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  161007. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  161008. #define DSTATE_START 200 /* after create_decompress */
  161009. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  161010. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  161011. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  161012. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  161013. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  161014. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  161015. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  161016. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  161017. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  161018. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  161019. /* Declarations for compression modules */
  161020. /* Master control module */
  161021. struct jpeg_comp_master {
  161022. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  161023. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  161024. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161025. /* State variables made visible to other modules */
  161026. boolean call_pass_startup; /* True if pass_startup must be called */
  161027. boolean is_last_pass; /* True during last pass */
  161028. };
  161029. /* Main buffer control (downsampled-data buffer) */
  161030. struct jpeg_c_main_controller {
  161031. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161032. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  161033. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161034. JDIMENSION in_rows_avail));
  161035. };
  161036. /* Compression preprocessing (downsampling input buffer control) */
  161037. struct jpeg_c_prep_controller {
  161038. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161039. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161040. JSAMPARRAY input_buf,
  161041. JDIMENSION *in_row_ctr,
  161042. JDIMENSION in_rows_avail,
  161043. JSAMPIMAGE output_buf,
  161044. JDIMENSION *out_row_group_ctr,
  161045. JDIMENSION out_row_groups_avail));
  161046. };
  161047. /* Coefficient buffer control */
  161048. struct jpeg_c_coef_controller {
  161049. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161050. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161051. JSAMPIMAGE input_buf));
  161052. };
  161053. /* Colorspace conversion */
  161054. struct jpeg_color_converter {
  161055. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161056. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161057. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161058. JDIMENSION output_row, int num_rows));
  161059. };
  161060. /* Downsampling */
  161061. struct jpeg_downsampler {
  161062. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161063. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161064. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161065. JSAMPIMAGE output_buf,
  161066. JDIMENSION out_row_group_index));
  161067. boolean need_context_rows; /* TRUE if need rows above & below */
  161068. };
  161069. /* Forward DCT (also controls coefficient quantization) */
  161070. struct jpeg_forward_dct {
  161071. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161072. /* perhaps this should be an array??? */
  161073. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161074. jpeg_component_info * compptr,
  161075. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161076. JDIMENSION start_row, JDIMENSION start_col,
  161077. JDIMENSION num_blocks));
  161078. };
  161079. /* Entropy encoding */
  161080. struct jpeg_entropy_encoder {
  161081. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161082. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161083. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161084. };
  161085. /* Marker writing */
  161086. struct jpeg_marker_writer {
  161087. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161088. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161089. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161090. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161091. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161092. /* These routines are exported to allow insertion of extra markers */
  161093. /* Probably only COM and APPn markers should be written this way */
  161094. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161095. unsigned int datalen));
  161096. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161097. };
  161098. /* Declarations for decompression modules */
  161099. /* Master control module */
  161100. struct jpeg_decomp_master {
  161101. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161102. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161103. /* State variables made visible to other modules */
  161104. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161105. };
  161106. /* Input control module */
  161107. struct jpeg_input_controller {
  161108. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161109. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161110. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161111. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161112. /* State variables made visible to other modules */
  161113. boolean has_multiple_scans; /* True if file has multiple scans */
  161114. boolean eoi_reached; /* True when EOI has been consumed */
  161115. };
  161116. /* Main buffer control (downsampled-data buffer) */
  161117. struct jpeg_d_main_controller {
  161118. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161119. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161120. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161121. JDIMENSION out_rows_avail));
  161122. };
  161123. /* Coefficient buffer control */
  161124. struct jpeg_d_coef_controller {
  161125. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161126. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161127. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161128. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161129. JSAMPIMAGE output_buf));
  161130. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161131. jvirt_barray_ptr *coef_arrays;
  161132. };
  161133. /* Decompression postprocessing (color quantization buffer control) */
  161134. struct jpeg_d_post_controller {
  161135. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161136. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161137. JSAMPIMAGE input_buf,
  161138. JDIMENSION *in_row_group_ctr,
  161139. JDIMENSION in_row_groups_avail,
  161140. JSAMPARRAY output_buf,
  161141. JDIMENSION *out_row_ctr,
  161142. JDIMENSION out_rows_avail));
  161143. };
  161144. /* Marker reading & parsing */
  161145. struct jpeg_marker_reader {
  161146. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161147. /* Read markers until SOS or EOI.
  161148. * Returns same codes as are defined for jpeg_consume_input:
  161149. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161150. */
  161151. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161152. /* Read a restart marker --- exported for use by entropy decoder only */
  161153. jpeg_marker_parser_method read_restart_marker;
  161154. /* State of marker reader --- nominally internal, but applications
  161155. * supplying COM or APPn handlers might like to know the state.
  161156. */
  161157. boolean saw_SOI; /* found SOI? */
  161158. boolean saw_SOF; /* found SOF? */
  161159. int next_restart_num; /* next restart number expected (0-7) */
  161160. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161161. };
  161162. /* Entropy decoding */
  161163. struct jpeg_entropy_decoder {
  161164. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161165. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161166. JBLOCKROW *MCU_data));
  161167. /* This is here to share code between baseline and progressive decoders; */
  161168. /* other modules probably should not use it */
  161169. boolean insufficient_data; /* set TRUE after emitting warning */
  161170. };
  161171. /* Inverse DCT (also performs dequantization) */
  161172. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161173. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161174. JCOEFPTR coef_block,
  161175. JSAMPARRAY output_buf, JDIMENSION output_col));
  161176. struct jpeg_inverse_dct {
  161177. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161178. /* It is useful to allow each component to have a separate IDCT method. */
  161179. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161180. };
  161181. /* Upsampling (note that upsampler must also call color converter) */
  161182. struct jpeg_upsampler {
  161183. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161184. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161185. JSAMPIMAGE input_buf,
  161186. JDIMENSION *in_row_group_ctr,
  161187. JDIMENSION in_row_groups_avail,
  161188. JSAMPARRAY output_buf,
  161189. JDIMENSION *out_row_ctr,
  161190. JDIMENSION out_rows_avail));
  161191. boolean need_context_rows; /* TRUE if need rows above & below */
  161192. };
  161193. /* Colorspace conversion */
  161194. struct jpeg_color_deconverter {
  161195. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161196. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161197. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161198. JSAMPARRAY output_buf, int num_rows));
  161199. };
  161200. /* Color quantization or color precision reduction */
  161201. struct jpeg_color_quantizer {
  161202. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161203. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161204. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161205. int num_rows));
  161206. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161207. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161208. };
  161209. /* Miscellaneous useful macros */
  161210. #undef MAX
  161211. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161212. #undef MIN
  161213. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161214. /* We assume that right shift corresponds to signed division by 2 with
  161215. * rounding towards minus infinity. This is correct for typical "arithmetic
  161216. * shift" instructions that shift in copies of the sign bit. But some
  161217. * C compilers implement >> with an unsigned shift. For these machines you
  161218. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161219. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161220. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161221. * included in the variables of any routine using RIGHT_SHIFT.
  161222. */
  161223. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161224. #define SHIFT_TEMPS INT32 shift_temp;
  161225. #define RIGHT_SHIFT(x,shft) \
  161226. ((shift_temp = (x)) < 0 ? \
  161227. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  161228. (shift_temp >> (shft)))
  161229. #else
  161230. #define SHIFT_TEMPS
  161231. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  161232. #endif
  161233. /* Short forms of external names for systems with brain-damaged linkers. */
  161234. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161235. #define jinit_compress_master jICompress
  161236. #define jinit_c_master_control jICMaster
  161237. #define jinit_c_main_controller jICMainC
  161238. #define jinit_c_prep_controller jICPrepC
  161239. #define jinit_c_coef_controller jICCoefC
  161240. #define jinit_color_converter jICColor
  161241. #define jinit_downsampler jIDownsampler
  161242. #define jinit_forward_dct jIFDCT
  161243. #define jinit_huff_encoder jIHEncoder
  161244. #define jinit_phuff_encoder jIPHEncoder
  161245. #define jinit_marker_writer jIMWriter
  161246. #define jinit_master_decompress jIDMaster
  161247. #define jinit_d_main_controller jIDMainC
  161248. #define jinit_d_coef_controller jIDCoefC
  161249. #define jinit_d_post_controller jIDPostC
  161250. #define jinit_input_controller jIInCtlr
  161251. #define jinit_marker_reader jIMReader
  161252. #define jinit_huff_decoder jIHDecoder
  161253. #define jinit_phuff_decoder jIPHDecoder
  161254. #define jinit_inverse_dct jIIDCT
  161255. #define jinit_upsampler jIUpsampler
  161256. #define jinit_color_deconverter jIDColor
  161257. #define jinit_1pass_quantizer jI1Quant
  161258. #define jinit_2pass_quantizer jI2Quant
  161259. #define jinit_merged_upsampler jIMUpsampler
  161260. #define jinit_memory_mgr jIMemMgr
  161261. #define jdiv_round_up jDivRound
  161262. #define jround_up jRound
  161263. #define jcopy_sample_rows jCopySamples
  161264. #define jcopy_block_row jCopyBlocks
  161265. #define jzero_far jZeroFar
  161266. #define jpeg_zigzag_order jZIGTable
  161267. #define jpeg_natural_order jZAGTable
  161268. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161269. /* Compression module initialization routines */
  161270. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  161271. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  161272. boolean transcode_only));
  161273. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  161274. boolean need_full_buffer));
  161275. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  161276. boolean need_full_buffer));
  161277. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  161278. boolean need_full_buffer));
  161279. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  161280. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  161281. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  161282. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  161283. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  161284. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  161285. /* Decompression module initialization routines */
  161286. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  161287. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  161288. boolean need_full_buffer));
  161289. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  161290. boolean need_full_buffer));
  161291. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  161292. boolean need_full_buffer));
  161293. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  161294. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  161295. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  161296. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  161297. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  161298. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  161299. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  161300. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  161301. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  161302. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  161303. /* Memory manager initialization */
  161304. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  161305. /* Utility routines in jutils.c */
  161306. EXTERN(long) jdiv_round_up JPP((long a, long b));
  161307. EXTERN(long) jround_up JPP((long a, long b));
  161308. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  161309. JSAMPARRAY output_array, int dest_row,
  161310. int num_rows, JDIMENSION num_cols));
  161311. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  161312. JDIMENSION num_blocks));
  161313. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  161314. /* Constant tables in jutils.c */
  161315. #if 0 /* This table is not actually needed in v6a */
  161316. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  161317. #endif
  161318. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  161319. /* Suppress undefined-structure complaints if necessary. */
  161320. #ifdef INCOMPLETE_TYPES_BROKEN
  161321. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  161322. struct jvirt_sarray_control { long dummy; };
  161323. struct jvirt_barray_control { long dummy; };
  161324. #endif
  161325. #endif /* INCOMPLETE_TYPES_BROKEN */
  161326. /*** End of inlined file: jpegint.h ***/
  161327. /* fetch private declarations */
  161328. /*** Start of inlined file: jerror.h ***/
  161329. /*
  161330. * To define the enum list of message codes, include this file without
  161331. * defining macro JMESSAGE. To create a message string table, include it
  161332. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  161333. */
  161334. #ifndef JMESSAGE
  161335. #ifndef JERROR_H
  161336. /* First time through, define the enum list */
  161337. #define JMAKE_ENUM_LIST
  161338. #else
  161339. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  161340. #define JMESSAGE(code,string)
  161341. #endif /* JERROR_H */
  161342. #endif /* JMESSAGE */
  161343. #ifdef JMAKE_ENUM_LIST
  161344. typedef enum {
  161345. #define JMESSAGE(code,string) code ,
  161346. #endif /* JMAKE_ENUM_LIST */
  161347. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  161348. /* For maintenance convenience, list is alphabetical by message code name */
  161349. JMESSAGE(JERR_ARITH_NOTIMPL,
  161350. "Sorry, there are legal restrictions on arithmetic coding")
  161351. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  161352. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  161353. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  161354. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  161355. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  161356. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  161357. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  161358. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  161359. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  161360. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  161361. JMESSAGE(JERR_BAD_LIB_VERSION,
  161362. "Wrong JPEG library version: library is %d, caller expects %d")
  161363. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  161364. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  161365. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  161366. JMESSAGE(JERR_BAD_PROGRESSION,
  161367. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  161368. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  161369. "Invalid progressive parameters at scan script entry %d")
  161370. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  161371. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  161372. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  161373. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  161374. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  161375. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  161376. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  161377. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  161378. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  161379. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  161380. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  161381. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  161382. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  161383. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  161384. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  161385. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  161386. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  161387. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  161388. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  161389. JMESSAGE(JERR_FILE_READ, "Input file read error")
  161390. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  161391. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  161392. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  161393. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  161394. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  161395. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  161396. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  161397. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  161398. "Cannot transcode due to multiple use of quantization table %d")
  161399. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  161400. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  161401. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  161402. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  161403. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  161404. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  161405. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  161406. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  161407. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  161408. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  161409. JMESSAGE(JERR_QUANT_COMPONENTS,
  161410. "Cannot quantize more than %d color components")
  161411. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  161412. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  161413. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  161414. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  161415. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  161416. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  161417. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  161418. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  161419. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  161420. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  161421. JMESSAGE(JERR_TFILE_WRITE,
  161422. "Write failed on temporary file --- out of disk space?")
  161423. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  161424. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  161425. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  161426. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  161427. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  161428. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  161429. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  161430. JMESSAGE(JMSG_VERSION, JVERSION)
  161431. JMESSAGE(JTRC_16BIT_TABLES,
  161432. "Caution: quantization tables are too coarse for baseline JPEG")
  161433. JMESSAGE(JTRC_ADOBE,
  161434. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  161435. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  161436. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  161437. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  161438. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  161439. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  161440. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  161441. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  161442. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  161443. JMESSAGE(JTRC_EOI, "End Of Image")
  161444. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  161445. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  161446. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  161447. "Warning: thumbnail image size does not match data length %u")
  161448. JMESSAGE(JTRC_JFIF_EXTENSION,
  161449. "JFIF extension marker: type 0x%02x, length %u")
  161450. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  161451. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  161452. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  161453. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  161454. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  161455. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  161456. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  161457. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  161458. JMESSAGE(JTRC_RST, "RST%d")
  161459. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  161460. "Smoothing not supported with nonstandard sampling ratios")
  161461. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  161462. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  161463. JMESSAGE(JTRC_SOI, "Start of Image")
  161464. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  161465. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  161466. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  161467. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  161468. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  161469. JMESSAGE(JTRC_THUMB_JPEG,
  161470. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  161471. JMESSAGE(JTRC_THUMB_PALETTE,
  161472. "JFIF extension marker: palette thumbnail image, length %u")
  161473. JMESSAGE(JTRC_THUMB_RGB,
  161474. "JFIF extension marker: RGB thumbnail image, length %u")
  161475. JMESSAGE(JTRC_UNKNOWN_IDS,
  161476. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  161477. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  161478. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  161479. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  161480. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  161481. "Inconsistent progression sequence for component %d coefficient %d")
  161482. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  161483. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  161484. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  161485. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  161486. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  161487. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  161488. JMESSAGE(JWRN_MUST_RESYNC,
  161489. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  161490. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  161491. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  161492. #ifdef JMAKE_ENUM_LIST
  161493. JMSG_LASTMSGCODE
  161494. } J_MESSAGE_CODE;
  161495. #undef JMAKE_ENUM_LIST
  161496. #endif /* JMAKE_ENUM_LIST */
  161497. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  161498. #undef JMESSAGE
  161499. #ifndef JERROR_H
  161500. #define JERROR_H
  161501. /* Macros to simplify using the error and trace message stuff */
  161502. /* The first parameter is either type of cinfo pointer */
  161503. /* Fatal errors (print message and exit) */
  161504. #define ERREXIT(cinfo,code) \
  161505. ((cinfo)->err->msg_code = (code), \
  161506. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161507. #define ERREXIT1(cinfo,code,p1) \
  161508. ((cinfo)->err->msg_code = (code), \
  161509. (cinfo)->err->msg_parm.i[0] = (p1), \
  161510. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161511. #define ERREXIT2(cinfo,code,p1,p2) \
  161512. ((cinfo)->err->msg_code = (code), \
  161513. (cinfo)->err->msg_parm.i[0] = (p1), \
  161514. (cinfo)->err->msg_parm.i[1] = (p2), \
  161515. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161516. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  161517. ((cinfo)->err->msg_code = (code), \
  161518. (cinfo)->err->msg_parm.i[0] = (p1), \
  161519. (cinfo)->err->msg_parm.i[1] = (p2), \
  161520. (cinfo)->err->msg_parm.i[2] = (p3), \
  161521. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161522. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  161523. ((cinfo)->err->msg_code = (code), \
  161524. (cinfo)->err->msg_parm.i[0] = (p1), \
  161525. (cinfo)->err->msg_parm.i[1] = (p2), \
  161526. (cinfo)->err->msg_parm.i[2] = (p3), \
  161527. (cinfo)->err->msg_parm.i[3] = (p4), \
  161528. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161529. #define ERREXITS(cinfo,code,str) \
  161530. ((cinfo)->err->msg_code = (code), \
  161531. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161532. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  161533. #define MAKESTMT(stuff) do { stuff } while (0)
  161534. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  161535. #define WARNMS(cinfo,code) \
  161536. ((cinfo)->err->msg_code = (code), \
  161537. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161538. #define WARNMS1(cinfo,code,p1) \
  161539. ((cinfo)->err->msg_code = (code), \
  161540. (cinfo)->err->msg_parm.i[0] = (p1), \
  161541. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161542. #define WARNMS2(cinfo,code,p1,p2) \
  161543. ((cinfo)->err->msg_code = (code), \
  161544. (cinfo)->err->msg_parm.i[0] = (p1), \
  161545. (cinfo)->err->msg_parm.i[1] = (p2), \
  161546. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  161547. /* Informational/debugging messages */
  161548. #define TRACEMS(cinfo,lvl,code) \
  161549. ((cinfo)->err->msg_code = (code), \
  161550. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161551. #define TRACEMS1(cinfo,lvl,code,p1) \
  161552. ((cinfo)->err->msg_code = (code), \
  161553. (cinfo)->err->msg_parm.i[0] = (p1), \
  161554. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161555. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  161556. ((cinfo)->err->msg_code = (code), \
  161557. (cinfo)->err->msg_parm.i[0] = (p1), \
  161558. (cinfo)->err->msg_parm.i[1] = (p2), \
  161559. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161560. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  161561. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161562. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  161563. (cinfo)->err->msg_code = (code); \
  161564. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161565. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  161566. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161567. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161568. (cinfo)->err->msg_code = (code); \
  161569. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161570. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  161571. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161572. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161573. _mp[4] = (p5); \
  161574. (cinfo)->err->msg_code = (code); \
  161575. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161576. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  161577. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  161578. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  161579. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  161580. (cinfo)->err->msg_code = (code); \
  161581. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  161582. #define TRACEMSS(cinfo,lvl,code,str) \
  161583. ((cinfo)->err->msg_code = (code), \
  161584. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  161585. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  161586. #endif /* JERROR_H */
  161587. /*** End of inlined file: jerror.h ***/
  161588. /* fetch error codes too */
  161589. #endif
  161590. #endif /* JPEGLIB_H */
  161591. /*** End of inlined file: jpeglib.h ***/
  161592. /*** Start of inlined file: jcapimin.c ***/
  161593. #define JPEG_INTERNALS
  161594. /*** Start of inlined file: jinclude.h ***/
  161595. /* Include auto-config file to find out which system include files we need. */
  161596. #ifndef __jinclude_h__
  161597. #define __jinclude_h__
  161598. /*** Start of inlined file: jconfig.h ***/
  161599. /* see jconfig.doc for explanations */
  161600. // disable all the warnings under MSVC
  161601. #ifdef _MSC_VER
  161602. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  161603. #endif
  161604. #ifdef __BORLANDC__
  161605. #pragma warn -8057
  161606. #pragma warn -8019
  161607. #pragma warn -8004
  161608. #pragma warn -8008
  161609. #endif
  161610. #define HAVE_PROTOTYPES
  161611. #define HAVE_UNSIGNED_CHAR
  161612. #define HAVE_UNSIGNED_SHORT
  161613. /* #define void char */
  161614. /* #define const */
  161615. #undef CHAR_IS_UNSIGNED
  161616. #define HAVE_STDDEF_H
  161617. #define HAVE_STDLIB_H
  161618. #undef NEED_BSD_STRINGS
  161619. #undef NEED_SYS_TYPES_H
  161620. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  161621. #undef NEED_SHORT_EXTERNAL_NAMES
  161622. #undef INCOMPLETE_TYPES_BROKEN
  161623. /* Define "boolean" as unsigned char, not int, per Windows custom */
  161624. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  161625. typedef unsigned char boolean;
  161626. #endif
  161627. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  161628. #ifdef JPEG_INTERNALS
  161629. #undef RIGHT_SHIFT_IS_UNSIGNED
  161630. #endif /* JPEG_INTERNALS */
  161631. #ifdef JPEG_CJPEG_DJPEG
  161632. #define BMP_SUPPORTED /* BMP image file format */
  161633. #define GIF_SUPPORTED /* GIF image file format */
  161634. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  161635. #undef RLE_SUPPORTED /* Utah RLE image file format */
  161636. #define TARGA_SUPPORTED /* Targa image file format */
  161637. #define TWO_FILE_COMMANDLINE /* optional */
  161638. #define USE_SETMODE /* Microsoft has setmode() */
  161639. #undef NEED_SIGNAL_CATCHER
  161640. #undef DONT_USE_B_MODE
  161641. #undef PROGRESS_REPORT /* optional */
  161642. #endif /* JPEG_CJPEG_DJPEG */
  161643. /*** End of inlined file: jconfig.h ***/
  161644. /* auto configuration options */
  161645. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  161646. /*
  161647. * We need the NULL macro and size_t typedef.
  161648. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  161649. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  161650. * pull in <sys/types.h> as well.
  161651. * Note that the core JPEG library does not require <stdio.h>;
  161652. * only the default error handler and data source/destination modules do.
  161653. * But we must pull it in because of the references to FILE in jpeglib.h.
  161654. * You can remove those references if you want to compile without <stdio.h>.
  161655. */
  161656. #ifdef HAVE_STDDEF_H
  161657. #include <stddef.h>
  161658. #endif
  161659. #ifdef HAVE_STDLIB_H
  161660. #include <stdlib.h>
  161661. #endif
  161662. #ifdef NEED_SYS_TYPES_H
  161663. #include <sys/types.h>
  161664. #endif
  161665. #include <stdio.h>
  161666. /*
  161667. * We need memory copying and zeroing functions, plus strncpy().
  161668. * ANSI and System V implementations declare these in <string.h>.
  161669. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  161670. * Some systems may declare memset and memcpy in <memory.h>.
  161671. *
  161672. * NOTE: we assume the size parameters to these functions are of type size_t.
  161673. * Change the casts in these macros if not!
  161674. */
  161675. #ifdef NEED_BSD_STRINGS
  161676. #include <strings.h>
  161677. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  161678. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  161679. #else /* not BSD, assume ANSI/SysV string lib */
  161680. #include <string.h>
  161681. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  161682. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  161683. #endif
  161684. /*
  161685. * In ANSI C, and indeed any rational implementation, size_t is also the
  161686. * type returned by sizeof(). However, it seems there are some irrational
  161687. * implementations out there, in which sizeof() returns an int even though
  161688. * size_t is defined as long or unsigned long. To ensure consistent results
  161689. * we always use this SIZEOF() macro in place of using sizeof() directly.
  161690. */
  161691. #define SIZEOF(object) ((size_t) sizeof(object))
  161692. /*
  161693. * The modules that use fread() and fwrite() always invoke them through
  161694. * these macros. On some systems you may need to twiddle the argument casts.
  161695. * CAUTION: argument order is different from underlying functions!
  161696. */
  161697. #define JFREAD(file,buf,sizeofbuf) \
  161698. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161699. #define JFWRITE(file,buf,sizeofbuf) \
  161700. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  161701. typedef enum { /* JPEG marker codes */
  161702. M_SOF0 = 0xc0,
  161703. M_SOF1 = 0xc1,
  161704. M_SOF2 = 0xc2,
  161705. M_SOF3 = 0xc3,
  161706. M_SOF5 = 0xc5,
  161707. M_SOF6 = 0xc6,
  161708. M_SOF7 = 0xc7,
  161709. M_JPG = 0xc8,
  161710. M_SOF9 = 0xc9,
  161711. M_SOF10 = 0xca,
  161712. M_SOF11 = 0xcb,
  161713. M_SOF13 = 0xcd,
  161714. M_SOF14 = 0xce,
  161715. M_SOF15 = 0xcf,
  161716. M_DHT = 0xc4,
  161717. M_DAC = 0xcc,
  161718. M_RST0 = 0xd0,
  161719. M_RST1 = 0xd1,
  161720. M_RST2 = 0xd2,
  161721. M_RST3 = 0xd3,
  161722. M_RST4 = 0xd4,
  161723. M_RST5 = 0xd5,
  161724. M_RST6 = 0xd6,
  161725. M_RST7 = 0xd7,
  161726. M_SOI = 0xd8,
  161727. M_EOI = 0xd9,
  161728. M_SOS = 0xda,
  161729. M_DQT = 0xdb,
  161730. M_DNL = 0xdc,
  161731. M_DRI = 0xdd,
  161732. M_DHP = 0xde,
  161733. M_EXP = 0xdf,
  161734. M_APP0 = 0xe0,
  161735. M_APP1 = 0xe1,
  161736. M_APP2 = 0xe2,
  161737. M_APP3 = 0xe3,
  161738. M_APP4 = 0xe4,
  161739. M_APP5 = 0xe5,
  161740. M_APP6 = 0xe6,
  161741. M_APP7 = 0xe7,
  161742. M_APP8 = 0xe8,
  161743. M_APP9 = 0xe9,
  161744. M_APP10 = 0xea,
  161745. M_APP11 = 0xeb,
  161746. M_APP12 = 0xec,
  161747. M_APP13 = 0xed,
  161748. M_APP14 = 0xee,
  161749. M_APP15 = 0xef,
  161750. M_JPG0 = 0xf0,
  161751. M_JPG13 = 0xfd,
  161752. M_COM = 0xfe,
  161753. M_TEM = 0x01,
  161754. M_ERROR = 0x100
  161755. } JPEG_MARKER;
  161756. /*
  161757. * Figure F.12: extend sign bit.
  161758. * On some machines, a shift and add will be faster than a table lookup.
  161759. */
  161760. #ifdef AVOID_TABLES
  161761. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  161762. #else
  161763. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  161764. static const int extend_test[16] = /* entry n is 2**(n-1) */
  161765. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  161766. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  161767. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  161768. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  161769. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  161770. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  161771. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  161772. #endif /* AVOID_TABLES */
  161773. #endif
  161774. /*** End of inlined file: jinclude.h ***/
  161775. /*
  161776. * Initialization of a JPEG compression object.
  161777. * The error manager must already be set up (in case memory manager fails).
  161778. */
  161779. GLOBAL(void)
  161780. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  161781. {
  161782. int i;
  161783. /* Guard against version mismatches between library and caller. */
  161784. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  161785. if (version != JPEG_LIB_VERSION)
  161786. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  161787. if (structsize != SIZEOF(struct jpeg_compress_struct))
  161788. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  161789. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  161790. /* For debugging purposes, we zero the whole master structure.
  161791. * But the application has already set the err pointer, and may have set
  161792. * client_data, so we have to save and restore those fields.
  161793. * Note: if application hasn't set client_data, tools like Purify may
  161794. * complain here.
  161795. */
  161796. {
  161797. struct jpeg_error_mgr * err = cinfo->err;
  161798. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  161799. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  161800. cinfo->err = err;
  161801. cinfo->client_data = client_data;
  161802. }
  161803. cinfo->is_decompressor = FALSE;
  161804. /* Initialize a memory manager instance for this object */
  161805. jinit_memory_mgr((j_common_ptr) cinfo);
  161806. /* Zero out pointers to permanent structures. */
  161807. cinfo->progress = NULL;
  161808. cinfo->dest = NULL;
  161809. cinfo->comp_info = NULL;
  161810. for (i = 0; i < NUM_QUANT_TBLS; i++)
  161811. cinfo->quant_tbl_ptrs[i] = NULL;
  161812. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161813. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  161814. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  161815. }
  161816. cinfo->script_space = NULL;
  161817. cinfo->input_gamma = 1.0; /* in case application forgets */
  161818. /* OK, I'm ready */
  161819. cinfo->global_state = CSTATE_START;
  161820. }
  161821. /*
  161822. * Destruction of a JPEG compression object
  161823. */
  161824. GLOBAL(void)
  161825. jpeg_destroy_compress (j_compress_ptr cinfo)
  161826. {
  161827. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  161828. }
  161829. /*
  161830. * Abort processing of a JPEG compression operation,
  161831. * but don't destroy the object itself.
  161832. */
  161833. GLOBAL(void)
  161834. jpeg_abort_compress (j_compress_ptr cinfo)
  161835. {
  161836. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  161837. }
  161838. /*
  161839. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  161840. * Marks all currently defined tables as already written (if suppress)
  161841. * or not written (if !suppress). This will control whether they get emitted
  161842. * by a subsequent jpeg_start_compress call.
  161843. *
  161844. * This routine is exported for use by applications that want to produce
  161845. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  161846. * since it is called by jpeg_start_compress, we put it here --- otherwise
  161847. * jcparam.o would be linked whether the application used it or not.
  161848. */
  161849. GLOBAL(void)
  161850. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  161851. {
  161852. int i;
  161853. JQUANT_TBL * qtbl;
  161854. JHUFF_TBL * htbl;
  161855. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  161856. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  161857. qtbl->sent_table = suppress;
  161858. }
  161859. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  161860. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  161861. htbl->sent_table = suppress;
  161862. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  161863. htbl->sent_table = suppress;
  161864. }
  161865. }
  161866. /*
  161867. * Finish JPEG compression.
  161868. *
  161869. * If a multipass operating mode was selected, this may do a great deal of
  161870. * work including most of the actual output.
  161871. */
  161872. GLOBAL(void)
  161873. jpeg_finish_compress (j_compress_ptr cinfo)
  161874. {
  161875. JDIMENSION iMCU_row;
  161876. if (cinfo->global_state == CSTATE_SCANNING ||
  161877. cinfo->global_state == CSTATE_RAW_OK) {
  161878. /* Terminate first pass */
  161879. if (cinfo->next_scanline < cinfo->image_height)
  161880. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  161881. (*cinfo->master->finish_pass) (cinfo);
  161882. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  161883. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161884. /* Perform any remaining passes */
  161885. while (! cinfo->master->is_last_pass) {
  161886. (*cinfo->master->prepare_for_pass) (cinfo);
  161887. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  161888. if (cinfo->progress != NULL) {
  161889. cinfo->progress->pass_counter = (long) iMCU_row;
  161890. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  161891. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  161892. }
  161893. /* We bypass the main controller and invoke coef controller directly;
  161894. * all work is being done from the coefficient buffer.
  161895. */
  161896. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  161897. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  161898. }
  161899. (*cinfo->master->finish_pass) (cinfo);
  161900. }
  161901. /* Write EOI, do final cleanup */
  161902. (*cinfo->marker->write_file_trailer) (cinfo);
  161903. (*cinfo->dest->term_destination) (cinfo);
  161904. /* We can use jpeg_abort to release memory and reset global_state */
  161905. jpeg_abort((j_common_ptr) cinfo);
  161906. }
  161907. /*
  161908. * Write a special marker.
  161909. * This is only recommended for writing COM or APPn markers.
  161910. * Must be called after jpeg_start_compress() and before
  161911. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  161912. */
  161913. GLOBAL(void)
  161914. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  161915. const JOCTET *dataptr, unsigned int datalen)
  161916. {
  161917. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  161918. if (cinfo->next_scanline != 0 ||
  161919. (cinfo->global_state != CSTATE_SCANNING &&
  161920. cinfo->global_state != CSTATE_RAW_OK &&
  161921. cinfo->global_state != CSTATE_WRCOEFS))
  161922. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161923. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161924. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  161925. while (datalen--) {
  161926. (*write_marker_byte) (cinfo, *dataptr);
  161927. dataptr++;
  161928. }
  161929. }
  161930. /* Same, but piecemeal. */
  161931. GLOBAL(void)
  161932. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  161933. {
  161934. if (cinfo->next_scanline != 0 ||
  161935. (cinfo->global_state != CSTATE_SCANNING &&
  161936. cinfo->global_state != CSTATE_RAW_OK &&
  161937. cinfo->global_state != CSTATE_WRCOEFS))
  161938. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161939. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  161940. }
  161941. GLOBAL(void)
  161942. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  161943. {
  161944. (*cinfo->marker->write_marker_byte) (cinfo, val);
  161945. }
  161946. /*
  161947. * Alternate compression function: just write an abbreviated table file.
  161948. * Before calling this, all parameters and a data destination must be set up.
  161949. *
  161950. * To produce a pair of files containing abbreviated tables and abbreviated
  161951. * image data, one would proceed as follows:
  161952. *
  161953. * initialize JPEG object
  161954. * set JPEG parameters
  161955. * set destination to table file
  161956. * jpeg_write_tables(cinfo);
  161957. * set destination to image file
  161958. * jpeg_start_compress(cinfo, FALSE);
  161959. * write data...
  161960. * jpeg_finish_compress(cinfo);
  161961. *
  161962. * jpeg_write_tables has the side effect of marking all tables written
  161963. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  161964. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  161965. */
  161966. GLOBAL(void)
  161967. jpeg_write_tables (j_compress_ptr cinfo)
  161968. {
  161969. if (cinfo->global_state != CSTATE_START)
  161970. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  161971. /* (Re)initialize error mgr and destination modules */
  161972. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  161973. (*cinfo->dest->init_destination) (cinfo);
  161974. /* Initialize the marker writer ... bit of a crock to do it here. */
  161975. jinit_marker_writer(cinfo);
  161976. /* Write them tables! */
  161977. (*cinfo->marker->write_tables_only) (cinfo);
  161978. /* And clean up. */
  161979. (*cinfo->dest->term_destination) (cinfo);
  161980. /*
  161981. * In library releases up through v6a, we called jpeg_abort() here to free
  161982. * any working memory allocated by the destination manager and marker
  161983. * writer. Some applications had a problem with that: they allocated space
  161984. * of their own from the library memory manager, and didn't want it to go
  161985. * away during write_tables. So now we do nothing. This will cause a
  161986. * memory leak if an app calls write_tables repeatedly without doing a full
  161987. * compression cycle or otherwise resetting the JPEG object. However, that
  161988. * seems less bad than unexpectedly freeing memory in the normal case.
  161989. * An app that prefers the old behavior can call jpeg_abort for itself after
  161990. * each call to jpeg_write_tables().
  161991. */
  161992. }
  161993. /*** End of inlined file: jcapimin.c ***/
  161994. /*** Start of inlined file: jcapistd.c ***/
  161995. #define JPEG_INTERNALS
  161996. /*
  161997. * Compression initialization.
  161998. * Before calling this, all parameters and a data destination must be set up.
  161999. *
  162000. * We require a write_all_tables parameter as a failsafe check when writing
  162001. * multiple datastreams from the same compression object. Since prior runs
  162002. * will have left all the tables marked sent_table=TRUE, a subsequent run
  162003. * would emit an abbreviated stream (no tables) by default. This may be what
  162004. * is wanted, but for safety's sake it should not be the default behavior:
  162005. * programmers should have to make a deliberate choice to emit abbreviated
  162006. * images. Therefore the documentation and examples should encourage people
  162007. * to pass write_all_tables=TRUE; then it will take active thought to do the
  162008. * wrong thing.
  162009. */
  162010. GLOBAL(void)
  162011. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  162012. {
  162013. if (cinfo->global_state != CSTATE_START)
  162014. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162015. if (write_all_tables)
  162016. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  162017. /* (Re)initialize error mgr and destination modules */
  162018. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162019. (*cinfo->dest->init_destination) (cinfo);
  162020. /* Perform master selection of active modules */
  162021. jinit_compress_master(cinfo);
  162022. /* Set up for the first pass */
  162023. (*cinfo->master->prepare_for_pass) (cinfo);
  162024. /* Ready for application to drive first pass through jpeg_write_scanlines
  162025. * or jpeg_write_raw_data.
  162026. */
  162027. cinfo->next_scanline = 0;
  162028. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  162029. }
  162030. /*
  162031. * Write some scanlines of data to the JPEG compressor.
  162032. *
  162033. * The return value will be the number of lines actually written.
  162034. * This should be less than the supplied num_lines only in case that
  162035. * the data destination module has requested suspension of the compressor,
  162036. * or if more than image_height scanlines are passed in.
  162037. *
  162038. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162039. * this likely signals an application programmer error. However,
  162040. * excess scanlines passed in the last valid call are *silently* ignored,
  162041. * so that the application need not adjust num_lines for end-of-image
  162042. * when using a multiple-scanline buffer.
  162043. */
  162044. GLOBAL(JDIMENSION)
  162045. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162046. JDIMENSION num_lines)
  162047. {
  162048. JDIMENSION row_ctr, rows_left;
  162049. if (cinfo->global_state != CSTATE_SCANNING)
  162050. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162051. if (cinfo->next_scanline >= cinfo->image_height)
  162052. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162053. /* Call progress monitor hook if present */
  162054. if (cinfo->progress != NULL) {
  162055. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162056. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162057. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162058. }
  162059. /* Give master control module another chance if this is first call to
  162060. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162061. * delayed so that application can write COM, etc, markers between
  162062. * jpeg_start_compress and jpeg_write_scanlines.
  162063. */
  162064. if (cinfo->master->call_pass_startup)
  162065. (*cinfo->master->pass_startup) (cinfo);
  162066. /* Ignore any extra scanlines at bottom of image. */
  162067. rows_left = cinfo->image_height - cinfo->next_scanline;
  162068. if (num_lines > rows_left)
  162069. num_lines = rows_left;
  162070. row_ctr = 0;
  162071. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162072. cinfo->next_scanline += row_ctr;
  162073. return row_ctr;
  162074. }
  162075. /*
  162076. * Alternate entry point to write raw data.
  162077. * Processes exactly one iMCU row per call, unless suspended.
  162078. */
  162079. GLOBAL(JDIMENSION)
  162080. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162081. JDIMENSION num_lines)
  162082. {
  162083. JDIMENSION lines_per_iMCU_row;
  162084. if (cinfo->global_state != CSTATE_RAW_OK)
  162085. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162086. if (cinfo->next_scanline >= cinfo->image_height) {
  162087. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162088. return 0;
  162089. }
  162090. /* Call progress monitor hook if present */
  162091. if (cinfo->progress != NULL) {
  162092. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162093. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162094. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162095. }
  162096. /* Give master control module another chance if this is first call to
  162097. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162098. * delayed so that application can write COM, etc, markers between
  162099. * jpeg_start_compress and jpeg_write_raw_data.
  162100. */
  162101. if (cinfo->master->call_pass_startup)
  162102. (*cinfo->master->pass_startup) (cinfo);
  162103. /* Verify that at least one iMCU row has been passed. */
  162104. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162105. if (num_lines < lines_per_iMCU_row)
  162106. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162107. /* Directly compress the row. */
  162108. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162109. /* If compressor did not consume the whole row, suspend processing. */
  162110. return 0;
  162111. }
  162112. /* OK, we processed one iMCU row. */
  162113. cinfo->next_scanline += lines_per_iMCU_row;
  162114. return lines_per_iMCU_row;
  162115. }
  162116. /*** End of inlined file: jcapistd.c ***/
  162117. /*** Start of inlined file: jccoefct.c ***/
  162118. #define JPEG_INTERNALS
  162119. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162120. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162121. * step is run during the first pass, and subsequent passes need only read
  162122. * the buffered coefficients.
  162123. */
  162124. #ifdef ENTROPY_OPT_SUPPORTED
  162125. #define FULL_COEF_BUFFER_SUPPORTED
  162126. #else
  162127. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162128. #define FULL_COEF_BUFFER_SUPPORTED
  162129. #endif
  162130. #endif
  162131. /* Private buffer controller object */
  162132. typedef struct {
  162133. struct jpeg_c_coef_controller pub; /* public fields */
  162134. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162135. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162136. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162137. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162138. /* For single-pass compression, it's sufficient to buffer just one MCU
  162139. * (although this may prove a bit slow in practice). We allocate a
  162140. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162141. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162142. * it's not really very big; this is to keep the module interfaces unchanged
  162143. * when a large coefficient buffer is necessary.)
  162144. * In multi-pass modes, this array points to the current MCU's blocks
  162145. * within the virtual arrays.
  162146. */
  162147. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162148. /* In multi-pass modes, we need a virtual block array for each component. */
  162149. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162150. } my_coef_controller;
  162151. typedef my_coef_controller * my_coef_ptr;
  162152. /* Forward declarations */
  162153. METHODDEF(boolean) compress_data
  162154. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162155. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162156. METHODDEF(boolean) compress_first_pass
  162157. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162158. METHODDEF(boolean) compress_output
  162159. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162160. #endif
  162161. LOCAL(void)
  162162. start_iMCU_row (j_compress_ptr cinfo)
  162163. /* Reset within-iMCU-row counters for a new row */
  162164. {
  162165. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162166. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162167. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162168. * But at the bottom of the image, process only what's left.
  162169. */
  162170. if (cinfo->comps_in_scan > 1) {
  162171. coef->MCU_rows_per_iMCU_row = 1;
  162172. } else {
  162173. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162174. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162175. else
  162176. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162177. }
  162178. coef->mcu_ctr = 0;
  162179. coef->MCU_vert_offset = 0;
  162180. }
  162181. /*
  162182. * Initialize for a processing pass.
  162183. */
  162184. METHODDEF(void)
  162185. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162186. {
  162187. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162188. coef->iMCU_row_num = 0;
  162189. start_iMCU_row(cinfo);
  162190. switch (pass_mode) {
  162191. case JBUF_PASS_THRU:
  162192. if (coef->whole_image[0] != NULL)
  162193. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162194. coef->pub.compress_data = compress_data;
  162195. break;
  162196. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162197. case JBUF_SAVE_AND_PASS:
  162198. if (coef->whole_image[0] == NULL)
  162199. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162200. coef->pub.compress_data = compress_first_pass;
  162201. break;
  162202. case JBUF_CRANK_DEST:
  162203. if (coef->whole_image[0] == NULL)
  162204. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162205. coef->pub.compress_data = compress_output;
  162206. break;
  162207. #endif
  162208. default:
  162209. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162210. break;
  162211. }
  162212. }
  162213. /*
  162214. * Process some data in the single-pass case.
  162215. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162216. * per call, ie, v_samp_factor block rows for each component in the image.
  162217. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162218. *
  162219. * NB: input_buf contains a plane for each component in image,
  162220. * which we index according to the component's SOF position.
  162221. */
  162222. METHODDEF(boolean)
  162223. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162224. {
  162225. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162226. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162227. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  162228. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162229. int blkn, bi, ci, yindex, yoffset, blockcnt;
  162230. JDIMENSION ypos, xpos;
  162231. jpeg_component_info *compptr;
  162232. /* Loop to write as much as one whole iMCU row */
  162233. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162234. yoffset++) {
  162235. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  162236. MCU_col_num++) {
  162237. /* Determine where data comes from in input_buf and do the DCT thing.
  162238. * Each call on forward_DCT processes a horizontal row of DCT blocks
  162239. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  162240. * sequentially. Dummy blocks at the right or bottom edge are filled in
  162241. * specially. The data in them does not matter for image reconstruction,
  162242. * so we fill them with values that will encode to the smallest amount of
  162243. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  162244. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  162245. */
  162246. blkn = 0;
  162247. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162248. compptr = cinfo->cur_comp_info[ci];
  162249. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  162250. : compptr->last_col_width;
  162251. xpos = MCU_col_num * compptr->MCU_sample_width;
  162252. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  162253. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162254. if (coef->iMCU_row_num < last_iMCU_row ||
  162255. yoffset+yindex < compptr->last_row_height) {
  162256. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162257. input_buf[compptr->component_index],
  162258. coef->MCU_buffer[blkn],
  162259. ypos, xpos, (JDIMENSION) blockcnt);
  162260. if (blockcnt < compptr->MCU_width) {
  162261. /* Create some dummy blocks at the right edge of the image. */
  162262. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  162263. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  162264. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  162265. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  162266. }
  162267. }
  162268. } else {
  162269. /* Create a row of dummy blocks at the bottom of the image. */
  162270. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  162271. compptr->MCU_width * SIZEOF(JBLOCK));
  162272. for (bi = 0; bi < compptr->MCU_width; bi++) {
  162273. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  162274. }
  162275. }
  162276. blkn += compptr->MCU_width;
  162277. ypos += DCTSIZE;
  162278. }
  162279. }
  162280. /* Try to write the MCU. In event of a suspension failure, we will
  162281. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  162282. */
  162283. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162284. /* Suspension forced; update state counters and exit */
  162285. coef->MCU_vert_offset = yoffset;
  162286. coef->mcu_ctr = MCU_col_num;
  162287. return FALSE;
  162288. }
  162289. }
  162290. /* Completed an MCU row, but perhaps not an iMCU row */
  162291. coef->mcu_ctr = 0;
  162292. }
  162293. /* Completed the iMCU row, advance counters for next one */
  162294. coef->iMCU_row_num++;
  162295. start_iMCU_row(cinfo);
  162296. return TRUE;
  162297. }
  162298. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162299. /*
  162300. * Process some data in the first pass of a multi-pass case.
  162301. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162302. * per call, ie, v_samp_factor block rows for each component in the image.
  162303. * This amount of data is read from the source buffer, DCT'd and quantized,
  162304. * and saved into the virtual arrays. We also generate suitable dummy blocks
  162305. * as needed at the right and lower edges. (The dummy blocks are constructed
  162306. * in the virtual arrays, which have been padded appropriately.) This makes
  162307. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  162308. *
  162309. * We must also emit the data to the entropy encoder. This is conveniently
  162310. * done by calling compress_output() after we've loaded the current strip
  162311. * of the virtual arrays.
  162312. *
  162313. * NB: input_buf contains a plane for each component in image. All
  162314. * components are DCT'd and loaded into the virtual arrays in this pass.
  162315. * However, it may be that only a subset of the components are emitted to
  162316. * the entropy encoder during this first pass; be careful about looking
  162317. * at the scan-dependent variables (MCU dimensions, etc).
  162318. */
  162319. METHODDEF(boolean)
  162320. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162321. {
  162322. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162323. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  162324. JDIMENSION blocks_across, MCUs_across, MCUindex;
  162325. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  162326. JCOEF lastDC;
  162327. jpeg_component_info *compptr;
  162328. JBLOCKARRAY buffer;
  162329. JBLOCKROW thisblockrow, lastblockrow;
  162330. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162331. ci++, compptr++) {
  162332. /* Align the virtual buffer for this component. */
  162333. buffer = (*cinfo->mem->access_virt_barray)
  162334. ((j_common_ptr) cinfo, coef->whole_image[ci],
  162335. coef->iMCU_row_num * compptr->v_samp_factor,
  162336. (JDIMENSION) compptr->v_samp_factor, TRUE);
  162337. /* Count non-dummy DCT block rows in this iMCU row. */
  162338. if (coef->iMCU_row_num < last_iMCU_row)
  162339. block_rows = compptr->v_samp_factor;
  162340. else {
  162341. /* NB: can't use last_row_height here, since may not be set! */
  162342. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  162343. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  162344. }
  162345. blocks_across = compptr->width_in_blocks;
  162346. h_samp_factor = compptr->h_samp_factor;
  162347. /* Count number of dummy blocks to be added at the right margin. */
  162348. ndummy = (int) (blocks_across % h_samp_factor);
  162349. if (ndummy > 0)
  162350. ndummy = h_samp_factor - ndummy;
  162351. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  162352. * on forward_DCT processes a complete horizontal row of DCT blocks.
  162353. */
  162354. for (block_row = 0; block_row < block_rows; block_row++) {
  162355. thisblockrow = buffer[block_row];
  162356. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  162357. input_buf[ci], thisblockrow,
  162358. (JDIMENSION) (block_row * DCTSIZE),
  162359. (JDIMENSION) 0, blocks_across);
  162360. if (ndummy > 0) {
  162361. /* Create dummy blocks at the right edge of the image. */
  162362. thisblockrow += blocks_across; /* => first dummy block */
  162363. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  162364. lastDC = thisblockrow[-1][0];
  162365. for (bi = 0; bi < ndummy; bi++) {
  162366. thisblockrow[bi][0] = lastDC;
  162367. }
  162368. }
  162369. }
  162370. /* If at end of image, create dummy block rows as needed.
  162371. * The tricky part here is that within each MCU, we want the DC values
  162372. * of the dummy blocks to match the last real block's DC value.
  162373. * This squeezes a few more bytes out of the resulting file...
  162374. */
  162375. if (coef->iMCU_row_num == last_iMCU_row) {
  162376. blocks_across += ndummy; /* include lower right corner */
  162377. MCUs_across = blocks_across / h_samp_factor;
  162378. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  162379. block_row++) {
  162380. thisblockrow = buffer[block_row];
  162381. lastblockrow = buffer[block_row-1];
  162382. jzero_far((void FAR *) thisblockrow,
  162383. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  162384. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  162385. lastDC = lastblockrow[h_samp_factor-1][0];
  162386. for (bi = 0; bi < h_samp_factor; bi++) {
  162387. thisblockrow[bi][0] = lastDC;
  162388. }
  162389. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  162390. lastblockrow += h_samp_factor;
  162391. }
  162392. }
  162393. }
  162394. }
  162395. /* NB: compress_output will increment iMCU_row_num if successful.
  162396. * A suspension return will result in redoing all the work above next time.
  162397. */
  162398. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  162399. return compress_output(cinfo, input_buf);
  162400. }
  162401. /*
  162402. * Process some data in subsequent passes of a multi-pass case.
  162403. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162404. * per call, ie, v_samp_factor block rows for each component in the scan.
  162405. * The data is obtained from the virtual arrays and fed to the entropy coder.
  162406. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162407. *
  162408. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  162409. */
  162410. METHODDEF(boolean)
  162411. compress_output (j_compress_ptr cinfo, JSAMPIMAGE)
  162412. {
  162413. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162414. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162415. int blkn, ci, xindex, yindex, yoffset;
  162416. JDIMENSION start_col;
  162417. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  162418. JBLOCKROW buffer_ptr;
  162419. jpeg_component_info *compptr;
  162420. /* Align the virtual buffers for the components used in this scan.
  162421. * NB: during first pass, this is safe only because the buffers will
  162422. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  162423. */
  162424. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162425. compptr = cinfo->cur_comp_info[ci];
  162426. buffer[ci] = (*cinfo->mem->access_virt_barray)
  162427. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  162428. coef->iMCU_row_num * compptr->v_samp_factor,
  162429. (JDIMENSION) compptr->v_samp_factor, FALSE);
  162430. }
  162431. /* Loop to process one whole iMCU row */
  162432. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  162433. yoffset++) {
  162434. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  162435. MCU_col_num++) {
  162436. /* Construct list of pointers to DCT blocks belonging to this MCU */
  162437. blkn = 0; /* index of current DCT block within MCU */
  162438. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  162439. compptr = cinfo->cur_comp_info[ci];
  162440. start_col = MCU_col_num * compptr->MCU_width;
  162441. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  162442. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  162443. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  162444. coef->MCU_buffer[blkn++] = buffer_ptr++;
  162445. }
  162446. }
  162447. }
  162448. /* Try to write the MCU. */
  162449. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  162450. /* Suspension forced; update state counters and exit */
  162451. coef->MCU_vert_offset = yoffset;
  162452. coef->mcu_ctr = MCU_col_num;
  162453. return FALSE;
  162454. }
  162455. }
  162456. /* Completed an MCU row, but perhaps not an iMCU row */
  162457. coef->mcu_ctr = 0;
  162458. }
  162459. /* Completed the iMCU row, advance counters for next one */
  162460. coef->iMCU_row_num++;
  162461. start_iMCU_row(cinfo);
  162462. return TRUE;
  162463. }
  162464. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  162465. /*
  162466. * Initialize coefficient buffer controller.
  162467. */
  162468. GLOBAL(void)
  162469. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  162470. {
  162471. my_coef_ptr coef;
  162472. coef = (my_coef_ptr)
  162473. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162474. SIZEOF(my_coef_controller));
  162475. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  162476. coef->pub.start_pass = start_pass_coef;
  162477. /* Create the coefficient buffer. */
  162478. if (need_full_buffer) {
  162479. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162480. /* Allocate a full-image virtual array for each component, */
  162481. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  162482. int ci;
  162483. jpeg_component_info *compptr;
  162484. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  162485. ci++, compptr++) {
  162486. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  162487. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  162488. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  162489. (long) compptr->h_samp_factor),
  162490. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  162491. (long) compptr->v_samp_factor),
  162492. (JDIMENSION) compptr->v_samp_factor);
  162493. }
  162494. #else
  162495. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162496. #endif
  162497. } else {
  162498. /* We only need a single-MCU buffer. */
  162499. JBLOCKROW buffer;
  162500. int i;
  162501. buffer = (JBLOCKROW)
  162502. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162503. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  162504. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  162505. coef->MCU_buffer[i] = buffer + i;
  162506. }
  162507. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  162508. }
  162509. }
  162510. /*** End of inlined file: jccoefct.c ***/
  162511. /*** Start of inlined file: jccolor.c ***/
  162512. #define JPEG_INTERNALS
  162513. /* Private subobject */
  162514. typedef struct {
  162515. struct jpeg_color_converter pub; /* public fields */
  162516. /* Private state for RGB->YCC conversion */
  162517. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  162518. } my_color_converter;
  162519. typedef my_color_converter * my_cconvert_ptr;
  162520. /**************** RGB -> YCbCr conversion: most common case **************/
  162521. /*
  162522. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  162523. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  162524. * The conversion equations to be implemented are therefore
  162525. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  162526. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  162527. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  162528. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  162529. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  162530. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  162531. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  162532. * were not represented exactly. Now we sacrifice exact representation of
  162533. * maximum red and maximum blue in order to get exact grayscales.
  162534. *
  162535. * To avoid floating-point arithmetic, we represent the fractional constants
  162536. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  162537. * the products by 2^16, with appropriate rounding, to get the correct answer.
  162538. *
  162539. * For even more speed, we avoid doing any multiplications in the inner loop
  162540. * by precalculating the constants times R,G,B for all possible values.
  162541. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  162542. * for 12-bit samples it is still acceptable. It's not very reasonable for
  162543. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  162544. * colorspace anyway.
  162545. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  162546. * in the tables to save adding them separately in the inner loop.
  162547. */
  162548. #define SCALEBITS 16 /* speediest right-shift on some machines */
  162549. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  162550. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  162551. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  162552. /* We allocate one big table and divide it up into eight parts, instead of
  162553. * doing eight alloc_small requests. This lets us use a single table base
  162554. * address, which can be held in a register in the inner loops on many
  162555. * machines (more than can hold all eight addresses, anyway).
  162556. */
  162557. #define R_Y_OFF 0 /* offset to R => Y section */
  162558. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  162559. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  162560. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  162561. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  162562. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  162563. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  162564. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  162565. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  162566. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  162567. /*
  162568. * Initialize for RGB->YCC colorspace conversion.
  162569. */
  162570. METHODDEF(void)
  162571. rgb_ycc_start (j_compress_ptr cinfo)
  162572. {
  162573. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162574. INT32 * rgb_ycc_tab;
  162575. INT32 i;
  162576. /* Allocate and fill in the conversion tables. */
  162577. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  162578. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162579. (TABLE_SIZE * SIZEOF(INT32)));
  162580. for (i = 0; i <= MAXJSAMPLE; i++) {
  162581. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  162582. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  162583. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  162584. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  162585. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  162586. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  162587. * This ensures that the maximum output will round to MAXJSAMPLE
  162588. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  162589. */
  162590. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162591. /* B=>Cb and R=>Cr tables are the same
  162592. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  162593. */
  162594. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  162595. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  162596. }
  162597. }
  162598. /*
  162599. * Convert some rows of samples to the JPEG colorspace.
  162600. *
  162601. * Note that we change from the application's interleaved-pixel format
  162602. * to our internal noninterleaved, one-plane-per-component format.
  162603. * The input buffer is therefore three times as wide as the output buffer.
  162604. *
  162605. * A starting row offset is provided only for the output buffer. The caller
  162606. * can easily adjust the passed input_buf value to accommodate any row
  162607. * offset required on that side.
  162608. */
  162609. METHODDEF(void)
  162610. rgb_ycc_convert (j_compress_ptr cinfo,
  162611. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162612. JDIMENSION output_row, int num_rows)
  162613. {
  162614. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162615. register int r, g, b;
  162616. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162617. register JSAMPROW inptr;
  162618. register JSAMPROW outptr0, outptr1, outptr2;
  162619. register JDIMENSION col;
  162620. JDIMENSION num_cols = cinfo->image_width;
  162621. while (--num_rows >= 0) {
  162622. inptr = *input_buf++;
  162623. outptr0 = output_buf[0][output_row];
  162624. outptr1 = output_buf[1][output_row];
  162625. outptr2 = output_buf[2][output_row];
  162626. output_row++;
  162627. for (col = 0; col < num_cols; col++) {
  162628. r = GETJSAMPLE(inptr[RGB_RED]);
  162629. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162630. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162631. inptr += RGB_PIXELSIZE;
  162632. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162633. * must be too; we do not need an explicit range-limiting operation.
  162634. * Hence the value being shifted is never negative, and we don't
  162635. * need the general RIGHT_SHIFT macro.
  162636. */
  162637. /* Y */
  162638. outptr0[col] = (JSAMPLE)
  162639. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162640. >> SCALEBITS);
  162641. /* Cb */
  162642. outptr1[col] = (JSAMPLE)
  162643. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162644. >> SCALEBITS);
  162645. /* Cr */
  162646. outptr2[col] = (JSAMPLE)
  162647. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162648. >> SCALEBITS);
  162649. }
  162650. }
  162651. }
  162652. /**************** Cases other than RGB -> YCbCr **************/
  162653. /*
  162654. * Convert some rows of samples to the JPEG colorspace.
  162655. * This version handles RGB->grayscale conversion, which is the same
  162656. * as the RGB->Y portion of RGB->YCbCr.
  162657. * We assume rgb_ycc_start has been called (we only use the Y tables).
  162658. */
  162659. METHODDEF(void)
  162660. rgb_gray_convert (j_compress_ptr cinfo,
  162661. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162662. JDIMENSION output_row, int num_rows)
  162663. {
  162664. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162665. register int r, g, b;
  162666. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162667. register JSAMPROW inptr;
  162668. register JSAMPROW outptr;
  162669. register JDIMENSION col;
  162670. JDIMENSION num_cols = cinfo->image_width;
  162671. while (--num_rows >= 0) {
  162672. inptr = *input_buf++;
  162673. outptr = output_buf[0][output_row];
  162674. output_row++;
  162675. for (col = 0; col < num_cols; col++) {
  162676. r = GETJSAMPLE(inptr[RGB_RED]);
  162677. g = GETJSAMPLE(inptr[RGB_GREEN]);
  162678. b = GETJSAMPLE(inptr[RGB_BLUE]);
  162679. inptr += RGB_PIXELSIZE;
  162680. /* Y */
  162681. outptr[col] = (JSAMPLE)
  162682. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162683. >> SCALEBITS);
  162684. }
  162685. }
  162686. }
  162687. /*
  162688. * Convert some rows of samples to the JPEG colorspace.
  162689. * This version handles Adobe-style CMYK->YCCK conversion,
  162690. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  162691. * conversion as above, while passing K (black) unchanged.
  162692. * We assume rgb_ycc_start has been called.
  162693. */
  162694. METHODDEF(void)
  162695. cmyk_ycck_convert (j_compress_ptr cinfo,
  162696. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162697. JDIMENSION output_row, int num_rows)
  162698. {
  162699. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  162700. register int r, g, b;
  162701. register INT32 * ctab = cconvert->rgb_ycc_tab;
  162702. register JSAMPROW inptr;
  162703. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  162704. register JDIMENSION col;
  162705. JDIMENSION num_cols = cinfo->image_width;
  162706. while (--num_rows >= 0) {
  162707. inptr = *input_buf++;
  162708. outptr0 = output_buf[0][output_row];
  162709. outptr1 = output_buf[1][output_row];
  162710. outptr2 = output_buf[2][output_row];
  162711. outptr3 = output_buf[3][output_row];
  162712. output_row++;
  162713. for (col = 0; col < num_cols; col++) {
  162714. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  162715. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  162716. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  162717. /* K passes through as-is */
  162718. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  162719. inptr += 4;
  162720. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  162721. * must be too; we do not need an explicit range-limiting operation.
  162722. * Hence the value being shifted is never negative, and we don't
  162723. * need the general RIGHT_SHIFT macro.
  162724. */
  162725. /* Y */
  162726. outptr0[col] = (JSAMPLE)
  162727. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  162728. >> SCALEBITS);
  162729. /* Cb */
  162730. outptr1[col] = (JSAMPLE)
  162731. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  162732. >> SCALEBITS);
  162733. /* Cr */
  162734. outptr2[col] = (JSAMPLE)
  162735. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  162736. >> SCALEBITS);
  162737. }
  162738. }
  162739. }
  162740. /*
  162741. * Convert some rows of samples to the JPEG colorspace.
  162742. * This version handles grayscale output with no conversion.
  162743. * The source can be either plain grayscale or YCbCr (since Y == gray).
  162744. */
  162745. METHODDEF(void)
  162746. grayscale_convert (j_compress_ptr cinfo,
  162747. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162748. JDIMENSION output_row, int num_rows)
  162749. {
  162750. register JSAMPROW inptr;
  162751. register JSAMPROW outptr;
  162752. register JDIMENSION col;
  162753. JDIMENSION num_cols = cinfo->image_width;
  162754. int instride = cinfo->input_components;
  162755. while (--num_rows >= 0) {
  162756. inptr = *input_buf++;
  162757. outptr = output_buf[0][output_row];
  162758. output_row++;
  162759. for (col = 0; col < num_cols; col++) {
  162760. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  162761. inptr += instride;
  162762. }
  162763. }
  162764. }
  162765. /*
  162766. * Convert some rows of samples to the JPEG colorspace.
  162767. * This version handles multi-component colorspaces without conversion.
  162768. * We assume input_components == num_components.
  162769. */
  162770. METHODDEF(void)
  162771. null_convert (j_compress_ptr cinfo,
  162772. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  162773. JDIMENSION output_row, int num_rows)
  162774. {
  162775. register JSAMPROW inptr;
  162776. register JSAMPROW outptr;
  162777. register JDIMENSION col;
  162778. register int ci;
  162779. int nc = cinfo->num_components;
  162780. JDIMENSION num_cols = cinfo->image_width;
  162781. while (--num_rows >= 0) {
  162782. /* It seems fastest to make a separate pass for each component. */
  162783. for (ci = 0; ci < nc; ci++) {
  162784. inptr = *input_buf;
  162785. outptr = output_buf[ci][output_row];
  162786. for (col = 0; col < num_cols; col++) {
  162787. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  162788. inptr += nc;
  162789. }
  162790. }
  162791. input_buf++;
  162792. output_row++;
  162793. }
  162794. }
  162795. /*
  162796. * Empty method for start_pass.
  162797. */
  162798. METHODDEF(void)
  162799. null_method (j_compress_ptr)
  162800. {
  162801. /* no work needed */
  162802. }
  162803. /*
  162804. * Module initialization routine for input colorspace conversion.
  162805. */
  162806. GLOBAL(void)
  162807. jinit_color_converter (j_compress_ptr cinfo)
  162808. {
  162809. my_cconvert_ptr cconvert;
  162810. cconvert = (my_cconvert_ptr)
  162811. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  162812. SIZEOF(my_color_converter));
  162813. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  162814. /* set start_pass to null method until we find out differently */
  162815. cconvert->pub.start_pass = null_method;
  162816. /* Make sure input_components agrees with in_color_space */
  162817. switch (cinfo->in_color_space) {
  162818. case JCS_GRAYSCALE:
  162819. if (cinfo->input_components != 1)
  162820. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162821. break;
  162822. case JCS_RGB:
  162823. #if RGB_PIXELSIZE != 3
  162824. if (cinfo->input_components != RGB_PIXELSIZE)
  162825. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162826. break;
  162827. #endif /* else share code with YCbCr */
  162828. case JCS_YCbCr:
  162829. if (cinfo->input_components != 3)
  162830. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162831. break;
  162832. case JCS_CMYK:
  162833. case JCS_YCCK:
  162834. if (cinfo->input_components != 4)
  162835. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162836. break;
  162837. default: /* JCS_UNKNOWN can be anything */
  162838. if (cinfo->input_components < 1)
  162839. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  162840. break;
  162841. }
  162842. /* Check num_components, set conversion method based on requested space */
  162843. switch (cinfo->jpeg_color_space) {
  162844. case JCS_GRAYSCALE:
  162845. if (cinfo->num_components != 1)
  162846. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162847. if (cinfo->in_color_space == JCS_GRAYSCALE)
  162848. cconvert->pub.color_convert = grayscale_convert;
  162849. else if (cinfo->in_color_space == JCS_RGB) {
  162850. cconvert->pub.start_pass = rgb_ycc_start;
  162851. cconvert->pub.color_convert = rgb_gray_convert;
  162852. } else if (cinfo->in_color_space == JCS_YCbCr)
  162853. cconvert->pub.color_convert = grayscale_convert;
  162854. else
  162855. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162856. break;
  162857. case JCS_RGB:
  162858. if (cinfo->num_components != 3)
  162859. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162860. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  162861. cconvert->pub.color_convert = null_convert;
  162862. else
  162863. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162864. break;
  162865. case JCS_YCbCr:
  162866. if (cinfo->num_components != 3)
  162867. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162868. if (cinfo->in_color_space == JCS_RGB) {
  162869. cconvert->pub.start_pass = rgb_ycc_start;
  162870. cconvert->pub.color_convert = rgb_ycc_convert;
  162871. } else if (cinfo->in_color_space == JCS_YCbCr)
  162872. cconvert->pub.color_convert = null_convert;
  162873. else
  162874. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162875. break;
  162876. case JCS_CMYK:
  162877. if (cinfo->num_components != 4)
  162878. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162879. if (cinfo->in_color_space == JCS_CMYK)
  162880. cconvert->pub.color_convert = null_convert;
  162881. else
  162882. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162883. break;
  162884. case JCS_YCCK:
  162885. if (cinfo->num_components != 4)
  162886. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  162887. if (cinfo->in_color_space == JCS_CMYK) {
  162888. cconvert->pub.start_pass = rgb_ycc_start;
  162889. cconvert->pub.color_convert = cmyk_ycck_convert;
  162890. } else if (cinfo->in_color_space == JCS_YCCK)
  162891. cconvert->pub.color_convert = null_convert;
  162892. else
  162893. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162894. break;
  162895. default: /* allow null conversion of JCS_UNKNOWN */
  162896. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  162897. cinfo->num_components != cinfo->input_components)
  162898. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  162899. cconvert->pub.color_convert = null_convert;
  162900. break;
  162901. }
  162902. }
  162903. /*** End of inlined file: jccolor.c ***/
  162904. #undef FIX
  162905. /*** Start of inlined file: jcdctmgr.c ***/
  162906. #define JPEG_INTERNALS
  162907. /*** Start of inlined file: jdct.h ***/
  162908. /*
  162909. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  162910. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  162911. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  162912. * implementations use an array of type FAST_FLOAT, instead.)
  162913. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  162914. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  162915. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  162916. * convention improves accuracy in integer implementations and saves some
  162917. * work in floating-point ones.
  162918. * Quantization of the output coefficients is done by jcdctmgr.c.
  162919. */
  162920. #ifndef __jdct_h__
  162921. #define __jdct_h__
  162922. #if BITS_IN_JSAMPLE == 8
  162923. typedef int DCTELEM; /* 16 or 32 bits is fine */
  162924. #else
  162925. typedef INT32 DCTELEM; /* must have 32 bits */
  162926. #endif
  162927. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  162928. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  162929. /*
  162930. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  162931. * to an output sample array. The routine must dequantize the input data as
  162932. * well as perform the IDCT; for dequantization, it uses the multiplier table
  162933. * pointed to by compptr->dct_table. The output data is to be placed into the
  162934. * sample array starting at a specified column. (Any row offset needed will
  162935. * be applied to the array pointer before it is passed to the IDCT code.)
  162936. * Note that the number of samples emitted by the IDCT routine is
  162937. * DCT_scaled_size * DCT_scaled_size.
  162938. */
  162939. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  162940. /*
  162941. * Each IDCT routine has its own ideas about the best dct_table element type.
  162942. */
  162943. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  162944. #if BITS_IN_JSAMPLE == 8
  162945. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  162946. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  162947. #else
  162948. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  162949. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  162950. #endif
  162951. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  162952. /*
  162953. * Each IDCT routine is responsible for range-limiting its results and
  162954. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  162955. * be quite far out of range if the input data is corrupt, so a bulletproof
  162956. * range-limiting step is required. We use a mask-and-table-lookup method
  162957. * to do the combined operations quickly. See the comments with
  162958. * prepare_range_limit_table (in jdmaster.c) for more info.
  162959. */
  162960. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  162961. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  162962. /* Short forms of external names for systems with brain-damaged linkers. */
  162963. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162964. #define jpeg_fdct_islow jFDislow
  162965. #define jpeg_fdct_ifast jFDifast
  162966. #define jpeg_fdct_float jFDfloat
  162967. #define jpeg_idct_islow jRDislow
  162968. #define jpeg_idct_ifast jRDifast
  162969. #define jpeg_idct_float jRDfloat
  162970. #define jpeg_idct_4x4 jRD4x4
  162971. #define jpeg_idct_2x2 jRD2x2
  162972. #define jpeg_idct_1x1 jRD1x1
  162973. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162974. /* Extern declarations for the forward and inverse DCT routines. */
  162975. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  162976. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  162977. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  162978. EXTERN(void) jpeg_idct_islow
  162979. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162980. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162981. EXTERN(void) jpeg_idct_ifast
  162982. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162983. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162984. EXTERN(void) jpeg_idct_float
  162985. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162986. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162987. EXTERN(void) jpeg_idct_4x4
  162988. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162989. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162990. EXTERN(void) jpeg_idct_2x2
  162991. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162992. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162993. EXTERN(void) jpeg_idct_1x1
  162994. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  162995. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  162996. /*
  162997. * Macros for handling fixed-point arithmetic; these are used by many
  162998. * but not all of the DCT/IDCT modules.
  162999. *
  163000. * All values are expected to be of type INT32.
  163001. * Fractional constants are scaled left by CONST_BITS bits.
  163002. * CONST_BITS is defined within each module using these macros,
  163003. * and may differ from one module to the next.
  163004. */
  163005. #define ONE ((INT32) 1)
  163006. #define CONST_SCALE (ONE << CONST_BITS)
  163007. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  163008. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  163009. * thus causing a lot of useless floating-point operations at run time.
  163010. */
  163011. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  163012. /* Descale and correctly round an INT32 value that's scaled by N bits.
  163013. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  163014. * the fudge factor is correct for either sign of X.
  163015. */
  163016. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  163017. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  163018. * This macro is used only when the two inputs will actually be no more than
  163019. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  163020. * full 32x32 multiply. This provides a useful speedup on many machines.
  163021. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  163022. * in C, but some C compilers will do the right thing if you provide the
  163023. * correct combination of casts.
  163024. */
  163025. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163026. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  163027. #endif
  163028. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  163029. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  163030. #endif
  163031. #ifndef MULTIPLY16C16 /* default definition */
  163032. #define MULTIPLY16C16(var,const) ((var) * (const))
  163033. #endif
  163034. /* Same except both inputs are variables. */
  163035. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163036. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163037. #endif
  163038. #ifndef MULTIPLY16V16 /* default definition */
  163039. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163040. #endif
  163041. #endif
  163042. /*** End of inlined file: jdct.h ***/
  163043. /* Private declarations for DCT subsystem */
  163044. /* Private subobject for this module */
  163045. typedef struct {
  163046. struct jpeg_forward_dct pub; /* public fields */
  163047. /* Pointer to the DCT routine actually in use */
  163048. forward_DCT_method_ptr do_dct;
  163049. /* The actual post-DCT divisors --- not identical to the quant table
  163050. * entries, because of scaling (especially for an unnormalized DCT).
  163051. * Each table is given in normal array order.
  163052. */
  163053. DCTELEM * divisors[NUM_QUANT_TBLS];
  163054. #ifdef DCT_FLOAT_SUPPORTED
  163055. /* Same as above for the floating-point case. */
  163056. float_DCT_method_ptr do_float_dct;
  163057. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163058. #endif
  163059. } my_fdct_controller;
  163060. typedef my_fdct_controller * my_fdct_ptr;
  163061. /*
  163062. * Initialize for a processing pass.
  163063. * Verify that all referenced Q-tables are present, and set up
  163064. * the divisor table for each one.
  163065. * In the current implementation, DCT of all components is done during
  163066. * the first pass, even if only some components will be output in the
  163067. * first scan. Hence all components should be examined here.
  163068. */
  163069. METHODDEF(void)
  163070. start_pass_fdctmgr (j_compress_ptr cinfo)
  163071. {
  163072. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163073. int ci, qtblno, i;
  163074. jpeg_component_info *compptr;
  163075. JQUANT_TBL * qtbl;
  163076. DCTELEM * dtbl;
  163077. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163078. ci++, compptr++) {
  163079. qtblno = compptr->quant_tbl_no;
  163080. /* Make sure specified quantization table is present */
  163081. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163082. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163083. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163084. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163085. /* Compute divisors for this quant table */
  163086. /* We may do this more than once for same table, but it's not a big deal */
  163087. switch (cinfo->dct_method) {
  163088. #ifdef DCT_ISLOW_SUPPORTED
  163089. case JDCT_ISLOW:
  163090. /* For LL&M IDCT method, divisors are equal to raw quantization
  163091. * coefficients multiplied by 8 (to counteract scaling).
  163092. */
  163093. if (fdct->divisors[qtblno] == NULL) {
  163094. fdct->divisors[qtblno] = (DCTELEM *)
  163095. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163096. DCTSIZE2 * SIZEOF(DCTELEM));
  163097. }
  163098. dtbl = fdct->divisors[qtblno];
  163099. for (i = 0; i < DCTSIZE2; i++) {
  163100. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163101. }
  163102. break;
  163103. #endif
  163104. #ifdef DCT_IFAST_SUPPORTED
  163105. case JDCT_IFAST:
  163106. {
  163107. /* For AA&N IDCT method, divisors are equal to quantization
  163108. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163109. * scalefactor[0] = 1
  163110. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163111. * We apply a further scale factor of 8.
  163112. */
  163113. #define CONST_BITS 14
  163114. static const INT16 aanscales[DCTSIZE2] = {
  163115. /* precomputed values scaled up by 14 bits */
  163116. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163117. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163118. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163119. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163120. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163121. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163122. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163123. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163124. };
  163125. SHIFT_TEMPS
  163126. if (fdct->divisors[qtblno] == NULL) {
  163127. fdct->divisors[qtblno] = (DCTELEM *)
  163128. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163129. DCTSIZE2 * SIZEOF(DCTELEM));
  163130. }
  163131. dtbl = fdct->divisors[qtblno];
  163132. for (i = 0; i < DCTSIZE2; i++) {
  163133. dtbl[i] = (DCTELEM)
  163134. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163135. (INT32) aanscales[i]),
  163136. CONST_BITS-3);
  163137. }
  163138. }
  163139. break;
  163140. #endif
  163141. #ifdef DCT_FLOAT_SUPPORTED
  163142. case JDCT_FLOAT:
  163143. {
  163144. /* For float AA&N IDCT method, divisors are equal to quantization
  163145. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163146. * scalefactor[0] = 1
  163147. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163148. * We apply a further scale factor of 8.
  163149. * What's actually stored is 1/divisor so that the inner loop can
  163150. * use a multiplication rather than a division.
  163151. */
  163152. FAST_FLOAT * fdtbl;
  163153. int row, col;
  163154. static const double aanscalefactor[DCTSIZE] = {
  163155. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163156. 1.0, 0.785694958, 0.541196100, 0.275899379
  163157. };
  163158. if (fdct->float_divisors[qtblno] == NULL) {
  163159. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163160. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163161. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163162. }
  163163. fdtbl = fdct->float_divisors[qtblno];
  163164. i = 0;
  163165. for (row = 0; row < DCTSIZE; row++) {
  163166. for (col = 0; col < DCTSIZE; col++) {
  163167. fdtbl[i] = (FAST_FLOAT)
  163168. (1.0 / (((double) qtbl->quantval[i] *
  163169. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163170. i++;
  163171. }
  163172. }
  163173. }
  163174. break;
  163175. #endif
  163176. default:
  163177. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163178. break;
  163179. }
  163180. }
  163181. }
  163182. /*
  163183. * Perform forward DCT on one or more blocks of a component.
  163184. *
  163185. * The input samples are taken from the sample_data[] array starting at
  163186. * position start_row/start_col, and moving to the right for any additional
  163187. * blocks. The quantized coefficients are returned in coef_blocks[].
  163188. */
  163189. METHODDEF(void)
  163190. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163191. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163192. JDIMENSION start_row, JDIMENSION start_col,
  163193. JDIMENSION num_blocks)
  163194. /* This version is used for integer DCT implementations. */
  163195. {
  163196. /* This routine is heavily used, so it's worth coding it tightly. */
  163197. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163198. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163199. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163200. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163201. JDIMENSION bi;
  163202. sample_data += start_row; /* fold in the vertical offset once */
  163203. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163204. /* Load data into workspace, applying unsigned->signed conversion */
  163205. { register DCTELEM *workspaceptr;
  163206. register JSAMPROW elemptr;
  163207. register int elemr;
  163208. workspaceptr = workspace;
  163209. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163210. elemptr = sample_data[elemr] + start_col;
  163211. #if DCTSIZE == 8 /* unroll the inner loop */
  163212. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163213. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163214. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163215. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163216. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163217. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163218. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163219. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163220. #else
  163221. { register int elemc;
  163222. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163223. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163224. }
  163225. }
  163226. #endif
  163227. }
  163228. }
  163229. /* Perform the DCT */
  163230. (*do_dct) (workspace);
  163231. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163232. { register DCTELEM temp, qval;
  163233. register int i;
  163234. register JCOEFPTR output_ptr = coef_blocks[bi];
  163235. for (i = 0; i < DCTSIZE2; i++) {
  163236. qval = divisors[i];
  163237. temp = workspace[i];
  163238. /* Divide the coefficient value by qval, ensuring proper rounding.
  163239. * Since C does not specify the direction of rounding for negative
  163240. * quotients, we have to force the dividend positive for portability.
  163241. *
  163242. * In most files, at least half of the output values will be zero
  163243. * (at default quantization settings, more like three-quarters...)
  163244. * so we should ensure that this case is fast. On many machines,
  163245. * a comparison is enough cheaper than a divide to make a special test
  163246. * a win. Since both inputs will be nonnegative, we need only test
  163247. * for a < b to discover whether a/b is 0.
  163248. * If your machine's division is fast enough, define FAST_DIVIDE.
  163249. */
  163250. #ifdef FAST_DIVIDE
  163251. #define DIVIDE_BY(a,b) a /= b
  163252. #else
  163253. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  163254. #endif
  163255. if (temp < 0) {
  163256. temp = -temp;
  163257. temp += qval>>1; /* for rounding */
  163258. DIVIDE_BY(temp, qval);
  163259. temp = -temp;
  163260. } else {
  163261. temp += qval>>1; /* for rounding */
  163262. DIVIDE_BY(temp, qval);
  163263. }
  163264. output_ptr[i] = (JCOEF) temp;
  163265. }
  163266. }
  163267. }
  163268. }
  163269. #ifdef DCT_FLOAT_SUPPORTED
  163270. METHODDEF(void)
  163271. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163272. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163273. JDIMENSION start_row, JDIMENSION start_col,
  163274. JDIMENSION num_blocks)
  163275. /* This version is used for floating-point DCT implementations. */
  163276. {
  163277. /* This routine is heavily used, so it's worth coding it tightly. */
  163278. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163279. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  163280. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  163281. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163282. JDIMENSION bi;
  163283. sample_data += start_row; /* fold in the vertical offset once */
  163284. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163285. /* Load data into workspace, applying unsigned->signed conversion */
  163286. { register FAST_FLOAT *workspaceptr;
  163287. register JSAMPROW elemptr;
  163288. register int elemr;
  163289. workspaceptr = workspace;
  163290. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163291. elemptr = sample_data[elemr] + start_col;
  163292. #if DCTSIZE == 8 /* unroll the inner loop */
  163293. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163294. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163295. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163296. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163297. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163298. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163299. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163300. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163301. #else
  163302. { register int elemc;
  163303. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163304. *workspaceptr++ = (FAST_FLOAT)
  163305. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  163306. }
  163307. }
  163308. #endif
  163309. }
  163310. }
  163311. /* Perform the DCT */
  163312. (*do_dct) (workspace);
  163313. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  163314. { register FAST_FLOAT temp;
  163315. register int i;
  163316. register JCOEFPTR output_ptr = coef_blocks[bi];
  163317. for (i = 0; i < DCTSIZE2; i++) {
  163318. /* Apply the quantization and scaling factor */
  163319. temp = workspace[i] * divisors[i];
  163320. /* Round to nearest integer.
  163321. * Since C does not specify the direction of rounding for negative
  163322. * quotients, we have to force the dividend positive for portability.
  163323. * The maximum coefficient size is +-16K (for 12-bit data), so this
  163324. * code should work for either 16-bit or 32-bit ints.
  163325. */
  163326. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  163327. }
  163328. }
  163329. }
  163330. }
  163331. #endif /* DCT_FLOAT_SUPPORTED */
  163332. /*
  163333. * Initialize FDCT manager.
  163334. */
  163335. GLOBAL(void)
  163336. jinit_forward_dct (j_compress_ptr cinfo)
  163337. {
  163338. my_fdct_ptr fdct;
  163339. int i;
  163340. fdct = (my_fdct_ptr)
  163341. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163342. SIZEOF(my_fdct_controller));
  163343. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  163344. fdct->pub.start_pass = start_pass_fdctmgr;
  163345. switch (cinfo->dct_method) {
  163346. #ifdef DCT_ISLOW_SUPPORTED
  163347. case JDCT_ISLOW:
  163348. fdct->pub.forward_DCT = forward_DCT;
  163349. fdct->do_dct = jpeg_fdct_islow;
  163350. break;
  163351. #endif
  163352. #ifdef DCT_IFAST_SUPPORTED
  163353. case JDCT_IFAST:
  163354. fdct->pub.forward_DCT = forward_DCT;
  163355. fdct->do_dct = jpeg_fdct_ifast;
  163356. break;
  163357. #endif
  163358. #ifdef DCT_FLOAT_SUPPORTED
  163359. case JDCT_FLOAT:
  163360. fdct->pub.forward_DCT = forward_DCT_float;
  163361. fdct->do_float_dct = jpeg_fdct_float;
  163362. break;
  163363. #endif
  163364. default:
  163365. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163366. break;
  163367. }
  163368. /* Mark divisor tables unallocated */
  163369. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  163370. fdct->divisors[i] = NULL;
  163371. #ifdef DCT_FLOAT_SUPPORTED
  163372. fdct->float_divisors[i] = NULL;
  163373. #endif
  163374. }
  163375. }
  163376. /*** End of inlined file: jcdctmgr.c ***/
  163377. #undef CONST_BITS
  163378. /*** Start of inlined file: jchuff.c ***/
  163379. #define JPEG_INTERNALS
  163380. /*** Start of inlined file: jchuff.h ***/
  163381. /* The legal range of a DCT coefficient is
  163382. * -1024 .. +1023 for 8-bit data;
  163383. * -16384 .. +16383 for 12-bit data.
  163384. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  163385. */
  163386. #ifndef _jchuff_h_
  163387. #define _jchuff_h_
  163388. #if BITS_IN_JSAMPLE == 8
  163389. #define MAX_COEF_BITS 10
  163390. #else
  163391. #define MAX_COEF_BITS 14
  163392. #endif
  163393. /* Derived data constructed for each Huffman table */
  163394. typedef struct {
  163395. unsigned int ehufco[256]; /* code for each symbol */
  163396. char ehufsi[256]; /* length of code for each symbol */
  163397. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  163398. } c_derived_tbl;
  163399. /* Short forms of external names for systems with brain-damaged linkers. */
  163400. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163401. #define jpeg_make_c_derived_tbl jMkCDerived
  163402. #define jpeg_gen_optimal_table jGenOptTbl
  163403. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163404. /* Expand a Huffman table definition into the derived format */
  163405. EXTERN(void) jpeg_make_c_derived_tbl
  163406. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  163407. c_derived_tbl ** pdtbl));
  163408. /* Generate an optimal table definition given the specified counts */
  163409. EXTERN(void) jpeg_gen_optimal_table
  163410. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  163411. #endif
  163412. /*** End of inlined file: jchuff.h ***/
  163413. /* Declarations shared with jcphuff.c */
  163414. /* Expanded entropy encoder object for Huffman encoding.
  163415. *
  163416. * The savable_state subrecord contains fields that change within an MCU,
  163417. * but must not be updated permanently until we complete the MCU.
  163418. */
  163419. typedef struct {
  163420. INT32 put_buffer; /* current bit-accumulation buffer */
  163421. int put_bits; /* # of bits now in it */
  163422. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  163423. } savable_state;
  163424. /* This macro is to work around compilers with missing or broken
  163425. * structure assignment. You'll need to fix this code if you have
  163426. * such a compiler and you change MAX_COMPS_IN_SCAN.
  163427. */
  163428. #ifndef NO_STRUCT_ASSIGN
  163429. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  163430. #else
  163431. #if MAX_COMPS_IN_SCAN == 4
  163432. #define ASSIGN_STATE(dest,src) \
  163433. ((dest).put_buffer = (src).put_buffer, \
  163434. (dest).put_bits = (src).put_bits, \
  163435. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  163436. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  163437. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  163438. (dest).last_dc_val[3] = (src).last_dc_val[3])
  163439. #endif
  163440. #endif
  163441. typedef struct {
  163442. struct jpeg_entropy_encoder pub; /* public fields */
  163443. savable_state saved; /* Bit buffer & DC state at start of MCU */
  163444. /* These fields are NOT loaded into local working state. */
  163445. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  163446. int next_restart_num; /* next restart number to write (0-7) */
  163447. /* Pointers to derived tables (these workspaces have image lifespan) */
  163448. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  163449. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  163450. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  163451. long * dc_count_ptrs[NUM_HUFF_TBLS];
  163452. long * ac_count_ptrs[NUM_HUFF_TBLS];
  163453. #endif
  163454. } huff_entropy_encoder;
  163455. typedef huff_entropy_encoder * huff_entropy_ptr;
  163456. /* Working state while writing an MCU.
  163457. * This struct contains all the fields that are needed by subroutines.
  163458. */
  163459. typedef struct {
  163460. JOCTET * next_output_byte; /* => next byte to write in buffer */
  163461. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  163462. savable_state cur; /* Current bit buffer & DC state */
  163463. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  163464. } working_state;
  163465. /* Forward declarations */
  163466. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  163467. JBLOCKROW *MCU_data));
  163468. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  163469. #ifdef ENTROPY_OPT_SUPPORTED
  163470. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  163471. JBLOCKROW *MCU_data));
  163472. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  163473. #endif
  163474. /*
  163475. * Initialize for a Huffman-compressed scan.
  163476. * If gather_statistics is TRUE, we do not output anything during the scan,
  163477. * just count the Huffman symbols used and generate Huffman code tables.
  163478. */
  163479. METHODDEF(void)
  163480. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  163481. {
  163482. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163483. int ci, dctbl, actbl;
  163484. jpeg_component_info * compptr;
  163485. if (gather_statistics) {
  163486. #ifdef ENTROPY_OPT_SUPPORTED
  163487. entropy->pub.encode_mcu = encode_mcu_gather;
  163488. entropy->pub.finish_pass = finish_pass_gather;
  163489. #else
  163490. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163491. #endif
  163492. } else {
  163493. entropy->pub.encode_mcu = encode_mcu_huff;
  163494. entropy->pub.finish_pass = finish_pass_huff;
  163495. }
  163496. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163497. compptr = cinfo->cur_comp_info[ci];
  163498. dctbl = compptr->dc_tbl_no;
  163499. actbl = compptr->ac_tbl_no;
  163500. if (gather_statistics) {
  163501. #ifdef ENTROPY_OPT_SUPPORTED
  163502. /* Check for invalid table indexes */
  163503. /* (make_c_derived_tbl does this in the other path) */
  163504. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  163505. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  163506. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  163507. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  163508. /* Allocate and zero the statistics tables */
  163509. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  163510. if (entropy->dc_count_ptrs[dctbl] == NULL)
  163511. entropy->dc_count_ptrs[dctbl] = (long *)
  163512. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163513. 257 * SIZEOF(long));
  163514. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  163515. if (entropy->ac_count_ptrs[actbl] == NULL)
  163516. entropy->ac_count_ptrs[actbl] = (long *)
  163517. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163518. 257 * SIZEOF(long));
  163519. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  163520. #endif
  163521. } else {
  163522. /* Compute derived values for Huffman tables */
  163523. /* We may do this more than once for a table, but it's not expensive */
  163524. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  163525. & entropy->dc_derived_tbls[dctbl]);
  163526. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  163527. & entropy->ac_derived_tbls[actbl]);
  163528. }
  163529. /* Initialize DC predictions to 0 */
  163530. entropy->saved.last_dc_val[ci] = 0;
  163531. }
  163532. /* Initialize bit buffer to empty */
  163533. entropy->saved.put_buffer = 0;
  163534. entropy->saved.put_bits = 0;
  163535. /* Initialize restart stuff */
  163536. entropy->restarts_to_go = cinfo->restart_interval;
  163537. entropy->next_restart_num = 0;
  163538. }
  163539. /*
  163540. * Compute the derived values for a Huffman table.
  163541. * This routine also performs some validation checks on the table.
  163542. *
  163543. * Note this is also used by jcphuff.c.
  163544. */
  163545. GLOBAL(void)
  163546. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  163547. c_derived_tbl ** pdtbl)
  163548. {
  163549. JHUFF_TBL *htbl;
  163550. c_derived_tbl *dtbl;
  163551. int p, i, l, lastp, si, maxsymbol;
  163552. char huffsize[257];
  163553. unsigned int huffcode[257];
  163554. unsigned int code;
  163555. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  163556. * paralleling the order of the symbols themselves in htbl->huffval[].
  163557. */
  163558. /* Find the input Huffman table */
  163559. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  163560. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163561. htbl =
  163562. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  163563. if (htbl == NULL)
  163564. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  163565. /* Allocate a workspace if we haven't already done so. */
  163566. if (*pdtbl == NULL)
  163567. *pdtbl = (c_derived_tbl *)
  163568. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163569. SIZEOF(c_derived_tbl));
  163570. dtbl = *pdtbl;
  163571. /* Figure C.1: make table of Huffman code length for each symbol */
  163572. p = 0;
  163573. for (l = 1; l <= 16; l++) {
  163574. i = (int) htbl->bits[l];
  163575. if (i < 0 || p + i > 256) /* protect against table overrun */
  163576. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163577. while (i--)
  163578. huffsize[p++] = (char) l;
  163579. }
  163580. huffsize[p] = 0;
  163581. lastp = p;
  163582. /* Figure C.2: generate the codes themselves */
  163583. /* We also validate that the counts represent a legal Huffman code tree. */
  163584. code = 0;
  163585. si = huffsize[0];
  163586. p = 0;
  163587. while (huffsize[p]) {
  163588. while (((int) huffsize[p]) == si) {
  163589. huffcode[p++] = code;
  163590. code++;
  163591. }
  163592. /* code is now 1 more than the last code used for codelength si; but
  163593. * it must still fit in si bits, since no code is allowed to be all ones.
  163594. */
  163595. if (((INT32) code) >= (((INT32) 1) << si))
  163596. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163597. code <<= 1;
  163598. si++;
  163599. }
  163600. /* Figure C.3: generate encoding tables */
  163601. /* These are code and size indexed by symbol value */
  163602. /* Set all codeless symbols to have code length 0;
  163603. * this lets us detect duplicate VAL entries here, and later
  163604. * allows emit_bits to detect any attempt to emit such symbols.
  163605. */
  163606. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  163607. /* This is also a convenient place to check for out-of-range
  163608. * and duplicated VAL entries. We allow 0..255 for AC symbols
  163609. * but only 0..15 for DC. (We could constrain them further
  163610. * based on data depth and mode, but this seems enough.)
  163611. */
  163612. maxsymbol = isDC ? 15 : 255;
  163613. for (p = 0; p < lastp; p++) {
  163614. i = htbl->huffval[p];
  163615. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  163616. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  163617. dtbl->ehufco[i] = huffcode[p];
  163618. dtbl->ehufsi[i] = huffsize[p];
  163619. }
  163620. }
  163621. /* Outputting bytes to the file */
  163622. /* Emit a byte, taking 'action' if must suspend. */
  163623. #define emit_byte(state,val,action) \
  163624. { *(state)->next_output_byte++ = (JOCTET) (val); \
  163625. if (--(state)->free_in_buffer == 0) \
  163626. if (! dump_buffer(state)) \
  163627. { action; } }
  163628. LOCAL(boolean)
  163629. dump_buffer (working_state * state)
  163630. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  163631. {
  163632. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  163633. if (! (*dest->empty_output_buffer) (state->cinfo))
  163634. return FALSE;
  163635. /* After a successful buffer dump, must reset buffer pointers */
  163636. state->next_output_byte = dest->next_output_byte;
  163637. state->free_in_buffer = dest->free_in_buffer;
  163638. return TRUE;
  163639. }
  163640. /* Outputting bits to the file */
  163641. /* Only the right 24 bits of put_buffer are used; the valid bits are
  163642. * left-justified in this part. At most 16 bits can be passed to emit_bits
  163643. * in one call, and we never retain more than 7 bits in put_buffer
  163644. * between calls, so 24 bits are sufficient.
  163645. */
  163646. INLINE
  163647. LOCAL(boolean)
  163648. emit_bits (working_state * state, unsigned int code, int size)
  163649. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  163650. {
  163651. /* This routine is heavily used, so it's worth coding tightly. */
  163652. register INT32 put_buffer = (INT32) code;
  163653. register int put_bits = state->cur.put_bits;
  163654. /* if size is 0, caller used an invalid Huffman table entry */
  163655. if (size == 0)
  163656. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  163657. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  163658. put_bits += size; /* new number of bits in buffer */
  163659. put_buffer <<= 24 - put_bits; /* align incoming bits */
  163660. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  163661. while (put_bits >= 8) {
  163662. int c = (int) ((put_buffer >> 16) & 0xFF);
  163663. emit_byte(state, c, return FALSE);
  163664. if (c == 0xFF) { /* need to stuff a zero byte? */
  163665. emit_byte(state, 0, return FALSE);
  163666. }
  163667. put_buffer <<= 8;
  163668. put_bits -= 8;
  163669. }
  163670. state->cur.put_buffer = put_buffer; /* update state variables */
  163671. state->cur.put_bits = put_bits;
  163672. return TRUE;
  163673. }
  163674. LOCAL(boolean)
  163675. flush_bits (working_state * state)
  163676. {
  163677. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  163678. return FALSE;
  163679. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  163680. state->cur.put_bits = 0;
  163681. return TRUE;
  163682. }
  163683. /* Encode a single block's worth of coefficients */
  163684. LOCAL(boolean)
  163685. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  163686. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  163687. {
  163688. register int temp, temp2;
  163689. register int nbits;
  163690. register int k, r, i;
  163691. /* Encode the DC coefficient difference per section F.1.2.1 */
  163692. temp = temp2 = block[0] - last_dc_val;
  163693. if (temp < 0) {
  163694. temp = -temp; /* temp is abs value of input */
  163695. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  163696. /* This code assumes we are on a two's complement machine */
  163697. temp2--;
  163698. }
  163699. /* Find the number of bits needed for the magnitude of the coefficient */
  163700. nbits = 0;
  163701. while (temp) {
  163702. nbits++;
  163703. temp >>= 1;
  163704. }
  163705. /* Check for out-of-range coefficient values.
  163706. * Since we're encoding a difference, the range limit is twice as much.
  163707. */
  163708. if (nbits > MAX_COEF_BITS+1)
  163709. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163710. /* Emit the Huffman-coded symbol for the number of bits */
  163711. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  163712. return FALSE;
  163713. /* Emit that number of bits of the value, if positive, */
  163714. /* or the complement of its magnitude, if negative. */
  163715. if (nbits) /* emit_bits rejects calls with size 0 */
  163716. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163717. return FALSE;
  163718. /* Encode the AC coefficients per section F.1.2.2 */
  163719. r = 0; /* r = run length of zeros */
  163720. for (k = 1; k < DCTSIZE2; k++) {
  163721. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163722. r++;
  163723. } else {
  163724. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163725. while (r > 15) {
  163726. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  163727. return FALSE;
  163728. r -= 16;
  163729. }
  163730. temp2 = temp;
  163731. if (temp < 0) {
  163732. temp = -temp; /* temp is abs value of input */
  163733. /* This code assumes we are on a two's complement machine */
  163734. temp2--;
  163735. }
  163736. /* Find the number of bits needed for the magnitude of the coefficient */
  163737. nbits = 1; /* there must be at least one 1 bit */
  163738. while ((temp >>= 1))
  163739. nbits++;
  163740. /* Check for out-of-range coefficient values */
  163741. if (nbits > MAX_COEF_BITS)
  163742. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  163743. /* Emit Huffman symbol for run length / number of bits */
  163744. i = (r << 4) + nbits;
  163745. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  163746. return FALSE;
  163747. /* Emit that number of bits of the value, if positive, */
  163748. /* or the complement of its magnitude, if negative. */
  163749. if (! emit_bits(state, (unsigned int) temp2, nbits))
  163750. return FALSE;
  163751. r = 0;
  163752. }
  163753. }
  163754. /* If the last coef(s) were zero, emit an end-of-block code */
  163755. if (r > 0)
  163756. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  163757. return FALSE;
  163758. return TRUE;
  163759. }
  163760. /*
  163761. * Emit a restart marker & resynchronize predictions.
  163762. */
  163763. LOCAL(boolean)
  163764. emit_restart (working_state * state, int restart_num)
  163765. {
  163766. int ci;
  163767. if (! flush_bits(state))
  163768. return FALSE;
  163769. emit_byte(state, 0xFF, return FALSE);
  163770. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  163771. /* Re-initialize DC predictions to 0 */
  163772. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  163773. state->cur.last_dc_val[ci] = 0;
  163774. /* The restart counter is not updated until we successfully write the MCU. */
  163775. return TRUE;
  163776. }
  163777. /*
  163778. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  163779. */
  163780. METHODDEF(boolean)
  163781. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163782. {
  163783. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163784. working_state state;
  163785. int blkn, ci;
  163786. jpeg_component_info * compptr;
  163787. /* Load up working state */
  163788. state.next_output_byte = cinfo->dest->next_output_byte;
  163789. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163790. ASSIGN_STATE(state.cur, entropy->saved);
  163791. state.cinfo = cinfo;
  163792. /* Emit restart marker if needed */
  163793. if (cinfo->restart_interval) {
  163794. if (entropy->restarts_to_go == 0)
  163795. if (! emit_restart(&state, entropy->next_restart_num))
  163796. return FALSE;
  163797. }
  163798. /* Encode the MCU data blocks */
  163799. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163800. ci = cinfo->MCU_membership[blkn];
  163801. compptr = cinfo->cur_comp_info[ci];
  163802. if (! encode_one_block(&state,
  163803. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  163804. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  163805. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  163806. return FALSE;
  163807. /* Update last_dc_val */
  163808. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  163809. }
  163810. /* Completed MCU, so update state */
  163811. cinfo->dest->next_output_byte = state.next_output_byte;
  163812. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163813. ASSIGN_STATE(entropy->saved, state.cur);
  163814. /* Update restart-interval state too */
  163815. if (cinfo->restart_interval) {
  163816. if (entropy->restarts_to_go == 0) {
  163817. entropy->restarts_to_go = cinfo->restart_interval;
  163818. entropy->next_restart_num++;
  163819. entropy->next_restart_num &= 7;
  163820. }
  163821. entropy->restarts_to_go--;
  163822. }
  163823. return TRUE;
  163824. }
  163825. /*
  163826. * Finish up at the end of a Huffman-compressed scan.
  163827. */
  163828. METHODDEF(void)
  163829. finish_pass_huff (j_compress_ptr cinfo)
  163830. {
  163831. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163832. working_state state;
  163833. /* Load up working state ... flush_bits needs it */
  163834. state.next_output_byte = cinfo->dest->next_output_byte;
  163835. state.free_in_buffer = cinfo->dest->free_in_buffer;
  163836. ASSIGN_STATE(state.cur, entropy->saved);
  163837. state.cinfo = cinfo;
  163838. /* Flush out the last data */
  163839. if (! flush_bits(&state))
  163840. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  163841. /* Update state */
  163842. cinfo->dest->next_output_byte = state.next_output_byte;
  163843. cinfo->dest->free_in_buffer = state.free_in_buffer;
  163844. ASSIGN_STATE(entropy->saved, state.cur);
  163845. }
  163846. /*
  163847. * Huffman coding optimization.
  163848. *
  163849. * We first scan the supplied data and count the number of uses of each symbol
  163850. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  163851. * Then we build a Huffman coding tree for the observed counts.
  163852. * Symbols which are not needed at all for the particular image are not
  163853. * assigned any code, which saves space in the DHT marker as well as in
  163854. * the compressed data.
  163855. */
  163856. #ifdef ENTROPY_OPT_SUPPORTED
  163857. /* Process a single block's worth of coefficients */
  163858. LOCAL(void)
  163859. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  163860. long dc_counts[], long ac_counts[])
  163861. {
  163862. register int temp;
  163863. register int nbits;
  163864. register int k, r;
  163865. /* Encode the DC coefficient difference per section F.1.2.1 */
  163866. temp = block[0] - last_dc_val;
  163867. if (temp < 0)
  163868. temp = -temp;
  163869. /* Find the number of bits needed for the magnitude of the coefficient */
  163870. nbits = 0;
  163871. while (temp) {
  163872. nbits++;
  163873. temp >>= 1;
  163874. }
  163875. /* Check for out-of-range coefficient values.
  163876. * Since we're encoding a difference, the range limit is twice as much.
  163877. */
  163878. if (nbits > MAX_COEF_BITS+1)
  163879. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163880. /* Count the Huffman symbol for the number of bits */
  163881. dc_counts[nbits]++;
  163882. /* Encode the AC coefficients per section F.1.2.2 */
  163883. r = 0; /* r = run length of zeros */
  163884. for (k = 1; k < DCTSIZE2; k++) {
  163885. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  163886. r++;
  163887. } else {
  163888. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  163889. while (r > 15) {
  163890. ac_counts[0xF0]++;
  163891. r -= 16;
  163892. }
  163893. /* Find the number of bits needed for the magnitude of the coefficient */
  163894. if (temp < 0)
  163895. temp = -temp;
  163896. /* Find the number of bits needed for the magnitude of the coefficient */
  163897. nbits = 1; /* there must be at least one 1 bit */
  163898. while ((temp >>= 1))
  163899. nbits++;
  163900. /* Check for out-of-range coefficient values */
  163901. if (nbits > MAX_COEF_BITS)
  163902. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  163903. /* Count Huffman symbol for run length / number of bits */
  163904. ac_counts[(r << 4) + nbits]++;
  163905. r = 0;
  163906. }
  163907. }
  163908. /* If the last coef(s) were zero, emit an end-of-block code */
  163909. if (r > 0)
  163910. ac_counts[0]++;
  163911. }
  163912. /*
  163913. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  163914. * No data is actually output, so no suspension return is possible.
  163915. */
  163916. METHODDEF(boolean)
  163917. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  163918. {
  163919. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  163920. int blkn, ci;
  163921. jpeg_component_info * compptr;
  163922. /* Take care of restart intervals if needed */
  163923. if (cinfo->restart_interval) {
  163924. if (entropy->restarts_to_go == 0) {
  163925. /* Re-initialize DC predictions to 0 */
  163926. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  163927. entropy->saved.last_dc_val[ci] = 0;
  163928. /* Update restart state */
  163929. entropy->restarts_to_go = cinfo->restart_interval;
  163930. }
  163931. entropy->restarts_to_go--;
  163932. }
  163933. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  163934. ci = cinfo->MCU_membership[blkn];
  163935. compptr = cinfo->cur_comp_info[ci];
  163936. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  163937. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  163938. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  163939. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  163940. }
  163941. return TRUE;
  163942. }
  163943. /*
  163944. * Generate the best Huffman code table for the given counts, fill htbl.
  163945. * Note this is also used by jcphuff.c.
  163946. *
  163947. * The JPEG standard requires that no symbol be assigned a codeword of all
  163948. * one bits (so that padding bits added at the end of a compressed segment
  163949. * can't look like a valid code). Because of the canonical ordering of
  163950. * codewords, this just means that there must be an unused slot in the
  163951. * longest codeword length category. Section K.2 of the JPEG spec suggests
  163952. * reserving such a slot by pretending that symbol 256 is a valid symbol
  163953. * with count 1. In theory that's not optimal; giving it count zero but
  163954. * including it in the symbol set anyway should give a better Huffman code.
  163955. * But the theoretically better code actually seems to come out worse in
  163956. * practice, because it produces more all-ones bytes (which incur stuffed
  163957. * zero bytes in the final file). In any case the difference is tiny.
  163958. *
  163959. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  163960. * If some symbols have a very small but nonzero probability, the Huffman tree
  163961. * must be adjusted to meet the code length restriction. We currently use
  163962. * the adjustment method suggested in JPEG section K.2. This method is *not*
  163963. * optimal; it may not choose the best possible limited-length code. But
  163964. * typically only very-low-frequency symbols will be given less-than-optimal
  163965. * lengths, so the code is almost optimal. Experimental comparisons against
  163966. * an optimal limited-length-code algorithm indicate that the difference is
  163967. * microscopic --- usually less than a hundredth of a percent of total size.
  163968. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  163969. */
  163970. GLOBAL(void)
  163971. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  163972. {
  163973. #define MAX_CLEN 32 /* assumed maximum initial code length */
  163974. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  163975. int codesize[257]; /* codesize[k] = code length of symbol k */
  163976. int others[257]; /* next symbol in current branch of tree */
  163977. int c1, c2;
  163978. int p, i, j;
  163979. long v;
  163980. /* This algorithm is explained in section K.2 of the JPEG standard */
  163981. MEMZERO(bits, SIZEOF(bits));
  163982. MEMZERO(codesize, SIZEOF(codesize));
  163983. for (i = 0; i < 257; i++)
  163984. others[i] = -1; /* init links to empty */
  163985. freq[256] = 1; /* make sure 256 has a nonzero count */
  163986. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  163987. * that no real symbol is given code-value of all ones, because 256
  163988. * will be placed last in the largest codeword category.
  163989. */
  163990. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  163991. for (;;) {
  163992. /* Find the smallest nonzero frequency, set c1 = its symbol */
  163993. /* In case of ties, take the larger symbol number */
  163994. c1 = -1;
  163995. v = 1000000000L;
  163996. for (i = 0; i <= 256; i++) {
  163997. if (freq[i] && freq[i] <= v) {
  163998. v = freq[i];
  163999. c1 = i;
  164000. }
  164001. }
  164002. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  164003. /* In case of ties, take the larger symbol number */
  164004. c2 = -1;
  164005. v = 1000000000L;
  164006. for (i = 0; i <= 256; i++) {
  164007. if (freq[i] && freq[i] <= v && i != c1) {
  164008. v = freq[i];
  164009. c2 = i;
  164010. }
  164011. }
  164012. /* Done if we've merged everything into one frequency */
  164013. if (c2 < 0)
  164014. break;
  164015. /* Else merge the two counts/trees */
  164016. freq[c1] += freq[c2];
  164017. freq[c2] = 0;
  164018. /* Increment the codesize of everything in c1's tree branch */
  164019. codesize[c1]++;
  164020. while (others[c1] >= 0) {
  164021. c1 = others[c1];
  164022. codesize[c1]++;
  164023. }
  164024. others[c1] = c2; /* chain c2 onto c1's tree branch */
  164025. /* Increment the codesize of everything in c2's tree branch */
  164026. codesize[c2]++;
  164027. while (others[c2] >= 0) {
  164028. c2 = others[c2];
  164029. codesize[c2]++;
  164030. }
  164031. }
  164032. /* Now count the number of symbols of each code length */
  164033. for (i = 0; i <= 256; i++) {
  164034. if (codesize[i]) {
  164035. /* The JPEG standard seems to think that this can't happen, */
  164036. /* but I'm paranoid... */
  164037. if (codesize[i] > MAX_CLEN)
  164038. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164039. bits[codesize[i]]++;
  164040. }
  164041. }
  164042. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164043. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164044. * Here is what the JPEG spec says about how this next bit works:
  164045. * Since symbols are paired for the longest Huffman code, the symbols are
  164046. * removed from this length category two at a time. The prefix for the pair
  164047. * (which is one bit shorter) is allocated to one of the pair; then,
  164048. * skipping the BITS entry for that prefix length, a code word from the next
  164049. * shortest nonzero BITS entry is converted into a prefix for two code words
  164050. * one bit longer.
  164051. */
  164052. for (i = MAX_CLEN; i > 16; i--) {
  164053. while (bits[i] > 0) {
  164054. j = i - 2; /* find length of new prefix to be used */
  164055. while (bits[j] == 0)
  164056. j--;
  164057. bits[i] -= 2; /* remove two symbols */
  164058. bits[i-1]++; /* one goes in this length */
  164059. bits[j+1] += 2; /* two new symbols in this length */
  164060. bits[j]--; /* symbol of this length is now a prefix */
  164061. }
  164062. }
  164063. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164064. while (bits[i] == 0) /* find largest codelength still in use */
  164065. i--;
  164066. bits[i]--;
  164067. /* Return final symbol counts (only for lengths 0..16) */
  164068. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164069. /* Return a list of the symbols sorted by code length */
  164070. /* It's not real clear to me why we don't need to consider the codelength
  164071. * changes made above, but the JPEG spec seems to think this works.
  164072. */
  164073. p = 0;
  164074. for (i = 1; i <= MAX_CLEN; i++) {
  164075. for (j = 0; j <= 255; j++) {
  164076. if (codesize[j] == i) {
  164077. htbl->huffval[p] = (UINT8) j;
  164078. p++;
  164079. }
  164080. }
  164081. }
  164082. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164083. htbl->sent_table = FALSE;
  164084. }
  164085. /*
  164086. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164087. */
  164088. METHODDEF(void)
  164089. finish_pass_gather (j_compress_ptr cinfo)
  164090. {
  164091. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164092. int ci, dctbl, actbl;
  164093. jpeg_component_info * compptr;
  164094. JHUFF_TBL **htblptr;
  164095. boolean did_dc[NUM_HUFF_TBLS];
  164096. boolean did_ac[NUM_HUFF_TBLS];
  164097. /* It's important not to apply jpeg_gen_optimal_table more than once
  164098. * per table, because it clobbers the input frequency counts!
  164099. */
  164100. MEMZERO(did_dc, SIZEOF(did_dc));
  164101. MEMZERO(did_ac, SIZEOF(did_ac));
  164102. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164103. compptr = cinfo->cur_comp_info[ci];
  164104. dctbl = compptr->dc_tbl_no;
  164105. actbl = compptr->ac_tbl_no;
  164106. if (! did_dc[dctbl]) {
  164107. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164108. if (*htblptr == NULL)
  164109. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164110. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164111. did_dc[dctbl] = TRUE;
  164112. }
  164113. if (! did_ac[actbl]) {
  164114. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164115. if (*htblptr == NULL)
  164116. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164117. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164118. did_ac[actbl] = TRUE;
  164119. }
  164120. }
  164121. }
  164122. #endif /* ENTROPY_OPT_SUPPORTED */
  164123. /*
  164124. * Module initialization routine for Huffman entropy encoding.
  164125. */
  164126. GLOBAL(void)
  164127. jinit_huff_encoder (j_compress_ptr cinfo)
  164128. {
  164129. huff_entropy_ptr entropy;
  164130. int i;
  164131. entropy = (huff_entropy_ptr)
  164132. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164133. SIZEOF(huff_entropy_encoder));
  164134. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164135. entropy->pub.start_pass = start_pass_huff;
  164136. /* Mark tables unallocated */
  164137. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164138. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164139. #ifdef ENTROPY_OPT_SUPPORTED
  164140. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164141. #endif
  164142. }
  164143. }
  164144. /*** End of inlined file: jchuff.c ***/
  164145. #undef emit_byte
  164146. /*** Start of inlined file: jcinit.c ***/
  164147. #define JPEG_INTERNALS
  164148. /*
  164149. * Master selection of compression modules.
  164150. * This is done once at the start of processing an image. We determine
  164151. * which modules will be used and give them appropriate initialization calls.
  164152. */
  164153. GLOBAL(void)
  164154. jinit_compress_master (j_compress_ptr cinfo)
  164155. {
  164156. /* Initialize master control (includes parameter checking/processing) */
  164157. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164158. /* Preprocessing */
  164159. if (! cinfo->raw_data_in) {
  164160. jinit_color_converter(cinfo);
  164161. jinit_downsampler(cinfo);
  164162. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164163. }
  164164. /* Forward DCT */
  164165. jinit_forward_dct(cinfo);
  164166. /* Entropy encoding: either Huffman or arithmetic coding. */
  164167. if (cinfo->arith_code) {
  164168. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164169. } else {
  164170. if (cinfo->progressive_mode) {
  164171. #ifdef C_PROGRESSIVE_SUPPORTED
  164172. jinit_phuff_encoder(cinfo);
  164173. #else
  164174. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164175. #endif
  164176. } else
  164177. jinit_huff_encoder(cinfo);
  164178. }
  164179. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164180. jinit_c_coef_controller(cinfo,
  164181. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164182. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164183. jinit_marker_writer(cinfo);
  164184. /* We can now tell the memory manager to allocate virtual arrays. */
  164185. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164186. /* Write the datastream header (SOI) immediately.
  164187. * Frame and scan headers are postponed till later.
  164188. * This lets application insert special markers after the SOI.
  164189. */
  164190. (*cinfo->marker->write_file_header) (cinfo);
  164191. }
  164192. /*** End of inlined file: jcinit.c ***/
  164193. /*** Start of inlined file: jcmainct.c ***/
  164194. #define JPEG_INTERNALS
  164195. /* Note: currently, there is no operating mode in which a full-image buffer
  164196. * is needed at this step. If there were, that mode could not be used with
  164197. * "raw data" input, since this module is bypassed in that case. However,
  164198. * we've left the code here for possible use in special applications.
  164199. */
  164200. #undef FULL_MAIN_BUFFER_SUPPORTED
  164201. /* Private buffer controller object */
  164202. typedef struct {
  164203. struct jpeg_c_main_controller pub; /* public fields */
  164204. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164205. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164206. boolean suspended; /* remember if we suspended output */
  164207. J_BUF_MODE pass_mode; /* current operating mode */
  164208. /* If using just a strip buffer, this points to the entire set of buffers
  164209. * (we allocate one for each component). In the full-image case, this
  164210. * points to the currently accessible strips of the virtual arrays.
  164211. */
  164212. JSAMPARRAY buffer[MAX_COMPONENTS];
  164213. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164214. /* If using full-image storage, this array holds pointers to virtual-array
  164215. * control blocks for each component. Unused if not full-image storage.
  164216. */
  164217. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164218. #endif
  164219. } my_main_controller;
  164220. typedef my_main_controller * my_main_ptr;
  164221. /* Forward declarations */
  164222. METHODDEF(void) process_data_simple_main
  164223. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164224. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164225. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164226. METHODDEF(void) process_data_buffer_main
  164227. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164228. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164229. #endif
  164230. /*
  164231. * Initialize for a processing pass.
  164232. */
  164233. METHODDEF(void)
  164234. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  164235. {
  164236. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164237. /* Do nothing in raw-data mode. */
  164238. if (cinfo->raw_data_in)
  164239. return;
  164240. main_->cur_iMCU_row = 0; /* initialize counters */
  164241. main_->rowgroup_ctr = 0;
  164242. main_->suspended = FALSE;
  164243. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  164244. switch (pass_mode) {
  164245. case JBUF_PASS_THRU:
  164246. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164247. if (main_->whole_image[0] != NULL)
  164248. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164249. #endif
  164250. main_->pub.process_data = process_data_simple_main;
  164251. break;
  164252. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164253. case JBUF_SAVE_SOURCE:
  164254. case JBUF_CRANK_DEST:
  164255. case JBUF_SAVE_AND_PASS:
  164256. if (main_->whole_image[0] == NULL)
  164257. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164258. main_->pub.process_data = process_data_buffer_main;
  164259. break;
  164260. #endif
  164261. default:
  164262. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164263. break;
  164264. }
  164265. }
  164266. /*
  164267. * Process some data.
  164268. * This routine handles the simple pass-through mode,
  164269. * where we have only a strip buffer.
  164270. */
  164271. METHODDEF(void)
  164272. process_data_simple_main (j_compress_ptr cinfo,
  164273. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164274. JDIMENSION in_rows_avail)
  164275. {
  164276. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  164277. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164278. /* Read input data if we haven't filled the main buffer yet */
  164279. if (main_->rowgroup_ctr < DCTSIZE)
  164280. (*cinfo->prep->pre_process_data) (cinfo,
  164281. input_buf, in_row_ctr, in_rows_avail,
  164282. main_->buffer, &main_->rowgroup_ctr,
  164283. (JDIMENSION) DCTSIZE);
  164284. /* If we don't have a full iMCU row buffered, return to application for
  164285. * more data. Note that preprocessor will always pad to fill the iMCU row
  164286. * at the bottom of the image.
  164287. */
  164288. if (main_->rowgroup_ctr != DCTSIZE)
  164289. return;
  164290. /* Send the completed row to the compressor */
  164291. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  164292. /* If compressor did not consume the whole row, then we must need to
  164293. * suspend processing and return to the application. In this situation
  164294. * we pretend we didn't yet consume the last input row; otherwise, if
  164295. * it happened to be the last row of the image, the application would
  164296. * think we were done.
  164297. */
  164298. if (! main_->suspended) {
  164299. (*in_row_ctr)--;
  164300. main_->suspended = TRUE;
  164301. }
  164302. return;
  164303. }
  164304. /* We did finish the row. Undo our little suspension hack if a previous
  164305. * call suspended; then mark the main buffer empty.
  164306. */
  164307. if (main_->suspended) {
  164308. (*in_row_ctr)++;
  164309. main_->suspended = FALSE;
  164310. }
  164311. main_->rowgroup_ctr = 0;
  164312. main_->cur_iMCU_row++;
  164313. }
  164314. }
  164315. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164316. /*
  164317. * Process some data.
  164318. * This routine handles all of the modes that use a full-size buffer.
  164319. */
  164320. METHODDEF(void)
  164321. process_data_buffer_main (j_compress_ptr cinfo,
  164322. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  164323. JDIMENSION in_rows_avail)
  164324. {
  164325. my_main_ptr main = (my_main_ptr) cinfo->main;
  164326. int ci;
  164327. jpeg_component_info *compptr;
  164328. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  164329. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  164330. /* Realign the virtual buffers if at the start of an iMCU row. */
  164331. if (main->rowgroup_ctr == 0) {
  164332. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164333. ci++, compptr++) {
  164334. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  164335. ((j_common_ptr) cinfo, main->whole_image[ci],
  164336. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  164337. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  164338. }
  164339. /* In a read pass, pretend we just read some source data. */
  164340. if (! writing) {
  164341. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  164342. main->rowgroup_ctr = DCTSIZE;
  164343. }
  164344. }
  164345. /* If a write pass, read input data until the current iMCU row is full. */
  164346. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  164347. if (writing) {
  164348. (*cinfo->prep->pre_process_data) (cinfo,
  164349. input_buf, in_row_ctr, in_rows_avail,
  164350. main->buffer, &main->rowgroup_ctr,
  164351. (JDIMENSION) DCTSIZE);
  164352. /* Return to application if we need more data to fill the iMCU row. */
  164353. if (main->rowgroup_ctr < DCTSIZE)
  164354. return;
  164355. }
  164356. /* Emit data, unless this is a sink-only pass. */
  164357. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  164358. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  164359. /* If compressor did not consume the whole row, then we must need to
  164360. * suspend processing and return to the application. In this situation
  164361. * we pretend we didn't yet consume the last input row; otherwise, if
  164362. * it happened to be the last row of the image, the application would
  164363. * think we were done.
  164364. */
  164365. if (! main->suspended) {
  164366. (*in_row_ctr)--;
  164367. main->suspended = TRUE;
  164368. }
  164369. return;
  164370. }
  164371. /* We did finish the row. Undo our little suspension hack if a previous
  164372. * call suspended; then mark the main buffer empty.
  164373. */
  164374. if (main->suspended) {
  164375. (*in_row_ctr)++;
  164376. main->suspended = FALSE;
  164377. }
  164378. }
  164379. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  164380. main->rowgroup_ctr = 0;
  164381. main->cur_iMCU_row++;
  164382. }
  164383. }
  164384. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  164385. /*
  164386. * Initialize main buffer controller.
  164387. */
  164388. GLOBAL(void)
  164389. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  164390. {
  164391. my_main_ptr main_;
  164392. int ci;
  164393. jpeg_component_info *compptr;
  164394. main_ = (my_main_ptr)
  164395. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164396. SIZEOF(my_main_controller));
  164397. cinfo->main = (struct jpeg_c_main_controller *) main_;
  164398. main_->pub.start_pass = start_pass_main;
  164399. /* We don't need to create a buffer in raw-data mode. */
  164400. if (cinfo->raw_data_in)
  164401. return;
  164402. /* Create the buffer. It holds downsampled data, so each component
  164403. * may be of a different size.
  164404. */
  164405. if (need_full_buffer) {
  164406. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164407. /* Allocate a full-image virtual array for each component */
  164408. /* Note we pad the bottom to a multiple of the iMCU height */
  164409. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164410. ci++, compptr++) {
  164411. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  164412. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  164413. compptr->width_in_blocks * DCTSIZE,
  164414. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  164415. (long) compptr->v_samp_factor) * DCTSIZE,
  164416. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164417. }
  164418. #else
  164419. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  164420. #endif
  164421. } else {
  164422. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164423. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  164424. #endif
  164425. /* Allocate a strip buffer for each component */
  164426. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164427. ci++, compptr++) {
  164428. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  164429. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164430. compptr->width_in_blocks * DCTSIZE,
  164431. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  164432. }
  164433. }
  164434. }
  164435. /*** End of inlined file: jcmainct.c ***/
  164436. /*** Start of inlined file: jcmarker.c ***/
  164437. #define JPEG_INTERNALS
  164438. /* Private state */
  164439. typedef struct {
  164440. struct jpeg_marker_writer pub; /* public fields */
  164441. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  164442. } my_marker_writer;
  164443. typedef my_marker_writer * my_marker_ptr;
  164444. /*
  164445. * Basic output routines.
  164446. *
  164447. * Note that we do not support suspension while writing a marker.
  164448. * Therefore, an application using suspension must ensure that there is
  164449. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  164450. * calling jpeg_start_compress, and enough space to write the trailing EOI
  164451. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  164452. * modes are not supported at all with suspension, so those two are the only
  164453. * points where markers will be written.
  164454. */
  164455. LOCAL(void)
  164456. emit_byte (j_compress_ptr cinfo, int val)
  164457. /* Emit a byte */
  164458. {
  164459. struct jpeg_destination_mgr * dest = cinfo->dest;
  164460. *(dest->next_output_byte)++ = (JOCTET) val;
  164461. if (--dest->free_in_buffer == 0) {
  164462. if (! (*dest->empty_output_buffer) (cinfo))
  164463. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164464. }
  164465. }
  164466. LOCAL(void)
  164467. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  164468. /* Emit a marker code */
  164469. {
  164470. emit_byte(cinfo, 0xFF);
  164471. emit_byte(cinfo, (int) mark);
  164472. }
  164473. LOCAL(void)
  164474. emit_2bytes (j_compress_ptr cinfo, int value)
  164475. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  164476. {
  164477. emit_byte(cinfo, (value >> 8) & 0xFF);
  164478. emit_byte(cinfo, value & 0xFF);
  164479. }
  164480. /*
  164481. * Routines to write specific marker types.
  164482. */
  164483. LOCAL(int)
  164484. emit_dqt (j_compress_ptr cinfo, int index)
  164485. /* Emit a DQT marker */
  164486. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  164487. {
  164488. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  164489. int prec;
  164490. int i;
  164491. if (qtbl == NULL)
  164492. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  164493. prec = 0;
  164494. for (i = 0; i < DCTSIZE2; i++) {
  164495. if (qtbl->quantval[i] > 255)
  164496. prec = 1;
  164497. }
  164498. if (! qtbl->sent_table) {
  164499. emit_marker(cinfo, M_DQT);
  164500. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  164501. emit_byte(cinfo, index + (prec<<4));
  164502. for (i = 0; i < DCTSIZE2; i++) {
  164503. /* The table entries must be emitted in zigzag order. */
  164504. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  164505. if (prec)
  164506. emit_byte(cinfo, (int) (qval >> 8));
  164507. emit_byte(cinfo, (int) (qval & 0xFF));
  164508. }
  164509. qtbl->sent_table = TRUE;
  164510. }
  164511. return prec;
  164512. }
  164513. LOCAL(void)
  164514. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  164515. /* Emit a DHT marker */
  164516. {
  164517. JHUFF_TBL * htbl;
  164518. int length, i;
  164519. if (is_ac) {
  164520. htbl = cinfo->ac_huff_tbl_ptrs[index];
  164521. index += 0x10; /* output index has AC bit set */
  164522. } else {
  164523. htbl = cinfo->dc_huff_tbl_ptrs[index];
  164524. }
  164525. if (htbl == NULL)
  164526. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  164527. if (! htbl->sent_table) {
  164528. emit_marker(cinfo, M_DHT);
  164529. length = 0;
  164530. for (i = 1; i <= 16; i++)
  164531. length += htbl->bits[i];
  164532. emit_2bytes(cinfo, length + 2 + 1 + 16);
  164533. emit_byte(cinfo, index);
  164534. for (i = 1; i <= 16; i++)
  164535. emit_byte(cinfo, htbl->bits[i]);
  164536. for (i = 0; i < length; i++)
  164537. emit_byte(cinfo, htbl->huffval[i]);
  164538. htbl->sent_table = TRUE;
  164539. }
  164540. }
  164541. LOCAL(void)
  164542. emit_dac (j_compress_ptr)
  164543. /* Emit a DAC marker */
  164544. /* Since the useful info is so small, we want to emit all the tables in */
  164545. /* one DAC marker. Therefore this routine does its own scan of the table. */
  164546. {
  164547. #ifdef C_ARITH_CODING_SUPPORTED
  164548. char dc_in_use[NUM_ARITH_TBLS];
  164549. char ac_in_use[NUM_ARITH_TBLS];
  164550. int length, i;
  164551. jpeg_component_info *compptr;
  164552. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164553. dc_in_use[i] = ac_in_use[i] = 0;
  164554. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164555. compptr = cinfo->cur_comp_info[i];
  164556. dc_in_use[compptr->dc_tbl_no] = 1;
  164557. ac_in_use[compptr->ac_tbl_no] = 1;
  164558. }
  164559. length = 0;
  164560. for (i = 0; i < NUM_ARITH_TBLS; i++)
  164561. length += dc_in_use[i] + ac_in_use[i];
  164562. emit_marker(cinfo, M_DAC);
  164563. emit_2bytes(cinfo, length*2 + 2);
  164564. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  164565. if (dc_in_use[i]) {
  164566. emit_byte(cinfo, i);
  164567. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  164568. }
  164569. if (ac_in_use[i]) {
  164570. emit_byte(cinfo, i + 0x10);
  164571. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  164572. }
  164573. }
  164574. #endif /* C_ARITH_CODING_SUPPORTED */
  164575. }
  164576. LOCAL(void)
  164577. emit_dri (j_compress_ptr cinfo)
  164578. /* Emit a DRI marker */
  164579. {
  164580. emit_marker(cinfo, M_DRI);
  164581. emit_2bytes(cinfo, 4); /* fixed length */
  164582. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  164583. }
  164584. LOCAL(void)
  164585. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  164586. /* Emit a SOF marker */
  164587. {
  164588. int ci;
  164589. jpeg_component_info *compptr;
  164590. emit_marker(cinfo, code);
  164591. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  164592. /* Make sure image isn't bigger than SOF field can handle */
  164593. if ((long) cinfo->image_height > 65535L ||
  164594. (long) cinfo->image_width > 65535L)
  164595. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  164596. emit_byte(cinfo, cinfo->data_precision);
  164597. emit_2bytes(cinfo, (int) cinfo->image_height);
  164598. emit_2bytes(cinfo, (int) cinfo->image_width);
  164599. emit_byte(cinfo, cinfo->num_components);
  164600. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164601. ci++, compptr++) {
  164602. emit_byte(cinfo, compptr->component_id);
  164603. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  164604. emit_byte(cinfo, compptr->quant_tbl_no);
  164605. }
  164606. }
  164607. LOCAL(void)
  164608. emit_sos (j_compress_ptr cinfo)
  164609. /* Emit a SOS marker */
  164610. {
  164611. int i, td, ta;
  164612. jpeg_component_info *compptr;
  164613. emit_marker(cinfo, M_SOS);
  164614. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  164615. emit_byte(cinfo, cinfo->comps_in_scan);
  164616. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164617. compptr = cinfo->cur_comp_info[i];
  164618. emit_byte(cinfo, compptr->component_id);
  164619. td = compptr->dc_tbl_no;
  164620. ta = compptr->ac_tbl_no;
  164621. if (cinfo->progressive_mode) {
  164622. /* Progressive mode: only DC or only AC tables are used in one scan;
  164623. * furthermore, Huffman coding of DC refinement uses no table at all.
  164624. * We emit 0 for unused field(s); this is recommended by the P&M text
  164625. * but does not seem to be specified in the standard.
  164626. */
  164627. if (cinfo->Ss == 0) {
  164628. ta = 0; /* DC scan */
  164629. if (cinfo->Ah != 0 && !cinfo->arith_code)
  164630. td = 0; /* no DC table either */
  164631. } else {
  164632. td = 0; /* AC scan */
  164633. }
  164634. }
  164635. emit_byte(cinfo, (td << 4) + ta);
  164636. }
  164637. emit_byte(cinfo, cinfo->Ss);
  164638. emit_byte(cinfo, cinfo->Se);
  164639. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  164640. }
  164641. LOCAL(void)
  164642. emit_jfif_app0 (j_compress_ptr cinfo)
  164643. /* Emit a JFIF-compliant APP0 marker */
  164644. {
  164645. /*
  164646. * Length of APP0 block (2 bytes)
  164647. * Block ID (4 bytes - ASCII "JFIF")
  164648. * Zero byte (1 byte to terminate the ID string)
  164649. * Version Major, Minor (2 bytes - major first)
  164650. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  164651. * Xdpu (2 bytes - dots per unit horizontal)
  164652. * Ydpu (2 bytes - dots per unit vertical)
  164653. * Thumbnail X size (1 byte)
  164654. * Thumbnail Y size (1 byte)
  164655. */
  164656. emit_marker(cinfo, M_APP0);
  164657. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  164658. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  164659. emit_byte(cinfo, 0x46);
  164660. emit_byte(cinfo, 0x49);
  164661. emit_byte(cinfo, 0x46);
  164662. emit_byte(cinfo, 0);
  164663. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  164664. emit_byte(cinfo, cinfo->JFIF_minor_version);
  164665. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  164666. emit_2bytes(cinfo, (int) cinfo->X_density);
  164667. emit_2bytes(cinfo, (int) cinfo->Y_density);
  164668. emit_byte(cinfo, 0); /* No thumbnail image */
  164669. emit_byte(cinfo, 0);
  164670. }
  164671. LOCAL(void)
  164672. emit_adobe_app14 (j_compress_ptr cinfo)
  164673. /* Emit an Adobe APP14 marker */
  164674. {
  164675. /*
  164676. * Length of APP14 block (2 bytes)
  164677. * Block ID (5 bytes - ASCII "Adobe")
  164678. * Version Number (2 bytes - currently 100)
  164679. * Flags0 (2 bytes - currently 0)
  164680. * Flags1 (2 bytes - currently 0)
  164681. * Color transform (1 byte)
  164682. *
  164683. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  164684. * now in circulation seem to use Version = 100, so that's what we write.
  164685. *
  164686. * We write the color transform byte as 1 if the JPEG color space is
  164687. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  164688. * whether the encoder performed a transformation, which is pretty useless.
  164689. */
  164690. emit_marker(cinfo, M_APP14);
  164691. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  164692. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  164693. emit_byte(cinfo, 0x64);
  164694. emit_byte(cinfo, 0x6F);
  164695. emit_byte(cinfo, 0x62);
  164696. emit_byte(cinfo, 0x65);
  164697. emit_2bytes(cinfo, 100); /* Version */
  164698. emit_2bytes(cinfo, 0); /* Flags0 */
  164699. emit_2bytes(cinfo, 0); /* Flags1 */
  164700. switch (cinfo->jpeg_color_space) {
  164701. case JCS_YCbCr:
  164702. emit_byte(cinfo, 1); /* Color transform = 1 */
  164703. break;
  164704. case JCS_YCCK:
  164705. emit_byte(cinfo, 2); /* Color transform = 2 */
  164706. break;
  164707. default:
  164708. emit_byte(cinfo, 0); /* Color transform = 0 */
  164709. break;
  164710. }
  164711. }
  164712. /*
  164713. * These routines allow writing an arbitrary marker with parameters.
  164714. * The only intended use is to emit COM or APPn markers after calling
  164715. * write_file_header and before calling write_frame_header.
  164716. * Other uses are not guaranteed to produce desirable results.
  164717. * Counting the parameter bytes properly is the caller's responsibility.
  164718. */
  164719. METHODDEF(void)
  164720. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  164721. /* Emit an arbitrary marker header */
  164722. {
  164723. if (datalen > (unsigned int) 65533) /* safety check */
  164724. ERREXIT(cinfo, JERR_BAD_LENGTH);
  164725. emit_marker(cinfo, (JPEG_MARKER) marker);
  164726. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  164727. }
  164728. METHODDEF(void)
  164729. write_marker_byte (j_compress_ptr cinfo, int val)
  164730. /* Emit one byte of marker parameters following write_marker_header */
  164731. {
  164732. emit_byte(cinfo, val);
  164733. }
  164734. /*
  164735. * Write datastream header.
  164736. * This consists of an SOI and optional APPn markers.
  164737. * We recommend use of the JFIF marker, but not the Adobe marker,
  164738. * when using YCbCr or grayscale data. The JFIF marker should NOT
  164739. * be used for any other JPEG colorspace. The Adobe marker is helpful
  164740. * to distinguish RGB, CMYK, and YCCK colorspaces.
  164741. * Note that an application can write additional header markers after
  164742. * jpeg_start_compress returns.
  164743. */
  164744. METHODDEF(void)
  164745. write_file_header (j_compress_ptr cinfo)
  164746. {
  164747. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164748. emit_marker(cinfo, M_SOI); /* first the SOI */
  164749. /* SOI is defined to reset restart interval to 0 */
  164750. marker->last_restart_interval = 0;
  164751. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  164752. emit_jfif_app0(cinfo);
  164753. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  164754. emit_adobe_app14(cinfo);
  164755. }
  164756. /*
  164757. * Write frame header.
  164758. * This consists of DQT and SOFn markers.
  164759. * Note that we do not emit the SOF until we have emitted the DQT(s).
  164760. * This avoids compatibility problems with incorrect implementations that
  164761. * try to error-check the quant table numbers as soon as they see the SOF.
  164762. */
  164763. METHODDEF(void)
  164764. write_frame_header (j_compress_ptr cinfo)
  164765. {
  164766. int ci, prec;
  164767. boolean is_baseline;
  164768. jpeg_component_info *compptr;
  164769. /* Emit DQT for each quantization table.
  164770. * Note that emit_dqt() suppresses any duplicate tables.
  164771. */
  164772. prec = 0;
  164773. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164774. ci++, compptr++) {
  164775. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  164776. }
  164777. /* now prec is nonzero iff there are any 16-bit quant tables. */
  164778. /* Check for a non-baseline specification.
  164779. * Note we assume that Huffman table numbers won't be changed later.
  164780. */
  164781. if (cinfo->arith_code || cinfo->progressive_mode ||
  164782. cinfo->data_precision != 8) {
  164783. is_baseline = FALSE;
  164784. } else {
  164785. is_baseline = TRUE;
  164786. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164787. ci++, compptr++) {
  164788. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  164789. is_baseline = FALSE;
  164790. }
  164791. if (prec && is_baseline) {
  164792. is_baseline = FALSE;
  164793. /* If it's baseline except for quantizer size, warn the user */
  164794. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  164795. }
  164796. }
  164797. /* Emit the proper SOF marker */
  164798. if (cinfo->arith_code) {
  164799. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  164800. } else {
  164801. if (cinfo->progressive_mode)
  164802. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  164803. else if (is_baseline)
  164804. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  164805. else
  164806. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  164807. }
  164808. }
  164809. /*
  164810. * Write scan header.
  164811. * This consists of DHT or DAC markers, optional DRI, and SOS.
  164812. * Compressed data will be written following the SOS.
  164813. */
  164814. METHODDEF(void)
  164815. write_scan_header (j_compress_ptr cinfo)
  164816. {
  164817. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  164818. int i;
  164819. jpeg_component_info *compptr;
  164820. if (cinfo->arith_code) {
  164821. /* Emit arith conditioning info. We may have some duplication
  164822. * if the file has multiple scans, but it's so small it's hardly
  164823. * worth worrying about.
  164824. */
  164825. emit_dac(cinfo);
  164826. } else {
  164827. /* Emit Huffman tables.
  164828. * Note that emit_dht() suppresses any duplicate tables.
  164829. */
  164830. for (i = 0; i < cinfo->comps_in_scan; i++) {
  164831. compptr = cinfo->cur_comp_info[i];
  164832. if (cinfo->progressive_mode) {
  164833. /* Progressive mode: only DC or only AC tables are used in one scan */
  164834. if (cinfo->Ss == 0) {
  164835. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  164836. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164837. } else {
  164838. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164839. }
  164840. } else {
  164841. /* Sequential mode: need both DC and AC tables */
  164842. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  164843. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  164844. }
  164845. }
  164846. }
  164847. /* Emit DRI if required --- note that DRI value could change for each scan.
  164848. * We avoid wasting space with unnecessary DRIs, however.
  164849. */
  164850. if (cinfo->restart_interval != marker->last_restart_interval) {
  164851. emit_dri(cinfo);
  164852. marker->last_restart_interval = cinfo->restart_interval;
  164853. }
  164854. emit_sos(cinfo);
  164855. }
  164856. /*
  164857. * Write datastream trailer.
  164858. */
  164859. METHODDEF(void)
  164860. write_file_trailer (j_compress_ptr cinfo)
  164861. {
  164862. emit_marker(cinfo, M_EOI);
  164863. }
  164864. /*
  164865. * Write an abbreviated table-specification datastream.
  164866. * This consists of SOI, DQT and DHT tables, and EOI.
  164867. * Any table that is defined and not marked sent_table = TRUE will be
  164868. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  164869. */
  164870. METHODDEF(void)
  164871. write_tables_only (j_compress_ptr cinfo)
  164872. {
  164873. int i;
  164874. emit_marker(cinfo, M_SOI);
  164875. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164876. if (cinfo->quant_tbl_ptrs[i] != NULL)
  164877. (void) emit_dqt(cinfo, i);
  164878. }
  164879. if (! cinfo->arith_code) {
  164880. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164881. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  164882. emit_dht(cinfo, i, FALSE);
  164883. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  164884. emit_dht(cinfo, i, TRUE);
  164885. }
  164886. }
  164887. emit_marker(cinfo, M_EOI);
  164888. }
  164889. /*
  164890. * Initialize the marker writer module.
  164891. */
  164892. GLOBAL(void)
  164893. jinit_marker_writer (j_compress_ptr cinfo)
  164894. {
  164895. my_marker_ptr marker;
  164896. /* Create the subobject */
  164897. marker = (my_marker_ptr)
  164898. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164899. SIZEOF(my_marker_writer));
  164900. cinfo->marker = (struct jpeg_marker_writer *) marker;
  164901. /* Initialize method pointers */
  164902. marker->pub.write_file_header = write_file_header;
  164903. marker->pub.write_frame_header = write_frame_header;
  164904. marker->pub.write_scan_header = write_scan_header;
  164905. marker->pub.write_file_trailer = write_file_trailer;
  164906. marker->pub.write_tables_only = write_tables_only;
  164907. marker->pub.write_marker_header = write_marker_header;
  164908. marker->pub.write_marker_byte = write_marker_byte;
  164909. /* Initialize private state */
  164910. marker->last_restart_interval = 0;
  164911. }
  164912. /*** End of inlined file: jcmarker.c ***/
  164913. /*** Start of inlined file: jcmaster.c ***/
  164914. #define JPEG_INTERNALS
  164915. /* Private state */
  164916. typedef enum {
  164917. main_pass, /* input data, also do first output step */
  164918. huff_opt_pass, /* Huffman code optimization pass */
  164919. output_pass /* data output pass */
  164920. } c_pass_type;
  164921. typedef struct {
  164922. struct jpeg_comp_master pub; /* public fields */
  164923. c_pass_type pass_type; /* the type of the current pass */
  164924. int pass_number; /* # of passes completed */
  164925. int total_passes; /* total # of passes needed */
  164926. int scan_number; /* current index in scan_info[] */
  164927. } my_comp_master;
  164928. typedef my_comp_master * my_master_ptr;
  164929. /*
  164930. * Support routines that do various essential calculations.
  164931. */
  164932. LOCAL(void)
  164933. initial_setup (j_compress_ptr cinfo)
  164934. /* Do computations that are needed before master selection phase */
  164935. {
  164936. int ci;
  164937. jpeg_component_info *compptr;
  164938. long samplesperrow;
  164939. JDIMENSION jd_samplesperrow;
  164940. /* Sanity check on image dimensions */
  164941. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  164942. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  164943. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  164944. /* Make sure image isn't bigger than I can handle */
  164945. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  164946. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  164947. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  164948. /* Width of an input scanline must be representable as JDIMENSION. */
  164949. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  164950. jd_samplesperrow = (JDIMENSION) samplesperrow;
  164951. if ((long) jd_samplesperrow != samplesperrow)
  164952. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  164953. /* For now, precision must match compiled-in value... */
  164954. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  164955. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  164956. /* Check that number of components won't exceed internal array sizes */
  164957. if (cinfo->num_components > MAX_COMPONENTS)
  164958. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  164959. MAX_COMPONENTS);
  164960. /* Compute maximum sampling factors; check factor validity */
  164961. cinfo->max_h_samp_factor = 1;
  164962. cinfo->max_v_samp_factor = 1;
  164963. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164964. ci++, compptr++) {
  164965. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  164966. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  164967. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  164968. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  164969. compptr->h_samp_factor);
  164970. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  164971. compptr->v_samp_factor);
  164972. }
  164973. /* Compute dimensions of components */
  164974. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  164975. ci++, compptr++) {
  164976. /* Fill in the correct component_index value; don't rely on application */
  164977. compptr->component_index = ci;
  164978. /* For compression, we never do DCT scaling. */
  164979. compptr->DCT_scaled_size = DCTSIZE;
  164980. /* Size in DCT blocks */
  164981. compptr->width_in_blocks = (JDIMENSION)
  164982. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164983. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  164984. compptr->height_in_blocks = (JDIMENSION)
  164985. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164986. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  164987. /* Size in samples */
  164988. compptr->downsampled_width = (JDIMENSION)
  164989. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  164990. (long) cinfo->max_h_samp_factor);
  164991. compptr->downsampled_height = (JDIMENSION)
  164992. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  164993. (long) cinfo->max_v_samp_factor);
  164994. /* Mark component needed (this flag isn't actually used for compression) */
  164995. compptr->component_needed = TRUE;
  164996. }
  164997. /* Compute number of fully interleaved MCU rows (number of times that
  164998. * main controller will call coefficient controller).
  164999. */
  165000. cinfo->total_iMCU_rows = (JDIMENSION)
  165001. jdiv_round_up((long) cinfo->image_height,
  165002. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165003. }
  165004. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165005. LOCAL(void)
  165006. validate_script (j_compress_ptr cinfo)
  165007. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  165008. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  165009. */
  165010. {
  165011. const jpeg_scan_info * scanptr;
  165012. int scanno, ncomps, ci, coefi, thisi;
  165013. int Ss, Se, Ah, Al;
  165014. boolean component_sent[MAX_COMPONENTS];
  165015. #ifdef C_PROGRESSIVE_SUPPORTED
  165016. int * last_bitpos_ptr;
  165017. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  165018. /* -1 until that coefficient has been seen; then last Al for it */
  165019. #endif
  165020. if (cinfo->num_scans <= 0)
  165021. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  165022. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  165023. * for progressive JPEG, no scan can have this.
  165024. */
  165025. scanptr = cinfo->scan_info;
  165026. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  165027. #ifdef C_PROGRESSIVE_SUPPORTED
  165028. cinfo->progressive_mode = TRUE;
  165029. last_bitpos_ptr = & last_bitpos[0][0];
  165030. for (ci = 0; ci < cinfo->num_components; ci++)
  165031. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  165032. *last_bitpos_ptr++ = -1;
  165033. #else
  165034. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165035. #endif
  165036. } else {
  165037. cinfo->progressive_mode = FALSE;
  165038. for (ci = 0; ci < cinfo->num_components; ci++)
  165039. component_sent[ci] = FALSE;
  165040. }
  165041. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165042. /* Validate component indexes */
  165043. ncomps = scanptr->comps_in_scan;
  165044. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165045. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165046. for (ci = 0; ci < ncomps; ci++) {
  165047. thisi = scanptr->component_index[ci];
  165048. if (thisi < 0 || thisi >= cinfo->num_components)
  165049. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165050. /* Components must appear in SOF order within each scan */
  165051. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165052. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165053. }
  165054. /* Validate progression parameters */
  165055. Ss = scanptr->Ss;
  165056. Se = scanptr->Se;
  165057. Ah = scanptr->Ah;
  165058. Al = scanptr->Al;
  165059. if (cinfo->progressive_mode) {
  165060. #ifdef C_PROGRESSIVE_SUPPORTED
  165061. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165062. * seems wrong: the upper bound ought to depend on data precision.
  165063. * Perhaps they really meant 0..N+1 for N-bit precision.
  165064. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165065. * out-of-range reconstructed DC values during the first DC scan,
  165066. * which might cause problems for some decoders.
  165067. */
  165068. #if BITS_IN_JSAMPLE == 8
  165069. #define MAX_AH_AL 10
  165070. #else
  165071. #define MAX_AH_AL 13
  165072. #endif
  165073. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165074. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165075. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165076. if (Ss == 0) {
  165077. if (Se != 0) /* DC and AC together not OK */
  165078. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165079. } else {
  165080. if (ncomps != 1) /* AC scans must be for only one component */
  165081. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165082. }
  165083. for (ci = 0; ci < ncomps; ci++) {
  165084. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165085. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165086. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165087. for (coefi = Ss; coefi <= Se; coefi++) {
  165088. if (last_bitpos_ptr[coefi] < 0) {
  165089. /* first scan of this coefficient */
  165090. if (Ah != 0)
  165091. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165092. } else {
  165093. /* not first scan */
  165094. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165095. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165096. }
  165097. last_bitpos_ptr[coefi] = Al;
  165098. }
  165099. }
  165100. #endif
  165101. } else {
  165102. /* For sequential JPEG, all progression parameters must be these: */
  165103. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165104. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165105. /* Make sure components are not sent twice */
  165106. for (ci = 0; ci < ncomps; ci++) {
  165107. thisi = scanptr->component_index[ci];
  165108. if (component_sent[thisi])
  165109. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165110. component_sent[thisi] = TRUE;
  165111. }
  165112. }
  165113. }
  165114. /* Now verify that everything got sent. */
  165115. if (cinfo->progressive_mode) {
  165116. #ifdef C_PROGRESSIVE_SUPPORTED
  165117. /* For progressive mode, we only check that at least some DC data
  165118. * got sent for each component; the spec does not require that all bits
  165119. * of all coefficients be transmitted. Would it be wiser to enforce
  165120. * transmission of all coefficient bits??
  165121. */
  165122. for (ci = 0; ci < cinfo->num_components; ci++) {
  165123. if (last_bitpos[ci][0] < 0)
  165124. ERREXIT(cinfo, JERR_MISSING_DATA);
  165125. }
  165126. #endif
  165127. } else {
  165128. for (ci = 0; ci < cinfo->num_components; ci++) {
  165129. if (! component_sent[ci])
  165130. ERREXIT(cinfo, JERR_MISSING_DATA);
  165131. }
  165132. }
  165133. }
  165134. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165135. LOCAL(void)
  165136. select_scan_parameters (j_compress_ptr cinfo)
  165137. /* Set up the scan parameters for the current scan */
  165138. {
  165139. int ci;
  165140. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165141. if (cinfo->scan_info != NULL) {
  165142. /* Prepare for current scan --- the script is already validated */
  165143. my_master_ptr master = (my_master_ptr) cinfo->master;
  165144. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165145. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165146. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165147. cinfo->cur_comp_info[ci] =
  165148. &cinfo->comp_info[scanptr->component_index[ci]];
  165149. }
  165150. cinfo->Ss = scanptr->Ss;
  165151. cinfo->Se = scanptr->Se;
  165152. cinfo->Ah = scanptr->Ah;
  165153. cinfo->Al = scanptr->Al;
  165154. }
  165155. else
  165156. #endif
  165157. {
  165158. /* Prepare for single sequential-JPEG scan containing all components */
  165159. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165160. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165161. MAX_COMPS_IN_SCAN);
  165162. cinfo->comps_in_scan = cinfo->num_components;
  165163. for (ci = 0; ci < cinfo->num_components; ci++) {
  165164. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165165. }
  165166. cinfo->Ss = 0;
  165167. cinfo->Se = DCTSIZE2-1;
  165168. cinfo->Ah = 0;
  165169. cinfo->Al = 0;
  165170. }
  165171. }
  165172. LOCAL(void)
  165173. per_scan_setup (j_compress_ptr cinfo)
  165174. /* Do computations that are needed before processing a JPEG scan */
  165175. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165176. {
  165177. int ci, mcublks, tmp;
  165178. jpeg_component_info *compptr;
  165179. if (cinfo->comps_in_scan == 1) {
  165180. /* Noninterleaved (single-component) scan */
  165181. compptr = cinfo->cur_comp_info[0];
  165182. /* Overall image size in MCUs */
  165183. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165184. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165185. /* For noninterleaved scan, always one block per MCU */
  165186. compptr->MCU_width = 1;
  165187. compptr->MCU_height = 1;
  165188. compptr->MCU_blocks = 1;
  165189. compptr->MCU_sample_width = DCTSIZE;
  165190. compptr->last_col_width = 1;
  165191. /* For noninterleaved scans, it is convenient to define last_row_height
  165192. * as the number of block rows present in the last iMCU row.
  165193. */
  165194. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165195. if (tmp == 0) tmp = compptr->v_samp_factor;
  165196. compptr->last_row_height = tmp;
  165197. /* Prepare array describing MCU composition */
  165198. cinfo->blocks_in_MCU = 1;
  165199. cinfo->MCU_membership[0] = 0;
  165200. } else {
  165201. /* Interleaved (multi-component) scan */
  165202. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165203. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165204. MAX_COMPS_IN_SCAN);
  165205. /* Overall image size in MCUs */
  165206. cinfo->MCUs_per_row = (JDIMENSION)
  165207. jdiv_round_up((long) cinfo->image_width,
  165208. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165209. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165210. jdiv_round_up((long) cinfo->image_height,
  165211. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165212. cinfo->blocks_in_MCU = 0;
  165213. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165214. compptr = cinfo->cur_comp_info[ci];
  165215. /* Sampling factors give # of blocks of component in each MCU */
  165216. compptr->MCU_width = compptr->h_samp_factor;
  165217. compptr->MCU_height = compptr->v_samp_factor;
  165218. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165219. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165220. /* Figure number of non-dummy blocks in last MCU column & row */
  165221. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165222. if (tmp == 0) tmp = compptr->MCU_width;
  165223. compptr->last_col_width = tmp;
  165224. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165225. if (tmp == 0) tmp = compptr->MCU_height;
  165226. compptr->last_row_height = tmp;
  165227. /* Prepare array describing MCU composition */
  165228. mcublks = compptr->MCU_blocks;
  165229. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  165230. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  165231. while (mcublks-- > 0) {
  165232. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  165233. }
  165234. }
  165235. }
  165236. /* Convert restart specified in rows to actual MCU count. */
  165237. /* Note that count must fit in 16 bits, so we provide limiting. */
  165238. if (cinfo->restart_in_rows > 0) {
  165239. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  165240. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  165241. }
  165242. }
  165243. /*
  165244. * Per-pass setup.
  165245. * This is called at the beginning of each pass. We determine which modules
  165246. * will be active during this pass and give them appropriate start_pass calls.
  165247. * We also set is_last_pass to indicate whether any more passes will be
  165248. * required.
  165249. */
  165250. METHODDEF(void)
  165251. prepare_for_pass (j_compress_ptr cinfo)
  165252. {
  165253. my_master_ptr master = (my_master_ptr) cinfo->master;
  165254. switch (master->pass_type) {
  165255. case main_pass:
  165256. /* Initial pass: will collect input data, and do either Huffman
  165257. * optimization or data output for the first scan.
  165258. */
  165259. select_scan_parameters(cinfo);
  165260. per_scan_setup(cinfo);
  165261. if (! cinfo->raw_data_in) {
  165262. (*cinfo->cconvert->start_pass) (cinfo);
  165263. (*cinfo->downsample->start_pass) (cinfo);
  165264. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  165265. }
  165266. (*cinfo->fdct->start_pass) (cinfo);
  165267. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  165268. (*cinfo->coef->start_pass) (cinfo,
  165269. (master->total_passes > 1 ?
  165270. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  165271. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  165272. if (cinfo->optimize_coding) {
  165273. /* No immediate data output; postpone writing frame/scan headers */
  165274. master->pub.call_pass_startup = FALSE;
  165275. } else {
  165276. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  165277. master->pub.call_pass_startup = TRUE;
  165278. }
  165279. break;
  165280. #ifdef ENTROPY_OPT_SUPPORTED
  165281. case huff_opt_pass:
  165282. /* Do Huffman optimization for a scan after the first one. */
  165283. select_scan_parameters(cinfo);
  165284. per_scan_setup(cinfo);
  165285. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  165286. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  165287. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165288. master->pub.call_pass_startup = FALSE;
  165289. break;
  165290. }
  165291. /* Special case: Huffman DC refinement scans need no Huffman table
  165292. * and therefore we can skip the optimization pass for them.
  165293. */
  165294. master->pass_type = output_pass;
  165295. master->pass_number++;
  165296. /*FALLTHROUGH*/
  165297. #endif
  165298. case output_pass:
  165299. /* Do a data-output pass. */
  165300. /* We need not repeat per-scan setup if prior optimization pass did it. */
  165301. if (! cinfo->optimize_coding) {
  165302. select_scan_parameters(cinfo);
  165303. per_scan_setup(cinfo);
  165304. }
  165305. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  165306. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  165307. /* We emit frame/scan headers now */
  165308. if (master->scan_number == 0)
  165309. (*cinfo->marker->write_frame_header) (cinfo);
  165310. (*cinfo->marker->write_scan_header) (cinfo);
  165311. master->pub.call_pass_startup = FALSE;
  165312. break;
  165313. default:
  165314. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165315. }
  165316. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  165317. /* Set up progress monitor's pass info if present */
  165318. if (cinfo->progress != NULL) {
  165319. cinfo->progress->completed_passes = master->pass_number;
  165320. cinfo->progress->total_passes = master->total_passes;
  165321. }
  165322. }
  165323. /*
  165324. * Special start-of-pass hook.
  165325. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  165326. * In single-pass processing, we need this hook because we don't want to
  165327. * write frame/scan headers during jpeg_start_compress; we want to let the
  165328. * application write COM markers etc. between jpeg_start_compress and the
  165329. * jpeg_write_scanlines loop.
  165330. * In multi-pass processing, this routine is not used.
  165331. */
  165332. METHODDEF(void)
  165333. pass_startup (j_compress_ptr cinfo)
  165334. {
  165335. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  165336. (*cinfo->marker->write_frame_header) (cinfo);
  165337. (*cinfo->marker->write_scan_header) (cinfo);
  165338. }
  165339. /*
  165340. * Finish up at end of pass.
  165341. */
  165342. METHODDEF(void)
  165343. finish_pass_master (j_compress_ptr cinfo)
  165344. {
  165345. my_master_ptr master = (my_master_ptr) cinfo->master;
  165346. /* The entropy coder always needs an end-of-pass call,
  165347. * either to analyze statistics or to flush its output buffer.
  165348. */
  165349. (*cinfo->entropy->finish_pass) (cinfo);
  165350. /* Update state for next pass */
  165351. switch (master->pass_type) {
  165352. case main_pass:
  165353. /* next pass is either output of scan 0 (after optimization)
  165354. * or output of scan 1 (if no optimization).
  165355. */
  165356. master->pass_type = output_pass;
  165357. if (! cinfo->optimize_coding)
  165358. master->scan_number++;
  165359. break;
  165360. case huff_opt_pass:
  165361. /* next pass is always output of current scan */
  165362. master->pass_type = output_pass;
  165363. break;
  165364. case output_pass:
  165365. /* next pass is either optimization or output of next scan */
  165366. if (cinfo->optimize_coding)
  165367. master->pass_type = huff_opt_pass;
  165368. master->scan_number++;
  165369. break;
  165370. }
  165371. master->pass_number++;
  165372. }
  165373. /*
  165374. * Initialize master compression control.
  165375. */
  165376. GLOBAL(void)
  165377. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  165378. {
  165379. my_master_ptr master;
  165380. master = (my_master_ptr)
  165381. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165382. SIZEOF(my_comp_master));
  165383. cinfo->master = (struct jpeg_comp_master *) master;
  165384. master->pub.prepare_for_pass = prepare_for_pass;
  165385. master->pub.pass_startup = pass_startup;
  165386. master->pub.finish_pass = finish_pass_master;
  165387. master->pub.is_last_pass = FALSE;
  165388. /* Validate parameters, determine derived values */
  165389. initial_setup(cinfo);
  165390. if (cinfo->scan_info != NULL) {
  165391. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165392. validate_script(cinfo);
  165393. #else
  165394. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165395. #endif
  165396. } else {
  165397. cinfo->progressive_mode = FALSE;
  165398. cinfo->num_scans = 1;
  165399. }
  165400. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  165401. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  165402. /* Initialize my private state */
  165403. if (transcode_only) {
  165404. /* no main pass in transcoding */
  165405. if (cinfo->optimize_coding)
  165406. master->pass_type = huff_opt_pass;
  165407. else
  165408. master->pass_type = output_pass;
  165409. } else {
  165410. /* for normal compression, first pass is always this type: */
  165411. master->pass_type = main_pass;
  165412. }
  165413. master->scan_number = 0;
  165414. master->pass_number = 0;
  165415. if (cinfo->optimize_coding)
  165416. master->total_passes = cinfo->num_scans * 2;
  165417. else
  165418. master->total_passes = cinfo->num_scans;
  165419. }
  165420. /*** End of inlined file: jcmaster.c ***/
  165421. /*** Start of inlined file: jcomapi.c ***/
  165422. #define JPEG_INTERNALS
  165423. /*
  165424. * Abort processing of a JPEG compression or decompression operation,
  165425. * but don't destroy the object itself.
  165426. *
  165427. * For this, we merely clean up all the nonpermanent memory pools.
  165428. * Note that temp files (virtual arrays) are not allowed to belong to
  165429. * the permanent pool, so we will be able to close all temp files here.
  165430. * Closing a data source or destination, if necessary, is the application's
  165431. * responsibility.
  165432. */
  165433. GLOBAL(void)
  165434. jpeg_abort (j_common_ptr cinfo)
  165435. {
  165436. int pool;
  165437. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  165438. if (cinfo->mem == NULL)
  165439. return;
  165440. /* Releasing pools in reverse order might help avoid fragmentation
  165441. * with some (brain-damaged) malloc libraries.
  165442. */
  165443. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  165444. (*cinfo->mem->free_pool) (cinfo, pool);
  165445. }
  165446. /* Reset overall state for possible reuse of object */
  165447. if (cinfo->is_decompressor) {
  165448. cinfo->global_state = DSTATE_START;
  165449. /* Try to keep application from accessing now-deleted marker list.
  165450. * A bit kludgy to do it here, but this is the most central place.
  165451. */
  165452. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  165453. } else {
  165454. cinfo->global_state = CSTATE_START;
  165455. }
  165456. }
  165457. /*
  165458. * Destruction of a JPEG object.
  165459. *
  165460. * Everything gets deallocated except the master jpeg_compress_struct itself
  165461. * and the error manager struct. Both of these are supplied by the application
  165462. * and must be freed, if necessary, by the application. (Often they are on
  165463. * the stack and so don't need to be freed anyway.)
  165464. * Closing a data source or destination, if necessary, is the application's
  165465. * responsibility.
  165466. */
  165467. GLOBAL(void)
  165468. jpeg_destroy (j_common_ptr cinfo)
  165469. {
  165470. /* We need only tell the memory manager to release everything. */
  165471. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  165472. if (cinfo->mem != NULL)
  165473. (*cinfo->mem->self_destruct) (cinfo);
  165474. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  165475. cinfo->global_state = 0; /* mark it destroyed */
  165476. }
  165477. /*
  165478. * Convenience routines for allocating quantization and Huffman tables.
  165479. * (Would jutils.c be a more reasonable place to put these?)
  165480. */
  165481. GLOBAL(JQUANT_TBL *)
  165482. jpeg_alloc_quant_table (j_common_ptr cinfo)
  165483. {
  165484. JQUANT_TBL *tbl;
  165485. tbl = (JQUANT_TBL *)
  165486. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  165487. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165488. return tbl;
  165489. }
  165490. GLOBAL(JHUFF_TBL *)
  165491. jpeg_alloc_huff_table (j_common_ptr cinfo)
  165492. {
  165493. JHUFF_TBL *tbl;
  165494. tbl = (JHUFF_TBL *)
  165495. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  165496. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  165497. return tbl;
  165498. }
  165499. /*** End of inlined file: jcomapi.c ***/
  165500. /*** Start of inlined file: jcparam.c ***/
  165501. #define JPEG_INTERNALS
  165502. /*
  165503. * Quantization table setup routines
  165504. */
  165505. GLOBAL(void)
  165506. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  165507. const unsigned int *basic_table,
  165508. int scale_factor, boolean force_baseline)
  165509. /* Define a quantization table equal to the basic_table times
  165510. * a scale factor (given as a percentage).
  165511. * If force_baseline is TRUE, the computed quantization table entries
  165512. * are limited to 1..255 for JPEG baseline compatibility.
  165513. */
  165514. {
  165515. JQUANT_TBL ** qtblptr;
  165516. int i;
  165517. long temp;
  165518. /* Safety check to ensure start_compress not called yet. */
  165519. if (cinfo->global_state != CSTATE_START)
  165520. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165521. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  165522. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  165523. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  165524. if (*qtblptr == NULL)
  165525. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  165526. for (i = 0; i < DCTSIZE2; i++) {
  165527. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  165528. /* limit the values to the valid range */
  165529. if (temp <= 0L) temp = 1L;
  165530. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  165531. if (force_baseline && temp > 255L)
  165532. temp = 255L; /* limit to baseline range if requested */
  165533. (*qtblptr)->quantval[i] = (UINT16) temp;
  165534. }
  165535. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165536. (*qtblptr)->sent_table = FALSE;
  165537. }
  165538. GLOBAL(void)
  165539. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  165540. boolean force_baseline)
  165541. /* Set or change the 'quality' (quantization) setting, using default tables
  165542. * and a straight percentage-scaling quality scale. In most cases it's better
  165543. * to use jpeg_set_quality (below); this entry point is provided for
  165544. * applications that insist on a linear percentage scaling.
  165545. */
  165546. {
  165547. /* These are the sample quantization tables given in JPEG spec section K.1.
  165548. * The spec says that the values given produce "good" quality, and
  165549. * when divided by 2, "very good" quality.
  165550. */
  165551. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  165552. 16, 11, 10, 16, 24, 40, 51, 61,
  165553. 12, 12, 14, 19, 26, 58, 60, 55,
  165554. 14, 13, 16, 24, 40, 57, 69, 56,
  165555. 14, 17, 22, 29, 51, 87, 80, 62,
  165556. 18, 22, 37, 56, 68, 109, 103, 77,
  165557. 24, 35, 55, 64, 81, 104, 113, 92,
  165558. 49, 64, 78, 87, 103, 121, 120, 101,
  165559. 72, 92, 95, 98, 112, 100, 103, 99
  165560. };
  165561. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  165562. 17, 18, 24, 47, 99, 99, 99, 99,
  165563. 18, 21, 26, 66, 99, 99, 99, 99,
  165564. 24, 26, 56, 99, 99, 99, 99, 99,
  165565. 47, 66, 99, 99, 99, 99, 99, 99,
  165566. 99, 99, 99, 99, 99, 99, 99, 99,
  165567. 99, 99, 99, 99, 99, 99, 99, 99,
  165568. 99, 99, 99, 99, 99, 99, 99, 99,
  165569. 99, 99, 99, 99, 99, 99, 99, 99
  165570. };
  165571. /* Set up two quantization tables using the specified scaling */
  165572. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  165573. scale_factor, force_baseline);
  165574. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  165575. scale_factor, force_baseline);
  165576. }
  165577. GLOBAL(int)
  165578. jpeg_quality_scaling (int quality)
  165579. /* Convert a user-specified quality rating to a percentage scaling factor
  165580. * for an underlying quantization table, using our recommended scaling curve.
  165581. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  165582. */
  165583. {
  165584. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  165585. if (quality <= 0) quality = 1;
  165586. if (quality > 100) quality = 100;
  165587. /* The basic table is used as-is (scaling 100) for a quality of 50.
  165588. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  165589. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  165590. * to make all the table entries 1 (hence, minimum quantization loss).
  165591. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  165592. */
  165593. if (quality < 50)
  165594. quality = 5000 / quality;
  165595. else
  165596. quality = 200 - quality*2;
  165597. return quality;
  165598. }
  165599. GLOBAL(void)
  165600. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  165601. /* Set or change the 'quality' (quantization) setting, using default tables.
  165602. * This is the standard quality-adjusting entry point for typical user
  165603. * interfaces; only those who want detailed control over quantization tables
  165604. * would use the preceding three routines directly.
  165605. */
  165606. {
  165607. /* Convert user 0-100 rating to percentage scaling */
  165608. quality = jpeg_quality_scaling(quality);
  165609. /* Set up standard quality tables */
  165610. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  165611. }
  165612. /*
  165613. * Huffman table setup routines
  165614. */
  165615. LOCAL(void)
  165616. add_huff_table (j_compress_ptr cinfo,
  165617. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  165618. /* Define a Huffman table */
  165619. {
  165620. int nsymbols, len;
  165621. if (*htblptr == NULL)
  165622. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  165623. /* Copy the number-of-symbols-of-each-code-length counts */
  165624. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  165625. /* Validate the counts. We do this here mainly so we can copy the right
  165626. * number of symbols from the val[] array, without risking marching off
  165627. * the end of memory. jchuff.c will do a more thorough test later.
  165628. */
  165629. nsymbols = 0;
  165630. for (len = 1; len <= 16; len++)
  165631. nsymbols += bits[len];
  165632. if (nsymbols < 1 || nsymbols > 256)
  165633. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  165634. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  165635. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  165636. (*htblptr)->sent_table = FALSE;
  165637. }
  165638. LOCAL(void)
  165639. std_huff_tables (j_compress_ptr cinfo)
  165640. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  165641. /* IMPORTANT: these are only valid for 8-bit data precision! */
  165642. {
  165643. static const UINT8 bits_dc_luminance[17] =
  165644. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  165645. static const UINT8 val_dc_luminance[] =
  165646. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165647. static const UINT8 bits_dc_chrominance[17] =
  165648. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  165649. static const UINT8 val_dc_chrominance[] =
  165650. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  165651. static const UINT8 bits_ac_luminance[17] =
  165652. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  165653. static const UINT8 val_ac_luminance[] =
  165654. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  165655. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  165656. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  165657. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  165658. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  165659. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  165660. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  165661. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  165662. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  165663. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  165664. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  165665. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  165666. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  165667. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  165668. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  165669. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  165670. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  165671. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  165672. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  165673. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165674. 0xf9, 0xfa };
  165675. static const UINT8 bits_ac_chrominance[17] =
  165676. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  165677. static const UINT8 val_ac_chrominance[] =
  165678. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  165679. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  165680. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  165681. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  165682. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  165683. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  165684. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  165685. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  165686. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  165687. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  165688. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  165689. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  165690. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  165691. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  165692. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  165693. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  165694. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  165695. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  165696. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  165697. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  165698. 0xf9, 0xfa };
  165699. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  165700. bits_dc_luminance, val_dc_luminance);
  165701. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  165702. bits_ac_luminance, val_ac_luminance);
  165703. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  165704. bits_dc_chrominance, val_dc_chrominance);
  165705. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  165706. bits_ac_chrominance, val_ac_chrominance);
  165707. }
  165708. /*
  165709. * Default parameter setup for compression.
  165710. *
  165711. * Applications that don't choose to use this routine must do their
  165712. * own setup of all these parameters. Alternately, you can call this
  165713. * to establish defaults and then alter parameters selectively. This
  165714. * is the recommended approach since, if we add any new parameters,
  165715. * your code will still work (they'll be set to reasonable defaults).
  165716. */
  165717. GLOBAL(void)
  165718. jpeg_set_defaults (j_compress_ptr cinfo)
  165719. {
  165720. int i;
  165721. /* Safety check to ensure start_compress not called yet. */
  165722. if (cinfo->global_state != CSTATE_START)
  165723. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165724. /* Allocate comp_info array large enough for maximum component count.
  165725. * Array is made permanent in case application wants to compress
  165726. * multiple images at same param settings.
  165727. */
  165728. if (cinfo->comp_info == NULL)
  165729. cinfo->comp_info = (jpeg_component_info *)
  165730. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165731. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  165732. /* Initialize everything not dependent on the color space */
  165733. cinfo->data_precision = BITS_IN_JSAMPLE;
  165734. /* Set up two quantization tables using default quality of 75 */
  165735. jpeg_set_quality(cinfo, 75, TRUE);
  165736. /* Set up two Huffman tables */
  165737. std_huff_tables(cinfo);
  165738. /* Initialize default arithmetic coding conditioning */
  165739. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165740. cinfo->arith_dc_L[i] = 0;
  165741. cinfo->arith_dc_U[i] = 1;
  165742. cinfo->arith_ac_K[i] = 5;
  165743. }
  165744. /* Default is no multiple-scan output */
  165745. cinfo->scan_info = NULL;
  165746. cinfo->num_scans = 0;
  165747. /* Expect normal source image, not raw downsampled data */
  165748. cinfo->raw_data_in = FALSE;
  165749. /* Use Huffman coding, not arithmetic coding, by default */
  165750. cinfo->arith_code = FALSE;
  165751. /* By default, don't do extra passes to optimize entropy coding */
  165752. cinfo->optimize_coding = FALSE;
  165753. /* The standard Huffman tables are only valid for 8-bit data precision.
  165754. * If the precision is higher, force optimization on so that usable
  165755. * tables will be computed. This test can be removed if default tables
  165756. * are supplied that are valid for the desired precision.
  165757. */
  165758. if (cinfo->data_precision > 8)
  165759. cinfo->optimize_coding = TRUE;
  165760. /* By default, use the simpler non-cosited sampling alignment */
  165761. cinfo->CCIR601_sampling = FALSE;
  165762. /* No input smoothing */
  165763. cinfo->smoothing_factor = 0;
  165764. /* DCT algorithm preference */
  165765. cinfo->dct_method = JDCT_DEFAULT;
  165766. /* No restart markers */
  165767. cinfo->restart_interval = 0;
  165768. cinfo->restart_in_rows = 0;
  165769. /* Fill in default JFIF marker parameters. Note that whether the marker
  165770. * will actually be written is determined by jpeg_set_colorspace.
  165771. *
  165772. * By default, the library emits JFIF version code 1.01.
  165773. * An application that wants to emit JFIF 1.02 extension markers should set
  165774. * JFIF_minor_version to 2. We could probably get away with just defaulting
  165775. * to 1.02, but there may still be some decoders in use that will complain
  165776. * about that; saying 1.01 should minimize compatibility problems.
  165777. */
  165778. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  165779. cinfo->JFIF_minor_version = 1;
  165780. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  165781. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  165782. cinfo->Y_density = 1;
  165783. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  165784. jpeg_default_colorspace(cinfo);
  165785. }
  165786. /*
  165787. * Select an appropriate JPEG colorspace for in_color_space.
  165788. */
  165789. GLOBAL(void)
  165790. jpeg_default_colorspace (j_compress_ptr cinfo)
  165791. {
  165792. switch (cinfo->in_color_space) {
  165793. case JCS_GRAYSCALE:
  165794. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  165795. break;
  165796. case JCS_RGB:
  165797. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165798. break;
  165799. case JCS_YCbCr:
  165800. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  165801. break;
  165802. case JCS_CMYK:
  165803. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  165804. break;
  165805. case JCS_YCCK:
  165806. jpeg_set_colorspace(cinfo, JCS_YCCK);
  165807. break;
  165808. case JCS_UNKNOWN:
  165809. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  165810. break;
  165811. default:
  165812. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  165813. }
  165814. }
  165815. /*
  165816. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  165817. */
  165818. GLOBAL(void)
  165819. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  165820. {
  165821. jpeg_component_info * compptr;
  165822. int ci;
  165823. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  165824. (compptr = &cinfo->comp_info[index], \
  165825. compptr->component_id = (id), \
  165826. compptr->h_samp_factor = (hsamp), \
  165827. compptr->v_samp_factor = (vsamp), \
  165828. compptr->quant_tbl_no = (quant), \
  165829. compptr->dc_tbl_no = (dctbl), \
  165830. compptr->ac_tbl_no = (actbl) )
  165831. /* Safety check to ensure start_compress not called yet. */
  165832. if (cinfo->global_state != CSTATE_START)
  165833. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165834. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  165835. * tables 1 for chrominance components.
  165836. */
  165837. cinfo->jpeg_color_space = colorspace;
  165838. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  165839. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  165840. switch (colorspace) {
  165841. case JCS_GRAYSCALE:
  165842. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165843. cinfo->num_components = 1;
  165844. /* JFIF specifies component ID 1 */
  165845. SET_COMP(0, 1, 1,1, 0, 0,0);
  165846. break;
  165847. case JCS_RGB:
  165848. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  165849. cinfo->num_components = 3;
  165850. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  165851. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  165852. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  165853. break;
  165854. case JCS_YCbCr:
  165855. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  165856. cinfo->num_components = 3;
  165857. /* JFIF specifies component IDs 1,2,3 */
  165858. /* We default to 2x2 subsamples of chrominance */
  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. break;
  165863. case JCS_CMYK:
  165864. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  165865. cinfo->num_components = 4;
  165866. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  165867. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  165868. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  165869. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  165870. break;
  165871. case JCS_YCCK:
  165872. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  165873. cinfo->num_components = 4;
  165874. SET_COMP(0, 1, 2,2, 0, 0,0);
  165875. SET_COMP(1, 2, 1,1, 1, 1,1);
  165876. SET_COMP(2, 3, 1,1, 1, 1,1);
  165877. SET_COMP(3, 4, 2,2, 0, 0,0);
  165878. break;
  165879. case JCS_UNKNOWN:
  165880. cinfo->num_components = cinfo->input_components;
  165881. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  165882. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165883. MAX_COMPONENTS);
  165884. for (ci = 0; ci < cinfo->num_components; ci++) {
  165885. SET_COMP(ci, ci, 1,1, 0, 0,0);
  165886. }
  165887. break;
  165888. default:
  165889. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  165890. }
  165891. }
  165892. #ifdef C_PROGRESSIVE_SUPPORTED
  165893. LOCAL(jpeg_scan_info *)
  165894. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  165895. int Ss, int Se, int Ah, int Al)
  165896. /* Support routine: generate one scan for specified component */
  165897. {
  165898. scanptr->comps_in_scan = 1;
  165899. scanptr->component_index[0] = ci;
  165900. scanptr->Ss = Ss;
  165901. scanptr->Se = Se;
  165902. scanptr->Ah = Ah;
  165903. scanptr->Al = Al;
  165904. scanptr++;
  165905. return scanptr;
  165906. }
  165907. LOCAL(jpeg_scan_info *)
  165908. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  165909. int Ss, int Se, int Ah, int Al)
  165910. /* Support routine: generate one scan for each component */
  165911. {
  165912. int ci;
  165913. for (ci = 0; ci < ncomps; ci++) {
  165914. scanptr->comps_in_scan = 1;
  165915. scanptr->component_index[0] = ci;
  165916. scanptr->Ss = Ss;
  165917. scanptr->Se = Se;
  165918. scanptr->Ah = Ah;
  165919. scanptr->Al = Al;
  165920. scanptr++;
  165921. }
  165922. return scanptr;
  165923. }
  165924. LOCAL(jpeg_scan_info *)
  165925. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  165926. /* Support routine: generate interleaved DC scan if possible, else N scans */
  165927. {
  165928. int ci;
  165929. if (ncomps <= MAX_COMPS_IN_SCAN) {
  165930. /* Single interleaved DC scan */
  165931. scanptr->comps_in_scan = ncomps;
  165932. for (ci = 0; ci < ncomps; ci++)
  165933. scanptr->component_index[ci] = ci;
  165934. scanptr->Ss = scanptr->Se = 0;
  165935. scanptr->Ah = Ah;
  165936. scanptr->Al = Al;
  165937. scanptr++;
  165938. } else {
  165939. /* Noninterleaved DC scan for each component */
  165940. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  165941. }
  165942. return scanptr;
  165943. }
  165944. /*
  165945. * Create a recommended progressive-JPEG script.
  165946. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  165947. */
  165948. GLOBAL(void)
  165949. jpeg_simple_progression (j_compress_ptr cinfo)
  165950. {
  165951. int ncomps = cinfo->num_components;
  165952. int nscans;
  165953. jpeg_scan_info * scanptr;
  165954. /* Safety check to ensure start_compress not called yet. */
  165955. if (cinfo->global_state != CSTATE_START)
  165956. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  165957. /* Figure space needed for script. Calculation must match code below! */
  165958. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165959. /* Custom script for YCbCr color images. */
  165960. nscans = 10;
  165961. } else {
  165962. /* All-purpose script for other color spaces. */
  165963. if (ncomps > MAX_COMPS_IN_SCAN)
  165964. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  165965. else
  165966. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  165967. }
  165968. /* Allocate space for script.
  165969. * We need to put it in the permanent pool in case the application performs
  165970. * multiple compressions without changing the settings. To avoid a memory
  165971. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  165972. * object, we try to re-use previously allocated space, and we allocate
  165973. * enough space to handle YCbCr even if initially asked for grayscale.
  165974. */
  165975. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  165976. cinfo->script_space_size = MAX(nscans, 10);
  165977. cinfo->script_space = (jpeg_scan_info *)
  165978. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  165979. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  165980. }
  165981. scanptr = cinfo->script_space;
  165982. cinfo->scan_info = scanptr;
  165983. cinfo->num_scans = nscans;
  165984. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  165985. /* Custom script for YCbCr color images. */
  165986. /* Initial DC scan */
  165987. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  165988. /* Initial AC scan: get some luma data out in a hurry */
  165989. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  165990. /* Chroma data is too small to be worth expending many scans on */
  165991. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  165992. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  165993. /* Complete spectral selection for luma AC */
  165994. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  165995. /* Refine next bit of luma AC */
  165996. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  165997. /* Finish DC successive approximation */
  165998. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  165999. /* Finish AC successive approximation */
  166000. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  166001. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  166002. /* Luma bottom bit comes last since it's usually largest scan */
  166003. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  166004. } else {
  166005. /* All-purpose script for other color spaces. */
  166006. /* Successive approximation first pass */
  166007. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  166008. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  166009. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  166010. /* Successive approximation second pass */
  166011. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  166012. /* Successive approximation final pass */
  166013. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  166014. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  166015. }
  166016. }
  166017. #endif /* C_PROGRESSIVE_SUPPORTED */
  166018. /*** End of inlined file: jcparam.c ***/
  166019. /*** Start of inlined file: jcphuff.c ***/
  166020. #define JPEG_INTERNALS
  166021. #ifdef C_PROGRESSIVE_SUPPORTED
  166022. /* Expanded entropy encoder object for progressive Huffman encoding. */
  166023. typedef struct {
  166024. struct jpeg_entropy_encoder pub; /* public fields */
  166025. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  166026. boolean gather_statistics;
  166027. /* Bit-level coding status.
  166028. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  166029. */
  166030. JOCTET * next_output_byte; /* => next byte to write in buffer */
  166031. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  166032. INT32 put_buffer; /* current bit-accumulation buffer */
  166033. int put_bits; /* # of bits now in it */
  166034. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166035. /* Coding status for DC components */
  166036. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166037. /* Coding status for AC components */
  166038. int ac_tbl_no; /* the table number of the single component */
  166039. unsigned int EOBRUN; /* run length of EOBs */
  166040. unsigned int BE; /* # of buffered correction bits before MCU */
  166041. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166042. /* packing correction bits tightly would save some space but cost time... */
  166043. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166044. int next_restart_num; /* next restart number to write (0-7) */
  166045. /* Pointers to derived tables (these workspaces have image lifespan).
  166046. * Since any one scan codes only DC or only AC, we only need one set
  166047. * of tables, not one for DC and one for AC.
  166048. */
  166049. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166050. /* Statistics tables for optimization; again, one set is enough */
  166051. long * count_ptrs[NUM_HUFF_TBLS];
  166052. } phuff_entropy_encoder;
  166053. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166054. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166055. * buffer can hold. Larger sizes may slightly improve compression, but
  166056. * 1000 is already well into the realm of overkill.
  166057. * The minimum safe size is 64 bits.
  166058. */
  166059. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166060. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166061. * We assume that int right shift is unsigned if INT32 right shift is,
  166062. * which should be safe.
  166063. */
  166064. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166065. #define ISHIFT_TEMPS int ishift_temp;
  166066. #define IRIGHT_SHIFT(x,shft) \
  166067. ((ishift_temp = (x)) < 0 ? \
  166068. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166069. (ishift_temp >> (shft)))
  166070. #else
  166071. #define ISHIFT_TEMPS
  166072. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166073. #endif
  166074. /* Forward declarations */
  166075. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166076. JBLOCKROW *MCU_data));
  166077. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166078. JBLOCKROW *MCU_data));
  166079. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166080. JBLOCKROW *MCU_data));
  166081. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166082. JBLOCKROW *MCU_data));
  166083. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166084. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166085. /*
  166086. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166087. */
  166088. METHODDEF(void)
  166089. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166090. {
  166091. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166092. boolean is_DC_band;
  166093. int ci, tbl;
  166094. jpeg_component_info * compptr;
  166095. entropy->cinfo = cinfo;
  166096. entropy->gather_statistics = gather_statistics;
  166097. is_DC_band = (cinfo->Ss == 0);
  166098. /* We assume jcmaster.c already validated the scan parameters. */
  166099. /* Select execution routines */
  166100. if (cinfo->Ah == 0) {
  166101. if (is_DC_band)
  166102. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166103. else
  166104. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166105. } else {
  166106. if (is_DC_band)
  166107. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166108. else {
  166109. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166110. /* AC refinement needs a correction bit buffer */
  166111. if (entropy->bit_buffer == NULL)
  166112. entropy->bit_buffer = (char *)
  166113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166114. MAX_CORR_BITS * SIZEOF(char));
  166115. }
  166116. }
  166117. if (gather_statistics)
  166118. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166119. else
  166120. entropy->pub.finish_pass = finish_pass_phuff;
  166121. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166122. * for AC coefficients.
  166123. */
  166124. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166125. compptr = cinfo->cur_comp_info[ci];
  166126. /* Initialize DC predictions to 0 */
  166127. entropy->last_dc_val[ci] = 0;
  166128. /* Get table index */
  166129. if (is_DC_band) {
  166130. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166131. continue;
  166132. tbl = compptr->dc_tbl_no;
  166133. } else {
  166134. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166135. }
  166136. if (gather_statistics) {
  166137. /* Check for invalid table index */
  166138. /* (make_c_derived_tbl does this in the other path) */
  166139. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166140. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166141. /* Allocate and zero the statistics tables */
  166142. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166143. if (entropy->count_ptrs[tbl] == NULL)
  166144. entropy->count_ptrs[tbl] = (long *)
  166145. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166146. 257 * SIZEOF(long));
  166147. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166148. } else {
  166149. /* Compute derived values for Huffman table */
  166150. /* We may do this more than once for a table, but it's not expensive */
  166151. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166152. & entropy->derived_tbls[tbl]);
  166153. }
  166154. }
  166155. /* Initialize AC stuff */
  166156. entropy->EOBRUN = 0;
  166157. entropy->BE = 0;
  166158. /* Initialize bit buffer to empty */
  166159. entropy->put_buffer = 0;
  166160. entropy->put_bits = 0;
  166161. /* Initialize restart stuff */
  166162. entropy->restarts_to_go = cinfo->restart_interval;
  166163. entropy->next_restart_num = 0;
  166164. }
  166165. /* Outputting bytes to the file.
  166166. * NB: these must be called only when actually outputting,
  166167. * that is, entropy->gather_statistics == FALSE.
  166168. */
  166169. /* Emit a byte */
  166170. #define emit_byte(entropy,val) \
  166171. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166172. if (--(entropy)->free_in_buffer == 0) \
  166173. dump_buffer_p(entropy); }
  166174. LOCAL(void)
  166175. dump_buffer_p (phuff_entropy_ptr entropy)
  166176. /* Empty the output buffer; we do not support suspension in this module. */
  166177. {
  166178. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166179. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166180. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166181. /* After a successful buffer dump, must reset buffer pointers */
  166182. entropy->next_output_byte = dest->next_output_byte;
  166183. entropy->free_in_buffer = dest->free_in_buffer;
  166184. }
  166185. /* Outputting bits to the file */
  166186. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166187. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166188. * in one call, and we never retain more than 7 bits in put_buffer
  166189. * between calls, so 24 bits are sufficient.
  166190. */
  166191. INLINE
  166192. LOCAL(void)
  166193. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166194. /* Emit some bits, unless we are in gather mode */
  166195. {
  166196. /* This routine is heavily used, so it's worth coding tightly. */
  166197. register INT32 put_buffer = (INT32) code;
  166198. register int put_bits = entropy->put_bits;
  166199. /* if size is 0, caller used an invalid Huffman table entry */
  166200. if (size == 0)
  166201. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166202. if (entropy->gather_statistics)
  166203. return; /* do nothing if we're only getting stats */
  166204. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166205. put_bits += size; /* new number of bits in buffer */
  166206. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166207. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166208. while (put_bits >= 8) {
  166209. int c = (int) ((put_buffer >> 16) & 0xFF);
  166210. emit_byte(entropy, c);
  166211. if (c == 0xFF) { /* need to stuff a zero byte? */
  166212. emit_byte(entropy, 0);
  166213. }
  166214. put_buffer <<= 8;
  166215. put_bits -= 8;
  166216. }
  166217. entropy->put_buffer = put_buffer; /* update variables */
  166218. entropy->put_bits = put_bits;
  166219. }
  166220. LOCAL(void)
  166221. flush_bits_p (phuff_entropy_ptr entropy)
  166222. {
  166223. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166224. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166225. entropy->put_bits = 0;
  166226. }
  166227. /*
  166228. * Emit (or just count) a Huffman symbol.
  166229. */
  166230. INLINE
  166231. LOCAL(void)
  166232. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  166233. {
  166234. if (entropy->gather_statistics)
  166235. entropy->count_ptrs[tbl_no][symbol]++;
  166236. else {
  166237. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  166238. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  166239. }
  166240. }
  166241. /*
  166242. * Emit bits from a correction bit buffer.
  166243. */
  166244. LOCAL(void)
  166245. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  166246. unsigned int nbits)
  166247. {
  166248. if (entropy->gather_statistics)
  166249. return; /* no real work */
  166250. while (nbits > 0) {
  166251. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  166252. bufstart++;
  166253. nbits--;
  166254. }
  166255. }
  166256. /*
  166257. * Emit any pending EOBRUN symbol.
  166258. */
  166259. LOCAL(void)
  166260. emit_eobrun (phuff_entropy_ptr entropy)
  166261. {
  166262. register int temp, nbits;
  166263. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  166264. temp = entropy->EOBRUN;
  166265. nbits = 0;
  166266. while ((temp >>= 1))
  166267. nbits++;
  166268. /* safety check: shouldn't happen given limited correction-bit buffer */
  166269. if (nbits > 14)
  166270. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166271. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  166272. if (nbits)
  166273. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  166274. entropy->EOBRUN = 0;
  166275. /* Emit any buffered correction bits */
  166276. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  166277. entropy->BE = 0;
  166278. }
  166279. }
  166280. /*
  166281. * Emit a restart marker & resynchronize predictions.
  166282. */
  166283. LOCAL(void)
  166284. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  166285. {
  166286. int ci;
  166287. emit_eobrun(entropy);
  166288. if (! entropy->gather_statistics) {
  166289. flush_bits_p(entropy);
  166290. emit_byte(entropy, 0xFF);
  166291. emit_byte(entropy, JPEG_RST0 + restart_num);
  166292. }
  166293. if (entropy->cinfo->Ss == 0) {
  166294. /* Re-initialize DC predictions to 0 */
  166295. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  166296. entropy->last_dc_val[ci] = 0;
  166297. } else {
  166298. /* Re-initialize all AC-related fields to 0 */
  166299. entropy->EOBRUN = 0;
  166300. entropy->BE = 0;
  166301. }
  166302. }
  166303. /*
  166304. * MCU encoding for DC initial scan (either spectral selection,
  166305. * or first pass of successive approximation).
  166306. */
  166307. METHODDEF(boolean)
  166308. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166309. {
  166310. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166311. register int temp, temp2;
  166312. register int nbits;
  166313. int blkn, ci;
  166314. int Al = cinfo->Al;
  166315. JBLOCKROW block;
  166316. jpeg_component_info * compptr;
  166317. ISHIFT_TEMPS
  166318. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166319. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166320. /* Emit restart marker if needed */
  166321. if (cinfo->restart_interval)
  166322. if (entropy->restarts_to_go == 0)
  166323. emit_restart_p(entropy, entropy->next_restart_num);
  166324. /* Encode the MCU data blocks */
  166325. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166326. block = MCU_data[blkn];
  166327. ci = cinfo->MCU_membership[blkn];
  166328. compptr = cinfo->cur_comp_info[ci];
  166329. /* Compute the DC value after the required point transform by Al.
  166330. * This is simply an arithmetic right shift.
  166331. */
  166332. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  166333. /* DC differences are figured on the point-transformed values. */
  166334. temp = temp2 - entropy->last_dc_val[ci];
  166335. entropy->last_dc_val[ci] = temp2;
  166336. /* Encode the DC coefficient difference per section G.1.2.1 */
  166337. temp2 = temp;
  166338. if (temp < 0) {
  166339. temp = -temp; /* temp is abs value of input */
  166340. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  166341. /* This code assumes we are on a two's complement machine */
  166342. temp2--;
  166343. }
  166344. /* Find the number of bits needed for the magnitude of the coefficient */
  166345. nbits = 0;
  166346. while (temp) {
  166347. nbits++;
  166348. temp >>= 1;
  166349. }
  166350. /* Check for out-of-range coefficient values.
  166351. * Since we're encoding a difference, the range limit is twice as much.
  166352. */
  166353. if (nbits > MAX_COEF_BITS+1)
  166354. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166355. /* Count/emit the Huffman-coded symbol for the number of bits */
  166356. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  166357. /* Emit that number of bits of the value, if positive, */
  166358. /* or the complement of its magnitude, if negative. */
  166359. if (nbits) /* emit_bits rejects calls with size 0 */
  166360. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166361. }
  166362. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166363. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166364. /* Update restart-interval state too */
  166365. if (cinfo->restart_interval) {
  166366. if (entropy->restarts_to_go == 0) {
  166367. entropy->restarts_to_go = cinfo->restart_interval;
  166368. entropy->next_restart_num++;
  166369. entropy->next_restart_num &= 7;
  166370. }
  166371. entropy->restarts_to_go--;
  166372. }
  166373. return TRUE;
  166374. }
  166375. /*
  166376. * MCU encoding for AC initial scan (either spectral selection,
  166377. * or first pass of successive approximation).
  166378. */
  166379. METHODDEF(boolean)
  166380. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166381. {
  166382. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166383. register int temp, temp2;
  166384. register int nbits;
  166385. register int r, k;
  166386. int Se = cinfo->Se;
  166387. int Al = cinfo->Al;
  166388. JBLOCKROW block;
  166389. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166390. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166391. /* Emit restart marker if needed */
  166392. if (cinfo->restart_interval)
  166393. if (entropy->restarts_to_go == 0)
  166394. emit_restart_p(entropy, entropy->next_restart_num);
  166395. /* Encode the MCU data block */
  166396. block = MCU_data[0];
  166397. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  166398. r = 0; /* r = run length of zeros */
  166399. for (k = cinfo->Ss; k <= Se; k++) {
  166400. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  166401. r++;
  166402. continue;
  166403. }
  166404. /* We must apply the point transform by Al. For AC coefficients this
  166405. * is an integer division with rounding towards 0. To do this portably
  166406. * in C, we shift after obtaining the absolute value; so the code is
  166407. * interwoven with finding the abs value (temp) and output bits (temp2).
  166408. */
  166409. if (temp < 0) {
  166410. temp = -temp; /* temp is abs value of input */
  166411. temp >>= Al; /* apply the point transform */
  166412. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  166413. temp2 = ~temp;
  166414. } else {
  166415. temp >>= Al; /* apply the point transform */
  166416. temp2 = temp;
  166417. }
  166418. /* Watch out for case that nonzero coef is zero after point transform */
  166419. if (temp == 0) {
  166420. r++;
  166421. continue;
  166422. }
  166423. /* Emit any pending EOBRUN */
  166424. if (entropy->EOBRUN > 0)
  166425. emit_eobrun(entropy);
  166426. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  166427. while (r > 15) {
  166428. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166429. r -= 16;
  166430. }
  166431. /* Find the number of bits needed for the magnitude of the coefficient */
  166432. nbits = 1; /* there must be at least one 1 bit */
  166433. while ((temp >>= 1))
  166434. nbits++;
  166435. /* Check for out-of-range coefficient values */
  166436. if (nbits > MAX_COEF_BITS)
  166437. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  166438. /* Count/emit Huffman symbol for run length / number of bits */
  166439. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  166440. /* Emit that number of bits of the value, if positive, */
  166441. /* or the complement of its magnitude, if negative. */
  166442. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  166443. r = 0; /* reset zero run length */
  166444. }
  166445. if (r > 0) { /* If there are trailing zeroes, */
  166446. entropy->EOBRUN++; /* count an EOB */
  166447. if (entropy->EOBRUN == 0x7FFF)
  166448. emit_eobrun(entropy); /* force it out to avoid overflow */
  166449. }
  166450. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166451. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166452. /* Update restart-interval state too */
  166453. if (cinfo->restart_interval) {
  166454. if (entropy->restarts_to_go == 0) {
  166455. entropy->restarts_to_go = cinfo->restart_interval;
  166456. entropy->next_restart_num++;
  166457. entropy->next_restart_num &= 7;
  166458. }
  166459. entropy->restarts_to_go--;
  166460. }
  166461. return TRUE;
  166462. }
  166463. /*
  166464. * MCU encoding for DC successive approximation refinement scan.
  166465. * Note: we assume such scans can be multi-component, although the spec
  166466. * is not very clear on the point.
  166467. */
  166468. METHODDEF(boolean)
  166469. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166470. {
  166471. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166472. register int temp;
  166473. int blkn;
  166474. int Al = cinfo->Al;
  166475. JBLOCKROW block;
  166476. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166477. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166478. /* Emit restart marker if needed */
  166479. if (cinfo->restart_interval)
  166480. if (entropy->restarts_to_go == 0)
  166481. emit_restart_p(entropy, entropy->next_restart_num);
  166482. /* Encode the MCU data blocks */
  166483. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  166484. block = MCU_data[blkn];
  166485. /* We simply emit the Al'th bit of the DC coefficient value. */
  166486. temp = (*block)[0];
  166487. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  166488. }
  166489. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166490. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166491. /* Update restart-interval state too */
  166492. if (cinfo->restart_interval) {
  166493. if (entropy->restarts_to_go == 0) {
  166494. entropy->restarts_to_go = cinfo->restart_interval;
  166495. entropy->next_restart_num++;
  166496. entropy->next_restart_num &= 7;
  166497. }
  166498. entropy->restarts_to_go--;
  166499. }
  166500. return TRUE;
  166501. }
  166502. /*
  166503. * MCU encoding for AC successive approximation refinement scan.
  166504. */
  166505. METHODDEF(boolean)
  166506. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  166507. {
  166508. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166509. register int temp;
  166510. register int r, k;
  166511. int EOB;
  166512. char *BR_buffer;
  166513. unsigned int BR;
  166514. int Se = cinfo->Se;
  166515. int Al = cinfo->Al;
  166516. JBLOCKROW block;
  166517. int absvalues[DCTSIZE2];
  166518. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166519. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166520. /* Emit restart marker if needed */
  166521. if (cinfo->restart_interval)
  166522. if (entropy->restarts_to_go == 0)
  166523. emit_restart_p(entropy, entropy->next_restart_num);
  166524. /* Encode the MCU data block */
  166525. block = MCU_data[0];
  166526. /* It is convenient to make a pre-pass to determine the transformed
  166527. * coefficients' absolute values and the EOB position.
  166528. */
  166529. EOB = 0;
  166530. for (k = cinfo->Ss; k <= Se; k++) {
  166531. temp = (*block)[jpeg_natural_order[k]];
  166532. /* We must apply the point transform by Al. For AC coefficients this
  166533. * is an integer division with rounding towards 0. To do this portably
  166534. * in C, we shift after obtaining the absolute value.
  166535. */
  166536. if (temp < 0)
  166537. temp = -temp; /* temp is abs value of input */
  166538. temp >>= Al; /* apply the point transform */
  166539. absvalues[k] = temp; /* save abs value for main pass */
  166540. if (temp == 1)
  166541. EOB = k; /* EOB = index of last newly-nonzero coef */
  166542. }
  166543. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  166544. r = 0; /* r = run length of zeros */
  166545. BR = 0; /* BR = count of buffered bits added now */
  166546. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  166547. for (k = cinfo->Ss; k <= Se; k++) {
  166548. if ((temp = absvalues[k]) == 0) {
  166549. r++;
  166550. continue;
  166551. }
  166552. /* Emit any required ZRLs, but not if they can be folded into EOB */
  166553. while (r > 15 && k <= EOB) {
  166554. /* emit any pending EOBRUN and the BE correction bits */
  166555. emit_eobrun(entropy);
  166556. /* Emit ZRL */
  166557. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  166558. r -= 16;
  166559. /* Emit buffered correction bits that must be associated with ZRL */
  166560. emit_buffered_bits(entropy, BR_buffer, BR);
  166561. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166562. BR = 0;
  166563. }
  166564. /* If the coef was previously nonzero, it only needs a correction bit.
  166565. * NOTE: a straight translation of the spec's figure G.7 would suggest
  166566. * that we also need to test r > 15. But if r > 15, we can only get here
  166567. * if k > EOB, which implies that this coefficient is not 1.
  166568. */
  166569. if (temp > 1) {
  166570. /* The correction bit is the next bit of the absolute value. */
  166571. BR_buffer[BR++] = (char) (temp & 1);
  166572. continue;
  166573. }
  166574. /* Emit any pending EOBRUN and the BE correction bits */
  166575. emit_eobrun(entropy);
  166576. /* Count/emit Huffman symbol for run length / number of bits */
  166577. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  166578. /* Emit output bit for newly-nonzero coef */
  166579. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  166580. emit_bits_p(entropy, (unsigned int) temp, 1);
  166581. /* Emit buffered correction bits that must be associated with this code */
  166582. emit_buffered_bits(entropy, BR_buffer, BR);
  166583. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  166584. BR = 0;
  166585. r = 0; /* reset zero run length */
  166586. }
  166587. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  166588. entropy->EOBRUN++; /* count an EOB */
  166589. entropy->BE += BR; /* concat my correction bits to older ones */
  166590. /* We force out the EOB if we risk either:
  166591. * 1. overflow of the EOB counter;
  166592. * 2. overflow of the correction bit buffer during the next MCU.
  166593. */
  166594. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  166595. emit_eobrun(entropy);
  166596. }
  166597. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166598. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166599. /* Update restart-interval state too */
  166600. if (cinfo->restart_interval) {
  166601. if (entropy->restarts_to_go == 0) {
  166602. entropy->restarts_to_go = cinfo->restart_interval;
  166603. entropy->next_restart_num++;
  166604. entropy->next_restart_num &= 7;
  166605. }
  166606. entropy->restarts_to_go--;
  166607. }
  166608. return TRUE;
  166609. }
  166610. /*
  166611. * Finish up at the end of a Huffman-compressed progressive scan.
  166612. */
  166613. METHODDEF(void)
  166614. finish_pass_phuff (j_compress_ptr cinfo)
  166615. {
  166616. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166617. entropy->next_output_byte = cinfo->dest->next_output_byte;
  166618. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  166619. /* Flush out any buffered data */
  166620. emit_eobrun(entropy);
  166621. flush_bits_p(entropy);
  166622. cinfo->dest->next_output_byte = entropy->next_output_byte;
  166623. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  166624. }
  166625. /*
  166626. * Finish up a statistics-gathering pass and create the new Huffman tables.
  166627. */
  166628. METHODDEF(void)
  166629. finish_pass_gather_phuff (j_compress_ptr cinfo)
  166630. {
  166631. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166632. boolean is_DC_band;
  166633. int ci, tbl;
  166634. jpeg_component_info * compptr;
  166635. JHUFF_TBL **htblptr;
  166636. boolean did[NUM_HUFF_TBLS];
  166637. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  166638. emit_eobrun(entropy);
  166639. is_DC_band = (cinfo->Ss == 0);
  166640. /* It's important not to apply jpeg_gen_optimal_table more than once
  166641. * per table, because it clobbers the input frequency counts!
  166642. */
  166643. MEMZERO(did, SIZEOF(did));
  166644. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166645. compptr = cinfo->cur_comp_info[ci];
  166646. if (is_DC_band) {
  166647. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166648. continue;
  166649. tbl = compptr->dc_tbl_no;
  166650. } else {
  166651. tbl = compptr->ac_tbl_no;
  166652. }
  166653. if (! did[tbl]) {
  166654. if (is_DC_band)
  166655. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  166656. else
  166657. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  166658. if (*htblptr == NULL)
  166659. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166660. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  166661. did[tbl] = TRUE;
  166662. }
  166663. }
  166664. }
  166665. /*
  166666. * Module initialization routine for progressive Huffman entropy encoding.
  166667. */
  166668. GLOBAL(void)
  166669. jinit_phuff_encoder (j_compress_ptr cinfo)
  166670. {
  166671. phuff_entropy_ptr entropy;
  166672. int i;
  166673. entropy = (phuff_entropy_ptr)
  166674. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166675. SIZEOF(phuff_entropy_encoder));
  166676. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  166677. entropy->pub.start_pass = start_pass_phuff;
  166678. /* Mark tables unallocated */
  166679. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  166680. entropy->derived_tbls[i] = NULL;
  166681. entropy->count_ptrs[i] = NULL;
  166682. }
  166683. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  166684. }
  166685. #endif /* C_PROGRESSIVE_SUPPORTED */
  166686. /*** End of inlined file: jcphuff.c ***/
  166687. /*** Start of inlined file: jcprepct.c ***/
  166688. #define JPEG_INTERNALS
  166689. /* At present, jcsample.c can request context rows only for smoothing.
  166690. * In the future, we might also need context rows for CCIR601 sampling
  166691. * or other more-complex downsampling procedures. The code to support
  166692. * context rows should be compiled only if needed.
  166693. */
  166694. #ifdef INPUT_SMOOTHING_SUPPORTED
  166695. #define CONTEXT_ROWS_SUPPORTED
  166696. #endif
  166697. /*
  166698. * For the simple (no-context-row) case, we just need to buffer one
  166699. * row group's worth of pixels for the downsampling step. At the bottom of
  166700. * the image, we pad to a full row group by replicating the last pixel row.
  166701. * The downsampler's last output row is then replicated if needed to pad
  166702. * out to a full iMCU row.
  166703. *
  166704. * When providing context rows, we must buffer three row groups' worth of
  166705. * pixels. Three row groups are physically allocated, but the row pointer
  166706. * arrays are made five row groups high, with the extra pointers above and
  166707. * below "wrapping around" to point to the last and first real row groups.
  166708. * This allows the downsampler to access the proper context rows.
  166709. * At the top and bottom of the image, we create dummy context rows by
  166710. * copying the first or last real pixel row. This copying could be avoided
  166711. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  166712. * trouble on the compression side.
  166713. */
  166714. /* Private buffer controller object */
  166715. typedef struct {
  166716. struct jpeg_c_prep_controller pub; /* public fields */
  166717. /* Downsampling input buffer. This buffer holds color-converted data
  166718. * until we have enough to do a downsample step.
  166719. */
  166720. JSAMPARRAY color_buf[MAX_COMPONENTS];
  166721. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  166722. int next_buf_row; /* index of next row to store in color_buf */
  166723. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  166724. int this_row_group; /* starting row index of group to process */
  166725. int next_buf_stop; /* downsample when we reach this index */
  166726. #endif
  166727. } my_prep_controller;
  166728. typedef my_prep_controller * my_prep_ptr;
  166729. /*
  166730. * Initialize for a processing pass.
  166731. */
  166732. METHODDEF(void)
  166733. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  166734. {
  166735. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166736. if (pass_mode != JBUF_PASS_THRU)
  166737. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166738. /* Initialize total-height counter for detecting bottom of image */
  166739. prep->rows_to_go = cinfo->image_height;
  166740. /* Mark the conversion buffer empty */
  166741. prep->next_buf_row = 0;
  166742. #ifdef CONTEXT_ROWS_SUPPORTED
  166743. /* Preset additional state variables for context mode.
  166744. * These aren't used in non-context mode, so we needn't test which mode.
  166745. */
  166746. prep->this_row_group = 0;
  166747. /* Set next_buf_stop to stop after two row groups have been read in. */
  166748. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  166749. #endif
  166750. }
  166751. /*
  166752. * Expand an image vertically from height input_rows to height output_rows,
  166753. * by duplicating the bottom row.
  166754. */
  166755. LOCAL(void)
  166756. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  166757. int input_rows, int output_rows)
  166758. {
  166759. register int row;
  166760. for (row = input_rows; row < output_rows; row++) {
  166761. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  166762. 1, num_cols);
  166763. }
  166764. }
  166765. /*
  166766. * Process some data in the simple no-context case.
  166767. *
  166768. * Preprocessor output data is counted in "row groups". A row group
  166769. * is defined to be v_samp_factor sample rows of each component.
  166770. * Downsampling will produce this much data from each max_v_samp_factor
  166771. * input rows.
  166772. */
  166773. METHODDEF(void)
  166774. pre_process_data (j_compress_ptr cinfo,
  166775. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166776. JDIMENSION in_rows_avail,
  166777. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166778. JDIMENSION out_row_groups_avail)
  166779. {
  166780. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166781. int numrows, ci;
  166782. JDIMENSION inrows;
  166783. jpeg_component_info * compptr;
  166784. while (*in_row_ctr < in_rows_avail &&
  166785. *out_row_group_ctr < out_row_groups_avail) {
  166786. /* Do color conversion to fill the conversion buffer. */
  166787. inrows = in_rows_avail - *in_row_ctr;
  166788. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  166789. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166790. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166791. prep->color_buf,
  166792. (JDIMENSION) prep->next_buf_row,
  166793. numrows);
  166794. *in_row_ctr += numrows;
  166795. prep->next_buf_row += numrows;
  166796. prep->rows_to_go -= numrows;
  166797. /* If at bottom of image, pad to fill the conversion buffer. */
  166798. if (prep->rows_to_go == 0 &&
  166799. prep->next_buf_row < cinfo->max_v_samp_factor) {
  166800. for (ci = 0; ci < cinfo->num_components; ci++) {
  166801. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166802. prep->next_buf_row, cinfo->max_v_samp_factor);
  166803. }
  166804. prep->next_buf_row = cinfo->max_v_samp_factor;
  166805. }
  166806. /* If we've filled the conversion buffer, empty it. */
  166807. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  166808. (*cinfo->downsample->downsample) (cinfo,
  166809. prep->color_buf, (JDIMENSION) 0,
  166810. output_buf, *out_row_group_ctr);
  166811. prep->next_buf_row = 0;
  166812. (*out_row_group_ctr)++;
  166813. }
  166814. /* If at bottom of image, pad the output to a full iMCU height.
  166815. * Note we assume the caller is providing a one-iMCU-height output buffer!
  166816. */
  166817. if (prep->rows_to_go == 0 &&
  166818. *out_row_group_ctr < out_row_groups_avail) {
  166819. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166820. ci++, compptr++) {
  166821. expand_bottom_edge(output_buf[ci],
  166822. compptr->width_in_blocks * DCTSIZE,
  166823. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  166824. (int) (out_row_groups_avail * compptr->v_samp_factor));
  166825. }
  166826. *out_row_group_ctr = out_row_groups_avail;
  166827. break; /* can exit outer loop without test */
  166828. }
  166829. }
  166830. }
  166831. #ifdef CONTEXT_ROWS_SUPPORTED
  166832. /*
  166833. * Process some data in the context case.
  166834. */
  166835. METHODDEF(void)
  166836. pre_process_context (j_compress_ptr cinfo,
  166837. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  166838. JDIMENSION in_rows_avail,
  166839. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  166840. JDIMENSION out_row_groups_avail)
  166841. {
  166842. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166843. int numrows, ci;
  166844. int buf_height = cinfo->max_v_samp_factor * 3;
  166845. JDIMENSION inrows;
  166846. while (*out_row_group_ctr < out_row_groups_avail) {
  166847. if (*in_row_ctr < in_rows_avail) {
  166848. /* Do color conversion to fill the conversion buffer. */
  166849. inrows = in_rows_avail - *in_row_ctr;
  166850. numrows = prep->next_buf_stop - prep->next_buf_row;
  166851. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  166852. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  166853. prep->color_buf,
  166854. (JDIMENSION) prep->next_buf_row,
  166855. numrows);
  166856. /* Pad at top of image, if first time through */
  166857. if (prep->rows_to_go == cinfo->image_height) {
  166858. for (ci = 0; ci < cinfo->num_components; ci++) {
  166859. int row;
  166860. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  166861. jcopy_sample_rows(prep->color_buf[ci], 0,
  166862. prep->color_buf[ci], -row,
  166863. 1, cinfo->image_width);
  166864. }
  166865. }
  166866. }
  166867. *in_row_ctr += numrows;
  166868. prep->next_buf_row += numrows;
  166869. prep->rows_to_go -= numrows;
  166870. } else {
  166871. /* Return for more data, unless we are at the bottom of the image. */
  166872. if (prep->rows_to_go != 0)
  166873. break;
  166874. /* When at bottom of image, pad to fill the conversion buffer. */
  166875. if (prep->next_buf_row < prep->next_buf_stop) {
  166876. for (ci = 0; ci < cinfo->num_components; ci++) {
  166877. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  166878. prep->next_buf_row, prep->next_buf_stop);
  166879. }
  166880. prep->next_buf_row = prep->next_buf_stop;
  166881. }
  166882. }
  166883. /* If we've gotten enough data, downsample a row group. */
  166884. if (prep->next_buf_row == prep->next_buf_stop) {
  166885. (*cinfo->downsample->downsample) (cinfo,
  166886. prep->color_buf,
  166887. (JDIMENSION) prep->this_row_group,
  166888. output_buf, *out_row_group_ctr);
  166889. (*out_row_group_ctr)++;
  166890. /* Advance pointers with wraparound as necessary. */
  166891. prep->this_row_group += cinfo->max_v_samp_factor;
  166892. if (prep->this_row_group >= buf_height)
  166893. prep->this_row_group = 0;
  166894. if (prep->next_buf_row >= buf_height)
  166895. prep->next_buf_row = 0;
  166896. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  166897. }
  166898. }
  166899. }
  166900. /*
  166901. * Create the wrapped-around downsampling input buffer needed for context mode.
  166902. */
  166903. LOCAL(void)
  166904. create_context_buffer (j_compress_ptr cinfo)
  166905. {
  166906. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  166907. int rgroup_height = cinfo->max_v_samp_factor;
  166908. int ci, i;
  166909. jpeg_component_info * compptr;
  166910. JSAMPARRAY true_buffer, fake_buffer;
  166911. /* Grab enough space for fake row pointers for all the components;
  166912. * we need five row groups' worth of pointers for each component.
  166913. */
  166914. fake_buffer = (JSAMPARRAY)
  166915. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166916. (cinfo->num_components * 5 * rgroup_height) *
  166917. SIZEOF(JSAMPROW));
  166918. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166919. ci++, compptr++) {
  166920. /* Allocate the actual buffer space (3 row groups) for this component.
  166921. * We make the buffer wide enough to allow the downsampler to edge-expand
  166922. * horizontally within the buffer, if it so chooses.
  166923. */
  166924. true_buffer = (*cinfo->mem->alloc_sarray)
  166925. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166926. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166927. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166928. (JDIMENSION) (3 * rgroup_height));
  166929. /* Copy true buffer row pointers into the middle of the fake row array */
  166930. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  166931. 3 * rgroup_height * SIZEOF(JSAMPROW));
  166932. /* Fill in the above and below wraparound pointers */
  166933. for (i = 0; i < rgroup_height; i++) {
  166934. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  166935. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  166936. }
  166937. prep->color_buf[ci] = fake_buffer + rgroup_height;
  166938. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  166939. }
  166940. }
  166941. #endif /* CONTEXT_ROWS_SUPPORTED */
  166942. /*
  166943. * Initialize preprocessing controller.
  166944. */
  166945. GLOBAL(void)
  166946. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  166947. {
  166948. my_prep_ptr prep;
  166949. int ci;
  166950. jpeg_component_info * compptr;
  166951. if (need_full_buffer) /* safety check */
  166952. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  166953. prep = (my_prep_ptr)
  166954. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166955. SIZEOF(my_prep_controller));
  166956. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  166957. prep->pub.start_pass = start_pass_prep;
  166958. /* Allocate the color conversion buffer.
  166959. * We make the buffer wide enough to allow the downsampler to edge-expand
  166960. * horizontally within the buffer, if it so chooses.
  166961. */
  166962. if (cinfo->downsample->need_context_rows) {
  166963. /* Set up to provide context rows */
  166964. #ifdef CONTEXT_ROWS_SUPPORTED
  166965. prep->pub.pre_process_data = pre_process_context;
  166966. create_context_buffer(cinfo);
  166967. #else
  166968. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166969. #endif
  166970. } else {
  166971. /* No context, just make it tall enough for one row group */
  166972. prep->pub.pre_process_data = pre_process_data;
  166973. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  166974. ci++, compptr++) {
  166975. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  166976. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166977. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  166978. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  166979. (JDIMENSION) cinfo->max_v_samp_factor);
  166980. }
  166981. }
  166982. }
  166983. /*** End of inlined file: jcprepct.c ***/
  166984. /*** Start of inlined file: jcsample.c ***/
  166985. #define JPEG_INTERNALS
  166986. /* Pointer to routine to downsample a single component */
  166987. typedef JMETHOD(void, downsample1_ptr,
  166988. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  166989. JSAMPARRAY input_data, JSAMPARRAY output_data));
  166990. /* Private subobject */
  166991. typedef struct {
  166992. struct jpeg_downsampler pub; /* public fields */
  166993. /* Downsampling method pointers, one per component */
  166994. downsample1_ptr methods[MAX_COMPONENTS];
  166995. } my_downsampler;
  166996. typedef my_downsampler * my_downsample_ptr;
  166997. /*
  166998. * Initialize for a downsampling pass.
  166999. */
  167000. METHODDEF(void)
  167001. start_pass_downsample (j_compress_ptr)
  167002. {
  167003. /* no work for now */
  167004. }
  167005. /*
  167006. * Expand a component horizontally from width input_cols to width output_cols,
  167007. * by duplicating the rightmost samples.
  167008. */
  167009. LOCAL(void)
  167010. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  167011. JDIMENSION input_cols, JDIMENSION output_cols)
  167012. {
  167013. register JSAMPROW ptr;
  167014. register JSAMPLE pixval;
  167015. register int count;
  167016. int row;
  167017. int numcols = (int) (output_cols - input_cols);
  167018. if (numcols > 0) {
  167019. for (row = 0; row < num_rows; row++) {
  167020. ptr = image_data[row] + input_cols;
  167021. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  167022. for (count = numcols; count > 0; count--)
  167023. *ptr++ = pixval;
  167024. }
  167025. }
  167026. }
  167027. /*
  167028. * Do downsampling for a whole row group (all components).
  167029. *
  167030. * In this version we simply downsample each component independently.
  167031. */
  167032. METHODDEF(void)
  167033. sep_downsample (j_compress_ptr cinfo,
  167034. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167035. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167036. {
  167037. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167038. int ci;
  167039. jpeg_component_info * compptr;
  167040. JSAMPARRAY in_ptr, out_ptr;
  167041. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167042. ci++, compptr++) {
  167043. in_ptr = input_buf[ci] + in_row_index;
  167044. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167045. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167046. }
  167047. }
  167048. /*
  167049. * Downsample pixel values of a single component.
  167050. * One row group is processed per call.
  167051. * This version handles arbitrary integral sampling ratios, without smoothing.
  167052. * Note that this version is not actually used for customary sampling ratios.
  167053. */
  167054. METHODDEF(void)
  167055. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167056. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167057. {
  167058. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167059. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167060. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167061. JSAMPROW inptr, outptr;
  167062. INT32 outvalue;
  167063. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167064. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167065. numpix = h_expand * v_expand;
  167066. numpix2 = numpix/2;
  167067. /* Expand input data enough to let all the output samples be generated
  167068. * by the standard loop. Special-casing padded output would be more
  167069. * efficient.
  167070. */
  167071. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167072. cinfo->image_width, output_cols * h_expand);
  167073. inrow = 0;
  167074. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167075. outptr = output_data[outrow];
  167076. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167077. outcol++, outcol_h += h_expand) {
  167078. outvalue = 0;
  167079. for (v = 0; v < v_expand; v++) {
  167080. inptr = input_data[inrow+v] + outcol_h;
  167081. for (h = 0; h < h_expand; h++) {
  167082. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167083. }
  167084. }
  167085. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167086. }
  167087. inrow += v_expand;
  167088. }
  167089. }
  167090. /*
  167091. * Downsample pixel values of a single component.
  167092. * This version handles the special case of a full-size component,
  167093. * without smoothing.
  167094. */
  167095. METHODDEF(void)
  167096. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167097. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167098. {
  167099. /* Copy the data */
  167100. jcopy_sample_rows(input_data, 0, output_data, 0,
  167101. cinfo->max_v_samp_factor, cinfo->image_width);
  167102. /* Edge-expand */
  167103. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167104. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167105. }
  167106. /*
  167107. * Downsample pixel values of a single component.
  167108. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167109. * without smoothing.
  167110. *
  167111. * A note about the "bias" calculations: when rounding fractional values to
  167112. * integer, we do not want to always round 0.5 up to the next integer.
  167113. * If we did that, we'd introduce a noticeable bias towards larger values.
  167114. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167115. * alternate pixel locations (a simple ordered dither pattern).
  167116. */
  167117. METHODDEF(void)
  167118. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167119. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167120. {
  167121. int outrow;
  167122. JDIMENSION outcol;
  167123. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167124. register JSAMPROW inptr, outptr;
  167125. register int bias;
  167126. /* Expand input data enough to let all the output samples be generated
  167127. * by the standard loop. Special-casing padded output would be more
  167128. * efficient.
  167129. */
  167130. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167131. cinfo->image_width, output_cols * 2);
  167132. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167133. outptr = output_data[outrow];
  167134. inptr = input_data[outrow];
  167135. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167136. for (outcol = 0; outcol < output_cols; outcol++) {
  167137. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167138. + bias) >> 1);
  167139. bias ^= 1; /* 0=>1, 1=>0 */
  167140. inptr += 2;
  167141. }
  167142. }
  167143. }
  167144. /*
  167145. * Downsample pixel values of a single component.
  167146. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167147. * without smoothing.
  167148. */
  167149. METHODDEF(void)
  167150. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167151. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167152. {
  167153. int inrow, outrow;
  167154. JDIMENSION outcol;
  167155. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167156. register JSAMPROW inptr0, inptr1, outptr;
  167157. register int bias;
  167158. /* Expand input data enough to let all the output samples be generated
  167159. * by the standard loop. Special-casing padded output would be more
  167160. * efficient.
  167161. */
  167162. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167163. cinfo->image_width, output_cols * 2);
  167164. inrow = 0;
  167165. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167166. outptr = output_data[outrow];
  167167. inptr0 = input_data[inrow];
  167168. inptr1 = input_data[inrow+1];
  167169. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167170. for (outcol = 0; outcol < output_cols; outcol++) {
  167171. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167172. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167173. + bias) >> 2);
  167174. bias ^= 3; /* 1=>2, 2=>1 */
  167175. inptr0 += 2; inptr1 += 2;
  167176. }
  167177. inrow += 2;
  167178. }
  167179. }
  167180. #ifdef INPUT_SMOOTHING_SUPPORTED
  167181. /*
  167182. * Downsample pixel values of a single component.
  167183. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167184. * with smoothing. One row of context is required.
  167185. */
  167186. METHODDEF(void)
  167187. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167188. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167189. {
  167190. int inrow, outrow;
  167191. JDIMENSION colctr;
  167192. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167193. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167194. INT32 membersum, neighsum, memberscale, neighscale;
  167195. /* Expand input data enough to let all the output samples be generated
  167196. * by the standard loop. Special-casing padded output would be more
  167197. * efficient.
  167198. */
  167199. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167200. cinfo->image_width, output_cols * 2);
  167201. /* We don't bother to form the individual "smoothed" input pixel values;
  167202. * we can directly compute the output which is the average of the four
  167203. * smoothed values. Each of the four member pixels contributes a fraction
  167204. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167205. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167206. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167207. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167208. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167209. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167210. * factors are scaled by 2^16 = 65536.
  167211. * Also recall that SF = smoothing_factor / 1024.
  167212. */
  167213. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167214. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167215. inrow = 0;
  167216. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167217. outptr = output_data[outrow];
  167218. inptr0 = input_data[inrow];
  167219. inptr1 = input_data[inrow+1];
  167220. above_ptr = input_data[inrow-1];
  167221. below_ptr = input_data[inrow+2];
  167222. /* Special case for first column: pretend column -1 is same as column 0 */
  167223. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167224. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167225. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167226. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167227. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  167228. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  167229. neighsum += neighsum;
  167230. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  167231. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  167232. membersum = membersum * memberscale + neighsum * neighscale;
  167233. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167234. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167235. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167236. /* sum of pixels directly mapped to this output element */
  167237. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167238. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167239. /* sum of edge-neighbor pixels */
  167240. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167241. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167242. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  167243. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  167244. /* The edge-neighbors count twice as much as corner-neighbors */
  167245. neighsum += neighsum;
  167246. /* Add in the corner-neighbors */
  167247. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  167248. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  167249. /* form final output scaled up by 2^16 */
  167250. membersum = membersum * memberscale + neighsum * neighscale;
  167251. /* round, descale and output it */
  167252. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167253. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  167254. }
  167255. /* Special case for last column */
  167256. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167257. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167258. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167259. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167260. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  167261. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  167262. neighsum += neighsum;
  167263. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  167264. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  167265. membersum = membersum * memberscale + neighsum * neighscale;
  167266. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167267. inrow += 2;
  167268. }
  167269. }
  167270. /*
  167271. * Downsample pixel values of a single component.
  167272. * This version handles the special case of a full-size component,
  167273. * with smoothing. One row of context is required.
  167274. */
  167275. METHODDEF(void)
  167276. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  167277. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167278. {
  167279. int outrow;
  167280. JDIMENSION colctr;
  167281. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167282. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  167283. INT32 membersum, neighsum, memberscale, neighscale;
  167284. int colsum, lastcolsum, nextcolsum;
  167285. /* Expand input data enough to let all the output samples be generated
  167286. * by the standard loop. Special-casing padded output would be more
  167287. * efficient.
  167288. */
  167289. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167290. cinfo->image_width, output_cols);
  167291. /* Each of the eight neighbor pixels contributes a fraction SF to the
  167292. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  167293. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  167294. * Also recall that SF = smoothing_factor / 1024.
  167295. */
  167296. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  167297. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  167298. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167299. outptr = output_data[outrow];
  167300. inptr = input_data[outrow];
  167301. above_ptr = input_data[outrow-1];
  167302. below_ptr = input_data[outrow+1];
  167303. /* Special case for first column */
  167304. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  167305. GETJSAMPLE(*inptr);
  167306. membersum = GETJSAMPLE(*inptr++);
  167307. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167308. GETJSAMPLE(*inptr);
  167309. neighsum = colsum + (colsum - membersum) + nextcolsum;
  167310. membersum = membersum * memberscale + neighsum * neighscale;
  167311. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167312. lastcolsum = colsum; colsum = nextcolsum;
  167313. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  167314. membersum = GETJSAMPLE(*inptr++);
  167315. above_ptr++; below_ptr++;
  167316. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  167317. GETJSAMPLE(*inptr);
  167318. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  167319. membersum = membersum * memberscale + neighsum * neighscale;
  167320. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  167321. lastcolsum = colsum; colsum = nextcolsum;
  167322. }
  167323. /* Special case for last column */
  167324. membersum = GETJSAMPLE(*inptr);
  167325. neighsum = lastcolsum + (colsum - membersum) + colsum;
  167326. membersum = membersum * memberscale + neighsum * neighscale;
  167327. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  167328. }
  167329. }
  167330. #endif /* INPUT_SMOOTHING_SUPPORTED */
  167331. /*
  167332. * Module initialization routine for downsampling.
  167333. * Note that we must select a routine for each component.
  167334. */
  167335. GLOBAL(void)
  167336. jinit_downsampler (j_compress_ptr cinfo)
  167337. {
  167338. my_downsample_ptr downsample;
  167339. int ci;
  167340. jpeg_component_info * compptr;
  167341. boolean smoothok = TRUE;
  167342. downsample = (my_downsample_ptr)
  167343. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167344. SIZEOF(my_downsampler));
  167345. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  167346. downsample->pub.start_pass = start_pass_downsample;
  167347. downsample->pub.downsample = sep_downsample;
  167348. downsample->pub.need_context_rows = FALSE;
  167349. if (cinfo->CCIR601_sampling)
  167350. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  167351. /* Verify we can handle the sampling factors, and set up method pointers */
  167352. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167353. ci++, compptr++) {
  167354. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  167355. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167356. #ifdef INPUT_SMOOTHING_SUPPORTED
  167357. if (cinfo->smoothing_factor) {
  167358. downsample->methods[ci] = fullsize_smooth_downsample;
  167359. downsample->pub.need_context_rows = TRUE;
  167360. } else
  167361. #endif
  167362. downsample->methods[ci] = fullsize_downsample;
  167363. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167364. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  167365. smoothok = FALSE;
  167366. downsample->methods[ci] = h2v1_downsample;
  167367. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  167368. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  167369. #ifdef INPUT_SMOOTHING_SUPPORTED
  167370. if (cinfo->smoothing_factor) {
  167371. downsample->methods[ci] = h2v2_smooth_downsample;
  167372. downsample->pub.need_context_rows = TRUE;
  167373. } else
  167374. #endif
  167375. downsample->methods[ci] = h2v2_downsample;
  167376. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  167377. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  167378. smoothok = FALSE;
  167379. downsample->methods[ci] = int_downsample;
  167380. } else
  167381. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  167382. }
  167383. #ifdef INPUT_SMOOTHING_SUPPORTED
  167384. if (cinfo->smoothing_factor && !smoothok)
  167385. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  167386. #endif
  167387. }
  167388. /*** End of inlined file: jcsample.c ***/
  167389. /*** Start of inlined file: jctrans.c ***/
  167390. #define JPEG_INTERNALS
  167391. /* Forward declarations */
  167392. LOCAL(void) transencode_master_selection
  167393. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167394. LOCAL(void) transencode_coef_controller
  167395. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  167396. /*
  167397. * Compression initialization for writing raw-coefficient data.
  167398. * Before calling this, all parameters and a data destination must be set up.
  167399. * Call jpeg_finish_compress() to actually write the data.
  167400. *
  167401. * The number of passed virtual arrays must match cinfo->num_components.
  167402. * Note that the virtual arrays need not be filled or even realized at
  167403. * the time write_coefficients is called; indeed, if the virtual arrays
  167404. * were requested from this compression object's memory manager, they
  167405. * typically will be realized during this routine and filled afterwards.
  167406. */
  167407. GLOBAL(void)
  167408. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  167409. {
  167410. if (cinfo->global_state != CSTATE_START)
  167411. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167412. /* Mark all tables to be written */
  167413. jpeg_suppress_tables(cinfo, FALSE);
  167414. /* (Re)initialize error mgr and destination modules */
  167415. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  167416. (*cinfo->dest->init_destination) (cinfo);
  167417. /* Perform master selection of active modules */
  167418. transencode_master_selection(cinfo, coef_arrays);
  167419. /* Wait for jpeg_finish_compress() call */
  167420. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  167421. cinfo->global_state = CSTATE_WRCOEFS;
  167422. }
  167423. /*
  167424. * Initialize the compression object with default parameters,
  167425. * then copy from the source object all parameters needed for lossless
  167426. * transcoding. Parameters that can be varied without loss (such as
  167427. * scan script and Huffman optimization) are left in their default states.
  167428. */
  167429. GLOBAL(void)
  167430. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  167431. j_compress_ptr dstinfo)
  167432. {
  167433. JQUANT_TBL ** qtblptr;
  167434. jpeg_component_info *incomp, *outcomp;
  167435. JQUANT_TBL *c_quant, *slot_quant;
  167436. int tblno, ci, coefi;
  167437. /* Safety check to ensure start_compress not called yet. */
  167438. if (dstinfo->global_state != CSTATE_START)
  167439. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  167440. /* Copy fundamental image dimensions */
  167441. dstinfo->image_width = srcinfo->image_width;
  167442. dstinfo->image_height = srcinfo->image_height;
  167443. dstinfo->input_components = srcinfo->num_components;
  167444. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  167445. /* Initialize all parameters to default values */
  167446. jpeg_set_defaults(dstinfo);
  167447. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  167448. * Fix it to get the right header markers for the image colorspace.
  167449. */
  167450. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  167451. dstinfo->data_precision = srcinfo->data_precision;
  167452. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  167453. /* Copy the source's quantization tables. */
  167454. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  167455. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  167456. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  167457. if (*qtblptr == NULL)
  167458. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  167459. MEMCOPY((*qtblptr)->quantval,
  167460. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  167461. SIZEOF((*qtblptr)->quantval));
  167462. (*qtblptr)->sent_table = FALSE;
  167463. }
  167464. }
  167465. /* Copy the source's per-component info.
  167466. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  167467. */
  167468. dstinfo->num_components = srcinfo->num_components;
  167469. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  167470. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  167471. MAX_COMPONENTS);
  167472. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  167473. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  167474. outcomp->component_id = incomp->component_id;
  167475. outcomp->h_samp_factor = incomp->h_samp_factor;
  167476. outcomp->v_samp_factor = incomp->v_samp_factor;
  167477. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  167478. /* Make sure saved quantization table for component matches the qtable
  167479. * slot. If not, the input file re-used this qtable slot.
  167480. * IJG encoder currently cannot duplicate this.
  167481. */
  167482. tblno = outcomp->quant_tbl_no;
  167483. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  167484. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  167485. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  167486. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  167487. c_quant = incomp->quant_table;
  167488. if (c_quant != NULL) {
  167489. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  167490. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  167491. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  167492. }
  167493. }
  167494. /* Note: we do not copy the source's Huffman table assignments;
  167495. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  167496. */
  167497. }
  167498. /* Also copy JFIF version and resolution information, if available.
  167499. * Strictly speaking this isn't "critical" info, but it's nearly
  167500. * always appropriate to copy it if available. In particular,
  167501. * if the application chooses to copy JFIF 1.02 extension markers from
  167502. * the source file, we need to copy the version to make sure we don't
  167503. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  167504. * We will *not*, however, copy version info from mislabeled "2.01" files.
  167505. */
  167506. if (srcinfo->saw_JFIF_marker) {
  167507. if (srcinfo->JFIF_major_version == 1) {
  167508. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  167509. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  167510. }
  167511. dstinfo->density_unit = srcinfo->density_unit;
  167512. dstinfo->X_density = srcinfo->X_density;
  167513. dstinfo->Y_density = srcinfo->Y_density;
  167514. }
  167515. }
  167516. /*
  167517. * Master selection of compression modules for transcoding.
  167518. * This substitutes for jcinit.c's initialization of the full compressor.
  167519. */
  167520. LOCAL(void)
  167521. transencode_master_selection (j_compress_ptr cinfo,
  167522. jvirt_barray_ptr * coef_arrays)
  167523. {
  167524. /* Although we don't actually use input_components for transcoding,
  167525. * jcmaster.c's initial_setup will complain if input_components is 0.
  167526. */
  167527. cinfo->input_components = 1;
  167528. /* Initialize master control (includes parameter checking/processing) */
  167529. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  167530. /* Entropy encoding: either Huffman or arithmetic coding. */
  167531. if (cinfo->arith_code) {
  167532. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  167533. } else {
  167534. if (cinfo->progressive_mode) {
  167535. #ifdef C_PROGRESSIVE_SUPPORTED
  167536. jinit_phuff_encoder(cinfo);
  167537. #else
  167538. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167539. #endif
  167540. } else
  167541. jinit_huff_encoder(cinfo);
  167542. }
  167543. /* We need a special coefficient buffer controller. */
  167544. transencode_coef_controller(cinfo, coef_arrays);
  167545. jinit_marker_writer(cinfo);
  167546. /* We can now tell the memory manager to allocate virtual arrays. */
  167547. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  167548. /* Write the datastream header (SOI, JFIF) immediately.
  167549. * Frame and scan headers are postponed till later.
  167550. * This lets application insert special markers after the SOI.
  167551. */
  167552. (*cinfo->marker->write_file_header) (cinfo);
  167553. }
  167554. /*
  167555. * The rest of this file is a special implementation of the coefficient
  167556. * buffer controller. This is similar to jccoefct.c, but it handles only
  167557. * output from presupplied virtual arrays. Furthermore, we generate any
  167558. * dummy padding blocks on-the-fly rather than expecting them to be present
  167559. * in the arrays.
  167560. */
  167561. /* Private buffer controller object */
  167562. typedef struct {
  167563. struct jpeg_c_coef_controller pub; /* public fields */
  167564. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  167565. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  167566. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  167567. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  167568. /* Virtual block array for each component. */
  167569. jvirt_barray_ptr * whole_image;
  167570. /* Workspace for constructing dummy blocks at right/bottom edges. */
  167571. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  167572. } my_coef_controller2;
  167573. typedef my_coef_controller2 * my_coef_ptr2;
  167574. LOCAL(void)
  167575. start_iMCU_row2 (j_compress_ptr cinfo)
  167576. /* Reset within-iMCU-row counters for a new row */
  167577. {
  167578. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167579. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  167580. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  167581. * But at the bottom of the image, process only what's left.
  167582. */
  167583. if (cinfo->comps_in_scan > 1) {
  167584. coef->MCU_rows_per_iMCU_row = 1;
  167585. } else {
  167586. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  167587. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  167588. else
  167589. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  167590. }
  167591. coef->mcu_ctr = 0;
  167592. coef->MCU_vert_offset = 0;
  167593. }
  167594. /*
  167595. * Initialize for a processing pass.
  167596. */
  167597. METHODDEF(void)
  167598. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167599. {
  167600. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167601. if (pass_mode != JBUF_CRANK_DEST)
  167602. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167603. coef->iMCU_row_num = 0;
  167604. start_iMCU_row2(cinfo);
  167605. }
  167606. /*
  167607. * Process some data.
  167608. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  167609. * per call, ie, v_samp_factor block rows for each component in the scan.
  167610. * The data is obtained from the virtual arrays and fed to the entropy coder.
  167611. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  167612. *
  167613. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  167614. */
  167615. METHODDEF(boolean)
  167616. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE)
  167617. {
  167618. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  167619. JDIMENSION MCU_col_num; /* index of current MCU within row */
  167620. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  167621. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  167622. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  167623. JDIMENSION start_col;
  167624. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  167625. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  167626. JBLOCKROW buffer_ptr;
  167627. jpeg_component_info *compptr;
  167628. /* Align the virtual buffers for the components used in this scan. */
  167629. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167630. compptr = cinfo->cur_comp_info[ci];
  167631. buffer[ci] = (*cinfo->mem->access_virt_barray)
  167632. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  167633. coef->iMCU_row_num * compptr->v_samp_factor,
  167634. (JDIMENSION) compptr->v_samp_factor, FALSE);
  167635. }
  167636. /* Loop to process one whole iMCU row */
  167637. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  167638. yoffset++) {
  167639. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  167640. MCU_col_num++) {
  167641. /* Construct list of pointers to DCT blocks belonging to this MCU */
  167642. blkn = 0; /* index of current DCT block within MCU */
  167643. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167644. compptr = cinfo->cur_comp_info[ci];
  167645. start_col = MCU_col_num * compptr->MCU_width;
  167646. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  167647. : compptr->last_col_width;
  167648. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  167649. if (coef->iMCU_row_num < last_iMCU_row ||
  167650. yindex+yoffset < compptr->last_row_height) {
  167651. /* Fill in pointers to real blocks in this row */
  167652. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  167653. for (xindex = 0; xindex < blockcnt; xindex++)
  167654. MCU_buffer[blkn++] = buffer_ptr++;
  167655. } else {
  167656. /* At bottom of image, need a whole row of dummy blocks */
  167657. xindex = 0;
  167658. }
  167659. /* Fill in any dummy blocks needed in this row.
  167660. * Dummy blocks are filled in the same way as in jccoefct.c:
  167661. * all zeroes in the AC entries, DC entries equal to previous
  167662. * block's DC value. The init routine has already zeroed the
  167663. * AC entries, so we need only set the DC entries correctly.
  167664. */
  167665. for (; xindex < compptr->MCU_width; xindex++) {
  167666. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  167667. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  167668. blkn++;
  167669. }
  167670. }
  167671. }
  167672. /* Try to write the MCU. */
  167673. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  167674. /* Suspension forced; update state counters and exit */
  167675. coef->MCU_vert_offset = yoffset;
  167676. coef->mcu_ctr = MCU_col_num;
  167677. return FALSE;
  167678. }
  167679. }
  167680. /* Completed an MCU row, but perhaps not an iMCU row */
  167681. coef->mcu_ctr = 0;
  167682. }
  167683. /* Completed the iMCU row, advance counters for next one */
  167684. coef->iMCU_row_num++;
  167685. start_iMCU_row2(cinfo);
  167686. return TRUE;
  167687. }
  167688. /*
  167689. * Initialize coefficient buffer controller.
  167690. *
  167691. * Each passed coefficient array must be the right size for that
  167692. * coefficient: width_in_blocks wide and height_in_blocks high,
  167693. * with unitheight at least v_samp_factor.
  167694. */
  167695. LOCAL(void)
  167696. transencode_coef_controller (j_compress_ptr cinfo,
  167697. jvirt_barray_ptr * coef_arrays)
  167698. {
  167699. my_coef_ptr2 coef;
  167700. JBLOCKROW buffer;
  167701. int i;
  167702. coef = (my_coef_ptr2)
  167703. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167704. SIZEOF(my_coef_controller2));
  167705. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  167706. coef->pub.start_pass = start_pass_coef2;
  167707. coef->pub.compress_data = compress_output2;
  167708. /* Save pointer to virtual arrays */
  167709. coef->whole_image = coef_arrays;
  167710. /* Allocate and pre-zero space for dummy DCT blocks. */
  167711. buffer = (JBLOCKROW)
  167712. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167713. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167714. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  167715. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  167716. coef->dummy_buffer[i] = buffer + i;
  167717. }
  167718. }
  167719. /*** End of inlined file: jctrans.c ***/
  167720. /*** Start of inlined file: jdapistd.c ***/
  167721. #define JPEG_INTERNALS
  167722. /* Forward declarations */
  167723. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  167724. /*
  167725. * Decompression initialization.
  167726. * jpeg_read_header must be completed before calling this.
  167727. *
  167728. * If a multipass operating mode was selected, this will do all but the
  167729. * last pass, and thus may take a great deal of time.
  167730. *
  167731. * Returns FALSE if suspended. The return value need be inspected only if
  167732. * a suspending data source is used.
  167733. */
  167734. GLOBAL(boolean)
  167735. jpeg_start_decompress (j_decompress_ptr cinfo)
  167736. {
  167737. if (cinfo->global_state == DSTATE_READY) {
  167738. /* First call: initialize master control, select active modules */
  167739. jinit_master_decompress(cinfo);
  167740. if (cinfo->buffered_image) {
  167741. /* No more work here; expecting jpeg_start_output next */
  167742. cinfo->global_state = DSTATE_BUFIMAGE;
  167743. return TRUE;
  167744. }
  167745. cinfo->global_state = DSTATE_PRELOAD;
  167746. }
  167747. if (cinfo->global_state == DSTATE_PRELOAD) {
  167748. /* If file has multiple scans, absorb them all into the coef buffer */
  167749. if (cinfo->inputctl->has_multiple_scans) {
  167750. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167751. for (;;) {
  167752. int retcode;
  167753. /* Call progress monitor hook if present */
  167754. if (cinfo->progress != NULL)
  167755. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167756. /* Absorb some more input */
  167757. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  167758. if (retcode == JPEG_SUSPENDED)
  167759. return FALSE;
  167760. if (retcode == JPEG_REACHED_EOI)
  167761. break;
  167762. /* Advance progress counter if appropriate */
  167763. if (cinfo->progress != NULL &&
  167764. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  167765. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  167766. /* jdmaster underestimated number of scans; ratchet up one scan */
  167767. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  167768. }
  167769. }
  167770. }
  167771. #else
  167772. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167773. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167774. }
  167775. cinfo->output_scan_number = cinfo->input_scan_number;
  167776. } else if (cinfo->global_state != DSTATE_PRESCAN)
  167777. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167778. /* Perform any dummy output passes, and set up for the final pass */
  167779. return output_pass_setup(cinfo);
  167780. }
  167781. /*
  167782. * Set up for an output pass, and perform any dummy pass(es) needed.
  167783. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  167784. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  167785. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  167786. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  167787. */
  167788. LOCAL(boolean)
  167789. output_pass_setup (j_decompress_ptr cinfo)
  167790. {
  167791. if (cinfo->global_state != DSTATE_PRESCAN) {
  167792. /* First call: do pass setup */
  167793. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167794. cinfo->output_scanline = 0;
  167795. cinfo->global_state = DSTATE_PRESCAN;
  167796. }
  167797. /* Loop over any required dummy passes */
  167798. while (cinfo->master->is_dummy_pass) {
  167799. #ifdef QUANT_2PASS_SUPPORTED
  167800. /* Crank through the dummy pass */
  167801. while (cinfo->output_scanline < cinfo->output_height) {
  167802. JDIMENSION last_scanline;
  167803. /* Call progress monitor hook if present */
  167804. if (cinfo->progress != NULL) {
  167805. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167806. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167807. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167808. }
  167809. /* Process some data */
  167810. last_scanline = cinfo->output_scanline;
  167811. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  167812. &cinfo->output_scanline, (JDIMENSION) 0);
  167813. if (cinfo->output_scanline == last_scanline)
  167814. return FALSE; /* No progress made, must suspend */
  167815. }
  167816. /* Finish up dummy pass, and set up for another one */
  167817. (*cinfo->master->finish_output_pass) (cinfo);
  167818. (*cinfo->master->prepare_for_output_pass) (cinfo);
  167819. cinfo->output_scanline = 0;
  167820. #else
  167821. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167822. #endif /* QUANT_2PASS_SUPPORTED */
  167823. }
  167824. /* Ready for application to drive output pass through
  167825. * jpeg_read_scanlines or jpeg_read_raw_data.
  167826. */
  167827. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  167828. return TRUE;
  167829. }
  167830. /*
  167831. * Read some scanlines of data from the JPEG decompressor.
  167832. *
  167833. * The return value will be the number of lines actually read.
  167834. * This may be less than the number requested in several cases,
  167835. * including bottom of image, data source suspension, and operating
  167836. * modes that emit multiple scanlines at a time.
  167837. *
  167838. * Note: we warn about excess calls to jpeg_read_scanlines() since
  167839. * this likely signals an application programmer error. However,
  167840. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  167841. */
  167842. GLOBAL(JDIMENSION)
  167843. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  167844. JDIMENSION max_lines)
  167845. {
  167846. JDIMENSION row_ctr;
  167847. if (cinfo->global_state != DSTATE_SCANNING)
  167848. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167849. if (cinfo->output_scanline >= cinfo->output_height) {
  167850. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167851. return 0;
  167852. }
  167853. /* Call progress monitor hook if present */
  167854. if (cinfo->progress != NULL) {
  167855. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167856. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167857. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167858. }
  167859. /* Process some data */
  167860. row_ctr = 0;
  167861. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  167862. cinfo->output_scanline += row_ctr;
  167863. return row_ctr;
  167864. }
  167865. /*
  167866. * Alternate entry point to read raw data.
  167867. * Processes exactly one iMCU row per call, unless suspended.
  167868. */
  167869. GLOBAL(JDIMENSION)
  167870. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  167871. JDIMENSION max_lines)
  167872. {
  167873. JDIMENSION lines_per_iMCU_row;
  167874. if (cinfo->global_state != DSTATE_RAW_OK)
  167875. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167876. if (cinfo->output_scanline >= cinfo->output_height) {
  167877. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  167878. return 0;
  167879. }
  167880. /* Call progress monitor hook if present */
  167881. if (cinfo->progress != NULL) {
  167882. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  167883. cinfo->progress->pass_limit = (long) cinfo->output_height;
  167884. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  167885. }
  167886. /* Verify that at least one iMCU row can be returned. */
  167887. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  167888. if (max_lines < lines_per_iMCU_row)
  167889. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  167890. /* Decompress directly into user's buffer. */
  167891. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  167892. return 0; /* suspension forced, can do nothing more */
  167893. /* OK, we processed one iMCU row. */
  167894. cinfo->output_scanline += lines_per_iMCU_row;
  167895. return lines_per_iMCU_row;
  167896. }
  167897. /* Additional entry points for buffered-image mode. */
  167898. #ifdef D_MULTISCAN_FILES_SUPPORTED
  167899. /*
  167900. * Initialize for an output pass in buffered-image mode.
  167901. */
  167902. GLOBAL(boolean)
  167903. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  167904. {
  167905. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  167906. cinfo->global_state != DSTATE_PRESCAN)
  167907. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167908. /* Limit scan number to valid range */
  167909. if (scan_number <= 0)
  167910. scan_number = 1;
  167911. if (cinfo->inputctl->eoi_reached &&
  167912. scan_number > cinfo->input_scan_number)
  167913. scan_number = cinfo->input_scan_number;
  167914. cinfo->output_scan_number = scan_number;
  167915. /* Perform any dummy output passes, and set up for the real pass */
  167916. return output_pass_setup(cinfo);
  167917. }
  167918. /*
  167919. * Finish up after an output pass in buffered-image mode.
  167920. *
  167921. * Returns FALSE if suspended. The return value need be inspected only if
  167922. * a suspending data source is used.
  167923. */
  167924. GLOBAL(boolean)
  167925. jpeg_finish_output (j_decompress_ptr cinfo)
  167926. {
  167927. if ((cinfo->global_state == DSTATE_SCANNING ||
  167928. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  167929. /* Terminate this pass. */
  167930. /* We do not require the whole pass to have been completed. */
  167931. (*cinfo->master->finish_output_pass) (cinfo);
  167932. cinfo->global_state = DSTATE_BUFPOST;
  167933. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  167934. /* BUFPOST = repeat call after a suspension, anything else is error */
  167935. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  167936. }
  167937. /* Read markers looking for SOS or EOI */
  167938. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  167939. ! cinfo->inputctl->eoi_reached) {
  167940. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  167941. return FALSE; /* Suspend, come back later */
  167942. }
  167943. cinfo->global_state = DSTATE_BUFIMAGE;
  167944. return TRUE;
  167945. }
  167946. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  167947. /*** End of inlined file: jdapistd.c ***/
  167948. /*** Start of inlined file: jdapimin.c ***/
  167949. #define JPEG_INTERNALS
  167950. /*
  167951. * Initialization of a JPEG decompression object.
  167952. * The error manager must already be set up (in case memory manager fails).
  167953. */
  167954. GLOBAL(void)
  167955. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  167956. {
  167957. int i;
  167958. /* Guard against version mismatches between library and caller. */
  167959. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  167960. if (version != JPEG_LIB_VERSION)
  167961. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  167962. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  167963. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  167964. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  167965. /* For debugging purposes, we zero the whole master structure.
  167966. * But the application has already set the err pointer, and may have set
  167967. * client_data, so we have to save and restore those fields.
  167968. * Note: if application hasn't set client_data, tools like Purify may
  167969. * complain here.
  167970. */
  167971. {
  167972. struct jpeg_error_mgr * err = cinfo->err;
  167973. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  167974. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  167975. cinfo->err = err;
  167976. cinfo->client_data = client_data;
  167977. }
  167978. cinfo->is_decompressor = TRUE;
  167979. /* Initialize a memory manager instance for this object */
  167980. jinit_memory_mgr((j_common_ptr) cinfo);
  167981. /* Zero out pointers to permanent structures. */
  167982. cinfo->progress = NULL;
  167983. cinfo->src = NULL;
  167984. for (i = 0; i < NUM_QUANT_TBLS; i++)
  167985. cinfo->quant_tbl_ptrs[i] = NULL;
  167986. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167987. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  167988. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  167989. }
  167990. /* Initialize marker processor so application can override methods
  167991. * for COM, APPn markers before calling jpeg_read_header.
  167992. */
  167993. cinfo->marker_list = NULL;
  167994. jinit_marker_reader(cinfo);
  167995. /* And initialize the overall input controller. */
  167996. jinit_input_controller(cinfo);
  167997. /* OK, I'm ready */
  167998. cinfo->global_state = DSTATE_START;
  167999. }
  168000. /*
  168001. * Destruction of a JPEG decompression object
  168002. */
  168003. GLOBAL(void)
  168004. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  168005. {
  168006. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  168007. }
  168008. /*
  168009. * Abort processing of a JPEG decompression operation,
  168010. * but don't destroy the object itself.
  168011. */
  168012. GLOBAL(void)
  168013. jpeg_abort_decompress (j_decompress_ptr cinfo)
  168014. {
  168015. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  168016. }
  168017. /*
  168018. * Set default decompression parameters.
  168019. */
  168020. LOCAL(void)
  168021. default_decompress_parms (j_decompress_ptr cinfo)
  168022. {
  168023. /* Guess the input colorspace, and set output colorspace accordingly. */
  168024. /* (Wish JPEG committee had provided a real way to specify this...) */
  168025. /* Note application may override our guesses. */
  168026. switch (cinfo->num_components) {
  168027. case 1:
  168028. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  168029. cinfo->out_color_space = JCS_GRAYSCALE;
  168030. break;
  168031. case 3:
  168032. if (cinfo->saw_JFIF_marker) {
  168033. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168034. } else if (cinfo->saw_Adobe_marker) {
  168035. switch (cinfo->Adobe_transform) {
  168036. case 0:
  168037. cinfo->jpeg_color_space = JCS_RGB;
  168038. break;
  168039. case 1:
  168040. cinfo->jpeg_color_space = JCS_YCbCr;
  168041. break;
  168042. default:
  168043. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168044. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168045. break;
  168046. }
  168047. } else {
  168048. /* Saw no special markers, try to guess from the component IDs */
  168049. int cid0 = cinfo->comp_info[0].component_id;
  168050. int cid1 = cinfo->comp_info[1].component_id;
  168051. int cid2 = cinfo->comp_info[2].component_id;
  168052. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168053. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168054. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168055. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168056. else {
  168057. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168058. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168059. }
  168060. }
  168061. /* Always guess RGB is proper output colorspace. */
  168062. cinfo->out_color_space = JCS_RGB;
  168063. break;
  168064. case 4:
  168065. if (cinfo->saw_Adobe_marker) {
  168066. switch (cinfo->Adobe_transform) {
  168067. case 0:
  168068. cinfo->jpeg_color_space = JCS_CMYK;
  168069. break;
  168070. case 2:
  168071. cinfo->jpeg_color_space = JCS_YCCK;
  168072. break;
  168073. default:
  168074. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168075. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168076. break;
  168077. }
  168078. } else {
  168079. /* No special markers, assume straight CMYK. */
  168080. cinfo->jpeg_color_space = JCS_CMYK;
  168081. }
  168082. cinfo->out_color_space = JCS_CMYK;
  168083. break;
  168084. default:
  168085. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168086. cinfo->out_color_space = JCS_UNKNOWN;
  168087. break;
  168088. }
  168089. /* Set defaults for other decompression parameters. */
  168090. cinfo->scale_num = 1; /* 1:1 scaling */
  168091. cinfo->scale_denom = 1;
  168092. cinfo->output_gamma = 1.0;
  168093. cinfo->buffered_image = FALSE;
  168094. cinfo->raw_data_out = FALSE;
  168095. cinfo->dct_method = JDCT_DEFAULT;
  168096. cinfo->do_fancy_upsampling = TRUE;
  168097. cinfo->do_block_smoothing = TRUE;
  168098. cinfo->quantize_colors = FALSE;
  168099. /* We set these in case application only sets quantize_colors. */
  168100. cinfo->dither_mode = JDITHER_FS;
  168101. #ifdef QUANT_2PASS_SUPPORTED
  168102. cinfo->two_pass_quantize = TRUE;
  168103. #else
  168104. cinfo->two_pass_quantize = FALSE;
  168105. #endif
  168106. cinfo->desired_number_of_colors = 256;
  168107. cinfo->colormap = NULL;
  168108. /* Initialize for no mode change in buffered-image mode. */
  168109. cinfo->enable_1pass_quant = FALSE;
  168110. cinfo->enable_external_quant = FALSE;
  168111. cinfo->enable_2pass_quant = FALSE;
  168112. }
  168113. /*
  168114. * Decompression startup: read start of JPEG datastream to see what's there.
  168115. * Need only initialize JPEG object and supply a data source before calling.
  168116. *
  168117. * This routine will read as far as the first SOS marker (ie, actual start of
  168118. * compressed data), and will save all tables and parameters in the JPEG
  168119. * object. It will also initialize the decompression parameters to default
  168120. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168121. * adjust the decompression parameters and then call jpeg_start_decompress.
  168122. * (Or, if the application only wanted to determine the image parameters,
  168123. * the data need not be decompressed. In that case, call jpeg_abort or
  168124. * jpeg_destroy to release any temporary space.)
  168125. * If an abbreviated (tables only) datastream is presented, the routine will
  168126. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168127. * re-use the JPEG object to read the abbreviated image datastream(s).
  168128. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168129. * The JPEG_SUSPENDED return code only occurs if the data source module
  168130. * requests suspension of the decompressor. In this case the application
  168131. * should load more source data and then re-call jpeg_read_header to resume
  168132. * processing.
  168133. * If a non-suspending data source is used and require_image is TRUE, then the
  168134. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168135. *
  168136. * This routine is now just a front end to jpeg_consume_input, with some
  168137. * extra error checking.
  168138. */
  168139. GLOBAL(int)
  168140. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168141. {
  168142. int retcode;
  168143. if (cinfo->global_state != DSTATE_START &&
  168144. cinfo->global_state != DSTATE_INHEADER)
  168145. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168146. retcode = jpeg_consume_input(cinfo);
  168147. switch (retcode) {
  168148. case JPEG_REACHED_SOS:
  168149. retcode = JPEG_HEADER_OK;
  168150. break;
  168151. case JPEG_REACHED_EOI:
  168152. if (require_image) /* Complain if application wanted an image */
  168153. ERREXIT(cinfo, JERR_NO_IMAGE);
  168154. /* Reset to start state; it would be safer to require the application to
  168155. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168156. * A side effect is to free any temporary memory (there shouldn't be any).
  168157. */
  168158. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168159. retcode = JPEG_HEADER_TABLES_ONLY;
  168160. break;
  168161. case JPEG_SUSPENDED:
  168162. /* no work */
  168163. break;
  168164. }
  168165. return retcode;
  168166. }
  168167. /*
  168168. * Consume data in advance of what the decompressor requires.
  168169. * This can be called at any time once the decompressor object has
  168170. * been created and a data source has been set up.
  168171. *
  168172. * This routine is essentially a state machine that handles a couple
  168173. * of critical state-transition actions, namely initial setup and
  168174. * transition from header scanning to ready-for-start_decompress.
  168175. * All the actual input is done via the input controller's consume_input
  168176. * method.
  168177. */
  168178. GLOBAL(int)
  168179. jpeg_consume_input (j_decompress_ptr cinfo)
  168180. {
  168181. int retcode = JPEG_SUSPENDED;
  168182. /* NB: every possible DSTATE value should be listed in this switch */
  168183. switch (cinfo->global_state) {
  168184. case DSTATE_START:
  168185. /* Start-of-datastream actions: reset appropriate modules */
  168186. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168187. /* Initialize application's data source module */
  168188. (*cinfo->src->init_source) (cinfo);
  168189. cinfo->global_state = DSTATE_INHEADER;
  168190. /*FALLTHROUGH*/
  168191. case DSTATE_INHEADER:
  168192. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168193. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168194. /* Set up default parameters based on header data */
  168195. default_decompress_parms(cinfo);
  168196. /* Set global state: ready for start_decompress */
  168197. cinfo->global_state = DSTATE_READY;
  168198. }
  168199. break;
  168200. case DSTATE_READY:
  168201. /* Can't advance past first SOS until start_decompress is called */
  168202. retcode = JPEG_REACHED_SOS;
  168203. break;
  168204. case DSTATE_PRELOAD:
  168205. case DSTATE_PRESCAN:
  168206. case DSTATE_SCANNING:
  168207. case DSTATE_RAW_OK:
  168208. case DSTATE_BUFIMAGE:
  168209. case DSTATE_BUFPOST:
  168210. case DSTATE_STOPPING:
  168211. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168212. break;
  168213. default:
  168214. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168215. }
  168216. return retcode;
  168217. }
  168218. /*
  168219. * Have we finished reading the input file?
  168220. */
  168221. GLOBAL(boolean)
  168222. jpeg_input_complete (j_decompress_ptr cinfo)
  168223. {
  168224. /* Check for valid jpeg object */
  168225. if (cinfo->global_state < DSTATE_START ||
  168226. cinfo->global_state > DSTATE_STOPPING)
  168227. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168228. return cinfo->inputctl->eoi_reached;
  168229. }
  168230. /*
  168231. * Is there more than one scan?
  168232. */
  168233. GLOBAL(boolean)
  168234. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  168235. {
  168236. /* Only valid after jpeg_read_header completes */
  168237. if (cinfo->global_state < DSTATE_READY ||
  168238. cinfo->global_state > DSTATE_STOPPING)
  168239. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168240. return cinfo->inputctl->has_multiple_scans;
  168241. }
  168242. /*
  168243. * Finish JPEG decompression.
  168244. *
  168245. * This will normally just verify the file trailer and release temp storage.
  168246. *
  168247. * Returns FALSE if suspended. The return value need be inspected only if
  168248. * a suspending data source is used.
  168249. */
  168250. GLOBAL(boolean)
  168251. jpeg_finish_decompress (j_decompress_ptr cinfo)
  168252. {
  168253. if ((cinfo->global_state == DSTATE_SCANNING ||
  168254. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  168255. /* Terminate final pass of non-buffered mode */
  168256. if (cinfo->output_scanline < cinfo->output_height)
  168257. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  168258. (*cinfo->master->finish_output_pass) (cinfo);
  168259. cinfo->global_state = DSTATE_STOPPING;
  168260. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  168261. /* Finishing after a buffered-image operation */
  168262. cinfo->global_state = DSTATE_STOPPING;
  168263. } else if (cinfo->global_state != DSTATE_STOPPING) {
  168264. /* STOPPING = repeat call after a suspension, anything else is error */
  168265. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168266. }
  168267. /* Read until EOI */
  168268. while (! cinfo->inputctl->eoi_reached) {
  168269. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168270. return FALSE; /* Suspend, come back later */
  168271. }
  168272. /* Do final cleanup */
  168273. (*cinfo->src->term_source) (cinfo);
  168274. /* We can use jpeg_abort to release memory and reset global_state */
  168275. jpeg_abort((j_common_ptr) cinfo);
  168276. return TRUE;
  168277. }
  168278. /*** End of inlined file: jdapimin.c ***/
  168279. /*** Start of inlined file: jdatasrc.c ***/
  168280. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  168281. /*** Start of inlined file: jerror.h ***/
  168282. /*
  168283. * To define the enum list of message codes, include this file without
  168284. * defining macro JMESSAGE. To create a message string table, include it
  168285. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  168286. */
  168287. #ifndef JMESSAGE
  168288. #ifndef JERROR_H
  168289. /* First time through, define the enum list */
  168290. #define JMAKE_ENUM_LIST
  168291. #else
  168292. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  168293. #define JMESSAGE(code,string)
  168294. #endif /* JERROR_H */
  168295. #endif /* JMESSAGE */
  168296. #ifdef JMAKE_ENUM_LIST
  168297. typedef enum {
  168298. #define JMESSAGE(code,string) code ,
  168299. #endif /* JMAKE_ENUM_LIST */
  168300. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  168301. /* For maintenance convenience, list is alphabetical by message code name */
  168302. JMESSAGE(JERR_ARITH_NOTIMPL,
  168303. "Sorry, there are legal restrictions on arithmetic coding")
  168304. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  168305. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  168306. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  168307. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  168308. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  168309. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  168310. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  168311. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  168312. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  168313. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  168314. JMESSAGE(JERR_BAD_LIB_VERSION,
  168315. "Wrong JPEG library version: library is %d, caller expects %d")
  168316. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  168317. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  168318. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  168319. JMESSAGE(JERR_BAD_PROGRESSION,
  168320. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  168321. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  168322. "Invalid progressive parameters at scan script entry %d")
  168323. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  168324. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  168325. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  168326. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  168327. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  168328. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  168329. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  168330. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  168331. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  168332. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  168333. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  168334. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  168335. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  168336. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  168337. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  168338. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  168339. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  168340. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  168341. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  168342. JMESSAGE(JERR_FILE_READ, "Input file read error")
  168343. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  168344. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  168345. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  168346. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  168347. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  168348. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  168349. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  168350. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  168351. "Cannot transcode due to multiple use of quantization table %d")
  168352. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  168353. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  168354. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  168355. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  168356. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  168357. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  168358. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  168359. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  168360. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  168361. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  168362. JMESSAGE(JERR_QUANT_COMPONENTS,
  168363. "Cannot quantize more than %d color components")
  168364. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  168365. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  168366. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  168367. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  168368. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  168369. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  168370. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  168371. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  168372. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  168373. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  168374. JMESSAGE(JERR_TFILE_WRITE,
  168375. "Write failed on temporary file --- out of disk space?")
  168376. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  168377. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  168378. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  168379. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  168380. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  168381. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  168382. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  168383. JMESSAGE(JMSG_VERSION, JVERSION)
  168384. JMESSAGE(JTRC_16BIT_TABLES,
  168385. "Caution: quantization tables are too coarse for baseline JPEG")
  168386. JMESSAGE(JTRC_ADOBE,
  168387. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  168388. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  168389. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  168390. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  168391. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  168392. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  168393. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  168394. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  168395. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  168396. JMESSAGE(JTRC_EOI, "End Of Image")
  168397. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  168398. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  168399. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  168400. "Warning: thumbnail image size does not match data length %u")
  168401. JMESSAGE(JTRC_JFIF_EXTENSION,
  168402. "JFIF extension marker: type 0x%02x, length %u")
  168403. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  168404. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  168405. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  168406. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  168407. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  168408. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  168409. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  168410. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  168411. JMESSAGE(JTRC_RST, "RST%d")
  168412. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  168413. "Smoothing not supported with nonstandard sampling ratios")
  168414. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  168415. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  168416. JMESSAGE(JTRC_SOI, "Start of Image")
  168417. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  168418. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  168419. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  168420. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  168421. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  168422. JMESSAGE(JTRC_THUMB_JPEG,
  168423. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  168424. JMESSAGE(JTRC_THUMB_PALETTE,
  168425. "JFIF extension marker: palette thumbnail image, length %u")
  168426. JMESSAGE(JTRC_THUMB_RGB,
  168427. "JFIF extension marker: RGB thumbnail image, length %u")
  168428. JMESSAGE(JTRC_UNKNOWN_IDS,
  168429. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  168430. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  168431. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  168432. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  168433. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  168434. "Inconsistent progression sequence for component %d coefficient %d")
  168435. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  168436. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  168437. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  168438. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  168439. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  168440. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  168441. JMESSAGE(JWRN_MUST_RESYNC,
  168442. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  168443. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  168444. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  168445. #ifdef JMAKE_ENUM_LIST
  168446. JMSG_LASTMSGCODE
  168447. } J_MESSAGE_CODE;
  168448. #undef JMAKE_ENUM_LIST
  168449. #endif /* JMAKE_ENUM_LIST */
  168450. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  168451. #undef JMESSAGE
  168452. #ifndef JERROR_H
  168453. #define JERROR_H
  168454. /* Macros to simplify using the error and trace message stuff */
  168455. /* The first parameter is either type of cinfo pointer */
  168456. /* Fatal errors (print message and exit) */
  168457. #define ERREXIT(cinfo,code) \
  168458. ((cinfo)->err->msg_code = (code), \
  168459. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168460. #define ERREXIT1(cinfo,code,p1) \
  168461. ((cinfo)->err->msg_code = (code), \
  168462. (cinfo)->err->msg_parm.i[0] = (p1), \
  168463. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168464. #define ERREXIT2(cinfo,code,p1,p2) \
  168465. ((cinfo)->err->msg_code = (code), \
  168466. (cinfo)->err->msg_parm.i[0] = (p1), \
  168467. (cinfo)->err->msg_parm.i[1] = (p2), \
  168468. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168469. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  168470. ((cinfo)->err->msg_code = (code), \
  168471. (cinfo)->err->msg_parm.i[0] = (p1), \
  168472. (cinfo)->err->msg_parm.i[1] = (p2), \
  168473. (cinfo)->err->msg_parm.i[2] = (p3), \
  168474. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168475. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  168476. ((cinfo)->err->msg_code = (code), \
  168477. (cinfo)->err->msg_parm.i[0] = (p1), \
  168478. (cinfo)->err->msg_parm.i[1] = (p2), \
  168479. (cinfo)->err->msg_parm.i[2] = (p3), \
  168480. (cinfo)->err->msg_parm.i[3] = (p4), \
  168481. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168482. #define ERREXITS(cinfo,code,str) \
  168483. ((cinfo)->err->msg_code = (code), \
  168484. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168485. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  168486. #define MAKESTMT(stuff) do { stuff } while (0)
  168487. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  168488. #define WARNMS(cinfo,code) \
  168489. ((cinfo)->err->msg_code = (code), \
  168490. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168491. #define WARNMS1(cinfo,code,p1) \
  168492. ((cinfo)->err->msg_code = (code), \
  168493. (cinfo)->err->msg_parm.i[0] = (p1), \
  168494. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168495. #define WARNMS2(cinfo,code,p1,p2) \
  168496. ((cinfo)->err->msg_code = (code), \
  168497. (cinfo)->err->msg_parm.i[0] = (p1), \
  168498. (cinfo)->err->msg_parm.i[1] = (p2), \
  168499. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  168500. /* Informational/debugging messages */
  168501. #define TRACEMS(cinfo,lvl,code) \
  168502. ((cinfo)->err->msg_code = (code), \
  168503. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168504. #define TRACEMS1(cinfo,lvl,code,p1) \
  168505. ((cinfo)->err->msg_code = (code), \
  168506. (cinfo)->err->msg_parm.i[0] = (p1), \
  168507. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168508. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  168509. ((cinfo)->err->msg_code = (code), \
  168510. (cinfo)->err->msg_parm.i[0] = (p1), \
  168511. (cinfo)->err->msg_parm.i[1] = (p2), \
  168512. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168513. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  168514. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168515. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  168516. (cinfo)->err->msg_code = (code); \
  168517. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168518. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  168519. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168520. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168521. (cinfo)->err->msg_code = (code); \
  168522. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168523. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  168524. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168525. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168526. _mp[4] = (p5); \
  168527. (cinfo)->err->msg_code = (code); \
  168528. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168529. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  168530. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  168531. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  168532. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  168533. (cinfo)->err->msg_code = (code); \
  168534. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  168535. #define TRACEMSS(cinfo,lvl,code,str) \
  168536. ((cinfo)->err->msg_code = (code), \
  168537. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  168538. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  168539. #endif /* JERROR_H */
  168540. /*** End of inlined file: jerror.h ***/
  168541. /* Expanded data source object for stdio input */
  168542. typedef struct {
  168543. struct jpeg_source_mgr pub; /* public fields */
  168544. FILE * infile; /* source stream */
  168545. JOCTET * buffer; /* start of buffer */
  168546. boolean start_of_file; /* have we gotten any data yet? */
  168547. } my_source_mgr;
  168548. typedef my_source_mgr * my_src_ptr;
  168549. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  168550. /*
  168551. * Initialize source --- called by jpeg_read_header
  168552. * before any data is actually read.
  168553. */
  168554. METHODDEF(void)
  168555. init_source (j_decompress_ptr cinfo)
  168556. {
  168557. my_src_ptr src = (my_src_ptr) cinfo->src;
  168558. /* We reset the empty-input-file flag for each image,
  168559. * but we don't clear the input buffer.
  168560. * This is correct behavior for reading a series of images from one source.
  168561. */
  168562. src->start_of_file = TRUE;
  168563. }
  168564. /*
  168565. * Fill the input buffer --- called whenever buffer is emptied.
  168566. *
  168567. * In typical applications, this should read fresh data into the buffer
  168568. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  168569. * reset the pointer & count to the start of the buffer, and return TRUE
  168570. * indicating that the buffer has been reloaded. It is not necessary to
  168571. * fill the buffer entirely, only to obtain at least one more byte.
  168572. *
  168573. * There is no such thing as an EOF return. If the end of the file has been
  168574. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  168575. * the buffer. In most cases, generating a warning message and inserting a
  168576. * fake EOI marker is the best course of action --- this will allow the
  168577. * decompressor to output however much of the image is there. However,
  168578. * the resulting error message is misleading if the real problem is an empty
  168579. * input file, so we handle that case specially.
  168580. *
  168581. * In applications that need to be able to suspend compression due to input
  168582. * not being available yet, a FALSE return indicates that no more data can be
  168583. * obtained right now, but more may be forthcoming later. In this situation,
  168584. * the decompressor will return to its caller (with an indication of the
  168585. * number of scanlines it has read, if any). The application should resume
  168586. * decompression after it has loaded more data into the input buffer. Note
  168587. * that there are substantial restrictions on the use of suspension --- see
  168588. * the documentation.
  168589. *
  168590. * When suspending, the decompressor will back up to a convenient restart point
  168591. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  168592. * indicate where the restart point will be if the current call returns FALSE.
  168593. * Data beyond this point must be rescanned after resumption, so move it to
  168594. * the front of the buffer rather than discarding it.
  168595. */
  168596. METHODDEF(boolean)
  168597. fill_input_buffer (j_decompress_ptr cinfo)
  168598. {
  168599. my_src_ptr src = (my_src_ptr) cinfo->src;
  168600. size_t nbytes;
  168601. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  168602. if (nbytes <= 0) {
  168603. if (src->start_of_file) /* Treat empty input file as fatal error */
  168604. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  168605. WARNMS(cinfo, JWRN_JPEG_EOF);
  168606. /* Insert a fake EOI marker */
  168607. src->buffer[0] = (JOCTET) 0xFF;
  168608. src->buffer[1] = (JOCTET) JPEG_EOI;
  168609. nbytes = 2;
  168610. }
  168611. src->pub.next_input_byte = src->buffer;
  168612. src->pub.bytes_in_buffer = nbytes;
  168613. src->start_of_file = FALSE;
  168614. return TRUE;
  168615. }
  168616. /*
  168617. * Skip data --- used to skip over a potentially large amount of
  168618. * uninteresting data (such as an APPn marker).
  168619. *
  168620. * Writers of suspendable-input applications must note that skip_input_data
  168621. * is not granted the right to give a suspension return. If the skip extends
  168622. * beyond the data currently in the buffer, the buffer can be marked empty so
  168623. * that the next read will cause a fill_input_buffer call that can suspend.
  168624. * Arranging for additional bytes to be discarded before reloading the input
  168625. * buffer is the application writer's problem.
  168626. */
  168627. METHODDEF(void)
  168628. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  168629. {
  168630. my_src_ptr src = (my_src_ptr) cinfo->src;
  168631. /* Just a dumb implementation for now. Could use fseek() except
  168632. * it doesn't work on pipes. Not clear that being smart is worth
  168633. * any trouble anyway --- large skips are infrequent.
  168634. */
  168635. if (num_bytes > 0) {
  168636. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  168637. num_bytes -= (long) src->pub.bytes_in_buffer;
  168638. (void) fill_input_buffer(cinfo);
  168639. /* note we assume that fill_input_buffer will never return FALSE,
  168640. * so suspension need not be handled.
  168641. */
  168642. }
  168643. src->pub.next_input_byte += (size_t) num_bytes;
  168644. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  168645. }
  168646. }
  168647. /*
  168648. * An additional method that can be provided by data source modules is the
  168649. * resync_to_restart method for error recovery in the presence of RST markers.
  168650. * For the moment, this source module just uses the default resync method
  168651. * provided by the JPEG library. That method assumes that no backtracking
  168652. * is possible.
  168653. */
  168654. /*
  168655. * Terminate source --- called by jpeg_finish_decompress
  168656. * after all data has been read. Often a no-op.
  168657. *
  168658. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  168659. * application must deal with any cleanup that should happen even
  168660. * for error exit.
  168661. */
  168662. METHODDEF(void)
  168663. term_source (j_decompress_ptr)
  168664. {
  168665. /* no work necessary here */
  168666. }
  168667. /*
  168668. * Prepare for input from a stdio stream.
  168669. * The caller must have already opened the stream, and is responsible
  168670. * for closing it after finishing decompression.
  168671. */
  168672. GLOBAL(void)
  168673. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  168674. {
  168675. my_src_ptr src;
  168676. /* The source object and input buffer are made permanent so that a series
  168677. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  168678. * only before the first one. (If we discarded the buffer at the end of
  168679. * one image, we'd likely lose the start of the next one.)
  168680. * This makes it unsafe to use this manager and a different source
  168681. * manager serially with the same JPEG object. Caveat programmer.
  168682. */
  168683. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  168684. cinfo->src = (struct jpeg_source_mgr *)
  168685. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168686. SIZEOF(my_source_mgr));
  168687. src = (my_src_ptr) cinfo->src;
  168688. src->buffer = (JOCTET *)
  168689. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  168690. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  168691. }
  168692. src = (my_src_ptr) cinfo->src;
  168693. src->pub.init_source = init_source;
  168694. src->pub.fill_input_buffer = fill_input_buffer;
  168695. src->pub.skip_input_data = skip_input_data;
  168696. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  168697. src->pub.term_source = term_source;
  168698. src->infile = infile;
  168699. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  168700. src->pub.next_input_byte = NULL; /* until buffer loaded */
  168701. }
  168702. /*** End of inlined file: jdatasrc.c ***/
  168703. /*** Start of inlined file: jdcoefct.c ***/
  168704. #define JPEG_INTERNALS
  168705. /* Block smoothing is only applicable for progressive JPEG, so: */
  168706. #ifndef D_PROGRESSIVE_SUPPORTED
  168707. #undef BLOCK_SMOOTHING_SUPPORTED
  168708. #endif
  168709. /* Private buffer controller object */
  168710. typedef struct {
  168711. struct jpeg_d_coef_controller pub; /* public fields */
  168712. /* These variables keep track of the current location of the input side. */
  168713. /* cinfo->input_iMCU_row is also used for this. */
  168714. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  168715. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168716. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168717. /* The output side's location is represented by cinfo->output_iMCU_row. */
  168718. /* In single-pass modes, it's sufficient to buffer just one MCU.
  168719. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  168720. * and let the entropy decoder write into that workspace each time.
  168721. * (On 80x86, the workspace is FAR even though it's not really very big;
  168722. * this is to keep the module interfaces unchanged when a large coefficient
  168723. * buffer is necessary.)
  168724. * In multi-pass modes, this array points to the current MCU's blocks
  168725. * within the virtual arrays; it is used only by the input side.
  168726. */
  168727. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  168728. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168729. /* In multi-pass modes, we need a virtual block array for each component. */
  168730. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  168731. #endif
  168732. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168733. /* When doing block smoothing, we latch coefficient Al values here */
  168734. int * coef_bits_latch;
  168735. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  168736. #endif
  168737. } my_coef_controller3;
  168738. typedef my_coef_controller3 * my_coef_ptr3;
  168739. /* Forward declarations */
  168740. METHODDEF(int) decompress_onepass
  168741. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168742. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168743. METHODDEF(int) decompress_data
  168744. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168745. #endif
  168746. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168747. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  168748. METHODDEF(int) decompress_smooth_data
  168749. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  168750. #endif
  168751. LOCAL(void)
  168752. start_iMCU_row3 (j_decompress_ptr cinfo)
  168753. /* Reset within-iMCU-row counters for a new row (input side) */
  168754. {
  168755. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168756. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168757. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168758. * But at the bottom of the image, process only what's left.
  168759. */
  168760. if (cinfo->comps_in_scan > 1) {
  168761. coef->MCU_rows_per_iMCU_row = 1;
  168762. } else {
  168763. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  168764. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168765. else
  168766. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168767. }
  168768. coef->MCU_ctr = 0;
  168769. coef->MCU_vert_offset = 0;
  168770. }
  168771. /*
  168772. * Initialize for an input processing pass.
  168773. */
  168774. METHODDEF(void)
  168775. start_input_pass (j_decompress_ptr cinfo)
  168776. {
  168777. cinfo->input_iMCU_row = 0;
  168778. start_iMCU_row3(cinfo);
  168779. }
  168780. /*
  168781. * Initialize for an output processing pass.
  168782. */
  168783. METHODDEF(void)
  168784. start_output_pass (j_decompress_ptr cinfo)
  168785. {
  168786. #ifdef BLOCK_SMOOTHING_SUPPORTED
  168787. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168788. /* If multipass, check to see whether to use block smoothing on this pass */
  168789. if (coef->pub.coef_arrays != NULL) {
  168790. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  168791. coef->pub.decompress_data = decompress_smooth_data;
  168792. else
  168793. coef->pub.decompress_data = decompress_data;
  168794. }
  168795. #endif
  168796. cinfo->output_iMCU_row = 0;
  168797. }
  168798. /*
  168799. * Decompress and return some data in the single-pass case.
  168800. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168801. * Input and output must run in lockstep since we have only a one-MCU buffer.
  168802. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168803. *
  168804. * NB: output_buf contains a plane for each component in image,
  168805. * which we index according to the component's SOF position.
  168806. */
  168807. METHODDEF(int)
  168808. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168809. {
  168810. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168811. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168812. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168813. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168814. int blkn, ci, xindex, yindex, yoffset, useful_width;
  168815. JSAMPARRAY output_ptr;
  168816. JDIMENSION start_col, output_col;
  168817. jpeg_component_info *compptr;
  168818. inverse_DCT_method_ptr inverse_DCT;
  168819. /* Loop to process as much as one whole iMCU row */
  168820. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168821. yoffset++) {
  168822. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  168823. MCU_col_num++) {
  168824. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  168825. jzero_far((void FAR *) coef->MCU_buffer[0],
  168826. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  168827. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168828. /* Suspension forced; update state counters and exit */
  168829. coef->MCU_vert_offset = yoffset;
  168830. coef->MCU_ctr = MCU_col_num;
  168831. return JPEG_SUSPENDED;
  168832. }
  168833. /* Determine where data should go in output_buf and do the IDCT thing.
  168834. * We skip dummy blocks at the right and bottom edges (but blkn gets
  168835. * incremented past them!). Note the inner loop relies on having
  168836. * allocated the MCU_buffer[] blocks sequentially.
  168837. */
  168838. blkn = 0; /* index of current DCT block within MCU */
  168839. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168840. compptr = cinfo->cur_comp_info[ci];
  168841. /* Don't bother to IDCT an uninteresting component. */
  168842. if (! compptr->component_needed) {
  168843. blkn += compptr->MCU_blocks;
  168844. continue;
  168845. }
  168846. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  168847. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168848. : compptr->last_col_width;
  168849. output_ptr = output_buf[compptr->component_index] +
  168850. yoffset * compptr->DCT_scaled_size;
  168851. start_col = MCU_col_num * compptr->MCU_sample_width;
  168852. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168853. if (cinfo->input_iMCU_row < last_iMCU_row ||
  168854. yoffset+yindex < compptr->last_row_height) {
  168855. output_col = start_col;
  168856. for (xindex = 0; xindex < useful_width; xindex++) {
  168857. (*inverse_DCT) (cinfo, compptr,
  168858. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  168859. output_ptr, output_col);
  168860. output_col += compptr->DCT_scaled_size;
  168861. }
  168862. }
  168863. blkn += compptr->MCU_width;
  168864. output_ptr += compptr->DCT_scaled_size;
  168865. }
  168866. }
  168867. }
  168868. /* Completed an MCU row, but perhaps not an iMCU row */
  168869. coef->MCU_ctr = 0;
  168870. }
  168871. /* Completed the iMCU row, advance counters for next one */
  168872. cinfo->output_iMCU_row++;
  168873. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168874. start_iMCU_row3(cinfo);
  168875. return JPEG_ROW_COMPLETED;
  168876. }
  168877. /* Completed the scan */
  168878. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168879. return JPEG_SCAN_COMPLETED;
  168880. }
  168881. /*
  168882. * Dummy consume-input routine for single-pass operation.
  168883. */
  168884. METHODDEF(int)
  168885. dummy_consume_data (j_decompress_ptr)
  168886. {
  168887. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  168888. }
  168889. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168890. /*
  168891. * Consume input data and store it in the full-image coefficient buffer.
  168892. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  168893. * ie, v_samp_factor block rows for each component in the scan.
  168894. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168895. */
  168896. METHODDEF(int)
  168897. consume_data (j_decompress_ptr cinfo)
  168898. {
  168899. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168900. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168901. int blkn, ci, xindex, yindex, yoffset;
  168902. JDIMENSION start_col;
  168903. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168904. JBLOCKROW buffer_ptr;
  168905. jpeg_component_info *compptr;
  168906. /* Align the virtual buffers for the components used in this scan. */
  168907. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168908. compptr = cinfo->cur_comp_info[ci];
  168909. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168910. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168911. cinfo->input_iMCU_row * compptr->v_samp_factor,
  168912. (JDIMENSION) compptr->v_samp_factor, TRUE);
  168913. /* Note: entropy decoder expects buffer to be zeroed,
  168914. * but this is handled automatically by the memory manager
  168915. * because we requested a pre-zeroed array.
  168916. */
  168917. }
  168918. /* Loop to process one whole iMCU row */
  168919. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168920. yoffset++) {
  168921. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168922. MCU_col_num++) {
  168923. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168924. blkn = 0; /* index of current DCT block within MCU */
  168925. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168926. compptr = cinfo->cur_comp_info[ci];
  168927. start_col = MCU_col_num * compptr->MCU_width;
  168928. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168929. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168930. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  168931. coef->MCU_buffer[blkn++] = buffer_ptr++;
  168932. }
  168933. }
  168934. }
  168935. /* Try to fetch the MCU. */
  168936. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  168937. /* Suspension forced; update state counters and exit */
  168938. coef->MCU_vert_offset = yoffset;
  168939. coef->MCU_ctr = MCU_col_num;
  168940. return JPEG_SUSPENDED;
  168941. }
  168942. }
  168943. /* Completed an MCU row, but perhaps not an iMCU row */
  168944. coef->MCU_ctr = 0;
  168945. }
  168946. /* Completed the iMCU row, advance counters for next one */
  168947. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  168948. start_iMCU_row3(cinfo);
  168949. return JPEG_ROW_COMPLETED;
  168950. }
  168951. /* Completed the scan */
  168952. (*cinfo->inputctl->finish_input_pass) (cinfo);
  168953. return JPEG_SCAN_COMPLETED;
  168954. }
  168955. /*
  168956. * Decompress and return some data in the multi-pass case.
  168957. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  168958. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  168959. *
  168960. * NB: output_buf contains a plane for each component in image.
  168961. */
  168962. METHODDEF(int)
  168963. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  168964. {
  168965. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  168966. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168967. JDIMENSION block_num;
  168968. int ci, block_row, block_rows;
  168969. JBLOCKARRAY buffer;
  168970. JBLOCKROW buffer_ptr;
  168971. JSAMPARRAY output_ptr;
  168972. JDIMENSION output_col;
  168973. jpeg_component_info *compptr;
  168974. inverse_DCT_method_ptr inverse_DCT;
  168975. /* Force some input to be done if we are getting ahead of the input. */
  168976. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  168977. (cinfo->input_scan_number == cinfo->output_scan_number &&
  168978. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  168979. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  168980. return JPEG_SUSPENDED;
  168981. }
  168982. /* OK, output from the virtual arrays. */
  168983. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168984. ci++, compptr++) {
  168985. /* Don't bother to IDCT an uninteresting component. */
  168986. if (! compptr->component_needed)
  168987. continue;
  168988. /* Align the virtual buffer for this component. */
  168989. buffer = (*cinfo->mem->access_virt_barray)
  168990. ((j_common_ptr) cinfo, coef->whole_image[ci],
  168991. cinfo->output_iMCU_row * compptr->v_samp_factor,
  168992. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168993. /* Count non-dummy DCT block rows in this iMCU row. */
  168994. if (cinfo->output_iMCU_row < last_iMCU_row)
  168995. block_rows = compptr->v_samp_factor;
  168996. else {
  168997. /* NB: can't use last_row_height here; it is input-side-dependent! */
  168998. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  168999. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169000. }
  169001. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169002. output_ptr = output_buf[ci];
  169003. /* Loop over all DCT blocks to be processed. */
  169004. for (block_row = 0; block_row < block_rows; block_row++) {
  169005. buffer_ptr = buffer[block_row];
  169006. output_col = 0;
  169007. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  169008. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  169009. output_ptr, output_col);
  169010. buffer_ptr++;
  169011. output_col += compptr->DCT_scaled_size;
  169012. }
  169013. output_ptr += compptr->DCT_scaled_size;
  169014. }
  169015. }
  169016. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169017. return JPEG_ROW_COMPLETED;
  169018. return JPEG_SCAN_COMPLETED;
  169019. }
  169020. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169021. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169022. /*
  169023. * This code applies interblock smoothing as described by section K.8
  169024. * of the JPEG standard: the first 5 AC coefficients are estimated from
  169025. * the DC values of a DCT block and its 8 neighboring blocks.
  169026. * We apply smoothing only for progressive JPEG decoding, and only if
  169027. * the coefficients it can estimate are not yet known to full precision.
  169028. */
  169029. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  169030. #define Q01_POS 1
  169031. #define Q10_POS 8
  169032. #define Q20_POS 16
  169033. #define Q11_POS 9
  169034. #define Q02_POS 2
  169035. /*
  169036. * Determine whether block smoothing is applicable and safe.
  169037. * We also latch the current states of the coef_bits[] entries for the
  169038. * AC coefficients; otherwise, if the input side of the decompressor
  169039. * advances into a new scan, we might think the coefficients are known
  169040. * more accurately than they really are.
  169041. */
  169042. LOCAL(boolean)
  169043. smoothing_ok (j_decompress_ptr cinfo)
  169044. {
  169045. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169046. boolean smoothing_useful = FALSE;
  169047. int ci, coefi;
  169048. jpeg_component_info *compptr;
  169049. JQUANT_TBL * qtable;
  169050. int * coef_bits;
  169051. int * coef_bits_latch;
  169052. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169053. return FALSE;
  169054. /* Allocate latch area if not already done */
  169055. if (coef->coef_bits_latch == NULL)
  169056. coef->coef_bits_latch = (int *)
  169057. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169058. cinfo->num_components *
  169059. (SAVED_COEFS * SIZEOF(int)));
  169060. coef_bits_latch = coef->coef_bits_latch;
  169061. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169062. ci++, compptr++) {
  169063. /* All components' quantization values must already be latched. */
  169064. if ((qtable = compptr->quant_table) == NULL)
  169065. return FALSE;
  169066. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169067. if (qtable->quantval[0] == 0 ||
  169068. qtable->quantval[Q01_POS] == 0 ||
  169069. qtable->quantval[Q10_POS] == 0 ||
  169070. qtable->quantval[Q20_POS] == 0 ||
  169071. qtable->quantval[Q11_POS] == 0 ||
  169072. qtable->quantval[Q02_POS] == 0)
  169073. return FALSE;
  169074. /* DC values must be at least partly known for all components. */
  169075. coef_bits = cinfo->coef_bits[ci];
  169076. if (coef_bits[0] < 0)
  169077. return FALSE;
  169078. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169079. for (coefi = 1; coefi <= 5; coefi++) {
  169080. coef_bits_latch[coefi] = coef_bits[coefi];
  169081. if (coef_bits[coefi] != 0)
  169082. smoothing_useful = TRUE;
  169083. }
  169084. coef_bits_latch += SAVED_COEFS;
  169085. }
  169086. return smoothing_useful;
  169087. }
  169088. /*
  169089. * Variant of decompress_data for use when doing block smoothing.
  169090. */
  169091. METHODDEF(int)
  169092. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169093. {
  169094. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169095. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169096. JDIMENSION block_num, last_block_column;
  169097. int ci, block_row, block_rows, access_rows;
  169098. JBLOCKARRAY buffer;
  169099. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169100. JSAMPARRAY output_ptr;
  169101. JDIMENSION output_col;
  169102. jpeg_component_info *compptr;
  169103. inverse_DCT_method_ptr inverse_DCT;
  169104. boolean first_row, last_row;
  169105. JBLOCK workspace;
  169106. int *coef_bits;
  169107. JQUANT_TBL *quanttbl;
  169108. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169109. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169110. int Al, pred;
  169111. /* Force some input to be done if we are getting ahead of the input. */
  169112. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169113. ! cinfo->inputctl->eoi_reached) {
  169114. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169115. /* If input is working on current scan, we ordinarily want it to
  169116. * have completed the current row. But if input scan is DC,
  169117. * we want it to keep one row ahead so that next block row's DC
  169118. * values are up to date.
  169119. */
  169120. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169121. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169122. break;
  169123. }
  169124. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169125. return JPEG_SUSPENDED;
  169126. }
  169127. /* OK, output from the virtual arrays. */
  169128. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169129. ci++, compptr++) {
  169130. /* Don't bother to IDCT an uninteresting component. */
  169131. if (! compptr->component_needed)
  169132. continue;
  169133. /* Count non-dummy DCT block rows in this iMCU row. */
  169134. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169135. block_rows = compptr->v_samp_factor;
  169136. access_rows = block_rows * 2; /* this and next iMCU row */
  169137. last_row = FALSE;
  169138. } else {
  169139. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169140. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169141. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169142. access_rows = block_rows; /* this iMCU row only */
  169143. last_row = TRUE;
  169144. }
  169145. /* Align the virtual buffer for this component. */
  169146. if (cinfo->output_iMCU_row > 0) {
  169147. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169148. buffer = (*cinfo->mem->access_virt_barray)
  169149. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169150. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169151. (JDIMENSION) access_rows, FALSE);
  169152. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169153. first_row = FALSE;
  169154. } else {
  169155. buffer = (*cinfo->mem->access_virt_barray)
  169156. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169157. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169158. first_row = TRUE;
  169159. }
  169160. /* Fetch component-dependent info */
  169161. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169162. quanttbl = compptr->quant_table;
  169163. Q00 = quanttbl->quantval[0];
  169164. Q01 = quanttbl->quantval[Q01_POS];
  169165. Q10 = quanttbl->quantval[Q10_POS];
  169166. Q20 = quanttbl->quantval[Q20_POS];
  169167. Q11 = quanttbl->quantval[Q11_POS];
  169168. Q02 = quanttbl->quantval[Q02_POS];
  169169. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169170. output_ptr = output_buf[ci];
  169171. /* Loop over all DCT blocks to be processed. */
  169172. for (block_row = 0; block_row < block_rows; block_row++) {
  169173. buffer_ptr = buffer[block_row];
  169174. if (first_row && block_row == 0)
  169175. prev_block_row = buffer_ptr;
  169176. else
  169177. prev_block_row = buffer[block_row-1];
  169178. if (last_row && block_row == block_rows-1)
  169179. next_block_row = buffer_ptr;
  169180. else
  169181. next_block_row = buffer[block_row+1];
  169182. /* We fetch the surrounding DC values using a sliding-register approach.
  169183. * Initialize all nine here so as to do the right thing on narrow pics.
  169184. */
  169185. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169186. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169187. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169188. output_col = 0;
  169189. last_block_column = compptr->width_in_blocks - 1;
  169190. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169191. /* Fetch current DCT block into workspace so we can modify it. */
  169192. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169193. /* Update DC values */
  169194. if (block_num < last_block_column) {
  169195. DC3 = (int) prev_block_row[1][0];
  169196. DC6 = (int) buffer_ptr[1][0];
  169197. DC9 = (int) next_block_row[1][0];
  169198. }
  169199. /* Compute coefficient estimates per K.8.
  169200. * An estimate is applied only if coefficient is still zero,
  169201. * and is not known to be fully accurate.
  169202. */
  169203. /* AC01 */
  169204. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169205. num = 36 * Q00 * (DC4 - DC6);
  169206. if (num >= 0) {
  169207. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169208. if (Al > 0 && pred >= (1<<Al))
  169209. pred = (1<<Al)-1;
  169210. } else {
  169211. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169212. if (Al > 0 && pred >= (1<<Al))
  169213. pred = (1<<Al)-1;
  169214. pred = -pred;
  169215. }
  169216. workspace[1] = (JCOEF) pred;
  169217. }
  169218. /* AC10 */
  169219. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169220. num = 36 * Q00 * (DC2 - DC8);
  169221. if (num >= 0) {
  169222. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169223. if (Al > 0 && pred >= (1<<Al))
  169224. pred = (1<<Al)-1;
  169225. } else {
  169226. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169227. if (Al > 0 && pred >= (1<<Al))
  169228. pred = (1<<Al)-1;
  169229. pred = -pred;
  169230. }
  169231. workspace[8] = (JCOEF) pred;
  169232. }
  169233. /* AC20 */
  169234. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  169235. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  169236. if (num >= 0) {
  169237. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  169238. if (Al > 0 && pred >= (1<<Al))
  169239. pred = (1<<Al)-1;
  169240. } else {
  169241. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  169242. if (Al > 0 && pred >= (1<<Al))
  169243. pred = (1<<Al)-1;
  169244. pred = -pred;
  169245. }
  169246. workspace[16] = (JCOEF) pred;
  169247. }
  169248. /* AC11 */
  169249. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  169250. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  169251. if (num >= 0) {
  169252. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  169253. if (Al > 0 && pred >= (1<<Al))
  169254. pred = (1<<Al)-1;
  169255. } else {
  169256. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  169257. if (Al > 0 && pred >= (1<<Al))
  169258. pred = (1<<Al)-1;
  169259. pred = -pred;
  169260. }
  169261. workspace[9] = (JCOEF) pred;
  169262. }
  169263. /* AC02 */
  169264. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  169265. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  169266. if (num >= 0) {
  169267. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  169268. if (Al > 0 && pred >= (1<<Al))
  169269. pred = (1<<Al)-1;
  169270. } else {
  169271. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  169272. if (Al > 0 && pred >= (1<<Al))
  169273. pred = (1<<Al)-1;
  169274. pred = -pred;
  169275. }
  169276. workspace[2] = (JCOEF) pred;
  169277. }
  169278. /* OK, do the IDCT */
  169279. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  169280. output_ptr, output_col);
  169281. /* Advance for next column */
  169282. DC1 = DC2; DC2 = DC3;
  169283. DC4 = DC5; DC5 = DC6;
  169284. DC7 = DC8; DC8 = DC9;
  169285. buffer_ptr++, prev_block_row++, next_block_row++;
  169286. output_col += compptr->DCT_scaled_size;
  169287. }
  169288. output_ptr += compptr->DCT_scaled_size;
  169289. }
  169290. }
  169291. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169292. return JPEG_ROW_COMPLETED;
  169293. return JPEG_SCAN_COMPLETED;
  169294. }
  169295. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  169296. /*
  169297. * Initialize coefficient buffer controller.
  169298. */
  169299. GLOBAL(void)
  169300. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  169301. {
  169302. my_coef_ptr3 coef;
  169303. coef = (my_coef_ptr3)
  169304. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169305. SIZEOF(my_coef_controller3));
  169306. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  169307. coef->pub.start_input_pass = start_input_pass;
  169308. coef->pub.start_output_pass = start_output_pass;
  169309. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169310. coef->coef_bits_latch = NULL;
  169311. #endif
  169312. /* Create the coefficient buffer. */
  169313. if (need_full_buffer) {
  169314. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169315. /* Allocate a full-image virtual array for each component, */
  169316. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  169317. /* Note we ask for a pre-zeroed array. */
  169318. int ci, access_rows;
  169319. jpeg_component_info *compptr;
  169320. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169321. ci++, compptr++) {
  169322. access_rows = compptr->v_samp_factor;
  169323. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169324. /* If block smoothing could be used, need a bigger window */
  169325. if (cinfo->progressive_mode)
  169326. access_rows *= 3;
  169327. #endif
  169328. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  169329. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  169330. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  169331. (long) compptr->h_samp_factor),
  169332. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  169333. (long) compptr->v_samp_factor),
  169334. (JDIMENSION) access_rows);
  169335. }
  169336. coef->pub.consume_data = consume_data;
  169337. coef->pub.decompress_data = decompress_data;
  169338. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  169339. #else
  169340. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169341. #endif
  169342. } else {
  169343. /* We only need a single-MCU buffer. */
  169344. JBLOCKROW buffer;
  169345. int i;
  169346. buffer = (JBLOCKROW)
  169347. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169348. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  169349. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  169350. coef->MCU_buffer[i] = buffer + i;
  169351. }
  169352. coef->pub.consume_data = dummy_consume_data;
  169353. coef->pub.decompress_data = decompress_onepass;
  169354. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  169355. }
  169356. }
  169357. /*** End of inlined file: jdcoefct.c ***/
  169358. #undef FIX
  169359. /*** Start of inlined file: jdcolor.c ***/
  169360. #define JPEG_INTERNALS
  169361. /* Private subobject */
  169362. typedef struct {
  169363. struct jpeg_color_deconverter pub; /* public fields */
  169364. /* Private state for YCC->RGB conversion */
  169365. int * Cr_r_tab; /* => table for Cr to R conversion */
  169366. int * Cb_b_tab; /* => table for Cb to B conversion */
  169367. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  169368. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  169369. } my_color_deconverter2;
  169370. typedef my_color_deconverter2 * my_cconvert_ptr2;
  169371. /**************** YCbCr -> RGB conversion: most common case **************/
  169372. /*
  169373. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  169374. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  169375. * The conversion equations to be implemented are therefore
  169376. * R = Y + 1.40200 * Cr
  169377. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  169378. * B = Y + 1.77200 * Cb
  169379. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  169380. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  169381. *
  169382. * To avoid floating-point arithmetic, we represent the fractional constants
  169383. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  169384. * the products by 2^16, with appropriate rounding, to get the correct answer.
  169385. * Notice that Y, being an integral input, does not contribute any fraction
  169386. * so it need not participate in the rounding.
  169387. *
  169388. * For even more speed, we avoid doing any multiplications in the inner loop
  169389. * by precalculating the constants times Cb and Cr for all possible values.
  169390. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  169391. * for 12-bit samples it is still acceptable. It's not very reasonable for
  169392. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  169393. * colorspace anyway.
  169394. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  169395. * values for the G calculation are left scaled up, since we must add them
  169396. * together before rounding.
  169397. */
  169398. #define SCALEBITS 16 /* speediest right-shift on some machines */
  169399. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  169400. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  169401. /*
  169402. * Initialize tables for YCC->RGB colorspace conversion.
  169403. */
  169404. LOCAL(void)
  169405. build_ycc_rgb_table (j_decompress_ptr cinfo)
  169406. {
  169407. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169408. int i;
  169409. INT32 x;
  169410. SHIFT_TEMPS
  169411. cconvert->Cr_r_tab = (int *)
  169412. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169413. (MAXJSAMPLE+1) * SIZEOF(int));
  169414. cconvert->Cb_b_tab = (int *)
  169415. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169416. (MAXJSAMPLE+1) * SIZEOF(int));
  169417. cconvert->Cr_g_tab = (INT32 *)
  169418. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169419. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169420. cconvert->Cb_g_tab = (INT32 *)
  169421. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169422. (MAXJSAMPLE+1) * SIZEOF(INT32));
  169423. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  169424. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  169425. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  169426. /* Cr=>R value is nearest int to 1.40200 * x */
  169427. cconvert->Cr_r_tab[i] = (int)
  169428. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  169429. /* Cb=>B value is nearest int to 1.77200 * x */
  169430. cconvert->Cb_b_tab[i] = (int)
  169431. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  169432. /* Cr=>G value is scaled-up -0.71414 * x */
  169433. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  169434. /* Cb=>G value is scaled-up -0.34414 * x */
  169435. /* We also add in ONE_HALF so that need not do it in inner loop */
  169436. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  169437. }
  169438. }
  169439. /*
  169440. * Convert some rows of samples to the output colorspace.
  169441. *
  169442. * Note that we change from noninterleaved, one-plane-per-component format
  169443. * to interleaved-pixel format. The output buffer is therefore three times
  169444. * as wide as the input buffer.
  169445. * A starting row offset is provided only for the input buffer. The caller
  169446. * can easily adjust the passed output_buf value to accommodate any row
  169447. * offset required on that side.
  169448. */
  169449. METHODDEF(void)
  169450. ycc_rgb_convert (j_decompress_ptr cinfo,
  169451. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169452. JSAMPARRAY output_buf, int num_rows)
  169453. {
  169454. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169455. register int y, cb, cr;
  169456. register JSAMPROW outptr;
  169457. register JSAMPROW inptr0, inptr1, inptr2;
  169458. register JDIMENSION col;
  169459. JDIMENSION num_cols = cinfo->output_width;
  169460. /* copy these pointers into registers if possible */
  169461. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169462. register int * Crrtab = cconvert->Cr_r_tab;
  169463. register int * Cbbtab = cconvert->Cb_b_tab;
  169464. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169465. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169466. SHIFT_TEMPS
  169467. while (--num_rows >= 0) {
  169468. inptr0 = input_buf[0][input_row];
  169469. inptr1 = input_buf[1][input_row];
  169470. inptr2 = input_buf[2][input_row];
  169471. input_row++;
  169472. outptr = *output_buf++;
  169473. for (col = 0; col < num_cols; col++) {
  169474. y = GETJSAMPLE(inptr0[col]);
  169475. cb = GETJSAMPLE(inptr1[col]);
  169476. cr = GETJSAMPLE(inptr2[col]);
  169477. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169478. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  169479. outptr[RGB_GREEN] = range_limit[y +
  169480. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169481. SCALEBITS))];
  169482. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  169483. outptr += RGB_PIXELSIZE;
  169484. }
  169485. }
  169486. }
  169487. /**************** Cases other than YCbCr -> RGB **************/
  169488. /*
  169489. * Color conversion for no colorspace change: just copy the data,
  169490. * converting from separate-planes to interleaved representation.
  169491. */
  169492. METHODDEF(void)
  169493. null_convert2 (j_decompress_ptr cinfo,
  169494. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169495. JSAMPARRAY output_buf, int num_rows)
  169496. {
  169497. register JSAMPROW inptr, outptr;
  169498. register JDIMENSION count;
  169499. register int num_components = cinfo->num_components;
  169500. JDIMENSION num_cols = cinfo->output_width;
  169501. int ci;
  169502. while (--num_rows >= 0) {
  169503. for (ci = 0; ci < num_components; ci++) {
  169504. inptr = input_buf[ci][input_row];
  169505. outptr = output_buf[0] + ci;
  169506. for (count = num_cols; count > 0; count--) {
  169507. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  169508. outptr += num_components;
  169509. }
  169510. }
  169511. input_row++;
  169512. output_buf++;
  169513. }
  169514. }
  169515. /*
  169516. * Color conversion for grayscale: just copy the data.
  169517. * This also works for YCbCr -> grayscale conversion, in which
  169518. * we just copy the Y (luminance) component and ignore chrominance.
  169519. */
  169520. METHODDEF(void)
  169521. grayscale_convert2 (j_decompress_ptr cinfo,
  169522. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169523. JSAMPARRAY output_buf, int num_rows)
  169524. {
  169525. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  169526. num_rows, cinfo->output_width);
  169527. }
  169528. /*
  169529. * Convert grayscale to RGB: just duplicate the graylevel three times.
  169530. * This is provided to support applications that don't want to cope
  169531. * with grayscale as a separate case.
  169532. */
  169533. METHODDEF(void)
  169534. gray_rgb_convert (j_decompress_ptr cinfo,
  169535. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169536. JSAMPARRAY output_buf, int num_rows)
  169537. {
  169538. register JSAMPROW inptr, outptr;
  169539. register JDIMENSION col;
  169540. JDIMENSION num_cols = cinfo->output_width;
  169541. while (--num_rows >= 0) {
  169542. inptr = input_buf[0][input_row++];
  169543. outptr = *output_buf++;
  169544. for (col = 0; col < num_cols; col++) {
  169545. /* We can dispense with GETJSAMPLE() here */
  169546. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  169547. outptr += RGB_PIXELSIZE;
  169548. }
  169549. }
  169550. }
  169551. /*
  169552. * Adobe-style YCCK->CMYK conversion.
  169553. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  169554. * conversion as above, while passing K (black) unchanged.
  169555. * We assume build_ycc_rgb_table has been called.
  169556. */
  169557. METHODDEF(void)
  169558. ycck_cmyk_convert (j_decompress_ptr cinfo,
  169559. JSAMPIMAGE input_buf, JDIMENSION input_row,
  169560. JSAMPARRAY output_buf, int num_rows)
  169561. {
  169562. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  169563. register int y, cb, cr;
  169564. register JSAMPROW outptr;
  169565. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  169566. register JDIMENSION col;
  169567. JDIMENSION num_cols = cinfo->output_width;
  169568. /* copy these pointers into registers if possible */
  169569. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  169570. register int * Crrtab = cconvert->Cr_r_tab;
  169571. register int * Cbbtab = cconvert->Cb_b_tab;
  169572. register INT32 * Crgtab = cconvert->Cr_g_tab;
  169573. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  169574. SHIFT_TEMPS
  169575. while (--num_rows >= 0) {
  169576. inptr0 = input_buf[0][input_row];
  169577. inptr1 = input_buf[1][input_row];
  169578. inptr2 = input_buf[2][input_row];
  169579. inptr3 = input_buf[3][input_row];
  169580. input_row++;
  169581. outptr = *output_buf++;
  169582. for (col = 0; col < num_cols; col++) {
  169583. y = GETJSAMPLE(inptr0[col]);
  169584. cb = GETJSAMPLE(inptr1[col]);
  169585. cr = GETJSAMPLE(inptr2[col]);
  169586. /* Range-limiting is essential due to noise introduced by DCT losses. */
  169587. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  169588. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  169589. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  169590. SCALEBITS)))];
  169591. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  169592. /* K passes through unchanged */
  169593. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  169594. outptr += 4;
  169595. }
  169596. }
  169597. }
  169598. /*
  169599. * Empty method for start_pass.
  169600. */
  169601. METHODDEF(void)
  169602. start_pass_dcolor (j_decompress_ptr)
  169603. {
  169604. /* no work needed */
  169605. }
  169606. /*
  169607. * Module initialization routine for output colorspace conversion.
  169608. */
  169609. GLOBAL(void)
  169610. jinit_color_deconverter (j_decompress_ptr cinfo)
  169611. {
  169612. my_cconvert_ptr2 cconvert;
  169613. int ci;
  169614. cconvert = (my_cconvert_ptr2)
  169615. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169616. SIZEOF(my_color_deconverter2));
  169617. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  169618. cconvert->pub.start_pass = start_pass_dcolor;
  169619. /* Make sure num_components agrees with jpeg_color_space */
  169620. switch (cinfo->jpeg_color_space) {
  169621. case JCS_GRAYSCALE:
  169622. if (cinfo->num_components != 1)
  169623. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169624. break;
  169625. case JCS_RGB:
  169626. case JCS_YCbCr:
  169627. if (cinfo->num_components != 3)
  169628. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169629. break;
  169630. case JCS_CMYK:
  169631. case JCS_YCCK:
  169632. if (cinfo->num_components != 4)
  169633. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169634. break;
  169635. default: /* JCS_UNKNOWN can be anything */
  169636. if (cinfo->num_components < 1)
  169637. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  169638. break;
  169639. }
  169640. /* Set out_color_components and conversion method based on requested space.
  169641. * Also clear the component_needed flags for any unused components,
  169642. * so that earlier pipeline stages can avoid useless computation.
  169643. */
  169644. switch (cinfo->out_color_space) {
  169645. case JCS_GRAYSCALE:
  169646. cinfo->out_color_components = 1;
  169647. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  169648. cinfo->jpeg_color_space == JCS_YCbCr) {
  169649. cconvert->pub.color_convert = grayscale_convert2;
  169650. /* For color->grayscale conversion, only the Y (0) component is needed */
  169651. for (ci = 1; ci < cinfo->num_components; ci++)
  169652. cinfo->comp_info[ci].component_needed = FALSE;
  169653. } else
  169654. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169655. break;
  169656. case JCS_RGB:
  169657. cinfo->out_color_components = RGB_PIXELSIZE;
  169658. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  169659. cconvert->pub.color_convert = ycc_rgb_convert;
  169660. build_ycc_rgb_table(cinfo);
  169661. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  169662. cconvert->pub.color_convert = gray_rgb_convert;
  169663. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  169664. cconvert->pub.color_convert = null_convert2;
  169665. } else
  169666. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169667. break;
  169668. case JCS_CMYK:
  169669. cinfo->out_color_components = 4;
  169670. if (cinfo->jpeg_color_space == JCS_YCCK) {
  169671. cconvert->pub.color_convert = ycck_cmyk_convert;
  169672. build_ycc_rgb_table(cinfo);
  169673. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  169674. cconvert->pub.color_convert = null_convert2;
  169675. } else
  169676. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169677. break;
  169678. default:
  169679. /* Permit null conversion to same output space */
  169680. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  169681. cinfo->out_color_components = cinfo->num_components;
  169682. cconvert->pub.color_convert = null_convert2;
  169683. } else /* unsupported non-null conversion */
  169684. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  169685. break;
  169686. }
  169687. if (cinfo->quantize_colors)
  169688. cinfo->output_components = 1; /* single colormapped output component */
  169689. else
  169690. cinfo->output_components = cinfo->out_color_components;
  169691. }
  169692. /*** End of inlined file: jdcolor.c ***/
  169693. #undef FIX
  169694. /*** Start of inlined file: jddctmgr.c ***/
  169695. #define JPEG_INTERNALS
  169696. /*
  169697. * The decompressor input side (jdinput.c) saves away the appropriate
  169698. * quantization table for each component at the start of the first scan
  169699. * involving that component. (This is necessary in order to correctly
  169700. * decode files that reuse Q-table slots.)
  169701. * When we are ready to make an output pass, the saved Q-table is converted
  169702. * to a multiplier table that will actually be used by the IDCT routine.
  169703. * The multiplier table contents are IDCT-method-dependent. To support
  169704. * application changes in IDCT method between scans, we can remake the
  169705. * multiplier tables if necessary.
  169706. * In buffered-image mode, the first output pass may occur before any data
  169707. * has been seen for some components, and thus before their Q-tables have
  169708. * been saved away. To handle this case, multiplier tables are preset
  169709. * to zeroes; the result of the IDCT will be a neutral gray level.
  169710. */
  169711. /* Private subobject for this module */
  169712. typedef struct {
  169713. struct jpeg_inverse_dct pub; /* public fields */
  169714. /* This array contains the IDCT method code that each multiplier table
  169715. * is currently set up for, or -1 if it's not yet set up.
  169716. * The actual multiplier tables are pointed to by dct_table in the
  169717. * per-component comp_info structures.
  169718. */
  169719. int cur_method[MAX_COMPONENTS];
  169720. } my_idct_controller;
  169721. typedef my_idct_controller * my_idct_ptr;
  169722. /* Allocated multiplier tables: big enough for any supported variant */
  169723. typedef union {
  169724. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  169725. #ifdef DCT_IFAST_SUPPORTED
  169726. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  169727. #endif
  169728. #ifdef DCT_FLOAT_SUPPORTED
  169729. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  169730. #endif
  169731. } multiplier_table;
  169732. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  169733. * so be sure to compile that code if either ISLOW or SCALING is requested.
  169734. */
  169735. #ifdef DCT_ISLOW_SUPPORTED
  169736. #define PROVIDE_ISLOW_TABLES
  169737. #else
  169738. #ifdef IDCT_SCALING_SUPPORTED
  169739. #define PROVIDE_ISLOW_TABLES
  169740. #endif
  169741. #endif
  169742. /*
  169743. * Prepare for an output pass.
  169744. * Here we select the proper IDCT routine for each component and build
  169745. * a matching multiplier table.
  169746. */
  169747. METHODDEF(void)
  169748. start_pass (j_decompress_ptr cinfo)
  169749. {
  169750. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  169751. int ci, i;
  169752. jpeg_component_info *compptr;
  169753. int method = 0;
  169754. inverse_DCT_method_ptr method_ptr = NULL;
  169755. JQUANT_TBL * qtbl;
  169756. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169757. ci++, compptr++) {
  169758. /* Select the proper IDCT routine for this component's scaling */
  169759. switch (compptr->DCT_scaled_size) {
  169760. #ifdef IDCT_SCALING_SUPPORTED
  169761. case 1:
  169762. method_ptr = jpeg_idct_1x1;
  169763. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169764. break;
  169765. case 2:
  169766. method_ptr = jpeg_idct_2x2;
  169767. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169768. break;
  169769. case 4:
  169770. method_ptr = jpeg_idct_4x4;
  169771. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  169772. break;
  169773. #endif
  169774. case DCTSIZE:
  169775. switch (cinfo->dct_method) {
  169776. #ifdef DCT_ISLOW_SUPPORTED
  169777. case JDCT_ISLOW:
  169778. method_ptr = jpeg_idct_islow;
  169779. method = JDCT_ISLOW;
  169780. break;
  169781. #endif
  169782. #ifdef DCT_IFAST_SUPPORTED
  169783. case JDCT_IFAST:
  169784. method_ptr = jpeg_idct_ifast;
  169785. method = JDCT_IFAST;
  169786. break;
  169787. #endif
  169788. #ifdef DCT_FLOAT_SUPPORTED
  169789. case JDCT_FLOAT:
  169790. method_ptr = jpeg_idct_float;
  169791. method = JDCT_FLOAT;
  169792. break;
  169793. #endif
  169794. default:
  169795. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169796. break;
  169797. }
  169798. break;
  169799. default:
  169800. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  169801. break;
  169802. }
  169803. idct->pub.inverse_DCT[ci] = method_ptr;
  169804. /* Create multiplier table from quant table.
  169805. * However, we can skip this if the component is uninteresting
  169806. * or if we already built the table. Also, if no quant table
  169807. * has yet been saved for the component, we leave the
  169808. * multiplier table all-zero; we'll be reading zeroes from the
  169809. * coefficient controller's buffer anyway.
  169810. */
  169811. if (! compptr->component_needed || idct->cur_method[ci] == method)
  169812. continue;
  169813. qtbl = compptr->quant_table;
  169814. if (qtbl == NULL) /* happens if no data yet for component */
  169815. continue;
  169816. idct->cur_method[ci] = method;
  169817. switch (method) {
  169818. #ifdef PROVIDE_ISLOW_TABLES
  169819. case JDCT_ISLOW:
  169820. {
  169821. /* For LL&M IDCT method, multipliers are equal to raw quantization
  169822. * coefficients, but are stored as ints to ensure access efficiency.
  169823. */
  169824. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  169825. for (i = 0; i < DCTSIZE2; i++) {
  169826. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  169827. }
  169828. }
  169829. break;
  169830. #endif
  169831. #ifdef DCT_IFAST_SUPPORTED
  169832. case JDCT_IFAST:
  169833. {
  169834. /* For AA&N IDCT method, multipliers are equal to quantization
  169835. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169836. * scalefactor[0] = 1
  169837. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169838. * For integer operation, the multiplier table is to be scaled by
  169839. * IFAST_SCALE_BITS.
  169840. */
  169841. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  169842. #define CONST_BITS 14
  169843. static const INT16 aanscales[DCTSIZE2] = {
  169844. /* precomputed values scaled up by 14 bits */
  169845. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169846. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  169847. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  169848. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  169849. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  169850. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  169851. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  169852. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  169853. };
  169854. SHIFT_TEMPS
  169855. for (i = 0; i < DCTSIZE2; i++) {
  169856. ifmtbl[i] = (IFAST_MULT_TYPE)
  169857. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  169858. (INT32) aanscales[i]),
  169859. CONST_BITS-IFAST_SCALE_BITS);
  169860. }
  169861. }
  169862. break;
  169863. #endif
  169864. #ifdef DCT_FLOAT_SUPPORTED
  169865. case JDCT_FLOAT:
  169866. {
  169867. /* For float AA&N IDCT method, multipliers are equal to quantization
  169868. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  169869. * scalefactor[0] = 1
  169870. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  169871. */
  169872. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  169873. int row, col;
  169874. static const double aanscalefactor[DCTSIZE] = {
  169875. 1.0, 1.387039845, 1.306562965, 1.175875602,
  169876. 1.0, 0.785694958, 0.541196100, 0.275899379
  169877. };
  169878. i = 0;
  169879. for (row = 0; row < DCTSIZE; row++) {
  169880. for (col = 0; col < DCTSIZE; col++) {
  169881. fmtbl[i] = (FLOAT_MULT_TYPE)
  169882. ((double) qtbl->quantval[i] *
  169883. aanscalefactor[row] * aanscalefactor[col]);
  169884. i++;
  169885. }
  169886. }
  169887. }
  169888. break;
  169889. #endif
  169890. default:
  169891. ERREXIT(cinfo, JERR_NOT_COMPILED);
  169892. break;
  169893. }
  169894. }
  169895. }
  169896. /*
  169897. * Initialize IDCT manager.
  169898. */
  169899. GLOBAL(void)
  169900. jinit_inverse_dct (j_decompress_ptr cinfo)
  169901. {
  169902. my_idct_ptr idct;
  169903. int ci;
  169904. jpeg_component_info *compptr;
  169905. idct = (my_idct_ptr)
  169906. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169907. SIZEOF(my_idct_controller));
  169908. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  169909. idct->pub.start_pass = start_pass;
  169910. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169911. ci++, compptr++) {
  169912. /* Allocate and pre-zero a multiplier table for each component */
  169913. compptr->dct_table =
  169914. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169915. SIZEOF(multiplier_table));
  169916. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  169917. /* Mark multiplier table not yet set up for any method */
  169918. idct->cur_method[ci] = -1;
  169919. }
  169920. }
  169921. /*** End of inlined file: jddctmgr.c ***/
  169922. #undef CONST_BITS
  169923. #undef ASSIGN_STATE
  169924. /*** Start of inlined file: jdhuff.c ***/
  169925. #define JPEG_INTERNALS
  169926. /*** Start of inlined file: jdhuff.h ***/
  169927. /* Short forms of external names for systems with brain-damaged linkers. */
  169928. #ifndef __jdhuff_h__
  169929. #define __jdhuff_h__
  169930. #ifdef NEED_SHORT_EXTERNAL_NAMES
  169931. #define jpeg_make_d_derived_tbl jMkDDerived
  169932. #define jpeg_fill_bit_buffer jFilBitBuf
  169933. #define jpeg_huff_decode jHufDecode
  169934. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  169935. /* Derived data constructed for each Huffman table */
  169936. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  169937. typedef struct {
  169938. /* Basic tables: (element [0] of each array is unused) */
  169939. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  169940. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  169941. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  169942. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  169943. * the smallest code of length k; so given a code of length k, the
  169944. * corresponding symbol is huffval[code + valoffset[k]]
  169945. */
  169946. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  169947. JHUFF_TBL *pub;
  169948. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  169949. * the input data stream. If the next Huffman code is no more
  169950. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  169951. * the corresponding symbol directly from these tables.
  169952. */
  169953. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  169954. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  169955. } d_derived_tbl;
  169956. /* Expand a Huffman table definition into the derived format */
  169957. EXTERN(void) jpeg_make_d_derived_tbl
  169958. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  169959. d_derived_tbl ** pdtbl));
  169960. /*
  169961. * Fetching the next N bits from the input stream is a time-critical operation
  169962. * for the Huffman decoders. We implement it with a combination of inline
  169963. * macros and out-of-line subroutines. Note that N (the number of bits
  169964. * demanded at one time) never exceeds 15 for JPEG use.
  169965. *
  169966. * We read source bytes into get_buffer and dole out bits as needed.
  169967. * If get_buffer already contains enough bits, they are fetched in-line
  169968. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  169969. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  169970. * as full as possible (not just to the number of bits needed; this
  169971. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  169972. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  169973. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  169974. * at least the requested number of bits --- dummy zeroes are inserted if
  169975. * necessary.
  169976. */
  169977. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  169978. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  169979. /* If long is > 32 bits on your machine, and shifting/masking longs is
  169980. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  169981. * appropriately should be a win. Unfortunately we can't define the size
  169982. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  169983. * because not all machines measure sizeof in 8-bit bytes.
  169984. */
  169985. typedef struct { /* Bitreading state saved across MCUs */
  169986. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169987. int bits_left; /* # of unused bits in it */
  169988. } bitread_perm_state;
  169989. typedef struct { /* Bitreading working state within an MCU */
  169990. /* Current data source location */
  169991. /* We need a copy, rather than munging the original, in case of suspension */
  169992. const JOCTET * next_input_byte; /* => next byte to read from source */
  169993. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  169994. /* Bit input buffer --- note these values are kept in register variables,
  169995. * not in this struct, inside the inner loops.
  169996. */
  169997. bit_buf_type get_buffer; /* current bit-extraction buffer */
  169998. int bits_left; /* # of unused bits in it */
  169999. /* Pointer needed by jpeg_fill_bit_buffer. */
  170000. j_decompress_ptr cinfo; /* back link to decompress master record */
  170001. } bitread_working_state;
  170002. /* Macros to declare and load/save bitread local variables. */
  170003. #define BITREAD_STATE_VARS \
  170004. register bit_buf_type get_buffer; \
  170005. register int bits_left; \
  170006. bitread_working_state br_state
  170007. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  170008. br_state.cinfo = cinfop; \
  170009. br_state.next_input_byte = cinfop->src->next_input_byte; \
  170010. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  170011. get_buffer = permstate.get_buffer; \
  170012. bits_left = permstate.bits_left;
  170013. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  170014. cinfop->src->next_input_byte = br_state.next_input_byte; \
  170015. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  170016. permstate.get_buffer = get_buffer; \
  170017. permstate.bits_left = bits_left
  170018. /*
  170019. * These macros provide the in-line portion of bit fetching.
  170020. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  170021. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  170022. * The variables get_buffer and bits_left are assumed to be locals,
  170023. * but the state struct might not be (jpeg_huff_decode needs this).
  170024. * CHECK_BIT_BUFFER(state,n,action);
  170025. * Ensure there are N bits in get_buffer; if suspend, take action.
  170026. * val = GET_BITS(n);
  170027. * Fetch next N bits.
  170028. * val = PEEK_BITS(n);
  170029. * Fetch next N bits without removing them from the buffer.
  170030. * DROP_BITS(n);
  170031. * Discard next N bits.
  170032. * The value N should be a simple variable, not an expression, because it
  170033. * is evaluated multiple times.
  170034. */
  170035. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170036. { if (bits_left < (nbits)) { \
  170037. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170038. { action; } \
  170039. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170040. #define GET_BITS(nbits) \
  170041. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170042. #define PEEK_BITS(nbits) \
  170043. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170044. #define DROP_BITS(nbits) \
  170045. (bits_left -= (nbits))
  170046. /* Load up the bit buffer to a depth of at least nbits */
  170047. EXTERN(boolean) jpeg_fill_bit_buffer
  170048. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170049. register int bits_left, int nbits));
  170050. /*
  170051. * Code for extracting next Huffman-coded symbol from input bit stream.
  170052. * Again, this is time-critical and we make the main paths be macros.
  170053. *
  170054. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170055. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170056. * or fewer bits long. The few overlength codes are handled with a loop,
  170057. * which need not be inline code.
  170058. *
  170059. * Notes about the HUFF_DECODE macro:
  170060. * 1. Near the end of the data segment, we may fail to get enough bits
  170061. * for a lookahead. In that case, we do it the hard way.
  170062. * 2. If the lookahead table contains no entry, the next code must be
  170063. * more than HUFF_LOOKAHEAD bits long.
  170064. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170065. */
  170066. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170067. { register int nb, look; \
  170068. if (bits_left < HUFF_LOOKAHEAD) { \
  170069. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170070. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170071. if (bits_left < HUFF_LOOKAHEAD) { \
  170072. nb = 1; goto slowlabel; \
  170073. } \
  170074. } \
  170075. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170076. if ((nb = htbl->look_nbits[look]) != 0) { \
  170077. DROP_BITS(nb); \
  170078. result = htbl->look_sym[look]; \
  170079. } else { \
  170080. nb = HUFF_LOOKAHEAD+1; \
  170081. slowlabel: \
  170082. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170083. { failaction; } \
  170084. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170085. } \
  170086. }
  170087. /* Out-of-line case for Huffman code fetching */
  170088. EXTERN(int) jpeg_huff_decode
  170089. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170090. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170091. #endif
  170092. /*** End of inlined file: jdhuff.h ***/
  170093. /* Declarations shared with jdphuff.c */
  170094. /*
  170095. * Expanded entropy decoder object for Huffman decoding.
  170096. *
  170097. * The savable_state subrecord contains fields that change within an MCU,
  170098. * but must not be updated permanently until we complete the MCU.
  170099. */
  170100. typedef struct {
  170101. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170102. } savable_state2;
  170103. /* This macro is to work around compilers with missing or broken
  170104. * structure assignment. You'll need to fix this code if you have
  170105. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170106. */
  170107. #ifndef NO_STRUCT_ASSIGN
  170108. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170109. #else
  170110. #if MAX_COMPS_IN_SCAN == 4
  170111. #define ASSIGN_STATE(dest,src) \
  170112. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170113. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170114. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170115. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170116. #endif
  170117. #endif
  170118. typedef struct {
  170119. struct jpeg_entropy_decoder pub; /* public fields */
  170120. /* These fields are loaded into local variables at start of each MCU.
  170121. * In case of suspension, we exit WITHOUT updating them.
  170122. */
  170123. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170124. savable_state2 saved; /* Other state at start of MCU */
  170125. /* These fields are NOT loaded into local working state. */
  170126. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170127. /* Pointers to derived tables (these workspaces have image lifespan) */
  170128. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170129. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170130. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170131. /* Pointers to derived tables to be used for each block within an MCU */
  170132. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170133. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170134. /* Whether we care about the DC and AC coefficient values for each block */
  170135. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170136. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170137. } huff_entropy_decoder2;
  170138. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170139. /*
  170140. * Initialize for a Huffman-compressed scan.
  170141. */
  170142. METHODDEF(void)
  170143. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170144. {
  170145. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170146. int ci, blkn, dctbl, actbl;
  170147. jpeg_component_info * compptr;
  170148. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170149. * This ought to be an error condition, but we make it a warning because
  170150. * there are some baseline files out there with all zeroes in these bytes.
  170151. */
  170152. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170153. cinfo->Ah != 0 || cinfo->Al != 0)
  170154. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170155. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170156. compptr = cinfo->cur_comp_info[ci];
  170157. dctbl = compptr->dc_tbl_no;
  170158. actbl = compptr->ac_tbl_no;
  170159. /* Compute derived values for Huffman tables */
  170160. /* We may do this more than once for a table, but it's not expensive */
  170161. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170162. & entropy->dc_derived_tbls[dctbl]);
  170163. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170164. & entropy->ac_derived_tbls[actbl]);
  170165. /* Initialize DC predictions to 0 */
  170166. entropy->saved.last_dc_val[ci] = 0;
  170167. }
  170168. /* Precalculate decoding info for each block in an MCU of this scan */
  170169. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170170. ci = cinfo->MCU_membership[blkn];
  170171. compptr = cinfo->cur_comp_info[ci];
  170172. /* Precalculate which table to use for each block */
  170173. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170174. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170175. /* Decide whether we really care about the coefficient values */
  170176. if (compptr->component_needed) {
  170177. entropy->dc_needed[blkn] = TRUE;
  170178. /* we don't need the ACs if producing a 1/8th-size image */
  170179. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170180. } else {
  170181. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170182. }
  170183. }
  170184. /* Initialize bitread state variables */
  170185. entropy->bitstate.bits_left = 0;
  170186. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170187. entropy->pub.insufficient_data = FALSE;
  170188. /* Initialize restart counter */
  170189. entropy->restarts_to_go = cinfo->restart_interval;
  170190. }
  170191. /*
  170192. * Compute the derived values for a Huffman table.
  170193. * This routine also performs some validation checks on the table.
  170194. *
  170195. * Note this is also used by jdphuff.c.
  170196. */
  170197. GLOBAL(void)
  170198. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170199. d_derived_tbl ** pdtbl)
  170200. {
  170201. JHUFF_TBL *htbl;
  170202. d_derived_tbl *dtbl;
  170203. int p, i, l, si, numsymbols;
  170204. int lookbits, ctr;
  170205. char huffsize[257];
  170206. unsigned int huffcode[257];
  170207. unsigned int code;
  170208. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170209. * paralleling the order of the symbols themselves in htbl->huffval[].
  170210. */
  170211. /* Find the input Huffman table */
  170212. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170213. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170214. htbl =
  170215. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170216. if (htbl == NULL)
  170217. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170218. /* Allocate a workspace if we haven't already done so. */
  170219. if (*pdtbl == NULL)
  170220. *pdtbl = (d_derived_tbl *)
  170221. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170222. SIZEOF(d_derived_tbl));
  170223. dtbl = *pdtbl;
  170224. dtbl->pub = htbl; /* fill in back link */
  170225. /* Figure C.1: make table of Huffman code length for each symbol */
  170226. p = 0;
  170227. for (l = 1; l <= 16; l++) {
  170228. i = (int) htbl->bits[l];
  170229. if (i < 0 || p + i > 256) /* protect against table overrun */
  170230. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170231. while (i--)
  170232. huffsize[p++] = (char) l;
  170233. }
  170234. huffsize[p] = 0;
  170235. numsymbols = p;
  170236. /* Figure C.2: generate the codes themselves */
  170237. /* We also validate that the counts represent a legal Huffman code tree. */
  170238. code = 0;
  170239. si = huffsize[0];
  170240. p = 0;
  170241. while (huffsize[p]) {
  170242. while (((int) huffsize[p]) == si) {
  170243. huffcode[p++] = code;
  170244. code++;
  170245. }
  170246. /* code is now 1 more than the last code used for codelength si; but
  170247. * it must still fit in si bits, since no code is allowed to be all ones.
  170248. */
  170249. if (((INT32) code) >= (((INT32) 1) << si))
  170250. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170251. code <<= 1;
  170252. si++;
  170253. }
  170254. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  170255. p = 0;
  170256. for (l = 1; l <= 16; l++) {
  170257. if (htbl->bits[l]) {
  170258. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  170259. * minus the minimum code of length l
  170260. */
  170261. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  170262. p += htbl->bits[l];
  170263. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  170264. } else {
  170265. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  170266. }
  170267. }
  170268. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  170269. /* Compute lookahead tables to speed up decoding.
  170270. * First we set all the table entries to 0, indicating "too long";
  170271. * then we iterate through the Huffman codes that are short enough and
  170272. * fill in all the entries that correspond to bit sequences starting
  170273. * with that code.
  170274. */
  170275. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  170276. p = 0;
  170277. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  170278. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  170279. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  170280. /* Generate left-justified code followed by all possible bit sequences */
  170281. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  170282. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  170283. dtbl->look_nbits[lookbits] = l;
  170284. dtbl->look_sym[lookbits] = htbl->huffval[p];
  170285. lookbits++;
  170286. }
  170287. }
  170288. }
  170289. /* Validate symbols as being reasonable.
  170290. * For AC tables, we make no check, but accept all byte values 0..255.
  170291. * For DC tables, we require the symbols to be in range 0..15.
  170292. * (Tighter bounds could be applied depending on the data depth and mode,
  170293. * but this is sufficient to ensure safe decoding.)
  170294. */
  170295. if (isDC) {
  170296. for (i = 0; i < numsymbols; i++) {
  170297. int sym = htbl->huffval[i];
  170298. if (sym < 0 || sym > 15)
  170299. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  170300. }
  170301. }
  170302. }
  170303. /*
  170304. * Out-of-line code for bit fetching (shared with jdphuff.c).
  170305. * See jdhuff.h for info about usage.
  170306. * Note: current values of get_buffer and bits_left are passed as parameters,
  170307. * but are returned in the corresponding fields of the state struct.
  170308. *
  170309. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  170310. * of get_buffer to be used. (On machines with wider words, an even larger
  170311. * buffer could be used.) However, on some machines 32-bit shifts are
  170312. * quite slow and take time proportional to the number of places shifted.
  170313. * (This is true with most PC compilers, for instance.) In this case it may
  170314. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  170315. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  170316. */
  170317. #ifdef SLOW_SHIFT_32
  170318. #define MIN_GET_BITS 15 /* minimum allowable value */
  170319. #else
  170320. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  170321. #endif
  170322. GLOBAL(boolean)
  170323. jpeg_fill_bit_buffer (bitread_working_state * state,
  170324. register bit_buf_type get_buffer, register int bits_left,
  170325. int nbits)
  170326. /* Load up the bit buffer to a depth of at least nbits */
  170327. {
  170328. /* Copy heavily used state fields into locals (hopefully registers) */
  170329. register const JOCTET * next_input_byte = state->next_input_byte;
  170330. register size_t bytes_in_buffer = state->bytes_in_buffer;
  170331. j_decompress_ptr cinfo = state->cinfo;
  170332. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  170333. /* (It is assumed that no request will be for more than that many bits.) */
  170334. /* We fail to do so only if we hit a marker or are forced to suspend. */
  170335. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  170336. while (bits_left < MIN_GET_BITS) {
  170337. register int c;
  170338. /* Attempt to read a byte */
  170339. if (bytes_in_buffer == 0) {
  170340. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170341. return FALSE;
  170342. next_input_byte = cinfo->src->next_input_byte;
  170343. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170344. }
  170345. bytes_in_buffer--;
  170346. c = GETJOCTET(*next_input_byte++);
  170347. /* If it's 0xFF, check and discard stuffed zero byte */
  170348. if (c == 0xFF) {
  170349. /* Loop here to discard any padding FF's on terminating marker,
  170350. * so that we can save a valid unread_marker value. NOTE: we will
  170351. * accept multiple FF's followed by a 0 as meaning a single FF data
  170352. * byte. This data pattern is not valid according to the standard.
  170353. */
  170354. do {
  170355. if (bytes_in_buffer == 0) {
  170356. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  170357. return FALSE;
  170358. next_input_byte = cinfo->src->next_input_byte;
  170359. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  170360. }
  170361. bytes_in_buffer--;
  170362. c = GETJOCTET(*next_input_byte++);
  170363. } while (c == 0xFF);
  170364. if (c == 0) {
  170365. /* Found FF/00, which represents an FF data byte */
  170366. c = 0xFF;
  170367. } else {
  170368. /* Oops, it's actually a marker indicating end of compressed data.
  170369. * Save the marker code for later use.
  170370. * Fine point: it might appear that we should save the marker into
  170371. * bitread working state, not straight into permanent state. But
  170372. * once we have hit a marker, we cannot need to suspend within the
  170373. * current MCU, because we will read no more bytes from the data
  170374. * source. So it is OK to update permanent state right away.
  170375. */
  170376. cinfo->unread_marker = c;
  170377. /* See if we need to insert some fake zero bits. */
  170378. goto no_more_bytes;
  170379. }
  170380. }
  170381. /* OK, load c into get_buffer */
  170382. get_buffer = (get_buffer << 8) | c;
  170383. bits_left += 8;
  170384. } /* end while */
  170385. } else {
  170386. no_more_bytes:
  170387. /* We get here if we've read the marker that terminates the compressed
  170388. * data segment. There should be enough bits in the buffer register
  170389. * to satisfy the request; if so, no problem.
  170390. */
  170391. if (nbits > bits_left) {
  170392. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  170393. * the data stream, so that we can produce some kind of image.
  170394. * We use a nonvolatile flag to ensure that only one warning message
  170395. * appears per data segment.
  170396. */
  170397. if (! cinfo->entropy->insufficient_data) {
  170398. WARNMS(cinfo, JWRN_HIT_MARKER);
  170399. cinfo->entropy->insufficient_data = TRUE;
  170400. }
  170401. /* Fill the buffer with zero bits */
  170402. get_buffer <<= MIN_GET_BITS - bits_left;
  170403. bits_left = MIN_GET_BITS;
  170404. }
  170405. }
  170406. /* Unload the local registers */
  170407. state->next_input_byte = next_input_byte;
  170408. state->bytes_in_buffer = bytes_in_buffer;
  170409. state->get_buffer = get_buffer;
  170410. state->bits_left = bits_left;
  170411. return TRUE;
  170412. }
  170413. /*
  170414. * Out-of-line code for Huffman code decoding.
  170415. * See jdhuff.h for info about usage.
  170416. */
  170417. GLOBAL(int)
  170418. jpeg_huff_decode (bitread_working_state * state,
  170419. register bit_buf_type get_buffer, register int bits_left,
  170420. d_derived_tbl * htbl, int min_bits)
  170421. {
  170422. register int l = min_bits;
  170423. register INT32 code;
  170424. /* HUFF_DECODE has determined that the code is at least min_bits */
  170425. /* bits long, so fetch that many bits in one swoop. */
  170426. CHECK_BIT_BUFFER(*state, l, return -1);
  170427. code = GET_BITS(l);
  170428. /* Collect the rest of the Huffman code one bit at a time. */
  170429. /* This is per Figure F.16 in the JPEG spec. */
  170430. while (code > htbl->maxcode[l]) {
  170431. code <<= 1;
  170432. CHECK_BIT_BUFFER(*state, 1, return -1);
  170433. code |= GET_BITS(1);
  170434. l++;
  170435. }
  170436. /* Unload the local registers */
  170437. state->get_buffer = get_buffer;
  170438. state->bits_left = bits_left;
  170439. /* With garbage input we may reach the sentinel value l = 17. */
  170440. if (l > 16) {
  170441. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  170442. return 0; /* fake a zero as the safest result */
  170443. }
  170444. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  170445. }
  170446. /*
  170447. * Check for a restart marker & resynchronize decoder.
  170448. * Returns FALSE if must suspend.
  170449. */
  170450. LOCAL(boolean)
  170451. process_restart (j_decompress_ptr cinfo)
  170452. {
  170453. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170454. int ci;
  170455. /* Throw away any unused bits remaining in bit buffer; */
  170456. /* include any full bytes in next_marker's count of discarded bytes */
  170457. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  170458. entropy->bitstate.bits_left = 0;
  170459. /* Advance past the RSTn marker */
  170460. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  170461. return FALSE;
  170462. /* Re-initialize DC predictions to 0 */
  170463. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  170464. entropy->saved.last_dc_val[ci] = 0;
  170465. /* Reset restart counter */
  170466. entropy->restarts_to_go = cinfo->restart_interval;
  170467. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  170468. * against a marker. In that case we will end up treating the next data
  170469. * segment as empty, and we can avoid producing bogus output pixels by
  170470. * leaving the flag set.
  170471. */
  170472. if (cinfo->unread_marker == 0)
  170473. entropy->pub.insufficient_data = FALSE;
  170474. return TRUE;
  170475. }
  170476. /*
  170477. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  170478. * The coefficients are reordered from zigzag order into natural array order,
  170479. * but are not dequantized.
  170480. *
  170481. * The i'th block of the MCU is stored into the block pointed to by
  170482. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  170483. * (Wholesale zeroing is usually a little faster than retail...)
  170484. *
  170485. * Returns FALSE if data source requested suspension. In that case no
  170486. * changes have been made to permanent state. (Exception: some output
  170487. * coefficients may already have been assigned. This is harmless for
  170488. * this module, since we'll just re-assign them on the next call.)
  170489. */
  170490. METHODDEF(boolean)
  170491. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  170492. {
  170493. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170494. int blkn;
  170495. BITREAD_STATE_VARS;
  170496. savable_state2 state;
  170497. /* Process restart marker if needed; may have to suspend */
  170498. if (cinfo->restart_interval) {
  170499. if (entropy->restarts_to_go == 0)
  170500. if (! process_restart(cinfo))
  170501. return FALSE;
  170502. }
  170503. /* If we've run out of data, just leave the MCU set to zeroes.
  170504. * This way, we return uniform gray for the remainder of the segment.
  170505. */
  170506. if (! entropy->pub.insufficient_data) {
  170507. /* Load up working state */
  170508. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  170509. ASSIGN_STATE(state, entropy->saved);
  170510. /* Outer loop handles each block in the MCU */
  170511. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170512. JBLOCKROW block = MCU_data[blkn];
  170513. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  170514. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  170515. register int s, k, r;
  170516. /* Decode a single block's worth of coefficients */
  170517. /* Section F.2.2.1: decode the DC coefficient difference */
  170518. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  170519. if (s) {
  170520. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170521. r = GET_BITS(s);
  170522. s = HUFF_EXTEND(r, s);
  170523. }
  170524. if (entropy->dc_needed[blkn]) {
  170525. /* Convert DC difference to actual value, update last_dc_val */
  170526. int ci = cinfo->MCU_membership[blkn];
  170527. s += state.last_dc_val[ci];
  170528. state.last_dc_val[ci] = s;
  170529. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  170530. (*block)[0] = (JCOEF) s;
  170531. }
  170532. if (entropy->ac_needed[blkn]) {
  170533. /* Section F.2.2.2: decode the AC coefficients */
  170534. /* Since zeroes are skipped, output area must be cleared beforehand */
  170535. for (k = 1; k < DCTSIZE2; k++) {
  170536. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  170537. r = s >> 4;
  170538. s &= 15;
  170539. if (s) {
  170540. k += r;
  170541. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170542. r = GET_BITS(s);
  170543. s = HUFF_EXTEND(r, s);
  170544. /* Output coefficient in natural (dezigzagged) order.
  170545. * Note: the extra entries in jpeg_natural_order[] will save us
  170546. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  170547. */
  170548. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  170549. } else {
  170550. if (r != 15)
  170551. break;
  170552. k += 15;
  170553. }
  170554. }
  170555. } else {
  170556. /* Section F.2.2.2: decode the AC coefficients */
  170557. /* In this path we just discard the values */
  170558. for (k = 1; k < DCTSIZE2; k++) {
  170559. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  170560. r = s >> 4;
  170561. s &= 15;
  170562. if (s) {
  170563. k += r;
  170564. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  170565. DROP_BITS(s);
  170566. } else {
  170567. if (r != 15)
  170568. break;
  170569. k += 15;
  170570. }
  170571. }
  170572. }
  170573. }
  170574. /* Completed MCU, so update state */
  170575. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  170576. ASSIGN_STATE(entropy->saved, state);
  170577. }
  170578. /* Account for restart interval (no-op if not using restarts) */
  170579. entropy->restarts_to_go--;
  170580. return TRUE;
  170581. }
  170582. /*
  170583. * Module initialization routine for Huffman entropy decoding.
  170584. */
  170585. GLOBAL(void)
  170586. jinit_huff_decoder (j_decompress_ptr cinfo)
  170587. {
  170588. huff_entropy_ptr2 entropy;
  170589. int i;
  170590. entropy = (huff_entropy_ptr2)
  170591. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170592. SIZEOF(huff_entropy_decoder2));
  170593. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  170594. entropy->pub.start_pass = start_pass_huff_decoder;
  170595. entropy->pub.decode_mcu = decode_mcu;
  170596. /* Mark tables unallocated */
  170597. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  170598. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  170599. }
  170600. }
  170601. /*** End of inlined file: jdhuff.c ***/
  170602. /*** Start of inlined file: jdinput.c ***/
  170603. #define JPEG_INTERNALS
  170604. /* Private state */
  170605. typedef struct {
  170606. struct jpeg_input_controller pub; /* public fields */
  170607. boolean inheaders; /* TRUE until first SOS is reached */
  170608. } my_input_controller;
  170609. typedef my_input_controller * my_inputctl_ptr;
  170610. /* Forward declarations */
  170611. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  170612. /*
  170613. * Routines to calculate various quantities related to the size of the image.
  170614. */
  170615. LOCAL(void)
  170616. initial_setup2 (j_decompress_ptr cinfo)
  170617. /* Called once, when first SOS marker is reached */
  170618. {
  170619. int ci;
  170620. jpeg_component_info *compptr;
  170621. /* Make sure image isn't bigger than I can handle */
  170622. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  170623. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  170624. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  170625. /* For now, precision must match compiled-in value... */
  170626. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  170627. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  170628. /* Check that number of components won't exceed internal array sizes */
  170629. if (cinfo->num_components > MAX_COMPONENTS)
  170630. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  170631. MAX_COMPONENTS);
  170632. /* Compute maximum sampling factors; check factor validity */
  170633. cinfo->max_h_samp_factor = 1;
  170634. cinfo->max_v_samp_factor = 1;
  170635. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170636. ci++, compptr++) {
  170637. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  170638. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  170639. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  170640. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  170641. compptr->h_samp_factor);
  170642. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  170643. compptr->v_samp_factor);
  170644. }
  170645. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  170646. * In the full decompressor, this will be overridden by jdmaster.c;
  170647. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  170648. */
  170649. cinfo->min_DCT_scaled_size = DCTSIZE;
  170650. /* Compute dimensions of components */
  170651. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170652. ci++, compptr++) {
  170653. compptr->DCT_scaled_size = DCTSIZE;
  170654. /* Size in DCT blocks */
  170655. compptr->width_in_blocks = (JDIMENSION)
  170656. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170657. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  170658. compptr->height_in_blocks = (JDIMENSION)
  170659. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170660. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  170661. /* downsampled_width and downsampled_height will also be overridden by
  170662. * jdmaster.c if we are doing full decompression. The transcoder library
  170663. * doesn't use these values, but the calling application might.
  170664. */
  170665. /* Size in samples */
  170666. compptr->downsampled_width = (JDIMENSION)
  170667. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  170668. (long) cinfo->max_h_samp_factor);
  170669. compptr->downsampled_height = (JDIMENSION)
  170670. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  170671. (long) cinfo->max_v_samp_factor);
  170672. /* Mark component needed, until color conversion says otherwise */
  170673. compptr->component_needed = TRUE;
  170674. /* Mark no quantization table yet saved for component */
  170675. compptr->quant_table = NULL;
  170676. }
  170677. /* Compute number of fully interleaved MCU rows. */
  170678. cinfo->total_iMCU_rows = (JDIMENSION)
  170679. jdiv_round_up((long) cinfo->image_height,
  170680. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170681. /* Decide whether file contains multiple scans */
  170682. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  170683. cinfo->inputctl->has_multiple_scans = TRUE;
  170684. else
  170685. cinfo->inputctl->has_multiple_scans = FALSE;
  170686. }
  170687. LOCAL(void)
  170688. per_scan_setup2 (j_decompress_ptr cinfo)
  170689. /* Do computations that are needed before processing a JPEG scan */
  170690. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  170691. {
  170692. int ci, mcublks, tmp;
  170693. jpeg_component_info *compptr;
  170694. if (cinfo->comps_in_scan == 1) {
  170695. /* Noninterleaved (single-component) scan */
  170696. compptr = cinfo->cur_comp_info[0];
  170697. /* Overall image size in MCUs */
  170698. cinfo->MCUs_per_row = compptr->width_in_blocks;
  170699. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  170700. /* For noninterleaved scan, always one block per MCU */
  170701. compptr->MCU_width = 1;
  170702. compptr->MCU_height = 1;
  170703. compptr->MCU_blocks = 1;
  170704. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  170705. compptr->last_col_width = 1;
  170706. /* For noninterleaved scans, it is convenient to define last_row_height
  170707. * as the number of block rows present in the last iMCU row.
  170708. */
  170709. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  170710. if (tmp == 0) tmp = compptr->v_samp_factor;
  170711. compptr->last_row_height = tmp;
  170712. /* Prepare array describing MCU composition */
  170713. cinfo->blocks_in_MCU = 1;
  170714. cinfo->MCU_membership[0] = 0;
  170715. } else {
  170716. /* Interleaved (multi-component) scan */
  170717. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  170718. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  170719. MAX_COMPS_IN_SCAN);
  170720. /* Overall image size in MCUs */
  170721. cinfo->MCUs_per_row = (JDIMENSION)
  170722. jdiv_round_up((long) cinfo->image_width,
  170723. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  170724. cinfo->MCU_rows_in_scan = (JDIMENSION)
  170725. jdiv_round_up((long) cinfo->image_height,
  170726. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  170727. cinfo->blocks_in_MCU = 0;
  170728. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170729. compptr = cinfo->cur_comp_info[ci];
  170730. /* Sampling factors give # of blocks of component in each MCU */
  170731. compptr->MCU_width = compptr->h_samp_factor;
  170732. compptr->MCU_height = compptr->v_samp_factor;
  170733. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  170734. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  170735. /* Figure number of non-dummy blocks in last MCU column & row */
  170736. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  170737. if (tmp == 0) tmp = compptr->MCU_width;
  170738. compptr->last_col_width = tmp;
  170739. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  170740. if (tmp == 0) tmp = compptr->MCU_height;
  170741. compptr->last_row_height = tmp;
  170742. /* Prepare array describing MCU composition */
  170743. mcublks = compptr->MCU_blocks;
  170744. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  170745. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  170746. while (mcublks-- > 0) {
  170747. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  170748. }
  170749. }
  170750. }
  170751. }
  170752. /*
  170753. * Save away a copy of the Q-table referenced by each component present
  170754. * in the current scan, unless already saved during a prior scan.
  170755. *
  170756. * In a multiple-scan JPEG file, the encoder could assign different components
  170757. * the same Q-table slot number, but change table definitions between scans
  170758. * so that each component uses a different Q-table. (The IJG encoder is not
  170759. * currently capable of doing this, but other encoders might.) Since we want
  170760. * to be able to dequantize all the components at the end of the file, this
  170761. * means that we have to save away the table actually used for each component.
  170762. * We do this by copying the table at the start of the first scan containing
  170763. * the component.
  170764. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  170765. * slot between scans of a component using that slot. If the encoder does so
  170766. * anyway, this decoder will simply use the Q-table values that were current
  170767. * at the start of the first scan for the component.
  170768. *
  170769. * The decompressor output side looks only at the saved quant tables,
  170770. * not at the current Q-table slots.
  170771. */
  170772. LOCAL(void)
  170773. latch_quant_tables (j_decompress_ptr cinfo)
  170774. {
  170775. int ci, qtblno;
  170776. jpeg_component_info *compptr;
  170777. JQUANT_TBL * qtbl;
  170778. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170779. compptr = cinfo->cur_comp_info[ci];
  170780. /* No work if we already saved Q-table for this component */
  170781. if (compptr->quant_table != NULL)
  170782. continue;
  170783. /* Make sure specified quantization table is present */
  170784. qtblno = compptr->quant_tbl_no;
  170785. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  170786. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  170787. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  170788. /* OK, save away the quantization table */
  170789. qtbl = (JQUANT_TBL *)
  170790. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170791. SIZEOF(JQUANT_TBL));
  170792. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  170793. compptr->quant_table = qtbl;
  170794. }
  170795. }
  170796. /*
  170797. * Initialize the input modules to read a scan of compressed data.
  170798. * The first call to this is done by jdmaster.c after initializing
  170799. * the entire decompressor (during jpeg_start_decompress).
  170800. * Subsequent calls come from consume_markers, below.
  170801. */
  170802. METHODDEF(void)
  170803. start_input_pass2 (j_decompress_ptr cinfo)
  170804. {
  170805. per_scan_setup2(cinfo);
  170806. latch_quant_tables(cinfo);
  170807. (*cinfo->entropy->start_pass) (cinfo);
  170808. (*cinfo->coef->start_input_pass) (cinfo);
  170809. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  170810. }
  170811. /*
  170812. * Finish up after inputting a compressed-data scan.
  170813. * This is called by the coefficient controller after it's read all
  170814. * the expected data of the scan.
  170815. */
  170816. METHODDEF(void)
  170817. finish_input_pass (j_decompress_ptr cinfo)
  170818. {
  170819. cinfo->inputctl->consume_input = consume_markers;
  170820. }
  170821. /*
  170822. * Read JPEG markers before, between, or after compressed-data scans.
  170823. * Change state as necessary when a new scan is reached.
  170824. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  170825. *
  170826. * The consume_input method pointer points either here or to the
  170827. * coefficient controller's consume_data routine, depending on whether
  170828. * we are reading a compressed data segment or inter-segment markers.
  170829. */
  170830. METHODDEF(int)
  170831. consume_markers (j_decompress_ptr cinfo)
  170832. {
  170833. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170834. int val;
  170835. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  170836. return JPEG_REACHED_EOI;
  170837. val = (*cinfo->marker->read_markers) (cinfo);
  170838. switch (val) {
  170839. case JPEG_REACHED_SOS: /* Found SOS */
  170840. if (inputctl->inheaders) { /* 1st SOS */
  170841. initial_setup2(cinfo);
  170842. inputctl->inheaders = FALSE;
  170843. /* Note: start_input_pass must be called by jdmaster.c
  170844. * before any more input can be consumed. jdapimin.c is
  170845. * responsible for enforcing this sequencing.
  170846. */
  170847. } else { /* 2nd or later SOS marker */
  170848. if (! inputctl->pub.has_multiple_scans)
  170849. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  170850. start_input_pass2(cinfo);
  170851. }
  170852. break;
  170853. case JPEG_REACHED_EOI: /* Found EOI */
  170854. inputctl->pub.eoi_reached = TRUE;
  170855. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  170856. if (cinfo->marker->saw_SOF)
  170857. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  170858. } else {
  170859. /* Prevent infinite loop in coef ctlr's decompress_data routine
  170860. * if user set output_scan_number larger than number of scans.
  170861. */
  170862. if (cinfo->output_scan_number > cinfo->input_scan_number)
  170863. cinfo->output_scan_number = cinfo->input_scan_number;
  170864. }
  170865. break;
  170866. case JPEG_SUSPENDED:
  170867. break;
  170868. }
  170869. return val;
  170870. }
  170871. /*
  170872. * Reset state to begin a fresh datastream.
  170873. */
  170874. METHODDEF(void)
  170875. reset_input_controller (j_decompress_ptr cinfo)
  170876. {
  170877. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  170878. inputctl->pub.consume_input = consume_markers;
  170879. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170880. inputctl->pub.eoi_reached = FALSE;
  170881. inputctl->inheaders = TRUE;
  170882. /* Reset other modules */
  170883. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  170884. (*cinfo->marker->reset_marker_reader) (cinfo);
  170885. /* Reset progression state -- would be cleaner if entropy decoder did this */
  170886. cinfo->coef_bits = NULL;
  170887. }
  170888. /*
  170889. * Initialize the input controller module.
  170890. * This is called only once, when the decompression object is created.
  170891. */
  170892. GLOBAL(void)
  170893. jinit_input_controller (j_decompress_ptr cinfo)
  170894. {
  170895. my_inputctl_ptr inputctl;
  170896. /* Create subobject in permanent pool */
  170897. inputctl = (my_inputctl_ptr)
  170898. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  170899. SIZEOF(my_input_controller));
  170900. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  170901. /* Initialize method pointers */
  170902. inputctl->pub.consume_input = consume_markers;
  170903. inputctl->pub.reset_input_controller = reset_input_controller;
  170904. inputctl->pub.start_input_pass = start_input_pass2;
  170905. inputctl->pub.finish_input_pass = finish_input_pass;
  170906. /* Initialize state: can't use reset_input_controller since we don't
  170907. * want to try to reset other modules yet.
  170908. */
  170909. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  170910. inputctl->pub.eoi_reached = FALSE;
  170911. inputctl->inheaders = TRUE;
  170912. }
  170913. /*** End of inlined file: jdinput.c ***/
  170914. /*** Start of inlined file: jdmainct.c ***/
  170915. #define JPEG_INTERNALS
  170916. /*
  170917. * In the current system design, the main buffer need never be a full-image
  170918. * buffer; any full-height buffers will be found inside the coefficient or
  170919. * postprocessing controllers. Nonetheless, the main controller is not
  170920. * trivial. Its responsibility is to provide context rows for upsampling/
  170921. * rescaling, and doing this in an efficient fashion is a bit tricky.
  170922. *
  170923. * Postprocessor input data is counted in "row groups". A row group
  170924. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  170925. * sample rows of each component. (We require DCT_scaled_size values to be
  170926. * chosen such that these numbers are integers. In practice DCT_scaled_size
  170927. * values will likely be powers of two, so we actually have the stronger
  170928. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  170929. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  170930. * row group (times any additional scale factor that the upsampler is
  170931. * applying).
  170932. *
  170933. * The coefficient controller will deliver data to us one iMCU row at a time;
  170934. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  170935. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  170936. * to one row of MCUs when the image is fully interleaved.) Note that the
  170937. * number of sample rows varies across components, but the number of row
  170938. * groups does not. Some garbage sample rows may be included in the last iMCU
  170939. * row at the bottom of the image.
  170940. *
  170941. * Depending on the vertical scaling algorithm used, the upsampler may need
  170942. * access to the sample row(s) above and below its current input row group.
  170943. * The upsampler is required to set need_context_rows TRUE at global selection
  170944. * time if so. When need_context_rows is FALSE, this controller can simply
  170945. * obtain one iMCU row at a time from the coefficient controller and dole it
  170946. * out as row groups to the postprocessor.
  170947. *
  170948. * When need_context_rows is TRUE, this controller guarantees that the buffer
  170949. * passed to postprocessing contains at least one row group's worth of samples
  170950. * above and below the row group(s) being processed. Note that the context
  170951. * rows "above" the first passed row group appear at negative row offsets in
  170952. * the passed buffer. At the top and bottom of the image, the required
  170953. * context rows are manufactured by duplicating the first or last real sample
  170954. * row; this avoids having special cases in the upsampling inner loops.
  170955. *
  170956. * The amount of context is fixed at one row group just because that's a
  170957. * convenient number for this controller to work with. The existing
  170958. * upsamplers really only need one sample row of context. An upsampler
  170959. * supporting arbitrary output rescaling might wish for more than one row
  170960. * group of context when shrinking the image; tough, we don't handle that.
  170961. * (This is justified by the assumption that downsizing will be handled mostly
  170962. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  170963. * the upsample step needn't be much less than one.)
  170964. *
  170965. * To provide the desired context, we have to retain the last two row groups
  170966. * of one iMCU row while reading in the next iMCU row. (The last row group
  170967. * can't be processed until we have another row group for its below-context,
  170968. * and so we have to save the next-to-last group too for its above-context.)
  170969. * We could do this most simply by copying data around in our buffer, but
  170970. * that'd be very slow. We can avoid copying any data by creating a rather
  170971. * strange pointer structure. Here's how it works. We allocate a workspace
  170972. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  170973. * of row groups per iMCU row). We create two sets of redundant pointers to
  170974. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  170975. * pointer lists look like this:
  170976. * M+1 M-1
  170977. * master pointer --> 0 master pointer --> 0
  170978. * 1 1
  170979. * ... ...
  170980. * M-3 M-3
  170981. * M-2 M
  170982. * M-1 M+1
  170983. * M M-2
  170984. * M+1 M-1
  170985. * 0 0
  170986. * We read alternate iMCU rows using each master pointer; thus the last two
  170987. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  170988. * The pointer lists are set up so that the required context rows appear to
  170989. * be adjacent to the proper places when we pass the pointer lists to the
  170990. * upsampler.
  170991. *
  170992. * The above pictures describe the normal state of the pointer lists.
  170993. * At top and bottom of the image, we diddle the pointer lists to duplicate
  170994. * the first or last sample row as necessary (this is cheaper than copying
  170995. * sample rows around).
  170996. *
  170997. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  170998. * situation each iMCU row provides only one row group so the buffering logic
  170999. * must be different (eg, we must read two iMCU rows before we can emit the
  171000. * first row group). For now, we simply do not support providing context
  171001. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  171002. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  171003. * want it quick and dirty, so a context-free upsampler is sufficient.
  171004. */
  171005. /* Private buffer controller object */
  171006. typedef struct {
  171007. struct jpeg_d_main_controller pub; /* public fields */
  171008. /* Pointer to allocated workspace (M or M+2 row groups). */
  171009. JSAMPARRAY buffer[MAX_COMPONENTS];
  171010. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  171011. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  171012. /* Remaining fields are only used in the context case. */
  171013. /* These are the master pointers to the funny-order pointer lists. */
  171014. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  171015. int whichptr; /* indicates which pointer set is now in use */
  171016. int context_state; /* process_data state machine status */
  171017. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  171018. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  171019. } my_main_controller4;
  171020. typedef my_main_controller4 * my_main_ptr4;
  171021. /* context_state values: */
  171022. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  171023. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  171024. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  171025. /* Forward declarations */
  171026. METHODDEF(void) process_data_simple_main2
  171027. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171028. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171029. METHODDEF(void) process_data_context_main
  171030. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171031. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171032. #ifdef QUANT_2PASS_SUPPORTED
  171033. METHODDEF(void) process_data_crank_post
  171034. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171035. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171036. #endif
  171037. LOCAL(void)
  171038. alloc_funny_pointers (j_decompress_ptr cinfo)
  171039. /* Allocate space for the funny pointer lists.
  171040. * This is done only once, not once per pass.
  171041. */
  171042. {
  171043. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171044. int ci, rgroup;
  171045. int M = cinfo->min_DCT_scaled_size;
  171046. jpeg_component_info *compptr;
  171047. JSAMPARRAY xbuf;
  171048. /* Get top-level space for component array pointers.
  171049. * We alloc both arrays with one call to save a few cycles.
  171050. */
  171051. main_->xbuffer[0] = (JSAMPIMAGE)
  171052. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171053. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171054. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171055. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171056. ci++, compptr++) {
  171057. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171058. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171059. /* Get space for pointer lists --- M+4 row groups in each list.
  171060. * We alloc both pointer lists with one call to save a few cycles.
  171061. */
  171062. xbuf = (JSAMPARRAY)
  171063. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171064. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171065. xbuf += rgroup; /* want one row group at negative offsets */
  171066. main_->xbuffer[0][ci] = xbuf;
  171067. xbuf += rgroup * (M + 4);
  171068. main_->xbuffer[1][ci] = xbuf;
  171069. }
  171070. }
  171071. LOCAL(void)
  171072. make_funny_pointers (j_decompress_ptr cinfo)
  171073. /* Create the funny pointer lists discussed in the comments above.
  171074. * The actual workspace is already allocated (in main->buffer),
  171075. * and the space for the pointer lists is allocated too.
  171076. * This routine just fills in the curiously ordered lists.
  171077. * This will be repeated at the beginning of each pass.
  171078. */
  171079. {
  171080. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171081. int ci, i, rgroup;
  171082. int M = cinfo->min_DCT_scaled_size;
  171083. jpeg_component_info *compptr;
  171084. JSAMPARRAY buf, xbuf0, xbuf1;
  171085. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171086. ci++, compptr++) {
  171087. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171088. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171089. xbuf0 = main_->xbuffer[0][ci];
  171090. xbuf1 = main_->xbuffer[1][ci];
  171091. /* First copy the workspace pointers as-is */
  171092. buf = main_->buffer[ci];
  171093. for (i = 0; i < rgroup * (M + 2); i++) {
  171094. xbuf0[i] = xbuf1[i] = buf[i];
  171095. }
  171096. /* In the second list, put the last four row groups in swapped order */
  171097. for (i = 0; i < rgroup * 2; i++) {
  171098. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171099. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171100. }
  171101. /* The wraparound pointers at top and bottom will be filled later
  171102. * (see set_wraparound_pointers, below). Initially we want the "above"
  171103. * pointers to duplicate the first actual data line. This only needs
  171104. * to happen in xbuffer[0].
  171105. */
  171106. for (i = 0; i < rgroup; i++) {
  171107. xbuf0[i - rgroup] = xbuf0[0];
  171108. }
  171109. }
  171110. }
  171111. LOCAL(void)
  171112. set_wraparound_pointers (j_decompress_ptr cinfo)
  171113. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171114. * This changes the pointer list state from top-of-image to the normal state.
  171115. */
  171116. {
  171117. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171118. int ci, i, rgroup;
  171119. int M = cinfo->min_DCT_scaled_size;
  171120. jpeg_component_info *compptr;
  171121. JSAMPARRAY xbuf0, xbuf1;
  171122. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171123. ci++, compptr++) {
  171124. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171125. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171126. xbuf0 = main_->xbuffer[0][ci];
  171127. xbuf1 = main_->xbuffer[1][ci];
  171128. for (i = 0; i < rgroup; i++) {
  171129. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171130. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171131. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171132. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171133. }
  171134. }
  171135. }
  171136. LOCAL(void)
  171137. set_bottom_pointers (j_decompress_ptr cinfo)
  171138. /* Change the pointer lists to duplicate the last sample row at the bottom
  171139. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171140. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171141. */
  171142. {
  171143. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171144. int ci, i, rgroup, iMCUheight, rows_left;
  171145. jpeg_component_info *compptr;
  171146. JSAMPARRAY xbuf;
  171147. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171148. ci++, compptr++) {
  171149. /* Count sample rows in one iMCU row and in one row group */
  171150. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171151. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171152. /* Count nondummy sample rows remaining for this component */
  171153. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171154. if (rows_left == 0) rows_left = iMCUheight;
  171155. /* Count nondummy row groups. Should get same answer for each component,
  171156. * so we need only do it once.
  171157. */
  171158. if (ci == 0) {
  171159. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171160. }
  171161. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171162. * last partial rowgroup and ensures at least one full rowgroup of context.
  171163. */
  171164. xbuf = main_->xbuffer[main_->whichptr][ci];
  171165. for (i = 0; i < rgroup * 2; i++) {
  171166. xbuf[rows_left + i] = xbuf[rows_left-1];
  171167. }
  171168. }
  171169. }
  171170. /*
  171171. * Initialize for a processing pass.
  171172. */
  171173. METHODDEF(void)
  171174. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171175. {
  171176. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171177. switch (pass_mode) {
  171178. case JBUF_PASS_THRU:
  171179. if (cinfo->upsample->need_context_rows) {
  171180. main_->pub.process_data = process_data_context_main;
  171181. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171182. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171183. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171184. main_->iMCU_row_ctr = 0;
  171185. } else {
  171186. /* Simple case with no context needed */
  171187. main_->pub.process_data = process_data_simple_main2;
  171188. }
  171189. main_->buffer_full = FALSE; /* Mark buffer empty */
  171190. main_->rowgroup_ctr = 0;
  171191. break;
  171192. #ifdef QUANT_2PASS_SUPPORTED
  171193. case JBUF_CRANK_DEST:
  171194. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171195. main_->pub.process_data = process_data_crank_post;
  171196. break;
  171197. #endif
  171198. default:
  171199. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171200. break;
  171201. }
  171202. }
  171203. /*
  171204. * Process some data.
  171205. * This handles the simple case where no context is required.
  171206. */
  171207. METHODDEF(void)
  171208. process_data_simple_main2 (j_decompress_ptr cinfo,
  171209. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171210. JDIMENSION out_rows_avail)
  171211. {
  171212. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171213. JDIMENSION rowgroups_avail;
  171214. /* Read input data if we haven't filled the main buffer yet */
  171215. if (! main_->buffer_full) {
  171216. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171217. return; /* suspension forced, can do nothing more */
  171218. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171219. }
  171220. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171221. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171222. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171223. * to the postprocessor. The postprocessor has to check for bottom
  171224. * of image anyway (at row resolution), so no point in us doing it too.
  171225. */
  171226. /* Feed the postprocessor */
  171227. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  171228. &main_->rowgroup_ctr, rowgroups_avail,
  171229. output_buf, out_row_ctr, out_rows_avail);
  171230. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  171231. if (main_->rowgroup_ctr >= rowgroups_avail) {
  171232. main_->buffer_full = FALSE;
  171233. main_->rowgroup_ctr = 0;
  171234. }
  171235. }
  171236. /*
  171237. * Process some data.
  171238. * This handles the case where context rows must be provided.
  171239. */
  171240. METHODDEF(void)
  171241. process_data_context_main (j_decompress_ptr cinfo,
  171242. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171243. JDIMENSION out_rows_avail)
  171244. {
  171245. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171246. /* Read input data if we haven't filled the main buffer yet */
  171247. if (! main_->buffer_full) {
  171248. if (! (*cinfo->coef->decompress_data) (cinfo,
  171249. main_->xbuffer[main_->whichptr]))
  171250. return; /* suspension forced, can do nothing more */
  171251. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171252. main_->iMCU_row_ctr++; /* count rows received */
  171253. }
  171254. /* Postprocessor typically will not swallow all the input data it is handed
  171255. * in one call (due to filling the output buffer first). Must be prepared
  171256. * to exit and restart. This switch lets us keep track of how far we got.
  171257. * Note that each case falls through to the next on successful completion.
  171258. */
  171259. switch (main_->context_state) {
  171260. case CTX_POSTPONED_ROW:
  171261. /* Call postprocessor using previously set pointers for postponed row */
  171262. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171263. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171264. output_buf, out_row_ctr, out_rows_avail);
  171265. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171266. return; /* Need to suspend */
  171267. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171268. if (*out_row_ctr >= out_rows_avail)
  171269. return; /* Postprocessor exactly filled output buf */
  171270. /*FALLTHROUGH*/
  171271. case CTX_PREPARE_FOR_IMCU:
  171272. /* Prepare to process first M-1 row groups of this iMCU row */
  171273. main_->rowgroup_ctr = 0;
  171274. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  171275. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  171276. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  171277. */
  171278. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  171279. set_bottom_pointers(cinfo);
  171280. main_->context_state = CTX_PROCESS_IMCU;
  171281. /*FALLTHROUGH*/
  171282. case CTX_PROCESS_IMCU:
  171283. /* Call postprocessor using previously set pointers */
  171284. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  171285. &main_->rowgroup_ctr, main_->rowgroups_avail,
  171286. output_buf, out_row_ctr, out_rows_avail);
  171287. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  171288. return; /* Need to suspend */
  171289. /* After the first iMCU, change wraparound pointers to normal state */
  171290. if (main_->iMCU_row_ctr == 1)
  171291. set_wraparound_pointers(cinfo);
  171292. /* Prepare to load new iMCU row using other xbuffer list */
  171293. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  171294. main_->buffer_full = FALSE;
  171295. /* Still need to process last row group of this iMCU row, */
  171296. /* which is saved at index M+1 of the other xbuffer */
  171297. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  171298. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  171299. main_->context_state = CTX_POSTPONED_ROW;
  171300. }
  171301. }
  171302. /*
  171303. * Process some data.
  171304. * Final pass of two-pass quantization: just call the postprocessor.
  171305. * Source data will be the postprocessor controller's internal buffer.
  171306. */
  171307. #ifdef QUANT_2PASS_SUPPORTED
  171308. METHODDEF(void)
  171309. process_data_crank_post (j_decompress_ptr cinfo,
  171310. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171311. JDIMENSION out_rows_avail)
  171312. {
  171313. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  171314. (JDIMENSION *) NULL, (JDIMENSION) 0,
  171315. output_buf, out_row_ctr, out_rows_avail);
  171316. }
  171317. #endif /* QUANT_2PASS_SUPPORTED */
  171318. /*
  171319. * Initialize main buffer controller.
  171320. */
  171321. GLOBAL(void)
  171322. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  171323. {
  171324. my_main_ptr4 main_;
  171325. int ci, rgroup, ngroups;
  171326. jpeg_component_info *compptr;
  171327. main_ = (my_main_ptr4)
  171328. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171329. SIZEOF(my_main_controller4));
  171330. cinfo->main = (struct jpeg_d_main_controller *) main_;
  171331. main_->pub.start_pass = start_pass_main2;
  171332. if (need_full_buffer) /* shouldn't happen */
  171333. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171334. /* Allocate the workspace.
  171335. * ngroups is the number of row groups we need.
  171336. */
  171337. if (cinfo->upsample->need_context_rows) {
  171338. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  171339. ERREXIT(cinfo, JERR_NOTIMPL);
  171340. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  171341. ngroups = cinfo->min_DCT_scaled_size + 2;
  171342. } else {
  171343. ngroups = cinfo->min_DCT_scaled_size;
  171344. }
  171345. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171346. ci++, compptr++) {
  171347. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171348. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171349. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  171350. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171351. compptr->width_in_blocks * compptr->DCT_scaled_size,
  171352. (JDIMENSION) (rgroup * ngroups));
  171353. }
  171354. }
  171355. /*** End of inlined file: jdmainct.c ***/
  171356. /*** Start of inlined file: jdmarker.c ***/
  171357. #define JPEG_INTERNALS
  171358. /* Private state */
  171359. typedef struct {
  171360. struct jpeg_marker_reader pub; /* public fields */
  171361. /* Application-overridable marker processing methods */
  171362. jpeg_marker_parser_method process_COM;
  171363. jpeg_marker_parser_method process_APPn[16];
  171364. /* Limit on marker data length to save for each marker type */
  171365. unsigned int length_limit_COM;
  171366. unsigned int length_limit_APPn[16];
  171367. /* Status of COM/APPn marker saving */
  171368. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  171369. unsigned int bytes_read; /* data bytes read so far in marker */
  171370. /* Note: cur_marker is not linked into marker_list until it's all read. */
  171371. } my_marker_reader;
  171372. typedef my_marker_reader * my_marker_ptr2;
  171373. /*
  171374. * Macros for fetching data from the data source module.
  171375. *
  171376. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  171377. * the current restart point; we update them only when we have reached a
  171378. * suitable place to restart if a suspension occurs.
  171379. */
  171380. /* Declare and initialize local copies of input pointer/count */
  171381. #define INPUT_VARS(cinfo) \
  171382. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  171383. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  171384. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  171385. /* Unload the local copies --- do this only at a restart boundary */
  171386. #define INPUT_SYNC(cinfo) \
  171387. ( datasrc->next_input_byte = next_input_byte, \
  171388. datasrc->bytes_in_buffer = bytes_in_buffer )
  171389. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  171390. #define INPUT_RELOAD(cinfo) \
  171391. ( next_input_byte = datasrc->next_input_byte, \
  171392. bytes_in_buffer = datasrc->bytes_in_buffer )
  171393. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  171394. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  171395. * but we must reload the local copies after a successful fill.
  171396. */
  171397. #define MAKE_BYTE_AVAIL(cinfo,action) \
  171398. if (bytes_in_buffer == 0) { \
  171399. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  171400. { action; } \
  171401. INPUT_RELOAD(cinfo); \
  171402. }
  171403. /* Read a byte into variable V.
  171404. * If must suspend, take the specified action (typically "return FALSE").
  171405. */
  171406. #define INPUT_BYTE(cinfo,V,action) \
  171407. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171408. bytes_in_buffer--; \
  171409. V = GETJOCTET(*next_input_byte++); )
  171410. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  171411. * V should be declared unsigned int or perhaps INT32.
  171412. */
  171413. #define INPUT_2BYTES(cinfo,V,action) \
  171414. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  171415. bytes_in_buffer--; \
  171416. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  171417. MAKE_BYTE_AVAIL(cinfo,action); \
  171418. bytes_in_buffer--; \
  171419. V += GETJOCTET(*next_input_byte++); )
  171420. /*
  171421. * Routines to process JPEG markers.
  171422. *
  171423. * Entry condition: JPEG marker itself has been read and its code saved
  171424. * in cinfo->unread_marker; input restart point is just after the marker.
  171425. *
  171426. * Exit: if return TRUE, have read and processed any parameters, and have
  171427. * updated the restart point to point after the parameters.
  171428. * If return FALSE, was forced to suspend before reaching end of
  171429. * marker parameters; restart point has not been moved. Same routine
  171430. * will be called again after application supplies more input data.
  171431. *
  171432. * This approach to suspension assumes that all of a marker's parameters
  171433. * can fit into a single input bufferload. This should hold for "normal"
  171434. * markers. Some COM/APPn markers might have large parameter segments
  171435. * that might not fit. If we are simply dropping such a marker, we use
  171436. * skip_input_data to get past it, and thereby put the problem on the
  171437. * source manager's shoulders. If we are saving the marker's contents
  171438. * into memory, we use a slightly different convention: when forced to
  171439. * suspend, the marker processor updates the restart point to the end of
  171440. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  171441. * On resumption, cinfo->unread_marker still contains the marker code,
  171442. * but the data source will point to the next chunk of marker data.
  171443. * The marker processor must retain internal state to deal with this.
  171444. *
  171445. * Note that we don't bother to avoid duplicate trace messages if a
  171446. * suspension occurs within marker parameters. Other side effects
  171447. * require more care.
  171448. */
  171449. LOCAL(boolean)
  171450. get_soi (j_decompress_ptr cinfo)
  171451. /* Process an SOI marker */
  171452. {
  171453. int i;
  171454. TRACEMS(cinfo, 1, JTRC_SOI);
  171455. if (cinfo->marker->saw_SOI)
  171456. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  171457. /* Reset all parameters that are defined to be reset by SOI */
  171458. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  171459. cinfo->arith_dc_L[i] = 0;
  171460. cinfo->arith_dc_U[i] = 1;
  171461. cinfo->arith_ac_K[i] = 5;
  171462. }
  171463. cinfo->restart_interval = 0;
  171464. /* Set initial assumptions for colorspace etc */
  171465. cinfo->jpeg_color_space = JCS_UNKNOWN;
  171466. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  171467. cinfo->saw_JFIF_marker = FALSE;
  171468. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  171469. cinfo->JFIF_minor_version = 1;
  171470. cinfo->density_unit = 0;
  171471. cinfo->X_density = 1;
  171472. cinfo->Y_density = 1;
  171473. cinfo->saw_Adobe_marker = FALSE;
  171474. cinfo->Adobe_transform = 0;
  171475. cinfo->marker->saw_SOI = TRUE;
  171476. return TRUE;
  171477. }
  171478. LOCAL(boolean)
  171479. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  171480. /* Process a SOFn marker */
  171481. {
  171482. INT32 length;
  171483. int c, ci;
  171484. jpeg_component_info * compptr;
  171485. INPUT_VARS(cinfo);
  171486. cinfo->progressive_mode = is_prog;
  171487. cinfo->arith_code = is_arith;
  171488. INPUT_2BYTES(cinfo, length, return FALSE);
  171489. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  171490. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  171491. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  171492. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  171493. length -= 8;
  171494. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  171495. (int) cinfo->image_width, (int) cinfo->image_height,
  171496. cinfo->num_components);
  171497. if (cinfo->marker->saw_SOF)
  171498. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  171499. /* We don't support files in which the image height is initially specified */
  171500. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  171501. /* might as well have a general sanity check. */
  171502. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  171503. || cinfo->num_components <= 0)
  171504. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  171505. if (length != (cinfo->num_components * 3))
  171506. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171507. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  171508. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  171509. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171510. cinfo->num_components * SIZEOF(jpeg_component_info));
  171511. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171512. ci++, compptr++) {
  171513. compptr->component_index = ci;
  171514. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  171515. INPUT_BYTE(cinfo, c, return FALSE);
  171516. compptr->h_samp_factor = (c >> 4) & 15;
  171517. compptr->v_samp_factor = (c ) & 15;
  171518. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  171519. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  171520. compptr->component_id, compptr->h_samp_factor,
  171521. compptr->v_samp_factor, compptr->quant_tbl_no);
  171522. }
  171523. cinfo->marker->saw_SOF = TRUE;
  171524. INPUT_SYNC(cinfo);
  171525. return TRUE;
  171526. }
  171527. LOCAL(boolean)
  171528. get_sos (j_decompress_ptr cinfo)
  171529. /* Process a SOS marker */
  171530. {
  171531. INT32 length;
  171532. int i, ci, n, c, cc;
  171533. jpeg_component_info * compptr;
  171534. INPUT_VARS(cinfo);
  171535. if (! cinfo->marker->saw_SOF)
  171536. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  171537. INPUT_2BYTES(cinfo, length, return FALSE);
  171538. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  171539. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  171540. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  171541. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171542. cinfo->comps_in_scan = n;
  171543. /* Collect the component-spec parameters */
  171544. for (i = 0; i < n; i++) {
  171545. INPUT_BYTE(cinfo, cc, return FALSE);
  171546. INPUT_BYTE(cinfo, c, return FALSE);
  171547. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171548. ci++, compptr++) {
  171549. if (cc == compptr->component_id)
  171550. goto id_found;
  171551. }
  171552. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  171553. id_found:
  171554. cinfo->cur_comp_info[i] = compptr;
  171555. compptr->dc_tbl_no = (c >> 4) & 15;
  171556. compptr->ac_tbl_no = (c ) & 15;
  171557. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  171558. compptr->dc_tbl_no, compptr->ac_tbl_no);
  171559. }
  171560. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  171561. INPUT_BYTE(cinfo, c, return FALSE);
  171562. cinfo->Ss = c;
  171563. INPUT_BYTE(cinfo, c, return FALSE);
  171564. cinfo->Se = c;
  171565. INPUT_BYTE(cinfo, c, return FALSE);
  171566. cinfo->Ah = (c >> 4) & 15;
  171567. cinfo->Al = (c ) & 15;
  171568. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  171569. cinfo->Ah, cinfo->Al);
  171570. /* Prepare to scan data & restart markers */
  171571. cinfo->marker->next_restart_num = 0;
  171572. /* Count another SOS marker */
  171573. cinfo->input_scan_number++;
  171574. INPUT_SYNC(cinfo);
  171575. return TRUE;
  171576. }
  171577. #ifdef D_ARITH_CODING_SUPPORTED
  171578. LOCAL(boolean)
  171579. get_dac (j_decompress_ptr cinfo)
  171580. /* Process a DAC marker */
  171581. {
  171582. INT32 length;
  171583. int index, val;
  171584. INPUT_VARS(cinfo);
  171585. INPUT_2BYTES(cinfo, length, return FALSE);
  171586. length -= 2;
  171587. while (length > 0) {
  171588. INPUT_BYTE(cinfo, index, return FALSE);
  171589. INPUT_BYTE(cinfo, val, return FALSE);
  171590. length -= 2;
  171591. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  171592. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  171593. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  171594. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  171595. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  171596. } else { /* define DC table */
  171597. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  171598. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  171599. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  171600. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  171601. }
  171602. }
  171603. if (length != 0)
  171604. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171605. INPUT_SYNC(cinfo);
  171606. return TRUE;
  171607. }
  171608. #else /* ! D_ARITH_CODING_SUPPORTED */
  171609. #define get_dac(cinfo) skip_variable(cinfo)
  171610. #endif /* D_ARITH_CODING_SUPPORTED */
  171611. LOCAL(boolean)
  171612. get_dht (j_decompress_ptr cinfo)
  171613. /* Process a DHT marker */
  171614. {
  171615. INT32 length;
  171616. UINT8 bits[17];
  171617. UINT8 huffval[256];
  171618. int i, index, count;
  171619. JHUFF_TBL **htblptr;
  171620. INPUT_VARS(cinfo);
  171621. INPUT_2BYTES(cinfo, length, return FALSE);
  171622. length -= 2;
  171623. while (length > 16) {
  171624. INPUT_BYTE(cinfo, index, return FALSE);
  171625. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  171626. bits[0] = 0;
  171627. count = 0;
  171628. for (i = 1; i <= 16; i++) {
  171629. INPUT_BYTE(cinfo, bits[i], return FALSE);
  171630. count += bits[i];
  171631. }
  171632. length -= 1 + 16;
  171633. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171634. bits[1], bits[2], bits[3], bits[4],
  171635. bits[5], bits[6], bits[7], bits[8]);
  171636. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  171637. bits[9], bits[10], bits[11], bits[12],
  171638. bits[13], bits[14], bits[15], bits[16]);
  171639. /* Here we just do minimal validation of the counts to avoid walking
  171640. * off the end of our table space. jdhuff.c will check more carefully.
  171641. */
  171642. if (count > 256 || ((INT32) count) > length)
  171643. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171644. for (i = 0; i < count; i++)
  171645. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  171646. length -= count;
  171647. if (index & 0x10) { /* AC table definition */
  171648. index -= 0x10;
  171649. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  171650. } else { /* DC table definition */
  171651. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  171652. }
  171653. if (index < 0 || index >= NUM_HUFF_TBLS)
  171654. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  171655. if (*htblptr == NULL)
  171656. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  171657. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  171658. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  171659. }
  171660. if (length != 0)
  171661. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171662. INPUT_SYNC(cinfo);
  171663. return TRUE;
  171664. }
  171665. LOCAL(boolean)
  171666. get_dqt (j_decompress_ptr cinfo)
  171667. /* Process a DQT marker */
  171668. {
  171669. INT32 length;
  171670. int n, i, prec;
  171671. unsigned int tmp;
  171672. JQUANT_TBL *quant_ptr;
  171673. INPUT_VARS(cinfo);
  171674. INPUT_2BYTES(cinfo, length, return FALSE);
  171675. length -= 2;
  171676. while (length > 0) {
  171677. INPUT_BYTE(cinfo, n, return FALSE);
  171678. prec = n >> 4;
  171679. n &= 0x0F;
  171680. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  171681. if (n >= NUM_QUANT_TBLS)
  171682. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  171683. if (cinfo->quant_tbl_ptrs[n] == NULL)
  171684. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  171685. quant_ptr = cinfo->quant_tbl_ptrs[n];
  171686. for (i = 0; i < DCTSIZE2; i++) {
  171687. if (prec)
  171688. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171689. else
  171690. INPUT_BYTE(cinfo, tmp, return FALSE);
  171691. /* We convert the zigzag-order table to natural array order. */
  171692. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  171693. }
  171694. if (cinfo->err->trace_level >= 2) {
  171695. for (i = 0; i < DCTSIZE2; i += 8) {
  171696. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  171697. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  171698. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  171699. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  171700. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  171701. }
  171702. }
  171703. length -= DCTSIZE2+1;
  171704. if (prec) length -= DCTSIZE2;
  171705. }
  171706. if (length != 0)
  171707. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171708. INPUT_SYNC(cinfo);
  171709. return TRUE;
  171710. }
  171711. LOCAL(boolean)
  171712. get_dri (j_decompress_ptr cinfo)
  171713. /* Process a DRI marker */
  171714. {
  171715. INT32 length;
  171716. unsigned int tmp;
  171717. INPUT_VARS(cinfo);
  171718. INPUT_2BYTES(cinfo, length, return FALSE);
  171719. if (length != 4)
  171720. ERREXIT(cinfo, JERR_BAD_LENGTH);
  171721. INPUT_2BYTES(cinfo, tmp, return FALSE);
  171722. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  171723. cinfo->restart_interval = tmp;
  171724. INPUT_SYNC(cinfo);
  171725. return TRUE;
  171726. }
  171727. /*
  171728. * Routines for processing APPn and COM markers.
  171729. * These are either saved in memory or discarded, per application request.
  171730. * APP0 and APP14 are specially checked to see if they are
  171731. * JFIF and Adobe markers, respectively.
  171732. */
  171733. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  171734. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  171735. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  171736. LOCAL(void)
  171737. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171738. unsigned int datalen, INT32 remaining)
  171739. /* Examine first few bytes from an APP0.
  171740. * Take appropriate action if it is a JFIF marker.
  171741. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171742. */
  171743. {
  171744. INT32 totallen = (INT32) datalen + remaining;
  171745. if (datalen >= APP0_DATA_LEN &&
  171746. GETJOCTET(data[0]) == 0x4A &&
  171747. GETJOCTET(data[1]) == 0x46 &&
  171748. GETJOCTET(data[2]) == 0x49 &&
  171749. GETJOCTET(data[3]) == 0x46 &&
  171750. GETJOCTET(data[4]) == 0) {
  171751. /* Found JFIF APP0 marker: save info */
  171752. cinfo->saw_JFIF_marker = TRUE;
  171753. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  171754. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  171755. cinfo->density_unit = GETJOCTET(data[7]);
  171756. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  171757. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  171758. /* Check version.
  171759. * Major version must be 1, anything else signals an incompatible change.
  171760. * (We used to treat this as an error, but now it's a nonfatal warning,
  171761. * because some bozo at Hijaak couldn't read the spec.)
  171762. * Minor version should be 0..2, but process anyway if newer.
  171763. */
  171764. if (cinfo->JFIF_major_version != 1)
  171765. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  171766. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  171767. /* Generate trace messages */
  171768. TRACEMS5(cinfo, 1, JTRC_JFIF,
  171769. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  171770. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  171771. /* Validate thumbnail dimensions and issue appropriate messages */
  171772. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  171773. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  171774. GETJOCTET(data[12]), GETJOCTET(data[13]));
  171775. totallen -= APP0_DATA_LEN;
  171776. if (totallen !=
  171777. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  171778. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  171779. } else if (datalen >= 6 &&
  171780. GETJOCTET(data[0]) == 0x4A &&
  171781. GETJOCTET(data[1]) == 0x46 &&
  171782. GETJOCTET(data[2]) == 0x58 &&
  171783. GETJOCTET(data[3]) == 0x58 &&
  171784. GETJOCTET(data[4]) == 0) {
  171785. /* Found JFIF "JFXX" extension APP0 marker */
  171786. /* The library doesn't actually do anything with these,
  171787. * but we try to produce a helpful trace message.
  171788. */
  171789. switch (GETJOCTET(data[5])) {
  171790. case 0x10:
  171791. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  171792. break;
  171793. case 0x11:
  171794. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  171795. break;
  171796. case 0x13:
  171797. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  171798. break;
  171799. default:
  171800. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  171801. GETJOCTET(data[5]), (int) totallen);
  171802. break;
  171803. }
  171804. } else {
  171805. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  171806. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  171807. }
  171808. }
  171809. LOCAL(void)
  171810. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  171811. unsigned int datalen, INT32 remaining)
  171812. /* Examine first few bytes from an APP14.
  171813. * Take appropriate action if it is an Adobe marker.
  171814. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  171815. */
  171816. {
  171817. unsigned int version, flags0, flags1, transform;
  171818. if (datalen >= APP14_DATA_LEN &&
  171819. GETJOCTET(data[0]) == 0x41 &&
  171820. GETJOCTET(data[1]) == 0x64 &&
  171821. GETJOCTET(data[2]) == 0x6F &&
  171822. GETJOCTET(data[3]) == 0x62 &&
  171823. GETJOCTET(data[4]) == 0x65) {
  171824. /* Found Adobe APP14 marker */
  171825. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  171826. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  171827. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  171828. transform = GETJOCTET(data[11]);
  171829. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  171830. cinfo->saw_Adobe_marker = TRUE;
  171831. cinfo->Adobe_transform = (UINT8) transform;
  171832. } else {
  171833. /* Start of APP14 does not match "Adobe", or too short */
  171834. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  171835. }
  171836. }
  171837. METHODDEF(boolean)
  171838. get_interesting_appn (j_decompress_ptr cinfo)
  171839. /* Process an APP0 or APP14 marker without saving it */
  171840. {
  171841. INT32 length;
  171842. JOCTET b[APPN_DATA_LEN];
  171843. unsigned int i, numtoread;
  171844. INPUT_VARS(cinfo);
  171845. INPUT_2BYTES(cinfo, length, return FALSE);
  171846. length -= 2;
  171847. /* get the interesting part of the marker data */
  171848. if (length >= APPN_DATA_LEN)
  171849. numtoread = APPN_DATA_LEN;
  171850. else if (length > 0)
  171851. numtoread = (unsigned int) length;
  171852. else
  171853. numtoread = 0;
  171854. for (i = 0; i < numtoread; i++)
  171855. INPUT_BYTE(cinfo, b[i], return FALSE);
  171856. length -= numtoread;
  171857. /* process it */
  171858. switch (cinfo->unread_marker) {
  171859. case M_APP0:
  171860. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  171861. break;
  171862. case M_APP14:
  171863. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  171864. break;
  171865. default:
  171866. /* can't get here unless jpeg_save_markers chooses wrong processor */
  171867. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  171868. break;
  171869. }
  171870. /* skip any remaining data -- could be lots */
  171871. INPUT_SYNC(cinfo);
  171872. if (length > 0)
  171873. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171874. return TRUE;
  171875. }
  171876. #ifdef SAVE_MARKERS_SUPPORTED
  171877. METHODDEF(boolean)
  171878. save_marker (j_decompress_ptr cinfo)
  171879. /* Save an APPn or COM marker into the marker list */
  171880. {
  171881. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  171882. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  171883. unsigned int bytes_read, data_length;
  171884. JOCTET FAR * data;
  171885. INT32 length = 0;
  171886. INPUT_VARS(cinfo);
  171887. if (cur_marker == NULL) {
  171888. /* begin reading a marker */
  171889. INPUT_2BYTES(cinfo, length, return FALSE);
  171890. length -= 2;
  171891. if (length >= 0) { /* watch out for bogus length word */
  171892. /* figure out how much we want to save */
  171893. unsigned int limit;
  171894. if (cinfo->unread_marker == (int) M_COM)
  171895. limit = marker->length_limit_COM;
  171896. else
  171897. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  171898. if ((unsigned int) length < limit)
  171899. limit = (unsigned int) length;
  171900. /* allocate and initialize the marker item */
  171901. cur_marker = (jpeg_saved_marker_ptr)
  171902. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171903. SIZEOF(struct jpeg_marker_struct) + limit);
  171904. cur_marker->next = NULL;
  171905. cur_marker->marker = (UINT8) cinfo->unread_marker;
  171906. cur_marker->original_length = (unsigned int) length;
  171907. cur_marker->data_length = limit;
  171908. /* data area is just beyond the jpeg_marker_struct */
  171909. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  171910. marker->cur_marker = cur_marker;
  171911. marker->bytes_read = 0;
  171912. bytes_read = 0;
  171913. data_length = limit;
  171914. } else {
  171915. /* deal with bogus length word */
  171916. bytes_read = data_length = 0;
  171917. data = NULL;
  171918. }
  171919. } else {
  171920. /* resume reading a marker */
  171921. bytes_read = marker->bytes_read;
  171922. data_length = cur_marker->data_length;
  171923. data = cur_marker->data + bytes_read;
  171924. }
  171925. while (bytes_read < data_length) {
  171926. INPUT_SYNC(cinfo); /* move the restart point to here */
  171927. marker->bytes_read = bytes_read;
  171928. /* If there's not at least one byte in buffer, suspend */
  171929. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  171930. /* Copy bytes with reasonable rapidity */
  171931. while (bytes_read < data_length && bytes_in_buffer > 0) {
  171932. *data++ = *next_input_byte++;
  171933. bytes_in_buffer--;
  171934. bytes_read++;
  171935. }
  171936. }
  171937. /* Done reading what we want to read */
  171938. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  171939. /* Add new marker to end of list */
  171940. if (cinfo->marker_list == NULL) {
  171941. cinfo->marker_list = cur_marker;
  171942. } else {
  171943. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  171944. while (prev->next != NULL)
  171945. prev = prev->next;
  171946. prev->next = cur_marker;
  171947. }
  171948. /* Reset pointer & calc remaining data length */
  171949. data = cur_marker->data;
  171950. length = cur_marker->original_length - data_length;
  171951. }
  171952. /* Reset to initial state for next marker */
  171953. marker->cur_marker = NULL;
  171954. /* Process the marker if interesting; else just make a generic trace msg */
  171955. switch (cinfo->unread_marker) {
  171956. case M_APP0:
  171957. examine_app0(cinfo, data, data_length, length);
  171958. break;
  171959. case M_APP14:
  171960. examine_app14(cinfo, data, data_length, length);
  171961. break;
  171962. default:
  171963. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  171964. (int) (data_length + length));
  171965. break;
  171966. }
  171967. /* skip any remaining data -- could be lots */
  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. #endif /* SAVE_MARKERS_SUPPORTED */
  171974. METHODDEF(boolean)
  171975. skip_variable (j_decompress_ptr cinfo)
  171976. /* Skip over an unknown or uninteresting variable-length marker */
  171977. {
  171978. INT32 length;
  171979. INPUT_VARS(cinfo);
  171980. INPUT_2BYTES(cinfo, length, return FALSE);
  171981. length -= 2;
  171982. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  171983. INPUT_SYNC(cinfo); /* do before skip_input_data */
  171984. if (length > 0)
  171985. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  171986. return TRUE;
  171987. }
  171988. /*
  171989. * Find the next JPEG marker, save it in cinfo->unread_marker.
  171990. * Returns FALSE if had to suspend before reaching a marker;
  171991. * in that case cinfo->unread_marker is unchanged.
  171992. *
  171993. * Note that the result might not be a valid marker code,
  171994. * but it will never be 0 or FF.
  171995. */
  171996. LOCAL(boolean)
  171997. next_marker (j_decompress_ptr cinfo)
  171998. {
  171999. int c;
  172000. INPUT_VARS(cinfo);
  172001. for (;;) {
  172002. INPUT_BYTE(cinfo, c, return FALSE);
  172003. /* Skip any non-FF bytes.
  172004. * This may look a bit inefficient, but it will not occur in a valid file.
  172005. * We sync after each discarded byte so that a suspending data source
  172006. * can discard the byte from its buffer.
  172007. */
  172008. while (c != 0xFF) {
  172009. cinfo->marker->discarded_bytes++;
  172010. INPUT_SYNC(cinfo);
  172011. INPUT_BYTE(cinfo, c, return FALSE);
  172012. }
  172013. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  172014. * pad bytes, so don't count them in discarded_bytes. We assume there
  172015. * will not be so many consecutive FF bytes as to overflow a suspending
  172016. * data source's input buffer.
  172017. */
  172018. do {
  172019. INPUT_BYTE(cinfo, c, return FALSE);
  172020. } while (c == 0xFF);
  172021. if (c != 0)
  172022. break; /* found a valid marker, exit loop */
  172023. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  172024. * Discard it and loop back to try again.
  172025. */
  172026. cinfo->marker->discarded_bytes += 2;
  172027. INPUT_SYNC(cinfo);
  172028. }
  172029. if (cinfo->marker->discarded_bytes != 0) {
  172030. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  172031. cinfo->marker->discarded_bytes = 0;
  172032. }
  172033. cinfo->unread_marker = c;
  172034. INPUT_SYNC(cinfo);
  172035. return TRUE;
  172036. }
  172037. LOCAL(boolean)
  172038. first_marker (j_decompress_ptr cinfo)
  172039. /* Like next_marker, but used to obtain the initial SOI marker. */
  172040. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172041. * we might well scan an entire input file before realizing it ain't JPEG.
  172042. * If an application wants to process non-JFIF files, it must seek to the
  172043. * SOI before calling the JPEG library.
  172044. */
  172045. {
  172046. int c, c2;
  172047. INPUT_VARS(cinfo);
  172048. INPUT_BYTE(cinfo, c, return FALSE);
  172049. INPUT_BYTE(cinfo, c2, return FALSE);
  172050. if (c != 0xFF || c2 != (int) M_SOI)
  172051. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172052. cinfo->unread_marker = c2;
  172053. INPUT_SYNC(cinfo);
  172054. return TRUE;
  172055. }
  172056. /*
  172057. * Read markers until SOS or EOI.
  172058. *
  172059. * Returns same codes as are defined for jpeg_consume_input:
  172060. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172061. */
  172062. METHODDEF(int)
  172063. read_markers (j_decompress_ptr cinfo)
  172064. {
  172065. /* Outer loop repeats once for each marker. */
  172066. for (;;) {
  172067. /* Collect the marker proper, unless we already did. */
  172068. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172069. if (cinfo->unread_marker == 0) {
  172070. if (! cinfo->marker->saw_SOI) {
  172071. if (! first_marker(cinfo))
  172072. return JPEG_SUSPENDED;
  172073. } else {
  172074. if (! next_marker(cinfo))
  172075. return JPEG_SUSPENDED;
  172076. }
  172077. }
  172078. /* At this point cinfo->unread_marker contains the marker code and the
  172079. * input point is just past the marker proper, but before any parameters.
  172080. * A suspension will cause us to return with this state still true.
  172081. */
  172082. switch (cinfo->unread_marker) {
  172083. case M_SOI:
  172084. if (! get_soi(cinfo))
  172085. return JPEG_SUSPENDED;
  172086. break;
  172087. case M_SOF0: /* Baseline */
  172088. case M_SOF1: /* Extended sequential, Huffman */
  172089. if (! get_sof(cinfo, FALSE, FALSE))
  172090. return JPEG_SUSPENDED;
  172091. break;
  172092. case M_SOF2: /* Progressive, Huffman */
  172093. if (! get_sof(cinfo, TRUE, FALSE))
  172094. return JPEG_SUSPENDED;
  172095. break;
  172096. case M_SOF9: /* Extended sequential, arithmetic */
  172097. if (! get_sof(cinfo, FALSE, TRUE))
  172098. return JPEG_SUSPENDED;
  172099. break;
  172100. case M_SOF10: /* Progressive, arithmetic */
  172101. if (! get_sof(cinfo, TRUE, TRUE))
  172102. return JPEG_SUSPENDED;
  172103. break;
  172104. /* Currently unsupported SOFn types */
  172105. case M_SOF3: /* Lossless, Huffman */
  172106. case M_SOF5: /* Differential sequential, Huffman */
  172107. case M_SOF6: /* Differential progressive, Huffman */
  172108. case M_SOF7: /* Differential lossless, Huffman */
  172109. case M_JPG: /* Reserved for JPEG extensions */
  172110. case M_SOF11: /* Lossless, arithmetic */
  172111. case M_SOF13: /* Differential sequential, arithmetic */
  172112. case M_SOF14: /* Differential progressive, arithmetic */
  172113. case M_SOF15: /* Differential lossless, arithmetic */
  172114. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172115. break;
  172116. case M_SOS:
  172117. if (! get_sos(cinfo))
  172118. return JPEG_SUSPENDED;
  172119. cinfo->unread_marker = 0; /* processed the marker */
  172120. return JPEG_REACHED_SOS;
  172121. case M_EOI:
  172122. TRACEMS(cinfo, 1, JTRC_EOI);
  172123. cinfo->unread_marker = 0; /* processed the marker */
  172124. return JPEG_REACHED_EOI;
  172125. case M_DAC:
  172126. if (! get_dac(cinfo))
  172127. return JPEG_SUSPENDED;
  172128. break;
  172129. case M_DHT:
  172130. if (! get_dht(cinfo))
  172131. return JPEG_SUSPENDED;
  172132. break;
  172133. case M_DQT:
  172134. if (! get_dqt(cinfo))
  172135. return JPEG_SUSPENDED;
  172136. break;
  172137. case M_DRI:
  172138. if (! get_dri(cinfo))
  172139. return JPEG_SUSPENDED;
  172140. break;
  172141. case M_APP0:
  172142. case M_APP1:
  172143. case M_APP2:
  172144. case M_APP3:
  172145. case M_APP4:
  172146. case M_APP5:
  172147. case M_APP6:
  172148. case M_APP7:
  172149. case M_APP8:
  172150. case M_APP9:
  172151. case M_APP10:
  172152. case M_APP11:
  172153. case M_APP12:
  172154. case M_APP13:
  172155. case M_APP14:
  172156. case M_APP15:
  172157. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172158. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172159. return JPEG_SUSPENDED;
  172160. break;
  172161. case M_COM:
  172162. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172163. return JPEG_SUSPENDED;
  172164. break;
  172165. case M_RST0: /* these are all parameterless */
  172166. case M_RST1:
  172167. case M_RST2:
  172168. case M_RST3:
  172169. case M_RST4:
  172170. case M_RST5:
  172171. case M_RST6:
  172172. case M_RST7:
  172173. case M_TEM:
  172174. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172175. break;
  172176. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172177. if (! skip_variable(cinfo))
  172178. return JPEG_SUSPENDED;
  172179. break;
  172180. default: /* must be DHP, EXP, JPGn, or RESn */
  172181. /* For now, we treat the reserved markers as fatal errors since they are
  172182. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172183. * Once the JPEG 3 version-number marker is well defined, this code
  172184. * ought to change!
  172185. */
  172186. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172187. break;
  172188. }
  172189. /* Successfully processed marker, so reset state variable */
  172190. cinfo->unread_marker = 0;
  172191. } /* end loop */
  172192. }
  172193. /*
  172194. * Read a restart marker, which is expected to appear next in the datastream;
  172195. * if the marker is not there, take appropriate recovery action.
  172196. * Returns FALSE if suspension is required.
  172197. *
  172198. * This is called by the entropy decoder after it has read an appropriate
  172199. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172200. * has already read a marker from the data source. Under normal conditions
  172201. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172202. * it holds a marker which the decoder will be unable to read past.
  172203. */
  172204. METHODDEF(boolean)
  172205. read_restart_marker (j_decompress_ptr cinfo)
  172206. {
  172207. /* Obtain a marker unless we already did. */
  172208. /* Note that next_marker will complain if it skips any data. */
  172209. if (cinfo->unread_marker == 0) {
  172210. if (! next_marker(cinfo))
  172211. return FALSE;
  172212. }
  172213. if (cinfo->unread_marker ==
  172214. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172215. /* Normal case --- swallow the marker and let entropy decoder continue */
  172216. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172217. cinfo->unread_marker = 0;
  172218. } else {
  172219. /* Uh-oh, the restart markers have been messed up. */
  172220. /* Let the data source manager determine how to resync. */
  172221. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172222. cinfo->marker->next_restart_num))
  172223. return FALSE;
  172224. }
  172225. /* Update next-restart state */
  172226. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172227. return TRUE;
  172228. }
  172229. /*
  172230. * This is the default resync_to_restart method for data source managers
  172231. * to use if they don't have any better approach. Some data source managers
  172232. * may be able to back up, or may have additional knowledge about the data
  172233. * which permits a more intelligent recovery strategy; such managers would
  172234. * presumably supply their own resync method.
  172235. *
  172236. * read_restart_marker calls resync_to_restart if it finds a marker other than
  172237. * the restart marker it was expecting. (This code is *not* used unless
  172238. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  172239. * the marker code actually found (might be anything, except 0 or FF).
  172240. * The desired restart marker number (0..7) is passed as a parameter.
  172241. * This routine is supposed to apply whatever error recovery strategy seems
  172242. * appropriate in order to position the input stream to the next data segment.
  172243. * Note that cinfo->unread_marker is treated as a marker appearing before
  172244. * the current data-source input point; usually it should be reset to zero
  172245. * before returning.
  172246. * Returns FALSE if suspension is required.
  172247. *
  172248. * This implementation is substantially constrained by wanting to treat the
  172249. * input as a data stream; this means we can't back up. Therefore, we have
  172250. * only the following actions to work with:
  172251. * 1. Simply discard the marker and let the entropy decoder resume at next
  172252. * byte of file.
  172253. * 2. Read forward until we find another marker, discarding intervening
  172254. * data. (In theory we could look ahead within the current bufferload,
  172255. * without having to discard data if we don't find the desired marker.
  172256. * This idea is not implemented here, in part because it makes behavior
  172257. * dependent on buffer size and chance buffer-boundary positions.)
  172258. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  172259. * This will cause the entropy decoder to process an empty data segment,
  172260. * inserting dummy zeroes, and then we will reprocess the marker.
  172261. *
  172262. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  172263. * appropriate if the found marker is a future restart marker (indicating
  172264. * that we have missed the desired restart marker, probably because it got
  172265. * corrupted).
  172266. * We apply #2 or #3 if the found marker is a restart marker no more than
  172267. * two counts behind or ahead of the expected one. We also apply #2 if the
  172268. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  172269. * If the found marker is a restart marker more than 2 counts away, we do #1
  172270. * (too much risk that the marker is erroneous; with luck we will be able to
  172271. * resync at some future point).
  172272. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  172273. * overrunning the end of a scan. An implementation limited to single-scan
  172274. * files might find it better to apply #2 for markers other than EOI, since
  172275. * any other marker would have to be bogus data in that case.
  172276. */
  172277. GLOBAL(boolean)
  172278. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  172279. {
  172280. int marker = cinfo->unread_marker;
  172281. int action = 1;
  172282. /* Always put up a warning. */
  172283. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  172284. /* Outer loop handles repeated decision after scanning forward. */
  172285. for (;;) {
  172286. if (marker < (int) M_SOF0)
  172287. action = 2; /* invalid marker */
  172288. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  172289. action = 3; /* valid non-restart marker */
  172290. else {
  172291. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  172292. marker == ((int) M_RST0 + ((desired+2) & 7)))
  172293. action = 3; /* one of the next two expected restarts */
  172294. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  172295. marker == ((int) M_RST0 + ((desired-2) & 7)))
  172296. action = 2; /* a prior restart, so advance */
  172297. else
  172298. action = 1; /* desired restart or too far away */
  172299. }
  172300. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  172301. switch (action) {
  172302. case 1:
  172303. /* Discard marker and let entropy decoder resume processing. */
  172304. cinfo->unread_marker = 0;
  172305. return TRUE;
  172306. case 2:
  172307. /* Scan to the next marker, and repeat the decision loop. */
  172308. if (! next_marker(cinfo))
  172309. return FALSE;
  172310. marker = cinfo->unread_marker;
  172311. break;
  172312. case 3:
  172313. /* Return without advancing past this marker. */
  172314. /* Entropy decoder will be forced to process an empty segment. */
  172315. return TRUE;
  172316. }
  172317. } /* end loop */
  172318. }
  172319. /*
  172320. * Reset marker processing state to begin a fresh datastream.
  172321. */
  172322. METHODDEF(void)
  172323. reset_marker_reader (j_decompress_ptr cinfo)
  172324. {
  172325. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172326. cinfo->comp_info = NULL; /* until allocated by get_sof */
  172327. cinfo->input_scan_number = 0; /* no SOS seen yet */
  172328. cinfo->unread_marker = 0; /* no pending marker */
  172329. marker->pub.saw_SOI = FALSE; /* set internal state too */
  172330. marker->pub.saw_SOF = FALSE;
  172331. marker->pub.discarded_bytes = 0;
  172332. marker->cur_marker = NULL;
  172333. }
  172334. /*
  172335. * Initialize the marker reader module.
  172336. * This is called only once, when the decompression object is created.
  172337. */
  172338. GLOBAL(void)
  172339. jinit_marker_reader (j_decompress_ptr cinfo)
  172340. {
  172341. my_marker_ptr2 marker;
  172342. int i;
  172343. /* Create subobject in permanent pool */
  172344. marker = (my_marker_ptr2)
  172345. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  172346. SIZEOF(my_marker_reader));
  172347. cinfo->marker = (struct jpeg_marker_reader *) marker;
  172348. /* Initialize public method pointers */
  172349. marker->pub.reset_marker_reader = reset_marker_reader;
  172350. marker->pub.read_markers = read_markers;
  172351. marker->pub.read_restart_marker = read_restart_marker;
  172352. /* Initialize COM/APPn processing.
  172353. * By default, we examine and then discard APP0 and APP14,
  172354. * but simply discard COM and all other APPn.
  172355. */
  172356. marker->process_COM = skip_variable;
  172357. marker->length_limit_COM = 0;
  172358. for (i = 0; i < 16; i++) {
  172359. marker->process_APPn[i] = skip_variable;
  172360. marker->length_limit_APPn[i] = 0;
  172361. }
  172362. marker->process_APPn[0] = get_interesting_appn;
  172363. marker->process_APPn[14] = get_interesting_appn;
  172364. /* Reset marker processing state */
  172365. reset_marker_reader(cinfo);
  172366. }
  172367. /*
  172368. * Control saving of COM and APPn markers into marker_list.
  172369. */
  172370. #ifdef SAVE_MARKERS_SUPPORTED
  172371. GLOBAL(void)
  172372. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  172373. unsigned int length_limit)
  172374. {
  172375. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172376. long maxlength;
  172377. jpeg_marker_parser_method processor;
  172378. /* Length limit mustn't be larger than what we can allocate
  172379. * (should only be a concern in a 16-bit environment).
  172380. */
  172381. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  172382. if (((long) length_limit) > maxlength)
  172383. length_limit = (unsigned int) maxlength;
  172384. /* Choose processor routine to use.
  172385. * APP0/APP14 have special requirements.
  172386. */
  172387. if (length_limit) {
  172388. processor = save_marker;
  172389. /* If saving APP0/APP14, save at least enough for our internal use. */
  172390. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  172391. length_limit = APP0_DATA_LEN;
  172392. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  172393. length_limit = APP14_DATA_LEN;
  172394. } else {
  172395. processor = skip_variable;
  172396. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  172397. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  172398. processor = get_interesting_appn;
  172399. }
  172400. if (marker_code == (int) M_COM) {
  172401. marker->process_COM = processor;
  172402. marker->length_limit_COM = length_limit;
  172403. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  172404. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  172405. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  172406. } else
  172407. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172408. }
  172409. #endif /* SAVE_MARKERS_SUPPORTED */
  172410. /*
  172411. * Install a special processing method for COM or APPn markers.
  172412. */
  172413. GLOBAL(void)
  172414. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  172415. jpeg_marker_parser_method routine)
  172416. {
  172417. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172418. if (marker_code == (int) M_COM)
  172419. marker->process_COM = routine;
  172420. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  172421. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  172422. else
  172423. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  172424. }
  172425. /*** End of inlined file: jdmarker.c ***/
  172426. /*** Start of inlined file: jdmaster.c ***/
  172427. #define JPEG_INTERNALS
  172428. /* Private state */
  172429. typedef struct {
  172430. struct jpeg_decomp_master pub; /* public fields */
  172431. int pass_number; /* # of passes completed */
  172432. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  172433. /* Saved references to initialized quantizer modules,
  172434. * in case we need to switch modes.
  172435. */
  172436. struct jpeg_color_quantizer * quantizer_1pass;
  172437. struct jpeg_color_quantizer * quantizer_2pass;
  172438. } my_decomp_master;
  172439. typedef my_decomp_master * my_master_ptr6;
  172440. /*
  172441. * Determine whether merged upsample/color conversion should be used.
  172442. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  172443. */
  172444. LOCAL(boolean)
  172445. use_merged_upsample (j_decompress_ptr cinfo)
  172446. {
  172447. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172448. /* Merging is the equivalent of plain box-filter upsampling */
  172449. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  172450. return FALSE;
  172451. /* jdmerge.c only supports YCC=>RGB color conversion */
  172452. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  172453. cinfo->out_color_space != JCS_RGB ||
  172454. cinfo->out_color_components != RGB_PIXELSIZE)
  172455. return FALSE;
  172456. /* and it only handles 2h1v or 2h2v sampling ratios */
  172457. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  172458. cinfo->comp_info[1].h_samp_factor != 1 ||
  172459. cinfo->comp_info[2].h_samp_factor != 1 ||
  172460. cinfo->comp_info[0].v_samp_factor > 2 ||
  172461. cinfo->comp_info[1].v_samp_factor != 1 ||
  172462. cinfo->comp_info[2].v_samp_factor != 1)
  172463. return FALSE;
  172464. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  172465. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172466. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  172467. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  172468. return FALSE;
  172469. /* ??? also need to test for upsample-time rescaling, when & if supported */
  172470. return TRUE; /* by golly, it'll work... */
  172471. #else
  172472. return FALSE;
  172473. #endif
  172474. }
  172475. /*
  172476. * Compute output image dimensions and related values.
  172477. * NOTE: this is exported for possible use by application.
  172478. * Hence it mustn't do anything that can't be done twice.
  172479. * Also note that it may be called before the master module is initialized!
  172480. */
  172481. GLOBAL(void)
  172482. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  172483. /* Do computations that are needed before master selection phase */
  172484. {
  172485. #ifdef IDCT_SCALING_SUPPORTED
  172486. int ci;
  172487. jpeg_component_info *compptr;
  172488. #endif
  172489. /* Prevent application from calling me at wrong times */
  172490. if (cinfo->global_state != DSTATE_READY)
  172491. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172492. #ifdef IDCT_SCALING_SUPPORTED
  172493. /* Compute actual output image dimensions and DCT scaling choices. */
  172494. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  172495. /* Provide 1/8 scaling */
  172496. cinfo->output_width = (JDIMENSION)
  172497. jdiv_round_up((long) cinfo->image_width, 8L);
  172498. cinfo->output_height = (JDIMENSION)
  172499. jdiv_round_up((long) cinfo->image_height, 8L);
  172500. cinfo->min_DCT_scaled_size = 1;
  172501. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  172502. /* Provide 1/4 scaling */
  172503. cinfo->output_width = (JDIMENSION)
  172504. jdiv_round_up((long) cinfo->image_width, 4L);
  172505. cinfo->output_height = (JDIMENSION)
  172506. jdiv_round_up((long) cinfo->image_height, 4L);
  172507. cinfo->min_DCT_scaled_size = 2;
  172508. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  172509. /* Provide 1/2 scaling */
  172510. cinfo->output_width = (JDIMENSION)
  172511. jdiv_round_up((long) cinfo->image_width, 2L);
  172512. cinfo->output_height = (JDIMENSION)
  172513. jdiv_round_up((long) cinfo->image_height, 2L);
  172514. cinfo->min_DCT_scaled_size = 4;
  172515. } else {
  172516. /* Provide 1/1 scaling */
  172517. cinfo->output_width = cinfo->image_width;
  172518. cinfo->output_height = cinfo->image_height;
  172519. cinfo->min_DCT_scaled_size = DCTSIZE;
  172520. }
  172521. /* In selecting the actual DCT scaling for each component, we try to
  172522. * scale up the chroma components via IDCT scaling rather than upsampling.
  172523. * This saves time if the upsampler gets to use 1:1 scaling.
  172524. * Note this code assumes that the supported DCT scalings are powers of 2.
  172525. */
  172526. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172527. ci++, compptr++) {
  172528. int ssize = cinfo->min_DCT_scaled_size;
  172529. while (ssize < DCTSIZE &&
  172530. (compptr->h_samp_factor * ssize * 2 <=
  172531. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  172532. (compptr->v_samp_factor * ssize * 2 <=
  172533. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  172534. ssize = ssize * 2;
  172535. }
  172536. compptr->DCT_scaled_size = ssize;
  172537. }
  172538. /* Recompute downsampled dimensions of components;
  172539. * application needs to know these if using raw downsampled data.
  172540. */
  172541. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172542. ci++, compptr++) {
  172543. /* Size in samples, after IDCT scaling */
  172544. compptr->downsampled_width = (JDIMENSION)
  172545. jdiv_round_up((long) cinfo->image_width *
  172546. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  172547. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  172548. compptr->downsampled_height = (JDIMENSION)
  172549. jdiv_round_up((long) cinfo->image_height *
  172550. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  172551. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  172552. }
  172553. #else /* !IDCT_SCALING_SUPPORTED */
  172554. /* Hardwire it to "no scaling" */
  172555. cinfo->output_width = cinfo->image_width;
  172556. cinfo->output_height = cinfo->image_height;
  172557. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  172558. * and has computed unscaled downsampled_width and downsampled_height.
  172559. */
  172560. #endif /* IDCT_SCALING_SUPPORTED */
  172561. /* Report number of components in selected colorspace. */
  172562. /* Probably this should be in the color conversion module... */
  172563. switch (cinfo->out_color_space) {
  172564. case JCS_GRAYSCALE:
  172565. cinfo->out_color_components = 1;
  172566. break;
  172567. case JCS_RGB:
  172568. #if RGB_PIXELSIZE != 3
  172569. cinfo->out_color_components = RGB_PIXELSIZE;
  172570. break;
  172571. #endif /* else share code with YCbCr */
  172572. case JCS_YCbCr:
  172573. cinfo->out_color_components = 3;
  172574. break;
  172575. case JCS_CMYK:
  172576. case JCS_YCCK:
  172577. cinfo->out_color_components = 4;
  172578. break;
  172579. default: /* else must be same colorspace as in file */
  172580. cinfo->out_color_components = cinfo->num_components;
  172581. break;
  172582. }
  172583. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  172584. cinfo->out_color_components);
  172585. /* See if upsampler will want to emit more than one row at a time */
  172586. if (use_merged_upsample(cinfo))
  172587. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  172588. else
  172589. cinfo->rec_outbuf_height = 1;
  172590. }
  172591. /*
  172592. * Several decompression processes need to range-limit values to the range
  172593. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  172594. * due to noise introduced by quantization, roundoff error, etc. These
  172595. * processes are inner loops and need to be as fast as possible. On most
  172596. * machines, particularly CPUs with pipelines or instruction prefetch,
  172597. * a (subscript-check-less) C table lookup
  172598. * x = sample_range_limit[x];
  172599. * is faster than explicit tests
  172600. * if (x < 0) x = 0;
  172601. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  172602. * These processes all use a common table prepared by the routine below.
  172603. *
  172604. * For most steps we can mathematically guarantee that the initial value
  172605. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  172606. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  172607. * limiting step (just after the IDCT), a wildly out-of-range value is
  172608. * possible if the input data is corrupt. To avoid any chance of indexing
  172609. * off the end of memory and getting a bad-pointer trap, we perform the
  172610. * post-IDCT limiting thus:
  172611. * x = range_limit[x & MASK];
  172612. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  172613. * samples. Under normal circumstances this is more than enough range and
  172614. * a correct output will be generated; with bogus input data the mask will
  172615. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  172616. * For the post-IDCT step, we want to convert the data from signed to unsigned
  172617. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  172618. * So the post-IDCT limiting table ends up looking like this:
  172619. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  172620. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172621. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  172622. * 0,1,...,CENTERJSAMPLE-1
  172623. * Negative inputs select values from the upper half of the table after
  172624. * masking.
  172625. *
  172626. * We can save some space by overlapping the start of the post-IDCT table
  172627. * with the simpler range limiting table. The post-IDCT table begins at
  172628. * sample_range_limit + CENTERJSAMPLE.
  172629. *
  172630. * Note that the table is allocated in near data space on PCs; it's small
  172631. * enough and used often enough to justify this.
  172632. */
  172633. LOCAL(void)
  172634. prepare_range_limit_table (j_decompress_ptr cinfo)
  172635. /* Allocate and fill in the sample_range_limit table */
  172636. {
  172637. JSAMPLE * table;
  172638. int i;
  172639. table = (JSAMPLE *)
  172640. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172641. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172642. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  172643. cinfo->sample_range_limit = table;
  172644. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  172645. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  172646. /* Main part of "simple" table: limit[x] = x */
  172647. for (i = 0; i <= MAXJSAMPLE; i++)
  172648. table[i] = (JSAMPLE) i;
  172649. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  172650. /* End of simple table, rest of first half of post-IDCT table */
  172651. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  172652. table[i] = MAXJSAMPLE;
  172653. /* Second half of post-IDCT table */
  172654. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  172655. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  172656. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  172657. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  172658. }
  172659. /*
  172660. * Master selection of decompression modules.
  172661. * This is done once at jpeg_start_decompress time. We determine
  172662. * which modules will be used and give them appropriate initialization calls.
  172663. * We also initialize the decompressor input side to begin consuming data.
  172664. *
  172665. * Since jpeg_read_header has finished, we know what is in the SOF
  172666. * and (first) SOS markers. We also have all the application parameter
  172667. * settings.
  172668. */
  172669. LOCAL(void)
  172670. master_selection (j_decompress_ptr cinfo)
  172671. {
  172672. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172673. boolean use_c_buffer;
  172674. long samplesperrow;
  172675. JDIMENSION jd_samplesperrow;
  172676. /* Initialize dimensions and other stuff */
  172677. jpeg_calc_output_dimensions(cinfo);
  172678. prepare_range_limit_table(cinfo);
  172679. /* Width of an output scanline must be representable as JDIMENSION. */
  172680. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  172681. jd_samplesperrow = (JDIMENSION) samplesperrow;
  172682. if ((long) jd_samplesperrow != samplesperrow)
  172683. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  172684. /* Initialize my private state */
  172685. master->pass_number = 0;
  172686. master->using_merged_upsample = use_merged_upsample(cinfo);
  172687. /* Color quantizer selection */
  172688. master->quantizer_1pass = NULL;
  172689. master->quantizer_2pass = NULL;
  172690. /* No mode changes if not using buffered-image mode. */
  172691. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  172692. cinfo->enable_1pass_quant = FALSE;
  172693. cinfo->enable_external_quant = FALSE;
  172694. cinfo->enable_2pass_quant = FALSE;
  172695. }
  172696. if (cinfo->quantize_colors) {
  172697. if (cinfo->raw_data_out)
  172698. ERREXIT(cinfo, JERR_NOTIMPL);
  172699. /* 2-pass quantizer only works in 3-component color space. */
  172700. if (cinfo->out_color_components != 3) {
  172701. cinfo->enable_1pass_quant = TRUE;
  172702. cinfo->enable_external_quant = FALSE;
  172703. cinfo->enable_2pass_quant = FALSE;
  172704. cinfo->colormap = NULL;
  172705. } else if (cinfo->colormap != NULL) {
  172706. cinfo->enable_external_quant = TRUE;
  172707. } else if (cinfo->two_pass_quantize) {
  172708. cinfo->enable_2pass_quant = TRUE;
  172709. } else {
  172710. cinfo->enable_1pass_quant = TRUE;
  172711. }
  172712. if (cinfo->enable_1pass_quant) {
  172713. #ifdef QUANT_1PASS_SUPPORTED
  172714. jinit_1pass_quantizer(cinfo);
  172715. master->quantizer_1pass = cinfo->cquantize;
  172716. #else
  172717. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172718. #endif
  172719. }
  172720. /* We use the 2-pass code to map to external colormaps. */
  172721. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  172722. #ifdef QUANT_2PASS_SUPPORTED
  172723. jinit_2pass_quantizer(cinfo);
  172724. master->quantizer_2pass = cinfo->cquantize;
  172725. #else
  172726. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172727. #endif
  172728. }
  172729. /* If both quantizers are initialized, the 2-pass one is left active;
  172730. * this is necessary for starting with quantization to an external map.
  172731. */
  172732. }
  172733. /* Post-processing: in particular, color conversion first */
  172734. if (! cinfo->raw_data_out) {
  172735. if (master->using_merged_upsample) {
  172736. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172737. jinit_merged_upsampler(cinfo); /* does color conversion too */
  172738. #else
  172739. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172740. #endif
  172741. } else {
  172742. jinit_color_deconverter(cinfo);
  172743. jinit_upsampler(cinfo);
  172744. }
  172745. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  172746. }
  172747. /* Inverse DCT */
  172748. jinit_inverse_dct(cinfo);
  172749. /* Entropy decoding: either Huffman or arithmetic coding. */
  172750. if (cinfo->arith_code) {
  172751. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  172752. } else {
  172753. if (cinfo->progressive_mode) {
  172754. #ifdef D_PROGRESSIVE_SUPPORTED
  172755. jinit_phuff_decoder(cinfo);
  172756. #else
  172757. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172758. #endif
  172759. } else
  172760. jinit_huff_decoder(cinfo);
  172761. }
  172762. /* Initialize principal buffer controllers. */
  172763. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  172764. jinit_d_coef_controller(cinfo, use_c_buffer);
  172765. if (! cinfo->raw_data_out)
  172766. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  172767. /* We can now tell the memory manager to allocate virtual arrays. */
  172768. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  172769. /* Initialize input side of decompressor to consume first scan. */
  172770. (*cinfo->inputctl->start_input_pass) (cinfo);
  172771. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172772. /* If jpeg_start_decompress will read the whole file, initialize
  172773. * progress monitoring appropriately. The input step is counted
  172774. * as one pass.
  172775. */
  172776. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  172777. cinfo->inputctl->has_multiple_scans) {
  172778. int nscans;
  172779. /* Estimate number of scans to set pass_limit. */
  172780. if (cinfo->progressive_mode) {
  172781. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  172782. nscans = 2 + 3 * cinfo->num_components;
  172783. } else {
  172784. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  172785. nscans = cinfo->num_components;
  172786. }
  172787. cinfo->progress->pass_counter = 0L;
  172788. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  172789. cinfo->progress->completed_passes = 0;
  172790. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  172791. /* Count the input pass as done */
  172792. master->pass_number++;
  172793. }
  172794. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172795. }
  172796. /*
  172797. * Per-pass setup.
  172798. * This is called at the beginning of each output pass. We determine which
  172799. * modules will be active during this pass and give them appropriate
  172800. * start_pass calls. We also set is_dummy_pass to indicate whether this
  172801. * is a "real" output pass or a dummy pass for color quantization.
  172802. * (In the latter case, jdapistd.c will crank the pass to completion.)
  172803. */
  172804. METHODDEF(void)
  172805. prepare_for_output_pass (j_decompress_ptr cinfo)
  172806. {
  172807. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172808. if (master->pub.is_dummy_pass) {
  172809. #ifdef QUANT_2PASS_SUPPORTED
  172810. /* Final pass of 2-pass quantization */
  172811. master->pub.is_dummy_pass = FALSE;
  172812. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  172813. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  172814. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  172815. #else
  172816. ERREXIT(cinfo, JERR_NOT_COMPILED);
  172817. #endif /* QUANT_2PASS_SUPPORTED */
  172818. } else {
  172819. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  172820. /* Select new quantization method */
  172821. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  172822. cinfo->cquantize = master->quantizer_2pass;
  172823. master->pub.is_dummy_pass = TRUE;
  172824. } else if (cinfo->enable_1pass_quant) {
  172825. cinfo->cquantize = master->quantizer_1pass;
  172826. } else {
  172827. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172828. }
  172829. }
  172830. (*cinfo->idct->start_pass) (cinfo);
  172831. (*cinfo->coef->start_output_pass) (cinfo);
  172832. if (! cinfo->raw_data_out) {
  172833. if (! master->using_merged_upsample)
  172834. (*cinfo->cconvert->start_pass) (cinfo);
  172835. (*cinfo->upsample->start_pass) (cinfo);
  172836. if (cinfo->quantize_colors)
  172837. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  172838. (*cinfo->post->start_pass) (cinfo,
  172839. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  172840. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  172841. }
  172842. }
  172843. /* Set up progress monitor's pass info if present */
  172844. if (cinfo->progress != NULL) {
  172845. cinfo->progress->completed_passes = master->pass_number;
  172846. cinfo->progress->total_passes = master->pass_number +
  172847. (master->pub.is_dummy_pass ? 2 : 1);
  172848. /* In buffered-image mode, we assume one more output pass if EOI not
  172849. * yet reached, but no more passes if EOI has been reached.
  172850. */
  172851. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  172852. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  172853. }
  172854. }
  172855. }
  172856. /*
  172857. * Finish up at end of an output pass.
  172858. */
  172859. METHODDEF(void)
  172860. finish_output_pass (j_decompress_ptr cinfo)
  172861. {
  172862. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172863. if (cinfo->quantize_colors)
  172864. (*cinfo->cquantize->finish_pass) (cinfo);
  172865. master->pass_number++;
  172866. }
  172867. #ifdef D_MULTISCAN_FILES_SUPPORTED
  172868. /*
  172869. * Switch to a new external colormap between output passes.
  172870. */
  172871. GLOBAL(void)
  172872. jpeg_new_colormap (j_decompress_ptr cinfo)
  172873. {
  172874. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  172875. /* Prevent application from calling me at wrong times */
  172876. if (cinfo->global_state != DSTATE_BUFIMAGE)
  172877. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  172878. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  172879. cinfo->colormap != NULL) {
  172880. /* Select 2-pass quantizer for external colormap use */
  172881. cinfo->cquantize = master->quantizer_2pass;
  172882. /* Notify quantizer of colormap change */
  172883. (*cinfo->cquantize->new_color_map) (cinfo);
  172884. master->pub.is_dummy_pass = FALSE; /* just in case */
  172885. } else
  172886. ERREXIT(cinfo, JERR_MODE_CHANGE);
  172887. }
  172888. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  172889. /*
  172890. * Initialize master decompression control and select active modules.
  172891. * This is performed at the start of jpeg_start_decompress.
  172892. */
  172893. GLOBAL(void)
  172894. jinit_master_decompress (j_decompress_ptr cinfo)
  172895. {
  172896. my_master_ptr6 master;
  172897. master = (my_master_ptr6)
  172898. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172899. SIZEOF(my_decomp_master));
  172900. cinfo->master = (struct jpeg_decomp_master *) master;
  172901. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  172902. master->pub.finish_output_pass = finish_output_pass;
  172903. master->pub.is_dummy_pass = FALSE;
  172904. master_selection(cinfo);
  172905. }
  172906. /*** End of inlined file: jdmaster.c ***/
  172907. #undef FIX
  172908. /*** Start of inlined file: jdmerge.c ***/
  172909. #define JPEG_INTERNALS
  172910. #ifdef UPSAMPLE_MERGING_SUPPORTED
  172911. /* Private subobject */
  172912. typedef struct {
  172913. struct jpeg_upsampler pub; /* public fields */
  172914. /* Pointer to routine to do actual upsampling/conversion of one row group */
  172915. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  172916. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  172917. JSAMPARRAY output_buf));
  172918. /* Private state for YCC->RGB conversion */
  172919. int * Cr_r_tab; /* => table for Cr to R conversion */
  172920. int * Cb_b_tab; /* => table for Cb to B conversion */
  172921. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  172922. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  172923. /* For 2:1 vertical sampling, we produce two output rows at a time.
  172924. * We need a "spare" row buffer to hold the second output row if the
  172925. * application provides just a one-row buffer; we also use the spare
  172926. * to discard the dummy last row if the image height is odd.
  172927. */
  172928. JSAMPROW spare_row;
  172929. boolean spare_full; /* T if spare buffer is occupied */
  172930. JDIMENSION out_row_width; /* samples per output row */
  172931. JDIMENSION rows_to_go; /* counts rows remaining in image */
  172932. } my_upsampler;
  172933. typedef my_upsampler * my_upsample_ptr;
  172934. #define SCALEBITS 16 /* speediest right-shift on some machines */
  172935. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  172936. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  172937. /*
  172938. * Initialize tables for YCC->RGB colorspace conversion.
  172939. * This is taken directly from jdcolor.c; see that file for more info.
  172940. */
  172941. LOCAL(void)
  172942. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  172943. {
  172944. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172945. int i;
  172946. INT32 x;
  172947. SHIFT_TEMPS
  172948. upsample->Cr_r_tab = (int *)
  172949. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172950. (MAXJSAMPLE+1) * SIZEOF(int));
  172951. upsample->Cb_b_tab = (int *)
  172952. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172953. (MAXJSAMPLE+1) * SIZEOF(int));
  172954. upsample->Cr_g_tab = (INT32 *)
  172955. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172956. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172957. upsample->Cb_g_tab = (INT32 *)
  172958. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172959. (MAXJSAMPLE+1) * SIZEOF(INT32));
  172960. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  172961. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  172962. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  172963. /* Cr=>R value is nearest int to 1.40200 * x */
  172964. upsample->Cr_r_tab[i] = (int)
  172965. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  172966. /* Cb=>B value is nearest int to 1.77200 * x */
  172967. upsample->Cb_b_tab[i] = (int)
  172968. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  172969. /* Cr=>G value is scaled-up -0.71414 * x */
  172970. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  172971. /* Cb=>G value is scaled-up -0.34414 * x */
  172972. /* We also add in ONE_HALF so that need not do it in inner loop */
  172973. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  172974. }
  172975. }
  172976. /*
  172977. * Initialize for an upsampling pass.
  172978. */
  172979. METHODDEF(void)
  172980. start_pass_merged_upsample (j_decompress_ptr cinfo)
  172981. {
  172982. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  172983. /* Mark the spare buffer empty */
  172984. upsample->spare_full = FALSE;
  172985. /* Initialize total-height counter for detecting bottom of image */
  172986. upsample->rows_to_go = cinfo->output_height;
  172987. }
  172988. /*
  172989. * Control routine to do upsampling (and color conversion).
  172990. *
  172991. * The control routine just handles the row buffering considerations.
  172992. */
  172993. METHODDEF(void)
  172994. merged_2v_upsample (j_decompress_ptr cinfo,
  172995. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  172996. JDIMENSION,
  172997. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172998. JDIMENSION out_rows_avail)
  172999. /* 2:1 vertical sampling case: may need a spare row. */
  173000. {
  173001. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173002. JSAMPROW work_ptrs[2];
  173003. JDIMENSION num_rows; /* number of rows returned to caller */
  173004. if (upsample->spare_full) {
  173005. /* If we have a spare row saved from a previous cycle, just return it. */
  173006. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  173007. 1, upsample->out_row_width);
  173008. num_rows = 1;
  173009. upsample->spare_full = FALSE;
  173010. } else {
  173011. /* Figure number of rows to return to caller. */
  173012. num_rows = 2;
  173013. /* Not more than the distance to the end of the image. */
  173014. if (num_rows > upsample->rows_to_go)
  173015. num_rows = upsample->rows_to_go;
  173016. /* And not more than what the client can accept: */
  173017. out_rows_avail -= *out_row_ctr;
  173018. if (num_rows > out_rows_avail)
  173019. num_rows = out_rows_avail;
  173020. /* Create output pointer array for upsampler. */
  173021. work_ptrs[0] = output_buf[*out_row_ctr];
  173022. if (num_rows > 1) {
  173023. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  173024. } else {
  173025. work_ptrs[1] = upsample->spare_row;
  173026. upsample->spare_full = TRUE;
  173027. }
  173028. /* Now do the upsampling. */
  173029. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  173030. }
  173031. /* Adjust counts */
  173032. *out_row_ctr += num_rows;
  173033. upsample->rows_to_go -= num_rows;
  173034. /* When the buffer is emptied, declare this input row group consumed */
  173035. if (! upsample->spare_full)
  173036. (*in_row_group_ctr)++;
  173037. }
  173038. METHODDEF(void)
  173039. merged_1v_upsample (j_decompress_ptr cinfo,
  173040. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173041. JDIMENSION,
  173042. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173043. JDIMENSION)
  173044. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173045. {
  173046. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173047. /* Just do the upsampling. */
  173048. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173049. output_buf + *out_row_ctr);
  173050. /* Adjust counts */
  173051. (*out_row_ctr)++;
  173052. (*in_row_group_ctr)++;
  173053. }
  173054. /*
  173055. * These are the routines invoked by the control routines to do
  173056. * the actual upsampling/conversion. One row group is processed per call.
  173057. *
  173058. * Note: since we may be writing directly into application-supplied buffers,
  173059. * we have to be honest about the output width; we can't assume the buffer
  173060. * has been rounded up to an even width.
  173061. */
  173062. /*
  173063. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173064. */
  173065. METHODDEF(void)
  173066. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173067. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173068. JSAMPARRAY output_buf)
  173069. {
  173070. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173071. register int y, cred, cgreen, cblue;
  173072. int cb, cr;
  173073. register JSAMPROW outptr;
  173074. JSAMPROW inptr0, inptr1, inptr2;
  173075. JDIMENSION col;
  173076. /* copy these pointers into registers if possible */
  173077. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173078. int * Crrtab = upsample->Cr_r_tab;
  173079. int * Cbbtab = upsample->Cb_b_tab;
  173080. INT32 * Crgtab = upsample->Cr_g_tab;
  173081. INT32 * Cbgtab = upsample->Cb_g_tab;
  173082. SHIFT_TEMPS
  173083. inptr0 = input_buf[0][in_row_group_ctr];
  173084. inptr1 = input_buf[1][in_row_group_ctr];
  173085. inptr2 = input_buf[2][in_row_group_ctr];
  173086. outptr = output_buf[0];
  173087. /* Loop for each pair of output pixels */
  173088. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173089. /* Do the chroma part of the calculation */
  173090. cb = GETJSAMPLE(*inptr1++);
  173091. cr = GETJSAMPLE(*inptr2++);
  173092. cred = Crrtab[cr];
  173093. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173094. cblue = Cbbtab[cb];
  173095. /* Fetch 2 Y values and emit 2 pixels */
  173096. y = GETJSAMPLE(*inptr0++);
  173097. outptr[RGB_RED] = range_limit[y + cred];
  173098. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173099. outptr[RGB_BLUE] = range_limit[y + cblue];
  173100. outptr += RGB_PIXELSIZE;
  173101. y = GETJSAMPLE(*inptr0++);
  173102. outptr[RGB_RED] = range_limit[y + cred];
  173103. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173104. outptr[RGB_BLUE] = range_limit[y + cblue];
  173105. outptr += RGB_PIXELSIZE;
  173106. }
  173107. /* If image width is odd, do the last output column separately */
  173108. if (cinfo->output_width & 1) {
  173109. cb = GETJSAMPLE(*inptr1);
  173110. cr = GETJSAMPLE(*inptr2);
  173111. cred = Crrtab[cr];
  173112. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173113. cblue = Cbbtab[cb];
  173114. y = GETJSAMPLE(*inptr0);
  173115. outptr[RGB_RED] = range_limit[y + cred];
  173116. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173117. outptr[RGB_BLUE] = range_limit[y + cblue];
  173118. }
  173119. }
  173120. /*
  173121. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173122. */
  173123. METHODDEF(void)
  173124. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173125. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173126. JSAMPARRAY output_buf)
  173127. {
  173128. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173129. register int y, cred, cgreen, cblue;
  173130. int cb, cr;
  173131. register JSAMPROW outptr0, outptr1;
  173132. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173133. JDIMENSION col;
  173134. /* copy these pointers into registers if possible */
  173135. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173136. int * Crrtab = upsample->Cr_r_tab;
  173137. int * Cbbtab = upsample->Cb_b_tab;
  173138. INT32 * Crgtab = upsample->Cr_g_tab;
  173139. INT32 * Cbgtab = upsample->Cb_g_tab;
  173140. SHIFT_TEMPS
  173141. inptr00 = input_buf[0][in_row_group_ctr*2];
  173142. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173143. inptr1 = input_buf[1][in_row_group_ctr];
  173144. inptr2 = input_buf[2][in_row_group_ctr];
  173145. outptr0 = output_buf[0];
  173146. outptr1 = output_buf[1];
  173147. /* Loop for each group of output pixels */
  173148. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173149. /* Do the chroma part of the calculation */
  173150. cb = GETJSAMPLE(*inptr1++);
  173151. cr = GETJSAMPLE(*inptr2++);
  173152. cred = Crrtab[cr];
  173153. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173154. cblue = Cbbtab[cb];
  173155. /* Fetch 4 Y values and emit 4 pixels */
  173156. y = GETJSAMPLE(*inptr00++);
  173157. outptr0[RGB_RED] = range_limit[y + cred];
  173158. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173159. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173160. outptr0 += RGB_PIXELSIZE;
  173161. y = GETJSAMPLE(*inptr00++);
  173162. outptr0[RGB_RED] = range_limit[y + cred];
  173163. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173164. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173165. outptr0 += RGB_PIXELSIZE;
  173166. y = GETJSAMPLE(*inptr01++);
  173167. outptr1[RGB_RED] = range_limit[y + cred];
  173168. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173169. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173170. outptr1 += RGB_PIXELSIZE;
  173171. y = GETJSAMPLE(*inptr01++);
  173172. outptr1[RGB_RED] = range_limit[y + cred];
  173173. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173174. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173175. outptr1 += RGB_PIXELSIZE;
  173176. }
  173177. /* If image width is odd, do the last output column separately */
  173178. if (cinfo->output_width & 1) {
  173179. cb = GETJSAMPLE(*inptr1);
  173180. cr = GETJSAMPLE(*inptr2);
  173181. cred = Crrtab[cr];
  173182. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173183. cblue = Cbbtab[cb];
  173184. y = GETJSAMPLE(*inptr00);
  173185. outptr0[RGB_RED] = range_limit[y + cred];
  173186. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173187. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173188. y = GETJSAMPLE(*inptr01);
  173189. outptr1[RGB_RED] = range_limit[y + cred];
  173190. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173191. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173192. }
  173193. }
  173194. /*
  173195. * Module initialization routine for merged upsampling/color conversion.
  173196. *
  173197. * NB: this is called under the conditions determined by use_merged_upsample()
  173198. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173199. * of this module; no safety checks are made here.
  173200. */
  173201. GLOBAL(void)
  173202. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173203. {
  173204. my_upsample_ptr upsample;
  173205. upsample = (my_upsample_ptr)
  173206. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173207. SIZEOF(my_upsampler));
  173208. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173209. upsample->pub.start_pass = start_pass_merged_upsample;
  173210. upsample->pub.need_context_rows = FALSE;
  173211. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173212. if (cinfo->max_v_samp_factor == 2) {
  173213. upsample->pub.upsample = merged_2v_upsample;
  173214. upsample->upmethod = h2v2_merged_upsample;
  173215. /* Allocate a spare row buffer */
  173216. upsample->spare_row = (JSAMPROW)
  173217. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173218. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173219. } else {
  173220. upsample->pub.upsample = merged_1v_upsample;
  173221. upsample->upmethod = h2v1_merged_upsample;
  173222. /* No spare row needed */
  173223. upsample->spare_row = NULL;
  173224. }
  173225. build_ycc_rgb_table2(cinfo);
  173226. }
  173227. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  173228. /*** End of inlined file: jdmerge.c ***/
  173229. #undef ASSIGN_STATE
  173230. /*** Start of inlined file: jdphuff.c ***/
  173231. #define JPEG_INTERNALS
  173232. #ifdef D_PROGRESSIVE_SUPPORTED
  173233. /*
  173234. * Expanded entropy decoder object for progressive Huffman decoding.
  173235. *
  173236. * The savable_state subrecord contains fields that change within an MCU,
  173237. * but must not be updated permanently until we complete the MCU.
  173238. */
  173239. typedef struct {
  173240. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  173241. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  173242. } savable_state3;
  173243. /* This macro is to work around compilers with missing or broken
  173244. * structure assignment. You'll need to fix this code if you have
  173245. * such a compiler and you change MAX_COMPS_IN_SCAN.
  173246. */
  173247. #ifndef NO_STRUCT_ASSIGN
  173248. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  173249. #else
  173250. #if MAX_COMPS_IN_SCAN == 4
  173251. #define ASSIGN_STATE(dest,src) \
  173252. ((dest).EOBRUN = (src).EOBRUN, \
  173253. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  173254. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  173255. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  173256. (dest).last_dc_val[3] = (src).last_dc_val[3])
  173257. #endif
  173258. #endif
  173259. typedef struct {
  173260. struct jpeg_entropy_decoder pub; /* public fields */
  173261. /* These fields are loaded into local variables at start of each MCU.
  173262. * In case of suspension, we exit WITHOUT updating them.
  173263. */
  173264. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  173265. savable_state3 saved; /* Other state at start of MCU */
  173266. /* These fields are NOT loaded into local working state. */
  173267. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  173268. /* Pointers to derived tables (these workspaces have image lifespan) */
  173269. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  173270. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  173271. } phuff_entropy_decoder;
  173272. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  173273. /* Forward declarations */
  173274. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  173275. JBLOCKROW *MCU_data));
  173276. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  173277. JBLOCKROW *MCU_data));
  173278. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  173279. JBLOCKROW *MCU_data));
  173280. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  173281. JBLOCKROW *MCU_data));
  173282. /*
  173283. * Initialize for a Huffman-compressed scan.
  173284. */
  173285. METHODDEF(void)
  173286. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  173287. {
  173288. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173289. boolean is_DC_band, bad;
  173290. int ci, coefi, tbl;
  173291. int *coef_bit_ptr;
  173292. jpeg_component_info * compptr;
  173293. is_DC_band = (cinfo->Ss == 0);
  173294. /* Validate scan parameters */
  173295. bad = FALSE;
  173296. if (is_DC_band) {
  173297. if (cinfo->Se != 0)
  173298. bad = TRUE;
  173299. } else {
  173300. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  173301. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  173302. bad = TRUE;
  173303. /* AC scans may have only one component */
  173304. if (cinfo->comps_in_scan != 1)
  173305. bad = TRUE;
  173306. }
  173307. if (cinfo->Ah != 0) {
  173308. /* Successive approximation refinement scan: must have Al = Ah-1. */
  173309. if (cinfo->Al != cinfo->Ah-1)
  173310. bad = TRUE;
  173311. }
  173312. if (cinfo->Al > 13) /* need not check for < 0 */
  173313. bad = TRUE;
  173314. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  173315. * but the spec doesn't say so, and we try to be liberal about what we
  173316. * accept. Note: large Al values could result in out-of-range DC
  173317. * coefficients during early scans, leading to bizarre displays due to
  173318. * overflows in the IDCT math. But we won't crash.
  173319. */
  173320. if (bad)
  173321. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  173322. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  173323. /* Update progression status, and verify that scan order is legal.
  173324. * Note that inter-scan inconsistencies are treated as warnings
  173325. * not fatal errors ... not clear if this is right way to behave.
  173326. */
  173327. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173328. int cindex = cinfo->cur_comp_info[ci]->component_index;
  173329. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  173330. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  173331. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  173332. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  173333. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  173334. if (cinfo->Ah != expected)
  173335. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  173336. coef_bit_ptr[coefi] = cinfo->Al;
  173337. }
  173338. }
  173339. /* Select MCU decoding routine */
  173340. if (cinfo->Ah == 0) {
  173341. if (is_DC_band)
  173342. entropy->pub.decode_mcu = decode_mcu_DC_first;
  173343. else
  173344. entropy->pub.decode_mcu = decode_mcu_AC_first;
  173345. } else {
  173346. if (is_DC_band)
  173347. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  173348. else
  173349. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  173350. }
  173351. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  173352. compptr = cinfo->cur_comp_info[ci];
  173353. /* Make sure requested tables are present, and compute derived tables.
  173354. * We may build same derived table more than once, but it's not expensive.
  173355. */
  173356. if (is_DC_band) {
  173357. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  173358. tbl = compptr->dc_tbl_no;
  173359. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  173360. & entropy->derived_tbls[tbl]);
  173361. }
  173362. } else {
  173363. tbl = compptr->ac_tbl_no;
  173364. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  173365. & entropy->derived_tbls[tbl]);
  173366. /* remember the single active table */
  173367. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  173368. }
  173369. /* Initialize DC predictions to 0 */
  173370. entropy->saved.last_dc_val[ci] = 0;
  173371. }
  173372. /* Initialize bitread state variables */
  173373. entropy->bitstate.bits_left = 0;
  173374. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  173375. entropy->pub.insufficient_data = FALSE;
  173376. /* Initialize private state variables */
  173377. entropy->saved.EOBRUN = 0;
  173378. /* Initialize restart counter */
  173379. entropy->restarts_to_go = cinfo->restart_interval;
  173380. }
  173381. /*
  173382. * Check for a restart marker & resynchronize decoder.
  173383. * Returns FALSE if must suspend.
  173384. */
  173385. LOCAL(boolean)
  173386. process_restartp (j_decompress_ptr cinfo)
  173387. {
  173388. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173389. int ci;
  173390. /* Throw away any unused bits remaining in bit buffer; */
  173391. /* include any full bytes in next_marker's count of discarded bytes */
  173392. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  173393. entropy->bitstate.bits_left = 0;
  173394. /* Advance past the RSTn marker */
  173395. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  173396. return FALSE;
  173397. /* Re-initialize DC predictions to 0 */
  173398. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  173399. entropy->saved.last_dc_val[ci] = 0;
  173400. /* Re-init EOB run count, too */
  173401. entropy->saved.EOBRUN = 0;
  173402. /* Reset restart counter */
  173403. entropy->restarts_to_go = cinfo->restart_interval;
  173404. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  173405. * against a marker. In that case we will end up treating the next data
  173406. * segment as empty, and we can avoid producing bogus output pixels by
  173407. * leaving the flag set.
  173408. */
  173409. if (cinfo->unread_marker == 0)
  173410. entropy->pub.insufficient_data = FALSE;
  173411. return TRUE;
  173412. }
  173413. /*
  173414. * Huffman MCU decoding.
  173415. * Each of these routines decodes and returns one MCU's worth of
  173416. * Huffman-compressed coefficients.
  173417. * The coefficients are reordered from zigzag order into natural array order,
  173418. * but are not dequantized.
  173419. *
  173420. * The i'th block of the MCU is stored into the block pointed to by
  173421. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  173422. *
  173423. * We return FALSE if data source requested suspension. In that case no
  173424. * changes have been made to permanent state. (Exception: some output
  173425. * coefficients may already have been assigned. This is harmless for
  173426. * spectral selection, since we'll just re-assign them on the next call.
  173427. * Successive approximation AC refinement has to be more careful, however.)
  173428. */
  173429. /*
  173430. * MCU decoding for DC initial scan (either spectral selection,
  173431. * or first pass of successive approximation).
  173432. */
  173433. METHODDEF(boolean)
  173434. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173435. {
  173436. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173437. int Al = cinfo->Al;
  173438. register int s, r;
  173439. int blkn, ci;
  173440. JBLOCKROW block;
  173441. BITREAD_STATE_VARS;
  173442. savable_state3 state;
  173443. d_derived_tbl * tbl;
  173444. jpeg_component_info * compptr;
  173445. /* Process restart marker if needed; may have to suspend */
  173446. if (cinfo->restart_interval) {
  173447. if (entropy->restarts_to_go == 0)
  173448. if (! process_restartp(cinfo))
  173449. return FALSE;
  173450. }
  173451. /* If we've run out of data, just leave the MCU set to zeroes.
  173452. * This way, we return uniform gray for the remainder of the segment.
  173453. */
  173454. if (! entropy->pub.insufficient_data) {
  173455. /* Load up working state */
  173456. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173457. ASSIGN_STATE(state, entropy->saved);
  173458. /* Outer loop handles each block in the MCU */
  173459. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173460. block = MCU_data[blkn];
  173461. ci = cinfo->MCU_membership[blkn];
  173462. compptr = cinfo->cur_comp_info[ci];
  173463. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  173464. /* Decode a single block's worth of coefficients */
  173465. /* Section F.2.2.1: decode the DC coefficient difference */
  173466. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  173467. if (s) {
  173468. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173469. r = GET_BITS(s);
  173470. s = HUFF_EXTEND(r, s);
  173471. }
  173472. /* Convert DC difference to actual value, update last_dc_val */
  173473. s += state.last_dc_val[ci];
  173474. state.last_dc_val[ci] = s;
  173475. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  173476. (*block)[0] = (JCOEF) (s << Al);
  173477. }
  173478. /* Completed MCU, so update state */
  173479. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173480. ASSIGN_STATE(entropy->saved, state);
  173481. }
  173482. /* Account for restart interval (no-op if not using restarts) */
  173483. entropy->restarts_to_go--;
  173484. return TRUE;
  173485. }
  173486. /*
  173487. * MCU decoding for AC initial scan (either spectral selection,
  173488. * or first pass of successive approximation).
  173489. */
  173490. METHODDEF(boolean)
  173491. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173492. {
  173493. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173494. int Se = cinfo->Se;
  173495. int Al = cinfo->Al;
  173496. register int s, k, r;
  173497. unsigned int EOBRUN;
  173498. JBLOCKROW block;
  173499. BITREAD_STATE_VARS;
  173500. d_derived_tbl * tbl;
  173501. /* Process restart marker if needed; may have to suspend */
  173502. if (cinfo->restart_interval) {
  173503. if (entropy->restarts_to_go == 0)
  173504. if (! process_restartp(cinfo))
  173505. return FALSE;
  173506. }
  173507. /* If we've run out of data, just leave the MCU set to zeroes.
  173508. * This way, we return uniform gray for the remainder of the segment.
  173509. */
  173510. if (! entropy->pub.insufficient_data) {
  173511. /* Load up working state.
  173512. * We can avoid loading/saving bitread state if in an EOB run.
  173513. */
  173514. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173515. /* There is always only one block per MCU */
  173516. if (EOBRUN > 0) /* if it's a band of zeroes... */
  173517. EOBRUN--; /* ...process it now (we do nothing) */
  173518. else {
  173519. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173520. block = MCU_data[0];
  173521. tbl = entropy->ac_derived_tbl;
  173522. for (k = cinfo->Ss; k <= Se; k++) {
  173523. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  173524. r = s >> 4;
  173525. s &= 15;
  173526. if (s) {
  173527. k += r;
  173528. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  173529. r = GET_BITS(s);
  173530. s = HUFF_EXTEND(r, s);
  173531. /* Scale and output coefficient in natural (dezigzagged) order */
  173532. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  173533. } else {
  173534. if (r == 15) { /* ZRL */
  173535. k += 15; /* skip 15 zeroes in band */
  173536. } else { /* EOBr, run length is 2^r + appended bits */
  173537. EOBRUN = 1 << r;
  173538. if (r) { /* EOBr, r > 0 */
  173539. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  173540. r = GET_BITS(r);
  173541. EOBRUN += r;
  173542. }
  173543. EOBRUN--; /* this band is processed at this moment */
  173544. break; /* force end-of-band */
  173545. }
  173546. }
  173547. }
  173548. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173549. }
  173550. /* Completed MCU, so update state */
  173551. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173552. }
  173553. /* Account for restart interval (no-op if not using restarts) */
  173554. entropy->restarts_to_go--;
  173555. return TRUE;
  173556. }
  173557. /*
  173558. * MCU decoding for DC successive approximation refinement scan.
  173559. * Note: we assume such scans can be multi-component, although the spec
  173560. * is not very clear on the point.
  173561. */
  173562. METHODDEF(boolean)
  173563. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173564. {
  173565. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173566. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173567. int blkn;
  173568. JBLOCKROW block;
  173569. BITREAD_STATE_VARS;
  173570. /* Process restart marker if needed; may have to suspend */
  173571. if (cinfo->restart_interval) {
  173572. if (entropy->restarts_to_go == 0)
  173573. if (! process_restartp(cinfo))
  173574. return FALSE;
  173575. }
  173576. /* Not worth the cycles to check insufficient_data here,
  173577. * since we will not change the data anyway if we read zeroes.
  173578. */
  173579. /* Load up working state */
  173580. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173581. /* Outer loop handles each block in the MCU */
  173582. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  173583. block = MCU_data[blkn];
  173584. /* Encoded data is simply the next bit of the two's-complement DC value */
  173585. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  173586. if (GET_BITS(1))
  173587. (*block)[0] |= p1;
  173588. /* Note: since we use |=, repeating the assignment later is safe */
  173589. }
  173590. /* Completed MCU, so update state */
  173591. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173592. /* Account for restart interval (no-op if not using restarts) */
  173593. entropy->restarts_to_go--;
  173594. return TRUE;
  173595. }
  173596. /*
  173597. * MCU decoding for AC successive approximation refinement scan.
  173598. */
  173599. METHODDEF(boolean)
  173600. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  173601. {
  173602. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  173603. int Se = cinfo->Se;
  173604. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  173605. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  173606. register int s, k, r;
  173607. unsigned int EOBRUN;
  173608. JBLOCKROW block;
  173609. JCOEFPTR thiscoef;
  173610. BITREAD_STATE_VARS;
  173611. d_derived_tbl * tbl;
  173612. int num_newnz;
  173613. int newnz_pos[DCTSIZE2];
  173614. /* Process restart marker if needed; may have to suspend */
  173615. if (cinfo->restart_interval) {
  173616. if (entropy->restarts_to_go == 0)
  173617. if (! process_restartp(cinfo))
  173618. return FALSE;
  173619. }
  173620. /* If we've run out of data, don't modify the MCU.
  173621. */
  173622. if (! entropy->pub.insufficient_data) {
  173623. /* Load up working state */
  173624. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  173625. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  173626. /* There is always only one block per MCU */
  173627. block = MCU_data[0];
  173628. tbl = entropy->ac_derived_tbl;
  173629. /* If we are forced to suspend, we must undo the assignments to any newly
  173630. * nonzero coefficients in the block, because otherwise we'd get confused
  173631. * next time about which coefficients were already nonzero.
  173632. * But we need not undo addition of bits to already-nonzero coefficients;
  173633. * instead, we can test the current bit to see if we already did it.
  173634. */
  173635. num_newnz = 0;
  173636. /* initialize coefficient loop counter to start of band */
  173637. k = cinfo->Ss;
  173638. if (EOBRUN == 0) {
  173639. for (; k <= Se; k++) {
  173640. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  173641. r = s >> 4;
  173642. s &= 15;
  173643. if (s) {
  173644. if (s != 1) /* size of new coef should always be 1 */
  173645. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  173646. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173647. if (GET_BITS(1))
  173648. s = p1; /* newly nonzero coef is positive */
  173649. else
  173650. s = m1; /* newly nonzero coef is negative */
  173651. } else {
  173652. if (r != 15) {
  173653. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  173654. if (r) {
  173655. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  173656. r = GET_BITS(r);
  173657. EOBRUN += r;
  173658. }
  173659. break; /* rest of block is handled by EOB logic */
  173660. }
  173661. /* note s = 0 for processing ZRL */
  173662. }
  173663. /* Advance over already-nonzero coefs and r still-zero coefs,
  173664. * appending correction bits to the nonzeroes. A correction bit is 1
  173665. * if the absolute value of the coefficient must be increased.
  173666. */
  173667. do {
  173668. thiscoef = *block + jpeg_natural_order[k];
  173669. if (*thiscoef != 0) {
  173670. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173671. if (GET_BITS(1)) {
  173672. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  173673. if (*thiscoef >= 0)
  173674. *thiscoef += p1;
  173675. else
  173676. *thiscoef += m1;
  173677. }
  173678. }
  173679. } else {
  173680. if (--r < 0)
  173681. break; /* reached target zero coefficient */
  173682. }
  173683. k++;
  173684. } while (k <= Se);
  173685. if (s) {
  173686. int pos = jpeg_natural_order[k];
  173687. /* Output newly nonzero coefficient */
  173688. (*block)[pos] = (JCOEF) s;
  173689. /* Remember its position in case we have to suspend */
  173690. newnz_pos[num_newnz++] = pos;
  173691. }
  173692. }
  173693. }
  173694. if (EOBRUN > 0) {
  173695. /* Scan any remaining coefficient positions after the end-of-band
  173696. * (the last newly nonzero coefficient, if any). Append a correction
  173697. * bit to each already-nonzero coefficient. A correction bit is 1
  173698. * if the absolute value of the coefficient must be increased.
  173699. */
  173700. for (; k <= Se; k++) {
  173701. thiscoef = *block + jpeg_natural_order[k];
  173702. if (*thiscoef != 0) {
  173703. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  173704. if (GET_BITS(1)) {
  173705. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  173706. if (*thiscoef >= 0)
  173707. *thiscoef += p1;
  173708. else
  173709. *thiscoef += m1;
  173710. }
  173711. }
  173712. }
  173713. }
  173714. /* Count one block completed in EOB run */
  173715. EOBRUN--;
  173716. }
  173717. /* Completed MCU, so update state */
  173718. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  173719. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  173720. }
  173721. /* Account for restart interval (no-op if not using restarts) */
  173722. entropy->restarts_to_go--;
  173723. return TRUE;
  173724. undoit:
  173725. /* Re-zero any output coefficients that we made newly nonzero */
  173726. while (num_newnz > 0)
  173727. (*block)[newnz_pos[--num_newnz]] = 0;
  173728. return FALSE;
  173729. }
  173730. /*
  173731. * Module initialization routine for progressive Huffman entropy decoding.
  173732. */
  173733. GLOBAL(void)
  173734. jinit_phuff_decoder (j_decompress_ptr cinfo)
  173735. {
  173736. phuff_entropy_ptr2 entropy;
  173737. int *coef_bit_ptr;
  173738. int ci, i;
  173739. entropy = (phuff_entropy_ptr2)
  173740. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173741. SIZEOF(phuff_entropy_decoder));
  173742. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  173743. entropy->pub.start_pass = start_pass_phuff_decoder;
  173744. /* Mark derived tables unallocated */
  173745. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  173746. entropy->derived_tbls[i] = NULL;
  173747. }
  173748. /* Create progression status table */
  173749. cinfo->coef_bits = (int (*)[DCTSIZE2])
  173750. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173751. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  173752. coef_bit_ptr = & cinfo->coef_bits[0][0];
  173753. for (ci = 0; ci < cinfo->num_components; ci++)
  173754. for (i = 0; i < DCTSIZE2; i++)
  173755. *coef_bit_ptr++ = -1;
  173756. }
  173757. #endif /* D_PROGRESSIVE_SUPPORTED */
  173758. /*** End of inlined file: jdphuff.c ***/
  173759. /*** Start of inlined file: jdpostct.c ***/
  173760. #define JPEG_INTERNALS
  173761. /* Private buffer controller object */
  173762. typedef struct {
  173763. struct jpeg_d_post_controller pub; /* public fields */
  173764. /* Color quantization source buffer: this holds output data from
  173765. * the upsample/color conversion step to be passed to the quantizer.
  173766. * For two-pass color quantization, we need a full-image buffer;
  173767. * for one-pass operation, a strip buffer is sufficient.
  173768. */
  173769. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  173770. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  173771. JDIMENSION strip_height; /* buffer size in rows */
  173772. /* for two-pass mode only: */
  173773. JDIMENSION starting_row; /* row # of first row in current strip */
  173774. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  173775. } my_post_controller;
  173776. typedef my_post_controller * my_post_ptr;
  173777. /* Forward declarations */
  173778. METHODDEF(void) post_process_1pass
  173779. JPP((j_decompress_ptr cinfo,
  173780. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173781. JDIMENSION in_row_groups_avail,
  173782. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173783. JDIMENSION out_rows_avail));
  173784. #ifdef QUANT_2PASS_SUPPORTED
  173785. METHODDEF(void) post_process_prepass
  173786. JPP((j_decompress_ptr cinfo,
  173787. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173788. JDIMENSION in_row_groups_avail,
  173789. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173790. JDIMENSION out_rows_avail));
  173791. METHODDEF(void) post_process_2pass
  173792. JPP((j_decompress_ptr cinfo,
  173793. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173794. JDIMENSION in_row_groups_avail,
  173795. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173796. JDIMENSION out_rows_avail));
  173797. #endif
  173798. /*
  173799. * Initialize for a processing pass.
  173800. */
  173801. METHODDEF(void)
  173802. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  173803. {
  173804. my_post_ptr post = (my_post_ptr) cinfo->post;
  173805. switch (pass_mode) {
  173806. case JBUF_PASS_THRU:
  173807. if (cinfo->quantize_colors) {
  173808. /* Single-pass processing with color quantization. */
  173809. post->pub.post_process_data = post_process_1pass;
  173810. /* We could be doing buffered-image output before starting a 2-pass
  173811. * color quantization; in that case, jinit_d_post_controller did not
  173812. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  173813. */
  173814. if (post->buffer == NULL) {
  173815. post->buffer = (*cinfo->mem->access_virt_sarray)
  173816. ((j_common_ptr) cinfo, post->whole_image,
  173817. (JDIMENSION) 0, post->strip_height, TRUE);
  173818. }
  173819. } else {
  173820. /* For single-pass processing without color quantization,
  173821. * I have no work to do; just call the upsampler directly.
  173822. */
  173823. post->pub.post_process_data = cinfo->upsample->upsample;
  173824. }
  173825. break;
  173826. #ifdef QUANT_2PASS_SUPPORTED
  173827. case JBUF_SAVE_AND_PASS:
  173828. /* First pass of 2-pass quantization */
  173829. if (post->whole_image == NULL)
  173830. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173831. post->pub.post_process_data = post_process_prepass;
  173832. break;
  173833. case JBUF_CRANK_DEST:
  173834. /* Second pass of 2-pass quantization */
  173835. if (post->whole_image == NULL)
  173836. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173837. post->pub.post_process_data = post_process_2pass;
  173838. break;
  173839. #endif /* QUANT_2PASS_SUPPORTED */
  173840. default:
  173841. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173842. break;
  173843. }
  173844. post->starting_row = post->next_row = 0;
  173845. }
  173846. /*
  173847. * Process some data in the one-pass (strip buffer) case.
  173848. * This is used for color precision reduction as well as one-pass quantization.
  173849. */
  173850. METHODDEF(void)
  173851. post_process_1pass (j_decompress_ptr cinfo,
  173852. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173853. JDIMENSION in_row_groups_avail,
  173854. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173855. JDIMENSION out_rows_avail)
  173856. {
  173857. my_post_ptr post = (my_post_ptr) cinfo->post;
  173858. JDIMENSION num_rows, max_rows;
  173859. /* Fill the buffer, but not more than what we can dump out in one go. */
  173860. /* Note we rely on the upsampler to detect bottom of image. */
  173861. max_rows = out_rows_avail - *out_row_ctr;
  173862. if (max_rows > post->strip_height)
  173863. max_rows = post->strip_height;
  173864. num_rows = 0;
  173865. (*cinfo->upsample->upsample) (cinfo,
  173866. input_buf, in_row_group_ctr, in_row_groups_avail,
  173867. post->buffer, &num_rows, max_rows);
  173868. /* Quantize and emit data. */
  173869. (*cinfo->cquantize->color_quantize) (cinfo,
  173870. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  173871. *out_row_ctr += num_rows;
  173872. }
  173873. #ifdef QUANT_2PASS_SUPPORTED
  173874. /*
  173875. * Process some data in the first pass of 2-pass quantization.
  173876. */
  173877. METHODDEF(void)
  173878. post_process_prepass (j_decompress_ptr cinfo,
  173879. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173880. JDIMENSION in_row_groups_avail,
  173881. JSAMPARRAY, JDIMENSION *out_row_ctr,
  173882. JDIMENSION)
  173883. {
  173884. my_post_ptr post = (my_post_ptr) cinfo->post;
  173885. JDIMENSION old_next_row, num_rows;
  173886. /* Reposition virtual buffer if at start of strip. */
  173887. if (post->next_row == 0) {
  173888. post->buffer = (*cinfo->mem->access_virt_sarray)
  173889. ((j_common_ptr) cinfo, post->whole_image,
  173890. post->starting_row, post->strip_height, TRUE);
  173891. }
  173892. /* Upsample some data (up to a strip height's worth). */
  173893. old_next_row = post->next_row;
  173894. (*cinfo->upsample->upsample) (cinfo,
  173895. input_buf, in_row_group_ctr, in_row_groups_avail,
  173896. post->buffer, &post->next_row, post->strip_height);
  173897. /* Allow quantizer to scan new data. No data is emitted, */
  173898. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  173899. if (post->next_row > old_next_row) {
  173900. num_rows = post->next_row - old_next_row;
  173901. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  173902. (JSAMPARRAY) NULL, (int) num_rows);
  173903. *out_row_ctr += num_rows;
  173904. }
  173905. /* Advance if we filled the strip. */
  173906. if (post->next_row >= post->strip_height) {
  173907. post->starting_row += post->strip_height;
  173908. post->next_row = 0;
  173909. }
  173910. }
  173911. /*
  173912. * Process some data in the second pass of 2-pass quantization.
  173913. */
  173914. METHODDEF(void)
  173915. post_process_2pass (j_decompress_ptr cinfo,
  173916. JSAMPIMAGE, JDIMENSION *,
  173917. JDIMENSION,
  173918. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173919. JDIMENSION out_rows_avail)
  173920. {
  173921. my_post_ptr post = (my_post_ptr) cinfo->post;
  173922. JDIMENSION num_rows, max_rows;
  173923. /* Reposition virtual buffer if at start of strip. */
  173924. if (post->next_row == 0) {
  173925. post->buffer = (*cinfo->mem->access_virt_sarray)
  173926. ((j_common_ptr) cinfo, post->whole_image,
  173927. post->starting_row, post->strip_height, FALSE);
  173928. }
  173929. /* Determine number of rows to emit. */
  173930. num_rows = post->strip_height - post->next_row; /* available in strip */
  173931. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  173932. if (num_rows > max_rows)
  173933. num_rows = max_rows;
  173934. /* We have to check bottom of image here, can't depend on upsampler. */
  173935. max_rows = cinfo->output_height - post->starting_row;
  173936. if (num_rows > max_rows)
  173937. num_rows = max_rows;
  173938. /* Quantize and emit data. */
  173939. (*cinfo->cquantize->color_quantize) (cinfo,
  173940. post->buffer + post->next_row, output_buf + *out_row_ctr,
  173941. (int) num_rows);
  173942. *out_row_ctr += num_rows;
  173943. /* Advance if we filled the strip. */
  173944. post->next_row += num_rows;
  173945. if (post->next_row >= post->strip_height) {
  173946. post->starting_row += post->strip_height;
  173947. post->next_row = 0;
  173948. }
  173949. }
  173950. #endif /* QUANT_2PASS_SUPPORTED */
  173951. /*
  173952. * Initialize postprocessing controller.
  173953. */
  173954. GLOBAL(void)
  173955. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  173956. {
  173957. my_post_ptr post;
  173958. post = (my_post_ptr)
  173959. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173960. SIZEOF(my_post_controller));
  173961. cinfo->post = (struct jpeg_d_post_controller *) post;
  173962. post->pub.start_pass = start_pass_dpost;
  173963. post->whole_image = NULL; /* flag for no virtual arrays */
  173964. post->buffer = NULL; /* flag for no strip buffer */
  173965. /* Create the quantization buffer, if needed */
  173966. if (cinfo->quantize_colors) {
  173967. /* The buffer strip height is max_v_samp_factor, which is typically
  173968. * an efficient number of rows for upsampling to return.
  173969. * (In the presence of output rescaling, we might want to be smarter?)
  173970. */
  173971. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  173972. if (need_full_buffer) {
  173973. /* Two-pass color quantization: need full-image storage. */
  173974. /* We round up the number of rows to a multiple of the strip height. */
  173975. #ifdef QUANT_2PASS_SUPPORTED
  173976. post->whole_image = (*cinfo->mem->request_virt_sarray)
  173977. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  173978. cinfo->output_width * cinfo->out_color_components,
  173979. (JDIMENSION) jround_up((long) cinfo->output_height,
  173980. (long) post->strip_height),
  173981. post->strip_height);
  173982. #else
  173983. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  173984. #endif /* QUANT_2PASS_SUPPORTED */
  173985. } else {
  173986. /* One-pass color quantization: just make a strip buffer. */
  173987. post->buffer = (*cinfo->mem->alloc_sarray)
  173988. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173989. cinfo->output_width * cinfo->out_color_components,
  173990. post->strip_height);
  173991. }
  173992. }
  173993. }
  173994. /*** End of inlined file: jdpostct.c ***/
  173995. #undef FIX
  173996. /*** Start of inlined file: jdsample.c ***/
  173997. #define JPEG_INTERNALS
  173998. /* Pointer to routine to upsample a single component */
  173999. typedef JMETHOD(void, upsample1_ptr,
  174000. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174001. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  174002. /* Private subobject */
  174003. typedef struct {
  174004. struct jpeg_upsampler pub; /* public fields */
  174005. /* Color conversion buffer. When using separate upsampling and color
  174006. * conversion steps, this buffer holds one upsampled row group until it
  174007. * has been color converted and output.
  174008. * Note: we do not allocate any storage for component(s) which are full-size,
  174009. * ie do not need rescaling. The corresponding entry of color_buf[] is
  174010. * simply set to point to the input data array, thereby avoiding copying.
  174011. */
  174012. JSAMPARRAY color_buf[MAX_COMPONENTS];
  174013. /* Per-component upsampling method pointers */
  174014. upsample1_ptr methods[MAX_COMPONENTS];
  174015. int next_row_out; /* counts rows emitted from color_buf */
  174016. JDIMENSION rows_to_go; /* counts rows remaining in image */
  174017. /* Height of an input row group for each component. */
  174018. int rowgroup_height[MAX_COMPONENTS];
  174019. /* These arrays save pixel expansion factors so that int_expand need not
  174020. * recompute them each time. They are unused for other upsampling methods.
  174021. */
  174022. UINT8 h_expand[MAX_COMPONENTS];
  174023. UINT8 v_expand[MAX_COMPONENTS];
  174024. } my_upsampler2;
  174025. typedef my_upsampler2 * my_upsample_ptr2;
  174026. /*
  174027. * Initialize for an upsampling pass.
  174028. */
  174029. METHODDEF(void)
  174030. start_pass_upsample (j_decompress_ptr cinfo)
  174031. {
  174032. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174033. /* Mark the conversion buffer empty */
  174034. upsample->next_row_out = cinfo->max_v_samp_factor;
  174035. /* Initialize total-height counter for detecting bottom of image */
  174036. upsample->rows_to_go = cinfo->output_height;
  174037. }
  174038. /*
  174039. * Control routine to do upsampling (and color conversion).
  174040. *
  174041. * In this version we upsample each component independently.
  174042. * We upsample one row group into the conversion buffer, then apply
  174043. * color conversion a row at a time.
  174044. */
  174045. METHODDEF(void)
  174046. sep_upsample (j_decompress_ptr cinfo,
  174047. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174048. JDIMENSION,
  174049. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174050. JDIMENSION out_rows_avail)
  174051. {
  174052. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174053. int ci;
  174054. jpeg_component_info * compptr;
  174055. JDIMENSION num_rows;
  174056. /* Fill the conversion buffer, if it's empty */
  174057. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174058. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174059. ci++, compptr++) {
  174060. /* Invoke per-component upsample method. Notice we pass a POINTER
  174061. * to color_buf[ci], so that fullsize_upsample can change it.
  174062. */
  174063. (*upsample->methods[ci]) (cinfo, compptr,
  174064. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174065. upsample->color_buf + ci);
  174066. }
  174067. upsample->next_row_out = 0;
  174068. }
  174069. /* Color-convert and emit rows */
  174070. /* How many we have in the buffer: */
  174071. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174072. /* Not more than the distance to the end of the image. Need this test
  174073. * in case the image height is not a multiple of max_v_samp_factor:
  174074. */
  174075. if (num_rows > upsample->rows_to_go)
  174076. num_rows = upsample->rows_to_go;
  174077. /* And not more than what the client can accept: */
  174078. out_rows_avail -= *out_row_ctr;
  174079. if (num_rows > out_rows_avail)
  174080. num_rows = out_rows_avail;
  174081. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174082. (JDIMENSION) upsample->next_row_out,
  174083. output_buf + *out_row_ctr,
  174084. (int) num_rows);
  174085. /* Adjust counts */
  174086. *out_row_ctr += num_rows;
  174087. upsample->rows_to_go -= num_rows;
  174088. upsample->next_row_out += num_rows;
  174089. /* When the buffer is emptied, declare this input row group consumed */
  174090. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174091. (*in_row_group_ctr)++;
  174092. }
  174093. /*
  174094. * These are the routines invoked by sep_upsample to upsample pixel values
  174095. * of a single component. One row group is processed per call.
  174096. */
  174097. /*
  174098. * For full-size components, we just make color_buf[ci] point at the
  174099. * input buffer, and thus avoid copying any data. Note that this is
  174100. * safe only because sep_upsample doesn't declare the input row group
  174101. * "consumed" until we are done color converting and emitting it.
  174102. */
  174103. METHODDEF(void)
  174104. fullsize_upsample (j_decompress_ptr, jpeg_component_info *,
  174105. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174106. {
  174107. *output_data_ptr = input_data;
  174108. }
  174109. /*
  174110. * This is a no-op version used for "uninteresting" components.
  174111. * These components will not be referenced by color conversion.
  174112. */
  174113. METHODDEF(void)
  174114. noop_upsample (j_decompress_ptr, jpeg_component_info *,
  174115. JSAMPARRAY, JSAMPARRAY * output_data_ptr)
  174116. {
  174117. *output_data_ptr = NULL; /* safety check */
  174118. }
  174119. /*
  174120. * This version handles any integral sampling ratios.
  174121. * This is not used for typical JPEG files, so it need not be fast.
  174122. * Nor, for that matter, is it particularly accurate: the algorithm is
  174123. * simple replication of the input pixel onto the corresponding output
  174124. * pixels. The hi-falutin sampling literature refers to this as a
  174125. * "box filter". A box filter tends to introduce visible artifacts,
  174126. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174127. * you would be well advised to improve this code.
  174128. */
  174129. METHODDEF(void)
  174130. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174131. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174132. {
  174133. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174134. JSAMPARRAY output_data = *output_data_ptr;
  174135. register JSAMPROW inptr, outptr;
  174136. register JSAMPLE invalue;
  174137. register int h;
  174138. JSAMPROW outend;
  174139. int h_expand, v_expand;
  174140. int inrow, outrow;
  174141. h_expand = upsample->h_expand[compptr->component_index];
  174142. v_expand = upsample->v_expand[compptr->component_index];
  174143. inrow = outrow = 0;
  174144. while (outrow < cinfo->max_v_samp_factor) {
  174145. /* Generate one output row with proper horizontal expansion */
  174146. inptr = input_data[inrow];
  174147. outptr = output_data[outrow];
  174148. outend = outptr + cinfo->output_width;
  174149. while (outptr < outend) {
  174150. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174151. for (h = h_expand; h > 0; h--) {
  174152. *outptr++ = invalue;
  174153. }
  174154. }
  174155. /* Generate any additional output rows by duplicating the first one */
  174156. if (v_expand > 1) {
  174157. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174158. v_expand-1, cinfo->output_width);
  174159. }
  174160. inrow++;
  174161. outrow += v_expand;
  174162. }
  174163. }
  174164. /*
  174165. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174166. * It's still a box filter.
  174167. */
  174168. METHODDEF(void)
  174169. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174170. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174171. {
  174172. JSAMPARRAY output_data = *output_data_ptr;
  174173. register JSAMPROW inptr, outptr;
  174174. register JSAMPLE invalue;
  174175. JSAMPROW outend;
  174176. int inrow;
  174177. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174178. inptr = input_data[inrow];
  174179. outptr = output_data[inrow];
  174180. outend = outptr + cinfo->output_width;
  174181. while (outptr < outend) {
  174182. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174183. *outptr++ = invalue;
  174184. *outptr++ = invalue;
  174185. }
  174186. }
  174187. }
  174188. /*
  174189. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174190. * It's still a box filter.
  174191. */
  174192. METHODDEF(void)
  174193. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info *,
  174194. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174195. {
  174196. JSAMPARRAY output_data = *output_data_ptr;
  174197. register JSAMPROW inptr, outptr;
  174198. register JSAMPLE invalue;
  174199. JSAMPROW outend;
  174200. int inrow, outrow;
  174201. inrow = outrow = 0;
  174202. while (outrow < cinfo->max_v_samp_factor) {
  174203. inptr = input_data[inrow];
  174204. outptr = output_data[outrow];
  174205. outend = outptr + cinfo->output_width;
  174206. while (outptr < outend) {
  174207. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174208. *outptr++ = invalue;
  174209. *outptr++ = invalue;
  174210. }
  174211. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174212. 1, cinfo->output_width);
  174213. inrow++;
  174214. outrow += 2;
  174215. }
  174216. }
  174217. /*
  174218. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174219. *
  174220. * The upsampling algorithm is linear interpolation between pixel centers,
  174221. * also known as a "triangle filter". This is a good compromise between
  174222. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174223. * of the way between input pixel centers.
  174224. *
  174225. * A note about the "bias" calculations: when rounding fractional values to
  174226. * integer, we do not want to always round 0.5 up to the next integer.
  174227. * If we did that, we'd introduce a noticeable bias towards larger values.
  174228. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  174229. * alternate pixel locations (a simple ordered dither pattern).
  174230. */
  174231. METHODDEF(void)
  174232. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174233. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174234. {
  174235. JSAMPARRAY output_data = *output_data_ptr;
  174236. register JSAMPROW inptr, outptr;
  174237. register int invalue;
  174238. register JDIMENSION colctr;
  174239. int inrow;
  174240. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174241. inptr = input_data[inrow];
  174242. outptr = output_data[inrow];
  174243. /* Special case for first column */
  174244. invalue = GETJSAMPLE(*inptr++);
  174245. *outptr++ = (JSAMPLE) invalue;
  174246. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  174247. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174248. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  174249. invalue = GETJSAMPLE(*inptr++) * 3;
  174250. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  174251. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  174252. }
  174253. /* Special case for last column */
  174254. invalue = GETJSAMPLE(*inptr);
  174255. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  174256. *outptr++ = (JSAMPLE) invalue;
  174257. }
  174258. }
  174259. /*
  174260. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  174261. * Again a triangle filter; see comments for h2v1 case, above.
  174262. *
  174263. * It is OK for us to reference the adjacent input rows because we demanded
  174264. * context from the main buffer controller (see initialization code).
  174265. */
  174266. METHODDEF(void)
  174267. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174268. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174269. {
  174270. JSAMPARRAY output_data = *output_data_ptr;
  174271. register JSAMPROW inptr0, inptr1, outptr;
  174272. #if BITS_IN_JSAMPLE == 8
  174273. register int thiscolsum, lastcolsum, nextcolsum;
  174274. #else
  174275. register INT32 thiscolsum, lastcolsum, nextcolsum;
  174276. #endif
  174277. register JDIMENSION colctr;
  174278. int inrow, outrow, v;
  174279. inrow = outrow = 0;
  174280. while (outrow < cinfo->max_v_samp_factor) {
  174281. for (v = 0; v < 2; v++) {
  174282. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  174283. inptr0 = input_data[inrow];
  174284. if (v == 0) /* next nearest is row above */
  174285. inptr1 = input_data[inrow-1];
  174286. else /* next nearest is row below */
  174287. inptr1 = input_data[inrow+1];
  174288. outptr = output_data[outrow++];
  174289. /* Special case for first column */
  174290. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174291. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174292. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  174293. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174294. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174295. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  174296. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  174297. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  174298. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  174299. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174300. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  174301. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  174302. }
  174303. /* Special case for last column */
  174304. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  174305. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  174306. }
  174307. inrow++;
  174308. }
  174309. }
  174310. /*
  174311. * Module initialization routine for upsampling.
  174312. */
  174313. GLOBAL(void)
  174314. jinit_upsampler (j_decompress_ptr cinfo)
  174315. {
  174316. my_upsample_ptr2 upsample;
  174317. int ci;
  174318. jpeg_component_info * compptr;
  174319. boolean need_buffer, do_fancy;
  174320. int h_in_group, v_in_group, h_out_group, v_out_group;
  174321. upsample = (my_upsample_ptr2)
  174322. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174323. SIZEOF(my_upsampler2));
  174324. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  174325. upsample->pub.start_pass = start_pass_upsample;
  174326. upsample->pub.upsample = sep_upsample;
  174327. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  174328. if (cinfo->CCIR601_sampling) /* this isn't supported */
  174329. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  174330. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  174331. * so don't ask for it.
  174332. */
  174333. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  174334. /* Verify we can handle the sampling factors, select per-component methods,
  174335. * and create storage as needed.
  174336. */
  174337. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174338. ci++, compptr++) {
  174339. /* Compute size of an "input group" after IDCT scaling. This many samples
  174340. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  174341. */
  174342. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  174343. cinfo->min_DCT_scaled_size;
  174344. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  174345. cinfo->min_DCT_scaled_size;
  174346. h_out_group = cinfo->max_h_samp_factor;
  174347. v_out_group = cinfo->max_v_samp_factor;
  174348. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  174349. need_buffer = TRUE;
  174350. if (! compptr->component_needed) {
  174351. /* Don't bother to upsample an uninteresting component. */
  174352. upsample->methods[ci] = noop_upsample;
  174353. need_buffer = FALSE;
  174354. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  174355. /* Fullsize components can be processed without any work. */
  174356. upsample->methods[ci] = fullsize_upsample;
  174357. need_buffer = FALSE;
  174358. } else if (h_in_group * 2 == h_out_group &&
  174359. v_in_group == v_out_group) {
  174360. /* Special cases for 2h1v upsampling */
  174361. if (do_fancy && compptr->downsampled_width > 2)
  174362. upsample->methods[ci] = h2v1_fancy_upsample;
  174363. else
  174364. upsample->methods[ci] = h2v1_upsample;
  174365. } else if (h_in_group * 2 == h_out_group &&
  174366. v_in_group * 2 == v_out_group) {
  174367. /* Special cases for 2h2v upsampling */
  174368. if (do_fancy && compptr->downsampled_width > 2) {
  174369. upsample->methods[ci] = h2v2_fancy_upsample;
  174370. upsample->pub.need_context_rows = TRUE;
  174371. } else
  174372. upsample->methods[ci] = h2v2_upsample;
  174373. } else if ((h_out_group % h_in_group) == 0 &&
  174374. (v_out_group % v_in_group) == 0) {
  174375. /* Generic integral-factors upsampling method */
  174376. upsample->methods[ci] = int_upsample;
  174377. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  174378. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  174379. } else
  174380. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  174381. if (need_buffer) {
  174382. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  174383. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174384. (JDIMENSION) jround_up((long) cinfo->output_width,
  174385. (long) cinfo->max_h_samp_factor),
  174386. (JDIMENSION) cinfo->max_v_samp_factor);
  174387. }
  174388. }
  174389. }
  174390. /*** End of inlined file: jdsample.c ***/
  174391. /*** Start of inlined file: jdtrans.c ***/
  174392. #define JPEG_INTERNALS
  174393. /* Forward declarations */
  174394. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  174395. /*
  174396. * Read the coefficient arrays from a JPEG file.
  174397. * jpeg_read_header must be completed before calling this.
  174398. *
  174399. * The entire image is read into a set of virtual coefficient-block arrays,
  174400. * one per component. The return value is a pointer to the array of
  174401. * virtual-array descriptors. These can be manipulated directly via the
  174402. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  174403. * To release the memory occupied by the virtual arrays, call
  174404. * jpeg_finish_decompress() when done with the data.
  174405. *
  174406. * An alternative usage is to simply obtain access to the coefficient arrays
  174407. * during a buffered-image-mode decompression operation. This is allowed
  174408. * after any jpeg_finish_output() call. The arrays can be accessed until
  174409. * jpeg_finish_decompress() is called. (Note that any call to the library
  174410. * may reposition the arrays, so don't rely on access_virt_barray() results
  174411. * to stay valid across library calls.)
  174412. *
  174413. * Returns NULL if suspended. This case need be checked only if
  174414. * a suspending data source is used.
  174415. */
  174416. GLOBAL(jvirt_barray_ptr *)
  174417. jpeg_read_coefficients (j_decompress_ptr cinfo)
  174418. {
  174419. if (cinfo->global_state == DSTATE_READY) {
  174420. /* First call: initialize active modules */
  174421. transdecode_master_selection(cinfo);
  174422. cinfo->global_state = DSTATE_RDCOEFS;
  174423. }
  174424. if (cinfo->global_state == DSTATE_RDCOEFS) {
  174425. /* Absorb whole file into the coef buffer */
  174426. for (;;) {
  174427. int retcode;
  174428. /* Call progress monitor hook if present */
  174429. if (cinfo->progress != NULL)
  174430. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  174431. /* Absorb some more input */
  174432. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  174433. if (retcode == JPEG_SUSPENDED)
  174434. return NULL;
  174435. if (retcode == JPEG_REACHED_EOI)
  174436. break;
  174437. /* Advance progress counter if appropriate */
  174438. if (cinfo->progress != NULL &&
  174439. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  174440. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  174441. /* startup underestimated number of scans; ratchet up one scan */
  174442. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  174443. }
  174444. }
  174445. }
  174446. /* Set state so that jpeg_finish_decompress does the right thing */
  174447. cinfo->global_state = DSTATE_STOPPING;
  174448. }
  174449. /* At this point we should be in state DSTATE_STOPPING if being used
  174450. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  174451. * to the coefficients during a full buffered-image-mode decompression.
  174452. */
  174453. if ((cinfo->global_state == DSTATE_STOPPING ||
  174454. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  174455. return cinfo->coef->coef_arrays;
  174456. }
  174457. /* Oops, improper usage */
  174458. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  174459. return NULL; /* keep compiler happy */
  174460. }
  174461. /*
  174462. * Master selection of decompression modules for transcoding.
  174463. * This substitutes for jdmaster.c's initialization of the full decompressor.
  174464. */
  174465. LOCAL(void)
  174466. transdecode_master_selection (j_decompress_ptr cinfo)
  174467. {
  174468. /* This is effectively a buffered-image operation. */
  174469. cinfo->buffered_image = TRUE;
  174470. /* Entropy decoding: either Huffman or arithmetic coding. */
  174471. if (cinfo->arith_code) {
  174472. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  174473. } else {
  174474. if (cinfo->progressive_mode) {
  174475. #ifdef D_PROGRESSIVE_SUPPORTED
  174476. jinit_phuff_decoder(cinfo);
  174477. #else
  174478. ERREXIT(cinfo, JERR_NOT_COMPILED);
  174479. #endif
  174480. } else
  174481. jinit_huff_decoder(cinfo);
  174482. }
  174483. /* Always get a full-image coefficient buffer. */
  174484. jinit_d_coef_controller(cinfo, TRUE);
  174485. /* We can now tell the memory manager to allocate virtual arrays. */
  174486. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  174487. /* Initialize input side of decompressor to consume first scan. */
  174488. (*cinfo->inputctl->start_input_pass) (cinfo);
  174489. /* Initialize progress monitoring. */
  174490. if (cinfo->progress != NULL) {
  174491. int nscans;
  174492. /* Estimate number of scans to set pass_limit. */
  174493. if (cinfo->progressive_mode) {
  174494. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  174495. nscans = 2 + 3 * cinfo->num_components;
  174496. } else if (cinfo->inputctl->has_multiple_scans) {
  174497. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  174498. nscans = cinfo->num_components;
  174499. } else {
  174500. nscans = 1;
  174501. }
  174502. cinfo->progress->pass_counter = 0L;
  174503. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  174504. cinfo->progress->completed_passes = 0;
  174505. cinfo->progress->total_passes = 1;
  174506. }
  174507. }
  174508. /*** End of inlined file: jdtrans.c ***/
  174509. /*** Start of inlined file: jfdctflt.c ***/
  174510. #define JPEG_INTERNALS
  174511. #ifdef DCT_FLOAT_SUPPORTED
  174512. /*
  174513. * This module is specialized to the case DCTSIZE = 8.
  174514. */
  174515. #if DCTSIZE != 8
  174516. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174517. #endif
  174518. /*
  174519. * Perform the forward DCT on one block of samples.
  174520. */
  174521. GLOBAL(void)
  174522. jpeg_fdct_float (FAST_FLOAT * data)
  174523. {
  174524. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174525. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174526. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  174527. FAST_FLOAT *dataptr;
  174528. int ctr;
  174529. /* Pass 1: process rows. */
  174530. dataptr = data;
  174531. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174532. tmp0 = dataptr[0] + dataptr[7];
  174533. tmp7 = dataptr[0] - dataptr[7];
  174534. tmp1 = dataptr[1] + dataptr[6];
  174535. tmp6 = dataptr[1] - dataptr[6];
  174536. tmp2 = dataptr[2] + dataptr[5];
  174537. tmp5 = dataptr[2] - dataptr[5];
  174538. tmp3 = dataptr[3] + dataptr[4];
  174539. tmp4 = dataptr[3] - dataptr[4];
  174540. /* Even part */
  174541. tmp10 = tmp0 + tmp3; /* phase 2 */
  174542. tmp13 = tmp0 - tmp3;
  174543. tmp11 = tmp1 + tmp2;
  174544. tmp12 = tmp1 - tmp2;
  174545. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174546. dataptr[4] = tmp10 - tmp11;
  174547. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174548. dataptr[2] = tmp13 + z1; /* phase 5 */
  174549. dataptr[6] = tmp13 - z1;
  174550. /* Odd part */
  174551. tmp10 = tmp4 + tmp5; /* phase 2 */
  174552. tmp11 = tmp5 + tmp6;
  174553. tmp12 = tmp6 + tmp7;
  174554. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174555. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174556. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174557. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174558. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174559. z11 = tmp7 + z3; /* phase 5 */
  174560. z13 = tmp7 - z3;
  174561. dataptr[5] = z13 + z2; /* phase 6 */
  174562. dataptr[3] = z13 - z2;
  174563. dataptr[1] = z11 + z4;
  174564. dataptr[7] = z11 - z4;
  174565. dataptr += DCTSIZE; /* advance pointer to next row */
  174566. }
  174567. /* Pass 2: process columns. */
  174568. dataptr = data;
  174569. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174570. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174571. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174572. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174573. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174574. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174575. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174576. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174577. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174578. /* Even part */
  174579. tmp10 = tmp0 + tmp3; /* phase 2 */
  174580. tmp13 = tmp0 - tmp3;
  174581. tmp11 = tmp1 + tmp2;
  174582. tmp12 = tmp1 - tmp2;
  174583. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174584. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174585. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  174586. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174587. dataptr[DCTSIZE*6] = tmp13 - z1;
  174588. /* Odd part */
  174589. tmp10 = tmp4 + tmp5; /* phase 2 */
  174590. tmp11 = tmp5 + tmp6;
  174591. tmp12 = tmp6 + tmp7;
  174592. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174593. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  174594. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  174595. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  174596. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  174597. z11 = tmp7 + z3; /* phase 5 */
  174598. z13 = tmp7 - z3;
  174599. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174600. dataptr[DCTSIZE*3] = z13 - z2;
  174601. dataptr[DCTSIZE*1] = z11 + z4;
  174602. dataptr[DCTSIZE*7] = z11 - z4;
  174603. dataptr++; /* advance pointer to next column */
  174604. }
  174605. }
  174606. #endif /* DCT_FLOAT_SUPPORTED */
  174607. /*** End of inlined file: jfdctflt.c ***/
  174608. /*** Start of inlined file: jfdctint.c ***/
  174609. #define JPEG_INTERNALS
  174610. #ifdef DCT_ISLOW_SUPPORTED
  174611. /*
  174612. * This module is specialized to the case DCTSIZE = 8.
  174613. */
  174614. #if DCTSIZE != 8
  174615. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174616. #endif
  174617. /*
  174618. * The poop on this scaling stuff is as follows:
  174619. *
  174620. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  174621. * larger than the true DCT outputs. The final outputs are therefore
  174622. * a factor of N larger than desired; since N=8 this can be cured by
  174623. * a simple right shift at the end of the algorithm. The advantage of
  174624. * this arrangement is that we save two multiplications per 1-D DCT,
  174625. * because the y0 and y4 outputs need not be divided by sqrt(N).
  174626. * In the IJG code, this factor of 8 is removed by the quantization step
  174627. * (in jcdctmgr.c), NOT in this module.
  174628. *
  174629. * We have to do addition and subtraction of the integer inputs, which
  174630. * is no problem, and multiplication by fractional constants, which is
  174631. * a problem to do in integer arithmetic. We multiply all the constants
  174632. * by CONST_SCALE and convert them to integer constants (thus retaining
  174633. * CONST_BITS bits of precision in the constants). After doing a
  174634. * multiplication we have to divide the product by CONST_SCALE, with proper
  174635. * rounding, to produce the correct output. This division can be done
  174636. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  174637. * as long as possible so that partial sums can be added together with
  174638. * full fractional precision.
  174639. *
  174640. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  174641. * they are represented to better-than-integral precision. These outputs
  174642. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  174643. * with the recommended scaling. (For 12-bit sample data, the intermediate
  174644. * array is INT32 anyway.)
  174645. *
  174646. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  174647. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  174648. * shows that the values given below are the most effective.
  174649. */
  174650. #if BITS_IN_JSAMPLE == 8
  174651. #define CONST_BITS 13
  174652. #define PASS1_BITS 2
  174653. #else
  174654. #define CONST_BITS 13
  174655. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  174656. #endif
  174657. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174658. * causing a lot of useless floating-point operations at run time.
  174659. * To get around this we use the following pre-calculated constants.
  174660. * If you change CONST_BITS you may want to add appropriate values.
  174661. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174662. */
  174663. #if CONST_BITS == 13
  174664. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  174665. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  174666. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  174667. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  174668. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  174669. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  174670. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  174671. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  174672. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  174673. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  174674. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  174675. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  174676. #else
  174677. #define FIX_0_298631336 FIX(0.298631336)
  174678. #define FIX_0_390180644 FIX(0.390180644)
  174679. #define FIX_0_541196100 FIX(0.541196100)
  174680. #define FIX_0_765366865 FIX(0.765366865)
  174681. #define FIX_0_899976223 FIX(0.899976223)
  174682. #define FIX_1_175875602 FIX(1.175875602)
  174683. #define FIX_1_501321110 FIX(1.501321110)
  174684. #define FIX_1_847759065 FIX(1.847759065)
  174685. #define FIX_1_961570560 FIX(1.961570560)
  174686. #define FIX_2_053119869 FIX(2.053119869)
  174687. #define FIX_2_562915447 FIX(2.562915447)
  174688. #define FIX_3_072711026 FIX(3.072711026)
  174689. #endif
  174690. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  174691. * For 8-bit samples with the recommended scaling, all the variable
  174692. * and constant values involved are no more than 16 bits wide, so a
  174693. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  174694. * For 12-bit samples, a full 32-bit multiplication will be needed.
  174695. */
  174696. #if BITS_IN_JSAMPLE == 8
  174697. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  174698. #else
  174699. #define MULTIPLY(var,const) ((var) * (const))
  174700. #endif
  174701. /*
  174702. * Perform the forward DCT on one block of samples.
  174703. */
  174704. GLOBAL(void)
  174705. jpeg_fdct_islow (DCTELEM * data)
  174706. {
  174707. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174708. INT32 tmp10, tmp11, tmp12, tmp13;
  174709. INT32 z1, z2, z3, z4, z5;
  174710. DCTELEM *dataptr;
  174711. int ctr;
  174712. SHIFT_TEMPS
  174713. /* Pass 1: process rows. */
  174714. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  174715. /* furthermore, we scale the results by 2**PASS1_BITS. */
  174716. dataptr = data;
  174717. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174718. tmp0 = dataptr[0] + dataptr[7];
  174719. tmp7 = dataptr[0] - dataptr[7];
  174720. tmp1 = dataptr[1] + dataptr[6];
  174721. tmp6 = dataptr[1] - dataptr[6];
  174722. tmp2 = dataptr[2] + dataptr[5];
  174723. tmp5 = dataptr[2] - dataptr[5];
  174724. tmp3 = dataptr[3] + dataptr[4];
  174725. tmp4 = dataptr[3] - dataptr[4];
  174726. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174727. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174728. */
  174729. tmp10 = tmp0 + tmp3;
  174730. tmp13 = tmp0 - tmp3;
  174731. tmp11 = tmp1 + tmp2;
  174732. tmp12 = tmp1 - tmp2;
  174733. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  174734. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  174735. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174736. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174737. CONST_BITS-PASS1_BITS);
  174738. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174739. CONST_BITS-PASS1_BITS);
  174740. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174741. * cK represents cos(K*pi/16).
  174742. * i0..i3 in the paper are tmp4..tmp7 here.
  174743. */
  174744. z1 = tmp4 + tmp7;
  174745. z2 = tmp5 + tmp6;
  174746. z3 = tmp4 + tmp6;
  174747. z4 = tmp5 + tmp7;
  174748. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174749. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174750. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174751. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174752. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174753. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174754. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174755. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174756. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174757. z3 += z5;
  174758. z4 += z5;
  174759. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  174760. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  174761. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  174762. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  174763. dataptr += DCTSIZE; /* advance pointer to next row */
  174764. }
  174765. /* Pass 2: process columns.
  174766. * We remove the PASS1_BITS scaling, but leave the results scaled up
  174767. * by an overall factor of 8.
  174768. */
  174769. dataptr = data;
  174770. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174771. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174772. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174773. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174774. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174775. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174776. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174777. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174778. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174779. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  174780. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  174781. */
  174782. tmp10 = tmp0 + tmp3;
  174783. tmp13 = tmp0 - tmp3;
  174784. tmp11 = tmp1 + tmp2;
  174785. tmp12 = tmp1 - tmp2;
  174786. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  174787. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  174788. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  174789. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  174790. CONST_BITS+PASS1_BITS);
  174791. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  174792. CONST_BITS+PASS1_BITS);
  174793. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  174794. * cK represents cos(K*pi/16).
  174795. * i0..i3 in the paper are tmp4..tmp7 here.
  174796. */
  174797. z1 = tmp4 + tmp7;
  174798. z2 = tmp5 + tmp6;
  174799. z3 = tmp4 + tmp6;
  174800. z4 = tmp5 + tmp7;
  174801. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  174802. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  174803. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  174804. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  174805. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  174806. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  174807. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  174808. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  174809. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  174810. z3 += z5;
  174811. z4 += z5;
  174812. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  174813. CONST_BITS+PASS1_BITS);
  174814. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  174815. CONST_BITS+PASS1_BITS);
  174816. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  174817. CONST_BITS+PASS1_BITS);
  174818. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  174819. CONST_BITS+PASS1_BITS);
  174820. dataptr++; /* advance pointer to next column */
  174821. }
  174822. }
  174823. #endif /* DCT_ISLOW_SUPPORTED */
  174824. /*** End of inlined file: jfdctint.c ***/
  174825. #undef CONST_BITS
  174826. #undef MULTIPLY
  174827. #undef FIX_0_541196100
  174828. /*** Start of inlined file: jfdctfst.c ***/
  174829. #define JPEG_INTERNALS
  174830. #ifdef DCT_IFAST_SUPPORTED
  174831. /*
  174832. * This module is specialized to the case DCTSIZE = 8.
  174833. */
  174834. #if DCTSIZE != 8
  174835. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174836. #endif
  174837. /* Scaling decisions are generally the same as in the LL&M algorithm;
  174838. * see jfdctint.c for more details. However, we choose to descale
  174839. * (right shift) multiplication products as soon as they are formed,
  174840. * rather than carrying additional fractional bits into subsequent additions.
  174841. * This compromises accuracy slightly, but it lets us save a few shifts.
  174842. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  174843. * everywhere except in the multiplications proper; this saves a good deal
  174844. * of work on 16-bit-int machines.
  174845. *
  174846. * Again to save a few shifts, the intermediate results between pass 1 and
  174847. * pass 2 are not upscaled, but are represented only to integral precision.
  174848. *
  174849. * A final compromise is to represent the multiplicative constants to only
  174850. * 8 fractional bits, rather than 13. This saves some shifting work on some
  174851. * machines, and may also reduce the cost of multiplication (since there
  174852. * are fewer one-bits in the constants).
  174853. */
  174854. #define CONST_BITS 8
  174855. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  174856. * causing a lot of useless floating-point operations at run time.
  174857. * To get around this we use the following pre-calculated constants.
  174858. * If you change CONST_BITS you may want to add appropriate values.
  174859. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  174860. */
  174861. #if CONST_BITS == 8
  174862. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  174863. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  174864. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  174865. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  174866. #else
  174867. #define FIX_0_382683433 FIX(0.382683433)
  174868. #define FIX_0_541196100 FIX(0.541196100)
  174869. #define FIX_0_707106781 FIX(0.707106781)
  174870. #define FIX_1_306562965 FIX(1.306562965)
  174871. #endif
  174872. /* We can gain a little more speed, with a further compromise in accuracy,
  174873. * by omitting the addition in a descaling shift. This yields an incorrectly
  174874. * rounded result half the time...
  174875. */
  174876. #ifndef USE_ACCURATE_ROUNDING
  174877. #undef DESCALE
  174878. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  174879. #endif
  174880. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  174881. * descale to yield a DCTELEM result.
  174882. */
  174883. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  174884. /*
  174885. * Perform the forward DCT on one block of samples.
  174886. */
  174887. GLOBAL(void)
  174888. jpeg_fdct_ifast (DCTELEM * data)
  174889. {
  174890. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174891. DCTELEM tmp10, tmp11, tmp12, tmp13;
  174892. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  174893. DCTELEM *dataptr;
  174894. int ctr;
  174895. SHIFT_TEMPS
  174896. /* Pass 1: process rows. */
  174897. dataptr = data;
  174898. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174899. tmp0 = dataptr[0] + dataptr[7];
  174900. tmp7 = dataptr[0] - dataptr[7];
  174901. tmp1 = dataptr[1] + dataptr[6];
  174902. tmp6 = dataptr[1] - dataptr[6];
  174903. tmp2 = dataptr[2] + dataptr[5];
  174904. tmp5 = dataptr[2] - dataptr[5];
  174905. tmp3 = dataptr[3] + dataptr[4];
  174906. tmp4 = dataptr[3] - dataptr[4];
  174907. /* Even part */
  174908. tmp10 = tmp0 + tmp3; /* phase 2 */
  174909. tmp13 = tmp0 - tmp3;
  174910. tmp11 = tmp1 + tmp2;
  174911. tmp12 = tmp1 - tmp2;
  174912. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  174913. dataptr[4] = tmp10 - tmp11;
  174914. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174915. dataptr[2] = tmp13 + z1; /* phase 5 */
  174916. dataptr[6] = tmp13 - z1;
  174917. /* Odd part */
  174918. tmp10 = tmp4 + tmp5; /* phase 2 */
  174919. tmp11 = tmp5 + tmp6;
  174920. tmp12 = tmp6 + tmp7;
  174921. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174922. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174923. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174924. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174925. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174926. z11 = tmp7 + z3; /* phase 5 */
  174927. z13 = tmp7 - z3;
  174928. dataptr[5] = z13 + z2; /* phase 6 */
  174929. dataptr[3] = z13 - z2;
  174930. dataptr[1] = z11 + z4;
  174931. dataptr[7] = z11 - z4;
  174932. dataptr += DCTSIZE; /* advance pointer to next row */
  174933. }
  174934. /* Pass 2: process columns. */
  174935. dataptr = data;
  174936. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  174937. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  174938. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  174939. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  174940. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  174941. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  174942. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  174943. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  174944. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  174945. /* Even part */
  174946. tmp10 = tmp0 + tmp3; /* phase 2 */
  174947. tmp13 = tmp0 - tmp3;
  174948. tmp11 = tmp1 + tmp2;
  174949. tmp12 = tmp1 - tmp2;
  174950. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  174951. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  174952. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  174953. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  174954. dataptr[DCTSIZE*6] = tmp13 - z1;
  174955. /* Odd part */
  174956. tmp10 = tmp4 + tmp5; /* phase 2 */
  174957. tmp11 = tmp5 + tmp6;
  174958. tmp12 = tmp6 + tmp7;
  174959. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  174960. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  174961. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  174962. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  174963. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  174964. z11 = tmp7 + z3; /* phase 5 */
  174965. z13 = tmp7 - z3;
  174966. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  174967. dataptr[DCTSIZE*3] = z13 - z2;
  174968. dataptr[DCTSIZE*1] = z11 + z4;
  174969. dataptr[DCTSIZE*7] = z11 - z4;
  174970. dataptr++; /* advance pointer to next column */
  174971. }
  174972. }
  174973. #endif /* DCT_IFAST_SUPPORTED */
  174974. /*** End of inlined file: jfdctfst.c ***/
  174975. #undef FIX_0_541196100
  174976. /*** Start of inlined file: jidctflt.c ***/
  174977. #define JPEG_INTERNALS
  174978. #ifdef DCT_FLOAT_SUPPORTED
  174979. /*
  174980. * This module is specialized to the case DCTSIZE = 8.
  174981. */
  174982. #if DCTSIZE != 8
  174983. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  174984. #endif
  174985. /* Dequantize a coefficient by multiplying it by the multiplier-table
  174986. * entry; produce a float result.
  174987. */
  174988. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  174989. /*
  174990. * Perform dequantization and inverse DCT on one block of coefficients.
  174991. */
  174992. GLOBAL(void)
  174993. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174994. JCOEFPTR coef_block,
  174995. JSAMPARRAY output_buf, JDIMENSION output_col)
  174996. {
  174997. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  174998. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  174999. FAST_FLOAT z5, z10, z11, z12, z13;
  175000. JCOEFPTR inptr;
  175001. FLOAT_MULT_TYPE * quantptr;
  175002. FAST_FLOAT * wsptr;
  175003. JSAMPROW outptr;
  175004. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175005. int ctr;
  175006. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  175007. SHIFT_TEMPS
  175008. /* Pass 1: process columns from input, store into work array. */
  175009. inptr = coef_block;
  175010. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  175011. wsptr = workspace;
  175012. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175013. /* Due to quantization, we will usually find that many of the input
  175014. * coefficients are zero, especially the AC terms. We can exploit this
  175015. * by short-circuiting the IDCT calculation for any column in which all
  175016. * the AC terms are zero. In that case each output is equal to the
  175017. * DC coefficient (with scale factor as needed).
  175018. * With typical images and quantization tables, half or more of the
  175019. * column DCT calculations can be simplified this way.
  175020. */
  175021. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175022. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175023. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175024. inptr[DCTSIZE*7] == 0) {
  175025. /* AC terms all zero */
  175026. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175027. wsptr[DCTSIZE*0] = dcval;
  175028. wsptr[DCTSIZE*1] = dcval;
  175029. wsptr[DCTSIZE*2] = dcval;
  175030. wsptr[DCTSIZE*3] = dcval;
  175031. wsptr[DCTSIZE*4] = dcval;
  175032. wsptr[DCTSIZE*5] = dcval;
  175033. wsptr[DCTSIZE*6] = dcval;
  175034. wsptr[DCTSIZE*7] = dcval;
  175035. inptr++; /* advance pointers to next column */
  175036. quantptr++;
  175037. wsptr++;
  175038. continue;
  175039. }
  175040. /* Even part */
  175041. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175042. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175043. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175044. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175045. tmp10 = tmp0 + tmp2; /* phase 3 */
  175046. tmp11 = tmp0 - tmp2;
  175047. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175048. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175049. tmp0 = tmp10 + tmp13; /* phase 2 */
  175050. tmp3 = tmp10 - tmp13;
  175051. tmp1 = tmp11 + tmp12;
  175052. tmp2 = tmp11 - tmp12;
  175053. /* Odd part */
  175054. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175055. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175056. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175057. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175058. z13 = tmp6 + tmp5; /* phase 6 */
  175059. z10 = tmp6 - tmp5;
  175060. z11 = tmp4 + tmp7;
  175061. z12 = tmp4 - tmp7;
  175062. tmp7 = z11 + z13; /* phase 5 */
  175063. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175064. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175065. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175066. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175067. tmp6 = tmp12 - tmp7; /* phase 2 */
  175068. tmp5 = tmp11 - tmp6;
  175069. tmp4 = tmp10 + tmp5;
  175070. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175071. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175072. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175073. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175074. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175075. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175076. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175077. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175078. inptr++; /* advance pointers to next column */
  175079. quantptr++;
  175080. wsptr++;
  175081. }
  175082. /* Pass 2: process rows from work array, store into output array. */
  175083. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175084. wsptr = workspace;
  175085. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175086. outptr = output_buf[ctr] + output_col;
  175087. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175088. * However, the column calculation has created many nonzero AC terms, so
  175089. * the simplification applies less often (typically 5% to 10% of the time).
  175090. * And testing floats for zero is relatively expensive, so we don't bother.
  175091. */
  175092. /* Even part */
  175093. tmp10 = wsptr[0] + wsptr[4];
  175094. tmp11 = wsptr[0] - wsptr[4];
  175095. tmp13 = wsptr[2] + wsptr[6];
  175096. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175097. tmp0 = tmp10 + tmp13;
  175098. tmp3 = tmp10 - tmp13;
  175099. tmp1 = tmp11 + tmp12;
  175100. tmp2 = tmp11 - tmp12;
  175101. /* Odd part */
  175102. z13 = wsptr[5] + wsptr[3];
  175103. z10 = wsptr[5] - wsptr[3];
  175104. z11 = wsptr[1] + wsptr[7];
  175105. z12 = wsptr[1] - wsptr[7];
  175106. tmp7 = z11 + z13;
  175107. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175108. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175109. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175110. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175111. tmp6 = tmp12 - tmp7;
  175112. tmp5 = tmp11 - tmp6;
  175113. tmp4 = tmp10 + tmp5;
  175114. /* Final output stage: scale down by a factor of 8 and range-limit */
  175115. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175116. & RANGE_MASK];
  175117. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175118. & RANGE_MASK];
  175119. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175120. & RANGE_MASK];
  175121. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175122. & RANGE_MASK];
  175123. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175124. & RANGE_MASK];
  175125. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175126. & RANGE_MASK];
  175127. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175128. & RANGE_MASK];
  175129. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175130. & RANGE_MASK];
  175131. wsptr += DCTSIZE; /* advance pointer to next row */
  175132. }
  175133. }
  175134. #endif /* DCT_FLOAT_SUPPORTED */
  175135. /*** End of inlined file: jidctflt.c ***/
  175136. #undef CONST_BITS
  175137. #undef FIX_1_847759065
  175138. #undef MULTIPLY
  175139. #undef DEQUANTIZE
  175140. #undef DESCALE
  175141. /*** Start of inlined file: jidctfst.c ***/
  175142. #define JPEG_INTERNALS
  175143. #ifdef DCT_IFAST_SUPPORTED
  175144. /*
  175145. * This module is specialized to the case DCTSIZE = 8.
  175146. */
  175147. #if DCTSIZE != 8
  175148. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175149. #endif
  175150. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175151. * see jidctint.c for more details. However, we choose to descale
  175152. * (right shift) multiplication products as soon as they are formed,
  175153. * rather than carrying additional fractional bits into subsequent additions.
  175154. * This compromises accuracy slightly, but it lets us save a few shifts.
  175155. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175156. * everywhere except in the multiplications proper; this saves a good deal
  175157. * of work on 16-bit-int machines.
  175158. *
  175159. * The dequantized coefficients are not integers because the AA&N scaling
  175160. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175161. * so that the first and second IDCT rounds have the same input scaling.
  175162. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175163. * avoid a descaling shift; this compromises accuracy rather drastically
  175164. * for small quantization table entries, but it saves a lot of shifts.
  175165. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175166. * so we use a much larger scaling factor to preserve accuracy.
  175167. *
  175168. * A final compromise is to represent the multiplicative constants to only
  175169. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175170. * machines, and may also reduce the cost of multiplication (since there
  175171. * are fewer one-bits in the constants).
  175172. */
  175173. #if BITS_IN_JSAMPLE == 8
  175174. #define CONST_BITS 8
  175175. #define PASS1_BITS 2
  175176. #else
  175177. #define CONST_BITS 8
  175178. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175179. #endif
  175180. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175181. * causing a lot of useless floating-point operations at run time.
  175182. * To get around this we use the following pre-calculated constants.
  175183. * If you change CONST_BITS you may want to add appropriate values.
  175184. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175185. */
  175186. #if CONST_BITS == 8
  175187. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175188. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175189. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175190. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175191. #else
  175192. #define FIX_1_082392200 FIX(1.082392200)
  175193. #define FIX_1_414213562 FIX(1.414213562)
  175194. #define FIX_1_847759065 FIX(1.847759065)
  175195. #define FIX_2_613125930 FIX(2.613125930)
  175196. #endif
  175197. /* We can gain a little more speed, with a further compromise in accuracy,
  175198. * by omitting the addition in a descaling shift. This yields an incorrectly
  175199. * rounded result half the time...
  175200. */
  175201. #ifndef USE_ACCURATE_ROUNDING
  175202. #undef DESCALE
  175203. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175204. #endif
  175205. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175206. * descale to yield a DCTELEM result.
  175207. */
  175208. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175209. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175210. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175211. * multiplication will do. For 12-bit data, the multiplier table is
  175212. * declared INT32, so a 32-bit multiply will be used.
  175213. */
  175214. #if BITS_IN_JSAMPLE == 8
  175215. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175216. #else
  175217. #define DEQUANTIZE(coef,quantval) \
  175218. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175219. #endif
  175220. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175221. * We assume that int right shift is unsigned if INT32 right shift is.
  175222. */
  175223. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175224. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175225. #if BITS_IN_JSAMPLE == 8
  175226. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175227. #else
  175228. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  175229. #endif
  175230. #define IRIGHT_SHIFT(x,shft) \
  175231. ((ishift_temp = (x)) < 0 ? \
  175232. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  175233. (ishift_temp >> (shft)))
  175234. #else
  175235. #define ISHIFT_TEMPS
  175236. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  175237. #endif
  175238. #ifdef USE_ACCURATE_ROUNDING
  175239. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  175240. #else
  175241. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  175242. #endif
  175243. /*
  175244. * Perform dequantization and inverse DCT on one block of coefficients.
  175245. */
  175246. GLOBAL(void)
  175247. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175248. JCOEFPTR coef_block,
  175249. JSAMPARRAY output_buf, JDIMENSION output_col)
  175250. {
  175251. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175252. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175253. DCTELEM z5, z10, z11, z12, z13;
  175254. JCOEFPTR inptr;
  175255. IFAST_MULT_TYPE * quantptr;
  175256. int * wsptr;
  175257. JSAMPROW outptr;
  175258. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175259. int ctr;
  175260. int workspace[DCTSIZE2]; /* buffers data between passes */
  175261. SHIFT_TEMPS /* for DESCALE */
  175262. ISHIFT_TEMPS /* for IDESCALE */
  175263. /* Pass 1: process columns from input, store into work array. */
  175264. inptr = coef_block;
  175265. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  175266. wsptr = workspace;
  175267. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175268. /* Due to quantization, we will usually find that many of the input
  175269. * coefficients are zero, especially the AC terms. We can exploit this
  175270. * by short-circuiting the IDCT calculation for any column in which all
  175271. * the AC terms are zero. In that case each output is equal to the
  175272. * DC coefficient (with scale factor as needed).
  175273. * With typical images and quantization tables, half or more of the
  175274. * column DCT calculations can be simplified this way.
  175275. */
  175276. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175277. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175278. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175279. inptr[DCTSIZE*7] == 0) {
  175280. /* AC terms all zero */
  175281. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175282. wsptr[DCTSIZE*0] = dcval;
  175283. wsptr[DCTSIZE*1] = dcval;
  175284. wsptr[DCTSIZE*2] = dcval;
  175285. wsptr[DCTSIZE*3] = dcval;
  175286. wsptr[DCTSIZE*4] = dcval;
  175287. wsptr[DCTSIZE*5] = dcval;
  175288. wsptr[DCTSIZE*6] = dcval;
  175289. wsptr[DCTSIZE*7] = dcval;
  175290. inptr++; /* advance pointers to next column */
  175291. quantptr++;
  175292. wsptr++;
  175293. continue;
  175294. }
  175295. /* Even part */
  175296. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175297. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175298. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175299. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175300. tmp10 = tmp0 + tmp2; /* phase 3 */
  175301. tmp11 = tmp0 - tmp2;
  175302. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175303. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  175304. tmp0 = tmp10 + tmp13; /* phase 2 */
  175305. tmp3 = tmp10 - tmp13;
  175306. tmp1 = tmp11 + tmp12;
  175307. tmp2 = tmp11 - tmp12;
  175308. /* Odd part */
  175309. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175310. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175311. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175312. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175313. z13 = tmp6 + tmp5; /* phase 6 */
  175314. z10 = tmp6 - tmp5;
  175315. z11 = tmp4 + tmp7;
  175316. z12 = tmp4 - tmp7;
  175317. tmp7 = z11 + z13; /* phase 5 */
  175318. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175319. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175320. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175321. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175322. tmp6 = tmp12 - tmp7; /* phase 2 */
  175323. tmp5 = tmp11 - tmp6;
  175324. tmp4 = tmp10 + tmp5;
  175325. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  175326. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  175327. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  175328. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  175329. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  175330. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  175331. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  175332. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  175333. inptr++; /* advance pointers to next column */
  175334. quantptr++;
  175335. wsptr++;
  175336. }
  175337. /* Pass 2: process rows from work array, store into output array. */
  175338. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175339. /* and also undo the PASS1_BITS scaling. */
  175340. wsptr = workspace;
  175341. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175342. outptr = output_buf[ctr] + output_col;
  175343. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175344. * However, the column calculation has created many nonzero AC terms, so
  175345. * the simplification applies less often (typically 5% to 10% of the time).
  175346. * On machines with very fast multiplication, it's possible that the
  175347. * test takes more time than it's worth. In that case this section
  175348. * may be commented out.
  175349. */
  175350. #ifndef NO_ZERO_ROW_TEST
  175351. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175352. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175353. /* AC terms all zero */
  175354. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  175355. & RANGE_MASK];
  175356. outptr[0] = dcval;
  175357. outptr[1] = dcval;
  175358. outptr[2] = dcval;
  175359. outptr[3] = dcval;
  175360. outptr[4] = dcval;
  175361. outptr[5] = dcval;
  175362. outptr[6] = dcval;
  175363. outptr[7] = dcval;
  175364. wsptr += DCTSIZE; /* advance pointer to next row */
  175365. continue;
  175366. }
  175367. #endif
  175368. /* Even part */
  175369. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  175370. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  175371. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  175372. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  175373. - tmp13;
  175374. tmp0 = tmp10 + tmp13;
  175375. tmp3 = tmp10 - tmp13;
  175376. tmp1 = tmp11 + tmp12;
  175377. tmp2 = tmp11 - tmp12;
  175378. /* Odd part */
  175379. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  175380. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  175381. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  175382. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  175383. tmp7 = z11 + z13; /* phase 5 */
  175384. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  175385. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  175386. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  175387. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  175388. tmp6 = tmp12 - tmp7; /* phase 2 */
  175389. tmp5 = tmp11 - tmp6;
  175390. tmp4 = tmp10 + tmp5;
  175391. /* Final output stage: scale down by a factor of 8 and range-limit */
  175392. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  175393. & RANGE_MASK];
  175394. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  175395. & RANGE_MASK];
  175396. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  175397. & RANGE_MASK];
  175398. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  175399. & RANGE_MASK];
  175400. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  175401. & RANGE_MASK];
  175402. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  175403. & RANGE_MASK];
  175404. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  175405. & RANGE_MASK];
  175406. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  175407. & RANGE_MASK];
  175408. wsptr += DCTSIZE; /* advance pointer to next row */
  175409. }
  175410. }
  175411. #endif /* DCT_IFAST_SUPPORTED */
  175412. /*** End of inlined file: jidctfst.c ***/
  175413. #undef CONST_BITS
  175414. #undef FIX_1_847759065
  175415. #undef MULTIPLY
  175416. #undef DEQUANTIZE
  175417. /*** Start of inlined file: jidctint.c ***/
  175418. #define JPEG_INTERNALS
  175419. #ifdef DCT_ISLOW_SUPPORTED
  175420. /*
  175421. * This module is specialized to the case DCTSIZE = 8.
  175422. */
  175423. #if DCTSIZE != 8
  175424. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175425. #endif
  175426. /*
  175427. * The poop on this scaling stuff is as follows:
  175428. *
  175429. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  175430. * larger than the true IDCT outputs. The final outputs are therefore
  175431. * a factor of N larger than desired; since N=8 this can be cured by
  175432. * a simple right shift at the end of the algorithm. The advantage of
  175433. * this arrangement is that we save two multiplications per 1-D IDCT,
  175434. * because the y0 and y4 inputs need not be divided by sqrt(N).
  175435. *
  175436. * We have to do addition and subtraction of the integer inputs, which
  175437. * is no problem, and multiplication by fractional constants, which is
  175438. * a problem to do in integer arithmetic. We multiply all the constants
  175439. * by CONST_SCALE and convert them to integer constants (thus retaining
  175440. * CONST_BITS bits of precision in the constants). After doing a
  175441. * multiplication we have to divide the product by CONST_SCALE, with proper
  175442. * rounding, to produce the correct output. This division can be done
  175443. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175444. * as long as possible so that partial sums can be added together with
  175445. * full fractional precision.
  175446. *
  175447. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175448. * they are represented to better-than-integral precision. These outputs
  175449. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175450. * with the recommended scaling. (To scale up 12-bit sample data further, an
  175451. * intermediate INT32 array would be needed.)
  175452. *
  175453. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175454. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175455. * shows that the values given below are the most effective.
  175456. */
  175457. #if BITS_IN_JSAMPLE == 8
  175458. #define CONST_BITS 13
  175459. #define PASS1_BITS 2
  175460. #else
  175461. #define CONST_BITS 13
  175462. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175463. #endif
  175464. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175465. * causing a lot of useless floating-point operations at run time.
  175466. * To get around this we use the following pre-calculated constants.
  175467. * If you change CONST_BITS you may want to add appropriate values.
  175468. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175469. */
  175470. #if CONST_BITS == 13
  175471. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175472. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175473. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175474. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175475. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175476. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175477. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175478. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175479. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175480. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175481. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175482. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175483. #else
  175484. #define FIX_0_298631336 FIX(0.298631336)
  175485. #define FIX_0_390180644 FIX(0.390180644)
  175486. #define FIX_0_541196100 FIX(0.541196100)
  175487. #define FIX_0_765366865 FIX(0.765366865)
  175488. #define FIX_0_899976223 FIX(0.899976223)
  175489. #define FIX_1_175875602 FIX(1.175875602)
  175490. #define FIX_1_501321110 FIX(1.501321110)
  175491. #define FIX_1_847759065 FIX(1.847759065)
  175492. #define FIX_1_961570560 FIX(1.961570560)
  175493. #define FIX_2_053119869 FIX(2.053119869)
  175494. #define FIX_2_562915447 FIX(2.562915447)
  175495. #define FIX_3_072711026 FIX(3.072711026)
  175496. #endif
  175497. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175498. * For 8-bit samples with the recommended scaling, all the variable
  175499. * and constant values involved are no more than 16 bits wide, so a
  175500. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175501. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175502. */
  175503. #if BITS_IN_JSAMPLE == 8
  175504. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175505. #else
  175506. #define MULTIPLY(var,const) ((var) * (const))
  175507. #endif
  175508. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175509. * entry; produce an int result. In this module, both inputs and result
  175510. * are 16 bits or less, so either int or short multiply will work.
  175511. */
  175512. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175513. /*
  175514. * Perform dequantization and inverse DCT on one block of coefficients.
  175515. */
  175516. GLOBAL(void)
  175517. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175518. JCOEFPTR coef_block,
  175519. JSAMPARRAY output_buf, JDIMENSION output_col)
  175520. {
  175521. INT32 tmp0, tmp1, tmp2, tmp3;
  175522. INT32 tmp10, tmp11, tmp12, tmp13;
  175523. INT32 z1, z2, z3, z4, z5;
  175524. JCOEFPTR inptr;
  175525. ISLOW_MULT_TYPE * quantptr;
  175526. int * wsptr;
  175527. JSAMPROW outptr;
  175528. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175529. int ctr;
  175530. int workspace[DCTSIZE2]; /* buffers data between passes */
  175531. SHIFT_TEMPS
  175532. /* Pass 1: process columns from input, store into work array. */
  175533. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  175534. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175535. inptr = coef_block;
  175536. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175537. wsptr = workspace;
  175538. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175539. /* Due to quantization, we will usually find that many of the input
  175540. * coefficients are zero, especially the AC terms. We can exploit this
  175541. * by short-circuiting the IDCT calculation for any column in which all
  175542. * the AC terms are zero. In that case each output is equal to the
  175543. * DC coefficient (with scale factor as needed).
  175544. * With typical images and quantization tables, half or more of the
  175545. * column DCT calculations can be simplified this way.
  175546. */
  175547. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175548. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175549. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175550. inptr[DCTSIZE*7] == 0) {
  175551. /* AC terms all zero */
  175552. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175553. wsptr[DCTSIZE*0] = dcval;
  175554. wsptr[DCTSIZE*1] = dcval;
  175555. wsptr[DCTSIZE*2] = dcval;
  175556. wsptr[DCTSIZE*3] = dcval;
  175557. wsptr[DCTSIZE*4] = dcval;
  175558. wsptr[DCTSIZE*5] = dcval;
  175559. wsptr[DCTSIZE*6] = dcval;
  175560. wsptr[DCTSIZE*7] = dcval;
  175561. inptr++; /* advance pointers to next column */
  175562. quantptr++;
  175563. wsptr++;
  175564. continue;
  175565. }
  175566. /* Even part: reverse the even part of the forward DCT. */
  175567. /* The rotator is sqrt(2)*c(-6). */
  175568. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175569. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175570. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175571. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175572. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175573. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175574. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175575. tmp0 = (z2 + z3) << CONST_BITS;
  175576. tmp1 = (z2 - z3) << CONST_BITS;
  175577. tmp10 = tmp0 + tmp3;
  175578. tmp13 = tmp0 - tmp3;
  175579. tmp11 = tmp1 + tmp2;
  175580. tmp12 = tmp1 - tmp2;
  175581. /* Odd part per figure 8; the matrix is unitary and hence its
  175582. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175583. */
  175584. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175585. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175586. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175587. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175588. z1 = tmp0 + tmp3;
  175589. z2 = tmp1 + tmp2;
  175590. z3 = tmp0 + tmp2;
  175591. z4 = tmp1 + tmp3;
  175592. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175593. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175594. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175595. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175596. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175597. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175598. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175599. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175600. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175601. z3 += z5;
  175602. z4 += z5;
  175603. tmp0 += z1 + z3;
  175604. tmp1 += z2 + z4;
  175605. tmp2 += z2 + z3;
  175606. tmp3 += z1 + z4;
  175607. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175608. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  175609. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  175610. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  175611. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  175612. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  175613. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  175614. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  175615. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  175616. inptr++; /* advance pointers to next column */
  175617. quantptr++;
  175618. wsptr++;
  175619. }
  175620. /* Pass 2: process rows from work array, store into output array. */
  175621. /* Note that we must descale the results by a factor of 8 == 2**3, */
  175622. /* and also undo the PASS1_BITS scaling. */
  175623. wsptr = workspace;
  175624. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175625. outptr = output_buf[ctr] + output_col;
  175626. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175627. * However, the column calculation has created many nonzero AC terms, so
  175628. * the simplification applies less often (typically 5% to 10% of the time).
  175629. * On machines with very fast multiplication, it's possible that the
  175630. * test takes more time than it's worth. In that case this section
  175631. * may be commented out.
  175632. */
  175633. #ifndef NO_ZERO_ROW_TEST
  175634. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  175635. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175636. /* AC terms all zero */
  175637. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175638. & RANGE_MASK];
  175639. outptr[0] = dcval;
  175640. outptr[1] = dcval;
  175641. outptr[2] = dcval;
  175642. outptr[3] = dcval;
  175643. outptr[4] = dcval;
  175644. outptr[5] = dcval;
  175645. outptr[6] = dcval;
  175646. outptr[7] = dcval;
  175647. wsptr += DCTSIZE; /* advance pointer to next row */
  175648. continue;
  175649. }
  175650. #endif
  175651. /* Even part: reverse the even part of the forward DCT. */
  175652. /* The rotator is sqrt(2)*c(-6). */
  175653. z2 = (INT32) wsptr[2];
  175654. z3 = (INT32) wsptr[6];
  175655. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  175656. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  175657. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  175658. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  175659. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  175660. tmp10 = tmp0 + tmp3;
  175661. tmp13 = tmp0 - tmp3;
  175662. tmp11 = tmp1 + tmp2;
  175663. tmp12 = tmp1 - tmp2;
  175664. /* Odd part per figure 8; the matrix is unitary and hence its
  175665. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  175666. */
  175667. tmp0 = (INT32) wsptr[7];
  175668. tmp1 = (INT32) wsptr[5];
  175669. tmp2 = (INT32) wsptr[3];
  175670. tmp3 = (INT32) wsptr[1];
  175671. z1 = tmp0 + tmp3;
  175672. z2 = tmp1 + tmp2;
  175673. z3 = tmp0 + tmp2;
  175674. z4 = tmp1 + tmp3;
  175675. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175676. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175677. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175678. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175679. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175680. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175681. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175682. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175683. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175684. z3 += z5;
  175685. z4 += z5;
  175686. tmp0 += z1 + z3;
  175687. tmp1 += z2 + z4;
  175688. tmp2 += z2 + z3;
  175689. tmp3 += z1 + z4;
  175690. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  175691. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  175692. CONST_BITS+PASS1_BITS+3)
  175693. & RANGE_MASK];
  175694. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  175695. CONST_BITS+PASS1_BITS+3)
  175696. & RANGE_MASK];
  175697. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  175698. CONST_BITS+PASS1_BITS+3)
  175699. & RANGE_MASK];
  175700. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  175701. CONST_BITS+PASS1_BITS+3)
  175702. & RANGE_MASK];
  175703. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  175704. CONST_BITS+PASS1_BITS+3)
  175705. & RANGE_MASK];
  175706. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  175707. CONST_BITS+PASS1_BITS+3)
  175708. & RANGE_MASK];
  175709. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  175710. CONST_BITS+PASS1_BITS+3)
  175711. & RANGE_MASK];
  175712. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  175713. CONST_BITS+PASS1_BITS+3)
  175714. & RANGE_MASK];
  175715. wsptr += DCTSIZE; /* advance pointer to next row */
  175716. }
  175717. }
  175718. #endif /* DCT_ISLOW_SUPPORTED */
  175719. /*** End of inlined file: jidctint.c ***/
  175720. /*** Start of inlined file: jidctred.c ***/
  175721. #define JPEG_INTERNALS
  175722. #ifdef IDCT_SCALING_SUPPORTED
  175723. /*
  175724. * This module is specialized to the case DCTSIZE = 8.
  175725. */
  175726. #if DCTSIZE != 8
  175727. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175728. #endif
  175729. /* Scaling is the same as in jidctint.c. */
  175730. #if BITS_IN_JSAMPLE == 8
  175731. #define CONST_BITS 13
  175732. #define PASS1_BITS 2
  175733. #else
  175734. #define CONST_BITS 13
  175735. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175736. #endif
  175737. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175738. * causing a lot of useless floating-point operations at run time.
  175739. * To get around this we use the following pre-calculated constants.
  175740. * If you change CONST_BITS you may want to add appropriate values.
  175741. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175742. */
  175743. #if CONST_BITS == 13
  175744. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  175745. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  175746. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  175747. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  175748. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175749. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  175750. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175751. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  175752. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  175753. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  175754. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175755. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  175756. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175757. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  175758. #else
  175759. #define FIX_0_211164243 FIX(0.211164243)
  175760. #define FIX_0_509795579 FIX(0.509795579)
  175761. #define FIX_0_601344887 FIX(0.601344887)
  175762. #define FIX_0_720959822 FIX(0.720959822)
  175763. #define FIX_0_765366865 FIX(0.765366865)
  175764. #define FIX_0_850430095 FIX(0.850430095)
  175765. #define FIX_0_899976223 FIX(0.899976223)
  175766. #define FIX_1_061594337 FIX(1.061594337)
  175767. #define FIX_1_272758580 FIX(1.272758580)
  175768. #define FIX_1_451774981 FIX(1.451774981)
  175769. #define FIX_1_847759065 FIX(1.847759065)
  175770. #define FIX_2_172734803 FIX(2.172734803)
  175771. #define FIX_2_562915447 FIX(2.562915447)
  175772. #define FIX_3_624509785 FIX(3.624509785)
  175773. #endif
  175774. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175775. * For 8-bit samples with the recommended scaling, all the variable
  175776. * and constant values involved are no more than 16 bits wide, so a
  175777. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175778. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175779. */
  175780. #if BITS_IN_JSAMPLE == 8
  175781. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175782. #else
  175783. #define MULTIPLY(var,const) ((var) * (const))
  175784. #endif
  175785. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175786. * entry; produce an int result. In this module, both inputs and result
  175787. * are 16 bits or less, so either int or short multiply will work.
  175788. */
  175789. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  175790. /*
  175791. * Perform dequantization and inverse DCT on one block of coefficients,
  175792. * producing a reduced-size 4x4 output block.
  175793. */
  175794. GLOBAL(void)
  175795. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175796. JCOEFPTR coef_block,
  175797. JSAMPARRAY output_buf, JDIMENSION output_col)
  175798. {
  175799. INT32 tmp0, tmp2, tmp10, tmp12;
  175800. INT32 z1, z2, z3, z4;
  175801. JCOEFPTR inptr;
  175802. ISLOW_MULT_TYPE * quantptr;
  175803. int * wsptr;
  175804. JSAMPROW outptr;
  175805. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175806. int ctr;
  175807. int workspace[DCTSIZE*4]; /* buffers data between passes */
  175808. SHIFT_TEMPS
  175809. /* Pass 1: process columns from input, store into work array. */
  175810. inptr = coef_block;
  175811. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175812. wsptr = workspace;
  175813. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175814. /* Don't bother to process column 4, because second pass won't use it */
  175815. if (ctr == DCTSIZE-4)
  175816. continue;
  175817. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175818. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  175819. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  175820. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  175821. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175822. wsptr[DCTSIZE*0] = dcval;
  175823. wsptr[DCTSIZE*1] = dcval;
  175824. wsptr[DCTSIZE*2] = dcval;
  175825. wsptr[DCTSIZE*3] = dcval;
  175826. continue;
  175827. }
  175828. /* Even part */
  175829. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175830. tmp0 <<= (CONST_BITS+1);
  175831. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175832. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175833. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  175834. tmp10 = tmp0 + tmp2;
  175835. tmp12 = tmp0 - tmp2;
  175836. /* Odd part */
  175837. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175838. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175839. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175840. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175841. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175842. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175843. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175844. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175845. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175846. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175847. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175848. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175849. /* Final output stage */
  175850. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  175851. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  175852. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  175853. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  175854. }
  175855. /* Pass 2: process 4 rows from work array, store into output array. */
  175856. wsptr = workspace;
  175857. for (ctr = 0; ctr < 4; ctr++) {
  175858. outptr = output_buf[ctr] + output_col;
  175859. /* It's not clear whether a zero row test is worthwhile here ... */
  175860. #ifndef NO_ZERO_ROW_TEST
  175861. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  175862. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  175863. /* AC terms all zero */
  175864. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175865. & RANGE_MASK];
  175866. outptr[0] = dcval;
  175867. outptr[1] = dcval;
  175868. outptr[2] = dcval;
  175869. outptr[3] = dcval;
  175870. wsptr += DCTSIZE; /* advance pointer to next row */
  175871. continue;
  175872. }
  175873. #endif
  175874. /* Even part */
  175875. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  175876. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  175877. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  175878. tmp10 = tmp0 + tmp2;
  175879. tmp12 = tmp0 - tmp2;
  175880. /* Odd part */
  175881. z1 = (INT32) wsptr[7];
  175882. z2 = (INT32) wsptr[5];
  175883. z3 = (INT32) wsptr[3];
  175884. z4 = (INT32) wsptr[1];
  175885. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  175886. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  175887. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  175888. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  175889. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  175890. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  175891. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  175892. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  175893. /* Final output stage */
  175894. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  175895. CONST_BITS+PASS1_BITS+3+1)
  175896. & RANGE_MASK];
  175897. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  175898. CONST_BITS+PASS1_BITS+3+1)
  175899. & RANGE_MASK];
  175900. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  175901. CONST_BITS+PASS1_BITS+3+1)
  175902. & RANGE_MASK];
  175903. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  175904. CONST_BITS+PASS1_BITS+3+1)
  175905. & RANGE_MASK];
  175906. wsptr += DCTSIZE; /* advance pointer to next row */
  175907. }
  175908. }
  175909. /*
  175910. * Perform dequantization and inverse DCT on one block of coefficients,
  175911. * producing a reduced-size 2x2 output block.
  175912. */
  175913. GLOBAL(void)
  175914. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175915. JCOEFPTR coef_block,
  175916. JSAMPARRAY output_buf, JDIMENSION output_col)
  175917. {
  175918. INT32 tmp0, tmp10, z1;
  175919. JCOEFPTR inptr;
  175920. ISLOW_MULT_TYPE * quantptr;
  175921. int * wsptr;
  175922. JSAMPROW outptr;
  175923. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175924. int ctr;
  175925. int workspace[DCTSIZE*2]; /* buffers data between passes */
  175926. SHIFT_TEMPS
  175927. /* Pass 1: process columns from input, store into work array. */
  175928. inptr = coef_block;
  175929. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  175930. wsptr = workspace;
  175931. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  175932. /* Don't bother to process columns 2,4,6 */
  175933. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  175934. continue;
  175935. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  175936. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  175937. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  175938. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  175939. wsptr[DCTSIZE*0] = dcval;
  175940. wsptr[DCTSIZE*1] = dcval;
  175941. continue;
  175942. }
  175943. /* Even part */
  175944. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175945. tmp10 = z1 << (CONST_BITS+2);
  175946. /* Odd part */
  175947. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175948. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  175949. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175950. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  175951. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175952. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  175953. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175954. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175955. /* Final output stage */
  175956. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  175957. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  175958. }
  175959. /* Pass 2: process 2 rows from work array, store into output array. */
  175960. wsptr = workspace;
  175961. for (ctr = 0; ctr < 2; ctr++) {
  175962. outptr = output_buf[ctr] + output_col;
  175963. /* It's not clear whether a zero row test is worthwhile here ... */
  175964. #ifndef NO_ZERO_ROW_TEST
  175965. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  175966. /* AC terms all zero */
  175967. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  175968. & RANGE_MASK];
  175969. outptr[0] = dcval;
  175970. outptr[1] = dcval;
  175971. wsptr += DCTSIZE; /* advance pointer to next row */
  175972. continue;
  175973. }
  175974. #endif
  175975. /* Even part */
  175976. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  175977. /* Odd part */
  175978. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  175979. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  175980. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  175981. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  175982. /* Final output stage */
  175983. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  175984. CONST_BITS+PASS1_BITS+3+2)
  175985. & RANGE_MASK];
  175986. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  175987. CONST_BITS+PASS1_BITS+3+2)
  175988. & RANGE_MASK];
  175989. wsptr += DCTSIZE; /* advance pointer to next row */
  175990. }
  175991. }
  175992. /*
  175993. * Perform dequantization and inverse DCT on one block of coefficients,
  175994. * producing a reduced-size 1x1 output block.
  175995. */
  175996. GLOBAL(void)
  175997. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175998. JCOEFPTR coef_block,
  175999. JSAMPARRAY output_buf, JDIMENSION output_col)
  176000. {
  176001. int dcval;
  176002. ISLOW_MULT_TYPE * quantptr;
  176003. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176004. SHIFT_TEMPS
  176005. /* We hardly need an inverse DCT routine for this: just take the
  176006. * average pixel value, which is one-eighth of the DC coefficient.
  176007. */
  176008. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  176009. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  176010. dcval = (int) DESCALE((INT32) dcval, 3);
  176011. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  176012. }
  176013. #endif /* IDCT_SCALING_SUPPORTED */
  176014. /*** End of inlined file: jidctred.c ***/
  176015. /*** Start of inlined file: jmemmgr.c ***/
  176016. #define JPEG_INTERNALS
  176017. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  176018. /*** Start of inlined file: jmemsys.h ***/
  176019. #ifndef __jmemsys_h__
  176020. #define __jmemsys_h__
  176021. /* Short forms of external names for systems with brain-damaged linkers. */
  176022. #ifdef NEED_SHORT_EXTERNAL_NAMES
  176023. #define jpeg_get_small jGetSmall
  176024. #define jpeg_free_small jFreeSmall
  176025. #define jpeg_get_large jGetLarge
  176026. #define jpeg_free_large jFreeLarge
  176027. #define jpeg_mem_available jMemAvail
  176028. #define jpeg_open_backing_store jOpenBackStore
  176029. #define jpeg_mem_init jMemInit
  176030. #define jpeg_mem_term jMemTerm
  176031. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176032. /*
  176033. * These two functions are used to allocate and release small chunks of
  176034. * memory. (Typically the total amount requested through jpeg_get_small is
  176035. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176036. * Behavior should be the same as for the standard library functions malloc
  176037. * and free; in particular, jpeg_get_small must return NULL on failure.
  176038. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176039. * size of the object being freed, just in case it's needed.
  176040. * On an 80x86 machine using small-data memory model, these manage near heap.
  176041. */
  176042. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176043. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176044. size_t sizeofobject));
  176045. /*
  176046. * These two functions are used to allocate and release large chunks of
  176047. * memory (up to the total free space designated by jpeg_mem_available).
  176048. * The interface is the same as above, except that on an 80x86 machine,
  176049. * far pointers are used. On most other machines these are identical to
  176050. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176051. * in case a different allocation strategy is desirable for large chunks.
  176052. */
  176053. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176054. size_t sizeofobject));
  176055. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176056. size_t sizeofobject));
  176057. /*
  176058. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176059. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176060. * matter, but that case should never come into play). This macro is needed
  176061. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176062. * On those machines, we expect that jconfig.h will provide a proper value.
  176063. * On machines with 32-bit flat address spaces, any large constant may be used.
  176064. *
  176065. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176066. * size_t and will be a multiple of sizeof(align_type).
  176067. */
  176068. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176069. #define MAX_ALLOC_CHUNK 1000000000L
  176070. #endif
  176071. /*
  176072. * This routine computes the total space still available for allocation by
  176073. * jpeg_get_large. If more space than this is needed, backing store will be
  176074. * used. NOTE: any memory already allocated must not be counted.
  176075. *
  176076. * There is a minimum space requirement, corresponding to the minimum
  176077. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176078. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176079. * all working storage in memory, is also passed in case it is useful.
  176080. * Finally, the total space already allocated is passed. If no better
  176081. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176082. * is often a suitable calculation.
  176083. *
  176084. * It is OK for jpeg_mem_available to underestimate the space available
  176085. * (that'll just lead to more backing-store access than is really necessary).
  176086. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176087. * a slop factor from the true available space. 5% should be enough.
  176088. *
  176089. * On machines with lots of virtual memory, any large constant may be returned.
  176090. * Conversely, zero may be returned to always use the minimum amount of memory.
  176091. */
  176092. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176093. long min_bytes_needed,
  176094. long max_bytes_needed,
  176095. long already_allocated));
  176096. /*
  176097. * This structure holds whatever state is needed to access a single
  176098. * backing-store object. The read/write/close method pointers are called
  176099. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176100. * are private to the system-dependent backing store routines.
  176101. */
  176102. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176103. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176104. typedef unsigned short XMSH; /* type of extended-memory handles */
  176105. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176106. typedef union {
  176107. short file_handle; /* DOS file handle if it's a temp file */
  176108. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176109. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176110. } handle_union;
  176111. #endif /* USE_MSDOS_MEMMGR */
  176112. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176113. #include <Files.h>
  176114. #endif /* USE_MAC_MEMMGR */
  176115. //typedef struct backing_store_struct * backing_store_ptr;
  176116. typedef struct backing_store_struct {
  176117. /* Methods for reading/writing/closing this backing-store object */
  176118. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176119. struct backing_store_struct *info,
  176120. void FAR * buffer_address,
  176121. long file_offset, long byte_count));
  176122. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176123. struct backing_store_struct *info,
  176124. void FAR * buffer_address,
  176125. long file_offset, long byte_count));
  176126. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176127. struct backing_store_struct *info));
  176128. /* Private fields for system-dependent backing-store management */
  176129. #ifdef USE_MSDOS_MEMMGR
  176130. /* For the MS-DOS manager (jmemdos.c), we need: */
  176131. handle_union handle; /* reference to backing-store storage object */
  176132. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176133. #else
  176134. #ifdef USE_MAC_MEMMGR
  176135. /* For the Mac manager (jmemmac.c), we need: */
  176136. short temp_file; /* file reference number to temp file */
  176137. FSSpec tempSpec; /* the FSSpec for the temp file */
  176138. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176139. #else
  176140. /* For a typical implementation with temp files, we need: */
  176141. FILE * temp_file; /* stdio reference to temp file */
  176142. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176143. #endif
  176144. #endif
  176145. } backing_store_info;
  176146. /*
  176147. * Initial opening of a backing-store object. This must fill in the
  176148. * read/write/close pointers in the object. The read/write routines
  176149. * may take an error exit if the specified maximum file size is exceeded.
  176150. * (If jpeg_mem_available always returns a large value, this routine can
  176151. * just take an error exit.)
  176152. */
  176153. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176154. struct backing_store_struct *info,
  176155. long total_bytes_needed));
  176156. /*
  176157. * These routines take care of any system-dependent initialization and
  176158. * cleanup required. jpeg_mem_init will be called before anything is
  176159. * allocated (and, therefore, nothing in cinfo is of use except the error
  176160. * manager pointer). It should return a suitable default value for
  176161. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176162. * application. (Note that max_memory_to_use is only important if
  176163. * jpeg_mem_available chooses to consult it ... no one else will.)
  176164. * jpeg_mem_term may assume that all requested memory has been freed and that
  176165. * all opened backing-store objects have been closed.
  176166. */
  176167. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176168. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176169. #endif
  176170. /*** End of inlined file: jmemsys.h ***/
  176171. /* import the system-dependent declarations */
  176172. #ifndef NO_GETENV
  176173. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176174. extern char * getenv JPP((const char * name));
  176175. #endif
  176176. #endif
  176177. /*
  176178. * Some important notes:
  176179. * The allocation routines provided here must never return NULL.
  176180. * They should exit to error_exit if unsuccessful.
  176181. *
  176182. * It's not a good idea to try to merge the sarray and barray routines,
  176183. * even though they are textually almost the same, because samples are
  176184. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176185. * in machines where byte pointers have a different representation from
  176186. * word pointers, the resulting machine code could not be the same.
  176187. */
  176188. /*
  176189. * Many machines require storage alignment: longs must start on 4-byte
  176190. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176191. * always returns pointers that are multiples of the worst-case alignment
  176192. * requirement, and we had better do so too.
  176193. * There isn't any really portable way to determine the worst-case alignment
  176194. * requirement. This module assumes that the alignment requirement is
  176195. * multiples of sizeof(ALIGN_TYPE).
  176196. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176197. * workstations (where doubles really do need 8-byte alignment) and will work
  176198. * fine on nearly everything. If your machine has lesser alignment needs,
  176199. * you can save a few bytes by making ALIGN_TYPE smaller.
  176200. * The only place I know of where this will NOT work is certain Macintosh
  176201. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176202. * Doing 10-byte alignment is counterproductive because longwords won't be
  176203. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176204. * such a compiler.
  176205. */
  176206. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176207. #define ALIGN_TYPE double
  176208. #endif
  176209. /*
  176210. * We allocate objects from "pools", where each pool is gotten with a single
  176211. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176212. * overhead within a pool, except for alignment padding. Each pool has a
  176213. * header with a link to the next pool of the same class.
  176214. * Small and large pool headers are identical except that the latter's
  176215. * link pointer must be FAR on 80x86 machines.
  176216. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176217. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176218. * of the alignment requirement of ALIGN_TYPE.
  176219. */
  176220. typedef union small_pool_struct * small_pool_ptr;
  176221. typedef union small_pool_struct {
  176222. struct {
  176223. small_pool_ptr next; /* next in list of pools */
  176224. size_t bytes_used; /* how many bytes already used within pool */
  176225. size_t bytes_left; /* bytes still available in this pool */
  176226. } hdr;
  176227. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176228. } small_pool_hdr;
  176229. typedef union large_pool_struct FAR * large_pool_ptr;
  176230. typedef union large_pool_struct {
  176231. struct {
  176232. large_pool_ptr next; /* next in list of pools */
  176233. size_t bytes_used; /* how many bytes already used within pool */
  176234. size_t bytes_left; /* bytes still available in this pool */
  176235. } hdr;
  176236. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  176237. } large_pool_hdr;
  176238. /*
  176239. * Here is the full definition of a memory manager object.
  176240. */
  176241. typedef struct {
  176242. struct jpeg_memory_mgr pub; /* public fields */
  176243. /* Each pool identifier (lifetime class) names a linked list of pools. */
  176244. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  176245. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  176246. /* Since we only have one lifetime class of virtual arrays, only one
  176247. * linked list is necessary (for each datatype). Note that the virtual
  176248. * array control blocks being linked together are actually stored somewhere
  176249. * in the small-pool list.
  176250. */
  176251. jvirt_sarray_ptr virt_sarray_list;
  176252. jvirt_barray_ptr virt_barray_list;
  176253. /* This counts total space obtained from jpeg_get_small/large */
  176254. long total_space_allocated;
  176255. /* alloc_sarray and alloc_barray set this value for use by virtual
  176256. * array routines.
  176257. */
  176258. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  176259. } my_memory_mgr;
  176260. typedef my_memory_mgr * my_mem_ptr;
  176261. /*
  176262. * The control blocks for virtual arrays.
  176263. * Note that these blocks are allocated in the "small" pool area.
  176264. * System-dependent info for the associated backing store (if any) is hidden
  176265. * inside the backing_store_info struct.
  176266. */
  176267. struct jvirt_sarray_control {
  176268. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  176269. JDIMENSION rows_in_array; /* total virtual array height */
  176270. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  176271. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  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_sarray_ptr next; /* link to next virtual sarray control block */
  176280. backing_store_info b_s_info; /* System-dependent control info */
  176281. };
  176282. struct jvirt_barray_control {
  176283. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  176284. JDIMENSION rows_in_array; /* total virtual array height */
  176285. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  176286. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  176287. JDIMENSION rows_in_mem; /* height of memory buffer */
  176288. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  176289. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  176290. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  176291. boolean pre_zero; /* pre-zero mode requested? */
  176292. boolean dirty; /* do current buffer contents need written? */
  176293. boolean b_s_open; /* is backing-store data valid? */
  176294. jvirt_barray_ptr next; /* link to next virtual barray control block */
  176295. backing_store_info b_s_info; /* System-dependent control info */
  176296. };
  176297. #ifdef MEM_STATS /* optional extra stuff for statistics */
  176298. LOCAL(void)
  176299. print_mem_stats (j_common_ptr cinfo, int pool_id)
  176300. {
  176301. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176302. small_pool_ptr shdr_ptr;
  176303. large_pool_ptr lhdr_ptr;
  176304. /* Since this is only a debugging stub, we can cheat a little by using
  176305. * fprintf directly rather than going through the trace message code.
  176306. * This is helpful because message parm array can't handle longs.
  176307. */
  176308. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  176309. pool_id, mem->total_space_allocated);
  176310. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  176311. lhdr_ptr = lhdr_ptr->hdr.next) {
  176312. fprintf(stderr, " Large chunk used %ld\n",
  176313. (long) lhdr_ptr->hdr.bytes_used);
  176314. }
  176315. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  176316. shdr_ptr = shdr_ptr->hdr.next) {
  176317. fprintf(stderr, " Small chunk used %ld free %ld\n",
  176318. (long) shdr_ptr->hdr.bytes_used,
  176319. (long) shdr_ptr->hdr.bytes_left);
  176320. }
  176321. }
  176322. #endif /* MEM_STATS */
  176323. LOCAL(void)
  176324. out_of_memory (j_common_ptr cinfo, int which)
  176325. /* Report an out-of-memory error and stop execution */
  176326. /* If we compiled MEM_STATS support, report alloc requests before dying */
  176327. {
  176328. #ifdef MEM_STATS
  176329. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  176330. #endif
  176331. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  176332. }
  176333. /*
  176334. * Allocation of "small" objects.
  176335. *
  176336. * For these, we use pooled storage. When a new pool must be created,
  176337. * we try to get enough space for the current request plus a "slop" factor,
  176338. * where the slop will be the amount of leftover space in the new pool.
  176339. * The speed vs. space tradeoff is largely determined by the slop values.
  176340. * A different slop value is provided for each pool class (lifetime),
  176341. * and we also distinguish the first pool of a class from later ones.
  176342. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  176343. * machines, but may be too small if longs are 64 bits or more.
  176344. */
  176345. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  176346. {
  176347. 1600, /* first PERMANENT pool */
  176348. 16000 /* first IMAGE pool */
  176349. };
  176350. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  176351. {
  176352. 0, /* additional PERMANENT pools */
  176353. 5000 /* additional IMAGE pools */
  176354. };
  176355. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  176356. METHODDEF(void *)
  176357. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176358. /* Allocate a "small" object */
  176359. {
  176360. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176361. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  176362. char * data_ptr;
  176363. size_t odd_bytes, min_request, slop;
  176364. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176365. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  176366. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  176367. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176368. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176369. if (odd_bytes > 0)
  176370. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176371. /* See if space is available in any existing pool */
  176372. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176373. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176374. prev_hdr_ptr = NULL;
  176375. hdr_ptr = mem->small_list[pool_id];
  176376. while (hdr_ptr != NULL) {
  176377. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  176378. break; /* found pool with enough space */
  176379. prev_hdr_ptr = hdr_ptr;
  176380. hdr_ptr = hdr_ptr->hdr.next;
  176381. }
  176382. /* Time to make a new pool? */
  176383. if (hdr_ptr == NULL) {
  176384. /* min_request is what we need now, slop is what will be leftover */
  176385. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  176386. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176387. slop = first_pool_slop[pool_id];
  176388. else
  176389. slop = extra_pool_slop[pool_id];
  176390. /* Don't ask for more than MAX_ALLOC_CHUNK */
  176391. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  176392. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  176393. /* Try to get space, if fail reduce slop and try again */
  176394. for (;;) {
  176395. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  176396. if (hdr_ptr != NULL)
  176397. break;
  176398. slop /= 2;
  176399. if (slop < MIN_SLOP) /* give up when it gets real small */
  176400. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  176401. }
  176402. mem->total_space_allocated += min_request + slop;
  176403. /* Success, initialize the new pool header and add to end of list */
  176404. hdr_ptr->hdr.next = NULL;
  176405. hdr_ptr->hdr.bytes_used = 0;
  176406. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  176407. if (prev_hdr_ptr == NULL) /* first pool in class? */
  176408. mem->small_list[pool_id] = hdr_ptr;
  176409. else
  176410. prev_hdr_ptr->hdr.next = hdr_ptr;
  176411. }
  176412. /* OK, allocate the object from the current pool */
  176413. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  176414. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  176415. hdr_ptr->hdr.bytes_used += sizeofobject;
  176416. hdr_ptr->hdr.bytes_left -= sizeofobject;
  176417. return (void *) data_ptr;
  176418. }
  176419. /*
  176420. * Allocation of "large" objects.
  176421. *
  176422. * The external semantics of these are the same as "small" objects,
  176423. * except that FAR pointers are used on 80x86. However the pool
  176424. * management heuristics are quite different. We assume that each
  176425. * request is large enough that it may as well be passed directly to
  176426. * jpeg_get_large; the pool management just links everything together
  176427. * so that we can free it all on demand.
  176428. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  176429. * structures. The routines that create these structures (see below)
  176430. * deliberately bunch rows together to ensure a large request size.
  176431. */
  176432. METHODDEF(void FAR *)
  176433. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  176434. /* Allocate a "large" object */
  176435. {
  176436. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176437. large_pool_ptr hdr_ptr;
  176438. size_t odd_bytes;
  176439. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  176440. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  176441. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  176442. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  176443. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  176444. if (odd_bytes > 0)
  176445. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  176446. /* Always make a new pool */
  176447. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176448. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176449. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  176450. SIZEOF(large_pool_hdr));
  176451. if (hdr_ptr == NULL)
  176452. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  176453. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  176454. /* Success, initialize the new pool header and add to list */
  176455. hdr_ptr->hdr.next = mem->large_list[pool_id];
  176456. /* We maintain space counts in each pool header for statistical purposes,
  176457. * even though they are not needed for allocation.
  176458. */
  176459. hdr_ptr->hdr.bytes_used = sizeofobject;
  176460. hdr_ptr->hdr.bytes_left = 0;
  176461. mem->large_list[pool_id] = hdr_ptr;
  176462. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  176463. }
  176464. /*
  176465. * Creation of 2-D sample arrays.
  176466. * The pointers are in near heap, the samples themselves in FAR heap.
  176467. *
  176468. * To minimize allocation overhead and to allow I/O of large contiguous
  176469. * blocks, we allocate the sample rows in groups of as many rows as possible
  176470. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  176471. * NB: the virtual array control routines, later in this file, know about
  176472. * this chunking of rows. The rowsperchunk value is left in the mem manager
  176473. * object so that it can be saved away if this sarray is the workspace for
  176474. * a virtual array.
  176475. */
  176476. METHODDEF(JSAMPARRAY)
  176477. alloc_sarray (j_common_ptr cinfo, int pool_id,
  176478. JDIMENSION samplesperrow, JDIMENSION numrows)
  176479. /* Allocate a 2-D sample array */
  176480. {
  176481. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176482. JSAMPARRAY result;
  176483. JSAMPROW workspace;
  176484. JDIMENSION rowsperchunk, currow, i;
  176485. long ltemp;
  176486. /* Calculate max # of rows allowed in one allocation chunk */
  176487. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176488. ((long) samplesperrow * SIZEOF(JSAMPLE));
  176489. if (ltemp <= 0)
  176490. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176491. if (ltemp < (long) numrows)
  176492. rowsperchunk = (JDIMENSION) ltemp;
  176493. else
  176494. rowsperchunk = numrows;
  176495. mem->last_rowsperchunk = rowsperchunk;
  176496. /* Get space for row pointers (small object) */
  176497. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  176498. (size_t) (numrows * SIZEOF(JSAMPROW)));
  176499. /* Get the rows themselves (large objects) */
  176500. currow = 0;
  176501. while (currow < numrows) {
  176502. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176503. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  176504. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  176505. * SIZEOF(JSAMPLE)));
  176506. for (i = rowsperchunk; i > 0; i--) {
  176507. result[currow++] = workspace;
  176508. workspace += samplesperrow;
  176509. }
  176510. }
  176511. return result;
  176512. }
  176513. /*
  176514. * Creation of 2-D coefficient-block arrays.
  176515. * This is essentially the same as the code for sample arrays, above.
  176516. */
  176517. METHODDEF(JBLOCKARRAY)
  176518. alloc_barray (j_common_ptr cinfo, int pool_id,
  176519. JDIMENSION blocksperrow, JDIMENSION numrows)
  176520. /* Allocate a 2-D coefficient-block array */
  176521. {
  176522. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176523. JBLOCKARRAY result;
  176524. JBLOCKROW workspace;
  176525. JDIMENSION rowsperchunk, currow, i;
  176526. long ltemp;
  176527. /* Calculate max # of rows allowed in one allocation chunk */
  176528. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  176529. ((long) blocksperrow * SIZEOF(JBLOCK));
  176530. if (ltemp <= 0)
  176531. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  176532. if (ltemp < (long) numrows)
  176533. rowsperchunk = (JDIMENSION) ltemp;
  176534. else
  176535. rowsperchunk = numrows;
  176536. mem->last_rowsperchunk = rowsperchunk;
  176537. /* Get space for row pointers (small object) */
  176538. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  176539. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  176540. /* Get the rows themselves (large objects) */
  176541. currow = 0;
  176542. while (currow < numrows) {
  176543. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  176544. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  176545. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  176546. * SIZEOF(JBLOCK)));
  176547. for (i = rowsperchunk; i > 0; i--) {
  176548. result[currow++] = workspace;
  176549. workspace += blocksperrow;
  176550. }
  176551. }
  176552. return result;
  176553. }
  176554. /*
  176555. * About virtual array management:
  176556. *
  176557. * The above "normal" array routines are only used to allocate strip buffers
  176558. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  176559. * are handled as "virtual" arrays. The array is still accessed a strip at a
  176560. * time, but the memory manager must save the whole array for repeated
  176561. * accesses. The intended implementation is that there is a strip buffer in
  176562. * memory (as high as is possible given the desired memory limit), plus a
  176563. * backing file that holds the rest of the array.
  176564. *
  176565. * The request_virt_array routines are told the total size of the image and
  176566. * the maximum number of rows that will be accessed at once. The in-memory
  176567. * buffer must be at least as large as the maxaccess value.
  176568. *
  176569. * The request routines create control blocks but not the in-memory buffers.
  176570. * That is postponed until realize_virt_arrays is called. At that time the
  176571. * total amount of space needed is known (approximately, anyway), so free
  176572. * memory can be divided up fairly.
  176573. *
  176574. * The access_virt_array routines are responsible for making a specific strip
  176575. * area accessible (after reading or writing the backing file, if necessary).
  176576. * Note that the access routines are told whether the caller intends to modify
  176577. * the accessed strip; during a read-only pass this saves having to rewrite
  176578. * data to disk. The access routines are also responsible for pre-zeroing
  176579. * any newly accessed rows, if pre-zeroing was requested.
  176580. *
  176581. * In current usage, the access requests are usually for nonoverlapping
  176582. * strips; that is, successive access start_row numbers differ by exactly
  176583. * num_rows = maxaccess. This means we can get good performance with simple
  176584. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  176585. * of the access height; then there will never be accesses across bufferload
  176586. * boundaries. The code will still work with overlapping access requests,
  176587. * but it doesn't handle bufferload overlaps very efficiently.
  176588. */
  176589. METHODDEF(jvirt_sarray_ptr)
  176590. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176591. JDIMENSION samplesperrow, JDIMENSION numrows,
  176592. JDIMENSION maxaccess)
  176593. /* Request a virtual 2-D sample array */
  176594. {
  176595. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176596. jvirt_sarray_ptr result;
  176597. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176598. if (pool_id != JPOOL_IMAGE)
  176599. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176600. /* get control block */
  176601. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  176602. SIZEOF(struct jvirt_sarray_control));
  176603. result->mem_buffer = NULL; /* marks array not yet realized */
  176604. result->rows_in_array = numrows;
  176605. result->samplesperrow = samplesperrow;
  176606. result->maxaccess = maxaccess;
  176607. result->pre_zero = pre_zero;
  176608. result->b_s_open = FALSE; /* no associated backing-store object */
  176609. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  176610. mem->virt_sarray_list = result;
  176611. return result;
  176612. }
  176613. METHODDEF(jvirt_barray_ptr)
  176614. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  176615. JDIMENSION blocksperrow, JDIMENSION numrows,
  176616. JDIMENSION maxaccess)
  176617. /* Request a virtual 2-D coefficient-block array */
  176618. {
  176619. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176620. jvirt_barray_ptr result;
  176621. /* Only IMAGE-lifetime virtual arrays are currently supported */
  176622. if (pool_id != JPOOL_IMAGE)
  176623. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176624. /* get control block */
  176625. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  176626. SIZEOF(struct jvirt_barray_control));
  176627. result->mem_buffer = NULL; /* marks array not yet realized */
  176628. result->rows_in_array = numrows;
  176629. result->blocksperrow = blocksperrow;
  176630. result->maxaccess = maxaccess;
  176631. result->pre_zero = pre_zero;
  176632. result->b_s_open = FALSE; /* no associated backing-store object */
  176633. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  176634. mem->virt_barray_list = result;
  176635. return result;
  176636. }
  176637. METHODDEF(void)
  176638. realize_virt_arrays (j_common_ptr cinfo)
  176639. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  176640. {
  176641. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176642. long space_per_minheight, maximum_space, avail_mem;
  176643. long minheights, max_minheights;
  176644. jvirt_sarray_ptr sptr;
  176645. jvirt_barray_ptr bptr;
  176646. /* Compute the minimum space needed (maxaccess rows in each buffer)
  176647. * and the maximum space needed (full image height in each buffer).
  176648. * These may be of use to the system-dependent jpeg_mem_available routine.
  176649. */
  176650. space_per_minheight = 0;
  176651. maximum_space = 0;
  176652. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176653. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176654. space_per_minheight += (long) sptr->maxaccess *
  176655. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176656. maximum_space += (long) sptr->rows_in_array *
  176657. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  176658. }
  176659. }
  176660. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176661. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176662. space_per_minheight += (long) bptr->maxaccess *
  176663. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176664. maximum_space += (long) bptr->rows_in_array *
  176665. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  176666. }
  176667. }
  176668. if (space_per_minheight <= 0)
  176669. return; /* no unrealized arrays, no work */
  176670. /* Determine amount of memory to actually use; this is system-dependent. */
  176671. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  176672. mem->total_space_allocated);
  176673. /* If the maximum space needed is available, make all the buffers full
  176674. * height; otherwise parcel it out with the same number of minheights
  176675. * in each buffer.
  176676. */
  176677. if (avail_mem >= maximum_space)
  176678. max_minheights = 1000000000L;
  176679. else {
  176680. max_minheights = avail_mem / space_per_minheight;
  176681. /* If there doesn't seem to be enough space, try to get the minimum
  176682. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  176683. */
  176684. if (max_minheights <= 0)
  176685. max_minheights = 1;
  176686. }
  176687. /* Allocate the in-memory buffers and initialize backing store as needed. */
  176688. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176689. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  176690. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  176691. if (minheights <= max_minheights) {
  176692. /* This buffer fits in memory */
  176693. sptr->rows_in_mem = sptr->rows_in_array;
  176694. } else {
  176695. /* It doesn't fit in memory, create backing store. */
  176696. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  176697. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  176698. (long) sptr->rows_in_array *
  176699. (long) sptr->samplesperrow *
  176700. (long) SIZEOF(JSAMPLE));
  176701. sptr->b_s_open = TRUE;
  176702. }
  176703. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  176704. sptr->samplesperrow, sptr->rows_in_mem);
  176705. sptr->rowsperchunk = mem->last_rowsperchunk;
  176706. sptr->cur_start_row = 0;
  176707. sptr->first_undef_row = 0;
  176708. sptr->dirty = FALSE;
  176709. }
  176710. }
  176711. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176712. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  176713. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  176714. if (minheights <= max_minheights) {
  176715. /* This buffer fits in memory */
  176716. bptr->rows_in_mem = bptr->rows_in_array;
  176717. } else {
  176718. /* It doesn't fit in memory, create backing store. */
  176719. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  176720. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  176721. (long) bptr->rows_in_array *
  176722. (long) bptr->blocksperrow *
  176723. (long) SIZEOF(JBLOCK));
  176724. bptr->b_s_open = TRUE;
  176725. }
  176726. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  176727. bptr->blocksperrow, bptr->rows_in_mem);
  176728. bptr->rowsperchunk = mem->last_rowsperchunk;
  176729. bptr->cur_start_row = 0;
  176730. bptr->first_undef_row = 0;
  176731. bptr->dirty = FALSE;
  176732. }
  176733. }
  176734. }
  176735. LOCAL(void)
  176736. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  176737. /* Do backing store read or write of a virtual sample array */
  176738. {
  176739. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176740. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176741. file_offset = ptr->cur_start_row * bytesperrow;
  176742. /* Loop to read or write each allocation chunk in mem_buffer */
  176743. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176744. /* One chunk, but check for short chunk at end of buffer */
  176745. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176746. /* Transfer no more than is currently defined */
  176747. thisrow = (long) ptr->cur_start_row + i;
  176748. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176749. /* Transfer no more than fits in file */
  176750. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176751. if (rows <= 0) /* this chunk might be past end of file! */
  176752. break;
  176753. byte_count = rows * bytesperrow;
  176754. if (writing)
  176755. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176756. (void FAR *) ptr->mem_buffer[i],
  176757. file_offset, byte_count);
  176758. else
  176759. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176760. (void FAR *) ptr->mem_buffer[i],
  176761. file_offset, byte_count);
  176762. file_offset += byte_count;
  176763. }
  176764. }
  176765. LOCAL(void)
  176766. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  176767. /* Do backing store read or write of a virtual coefficient-block array */
  176768. {
  176769. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  176770. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  176771. file_offset = ptr->cur_start_row * bytesperrow;
  176772. /* Loop to read or write each allocation chunk in mem_buffer */
  176773. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  176774. /* One chunk, but check for short chunk at end of buffer */
  176775. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  176776. /* Transfer no more than is currently defined */
  176777. thisrow = (long) ptr->cur_start_row + i;
  176778. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  176779. /* Transfer no more than fits in file */
  176780. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  176781. if (rows <= 0) /* this chunk might be past end of file! */
  176782. break;
  176783. byte_count = rows * bytesperrow;
  176784. if (writing)
  176785. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  176786. (void FAR *) ptr->mem_buffer[i],
  176787. file_offset, byte_count);
  176788. else
  176789. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  176790. (void FAR *) ptr->mem_buffer[i],
  176791. file_offset, byte_count);
  176792. file_offset += byte_count;
  176793. }
  176794. }
  176795. METHODDEF(JSAMPARRAY)
  176796. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  176797. JDIMENSION start_row, JDIMENSION num_rows,
  176798. boolean writable)
  176799. /* Access the part of a virtual sample array starting at start_row */
  176800. /* and extending for num_rows rows. writable is true if */
  176801. /* caller intends to modify the accessed area. */
  176802. {
  176803. JDIMENSION end_row = start_row + num_rows;
  176804. JDIMENSION undef_row;
  176805. /* debugging check */
  176806. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176807. ptr->mem_buffer == NULL)
  176808. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176809. /* Make the desired part of the virtual array accessible */
  176810. if (start_row < ptr->cur_start_row ||
  176811. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176812. if (! ptr->b_s_open)
  176813. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176814. /* Flush old buffer contents if necessary */
  176815. if (ptr->dirty) {
  176816. do_sarray_io(cinfo, ptr, TRUE);
  176817. ptr->dirty = FALSE;
  176818. }
  176819. /* Decide what part of virtual array to access.
  176820. * Algorithm: if target address > current window, assume forward scan,
  176821. * load starting at target address. If target address < current window,
  176822. * assume backward scan, load so that target area is top of window.
  176823. * Note that when switching from forward write to forward read, will have
  176824. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176825. */
  176826. if (start_row > ptr->cur_start_row) {
  176827. ptr->cur_start_row = start_row;
  176828. } else {
  176829. /* use long arithmetic here to avoid overflow & unsigned problems */
  176830. long ltemp;
  176831. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176832. if (ltemp < 0)
  176833. ltemp = 0; /* don't fall off front end of file */
  176834. ptr->cur_start_row = (JDIMENSION) ltemp;
  176835. }
  176836. /* Read in the selected part of the array.
  176837. * During the initial write pass, we will do no actual read
  176838. * because the selected part is all undefined.
  176839. */
  176840. do_sarray_io(cinfo, ptr, FALSE);
  176841. }
  176842. /* Ensure the accessed part of the array is defined; prezero if needed.
  176843. * To improve locality of access, we only prezero the part of the array
  176844. * that the caller is about to access, not the entire in-memory array.
  176845. */
  176846. if (ptr->first_undef_row < end_row) {
  176847. if (ptr->first_undef_row < start_row) {
  176848. if (writable) /* writer skipped over a section of array */
  176849. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176850. undef_row = start_row; /* but reader is allowed to read ahead */
  176851. } else {
  176852. undef_row = ptr->first_undef_row;
  176853. }
  176854. if (writable)
  176855. ptr->first_undef_row = end_row;
  176856. if (ptr->pre_zero) {
  176857. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  176858. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176859. end_row -= ptr->cur_start_row;
  176860. while (undef_row < end_row) {
  176861. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176862. undef_row++;
  176863. }
  176864. } else {
  176865. if (! writable) /* reader looking at undefined data */
  176866. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176867. }
  176868. }
  176869. /* Flag the buffer dirty if caller will write in it */
  176870. if (writable)
  176871. ptr->dirty = TRUE;
  176872. /* Return address of proper part of the buffer */
  176873. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176874. }
  176875. METHODDEF(JBLOCKARRAY)
  176876. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  176877. JDIMENSION start_row, JDIMENSION num_rows,
  176878. boolean writable)
  176879. /* Access the part of a virtual block array starting at start_row */
  176880. /* and extending for num_rows rows. writable is true if */
  176881. /* caller intends to modify the accessed area. */
  176882. {
  176883. JDIMENSION end_row = start_row + num_rows;
  176884. JDIMENSION undef_row;
  176885. /* debugging check */
  176886. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  176887. ptr->mem_buffer == NULL)
  176888. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176889. /* Make the desired part of the virtual array accessible */
  176890. if (start_row < ptr->cur_start_row ||
  176891. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  176892. if (! ptr->b_s_open)
  176893. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  176894. /* Flush old buffer contents if necessary */
  176895. if (ptr->dirty) {
  176896. do_barray_io(cinfo, ptr, TRUE);
  176897. ptr->dirty = FALSE;
  176898. }
  176899. /* Decide what part of virtual array to access.
  176900. * Algorithm: if target address > current window, assume forward scan,
  176901. * load starting at target address. If target address < current window,
  176902. * assume backward scan, load so that target area is top of window.
  176903. * Note that when switching from forward write to forward read, will have
  176904. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  176905. */
  176906. if (start_row > ptr->cur_start_row) {
  176907. ptr->cur_start_row = start_row;
  176908. } else {
  176909. /* use long arithmetic here to avoid overflow & unsigned problems */
  176910. long ltemp;
  176911. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  176912. if (ltemp < 0)
  176913. ltemp = 0; /* don't fall off front end of file */
  176914. ptr->cur_start_row = (JDIMENSION) ltemp;
  176915. }
  176916. /* Read in the selected part of the array.
  176917. * During the initial write pass, we will do no actual read
  176918. * because the selected part is all undefined.
  176919. */
  176920. do_barray_io(cinfo, ptr, FALSE);
  176921. }
  176922. /* Ensure the accessed part of the array is defined; prezero if needed.
  176923. * To improve locality of access, we only prezero the part of the array
  176924. * that the caller is about to access, not the entire in-memory array.
  176925. */
  176926. if (ptr->first_undef_row < end_row) {
  176927. if (ptr->first_undef_row < start_row) {
  176928. if (writable) /* writer skipped over a section of array */
  176929. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176930. undef_row = start_row; /* but reader is allowed to read ahead */
  176931. } else {
  176932. undef_row = ptr->first_undef_row;
  176933. }
  176934. if (writable)
  176935. ptr->first_undef_row = end_row;
  176936. if (ptr->pre_zero) {
  176937. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  176938. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  176939. end_row -= ptr->cur_start_row;
  176940. while (undef_row < end_row) {
  176941. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  176942. undef_row++;
  176943. }
  176944. } else {
  176945. if (! writable) /* reader looking at undefined data */
  176946. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  176947. }
  176948. }
  176949. /* Flag the buffer dirty if caller will write in it */
  176950. if (writable)
  176951. ptr->dirty = TRUE;
  176952. /* Return address of proper part of the buffer */
  176953. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  176954. }
  176955. /*
  176956. * Release all objects belonging to a specified pool.
  176957. */
  176958. METHODDEF(void)
  176959. free_pool (j_common_ptr cinfo, int pool_id)
  176960. {
  176961. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  176962. small_pool_ptr shdr_ptr;
  176963. large_pool_ptr lhdr_ptr;
  176964. size_t space_freed;
  176965. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  176966. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  176967. #ifdef MEM_STATS
  176968. if (cinfo->err->trace_level > 1)
  176969. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  176970. #endif
  176971. /* If freeing IMAGE pool, close any virtual arrays first */
  176972. if (pool_id == JPOOL_IMAGE) {
  176973. jvirt_sarray_ptr sptr;
  176974. jvirt_barray_ptr bptr;
  176975. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  176976. if (sptr->b_s_open) { /* there may be no backing store */
  176977. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  176978. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  176979. }
  176980. }
  176981. mem->virt_sarray_list = NULL;
  176982. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  176983. if (bptr->b_s_open) { /* there may be no backing store */
  176984. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  176985. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  176986. }
  176987. }
  176988. mem->virt_barray_list = NULL;
  176989. }
  176990. /* Release large objects */
  176991. lhdr_ptr = mem->large_list[pool_id];
  176992. mem->large_list[pool_id] = NULL;
  176993. while (lhdr_ptr != NULL) {
  176994. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  176995. space_freed = lhdr_ptr->hdr.bytes_used +
  176996. lhdr_ptr->hdr.bytes_left +
  176997. SIZEOF(large_pool_hdr);
  176998. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  176999. mem->total_space_allocated -= space_freed;
  177000. lhdr_ptr = next_lhdr_ptr;
  177001. }
  177002. /* Release small objects */
  177003. shdr_ptr = mem->small_list[pool_id];
  177004. mem->small_list[pool_id] = NULL;
  177005. while (shdr_ptr != NULL) {
  177006. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  177007. space_freed = shdr_ptr->hdr.bytes_used +
  177008. shdr_ptr->hdr.bytes_left +
  177009. SIZEOF(small_pool_hdr);
  177010. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  177011. mem->total_space_allocated -= space_freed;
  177012. shdr_ptr = next_shdr_ptr;
  177013. }
  177014. }
  177015. /*
  177016. * Close up shop entirely.
  177017. * Note that this cannot be called unless cinfo->mem is non-NULL.
  177018. */
  177019. METHODDEF(void)
  177020. self_destruct (j_common_ptr cinfo)
  177021. {
  177022. int pool;
  177023. /* Close all backing store, release all memory.
  177024. * Releasing pools in reverse order might help avoid fragmentation
  177025. * with some (brain-damaged) malloc libraries.
  177026. */
  177027. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177028. free_pool(cinfo, pool);
  177029. }
  177030. /* Release the memory manager control block too. */
  177031. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  177032. cinfo->mem = NULL; /* ensures I will be called only once */
  177033. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177034. }
  177035. /*
  177036. * Memory manager initialization.
  177037. * When this is called, only the error manager pointer is valid in cinfo!
  177038. */
  177039. GLOBAL(void)
  177040. jinit_memory_mgr (j_common_ptr cinfo)
  177041. {
  177042. my_mem_ptr mem;
  177043. long max_to_use;
  177044. int pool;
  177045. size_t test_mac;
  177046. cinfo->mem = NULL; /* for safety if init fails */
  177047. /* Check for configuration errors.
  177048. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177049. * doesn't reflect any real hardware alignment requirement.
  177050. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177051. * in common if and only if X is a power of 2, ie has only one one-bit.
  177052. * Some compilers may give an "unreachable code" warning here; ignore it.
  177053. */
  177054. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177055. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177056. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177057. * a multiple of SIZEOF(ALIGN_TYPE).
  177058. * Again, an "unreachable code" warning may be ignored here.
  177059. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177060. */
  177061. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177062. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177063. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177064. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177065. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177066. /* Attempt to allocate memory manager's control block */
  177067. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177068. if (mem == NULL) {
  177069. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177070. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177071. }
  177072. /* OK, fill in the method pointers */
  177073. mem->pub.alloc_small = alloc_small;
  177074. mem->pub.alloc_large = alloc_large;
  177075. mem->pub.alloc_sarray = alloc_sarray;
  177076. mem->pub.alloc_barray = alloc_barray;
  177077. mem->pub.request_virt_sarray = request_virt_sarray;
  177078. mem->pub.request_virt_barray = request_virt_barray;
  177079. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177080. mem->pub.access_virt_sarray = access_virt_sarray;
  177081. mem->pub.access_virt_barray = access_virt_barray;
  177082. mem->pub.free_pool = free_pool;
  177083. mem->pub.self_destruct = self_destruct;
  177084. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177085. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177086. /* Initialize working state */
  177087. mem->pub.max_memory_to_use = max_to_use;
  177088. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177089. mem->small_list[pool] = NULL;
  177090. mem->large_list[pool] = NULL;
  177091. }
  177092. mem->virt_sarray_list = NULL;
  177093. mem->virt_barray_list = NULL;
  177094. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177095. /* Declare ourselves open for business */
  177096. cinfo->mem = & mem->pub;
  177097. /* Check for an environment variable JPEGMEM; if found, override the
  177098. * default max_memory setting from jpeg_mem_init. Note that the
  177099. * surrounding application may again override this value.
  177100. * If your system doesn't support getenv(), define NO_GETENV to disable
  177101. * this feature.
  177102. */
  177103. #ifndef NO_GETENV
  177104. { char * memenv;
  177105. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177106. char ch = 'x';
  177107. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177108. if (ch == 'm' || ch == 'M')
  177109. max_to_use *= 1000L;
  177110. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177111. }
  177112. }
  177113. }
  177114. #endif
  177115. }
  177116. /*** End of inlined file: jmemmgr.c ***/
  177117. /*** Start of inlined file: jmemnobs.c ***/
  177118. #define JPEG_INTERNALS
  177119. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177120. extern void * malloc JPP((size_t size));
  177121. extern void free JPP((void *ptr));
  177122. #endif
  177123. /*
  177124. * Memory allocation and freeing are controlled by the regular library
  177125. * routines malloc() and free().
  177126. */
  177127. GLOBAL(void *)
  177128. jpeg_get_small (j_common_ptr , size_t sizeofobject)
  177129. {
  177130. return (void *) malloc(sizeofobject);
  177131. }
  177132. GLOBAL(void)
  177133. jpeg_free_small (j_common_ptr , void * object, size_t)
  177134. {
  177135. free(object);
  177136. }
  177137. /*
  177138. * "Large" objects are treated the same as "small" ones.
  177139. * NB: although we include FAR keywords in the routine declarations,
  177140. * this file won't actually work in 80x86 small/medium model; at least,
  177141. * you probably won't be able to process useful-size images in only 64KB.
  177142. */
  177143. GLOBAL(void FAR *)
  177144. jpeg_get_large (j_common_ptr, size_t sizeofobject)
  177145. {
  177146. return (void FAR *) malloc(sizeofobject);
  177147. }
  177148. GLOBAL(void)
  177149. jpeg_free_large (j_common_ptr, void FAR * object, size_t)
  177150. {
  177151. free(object);
  177152. }
  177153. /*
  177154. * This routine computes the total memory space available for allocation.
  177155. * Here we always say, "we got all you want bud!"
  177156. */
  177157. GLOBAL(long)
  177158. jpeg_mem_available (j_common_ptr, long,
  177159. long max_bytes_needed, long)
  177160. {
  177161. return max_bytes_needed;
  177162. }
  177163. /*
  177164. * Backing store (temporary file) management.
  177165. * Since jpeg_mem_available always promised the moon,
  177166. * this should never be called and we can just error out.
  177167. */
  177168. GLOBAL(void)
  177169. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *,
  177170. long )
  177171. {
  177172. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177173. }
  177174. /*
  177175. * These routines take care of any system-dependent initialization and
  177176. * cleanup required. Here, there isn't any.
  177177. */
  177178. GLOBAL(long)
  177179. jpeg_mem_init (j_common_ptr)
  177180. {
  177181. return 0; /* just set max_memory_to_use to 0 */
  177182. }
  177183. GLOBAL(void)
  177184. jpeg_mem_term (j_common_ptr)
  177185. {
  177186. /* no work */
  177187. }
  177188. /*** End of inlined file: jmemnobs.c ***/
  177189. /*** Start of inlined file: jquant1.c ***/
  177190. #define JPEG_INTERNALS
  177191. #ifdef QUANT_1PASS_SUPPORTED
  177192. /*
  177193. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177194. * high quality, colormapped output capability. A 2-pass quantizer usually
  177195. * gives better visual quality; however, for quantized grayscale output this
  177196. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177197. * quantizer, though you can turn it off if you really want to.
  177198. *
  177199. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177200. * image. We use a map consisting of all combinations of Ncolors[i] color
  177201. * values for the i'th component. The Ncolors[] values are chosen so that
  177202. * their product, the total number of colors, is no more than that requested.
  177203. * (In most cases, the product will be somewhat less.)
  177204. *
  177205. * Since the colormap is orthogonal, the representative value for each color
  177206. * component can be determined without considering the other components;
  177207. * then these indexes can be combined into a colormap index by a standard
  177208. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177209. * can be precalculated and stored in the lookup table colorindex[].
  177210. * colorindex[i][j] maps pixel value j in component i to the nearest
  177211. * representative value (grid plane) for that component; this index is
  177212. * multiplied by the array stride for component i, so that the
  177213. * index of the colormap entry closest to a given pixel value is just
  177214. * sum( colorindex[component-number][pixel-component-value] )
  177215. * Aside from being fast, this scheme allows for variable spacing between
  177216. * representative values with no additional lookup cost.
  177217. *
  177218. * If gamma correction has been applied in color conversion, it might be wise
  177219. * to adjust the color grid spacing so that the representative colors are
  177220. * equidistant in linear space. At this writing, gamma correction is not
  177221. * implemented by jdcolor, so nothing is done here.
  177222. */
  177223. /* Declarations for ordered dithering.
  177224. *
  177225. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177226. * dithering is described in many references, for instance Dale Schumacher's
  177227. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  177228. * In place of Schumacher's comparisons against a "threshold" value, we add a
  177229. * "dither" value to the input pixel and then round the result to the nearest
  177230. * output value. The dither value is equivalent to (0.5 - threshold) times
  177231. * the distance between output values. For ordered dithering, we assume that
  177232. * the output colors are equally spaced; if not, results will probably be
  177233. * worse, since the dither may be too much or too little at a given point.
  177234. *
  177235. * The normal calculation would be to form pixel value + dither, range-limit
  177236. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  177237. * We can skip the separate range-limiting step by extending the colorindex
  177238. * table in both directions.
  177239. */
  177240. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  177241. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  177242. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  177243. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  177244. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  177245. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  177246. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  177247. /* Bayer's order-4 dither array. Generated by the code given in
  177248. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  177249. * The values in this array must range from 0 to ODITHER_CELLS-1.
  177250. */
  177251. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  177252. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  177253. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  177254. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  177255. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  177256. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  177257. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  177258. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  177259. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  177260. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  177261. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  177262. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  177263. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  177264. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  177265. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  177266. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  177267. };
  177268. /* Declarations for Floyd-Steinberg dithering.
  177269. *
  177270. * Errors are accumulated into the array fserrors[], at a resolution of
  177271. * 1/16th of a pixel count. The error at a given pixel is propagated
  177272. * to its not-yet-processed neighbors using the standard F-S fractions,
  177273. * ... (here) 7/16
  177274. * 3/16 5/16 1/16
  177275. * We work left-to-right on even rows, right-to-left on odd rows.
  177276. *
  177277. * We can get away with a single array (holding one row's worth of errors)
  177278. * by using it to store the current row's errors at pixel columns not yet
  177279. * processed, but the next row's errors at columns already processed. We
  177280. * need only a few extra variables to hold the errors immediately around the
  177281. * current column. (If we are lucky, those variables are in registers, but
  177282. * even if not, they're probably cheaper to access than array elements are.)
  177283. *
  177284. * The fserrors[] array is indexed [component#][position].
  177285. * We provide (#columns + 2) entries per component; the extra entry at each
  177286. * end saves us from special-casing the first and last pixels.
  177287. *
  177288. * Note: on a wide image, we might not have enough room in a PC's near data
  177289. * segment to hold the error array; so it is allocated with alloc_large.
  177290. */
  177291. #if BITS_IN_JSAMPLE == 8
  177292. typedef INT16 FSERROR; /* 16 bits should be enough */
  177293. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  177294. #else
  177295. typedef INT32 FSERROR; /* may need more than 16 bits */
  177296. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  177297. #endif
  177298. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  177299. /* Private subobject */
  177300. #define MAX_Q_COMPS 4 /* max components I can handle */
  177301. typedef struct {
  177302. struct jpeg_color_quantizer pub; /* public fields */
  177303. /* Initially allocated colormap is saved here */
  177304. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  177305. int sv_actual; /* number of entries in use */
  177306. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  177307. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  177308. * premultiplied as described above. Since colormap indexes must fit into
  177309. * JSAMPLEs, the entries of this array will too.
  177310. */
  177311. boolean is_padded; /* is the colorindex padded for odither? */
  177312. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  177313. /* Variables for ordered dithering */
  177314. int row_index; /* cur row's vertical index in dither matrix */
  177315. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  177316. /* Variables for Floyd-Steinberg dithering */
  177317. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  177318. boolean on_odd_row; /* flag to remember which row we are on */
  177319. } my_cquantizer;
  177320. typedef my_cquantizer * my_cquantize_ptr;
  177321. /*
  177322. * Policy-making subroutines for create_colormap and create_colorindex.
  177323. * These routines determine the colormap to be used. The rest of the module
  177324. * only assumes that the colormap is orthogonal.
  177325. *
  177326. * * select_ncolors decides how to divvy up the available colors
  177327. * among the components.
  177328. * * output_value defines the set of representative values for a component.
  177329. * * largest_input_value defines the mapping from input values to
  177330. * representative values for a component.
  177331. * Note that the latter two routines may impose different policies for
  177332. * different components, though this is not currently done.
  177333. */
  177334. LOCAL(int)
  177335. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  177336. /* Determine allocation of desired colors to components, */
  177337. /* and fill in Ncolors[] array to indicate choice. */
  177338. /* Return value is total number of colors (product of Ncolors[] values). */
  177339. {
  177340. int nc = cinfo->out_color_components; /* number of color components */
  177341. int max_colors = cinfo->desired_number_of_colors;
  177342. int total_colors, iroot, i, j;
  177343. boolean changed;
  177344. long temp;
  177345. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  177346. /* We can allocate at least the nc'th root of max_colors per component. */
  177347. /* Compute floor(nc'th root of max_colors). */
  177348. iroot = 1;
  177349. do {
  177350. iroot++;
  177351. temp = iroot; /* set temp = iroot ** nc */
  177352. for (i = 1; i < nc; i++)
  177353. temp *= iroot;
  177354. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  177355. iroot--; /* now iroot = floor(root) */
  177356. /* Must have at least 2 color values per component */
  177357. if (iroot < 2)
  177358. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  177359. /* Initialize to iroot color values for each component */
  177360. total_colors = 1;
  177361. for (i = 0; i < nc; i++) {
  177362. Ncolors[i] = iroot;
  177363. total_colors *= iroot;
  177364. }
  177365. /* We may be able to increment the count for one or more components without
  177366. * exceeding max_colors, though we know not all can be incremented.
  177367. * Sometimes, the first component can be incremented more than once!
  177368. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  177369. * In RGB colorspace, try to increment G first, then R, then B.
  177370. */
  177371. do {
  177372. changed = FALSE;
  177373. for (i = 0; i < nc; i++) {
  177374. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  177375. /* calculate new total_colors if Ncolors[j] is incremented */
  177376. temp = total_colors / Ncolors[j];
  177377. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  177378. if (temp > (long) max_colors)
  177379. break; /* won't fit, done with this pass */
  177380. Ncolors[j]++; /* OK, apply the increment */
  177381. total_colors = (int) temp;
  177382. changed = TRUE;
  177383. }
  177384. } while (changed);
  177385. return total_colors;
  177386. }
  177387. LOCAL(int)
  177388. output_value (j_decompress_ptr, int, int j, int maxj)
  177389. /* Return j'th output value, where j will range from 0 to maxj */
  177390. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  177391. {
  177392. /* We always provide values 0 and MAXJSAMPLE for each component;
  177393. * any additional values are equally spaced between these limits.
  177394. * (Forcing the upper and lower values to the limits ensures that
  177395. * dithering can't produce a color outside the selected gamut.)
  177396. */
  177397. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  177398. }
  177399. LOCAL(int)
  177400. largest_input_value (j_decompress_ptr, int, int j, int maxj)
  177401. /* Return largest input value that should map to j'th output value */
  177402. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  177403. {
  177404. /* Breakpoints are halfway between values returned by output_value */
  177405. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  177406. }
  177407. /*
  177408. * Create the colormap.
  177409. */
  177410. LOCAL(void)
  177411. create_colormap (j_decompress_ptr cinfo)
  177412. {
  177413. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177414. JSAMPARRAY colormap; /* Created colormap */
  177415. int total_colors; /* Number of distinct output colors */
  177416. int i,j,k, nci, blksize, blkdist, ptr, val;
  177417. /* Select number of colors for each component */
  177418. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  177419. /* Report selected color counts */
  177420. if (cinfo->out_color_components == 3)
  177421. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  177422. total_colors, cquantize->Ncolors[0],
  177423. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  177424. else
  177425. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  177426. /* Allocate and fill in the colormap. */
  177427. /* The colors are ordered in the map in standard row-major order, */
  177428. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  177429. colormap = (*cinfo->mem->alloc_sarray)
  177430. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177431. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  177432. /* blksize is number of adjacent repeated entries for a component */
  177433. /* blkdist is distance between groups of identical entries for a component */
  177434. blkdist = total_colors;
  177435. for (i = 0; i < cinfo->out_color_components; i++) {
  177436. /* fill in colormap entries for i'th color component */
  177437. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177438. blksize = blkdist / nci;
  177439. for (j = 0; j < nci; j++) {
  177440. /* Compute j'th output value (out of nci) for component */
  177441. val = output_value(cinfo, i, j, nci-1);
  177442. /* Fill in all colormap entries that have this value of this component */
  177443. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  177444. /* fill in blksize entries beginning at ptr */
  177445. for (k = 0; k < blksize; k++)
  177446. colormap[i][ptr+k] = (JSAMPLE) val;
  177447. }
  177448. }
  177449. blkdist = blksize; /* blksize of this color is blkdist of next */
  177450. }
  177451. /* Save the colormap in private storage,
  177452. * where it will survive color quantization mode changes.
  177453. */
  177454. cquantize->sv_colormap = colormap;
  177455. cquantize->sv_actual = total_colors;
  177456. }
  177457. /*
  177458. * Create the color index table.
  177459. */
  177460. LOCAL(void)
  177461. create_colorindex (j_decompress_ptr cinfo)
  177462. {
  177463. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177464. JSAMPROW indexptr;
  177465. int i,j,k, nci, blksize, val, pad;
  177466. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  177467. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  177468. * This is not necessary in the other dithering modes. However, we
  177469. * flag whether it was done in case user changes dithering mode.
  177470. */
  177471. if (cinfo->dither_mode == JDITHER_ORDERED) {
  177472. pad = MAXJSAMPLE*2;
  177473. cquantize->is_padded = TRUE;
  177474. } else {
  177475. pad = 0;
  177476. cquantize->is_padded = FALSE;
  177477. }
  177478. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  177479. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177480. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  177481. (JDIMENSION) cinfo->out_color_components);
  177482. /* blksize is number of adjacent repeated entries for a component */
  177483. blksize = cquantize->sv_actual;
  177484. for (i = 0; i < cinfo->out_color_components; i++) {
  177485. /* fill in colorindex entries for i'th color component */
  177486. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177487. blksize = blksize / nci;
  177488. /* adjust colorindex pointers to provide padding at negative indexes. */
  177489. if (pad)
  177490. cquantize->colorindex[i] += MAXJSAMPLE;
  177491. /* in loop, val = index of current output value, */
  177492. /* and k = largest j that maps to current val */
  177493. indexptr = cquantize->colorindex[i];
  177494. val = 0;
  177495. k = largest_input_value(cinfo, i, 0, nci-1);
  177496. for (j = 0; j <= MAXJSAMPLE; j++) {
  177497. while (j > k) /* advance val if past boundary */
  177498. k = largest_input_value(cinfo, i, ++val, nci-1);
  177499. /* premultiply so that no multiplication needed in main processing */
  177500. indexptr[j] = (JSAMPLE) (val * blksize);
  177501. }
  177502. /* Pad at both ends if necessary */
  177503. if (pad)
  177504. for (j = 1; j <= MAXJSAMPLE; j++) {
  177505. indexptr[-j] = indexptr[0];
  177506. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  177507. }
  177508. }
  177509. }
  177510. /*
  177511. * Create an ordered-dither array for a component having ncolors
  177512. * distinct output values.
  177513. */
  177514. LOCAL(ODITHER_MATRIX_PTR)
  177515. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  177516. {
  177517. ODITHER_MATRIX_PTR odither;
  177518. int j,k;
  177519. INT32 num,den;
  177520. odither = (ODITHER_MATRIX_PTR)
  177521. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177522. SIZEOF(ODITHER_MATRIX));
  177523. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  177524. * Hence the dither value for the matrix cell with fill order f
  177525. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  177526. * On 16-bit-int machine, be careful to avoid overflow.
  177527. */
  177528. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  177529. for (j = 0; j < ODITHER_SIZE; j++) {
  177530. for (k = 0; k < ODITHER_SIZE; k++) {
  177531. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  177532. * MAXJSAMPLE;
  177533. /* Ensure round towards zero despite C's lack of consistency
  177534. * about rounding negative values in integer division...
  177535. */
  177536. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  177537. }
  177538. }
  177539. return odither;
  177540. }
  177541. /*
  177542. * Create the ordered-dither tables.
  177543. * Components having the same number of representative colors may
  177544. * share a dither table.
  177545. */
  177546. LOCAL(void)
  177547. create_odither_tables (j_decompress_ptr cinfo)
  177548. {
  177549. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177550. ODITHER_MATRIX_PTR odither;
  177551. int i, j, nci;
  177552. for (i = 0; i < cinfo->out_color_components; i++) {
  177553. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  177554. odither = NULL; /* search for matching prior component */
  177555. for (j = 0; j < i; j++) {
  177556. if (nci == cquantize->Ncolors[j]) {
  177557. odither = cquantize->odither[j];
  177558. break;
  177559. }
  177560. }
  177561. if (odither == NULL) /* need a new table? */
  177562. odither = make_odither_array(cinfo, nci);
  177563. cquantize->odither[i] = odither;
  177564. }
  177565. }
  177566. /*
  177567. * Map some rows of pixels to the output colormapped representation.
  177568. */
  177569. METHODDEF(void)
  177570. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177571. JSAMPARRAY output_buf, int num_rows)
  177572. /* General case, no dithering */
  177573. {
  177574. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177575. JSAMPARRAY colorindex = cquantize->colorindex;
  177576. register int pixcode, ci;
  177577. register JSAMPROW ptrin, ptrout;
  177578. int row;
  177579. JDIMENSION col;
  177580. JDIMENSION width = cinfo->output_width;
  177581. register int nc = cinfo->out_color_components;
  177582. for (row = 0; row < num_rows; row++) {
  177583. ptrin = input_buf[row];
  177584. ptrout = output_buf[row];
  177585. for (col = width; col > 0; col--) {
  177586. pixcode = 0;
  177587. for (ci = 0; ci < nc; ci++) {
  177588. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  177589. }
  177590. *ptrout++ = (JSAMPLE) pixcode;
  177591. }
  177592. }
  177593. }
  177594. METHODDEF(void)
  177595. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177596. JSAMPARRAY output_buf, int num_rows)
  177597. /* Fast path for out_color_components==3, no dithering */
  177598. {
  177599. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177600. register int pixcode;
  177601. register JSAMPROW ptrin, ptrout;
  177602. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177603. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177604. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177605. int row;
  177606. JDIMENSION col;
  177607. JDIMENSION width = cinfo->output_width;
  177608. for (row = 0; row < num_rows; row++) {
  177609. ptrin = input_buf[row];
  177610. ptrout = output_buf[row];
  177611. for (col = width; col > 0; col--) {
  177612. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  177613. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  177614. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  177615. *ptrout++ = (JSAMPLE) pixcode;
  177616. }
  177617. }
  177618. }
  177619. METHODDEF(void)
  177620. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177621. JSAMPARRAY output_buf, int num_rows)
  177622. /* General case, with ordered dithering */
  177623. {
  177624. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177625. register JSAMPROW input_ptr;
  177626. register JSAMPROW output_ptr;
  177627. JSAMPROW colorindex_ci;
  177628. int * dither; /* points to active row of dither matrix */
  177629. int row_index, col_index; /* current indexes into dither matrix */
  177630. int nc = cinfo->out_color_components;
  177631. int ci;
  177632. int row;
  177633. JDIMENSION col;
  177634. JDIMENSION width = cinfo->output_width;
  177635. for (row = 0; row < num_rows; row++) {
  177636. /* Initialize output values to 0 so can process components separately */
  177637. jzero_far((void FAR *) output_buf[row],
  177638. (size_t) (width * SIZEOF(JSAMPLE)));
  177639. row_index = cquantize->row_index;
  177640. for (ci = 0; ci < nc; ci++) {
  177641. input_ptr = input_buf[row] + ci;
  177642. output_ptr = output_buf[row];
  177643. colorindex_ci = cquantize->colorindex[ci];
  177644. dither = cquantize->odither[ci][row_index];
  177645. col_index = 0;
  177646. for (col = width; col > 0; col--) {
  177647. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  177648. * select output value, accumulate into output code for this pixel.
  177649. * Range-limiting need not be done explicitly, as we have extended
  177650. * the colorindex table to produce the right answers for out-of-range
  177651. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  177652. * required amount of padding.
  177653. */
  177654. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  177655. input_ptr += nc;
  177656. output_ptr++;
  177657. col_index = (col_index + 1) & ODITHER_MASK;
  177658. }
  177659. }
  177660. /* Advance row index for next row */
  177661. row_index = (row_index + 1) & ODITHER_MASK;
  177662. cquantize->row_index = row_index;
  177663. }
  177664. }
  177665. METHODDEF(void)
  177666. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177667. JSAMPARRAY output_buf, int num_rows)
  177668. /* Fast path for out_color_components==3, with ordered dithering */
  177669. {
  177670. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177671. register int pixcode;
  177672. register JSAMPROW input_ptr;
  177673. register JSAMPROW output_ptr;
  177674. JSAMPROW colorindex0 = cquantize->colorindex[0];
  177675. JSAMPROW colorindex1 = cquantize->colorindex[1];
  177676. JSAMPROW colorindex2 = cquantize->colorindex[2];
  177677. int * dither0; /* points to active row of dither matrix */
  177678. int * dither1;
  177679. int * dither2;
  177680. int row_index, col_index; /* current indexes into dither matrix */
  177681. int row;
  177682. JDIMENSION col;
  177683. JDIMENSION width = cinfo->output_width;
  177684. for (row = 0; row < num_rows; row++) {
  177685. row_index = cquantize->row_index;
  177686. input_ptr = input_buf[row];
  177687. output_ptr = output_buf[row];
  177688. dither0 = cquantize->odither[0][row_index];
  177689. dither1 = cquantize->odither[1][row_index];
  177690. dither2 = cquantize->odither[2][row_index];
  177691. col_index = 0;
  177692. for (col = width; col > 0; col--) {
  177693. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  177694. dither0[col_index]]);
  177695. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  177696. dither1[col_index]]);
  177697. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  177698. dither2[col_index]]);
  177699. *output_ptr++ = (JSAMPLE) pixcode;
  177700. col_index = (col_index + 1) & ODITHER_MASK;
  177701. }
  177702. row_index = (row_index + 1) & ODITHER_MASK;
  177703. cquantize->row_index = row_index;
  177704. }
  177705. }
  177706. METHODDEF(void)
  177707. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  177708. JSAMPARRAY output_buf, int num_rows)
  177709. /* General case, with Floyd-Steinberg dithering */
  177710. {
  177711. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177712. register LOCFSERROR cur; /* current error or pixel value */
  177713. LOCFSERROR belowerr; /* error for pixel below cur */
  177714. LOCFSERROR bpreverr; /* error for below/prev col */
  177715. LOCFSERROR bnexterr; /* error for below/next col */
  177716. LOCFSERROR delta;
  177717. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  177718. register JSAMPROW input_ptr;
  177719. register JSAMPROW output_ptr;
  177720. JSAMPROW colorindex_ci;
  177721. JSAMPROW colormap_ci;
  177722. int pixcode;
  177723. int nc = cinfo->out_color_components;
  177724. int dir; /* 1 for left-to-right, -1 for right-to-left */
  177725. int dirnc; /* dir * nc */
  177726. int ci;
  177727. int row;
  177728. JDIMENSION col;
  177729. JDIMENSION width = cinfo->output_width;
  177730. JSAMPLE *range_limit = cinfo->sample_range_limit;
  177731. SHIFT_TEMPS
  177732. for (row = 0; row < num_rows; row++) {
  177733. /* Initialize output values to 0 so can process components separately */
  177734. jzero_far((void FAR *) output_buf[row],
  177735. (size_t) (width * SIZEOF(JSAMPLE)));
  177736. for (ci = 0; ci < nc; ci++) {
  177737. input_ptr = input_buf[row] + ci;
  177738. output_ptr = output_buf[row];
  177739. if (cquantize->on_odd_row) {
  177740. /* work right to left in this row */
  177741. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  177742. output_ptr += width-1;
  177743. dir = -1;
  177744. dirnc = -nc;
  177745. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  177746. } else {
  177747. /* work left to right in this row */
  177748. dir = 1;
  177749. dirnc = nc;
  177750. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  177751. }
  177752. colorindex_ci = cquantize->colorindex[ci];
  177753. colormap_ci = cquantize->sv_colormap[ci];
  177754. /* Preset error values: no error propagated to first pixel from left */
  177755. cur = 0;
  177756. /* and no error propagated to row below yet */
  177757. belowerr = bpreverr = 0;
  177758. for (col = width; col > 0; col--) {
  177759. /* cur holds the error propagated from the previous pixel on the
  177760. * current line. Add the error propagated from the previous line
  177761. * to form the complete error correction term for this pixel, and
  177762. * round the error term (which is expressed * 16) to an integer.
  177763. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  177764. * for either sign of the error value.
  177765. * Note: errorptr points to *previous* column's array entry.
  177766. */
  177767. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  177768. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  177769. * The maximum error is +- MAXJSAMPLE; this sets the required size
  177770. * of the range_limit array.
  177771. */
  177772. cur += GETJSAMPLE(*input_ptr);
  177773. cur = GETJSAMPLE(range_limit[cur]);
  177774. /* Select output value, accumulate into output code for this pixel */
  177775. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  177776. *output_ptr += (JSAMPLE) pixcode;
  177777. /* Compute actual representation error at this pixel */
  177778. /* Note: we can do this even though we don't have the final */
  177779. /* pixel code, because the colormap is orthogonal. */
  177780. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  177781. /* Compute error fractions to be propagated to adjacent pixels.
  177782. * Add these into the running sums, and simultaneously shift the
  177783. * next-line error sums left by 1 column.
  177784. */
  177785. bnexterr = cur;
  177786. delta = cur * 2;
  177787. cur += delta; /* form error * 3 */
  177788. errorptr[0] = (FSERROR) (bpreverr + cur);
  177789. cur += delta; /* form error * 5 */
  177790. bpreverr = belowerr + cur;
  177791. belowerr = bnexterr;
  177792. cur += delta; /* form error * 7 */
  177793. /* At this point cur contains the 7/16 error value to be propagated
  177794. * to the next pixel on the current line, and all the errors for the
  177795. * next line have been shifted over. We are therefore ready to move on.
  177796. */
  177797. input_ptr += dirnc; /* advance input ptr to next column */
  177798. output_ptr += dir; /* advance output ptr to next column */
  177799. errorptr += dir; /* advance errorptr to current column */
  177800. }
  177801. /* Post-loop cleanup: we must unload the final error value into the
  177802. * final fserrors[] entry. Note we need not unload belowerr because
  177803. * it is for the dummy column before or after the actual array.
  177804. */
  177805. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  177806. }
  177807. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  177808. }
  177809. }
  177810. /*
  177811. * Allocate workspace for Floyd-Steinberg errors.
  177812. */
  177813. LOCAL(void)
  177814. alloc_fs_workspace (j_decompress_ptr cinfo)
  177815. {
  177816. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177817. size_t arraysize;
  177818. int i;
  177819. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177820. for (i = 0; i < cinfo->out_color_components; i++) {
  177821. cquantize->fserrors[i] = (FSERRPTR)
  177822. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  177823. }
  177824. }
  177825. /*
  177826. * Initialize for one-pass color quantization.
  177827. */
  177828. METHODDEF(void)
  177829. start_pass_1_quant (j_decompress_ptr cinfo, boolean)
  177830. {
  177831. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  177832. size_t arraysize;
  177833. int i;
  177834. /* Install my colormap. */
  177835. cinfo->colormap = cquantize->sv_colormap;
  177836. cinfo->actual_number_of_colors = cquantize->sv_actual;
  177837. /* Initialize for desired dithering mode. */
  177838. switch (cinfo->dither_mode) {
  177839. case JDITHER_NONE:
  177840. if (cinfo->out_color_components == 3)
  177841. cquantize->pub.color_quantize = color_quantize3;
  177842. else
  177843. cquantize->pub.color_quantize = color_quantize;
  177844. break;
  177845. case JDITHER_ORDERED:
  177846. if (cinfo->out_color_components == 3)
  177847. cquantize->pub.color_quantize = quantize3_ord_dither;
  177848. else
  177849. cquantize->pub.color_quantize = quantize_ord_dither;
  177850. cquantize->row_index = 0; /* initialize state for ordered dither */
  177851. /* If user changed to ordered dither from another mode,
  177852. * we must recreate the color index table with padding.
  177853. * This will cost extra space, but probably isn't very likely.
  177854. */
  177855. if (! cquantize->is_padded)
  177856. create_colorindex(cinfo);
  177857. /* Create ordered-dither tables if we didn't already. */
  177858. if (cquantize->odither[0] == NULL)
  177859. create_odither_tables(cinfo);
  177860. break;
  177861. case JDITHER_FS:
  177862. cquantize->pub.color_quantize = quantize_fs_dither;
  177863. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  177864. /* Allocate Floyd-Steinberg workspace if didn't already. */
  177865. if (cquantize->fserrors[0] == NULL)
  177866. alloc_fs_workspace(cinfo);
  177867. /* Initialize the propagated errors to zero. */
  177868. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  177869. for (i = 0; i < cinfo->out_color_components; i++)
  177870. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  177871. break;
  177872. default:
  177873. ERREXIT(cinfo, JERR_NOT_COMPILED);
  177874. break;
  177875. }
  177876. }
  177877. /*
  177878. * Finish up at the end of the pass.
  177879. */
  177880. METHODDEF(void)
  177881. finish_pass_1_quant (j_decompress_ptr)
  177882. {
  177883. /* no work in 1-pass case */
  177884. }
  177885. /*
  177886. * Switch to a new external colormap between output passes.
  177887. * Shouldn't get to this module!
  177888. */
  177889. METHODDEF(void)
  177890. new_color_map_1_quant (j_decompress_ptr cinfo)
  177891. {
  177892. ERREXIT(cinfo, JERR_MODE_CHANGE);
  177893. }
  177894. /*
  177895. * Module initialization routine for 1-pass color quantization.
  177896. */
  177897. GLOBAL(void)
  177898. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  177899. {
  177900. my_cquantize_ptr cquantize;
  177901. cquantize = (my_cquantize_ptr)
  177902. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  177903. SIZEOF(my_cquantizer));
  177904. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  177905. cquantize->pub.start_pass = start_pass_1_quant;
  177906. cquantize->pub.finish_pass = finish_pass_1_quant;
  177907. cquantize->pub.new_color_map = new_color_map_1_quant;
  177908. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  177909. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  177910. /* Make sure my internal arrays won't overflow */
  177911. if (cinfo->out_color_components > MAX_Q_COMPS)
  177912. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  177913. /* Make sure colormap indexes can be represented by JSAMPLEs */
  177914. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  177915. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  177916. /* Create the colormap and color index table. */
  177917. create_colormap(cinfo);
  177918. create_colorindex(cinfo);
  177919. /* Allocate Floyd-Steinberg workspace now if requested.
  177920. * We do this now since it is FAR storage and may affect the memory
  177921. * manager's space calculations. If the user changes to FS dither
  177922. * mode in a later pass, we will allocate the space then, and will
  177923. * possibly overrun the max_memory_to_use setting.
  177924. */
  177925. if (cinfo->dither_mode == JDITHER_FS)
  177926. alloc_fs_workspace(cinfo);
  177927. }
  177928. #endif /* QUANT_1PASS_SUPPORTED */
  177929. /*** End of inlined file: jquant1.c ***/
  177930. /*** Start of inlined file: jquant2.c ***/
  177931. #define JPEG_INTERNALS
  177932. #ifdef QUANT_2PASS_SUPPORTED
  177933. /*
  177934. * This module implements the well-known Heckbert paradigm for color
  177935. * quantization. Most of the ideas used here can be traced back to
  177936. * Heckbert's seminal paper
  177937. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  177938. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  177939. *
  177940. * In the first pass over the image, we accumulate a histogram showing the
  177941. * usage count of each possible color. To keep the histogram to a reasonable
  177942. * size, we reduce the precision of the input; typical practice is to retain
  177943. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  177944. * in the same histogram cell.
  177945. *
  177946. * Next, the color-selection step begins with a box representing the whole
  177947. * color space, and repeatedly splits the "largest" remaining box until we
  177948. * have as many boxes as desired colors. Then the mean color in each
  177949. * remaining box becomes one of the possible output colors.
  177950. *
  177951. * The second pass over the image maps each input pixel to the closest output
  177952. * color (optionally after applying a Floyd-Steinberg dithering correction).
  177953. * This mapping is logically trivial, but making it go fast enough requires
  177954. * considerable care.
  177955. *
  177956. * Heckbert-style quantizers vary a good deal in their policies for choosing
  177957. * the "largest" box and deciding where to cut it. The particular policies
  177958. * used here have proved out well in experimental comparisons, but better ones
  177959. * may yet be found.
  177960. *
  177961. * In earlier versions of the IJG code, this module quantized in YCbCr color
  177962. * space, processing the raw upsampled data without a color conversion step.
  177963. * This allowed the color conversion math to be done only once per colormap
  177964. * entry, not once per pixel. However, that optimization precluded other
  177965. * useful optimizations (such as merging color conversion with upsampling)
  177966. * and it also interfered with desired capabilities such as quantizing to an
  177967. * externally-supplied colormap. We have therefore abandoned that approach.
  177968. * The present code works in the post-conversion color space, typically RGB.
  177969. *
  177970. * To improve the visual quality of the results, we actually work in scaled
  177971. * RGB space, giving G distances more weight than R, and R in turn more than
  177972. * B. To do everything in integer math, we must use integer scale factors.
  177973. * The 2/3/1 scale factors used here correspond loosely to the relative
  177974. * weights of the colors in the NTSC grayscale equation.
  177975. * If you want to use this code to quantize a non-RGB color space, you'll
  177976. * probably need to change these scale factors.
  177977. */
  177978. #define R_SCALE 2 /* scale R distances by this much */
  177979. #define G_SCALE 3 /* scale G distances by this much */
  177980. #define B_SCALE 1 /* and B by this much */
  177981. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  177982. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  177983. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  177984. * you'll get compile errors until you extend this logic. In that case
  177985. * you'll probably want to tweak the histogram sizes too.
  177986. */
  177987. #if RGB_RED == 0
  177988. #define C0_SCALE R_SCALE
  177989. #endif
  177990. #if RGB_BLUE == 0
  177991. #define C0_SCALE B_SCALE
  177992. #endif
  177993. #if RGB_GREEN == 1
  177994. #define C1_SCALE G_SCALE
  177995. #endif
  177996. #if RGB_RED == 2
  177997. #define C2_SCALE R_SCALE
  177998. #endif
  177999. #if RGB_BLUE == 2
  178000. #define C2_SCALE B_SCALE
  178001. #endif
  178002. /*
  178003. * First we have the histogram data structure and routines for creating it.
  178004. *
  178005. * The number of bits of precision can be adjusted by changing these symbols.
  178006. * We recommend keeping 6 bits for G and 5 each for R and B.
  178007. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  178008. * better results; if you are short of memory, 5 bits all around will save
  178009. * some space but degrade the results.
  178010. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  178011. * (preferably unsigned long) for each cell. In practice this is overkill;
  178012. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  178013. * and clamping those that do overflow to the maximum value will give close-
  178014. * enough results. This reduces the recommended histogram size from 256Kb
  178015. * to 128Kb, which is a useful savings on PC-class machines.
  178016. * (In the second pass the histogram space is re-used for pixel mapping data;
  178017. * in that capacity, each cell must be able to store zero to the number of
  178018. * desired colors. 16 bits/cell is plenty for that too.)
  178019. * Since the JPEG code is intended to run in small memory model on 80x86
  178020. * machines, we can't just allocate the histogram in one chunk. Instead
  178021. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  178022. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  178023. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  178024. * on 80x86 machines, the pointer row is in near memory but the actual
  178025. * arrays are in far memory (same arrangement as we use for image arrays).
  178026. */
  178027. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  178028. /* These will do the right thing for either R,G,B or B,G,R color order,
  178029. * but you may not like the results for other color orders.
  178030. */
  178031. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  178032. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  178033. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178034. /* Number of elements along histogram axes. */
  178035. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178036. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178037. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178038. /* These are the amounts to shift an input value to get a histogram index. */
  178039. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178040. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178041. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178042. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178043. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178044. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178045. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178046. typedef hist2d * hist3d; /* type for top-level pointer */
  178047. /* Declarations for Floyd-Steinberg dithering.
  178048. *
  178049. * Errors are accumulated into the array fserrors[], at a resolution of
  178050. * 1/16th of a pixel count. The error at a given pixel is propagated
  178051. * to its not-yet-processed neighbors using the standard F-S fractions,
  178052. * ... (here) 7/16
  178053. * 3/16 5/16 1/16
  178054. * We work left-to-right on even rows, right-to-left on odd rows.
  178055. *
  178056. * We can get away with a single array (holding one row's worth of errors)
  178057. * by using it to store the current row's errors at pixel columns not yet
  178058. * processed, but the next row's errors at columns already processed. We
  178059. * need only a few extra variables to hold the errors immediately around the
  178060. * current column. (If we are lucky, those variables are in registers, but
  178061. * even if not, they're probably cheaper to access than array elements are.)
  178062. *
  178063. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178064. * each end saves us from special-casing the first and last pixels.
  178065. * Each entry is three values long, one value for each color component.
  178066. *
  178067. * Note: on a wide image, we might not have enough room in a PC's near data
  178068. * segment to hold the error array; so it is allocated with alloc_large.
  178069. */
  178070. #if BITS_IN_JSAMPLE == 8
  178071. typedef INT16 FSERROR; /* 16 bits should be enough */
  178072. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178073. #else
  178074. typedef INT32 FSERROR; /* may need more than 16 bits */
  178075. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178076. #endif
  178077. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178078. /* Private subobject */
  178079. typedef struct {
  178080. struct jpeg_color_quantizer pub; /* public fields */
  178081. /* Space for the eventually created colormap is stashed here */
  178082. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178083. int desired; /* desired # of colors = size of colormap */
  178084. /* Variables for accumulating image statistics */
  178085. hist3d histogram; /* pointer to the histogram */
  178086. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178087. /* Variables for Floyd-Steinberg dithering */
  178088. FSERRPTR fserrors; /* accumulated errors */
  178089. boolean on_odd_row; /* flag to remember which row we are on */
  178090. int * error_limiter; /* table for clamping the applied error */
  178091. } my_cquantizer2;
  178092. typedef my_cquantizer2 * my_cquantize_ptr2;
  178093. /*
  178094. * Prescan some rows of pixels.
  178095. * In this module the prescan simply updates the histogram, which has been
  178096. * initialized to zeroes by start_pass.
  178097. * An output_buf parameter is required by the method signature, but no data
  178098. * is actually output (in fact the buffer controller is probably passing a
  178099. * NULL pointer).
  178100. */
  178101. METHODDEF(void)
  178102. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178103. JSAMPARRAY, int num_rows)
  178104. {
  178105. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178106. register JSAMPROW ptr;
  178107. register histptr histp;
  178108. register hist3d histogram = cquantize->histogram;
  178109. int row;
  178110. JDIMENSION col;
  178111. JDIMENSION width = cinfo->output_width;
  178112. for (row = 0; row < num_rows; row++) {
  178113. ptr = input_buf[row];
  178114. for (col = width; col > 0; col--) {
  178115. /* get pixel value and index into the histogram */
  178116. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178117. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178118. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178119. /* increment, check for overflow and undo increment if so. */
  178120. if (++(*histp) <= 0)
  178121. (*histp)--;
  178122. ptr += 3;
  178123. }
  178124. }
  178125. }
  178126. /*
  178127. * Next we have the really interesting routines: selection of a colormap
  178128. * given the completed histogram.
  178129. * These routines work with a list of "boxes", each representing a rectangular
  178130. * subset of the input color space (to histogram precision).
  178131. */
  178132. typedef struct {
  178133. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178134. int c0min, c0max;
  178135. int c1min, c1max;
  178136. int c2min, c2max;
  178137. /* The volume (actually 2-norm) of the box */
  178138. INT32 volume;
  178139. /* The number of nonzero histogram cells within this box */
  178140. long colorcount;
  178141. } box;
  178142. typedef box * boxptr;
  178143. LOCAL(boxptr)
  178144. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178145. /* Find the splittable box with the largest color population */
  178146. /* Returns NULL if no splittable boxes remain */
  178147. {
  178148. register boxptr boxp;
  178149. register int i;
  178150. register long maxc = 0;
  178151. boxptr which = NULL;
  178152. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178153. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178154. which = boxp;
  178155. maxc = boxp->colorcount;
  178156. }
  178157. }
  178158. return which;
  178159. }
  178160. LOCAL(boxptr)
  178161. find_biggest_volume (boxptr boxlist, int numboxes)
  178162. /* Find the splittable box with the largest (scaled) volume */
  178163. /* Returns NULL if no splittable boxes remain */
  178164. {
  178165. register boxptr boxp;
  178166. register int i;
  178167. register INT32 maxv = 0;
  178168. boxptr which = NULL;
  178169. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178170. if (boxp->volume > maxv) {
  178171. which = boxp;
  178172. maxv = boxp->volume;
  178173. }
  178174. }
  178175. return which;
  178176. }
  178177. LOCAL(void)
  178178. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178179. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178180. /* and recompute its volume and population */
  178181. {
  178182. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178183. hist3d histogram = cquantize->histogram;
  178184. histptr histp;
  178185. int c0,c1,c2;
  178186. int c0min,c0max,c1min,c1max,c2min,c2max;
  178187. INT32 dist0,dist1,dist2;
  178188. long ccount;
  178189. c0min = boxp->c0min; c0max = boxp->c0max;
  178190. c1min = boxp->c1min; c1max = boxp->c1max;
  178191. c2min = boxp->c2min; c2max = boxp->c2max;
  178192. if (c0max > c0min)
  178193. for (c0 = c0min; c0 <= c0max; c0++)
  178194. for (c1 = c1min; c1 <= c1max; c1++) {
  178195. histp = & histogram[c0][c1][c2min];
  178196. for (c2 = c2min; c2 <= c2max; c2++)
  178197. if (*histp++ != 0) {
  178198. boxp->c0min = c0min = c0;
  178199. goto have_c0min;
  178200. }
  178201. }
  178202. have_c0min:
  178203. if (c0max > c0min)
  178204. for (c0 = c0max; c0 >= c0min; c0--)
  178205. for (c1 = c1min; c1 <= c1max; c1++) {
  178206. histp = & histogram[c0][c1][c2min];
  178207. for (c2 = c2min; c2 <= c2max; c2++)
  178208. if (*histp++ != 0) {
  178209. boxp->c0max = c0max = c0;
  178210. goto have_c0max;
  178211. }
  178212. }
  178213. have_c0max:
  178214. if (c1max > c1min)
  178215. for (c1 = c1min; c1 <= c1max; c1++)
  178216. for (c0 = c0min; c0 <= c0max; c0++) {
  178217. histp = & histogram[c0][c1][c2min];
  178218. for (c2 = c2min; c2 <= c2max; c2++)
  178219. if (*histp++ != 0) {
  178220. boxp->c1min = c1min = c1;
  178221. goto have_c1min;
  178222. }
  178223. }
  178224. have_c1min:
  178225. if (c1max > c1min)
  178226. for (c1 = c1max; c1 >= c1min; c1--)
  178227. for (c0 = c0min; c0 <= c0max; c0++) {
  178228. histp = & histogram[c0][c1][c2min];
  178229. for (c2 = c2min; c2 <= c2max; c2++)
  178230. if (*histp++ != 0) {
  178231. boxp->c1max = c1max = c1;
  178232. goto have_c1max;
  178233. }
  178234. }
  178235. have_c1max:
  178236. if (c2max > c2min)
  178237. for (c2 = c2min; c2 <= c2max; c2++)
  178238. for (c0 = c0min; c0 <= c0max; c0++) {
  178239. histp = & histogram[c0][c1min][c2];
  178240. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178241. if (*histp != 0) {
  178242. boxp->c2min = c2min = c2;
  178243. goto have_c2min;
  178244. }
  178245. }
  178246. have_c2min:
  178247. if (c2max > c2min)
  178248. for (c2 = c2max; c2 >= c2min; c2--)
  178249. for (c0 = c0min; c0 <= c0max; c0++) {
  178250. histp = & histogram[c0][c1min][c2];
  178251. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  178252. if (*histp != 0) {
  178253. boxp->c2max = c2max = c2;
  178254. goto have_c2max;
  178255. }
  178256. }
  178257. have_c2max:
  178258. /* Update box volume.
  178259. * We use 2-norm rather than real volume here; this biases the method
  178260. * against making long narrow boxes, and it has the side benefit that
  178261. * a box is splittable iff norm > 0.
  178262. * Since the differences are expressed in histogram-cell units,
  178263. * we have to shift back to JSAMPLE units to get consistent distances;
  178264. * after which, we scale according to the selected distance scale factors.
  178265. */
  178266. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  178267. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  178268. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  178269. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  178270. /* Now scan remaining volume of box and compute population */
  178271. ccount = 0;
  178272. for (c0 = c0min; c0 <= c0max; c0++)
  178273. for (c1 = c1min; c1 <= c1max; c1++) {
  178274. histp = & histogram[c0][c1][c2min];
  178275. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  178276. if (*histp != 0) {
  178277. ccount++;
  178278. }
  178279. }
  178280. boxp->colorcount = ccount;
  178281. }
  178282. LOCAL(int)
  178283. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  178284. int desired_colors)
  178285. /* Repeatedly select and split the largest box until we have enough boxes */
  178286. {
  178287. int n,lb;
  178288. int c0,c1,c2,cmax;
  178289. register boxptr b1,b2;
  178290. while (numboxes < desired_colors) {
  178291. /* Select box to split.
  178292. * Current algorithm: by population for first half, then by volume.
  178293. */
  178294. if (numboxes*2 <= desired_colors) {
  178295. b1 = find_biggest_color_pop(boxlist, numboxes);
  178296. } else {
  178297. b1 = find_biggest_volume(boxlist, numboxes);
  178298. }
  178299. if (b1 == NULL) /* no splittable boxes left! */
  178300. break;
  178301. b2 = &boxlist[numboxes]; /* where new box will go */
  178302. /* Copy the color bounds to the new box. */
  178303. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  178304. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  178305. /* Choose which axis to split the box on.
  178306. * Current algorithm: longest scaled axis.
  178307. * See notes in update_box about scaling distances.
  178308. */
  178309. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  178310. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  178311. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  178312. /* We want to break any ties in favor of green, then red, blue last.
  178313. * This code does the right thing for R,G,B or B,G,R color orders only.
  178314. */
  178315. #if RGB_RED == 0
  178316. cmax = c1; n = 1;
  178317. if (c0 > cmax) { cmax = c0; n = 0; }
  178318. if (c2 > cmax) { n = 2; }
  178319. #else
  178320. cmax = c1; n = 1;
  178321. if (c2 > cmax) { cmax = c2; n = 2; }
  178322. if (c0 > cmax) { n = 0; }
  178323. #endif
  178324. /* Choose split point along selected axis, and update box bounds.
  178325. * Current algorithm: split at halfway point.
  178326. * (Since the box has been shrunk to minimum volume,
  178327. * any split will produce two nonempty subboxes.)
  178328. * Note that lb value is max for lower box, so must be < old max.
  178329. */
  178330. switch (n) {
  178331. case 0:
  178332. lb = (b1->c0max + b1->c0min) / 2;
  178333. b1->c0max = lb;
  178334. b2->c0min = lb+1;
  178335. break;
  178336. case 1:
  178337. lb = (b1->c1max + b1->c1min) / 2;
  178338. b1->c1max = lb;
  178339. b2->c1min = lb+1;
  178340. break;
  178341. case 2:
  178342. lb = (b1->c2max + b1->c2min) / 2;
  178343. b1->c2max = lb;
  178344. b2->c2min = lb+1;
  178345. break;
  178346. }
  178347. /* Update stats for boxes */
  178348. update_box(cinfo, b1);
  178349. update_box(cinfo, b2);
  178350. numboxes++;
  178351. }
  178352. return numboxes;
  178353. }
  178354. LOCAL(void)
  178355. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  178356. /* Compute representative color for a box, put it in colormap[icolor] */
  178357. {
  178358. /* Current algorithm: mean weighted by pixels (not colors) */
  178359. /* Note it is important to get the rounding correct! */
  178360. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178361. hist3d histogram = cquantize->histogram;
  178362. histptr histp;
  178363. int c0,c1,c2;
  178364. int c0min,c0max,c1min,c1max,c2min,c2max;
  178365. long count;
  178366. long total = 0;
  178367. long c0total = 0;
  178368. long c1total = 0;
  178369. long c2total = 0;
  178370. c0min = boxp->c0min; c0max = boxp->c0max;
  178371. c1min = boxp->c1min; c1max = boxp->c1max;
  178372. c2min = boxp->c2min; c2max = boxp->c2max;
  178373. for (c0 = c0min; c0 <= c0max; c0++)
  178374. for (c1 = c1min; c1 <= c1max; c1++) {
  178375. histp = & histogram[c0][c1][c2min];
  178376. for (c2 = c2min; c2 <= c2max; c2++) {
  178377. if ((count = *histp++) != 0) {
  178378. total += count;
  178379. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  178380. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  178381. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  178382. }
  178383. }
  178384. }
  178385. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  178386. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  178387. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  178388. }
  178389. LOCAL(void)
  178390. select_colors (j_decompress_ptr cinfo, int desired_colors)
  178391. /* Master routine for color selection */
  178392. {
  178393. boxptr boxlist;
  178394. int numboxes;
  178395. int i;
  178396. /* Allocate workspace for box list */
  178397. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  178398. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  178399. /* Initialize one box containing whole space */
  178400. numboxes = 1;
  178401. boxlist[0].c0min = 0;
  178402. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  178403. boxlist[0].c1min = 0;
  178404. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  178405. boxlist[0].c2min = 0;
  178406. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  178407. /* Shrink it to actually-used volume and set its statistics */
  178408. update_box(cinfo, & boxlist[0]);
  178409. /* Perform median-cut to produce final box list */
  178410. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  178411. /* Compute the representative color for each box, fill colormap */
  178412. for (i = 0; i < numboxes; i++)
  178413. compute_color(cinfo, & boxlist[i], i);
  178414. cinfo->actual_number_of_colors = numboxes;
  178415. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  178416. }
  178417. /*
  178418. * These routines are concerned with the time-critical task of mapping input
  178419. * colors to the nearest color in the selected colormap.
  178420. *
  178421. * We re-use the histogram space as an "inverse color map", essentially a
  178422. * cache for the results of nearest-color searches. All colors within a
  178423. * histogram cell will be mapped to the same colormap entry, namely the one
  178424. * closest to the cell's center. This may not be quite the closest entry to
  178425. * the actual input color, but it's almost as good. A zero in the cache
  178426. * indicates we haven't found the nearest color for that cell yet; the array
  178427. * is cleared to zeroes before starting the mapping pass. When we find the
  178428. * nearest color for a cell, its colormap index plus one is recorded in the
  178429. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  178430. * when they need to use an unfilled entry in the cache.
  178431. *
  178432. * Our method of efficiently finding nearest colors is based on the "locally
  178433. * sorted search" idea described by Heckbert and on the incremental distance
  178434. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  178435. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  178436. * the distances from a given colormap entry to each cell of the histogram can
  178437. * be computed quickly using an incremental method: the differences between
  178438. * distances to adjacent cells themselves differ by a constant. This allows a
  178439. * fairly fast implementation of the "brute force" approach of computing the
  178440. * distance from every colormap entry to every histogram cell. Unfortunately,
  178441. * it needs a work array to hold the best-distance-so-far for each histogram
  178442. * cell (because the inner loop has to be over cells, not colormap entries).
  178443. * The work array elements have to be INT32s, so the work array would need
  178444. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  178445. *
  178446. * To get around these problems, we apply Thomas' method to compute the
  178447. * nearest colors for only the cells within a small subbox of the histogram.
  178448. * The work array need be only as big as the subbox, so the memory usage
  178449. * problem is solved. Furthermore, we need not fill subboxes that are never
  178450. * referenced in pass2; many images use only part of the color gamut, so a
  178451. * fair amount of work is saved. An additional advantage of this
  178452. * approach is that we can apply Heckbert's locality criterion to quickly
  178453. * eliminate colormap entries that are far away from the subbox; typically
  178454. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  178455. * and we need not compute their distances to individual cells in the subbox.
  178456. * The speed of this approach is heavily influenced by the subbox size: too
  178457. * small means too much overhead, too big loses because Heckbert's criterion
  178458. * can't eliminate as many colormap entries. Empirically the best subbox
  178459. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  178460. *
  178461. * Thomas' article also describes a refined method which is asymptotically
  178462. * faster than the brute-force method, but it is also far more complex and
  178463. * cannot efficiently be applied to small subboxes. It is therefore not
  178464. * useful for programs intended to be portable to DOS machines. On machines
  178465. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  178466. * refined method might be faster than the present code --- but then again,
  178467. * it might not be any faster, and it's certainly more complicated.
  178468. */
  178469. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  178470. #define BOX_C0_LOG (HIST_C0_BITS-3)
  178471. #define BOX_C1_LOG (HIST_C1_BITS-3)
  178472. #define BOX_C2_LOG (HIST_C2_BITS-3)
  178473. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  178474. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  178475. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  178476. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  178477. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  178478. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  178479. /*
  178480. * The next three routines implement inverse colormap filling. They could
  178481. * all be folded into one big routine, but splitting them up this way saves
  178482. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  178483. * and may allow some compilers to produce better code by registerizing more
  178484. * inner-loop variables.
  178485. */
  178486. LOCAL(int)
  178487. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178488. JSAMPLE colorlist[])
  178489. /* Locate the colormap entries close enough to an update box to be candidates
  178490. * for the nearest entry to some cell(s) in the update box. The update box
  178491. * is specified by the center coordinates of its first cell. The number of
  178492. * candidate colormap entries is returned, and their colormap indexes are
  178493. * placed in colorlist[].
  178494. * This routine uses Heckbert's "locally sorted search" criterion to select
  178495. * the colors that need further consideration.
  178496. */
  178497. {
  178498. int numcolors = cinfo->actual_number_of_colors;
  178499. int maxc0, maxc1, maxc2;
  178500. int centerc0, centerc1, centerc2;
  178501. int i, x, ncolors;
  178502. INT32 minmaxdist, min_dist, max_dist, tdist;
  178503. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  178504. /* Compute true coordinates of update box's upper corner and center.
  178505. * Actually we compute the coordinates of the center of the upper-corner
  178506. * histogram cell, which are the upper bounds of the volume we care about.
  178507. * Note that since ">>" rounds down, the "center" values may be closer to
  178508. * min than to max; hence comparisons to them must be "<=", not "<".
  178509. */
  178510. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  178511. centerc0 = (minc0 + maxc0) >> 1;
  178512. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  178513. centerc1 = (minc1 + maxc1) >> 1;
  178514. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  178515. centerc2 = (minc2 + maxc2) >> 1;
  178516. /* For each color in colormap, find:
  178517. * 1. its minimum squared-distance to any point in the update box
  178518. * (zero if color is within update box);
  178519. * 2. its maximum squared-distance to any point in the update box.
  178520. * Both of these can be found by considering only the corners of the box.
  178521. * We save the minimum distance for each color in mindist[];
  178522. * only the smallest maximum distance is of interest.
  178523. */
  178524. minmaxdist = 0x7FFFFFFFL;
  178525. for (i = 0; i < numcolors; i++) {
  178526. /* We compute the squared-c0-distance term, then add in the other two. */
  178527. x = GETJSAMPLE(cinfo->colormap[0][i]);
  178528. if (x < minc0) {
  178529. tdist = (x - minc0) * C0_SCALE;
  178530. min_dist = tdist*tdist;
  178531. tdist = (x - maxc0) * C0_SCALE;
  178532. max_dist = tdist*tdist;
  178533. } else if (x > maxc0) {
  178534. tdist = (x - maxc0) * C0_SCALE;
  178535. min_dist = tdist*tdist;
  178536. tdist = (x - minc0) * C0_SCALE;
  178537. max_dist = tdist*tdist;
  178538. } else {
  178539. /* within cell range so no contribution to min_dist */
  178540. min_dist = 0;
  178541. if (x <= centerc0) {
  178542. tdist = (x - maxc0) * C0_SCALE;
  178543. max_dist = tdist*tdist;
  178544. } else {
  178545. tdist = (x - minc0) * C0_SCALE;
  178546. max_dist = tdist*tdist;
  178547. }
  178548. }
  178549. x = GETJSAMPLE(cinfo->colormap[1][i]);
  178550. if (x < minc1) {
  178551. tdist = (x - minc1) * C1_SCALE;
  178552. min_dist += tdist*tdist;
  178553. tdist = (x - maxc1) * C1_SCALE;
  178554. max_dist += tdist*tdist;
  178555. } else if (x > maxc1) {
  178556. tdist = (x - maxc1) * C1_SCALE;
  178557. min_dist += tdist*tdist;
  178558. tdist = (x - minc1) * C1_SCALE;
  178559. max_dist += tdist*tdist;
  178560. } else {
  178561. /* within cell range so no contribution to min_dist */
  178562. if (x <= centerc1) {
  178563. tdist = (x - maxc1) * C1_SCALE;
  178564. max_dist += tdist*tdist;
  178565. } else {
  178566. tdist = (x - minc1) * C1_SCALE;
  178567. max_dist += tdist*tdist;
  178568. }
  178569. }
  178570. x = GETJSAMPLE(cinfo->colormap[2][i]);
  178571. if (x < minc2) {
  178572. tdist = (x - minc2) * C2_SCALE;
  178573. min_dist += tdist*tdist;
  178574. tdist = (x - maxc2) * C2_SCALE;
  178575. max_dist += tdist*tdist;
  178576. } else if (x > maxc2) {
  178577. tdist = (x - maxc2) * C2_SCALE;
  178578. min_dist += tdist*tdist;
  178579. tdist = (x - minc2) * C2_SCALE;
  178580. max_dist += tdist*tdist;
  178581. } else {
  178582. /* within cell range so no contribution to min_dist */
  178583. if (x <= centerc2) {
  178584. tdist = (x - maxc2) * C2_SCALE;
  178585. max_dist += tdist*tdist;
  178586. } else {
  178587. tdist = (x - minc2) * C2_SCALE;
  178588. max_dist += tdist*tdist;
  178589. }
  178590. }
  178591. mindist[i] = min_dist; /* save away the results */
  178592. if (max_dist < minmaxdist)
  178593. minmaxdist = max_dist;
  178594. }
  178595. /* Now we know that no cell in the update box is more than minmaxdist
  178596. * away from some colormap entry. Therefore, only colors that are
  178597. * within minmaxdist of some part of the box need be considered.
  178598. */
  178599. ncolors = 0;
  178600. for (i = 0; i < numcolors; i++) {
  178601. if (mindist[i] <= minmaxdist)
  178602. colorlist[ncolors++] = (JSAMPLE) i;
  178603. }
  178604. return ncolors;
  178605. }
  178606. LOCAL(void)
  178607. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  178608. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  178609. /* Find the closest colormap entry for each cell in the update box,
  178610. * given the list of candidate colors prepared by find_nearby_colors.
  178611. * Return the indexes of the closest entries in the bestcolor[] array.
  178612. * This routine uses Thomas' incremental distance calculation method to
  178613. * find the distance from a colormap entry to successive cells in the box.
  178614. */
  178615. {
  178616. int ic0, ic1, ic2;
  178617. int i, icolor;
  178618. register INT32 * bptr; /* pointer into bestdist[] array */
  178619. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178620. INT32 dist0, dist1; /* initial distance values */
  178621. register INT32 dist2; /* current distance in inner loop */
  178622. INT32 xx0, xx1; /* distance increments */
  178623. register INT32 xx2;
  178624. INT32 inc0, inc1, inc2; /* initial values for increments */
  178625. /* This array holds the distance to the nearest-so-far color for each cell */
  178626. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178627. /* Initialize best-distance for each cell of the update box */
  178628. bptr = bestdist;
  178629. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  178630. *bptr++ = 0x7FFFFFFFL;
  178631. /* For each color selected by find_nearby_colors,
  178632. * compute its distance to the center of each cell in the box.
  178633. * If that's less than best-so-far, update best distance and color number.
  178634. */
  178635. /* Nominal steps between cell centers ("x" in Thomas article) */
  178636. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  178637. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  178638. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  178639. for (i = 0; i < numcolors; i++) {
  178640. icolor = GETJSAMPLE(colorlist[i]);
  178641. /* Compute (square of) distance from minc0/c1/c2 to this color */
  178642. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  178643. dist0 = inc0*inc0;
  178644. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  178645. dist0 += inc1*inc1;
  178646. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  178647. dist0 += inc2*inc2;
  178648. /* Form the initial difference increments */
  178649. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  178650. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  178651. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  178652. /* Now loop over all cells in box, updating distance per Thomas method */
  178653. bptr = bestdist;
  178654. cptr = bestcolor;
  178655. xx0 = inc0;
  178656. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  178657. dist1 = dist0;
  178658. xx1 = inc1;
  178659. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  178660. dist2 = dist1;
  178661. xx2 = inc2;
  178662. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  178663. if (dist2 < *bptr) {
  178664. *bptr = dist2;
  178665. *cptr = (JSAMPLE) icolor;
  178666. }
  178667. dist2 += xx2;
  178668. xx2 += 2 * STEP_C2 * STEP_C2;
  178669. bptr++;
  178670. cptr++;
  178671. }
  178672. dist1 += xx1;
  178673. xx1 += 2 * STEP_C1 * STEP_C1;
  178674. }
  178675. dist0 += xx0;
  178676. xx0 += 2 * STEP_C0 * STEP_C0;
  178677. }
  178678. }
  178679. }
  178680. LOCAL(void)
  178681. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  178682. /* Fill the inverse-colormap entries in the update box that contains */
  178683. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  178684. /* we can fill as many others as we wish.) */
  178685. {
  178686. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178687. hist3d histogram = cquantize->histogram;
  178688. int minc0, minc1, minc2; /* lower left corner of update box */
  178689. int ic0, ic1, ic2;
  178690. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  178691. register histptr cachep; /* pointer into main cache array */
  178692. /* This array lists the candidate colormap indexes. */
  178693. JSAMPLE colorlist[MAXNUMCOLORS];
  178694. int numcolors; /* number of candidate colors */
  178695. /* This array holds the actually closest colormap index for each cell. */
  178696. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  178697. /* Convert cell coordinates to update box ID */
  178698. c0 >>= BOX_C0_LOG;
  178699. c1 >>= BOX_C1_LOG;
  178700. c2 >>= BOX_C2_LOG;
  178701. /* Compute true coordinates of update box's origin corner.
  178702. * Actually we compute the coordinates of the center of the corner
  178703. * histogram cell, which are the lower bounds of the volume we care about.
  178704. */
  178705. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  178706. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  178707. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  178708. /* Determine which colormap entries are close enough to be candidates
  178709. * for the nearest entry to some cell in the update box.
  178710. */
  178711. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  178712. /* Determine the actually nearest colors. */
  178713. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  178714. bestcolor);
  178715. /* Save the best color numbers (plus 1) in the main cache array */
  178716. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  178717. c1 <<= BOX_C1_LOG;
  178718. c2 <<= BOX_C2_LOG;
  178719. cptr = bestcolor;
  178720. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  178721. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  178722. cachep = & histogram[c0+ic0][c1+ic1][c2];
  178723. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  178724. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  178725. }
  178726. }
  178727. }
  178728. }
  178729. /*
  178730. * Map some rows of pixels to the output colormapped representation.
  178731. */
  178732. METHODDEF(void)
  178733. pass2_no_dither (j_decompress_ptr cinfo,
  178734. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178735. /* This version performs no dithering */
  178736. {
  178737. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178738. hist3d histogram = cquantize->histogram;
  178739. register JSAMPROW inptr, outptr;
  178740. register histptr cachep;
  178741. register int c0, c1, c2;
  178742. int row;
  178743. JDIMENSION col;
  178744. JDIMENSION width = cinfo->output_width;
  178745. for (row = 0; row < num_rows; row++) {
  178746. inptr = input_buf[row];
  178747. outptr = output_buf[row];
  178748. for (col = width; col > 0; col--) {
  178749. /* get pixel value and index into the cache */
  178750. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  178751. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  178752. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  178753. cachep = & histogram[c0][c1][c2];
  178754. /* If we have not seen this color before, find nearest colormap entry */
  178755. /* and update the cache */
  178756. if (*cachep == 0)
  178757. fill_inverse_cmap(cinfo, c0,c1,c2);
  178758. /* Now emit the colormap index for this cell */
  178759. *outptr++ = (JSAMPLE) (*cachep - 1);
  178760. }
  178761. }
  178762. }
  178763. METHODDEF(void)
  178764. pass2_fs_dither (j_decompress_ptr cinfo,
  178765. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  178766. /* This version performs Floyd-Steinberg dithering */
  178767. {
  178768. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178769. hist3d histogram = cquantize->histogram;
  178770. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  178771. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  178772. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  178773. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178774. JSAMPROW inptr; /* => current input pixel */
  178775. JSAMPROW outptr; /* => current output pixel */
  178776. histptr cachep;
  178777. int dir; /* +1 or -1 depending on direction */
  178778. int dir3; /* 3*dir, for advancing inptr & errorptr */
  178779. int row;
  178780. JDIMENSION col;
  178781. JDIMENSION width = cinfo->output_width;
  178782. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178783. int *error_limit = cquantize->error_limiter;
  178784. JSAMPROW colormap0 = cinfo->colormap[0];
  178785. JSAMPROW colormap1 = cinfo->colormap[1];
  178786. JSAMPROW colormap2 = cinfo->colormap[2];
  178787. SHIFT_TEMPS
  178788. for (row = 0; row < num_rows; row++) {
  178789. inptr = input_buf[row];
  178790. outptr = output_buf[row];
  178791. if (cquantize->on_odd_row) {
  178792. /* work right to left in this row */
  178793. inptr += (width-1) * 3; /* so point to rightmost pixel */
  178794. outptr += width-1;
  178795. dir = -1;
  178796. dir3 = -3;
  178797. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  178798. cquantize->on_odd_row = FALSE; /* flip for next time */
  178799. } else {
  178800. /* work left to right in this row */
  178801. dir = 1;
  178802. dir3 = 3;
  178803. errorptr = cquantize->fserrors; /* => entry before first real column */
  178804. cquantize->on_odd_row = TRUE; /* flip for next time */
  178805. }
  178806. /* Preset error values: no error propagated to first pixel from left */
  178807. cur0 = cur1 = cur2 = 0;
  178808. /* and no error propagated to row below yet */
  178809. belowerr0 = belowerr1 = belowerr2 = 0;
  178810. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  178811. for (col = width; col > 0; col--) {
  178812. /* curN holds the error propagated from the previous pixel on the
  178813. * current line. Add the error propagated from the previous line
  178814. * to form the complete error correction term for this pixel, and
  178815. * round the error term (which is expressed * 16) to an integer.
  178816. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178817. * for either sign of the error value.
  178818. * Note: errorptr points to *previous* column's array entry.
  178819. */
  178820. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  178821. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  178822. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  178823. /* Limit the error using transfer function set by init_error_limit.
  178824. * See comments with init_error_limit for rationale.
  178825. */
  178826. cur0 = error_limit[cur0];
  178827. cur1 = error_limit[cur1];
  178828. cur2 = error_limit[cur2];
  178829. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178830. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  178831. * this sets the required size of the range_limit array.
  178832. */
  178833. cur0 += GETJSAMPLE(inptr[0]);
  178834. cur1 += GETJSAMPLE(inptr[1]);
  178835. cur2 += GETJSAMPLE(inptr[2]);
  178836. cur0 = GETJSAMPLE(range_limit[cur0]);
  178837. cur1 = GETJSAMPLE(range_limit[cur1]);
  178838. cur2 = GETJSAMPLE(range_limit[cur2]);
  178839. /* Index into the cache with adjusted pixel value */
  178840. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  178841. /* If we have not seen this color before, find nearest colormap */
  178842. /* entry and update the cache */
  178843. if (*cachep == 0)
  178844. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  178845. /* Now emit the colormap index for this cell */
  178846. { register int pixcode = *cachep - 1;
  178847. *outptr = (JSAMPLE) pixcode;
  178848. /* Compute representation error for this pixel */
  178849. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  178850. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  178851. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  178852. }
  178853. /* Compute error fractions to be propagated to adjacent pixels.
  178854. * Add these into the running sums, and simultaneously shift the
  178855. * next-line error sums left by 1 column.
  178856. */
  178857. { register LOCFSERROR bnexterr, delta;
  178858. bnexterr = cur0; /* Process component 0 */
  178859. delta = cur0 * 2;
  178860. cur0 += delta; /* form error * 3 */
  178861. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  178862. cur0 += delta; /* form error * 5 */
  178863. bpreverr0 = belowerr0 + cur0;
  178864. belowerr0 = bnexterr;
  178865. cur0 += delta; /* form error * 7 */
  178866. bnexterr = cur1; /* Process component 1 */
  178867. delta = cur1 * 2;
  178868. cur1 += delta; /* form error * 3 */
  178869. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  178870. cur1 += delta; /* form error * 5 */
  178871. bpreverr1 = belowerr1 + cur1;
  178872. belowerr1 = bnexterr;
  178873. cur1 += delta; /* form error * 7 */
  178874. bnexterr = cur2; /* Process component 2 */
  178875. delta = cur2 * 2;
  178876. cur2 += delta; /* form error * 3 */
  178877. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  178878. cur2 += delta; /* form error * 5 */
  178879. bpreverr2 = belowerr2 + cur2;
  178880. belowerr2 = bnexterr;
  178881. cur2 += delta; /* form error * 7 */
  178882. }
  178883. /* At this point curN contains the 7/16 error value to be propagated
  178884. * to the next pixel on the current line, and all the errors for the
  178885. * next line have been shifted over. We are therefore ready to move on.
  178886. */
  178887. inptr += dir3; /* Advance pixel pointers to next column */
  178888. outptr += dir;
  178889. errorptr += dir3; /* advance errorptr to current column */
  178890. }
  178891. /* Post-loop cleanup: we must unload the final error values into the
  178892. * final fserrors[] entry. Note we need not unload belowerrN because
  178893. * it is for the dummy column before or after the actual array.
  178894. */
  178895. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  178896. errorptr[1] = (FSERROR) bpreverr1;
  178897. errorptr[2] = (FSERROR) bpreverr2;
  178898. }
  178899. }
  178900. /*
  178901. * Initialize the error-limiting transfer function (lookup table).
  178902. * The raw F-S error computation can potentially compute error values of up to
  178903. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  178904. * much less, otherwise obviously wrong pixels will be created. (Typical
  178905. * effects include weird fringes at color-area boundaries, isolated bright
  178906. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  178907. * is to ensure that the "corners" of the color cube are allocated as output
  178908. * colors; then repeated errors in the same direction cannot cause cascading
  178909. * error buildup. However, that only prevents the error from getting
  178910. * completely out of hand; Aaron Giles reports that error limiting improves
  178911. * the results even with corner colors allocated.
  178912. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  178913. * well, but the smoother transfer function used below is even better. Thanks
  178914. * to Aaron Giles for this idea.
  178915. */
  178916. LOCAL(void)
  178917. init_error_limit (j_decompress_ptr cinfo)
  178918. /* Allocate and fill in the error_limiter table */
  178919. {
  178920. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178921. int * table;
  178922. int in, out;
  178923. table = (int *) (*cinfo->mem->alloc_small)
  178924. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  178925. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  178926. cquantize->error_limiter = table;
  178927. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  178928. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  178929. out = 0;
  178930. for (in = 0; in < STEPSIZE; in++, out++) {
  178931. table[in] = out; table[-in] = -out;
  178932. }
  178933. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  178934. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  178935. table[in] = out; table[-in] = -out;
  178936. }
  178937. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  178938. for (; in <= MAXJSAMPLE; in++) {
  178939. table[in] = out; table[-in] = -out;
  178940. }
  178941. #undef STEPSIZE
  178942. }
  178943. /*
  178944. * Finish up at the end of each pass.
  178945. */
  178946. METHODDEF(void)
  178947. finish_pass1 (j_decompress_ptr cinfo)
  178948. {
  178949. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178950. /* Select the representative colors and fill in cinfo->colormap */
  178951. cinfo->colormap = cquantize->sv_colormap;
  178952. select_colors(cinfo, cquantize->desired);
  178953. /* Force next pass to zero the color index table */
  178954. cquantize->needs_zeroed = TRUE;
  178955. }
  178956. METHODDEF(void)
  178957. finish_pass2 (j_decompress_ptr)
  178958. {
  178959. /* no work */
  178960. }
  178961. /*
  178962. * Initialize for each processing pass.
  178963. */
  178964. METHODDEF(void)
  178965. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178966. {
  178967. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178968. hist3d histogram = cquantize->histogram;
  178969. int i;
  178970. /* Only F-S dithering or no dithering is supported. */
  178971. /* If user asks for ordered dither, give him F-S. */
  178972. if (cinfo->dither_mode != JDITHER_NONE)
  178973. cinfo->dither_mode = JDITHER_FS;
  178974. if (is_pre_scan) {
  178975. /* Set up method pointers */
  178976. cquantize->pub.color_quantize = prescan_quantize;
  178977. cquantize->pub.finish_pass = finish_pass1;
  178978. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  178979. } else {
  178980. /* Set up method pointers */
  178981. if (cinfo->dither_mode == JDITHER_FS)
  178982. cquantize->pub.color_quantize = pass2_fs_dither;
  178983. else
  178984. cquantize->pub.color_quantize = pass2_no_dither;
  178985. cquantize->pub.finish_pass = finish_pass2;
  178986. /* Make sure color count is acceptable */
  178987. i = cinfo->actual_number_of_colors;
  178988. if (i < 1)
  178989. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  178990. if (i > MAXNUMCOLORS)
  178991. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  178992. if (cinfo->dither_mode == JDITHER_FS) {
  178993. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  178994. (3 * SIZEOF(FSERROR)));
  178995. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  178996. if (cquantize->fserrors == NULL)
  178997. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  178998. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178999. /* Initialize the propagated errors to zero. */
  179000. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  179001. /* Make the error-limit table if we didn't already. */
  179002. if (cquantize->error_limiter == NULL)
  179003. init_error_limit(cinfo);
  179004. cquantize->on_odd_row = FALSE;
  179005. }
  179006. }
  179007. /* Zero the histogram or inverse color map, if necessary */
  179008. if (cquantize->needs_zeroed) {
  179009. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179010. jzero_far((void FAR *) histogram[i],
  179011. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179012. }
  179013. cquantize->needs_zeroed = FALSE;
  179014. }
  179015. }
  179016. /*
  179017. * Switch to a new external colormap between output passes.
  179018. */
  179019. METHODDEF(void)
  179020. new_color_map_2_quant (j_decompress_ptr cinfo)
  179021. {
  179022. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179023. /* Reset the inverse color map */
  179024. cquantize->needs_zeroed = TRUE;
  179025. }
  179026. /*
  179027. * Module initialization routine for 2-pass color quantization.
  179028. */
  179029. GLOBAL(void)
  179030. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  179031. {
  179032. my_cquantize_ptr2 cquantize;
  179033. int i;
  179034. cquantize = (my_cquantize_ptr2)
  179035. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179036. SIZEOF(my_cquantizer2));
  179037. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179038. cquantize->pub.start_pass = start_pass_2_quant;
  179039. cquantize->pub.new_color_map = new_color_map_2_quant;
  179040. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179041. cquantize->error_limiter = NULL;
  179042. /* Make sure jdmaster didn't give me a case I can't handle */
  179043. if (cinfo->out_color_components != 3)
  179044. ERREXIT(cinfo, JERR_NOTIMPL);
  179045. /* Allocate the histogram/inverse colormap storage */
  179046. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179047. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179048. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179049. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179050. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179051. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179052. }
  179053. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179054. /* Allocate storage for the completed colormap, if required.
  179055. * We do this now since it is FAR storage and may affect
  179056. * the memory manager's space calculations.
  179057. */
  179058. if (cinfo->enable_2pass_quant) {
  179059. /* Make sure color count is acceptable */
  179060. int desired = cinfo->desired_number_of_colors;
  179061. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179062. if (desired < 8)
  179063. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179064. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179065. if (desired > MAXNUMCOLORS)
  179066. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179067. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179068. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179069. cquantize->desired = desired;
  179070. } else
  179071. cquantize->sv_colormap = NULL;
  179072. /* Only F-S dithering or no dithering is supported. */
  179073. /* If user asks for ordered dither, give him F-S. */
  179074. if (cinfo->dither_mode != JDITHER_NONE)
  179075. cinfo->dither_mode = JDITHER_FS;
  179076. /* Allocate Floyd-Steinberg workspace if necessary.
  179077. * This isn't really needed until pass 2, but again it is FAR storage.
  179078. * Although we will cope with a later change in dither_mode,
  179079. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179080. */
  179081. if (cinfo->dither_mode == JDITHER_FS) {
  179082. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179083. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179084. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179085. /* Might as well create the error-limiting table too. */
  179086. init_error_limit(cinfo);
  179087. }
  179088. }
  179089. #endif /* QUANT_2PASS_SUPPORTED */
  179090. /*** End of inlined file: jquant2.c ***/
  179091. /*** Start of inlined file: jutils.c ***/
  179092. #define JPEG_INTERNALS
  179093. /*
  179094. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179095. * of a DCT block read in natural order (left to right, top to bottom).
  179096. */
  179097. #if 0 /* This table is not actually needed in v6a */
  179098. const int jpeg_zigzag_order[DCTSIZE2] = {
  179099. 0, 1, 5, 6, 14, 15, 27, 28,
  179100. 2, 4, 7, 13, 16, 26, 29, 42,
  179101. 3, 8, 12, 17, 25, 30, 41, 43,
  179102. 9, 11, 18, 24, 31, 40, 44, 53,
  179103. 10, 19, 23, 32, 39, 45, 52, 54,
  179104. 20, 22, 33, 38, 46, 51, 55, 60,
  179105. 21, 34, 37, 47, 50, 56, 59, 61,
  179106. 35, 36, 48, 49, 57, 58, 62, 63
  179107. };
  179108. #endif
  179109. /*
  179110. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179111. * of zigzag order.
  179112. *
  179113. * When reading corrupted data, the Huffman decoders could attempt
  179114. * to reference an entry beyond the end of this array (if the decoded
  179115. * zero run length reaches past the end of the block). To prevent
  179116. * wild stores without adding an inner-loop test, we put some extra
  179117. * "63"s after the real entries. This will cause the extra coefficient
  179118. * to be stored in location 63 of the block, not somewhere random.
  179119. * The worst case would be a run-length of 15, which means we need 16
  179120. * fake entries.
  179121. */
  179122. const int jpeg_natural_order[DCTSIZE2+16] = {
  179123. 0, 1, 8, 16, 9, 2, 3, 10,
  179124. 17, 24, 32, 25, 18, 11, 4, 5,
  179125. 12, 19, 26, 33, 40, 48, 41, 34,
  179126. 27, 20, 13, 6, 7, 14, 21, 28,
  179127. 35, 42, 49, 56, 57, 50, 43, 36,
  179128. 29, 22, 15, 23, 30, 37, 44, 51,
  179129. 58, 59, 52, 45, 38, 31, 39, 46,
  179130. 53, 60, 61, 54, 47, 55, 62, 63,
  179131. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179132. 63, 63, 63, 63, 63, 63, 63, 63
  179133. };
  179134. /*
  179135. * Arithmetic utilities
  179136. */
  179137. GLOBAL(long)
  179138. jdiv_round_up (long a, long b)
  179139. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179140. /* Assumes a >= 0, b > 0 */
  179141. {
  179142. return (a + b - 1L) / b;
  179143. }
  179144. GLOBAL(long)
  179145. jround_up (long a, long b)
  179146. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179147. /* Assumes a >= 0, b > 0 */
  179148. {
  179149. a += b - 1L;
  179150. return a - (a % b);
  179151. }
  179152. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179153. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179154. * are FAR and we're assuming a small-pointer memory model. However, some
  179155. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179156. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179157. * Otherwise, the routines below do it the hard way. (The performance cost
  179158. * is not all that great, because these routines aren't very heavily used.)
  179159. */
  179160. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179161. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179162. #define FMEMZERO(target,size) MEMZERO(target,size)
  179163. #else /* 80x86 case, define if we can */
  179164. #ifdef USE_FMEM
  179165. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179166. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179167. #endif
  179168. #endif
  179169. GLOBAL(void)
  179170. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179171. JSAMPARRAY output_array, int dest_row,
  179172. int num_rows, JDIMENSION num_cols)
  179173. /* Copy some rows of samples from one place to another.
  179174. * num_rows rows are copied from input_array[source_row++]
  179175. * to output_array[dest_row++]; these areas may overlap for duplication.
  179176. * The source and destination arrays must be at least as wide as num_cols.
  179177. */
  179178. {
  179179. register JSAMPROW inptr, outptr;
  179180. #ifdef FMEMCOPY
  179181. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179182. #else
  179183. register JDIMENSION count;
  179184. #endif
  179185. register int row;
  179186. input_array += source_row;
  179187. output_array += dest_row;
  179188. for (row = num_rows; row > 0; row--) {
  179189. inptr = *input_array++;
  179190. outptr = *output_array++;
  179191. #ifdef FMEMCOPY
  179192. FMEMCOPY(outptr, inptr, count);
  179193. #else
  179194. for (count = num_cols; count > 0; count--)
  179195. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179196. #endif
  179197. }
  179198. }
  179199. GLOBAL(void)
  179200. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179201. JDIMENSION num_blocks)
  179202. /* Copy a row of coefficient blocks from one place to another. */
  179203. {
  179204. #ifdef FMEMCOPY
  179205. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179206. #else
  179207. register JCOEFPTR inptr, outptr;
  179208. register long count;
  179209. inptr = (JCOEFPTR) input_row;
  179210. outptr = (JCOEFPTR) output_row;
  179211. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179212. *outptr++ = *inptr++;
  179213. }
  179214. #endif
  179215. }
  179216. GLOBAL(void)
  179217. jzero_far (void FAR * target, size_t bytestozero)
  179218. /* Zero out a chunk of FAR memory. */
  179219. /* This might be sample-array data, block-array data, or alloc_large data. */
  179220. {
  179221. #ifdef FMEMZERO
  179222. FMEMZERO(target, bytestozero);
  179223. #else
  179224. register char FAR * ptr = (char FAR *) target;
  179225. register size_t count;
  179226. for (count = bytestozero; count > 0; count--) {
  179227. *ptr++ = 0;
  179228. }
  179229. #endif
  179230. }
  179231. /*** End of inlined file: jutils.c ***/
  179232. /*** Start of inlined file: transupp.c ***/
  179233. /* Although this file really shouldn't have access to the library internals,
  179234. * it's helpful to let it call jround_up() and jcopy_block_row().
  179235. */
  179236. #define JPEG_INTERNALS
  179237. /*** Start of inlined file: transupp.h ***/
  179238. /* If you happen not to want the image transform support, disable it here */
  179239. #ifndef TRANSFORMS_SUPPORTED
  179240. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  179241. #endif
  179242. /* Short forms of external names for systems with brain-damaged linkers. */
  179243. #ifdef NEED_SHORT_EXTERNAL_NAMES
  179244. #define jtransform_request_workspace jTrRequest
  179245. #define jtransform_adjust_parameters jTrAdjust
  179246. #define jtransform_execute_transformation jTrExec
  179247. #define jcopy_markers_setup jCMrkSetup
  179248. #define jcopy_markers_execute jCMrkExec
  179249. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  179250. /*
  179251. * Codes for supported types of image transformations.
  179252. */
  179253. typedef enum {
  179254. JXFORM_NONE, /* no transformation */
  179255. JXFORM_FLIP_H, /* horizontal flip */
  179256. JXFORM_FLIP_V, /* vertical flip */
  179257. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  179258. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  179259. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  179260. JXFORM_ROT_180, /* 180-degree rotation */
  179261. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  179262. } JXFORM_CODE;
  179263. /*
  179264. * Although rotating and flipping data expressed as DCT coefficients is not
  179265. * hard, there is an asymmetry in the JPEG format specification for images
  179266. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  179267. * image edges are padded out to the next iMCU boundary with junk data; but
  179268. * no padding is possible at the top and left edges. If we were to flip
  179269. * the whole image including the pad data, then pad garbage would become
  179270. * visible at the top and/or left, and real pixels would disappear into the
  179271. * pad margins --- perhaps permanently, since encoders & decoders may not
  179272. * bother to preserve DCT blocks that appear to be completely outside the
  179273. * nominal image area. So, we have to exclude any partial iMCUs from the
  179274. * basic transformation.
  179275. *
  179276. * Transpose is the only transformation that can handle partial iMCUs at the
  179277. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  179278. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  179279. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  179280. * The other transforms are defined as combinations of these basic transforms
  179281. * and process edge blocks in a way that preserves the equivalence.
  179282. *
  179283. * The "trim" option causes untransformable partial iMCUs to be dropped;
  179284. * this is not strictly lossless, but it usually gives the best-looking
  179285. * result for odd-size images. Note that when this option is active,
  179286. * the expected mathematical equivalences between the transforms may not hold.
  179287. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  179288. * followed by -rot 180 -trim trims both edges.)
  179289. *
  179290. * We also offer a "force to grayscale" option, which simply discards the
  179291. * chrominance channels of a YCbCr image. This is lossless in the sense that
  179292. * the luminance channel is preserved exactly. It's not the same kind of
  179293. * thing as the rotate/flip transformations, but it's convenient to handle it
  179294. * as part of this package, mainly because the transformation routines have to
  179295. * be aware of the option to know how many components to work on.
  179296. */
  179297. typedef struct {
  179298. /* Options: set by caller */
  179299. JXFORM_CODE transform; /* image transform operator */
  179300. boolean trim; /* if TRUE, trim partial MCUs as needed */
  179301. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  179302. /* Internal workspace: caller should not touch these */
  179303. int num_components; /* # of components in workspace */
  179304. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  179305. } jpeg_transform_info;
  179306. #if TRANSFORMS_SUPPORTED
  179307. /* Request any required workspace */
  179308. EXTERN(void) jtransform_request_workspace
  179309. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  179310. /* Adjust output image parameters */
  179311. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  179312. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179313. jvirt_barray_ptr *src_coef_arrays,
  179314. jpeg_transform_info *info));
  179315. /* Execute the actual transformation, if any */
  179316. EXTERN(void) jtransform_execute_transformation
  179317. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179318. jvirt_barray_ptr *src_coef_arrays,
  179319. jpeg_transform_info *info));
  179320. #endif /* TRANSFORMS_SUPPORTED */
  179321. /*
  179322. * Support for copying optional markers from source to destination file.
  179323. */
  179324. typedef enum {
  179325. JCOPYOPT_NONE, /* copy no optional markers */
  179326. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  179327. JCOPYOPT_ALL /* copy all optional markers */
  179328. } JCOPY_OPTION;
  179329. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  179330. /* Setup decompression object to save desired markers in memory */
  179331. EXTERN(void) jcopy_markers_setup
  179332. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  179333. /* Copy markers saved in the given source object to the destination object */
  179334. EXTERN(void) jcopy_markers_execute
  179335. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179336. JCOPY_OPTION option));
  179337. /*** End of inlined file: transupp.h ***/
  179338. /* My own external interface */
  179339. #if TRANSFORMS_SUPPORTED
  179340. /*
  179341. * Lossless image transformation routines. These routines work on DCT
  179342. * coefficient arrays and thus do not require any lossy decompression
  179343. * or recompression of the image.
  179344. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  179345. *
  179346. * Horizontal flipping is done in-place, using a single top-to-bottom
  179347. * pass through the virtual source array. It will thus be much the
  179348. * fastest option for images larger than main memory.
  179349. *
  179350. * The other routines require a set of destination virtual arrays, so they
  179351. * need twice as much memory as jpegtran normally does. The destination
  179352. * arrays are always written in normal scan order (top to bottom) because
  179353. * the virtual array manager expects this. The source arrays will be scanned
  179354. * in the corresponding order, which means multiple passes through the source
  179355. * arrays for most of the transforms. That could result in much thrashing
  179356. * if the image is larger than main memory.
  179357. *
  179358. * Some notes about the operating environment of the individual transform
  179359. * routines:
  179360. * 1. Both the source and destination virtual arrays are allocated from the
  179361. * source JPEG object, and therefore should be manipulated by calling the
  179362. * source's memory manager.
  179363. * 2. The destination's component count should be used. It may be smaller
  179364. * than the source's when forcing to grayscale.
  179365. * 3. Likewise the destination's sampling factors should be used. When
  179366. * forcing to grayscale the destination's sampling factors will be all 1,
  179367. * and we may as well take that as the effective iMCU size.
  179368. * 4. When "trim" is in effect, the destination's dimensions will be the
  179369. * trimmed values but the source's will be untrimmed.
  179370. * 5. All the routines assume that the source and destination buffers are
  179371. * padded out to a full iMCU boundary. This is true, although for the
  179372. * source buffer it is an undocumented property of jdcoefct.c.
  179373. * Notes 2,3,4 boil down to this: generally we should use the destination's
  179374. * dimensions and ignore the source's.
  179375. */
  179376. LOCAL(void)
  179377. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179378. jvirt_barray_ptr *src_coef_arrays)
  179379. /* Horizontal flip; done in-place, so no separate dest array is required */
  179380. {
  179381. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  179382. int ci, k, offset_y;
  179383. JBLOCKARRAY buffer;
  179384. JCOEFPTR ptr1, ptr2;
  179385. JCOEF temp1, temp2;
  179386. jpeg_component_info *compptr;
  179387. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  179388. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  179389. * mirroring by changing the signs of odd-numbered columns.
  179390. * Partial iMCUs at the right edge are left untouched.
  179391. */
  179392. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179393. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179394. compptr = dstinfo->comp_info + ci;
  179395. comp_width = MCU_cols * compptr->h_samp_factor;
  179396. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  179397. blk_y += compptr->v_samp_factor) {
  179398. buffer = (*srcinfo->mem->access_virt_barray)
  179399. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  179400. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179401. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179402. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  179403. ptr1 = buffer[offset_y][blk_x];
  179404. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  179405. /* this unrolled loop doesn't need to know which row it's on... */
  179406. for (k = 0; k < DCTSIZE2; k += 2) {
  179407. temp1 = *ptr1; /* swap even column */
  179408. temp2 = *ptr2;
  179409. *ptr1++ = temp2;
  179410. *ptr2++ = temp1;
  179411. temp1 = *ptr1; /* swap odd column with sign change */
  179412. temp2 = *ptr2;
  179413. *ptr1++ = -temp2;
  179414. *ptr2++ = -temp1;
  179415. }
  179416. }
  179417. }
  179418. }
  179419. }
  179420. }
  179421. LOCAL(void)
  179422. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179423. jvirt_barray_ptr *src_coef_arrays,
  179424. jvirt_barray_ptr *dst_coef_arrays)
  179425. /* Vertical flip */
  179426. {
  179427. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179428. int ci, i, j, offset_y;
  179429. JBLOCKARRAY src_buffer, dst_buffer;
  179430. JBLOCKROW src_row_ptr, dst_row_ptr;
  179431. JCOEFPTR src_ptr, dst_ptr;
  179432. jpeg_component_info *compptr;
  179433. /* We output into a separate array because we can't touch different
  179434. * rows of the source virtual array simultaneously. Otherwise, this
  179435. * is a pretty straightforward analog of horizontal flip.
  179436. * Within a DCT block, vertical mirroring is done by changing the signs
  179437. * of odd-numbered rows.
  179438. * Partial iMCUs at the bottom edge are copied verbatim.
  179439. */
  179440. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179441. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179442. compptr = dstinfo->comp_info + ci;
  179443. comp_height = MCU_rows * compptr->v_samp_factor;
  179444. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179445. dst_blk_y += compptr->v_samp_factor) {
  179446. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179447. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179448. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179449. if (dst_blk_y < comp_height) {
  179450. /* Row is within the mirrorable area. */
  179451. src_buffer = (*srcinfo->mem->access_virt_barray)
  179452. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179453. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179454. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179455. } else {
  179456. /* Bottom-edge blocks will be copied verbatim. */
  179457. src_buffer = (*srcinfo->mem->access_virt_barray)
  179458. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179459. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179460. }
  179461. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179462. if (dst_blk_y < comp_height) {
  179463. /* Row is within the mirrorable area. */
  179464. dst_row_ptr = dst_buffer[offset_y];
  179465. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179466. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179467. dst_blk_x++) {
  179468. dst_ptr = dst_row_ptr[dst_blk_x];
  179469. src_ptr = src_row_ptr[dst_blk_x];
  179470. for (i = 0; i < DCTSIZE; i += 2) {
  179471. /* copy even row */
  179472. for (j = 0; j < DCTSIZE; j++)
  179473. *dst_ptr++ = *src_ptr++;
  179474. /* copy odd row with sign change */
  179475. for (j = 0; j < DCTSIZE; j++)
  179476. *dst_ptr++ = - *src_ptr++;
  179477. }
  179478. }
  179479. } else {
  179480. /* Just copy row verbatim. */
  179481. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  179482. compptr->width_in_blocks);
  179483. }
  179484. }
  179485. }
  179486. }
  179487. }
  179488. LOCAL(void)
  179489. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179490. jvirt_barray_ptr *src_coef_arrays,
  179491. jvirt_barray_ptr *dst_coef_arrays)
  179492. /* Transpose source into destination */
  179493. {
  179494. JDIMENSION dst_blk_x, dst_blk_y;
  179495. int ci, i, j, offset_x, offset_y;
  179496. JBLOCKARRAY src_buffer, dst_buffer;
  179497. JCOEFPTR src_ptr, dst_ptr;
  179498. jpeg_component_info *compptr;
  179499. /* Transposing pixels within a block just requires transposing the
  179500. * DCT coefficients.
  179501. * Partial iMCUs at the edges require no special treatment; we simply
  179502. * process all the available DCT blocks for every component.
  179503. */
  179504. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179505. compptr = dstinfo->comp_info + ci;
  179506. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179507. dst_blk_y += compptr->v_samp_factor) {
  179508. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179509. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179510. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179511. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179512. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179513. dst_blk_x += compptr->h_samp_factor) {
  179514. src_buffer = (*srcinfo->mem->access_virt_barray)
  179515. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179516. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179517. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179518. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179519. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179520. for (i = 0; i < DCTSIZE; i++)
  179521. for (j = 0; j < DCTSIZE; j++)
  179522. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179523. }
  179524. }
  179525. }
  179526. }
  179527. }
  179528. }
  179529. LOCAL(void)
  179530. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179531. jvirt_barray_ptr *src_coef_arrays,
  179532. jvirt_barray_ptr *dst_coef_arrays)
  179533. /* 90 degree rotation is equivalent to
  179534. * 1. Transposing the image;
  179535. * 2. Horizontal mirroring.
  179536. * These two steps are merged into a single processing routine.
  179537. */
  179538. {
  179539. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  179540. int ci, i, j, offset_x, offset_y;
  179541. JBLOCKARRAY src_buffer, dst_buffer;
  179542. JCOEFPTR src_ptr, dst_ptr;
  179543. jpeg_component_info *compptr;
  179544. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179545. * at the (output) right edge properly. They just get transposed and
  179546. * not mirrored.
  179547. */
  179548. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179549. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179550. compptr = dstinfo->comp_info + ci;
  179551. comp_width = MCU_cols * compptr->h_samp_factor;
  179552. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179553. dst_blk_y += compptr->v_samp_factor) {
  179554. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179555. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179556. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179557. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179558. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179559. dst_blk_x += compptr->h_samp_factor) {
  179560. src_buffer = (*srcinfo->mem->access_virt_barray)
  179561. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179562. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179563. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179564. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179565. if (dst_blk_x < comp_width) {
  179566. /* Block is within the mirrorable area. */
  179567. dst_ptr = dst_buffer[offset_y]
  179568. [comp_width - dst_blk_x - offset_x - 1];
  179569. for (i = 0; i < DCTSIZE; i++) {
  179570. for (j = 0; j < DCTSIZE; j++)
  179571. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179572. i++;
  179573. for (j = 0; j < DCTSIZE; j++)
  179574. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179575. }
  179576. } else {
  179577. /* Edge blocks are transposed but not mirrored. */
  179578. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179579. for (i = 0; i < DCTSIZE; i++)
  179580. for (j = 0; j < DCTSIZE; j++)
  179581. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179582. }
  179583. }
  179584. }
  179585. }
  179586. }
  179587. }
  179588. }
  179589. LOCAL(void)
  179590. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179591. jvirt_barray_ptr *src_coef_arrays,
  179592. jvirt_barray_ptr *dst_coef_arrays)
  179593. /* 270 degree rotation is equivalent to
  179594. * 1. Horizontal mirroring;
  179595. * 2. Transposing the image.
  179596. * These two steps are merged into a single processing routine.
  179597. */
  179598. {
  179599. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  179600. int ci, i, j, offset_x, offset_y;
  179601. JBLOCKARRAY src_buffer, dst_buffer;
  179602. JCOEFPTR src_ptr, dst_ptr;
  179603. jpeg_component_info *compptr;
  179604. /* Because of the horizontal mirror step, we can't process partial iMCUs
  179605. * at the (output) bottom edge properly. They just get transposed and
  179606. * not mirrored.
  179607. */
  179608. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179609. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179610. compptr = dstinfo->comp_info + ci;
  179611. comp_height = MCU_rows * compptr->v_samp_factor;
  179612. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179613. dst_blk_y += compptr->v_samp_factor) {
  179614. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179615. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179616. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179617. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179618. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179619. dst_blk_x += compptr->h_samp_factor) {
  179620. src_buffer = (*srcinfo->mem->access_virt_barray)
  179621. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179622. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179623. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179624. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179625. if (dst_blk_y < comp_height) {
  179626. /* Block is within the mirrorable area. */
  179627. src_ptr = src_buffer[offset_x]
  179628. [comp_height - dst_blk_y - offset_y - 1];
  179629. for (i = 0; i < DCTSIZE; i++) {
  179630. for (j = 0; j < DCTSIZE; j++) {
  179631. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179632. j++;
  179633. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179634. }
  179635. }
  179636. } else {
  179637. /* Edge blocks are transposed but not mirrored. */
  179638. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179639. for (i = 0; i < DCTSIZE; i++)
  179640. for (j = 0; j < DCTSIZE; j++)
  179641. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179642. }
  179643. }
  179644. }
  179645. }
  179646. }
  179647. }
  179648. }
  179649. LOCAL(void)
  179650. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179651. jvirt_barray_ptr *src_coef_arrays,
  179652. jvirt_barray_ptr *dst_coef_arrays)
  179653. /* 180 degree rotation is equivalent to
  179654. * 1. Vertical mirroring;
  179655. * 2. Horizontal mirroring.
  179656. * These two steps are merged into a single processing routine.
  179657. */
  179658. {
  179659. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179660. int ci, i, j, offset_y;
  179661. JBLOCKARRAY src_buffer, dst_buffer;
  179662. JBLOCKROW src_row_ptr, dst_row_ptr;
  179663. JCOEFPTR src_ptr, dst_ptr;
  179664. jpeg_component_info *compptr;
  179665. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179666. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179667. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179668. compptr = dstinfo->comp_info + ci;
  179669. comp_width = MCU_cols * compptr->h_samp_factor;
  179670. comp_height = MCU_rows * compptr->v_samp_factor;
  179671. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179672. dst_blk_y += compptr->v_samp_factor) {
  179673. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179674. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179675. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179676. if (dst_blk_y < comp_height) {
  179677. /* Row is within the vertically mirrorable area. */
  179678. src_buffer = (*srcinfo->mem->access_virt_barray)
  179679. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  179680. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  179681. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179682. } else {
  179683. /* Bottom-edge rows are only mirrored horizontally. */
  179684. src_buffer = (*srcinfo->mem->access_virt_barray)
  179685. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  179686. (JDIMENSION) compptr->v_samp_factor, FALSE);
  179687. }
  179688. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179689. if (dst_blk_y < comp_height) {
  179690. /* Row is within the mirrorable area. */
  179691. dst_row_ptr = dst_buffer[offset_y];
  179692. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  179693. /* Process the blocks that can be mirrored both ways. */
  179694. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179695. dst_ptr = dst_row_ptr[dst_blk_x];
  179696. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179697. for (i = 0; i < DCTSIZE; i += 2) {
  179698. /* For even row, negate every odd column. */
  179699. for (j = 0; j < DCTSIZE; j += 2) {
  179700. *dst_ptr++ = *src_ptr++;
  179701. *dst_ptr++ = - *src_ptr++;
  179702. }
  179703. /* For odd row, negate every even column. */
  179704. for (j = 0; j < DCTSIZE; j += 2) {
  179705. *dst_ptr++ = - *src_ptr++;
  179706. *dst_ptr++ = *src_ptr++;
  179707. }
  179708. }
  179709. }
  179710. /* Any remaining right-edge blocks are only mirrored vertically. */
  179711. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179712. dst_ptr = dst_row_ptr[dst_blk_x];
  179713. src_ptr = src_row_ptr[dst_blk_x];
  179714. for (i = 0; i < DCTSIZE; i += 2) {
  179715. for (j = 0; j < DCTSIZE; j++)
  179716. *dst_ptr++ = *src_ptr++;
  179717. for (j = 0; j < DCTSIZE; j++)
  179718. *dst_ptr++ = - *src_ptr++;
  179719. }
  179720. }
  179721. } else {
  179722. /* Remaining rows are just mirrored horizontally. */
  179723. dst_row_ptr = dst_buffer[offset_y];
  179724. src_row_ptr = src_buffer[offset_y];
  179725. /* Process the blocks that can be mirrored. */
  179726. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  179727. dst_ptr = dst_row_ptr[dst_blk_x];
  179728. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  179729. for (i = 0; i < DCTSIZE2; i += 2) {
  179730. *dst_ptr++ = *src_ptr++;
  179731. *dst_ptr++ = - *src_ptr++;
  179732. }
  179733. }
  179734. /* Any remaining right-edge blocks are only copied. */
  179735. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  179736. dst_ptr = dst_row_ptr[dst_blk_x];
  179737. src_ptr = src_row_ptr[dst_blk_x];
  179738. for (i = 0; i < DCTSIZE2; i++)
  179739. *dst_ptr++ = *src_ptr++;
  179740. }
  179741. }
  179742. }
  179743. }
  179744. }
  179745. }
  179746. LOCAL(void)
  179747. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  179748. jvirt_barray_ptr *src_coef_arrays,
  179749. jvirt_barray_ptr *dst_coef_arrays)
  179750. /* Transverse transpose is equivalent to
  179751. * 1. 180 degree rotation;
  179752. * 2. Transposition;
  179753. * or
  179754. * 1. Horizontal mirroring;
  179755. * 2. Transposition;
  179756. * 3. Horizontal mirroring.
  179757. * These steps are merged into a single processing routine.
  179758. */
  179759. {
  179760. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  179761. int ci, i, j, offset_x, offset_y;
  179762. JBLOCKARRAY src_buffer, dst_buffer;
  179763. JCOEFPTR src_ptr, dst_ptr;
  179764. jpeg_component_info *compptr;
  179765. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  179766. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  179767. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179768. compptr = dstinfo->comp_info + ci;
  179769. comp_width = MCU_cols * compptr->h_samp_factor;
  179770. comp_height = MCU_rows * compptr->v_samp_factor;
  179771. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  179772. dst_blk_y += compptr->v_samp_factor) {
  179773. dst_buffer = (*srcinfo->mem->access_virt_barray)
  179774. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  179775. (JDIMENSION) compptr->v_samp_factor, TRUE);
  179776. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  179777. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  179778. dst_blk_x += compptr->h_samp_factor) {
  179779. src_buffer = (*srcinfo->mem->access_virt_barray)
  179780. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  179781. (JDIMENSION) compptr->h_samp_factor, FALSE);
  179782. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  179783. if (dst_blk_y < comp_height) {
  179784. src_ptr = src_buffer[offset_x]
  179785. [comp_height - dst_blk_y - offset_y - 1];
  179786. if (dst_blk_x < comp_width) {
  179787. /* Block is within the mirrorable area. */
  179788. dst_ptr = dst_buffer[offset_y]
  179789. [comp_width - dst_blk_x - offset_x - 1];
  179790. for (i = 0; i < DCTSIZE; i++) {
  179791. for (j = 0; j < DCTSIZE; j++) {
  179792. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179793. j++;
  179794. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179795. }
  179796. i++;
  179797. for (j = 0; j < DCTSIZE; j++) {
  179798. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179799. j++;
  179800. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179801. }
  179802. }
  179803. } else {
  179804. /* Right-edge blocks are mirrored in y only */
  179805. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179806. for (i = 0; i < DCTSIZE; i++) {
  179807. for (j = 0; j < DCTSIZE; j++) {
  179808. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179809. j++;
  179810. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179811. }
  179812. }
  179813. }
  179814. } else {
  179815. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  179816. if (dst_blk_x < comp_width) {
  179817. /* Bottom-edge blocks are mirrored in x only */
  179818. dst_ptr = dst_buffer[offset_y]
  179819. [comp_width - dst_blk_x - offset_x - 1];
  179820. for (i = 0; i < DCTSIZE; i++) {
  179821. for (j = 0; j < DCTSIZE; j++)
  179822. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179823. i++;
  179824. for (j = 0; j < DCTSIZE; j++)
  179825. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  179826. }
  179827. } else {
  179828. /* At lower right corner, just transpose, no mirroring */
  179829. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  179830. for (i = 0; i < DCTSIZE; i++)
  179831. for (j = 0; j < DCTSIZE; j++)
  179832. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  179833. }
  179834. }
  179835. }
  179836. }
  179837. }
  179838. }
  179839. }
  179840. }
  179841. /* Request any required workspace.
  179842. *
  179843. * We allocate the workspace virtual arrays from the source decompression
  179844. * object, so that all the arrays (both the original data and the workspace)
  179845. * will be taken into account while making memory management decisions.
  179846. * Hence, this routine must be called after jpeg_read_header (which reads
  179847. * the image dimensions) and before jpeg_read_coefficients (which realizes
  179848. * the source's virtual arrays).
  179849. */
  179850. GLOBAL(void)
  179851. jtransform_request_workspace (j_decompress_ptr srcinfo,
  179852. jpeg_transform_info *info)
  179853. {
  179854. jvirt_barray_ptr *coef_arrays = NULL;
  179855. jpeg_component_info *compptr;
  179856. int ci;
  179857. if (info->force_grayscale &&
  179858. srcinfo->jpeg_color_space == JCS_YCbCr &&
  179859. srcinfo->num_components == 3) {
  179860. /* We'll only process the first component */
  179861. info->num_components = 1;
  179862. } else {
  179863. /* Process all the components */
  179864. info->num_components = srcinfo->num_components;
  179865. }
  179866. switch (info->transform) {
  179867. case JXFORM_NONE:
  179868. case JXFORM_FLIP_H:
  179869. /* Don't need a workspace array */
  179870. break;
  179871. case JXFORM_FLIP_V:
  179872. case JXFORM_ROT_180:
  179873. /* Need workspace arrays having same dimensions as source image.
  179874. * Note that we allocate arrays padded out to the next iMCU boundary,
  179875. * so that transform routines need not worry about missing edge blocks.
  179876. */
  179877. coef_arrays = (jvirt_barray_ptr *)
  179878. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179879. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179880. for (ci = 0; ci < info->num_components; ci++) {
  179881. compptr = srcinfo->comp_info + ci;
  179882. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179883. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179884. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179885. (long) compptr->h_samp_factor),
  179886. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179887. (long) compptr->v_samp_factor),
  179888. (JDIMENSION) compptr->v_samp_factor);
  179889. }
  179890. break;
  179891. case JXFORM_TRANSPOSE:
  179892. case JXFORM_TRANSVERSE:
  179893. case JXFORM_ROT_90:
  179894. case JXFORM_ROT_270:
  179895. /* Need workspace arrays having transposed dimensions.
  179896. * Note that we allocate arrays padded out to the next iMCU boundary,
  179897. * so that transform routines need not worry about missing edge blocks.
  179898. */
  179899. coef_arrays = (jvirt_barray_ptr *)
  179900. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  179901. SIZEOF(jvirt_barray_ptr) * info->num_components);
  179902. for (ci = 0; ci < info->num_components; ci++) {
  179903. compptr = srcinfo->comp_info + ci;
  179904. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  179905. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  179906. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  179907. (long) compptr->v_samp_factor),
  179908. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  179909. (long) compptr->h_samp_factor),
  179910. (JDIMENSION) compptr->h_samp_factor);
  179911. }
  179912. break;
  179913. }
  179914. info->workspace_coef_arrays = coef_arrays;
  179915. }
  179916. /* Transpose destination image parameters */
  179917. LOCAL(void)
  179918. transpose_critical_parameters (j_compress_ptr dstinfo)
  179919. {
  179920. int tblno, i, j, ci, itemp;
  179921. jpeg_component_info *compptr;
  179922. JQUANT_TBL *qtblptr;
  179923. JDIMENSION dtemp;
  179924. UINT16 qtemp;
  179925. /* Transpose basic image dimensions */
  179926. dtemp = dstinfo->image_width;
  179927. dstinfo->image_width = dstinfo->image_height;
  179928. dstinfo->image_height = dtemp;
  179929. /* Transpose sampling factors */
  179930. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179931. compptr = dstinfo->comp_info + ci;
  179932. itemp = compptr->h_samp_factor;
  179933. compptr->h_samp_factor = compptr->v_samp_factor;
  179934. compptr->v_samp_factor = itemp;
  179935. }
  179936. /* Transpose quantization tables */
  179937. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  179938. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  179939. if (qtblptr != NULL) {
  179940. for (i = 0; i < DCTSIZE; i++) {
  179941. for (j = 0; j < i; j++) {
  179942. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  179943. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  179944. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  179945. }
  179946. }
  179947. }
  179948. }
  179949. }
  179950. /* Trim off any partial iMCUs on the indicated destination edge */
  179951. LOCAL(void)
  179952. trim_right_edge (j_compress_ptr dstinfo)
  179953. {
  179954. int ci, max_h_samp_factor;
  179955. JDIMENSION MCU_cols;
  179956. /* We have to compute max_h_samp_factor ourselves,
  179957. * because it hasn't been set yet in the destination
  179958. * (and we don't want to use the source's value).
  179959. */
  179960. max_h_samp_factor = 1;
  179961. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179962. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  179963. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  179964. }
  179965. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  179966. if (MCU_cols > 0) /* can't trim to 0 pixels */
  179967. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  179968. }
  179969. LOCAL(void)
  179970. trim_bottom_edge (j_compress_ptr dstinfo)
  179971. {
  179972. int ci, max_v_samp_factor;
  179973. JDIMENSION MCU_rows;
  179974. /* We have to compute max_v_samp_factor ourselves,
  179975. * because it hasn't been set yet in the destination
  179976. * (and we don't want to use the source's value).
  179977. */
  179978. max_v_samp_factor = 1;
  179979. for (ci = 0; ci < dstinfo->num_components; ci++) {
  179980. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  179981. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  179982. }
  179983. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  179984. if (MCU_rows > 0) /* can't trim to 0 pixels */
  179985. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  179986. }
  179987. /* Adjust output image parameters as needed.
  179988. *
  179989. * This must be called after jpeg_copy_critical_parameters()
  179990. * and before jpeg_write_coefficients().
  179991. *
  179992. * The return value is the set of virtual coefficient arrays to be written
  179993. * (either the ones allocated by jtransform_request_workspace, or the
  179994. * original source data arrays). The caller will need to pass this value
  179995. * to jpeg_write_coefficients().
  179996. */
  179997. GLOBAL(jvirt_barray_ptr *)
  179998. jtransform_adjust_parameters (j_decompress_ptr,
  179999. j_compress_ptr dstinfo,
  180000. jvirt_barray_ptr *src_coef_arrays,
  180001. jpeg_transform_info *info)
  180002. {
  180003. /* If force-to-grayscale is requested, adjust destination parameters */
  180004. if (info->force_grayscale) {
  180005. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  180006. * properly. Among other things, the target h_samp_factor & v_samp_factor
  180007. * will get set to 1, which typically won't match the source.
  180008. * In fact we do this even if the source is already grayscale; that
  180009. * provides an easy way of coercing a grayscale JPEG with funny sampling
  180010. * factors to the customary 1,1. (Some decoders fail on other factors.)
  180011. */
  180012. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  180013. dstinfo->num_components == 3) ||
  180014. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  180015. dstinfo->num_components == 1)) {
  180016. /* We have to preserve the source's quantization table number. */
  180017. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  180018. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  180019. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  180020. } else {
  180021. /* Sorry, can't do it */
  180022. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  180023. }
  180024. }
  180025. /* Correct the destination's image dimensions etc if necessary */
  180026. switch (info->transform) {
  180027. case JXFORM_NONE:
  180028. /* Nothing to do */
  180029. break;
  180030. case JXFORM_FLIP_H:
  180031. if (info->trim)
  180032. trim_right_edge(dstinfo);
  180033. break;
  180034. case JXFORM_FLIP_V:
  180035. if (info->trim)
  180036. trim_bottom_edge(dstinfo);
  180037. break;
  180038. case JXFORM_TRANSPOSE:
  180039. transpose_critical_parameters(dstinfo);
  180040. /* transpose does NOT have to trim anything */
  180041. break;
  180042. case JXFORM_TRANSVERSE:
  180043. transpose_critical_parameters(dstinfo);
  180044. if (info->trim) {
  180045. trim_right_edge(dstinfo);
  180046. trim_bottom_edge(dstinfo);
  180047. }
  180048. break;
  180049. case JXFORM_ROT_90:
  180050. transpose_critical_parameters(dstinfo);
  180051. if (info->trim)
  180052. trim_right_edge(dstinfo);
  180053. break;
  180054. case JXFORM_ROT_180:
  180055. if (info->trim) {
  180056. trim_right_edge(dstinfo);
  180057. trim_bottom_edge(dstinfo);
  180058. }
  180059. break;
  180060. case JXFORM_ROT_270:
  180061. transpose_critical_parameters(dstinfo);
  180062. if (info->trim)
  180063. trim_bottom_edge(dstinfo);
  180064. break;
  180065. }
  180066. /* Return the appropriate output data set */
  180067. if (info->workspace_coef_arrays != NULL)
  180068. return info->workspace_coef_arrays;
  180069. return src_coef_arrays;
  180070. }
  180071. /* Execute the actual transformation, if any.
  180072. *
  180073. * This must be called *after* jpeg_write_coefficients, because it depends
  180074. * on jpeg_write_coefficients to have computed subsidiary values such as
  180075. * the per-component width and height fields in the destination object.
  180076. *
  180077. * Note that some transformations will modify the source data arrays!
  180078. */
  180079. GLOBAL(void)
  180080. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180081. j_compress_ptr dstinfo,
  180082. jvirt_barray_ptr *src_coef_arrays,
  180083. jpeg_transform_info *info)
  180084. {
  180085. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180086. switch (info->transform) {
  180087. case JXFORM_NONE:
  180088. break;
  180089. case JXFORM_FLIP_H:
  180090. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180091. break;
  180092. case JXFORM_FLIP_V:
  180093. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180094. break;
  180095. case JXFORM_TRANSPOSE:
  180096. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180097. break;
  180098. case JXFORM_TRANSVERSE:
  180099. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180100. break;
  180101. case JXFORM_ROT_90:
  180102. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180103. break;
  180104. case JXFORM_ROT_180:
  180105. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180106. break;
  180107. case JXFORM_ROT_270:
  180108. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180109. break;
  180110. }
  180111. }
  180112. #endif /* TRANSFORMS_SUPPORTED */
  180113. /* Setup decompression object to save desired markers in memory.
  180114. * This must be called before jpeg_read_header() to have the desired effect.
  180115. */
  180116. GLOBAL(void)
  180117. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180118. {
  180119. #ifdef SAVE_MARKERS_SUPPORTED
  180120. int m;
  180121. /* Save comments except under NONE option */
  180122. if (option != JCOPYOPT_NONE) {
  180123. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180124. }
  180125. /* Save all types of APPn markers iff ALL option */
  180126. if (option == JCOPYOPT_ALL) {
  180127. for (m = 0; m < 16; m++)
  180128. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180129. }
  180130. #endif /* SAVE_MARKERS_SUPPORTED */
  180131. }
  180132. /* Copy markers saved in the given source object to the destination object.
  180133. * This should be called just after jpeg_start_compress() or
  180134. * jpeg_write_coefficients().
  180135. * Note that those routines will have written the SOI, and also the
  180136. * JFIF APP0 or Adobe APP14 markers if selected.
  180137. */
  180138. GLOBAL(void)
  180139. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180140. JCOPY_OPTION)
  180141. {
  180142. jpeg_saved_marker_ptr marker;
  180143. /* In the current implementation, we don't actually need to examine the
  180144. * option flag here; we just copy everything that got saved.
  180145. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180146. * if the encoder library already wrote one.
  180147. */
  180148. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180149. if (dstinfo->write_JFIF_header &&
  180150. marker->marker == JPEG_APP0 &&
  180151. marker->data_length >= 5 &&
  180152. GETJOCTET(marker->data[0]) == 0x4A &&
  180153. GETJOCTET(marker->data[1]) == 0x46 &&
  180154. GETJOCTET(marker->data[2]) == 0x49 &&
  180155. GETJOCTET(marker->data[3]) == 0x46 &&
  180156. GETJOCTET(marker->data[4]) == 0)
  180157. continue; /* reject duplicate JFIF */
  180158. if (dstinfo->write_Adobe_marker &&
  180159. marker->marker == JPEG_APP0+14 &&
  180160. marker->data_length >= 5 &&
  180161. GETJOCTET(marker->data[0]) == 0x41 &&
  180162. GETJOCTET(marker->data[1]) == 0x64 &&
  180163. GETJOCTET(marker->data[2]) == 0x6F &&
  180164. GETJOCTET(marker->data[3]) == 0x62 &&
  180165. GETJOCTET(marker->data[4]) == 0x65)
  180166. continue; /* reject duplicate Adobe */
  180167. #ifdef NEED_FAR_POINTERS
  180168. /* We could use jpeg_write_marker if the data weren't FAR... */
  180169. {
  180170. unsigned int i;
  180171. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180172. for (i = 0; i < marker->data_length; i++)
  180173. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180174. }
  180175. #else
  180176. jpeg_write_marker(dstinfo, marker->marker,
  180177. marker->data, marker->data_length);
  180178. #endif
  180179. }
  180180. }
  180181. /*** End of inlined file: transupp.c ***/
  180182. #else
  180183. #define JPEG_INTERNALS
  180184. #undef FAR
  180185. #include <jpeglib.h>
  180186. #endif
  180187. }
  180188. #undef max
  180189. #undef min
  180190. #if JUCE_MSVC
  180191. #pragma warning (pop)
  180192. #endif
  180193. BEGIN_JUCE_NAMESPACE
  180194. namespace JPEGHelpers
  180195. {
  180196. using namespace jpeglibNamespace;
  180197. #if ! JUCE_MSVC
  180198. using jpeglibNamespace::boolean;
  180199. #endif
  180200. struct JPEGDecodingFailure {};
  180201. static void fatalErrorHandler (j_common_ptr)
  180202. {
  180203. throw JPEGDecodingFailure();
  180204. }
  180205. static void silentErrorCallback1 (j_common_ptr) {}
  180206. static void silentErrorCallback2 (j_common_ptr, int) {}
  180207. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180208. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180209. {
  180210. zerostruct (err);
  180211. err.error_exit = fatalErrorHandler;
  180212. err.emit_message = silentErrorCallback2;
  180213. err.output_message = silentErrorCallback1;
  180214. err.format_message = silentErrorCallback3;
  180215. err.reset_error_mgr = silentErrorCallback1;
  180216. }
  180217. static void dummyCallback1 (j_decompress_ptr)
  180218. {
  180219. }
  180220. static void jpegSkip (j_decompress_ptr decompStruct, long num)
  180221. {
  180222. decompStruct->src->next_input_byte += num;
  180223. num = jmin (num, (long) decompStruct->src->bytes_in_buffer);
  180224. decompStruct->src->bytes_in_buffer -= num;
  180225. }
  180226. static boolean jpegFill (j_decompress_ptr)
  180227. {
  180228. return 0;
  180229. }
  180230. static const int jpegBufferSize = 512;
  180231. struct JuceJpegDest : public jpeg_destination_mgr
  180232. {
  180233. OutputStream* output;
  180234. char* buffer;
  180235. };
  180236. static void jpegWriteInit (j_compress_ptr)
  180237. {
  180238. }
  180239. static void jpegWriteTerminate (j_compress_ptr cinfo)
  180240. {
  180241. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180242. const size_t numToWrite = jpegBufferSize - dest->free_in_buffer;
  180243. dest->output->write (dest->buffer, (int) numToWrite);
  180244. }
  180245. static boolean jpegWriteFlush (j_compress_ptr cinfo)
  180246. {
  180247. JuceJpegDest* const dest = static_cast <JuceJpegDest*> (cinfo->dest);
  180248. const int numToWrite = jpegBufferSize;
  180249. dest->next_output_byte = reinterpret_cast <JOCTET*> (dest->buffer);
  180250. dest->free_in_buffer = jpegBufferSize;
  180251. return dest->output->write (dest->buffer, numToWrite);
  180252. }
  180253. }
  180254. JPEGImageFormat::JPEGImageFormat()
  180255. : quality (-1.0f)
  180256. {
  180257. }
  180258. JPEGImageFormat::~JPEGImageFormat() {}
  180259. void JPEGImageFormat::setQuality (const float newQuality)
  180260. {
  180261. quality = newQuality;
  180262. }
  180263. const String JPEGImageFormat::getFormatName()
  180264. {
  180265. return "JPEG";
  180266. }
  180267. bool JPEGImageFormat::canUnderstand (InputStream& in)
  180268. {
  180269. const int bytesNeeded = 10;
  180270. uint8 header [bytesNeeded];
  180271. if (in.read (header, bytesNeeded) == bytesNeeded)
  180272. {
  180273. return header[0] == 0xff
  180274. && header[1] == 0xd8
  180275. && header[2] == 0xff
  180276. && (header[3] == 0xe0 || header[3] == 0xe1);
  180277. }
  180278. return false;
  180279. }
  180280. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180281. const Image juce_loadWithCoreImage (InputStream& input);
  180282. #endif
  180283. const Image JPEGImageFormat::decodeImage (InputStream& in)
  180284. {
  180285. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  180286. return juce_loadWithCoreImage (in);
  180287. #else
  180288. using namespace jpeglibNamespace;
  180289. using namespace JPEGHelpers;
  180290. MemoryOutputStream mb;
  180291. mb.writeFromInputStream (in, -1);
  180292. Image image;
  180293. if (mb.getDataSize() > 16)
  180294. {
  180295. struct jpeg_decompress_struct jpegDecompStruct;
  180296. struct jpeg_error_mgr jerr;
  180297. setupSilentErrorHandler (jerr);
  180298. jpegDecompStruct.err = &jerr;
  180299. jpeg_create_decompress (&jpegDecompStruct);
  180300. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  180301. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  180302. jpegDecompStruct.src->init_source = dummyCallback1;
  180303. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  180304. jpegDecompStruct.src->skip_input_data = jpegSkip;
  180305. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  180306. jpegDecompStruct.src->term_source = dummyCallback1;
  180307. jpegDecompStruct.src->next_input_byte = static_cast <const unsigned char*> (mb.getData());
  180308. jpegDecompStruct.src->bytes_in_buffer = mb.getDataSize();
  180309. try
  180310. {
  180311. jpeg_read_header (&jpegDecompStruct, TRUE);
  180312. jpeg_calc_output_dimensions (&jpegDecompStruct);
  180313. const int width = jpegDecompStruct.output_width;
  180314. const int height = jpegDecompStruct.output_height;
  180315. jpegDecompStruct.out_color_space = JCS_RGB;
  180316. JSAMPARRAY buffer
  180317. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  180318. JPOOL_IMAGE,
  180319. width * 3, 1);
  180320. if (jpeg_start_decompress (&jpegDecompStruct))
  180321. {
  180322. image = Image (Image::RGB, width, height, false);
  180323. image.getProperties()->set ("originalImageHadAlpha", false);
  180324. const bool hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  180325. const Image::BitmapData destData (image, true);
  180326. for (int y = 0; y < height; ++y)
  180327. {
  180328. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  180329. const uint8* src = *buffer;
  180330. uint8* dest = destData.getLinePointer (y);
  180331. if (hasAlphaChan)
  180332. {
  180333. for (int i = width; --i >= 0;)
  180334. {
  180335. ((PixelARGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180336. ((PixelARGB*) dest)->premultiply();
  180337. dest += destData.pixelStride;
  180338. src += 3;
  180339. }
  180340. }
  180341. else
  180342. {
  180343. for (int i = width; --i >= 0;)
  180344. {
  180345. ((PixelRGB*) dest)->setARGB (0xff, src[0], src[1], src[2]);
  180346. dest += destData.pixelStride;
  180347. src += 3;
  180348. }
  180349. }
  180350. }
  180351. jpeg_finish_decompress (&jpegDecompStruct);
  180352. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  180353. }
  180354. jpeg_destroy_decompress (&jpegDecompStruct);
  180355. }
  180356. catch (...)
  180357. {}
  180358. }
  180359. return image;
  180360. #endif
  180361. }
  180362. bool JPEGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  180363. {
  180364. using namespace jpeglibNamespace;
  180365. using namespace JPEGHelpers;
  180366. if (image.hasAlphaChannel())
  180367. {
  180368. // this method could fill the background in white and still save the image..
  180369. jassertfalse;
  180370. return true;
  180371. }
  180372. struct jpeg_compress_struct jpegCompStruct;
  180373. struct jpeg_error_mgr jerr;
  180374. setupSilentErrorHandler (jerr);
  180375. jpegCompStruct.err = &jerr;
  180376. jpeg_create_compress (&jpegCompStruct);
  180377. JuceJpegDest dest;
  180378. jpegCompStruct.dest = &dest;
  180379. dest.output = &out;
  180380. HeapBlock <char> tempBuffer (jpegBufferSize);
  180381. dest.buffer = tempBuffer;
  180382. dest.next_output_byte = (JOCTET*) dest.buffer;
  180383. dest.free_in_buffer = jpegBufferSize;
  180384. dest.init_destination = jpegWriteInit;
  180385. dest.empty_output_buffer = jpegWriteFlush;
  180386. dest.term_destination = jpegWriteTerminate;
  180387. jpegCompStruct.image_width = image.getWidth();
  180388. jpegCompStruct.image_height = image.getHeight();
  180389. jpegCompStruct.input_components = 3;
  180390. jpegCompStruct.in_color_space = JCS_RGB;
  180391. jpegCompStruct.write_JFIF_header = 1;
  180392. jpegCompStruct.X_density = 72;
  180393. jpegCompStruct.Y_density = 72;
  180394. jpeg_set_defaults (&jpegCompStruct);
  180395. jpegCompStruct.dct_method = JDCT_FLOAT;
  180396. jpegCompStruct.optimize_coding = 1;
  180397. //jpegCompStruct.smoothing_factor = 10;
  180398. if (quality < 0.0f)
  180399. quality = 0.85f;
  180400. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundToInt (quality * 100.0f)), TRUE);
  180401. jpeg_start_compress (&jpegCompStruct, TRUE);
  180402. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  180403. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  180404. JPOOL_IMAGE, strideBytes, 1);
  180405. const Image::BitmapData srcData (image, false);
  180406. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  180407. {
  180408. const uint8* src = srcData.getLinePointer (jpegCompStruct.next_scanline);
  180409. uint8* dst = *buffer;
  180410. for (int i = jpegCompStruct.image_width; --i >= 0;)
  180411. {
  180412. *dst++ = ((const PixelRGB*) src)->getRed();
  180413. *dst++ = ((const PixelRGB*) src)->getGreen();
  180414. *dst++ = ((const PixelRGB*) src)->getBlue();
  180415. src += srcData.pixelStride;
  180416. }
  180417. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  180418. }
  180419. jpeg_finish_compress (&jpegCompStruct);
  180420. jpeg_destroy_compress (&jpegCompStruct);
  180421. out.flush();
  180422. return true;
  180423. }
  180424. END_JUCE_NAMESPACE
  180425. /*** End of inlined file: juce_JPEGLoader.cpp ***/
  180426. /*** Start of inlined file: juce_PNGLoader.cpp ***/
  180427. #if JUCE_MSVC
  180428. #pragma warning (push)
  180429. #pragma warning (disable: 4390 4611)
  180430. #endif
  180431. namespace zlibNamespace
  180432. {
  180433. #if JUCE_INCLUDE_ZLIB_CODE
  180434. #undef OS_CODE
  180435. #undef fdopen
  180436. #undef OS_CODE
  180437. #else
  180438. #include <zlib.h>
  180439. #endif
  180440. }
  180441. namespace pnglibNamespace
  180442. {
  180443. using namespace zlibNamespace;
  180444. #if JUCE_INCLUDE_PNGLIB_CODE
  180445. #if _MSC_VER != 1310
  180446. using ::calloc; // (causes conflict in VS.NET 2003)
  180447. using ::malloc;
  180448. using ::free;
  180449. #endif
  180450. using ::abs;
  180451. #define PNG_INTERNAL
  180452. #define NO_DUMMY_DECL
  180453. #define PNG_SETJMP_NOT_SUPPORTED
  180454. /*** Start of inlined file: png.h ***/
  180455. /* png.h - header file for PNG reference library
  180456. *
  180457. * libpng version 1.2.21 - October 4, 2007
  180458. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180459. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180460. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180461. *
  180462. * Authors and maintainers:
  180463. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  180464. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  180465. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  180466. * See also "Contributing Authors", below.
  180467. *
  180468. * Note about libpng version numbers:
  180469. *
  180470. * Due to various miscommunications, unforeseen code incompatibilities
  180471. * and occasional factors outside the authors' control, version numbering
  180472. * on the library has not always been consistent and straightforward.
  180473. * The following table summarizes matters since version 0.89c, which was
  180474. * the first widely used release:
  180475. *
  180476. * source png.h png.h shared-lib
  180477. * version string int version
  180478. * ------- ------ ----- ----------
  180479. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  180480. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  180481. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  180482. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  180483. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  180484. * 0.97c 0.97 97 2.0.97
  180485. * 0.98 0.98 98 2.0.98
  180486. * 0.99 0.99 98 2.0.99
  180487. * 0.99a-m 0.99 99 2.0.99
  180488. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  180489. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  180490. * 1.0.1 png.h string is 10001 2.1.0
  180491. * 1.0.1a-e identical to the 10002 from here on, the shared library
  180492. * 1.0.2 source version) 10002 is 2.V where V is the source code
  180493. * 1.0.2a-b 10003 version, except as noted.
  180494. * 1.0.3 10003
  180495. * 1.0.3a-d 10004
  180496. * 1.0.4 10004
  180497. * 1.0.4a-f 10005
  180498. * 1.0.5 (+ 2 patches) 10005
  180499. * 1.0.5a-d 10006
  180500. * 1.0.5e-r 10100 (not source compatible)
  180501. * 1.0.5s-v 10006 (not binary compatible)
  180502. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  180503. * 1.0.6d-f 10007 (still binary incompatible)
  180504. * 1.0.6g 10007
  180505. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  180506. * 1.0.6i 10007 10.6i
  180507. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  180508. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  180509. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  180510. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  180511. * 1.0.7 1 10007 (still compatible)
  180512. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  180513. * 1.0.8rc1 1 10008 2.1.0.8rc1
  180514. * 1.0.8 1 10008 2.1.0.8
  180515. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  180516. * 1.0.9rc1 1 10009 2.1.0.9rc1
  180517. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  180518. * 1.0.9rc2 1 10009 2.1.0.9rc2
  180519. * 1.0.9 1 10009 2.1.0.9
  180520. * 1.0.10beta1 1 10010 2.1.0.10beta1
  180521. * 1.0.10rc1 1 10010 2.1.0.10rc1
  180522. * 1.0.10 1 10010 2.1.0.10
  180523. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  180524. * 1.0.11rc1 1 10011 2.1.0.11rc1
  180525. * 1.0.11 1 10011 2.1.0.11
  180526. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  180527. * 1.0.12rc1 2 10012 2.1.0.12rc1
  180528. * 1.0.12 2 10012 2.1.0.12
  180529. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  180530. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  180531. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  180532. * 1.2.0rc1 3 10200 3.1.2.0rc1
  180533. * 1.2.0 3 10200 3.1.2.0
  180534. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  180535. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  180536. * 1.2.1 3 10201 3.1.2.1
  180537. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  180538. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  180539. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  180540. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  180541. * 1.0.13 10 10013 10.so.0.1.0.13
  180542. * 1.2.2 12 10202 12.so.0.1.2.2
  180543. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  180544. * 1.2.3 12 10203 12.so.0.1.2.3
  180545. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  180546. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  180547. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  180548. * 1.0.14 10 10014 10.so.0.1.0.14
  180549. * 1.2.4 13 10204 12.so.0.1.2.4
  180550. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  180551. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  180552. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  180553. * 1.0.15 10 10015 10.so.0.1.0.15
  180554. * 1.2.5 13 10205 12.so.0.1.2.5
  180555. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  180556. * 1.0.16 10 10016 10.so.0.1.0.16
  180557. * 1.2.6 13 10206 12.so.0.1.2.6
  180558. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  180559. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  180560. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  180561. * 1.0.17 10 10017 10.so.0.1.0.17
  180562. * 1.2.7 13 10207 12.so.0.1.2.7
  180563. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  180564. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  180565. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  180566. * 1.0.18 10 10018 10.so.0.1.0.18
  180567. * 1.2.8 13 10208 12.so.0.1.2.8
  180568. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  180569. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  180570. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  180571. * 1.2.9 13 10209 12.so.0.9[.0]
  180572. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  180573. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  180574. * 1.2.10 13 10210 12.so.0.10[.0]
  180575. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  180576. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  180577. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  180578. * 1.0.19 10 10019 10.so.0.19[.0]
  180579. * 1.2.11 13 10211 12.so.0.11[.0]
  180580. * 1.0.20 10 10020 10.so.0.20[.0]
  180581. * 1.2.12 13 10212 12.so.0.12[.0]
  180582. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  180583. * 1.0.21 10 10021 10.so.0.21[.0]
  180584. * 1.2.13 13 10213 12.so.0.13[.0]
  180585. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  180586. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  180587. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  180588. * 1.0.22 10 10022 10.so.0.22[.0]
  180589. * 1.2.14 13 10214 12.so.0.14[.0]
  180590. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  180591. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  180592. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  180593. * 1.0.23 10 10023 10.so.0.23[.0]
  180594. * 1.2.15 13 10215 12.so.0.15[.0]
  180595. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  180596. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  180597. * 1.0.24 10 10024 10.so.0.24[.0]
  180598. * 1.2.16 13 10216 12.so.0.16[.0]
  180599. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  180600. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  180601. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  180602. * 1.0.25 10 10025 10.so.0.25[.0]
  180603. * 1.2.17 13 10217 12.so.0.17[.0]
  180604. * 1.0.26 10 10026 10.so.0.26[.0]
  180605. * 1.2.18 13 10218 12.so.0.18[.0]
  180606. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  180607. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  180608. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  180609. * 1.0.27 10 10027 10.so.0.27[.0]
  180610. * 1.2.19 13 10219 12.so.0.19[.0]
  180611. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  180612. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  180613. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  180614. * 1.0.28 10 10028 10.so.0.28[.0]
  180615. * 1.2.20 13 10220 12.so.0.20[.0]
  180616. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  180617. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  180618. * 1.0.29 10 10029 10.so.0.29[.0]
  180619. * 1.2.21 13 10221 12.so.0.21[.0]
  180620. *
  180621. * Henceforth the source version will match the shared-library major
  180622. * and minor numbers; the shared-library major version number will be
  180623. * used for changes in backward compatibility, as it is intended. The
  180624. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  180625. * for applications, is an unsigned integer of the form xyyzz corresponding
  180626. * to the source version x.y.z (leading zeros in y and z). Beta versions
  180627. * were given the previous public release number plus a letter, until
  180628. * version 1.0.6j; from then on they were given the upcoming public
  180629. * release number plus "betaNN" or "rcN".
  180630. *
  180631. * Binary incompatibility exists only when applications make direct access
  180632. * to the info_ptr or png_ptr members through png.h, and the compiled
  180633. * application is loaded with a different version of the library.
  180634. *
  180635. * DLLNUM will change each time there are forward or backward changes
  180636. * in binary compatibility (e.g., when a new feature is added).
  180637. *
  180638. * See libpng.txt or libpng.3 for more information. The PNG specification
  180639. * is available as a W3C Recommendation and as an ISO Specification,
  180640. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  180641. */
  180642. /*
  180643. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  180644. *
  180645. * If you modify libpng you may insert additional notices immediately following
  180646. * this sentence.
  180647. *
  180648. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  180649. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  180650. * distributed according to the same disclaimer and license as libpng-1.2.5
  180651. * with the following individual added to the list of Contributing Authors:
  180652. *
  180653. * Cosmin Truta
  180654. *
  180655. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  180656. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  180657. * distributed according to the same disclaimer and license as libpng-1.0.6
  180658. * with the following individuals added to the list of Contributing Authors:
  180659. *
  180660. * Simon-Pierre Cadieux
  180661. * Eric S. Raymond
  180662. * Gilles Vollant
  180663. *
  180664. * and with the following additions to the disclaimer:
  180665. *
  180666. * There is no warranty against interference with your enjoyment of the
  180667. * library or against infringement. There is no warranty that our
  180668. * efforts or the library will fulfill any of your particular purposes
  180669. * or needs. This library is provided with all faults, and the entire
  180670. * risk of satisfactory quality, performance, accuracy, and effort is with
  180671. * the user.
  180672. *
  180673. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  180674. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  180675. * distributed according to the same disclaimer and license as libpng-0.96,
  180676. * with the following individuals added to the list of Contributing Authors:
  180677. *
  180678. * Tom Lane
  180679. * Glenn Randers-Pehrson
  180680. * Willem van Schaik
  180681. *
  180682. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  180683. * Copyright (c) 1996, 1997 Andreas Dilger
  180684. * Distributed according to the same disclaimer and license as libpng-0.88,
  180685. * with the following individuals added to the list of Contributing Authors:
  180686. *
  180687. * John Bowler
  180688. * Kevin Bracey
  180689. * Sam Bushell
  180690. * Magnus Holmgren
  180691. * Greg Roelofs
  180692. * Tom Tanner
  180693. *
  180694. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  180695. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  180696. *
  180697. * For the purposes of this copyright and license, "Contributing Authors"
  180698. * is defined as the following set of individuals:
  180699. *
  180700. * Andreas Dilger
  180701. * Dave Martindale
  180702. * Guy Eric Schalnat
  180703. * Paul Schmidt
  180704. * Tim Wegner
  180705. *
  180706. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  180707. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  180708. * including, without limitation, the warranties of merchantability and of
  180709. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  180710. * assume no liability for direct, indirect, incidental, special, exemplary,
  180711. * or consequential damages, which may result from the use of the PNG
  180712. * Reference Library, even if advised of the possibility of such damage.
  180713. *
  180714. * Permission is hereby granted to use, copy, modify, and distribute this
  180715. * source code, or portions hereof, for any purpose, without fee, subject
  180716. * to the following restrictions:
  180717. *
  180718. * 1. The origin of this source code must not be misrepresented.
  180719. *
  180720. * 2. Altered versions must be plainly marked as such and
  180721. * must not be misrepresented as being the original source.
  180722. *
  180723. * 3. This Copyright notice may not be removed or altered from
  180724. * any source or altered source distribution.
  180725. *
  180726. * The Contributing Authors and Group 42, Inc. specifically permit, without
  180727. * fee, and encourage the use of this source code as a component to
  180728. * supporting the PNG file format in commercial products. If you use this
  180729. * source code in a product, acknowledgment is not required but would be
  180730. * appreciated.
  180731. */
  180732. /*
  180733. * A "png_get_copyright" function is available, for convenient use in "about"
  180734. * boxes and the like:
  180735. *
  180736. * printf("%s",png_get_copyright(NULL));
  180737. *
  180738. * Also, the PNG logo (in PNG format, of course) is supplied in the
  180739. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  180740. */
  180741. /*
  180742. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  180743. * certification mark of the Open Source Initiative.
  180744. */
  180745. /*
  180746. * The contributing authors would like to thank all those who helped
  180747. * with testing, bug fixes, and patience. This wouldn't have been
  180748. * possible without all of you.
  180749. *
  180750. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  180751. */
  180752. /*
  180753. * Y2K compliance in libpng:
  180754. * =========================
  180755. *
  180756. * October 4, 2007
  180757. *
  180758. * Since the PNG Development group is an ad-hoc body, we can't make
  180759. * an official declaration.
  180760. *
  180761. * This is your unofficial assurance that libpng from version 0.71 and
  180762. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  180763. * versions were also Y2K compliant.
  180764. *
  180765. * Libpng only has three year fields. One is a 2-byte unsigned integer
  180766. * that will hold years up to 65535. The other two hold the date in text
  180767. * format, and will hold years up to 9999.
  180768. *
  180769. * The integer is
  180770. * "png_uint_16 year" in png_time_struct.
  180771. *
  180772. * The strings are
  180773. * "png_charp time_buffer" in png_struct and
  180774. * "near_time_buffer", which is a local character string in png.c.
  180775. *
  180776. * There are seven time-related functions:
  180777. * png.c: png_convert_to_rfc_1123() in png.c
  180778. * (formerly png_convert_to_rfc_1152() in error)
  180779. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  180780. * png_convert_from_time_t() in pngwrite.c
  180781. * png_get_tIME() in pngget.c
  180782. * png_handle_tIME() in pngrutil.c, called in pngread.c
  180783. * png_set_tIME() in pngset.c
  180784. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  180785. *
  180786. * All handle dates properly in a Y2K environment. The
  180787. * png_convert_from_time_t() function calls gmtime() to convert from system
  180788. * clock time, which returns (year - 1900), which we properly convert to
  180789. * the full 4-digit year. There is a possibility that applications using
  180790. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  180791. * function, or that they are incorrectly passing only a 2-digit year
  180792. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  180793. * but this is not under our control. The libpng documentation has always
  180794. * stated that it works with 4-digit years, and the APIs have been
  180795. * documented as such.
  180796. *
  180797. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  180798. * integer to hold the year, and can hold years as large as 65535.
  180799. *
  180800. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  180801. * no date-related code.
  180802. *
  180803. * Glenn Randers-Pehrson
  180804. * libpng maintainer
  180805. * PNG Development Group
  180806. */
  180807. #ifndef PNG_H
  180808. #define PNG_H
  180809. /* This is not the place to learn how to use libpng. The file libpng.txt
  180810. * describes how to use libpng, and the file example.c summarizes it
  180811. * with some code on which to build. This file is useful for looking
  180812. * at the actual function definitions and structure components.
  180813. */
  180814. /* Version information for png.h - this should match the version in png.c */
  180815. #define PNG_LIBPNG_VER_STRING "1.2.21"
  180816. #define PNG_HEADER_VERSION_STRING \
  180817. " libpng version 1.2.21 - October 4, 2007\n"
  180818. #define PNG_LIBPNG_VER_SONUM 0
  180819. #define PNG_LIBPNG_VER_DLLNUM 13
  180820. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  180821. #define PNG_LIBPNG_VER_MAJOR 1
  180822. #define PNG_LIBPNG_VER_MINOR 2
  180823. #define PNG_LIBPNG_VER_RELEASE 21
  180824. /* This should match the numeric part of the final component of
  180825. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  180826. #define PNG_LIBPNG_VER_BUILD 0
  180827. /* Release Status */
  180828. #define PNG_LIBPNG_BUILD_ALPHA 1
  180829. #define PNG_LIBPNG_BUILD_BETA 2
  180830. #define PNG_LIBPNG_BUILD_RC 3
  180831. #define PNG_LIBPNG_BUILD_STABLE 4
  180832. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  180833. /* Release-Specific Flags */
  180834. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  180835. PNG_LIBPNG_BUILD_STABLE only */
  180836. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  180837. PNG_LIBPNG_BUILD_SPECIAL */
  180838. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  180839. PNG_LIBPNG_BUILD_PRIVATE */
  180840. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  180841. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  180842. * We must not include leading zeros.
  180843. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  180844. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  180845. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  180846. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  180847. #ifndef PNG_VERSION_INFO_ONLY
  180848. /* include the compression library's header */
  180849. #endif
  180850. /* include all user configurable info, including optional assembler routines */
  180851. /*** Start of inlined file: pngconf.h ***/
  180852. /* pngconf.h - machine configurable file for libpng
  180853. *
  180854. * libpng version 1.2.21 - October 4, 2007
  180855. * For conditions of distribution and use, see copyright notice in png.h
  180856. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  180857. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  180858. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  180859. */
  180860. /* Any machine specific code is near the front of this file, so if you
  180861. * are configuring libpng for a machine, you may want to read the section
  180862. * starting here down to where it starts to typedef png_color, png_text,
  180863. * and png_info.
  180864. */
  180865. #ifndef PNGCONF_H
  180866. #define PNGCONF_H
  180867. #define PNG_1_2_X
  180868. // These are some Juce config settings that should remove any unnecessary code bloat..
  180869. #define PNG_NO_STDIO 1
  180870. #define PNG_DEBUG 0
  180871. #define PNG_NO_WARNINGS 1
  180872. #define PNG_NO_ERROR_TEXT 1
  180873. #define PNG_NO_ERROR_NUMBERS 1
  180874. #define PNG_NO_USER_MEM 1
  180875. #define PNG_NO_READ_iCCP 1
  180876. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  180877. #define PNG_NO_READ_USER_CHUNKS 1
  180878. #define PNG_NO_READ_iTXt 1
  180879. #define PNG_NO_READ_sCAL 1
  180880. #define PNG_NO_READ_sPLT 1
  180881. #define png_error(a, b) png_err(a)
  180882. #define png_warning(a, b)
  180883. #define png_chunk_error(a, b) png_err(a)
  180884. #define png_chunk_warning(a, b)
  180885. /*
  180886. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  180887. * includes the resource compiler for Windows DLL configurations.
  180888. */
  180889. #ifdef PNG_USER_CONFIG
  180890. # ifndef PNG_USER_PRIVATEBUILD
  180891. # define PNG_USER_PRIVATEBUILD
  180892. # endif
  180893. #include "pngusr.h"
  180894. #endif
  180895. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  180896. #ifdef PNG_CONFIGURE_LIBPNG
  180897. #ifdef HAVE_CONFIG_H
  180898. #include "config.h"
  180899. #endif
  180900. #endif
  180901. /*
  180902. * Added at libpng-1.2.8
  180903. *
  180904. * If you create a private DLL you need to define in "pngusr.h" the followings:
  180905. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  180906. * the DLL was built>
  180907. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  180908. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  180909. * distinguish your DLL from those of the official release. These
  180910. * correspond to the trailing letters that come after the version
  180911. * number and must match your private DLL name>
  180912. * e.g. // private DLL "libpng13gx.dll"
  180913. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  180914. *
  180915. * The following macros are also at your disposal if you want to complete the
  180916. * DLL VERSIONINFO structure.
  180917. * - PNG_USER_VERSIONINFO_COMMENTS
  180918. * - PNG_USER_VERSIONINFO_COMPANYNAME
  180919. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  180920. */
  180921. #ifdef __STDC__
  180922. #ifdef SPECIALBUILD
  180923. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  180924. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  180925. #endif
  180926. #ifdef PRIVATEBUILD
  180927. # pragma message("PRIVATEBUILD is deprecated.\
  180928. Use PNG_USER_PRIVATEBUILD instead.")
  180929. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  180930. #endif
  180931. #endif /* __STDC__ */
  180932. #ifndef PNG_VERSION_INFO_ONLY
  180933. /* End of material added to libpng-1.2.8 */
  180934. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  180935. Restored at libpng-1.2.21 */
  180936. # define PNG_WARN_UNINITIALIZED_ROW 1
  180937. /* End of material added at libpng-1.2.19/1.2.21 */
  180938. /* This is the size of the compression buffer, and thus the size of
  180939. * an IDAT chunk. Make this whatever size you feel is best for your
  180940. * machine. One of these will be allocated per png_struct. When this
  180941. * is full, it writes the data to the disk, and does some other
  180942. * calculations. Making this an extremely small size will slow
  180943. * the library down, but you may want to experiment to determine
  180944. * where it becomes significant, if you are concerned with memory
  180945. * usage. Note that zlib allocates at least 32Kb also. For readers,
  180946. * this describes the size of the buffer available to read the data in.
  180947. * Unless this gets smaller than the size of a row (compressed),
  180948. * it should not make much difference how big this is.
  180949. */
  180950. #ifndef PNG_ZBUF_SIZE
  180951. # define PNG_ZBUF_SIZE 8192
  180952. #endif
  180953. /* Enable if you want a write-only libpng */
  180954. #ifndef PNG_NO_READ_SUPPORTED
  180955. # define PNG_READ_SUPPORTED
  180956. #endif
  180957. /* Enable if you want a read-only libpng */
  180958. #ifndef PNG_NO_WRITE_SUPPORTED
  180959. # define PNG_WRITE_SUPPORTED
  180960. #endif
  180961. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  180962. support PNGs that are embedded in MNG datastreams */
  180963. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  180964. # ifndef PNG_MNG_FEATURES_SUPPORTED
  180965. # define PNG_MNG_FEATURES_SUPPORTED
  180966. # endif
  180967. #endif
  180968. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  180969. # ifndef PNG_FLOATING_POINT_SUPPORTED
  180970. # define PNG_FLOATING_POINT_SUPPORTED
  180971. # endif
  180972. #endif
  180973. /* If you are running on a machine where you cannot allocate more
  180974. * than 64K of memory at once, uncomment this. While libpng will not
  180975. * normally need that much memory in a chunk (unless you load up a very
  180976. * large file), zlib needs to know how big of a chunk it can use, and
  180977. * libpng thus makes sure to check any memory allocation to verify it
  180978. * will fit into memory.
  180979. #define PNG_MAX_MALLOC_64K
  180980. */
  180981. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  180982. # define PNG_MAX_MALLOC_64K
  180983. #endif
  180984. /* Special munging to support doing things the 'cygwin' way:
  180985. * 'Normal' png-on-win32 defines/defaults:
  180986. * PNG_BUILD_DLL -- building dll
  180987. * PNG_USE_DLL -- building an application, linking to dll
  180988. * (no define) -- building static library, or building an
  180989. * application and linking to the static lib
  180990. * 'Cygwin' defines/defaults:
  180991. * PNG_BUILD_DLL -- (ignored) building the dll
  180992. * (no define) -- (ignored) building an application, linking to the dll
  180993. * PNG_STATIC -- (ignored) building the static lib, or building an
  180994. * application that links to the static lib.
  180995. * ALL_STATIC -- (ignored) building various static libs, or building an
  180996. * application that links to the static libs.
  180997. * Thus,
  180998. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  180999. * this bit of #ifdefs will define the 'correct' config variables based on
  181000. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  181001. * unnecessary.
  181002. *
  181003. * Also, the precedence order is:
  181004. * ALL_STATIC (since we can't #undef something outside our namespace)
  181005. * PNG_BUILD_DLL
  181006. * PNG_STATIC
  181007. * (nothing) == PNG_USE_DLL
  181008. *
  181009. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  181010. * of auto-import in binutils, we no longer need to worry about
  181011. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  181012. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  181013. * to __declspec() stuff. However, we DO need to worry about
  181014. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  181015. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  181016. */
  181017. #if defined(__CYGWIN__)
  181018. # if defined(ALL_STATIC)
  181019. # if defined(PNG_BUILD_DLL)
  181020. # undef PNG_BUILD_DLL
  181021. # endif
  181022. # if defined(PNG_USE_DLL)
  181023. # undef PNG_USE_DLL
  181024. # endif
  181025. # if defined(PNG_DLL)
  181026. # undef PNG_DLL
  181027. # endif
  181028. # if !defined(PNG_STATIC)
  181029. # define PNG_STATIC
  181030. # endif
  181031. # else
  181032. # if defined (PNG_BUILD_DLL)
  181033. # if defined(PNG_STATIC)
  181034. # undef PNG_STATIC
  181035. # endif
  181036. # if defined(PNG_USE_DLL)
  181037. # undef PNG_USE_DLL
  181038. # endif
  181039. # if !defined(PNG_DLL)
  181040. # define PNG_DLL
  181041. # endif
  181042. # else
  181043. # if defined(PNG_STATIC)
  181044. # if defined(PNG_USE_DLL)
  181045. # undef PNG_USE_DLL
  181046. # endif
  181047. # if defined(PNG_DLL)
  181048. # undef PNG_DLL
  181049. # endif
  181050. # else
  181051. # if !defined(PNG_USE_DLL)
  181052. # define PNG_USE_DLL
  181053. # endif
  181054. # if !defined(PNG_DLL)
  181055. # define PNG_DLL
  181056. # endif
  181057. # endif
  181058. # endif
  181059. # endif
  181060. #endif
  181061. /* This protects us against compilers that run on a windowing system
  181062. * and thus don't have or would rather us not use the stdio types:
  181063. * stdin, stdout, and stderr. The only one currently used is stderr
  181064. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181065. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181066. * will also prevent these, plus will prevent the entire set of stdio
  181067. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181068. * unless (PNG_DEBUG > 0) has been #defined.
  181069. *
  181070. * #define PNG_NO_CONSOLE_IO
  181071. * #define PNG_NO_STDIO
  181072. */
  181073. #if defined(_WIN32_WCE)
  181074. # include <windows.h>
  181075. /* Console I/O functions are not supported on WindowsCE */
  181076. # define PNG_NO_CONSOLE_IO
  181077. # ifdef PNG_DEBUG
  181078. # undef PNG_DEBUG
  181079. # endif
  181080. #endif
  181081. #ifdef PNG_BUILD_DLL
  181082. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181083. # ifndef PNG_NO_CONSOLE_IO
  181084. # define PNG_NO_CONSOLE_IO
  181085. # endif
  181086. # endif
  181087. #endif
  181088. # ifdef PNG_NO_STDIO
  181089. # ifndef PNG_NO_CONSOLE_IO
  181090. # define PNG_NO_CONSOLE_IO
  181091. # endif
  181092. # ifdef PNG_DEBUG
  181093. # if (PNG_DEBUG > 0)
  181094. # include <stdio.h>
  181095. # endif
  181096. # endif
  181097. # else
  181098. # if !defined(_WIN32_WCE)
  181099. /* "stdio.h" functions are not supported on WindowsCE */
  181100. # include <stdio.h>
  181101. # endif
  181102. # endif
  181103. /* This macro protects us against machines that don't have function
  181104. * prototypes (ie K&R style headers). If your compiler does not handle
  181105. * function prototypes, define this macro and use the included ansi2knr.
  181106. * I've always been able to use _NO_PROTO as the indicator, but you may
  181107. * need to drag the empty declaration out in front of here, or change the
  181108. * ifdef to suit your own needs.
  181109. */
  181110. #ifndef PNGARG
  181111. #ifdef OF /* zlib prototype munger */
  181112. # define PNGARG(arglist) OF(arglist)
  181113. #else
  181114. #ifdef _NO_PROTO
  181115. # define PNGARG(arglist) ()
  181116. # ifndef PNG_TYPECAST_NULL
  181117. # define PNG_TYPECAST_NULL
  181118. # endif
  181119. #else
  181120. # define PNGARG(arglist) arglist
  181121. #endif /* _NO_PROTO */
  181122. #endif /* OF */
  181123. #endif /* PNGARG */
  181124. /* Try to determine if we are compiling on a Mac. Note that testing for
  181125. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181126. * on non-Mac platforms.
  181127. */
  181128. #ifndef MACOS
  181129. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181130. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181131. # define MACOS
  181132. # endif
  181133. #endif
  181134. /* enough people need this for various reasons to include it here */
  181135. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181136. # include <sys/types.h>
  181137. #endif
  181138. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181139. # define PNG_SETJMP_SUPPORTED
  181140. #endif
  181141. #ifdef PNG_SETJMP_SUPPORTED
  181142. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181143. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181144. */
  181145. # ifdef __linux__
  181146. # ifdef _BSD_SOURCE
  181147. # define PNG_SAVE_BSD_SOURCE
  181148. # undef _BSD_SOURCE
  181149. # endif
  181150. # ifdef _SETJMP_H
  181151. /* If you encounter a compiler error here, see the explanation
  181152. * near the end of INSTALL.
  181153. */
  181154. __png.h__ already includes setjmp.h;
  181155. __dont__ include it again.;
  181156. # endif
  181157. # endif /* __linux__ */
  181158. /* include setjmp.h for error handling */
  181159. # include <setjmp.h>
  181160. # ifdef __linux__
  181161. # ifdef PNG_SAVE_BSD_SOURCE
  181162. # define _BSD_SOURCE
  181163. # undef PNG_SAVE_BSD_SOURCE
  181164. # endif
  181165. # endif /* __linux__ */
  181166. #endif /* PNG_SETJMP_SUPPORTED */
  181167. #ifdef BSD
  181168. #if ! JUCE_MAC
  181169. # include <strings.h>
  181170. #endif
  181171. #else
  181172. # include <string.h>
  181173. #endif
  181174. /* Other defines for things like memory and the like can go here. */
  181175. #ifdef PNG_INTERNAL
  181176. #include <stdlib.h>
  181177. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181178. * aren't usually used outside the library (as far as I know), so it is
  181179. * debatable if they should be exported at all. In the future, when it is
  181180. * possible to have run-time registry of chunk-handling functions, some of
  181181. * these will be made available again.
  181182. #define PNG_EXTERN extern
  181183. */
  181184. #define PNG_EXTERN
  181185. /* Other defines specific to compilers can go here. Try to keep
  181186. * them inside an appropriate ifdef/endif pair for portability.
  181187. */
  181188. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181189. # if defined(MACOS)
  181190. /* We need to check that <math.h> hasn't already been included earlier
  181191. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181192. * <fp.h> if possible.
  181193. */
  181194. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181195. # include <fp.h>
  181196. # endif
  181197. # else
  181198. # include <math.h>
  181199. # endif
  181200. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181201. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181202. * MATH=68881
  181203. */
  181204. # include <m68881.h>
  181205. # endif
  181206. #endif
  181207. /* Codewarrior on NT has linking problems without this. */
  181208. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181209. # define PNG_ALWAYS_EXTERN
  181210. #endif
  181211. /* This provides the non-ANSI (far) memory allocation routines. */
  181212. #if defined(__TURBOC__) && defined(__MSDOS__)
  181213. # include <mem.h>
  181214. # include <alloc.h>
  181215. #endif
  181216. /* I have no idea why is this necessary... */
  181217. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181218. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181219. # include <malloc.h>
  181220. #endif
  181221. /* This controls how fine the dithering gets. As this allocates
  181222. * a largish chunk of memory (32K), those who are not as concerned
  181223. * with dithering quality can decrease some or all of these.
  181224. */
  181225. #ifndef PNG_DITHER_RED_BITS
  181226. # define PNG_DITHER_RED_BITS 5
  181227. #endif
  181228. #ifndef PNG_DITHER_GREEN_BITS
  181229. # define PNG_DITHER_GREEN_BITS 5
  181230. #endif
  181231. #ifndef PNG_DITHER_BLUE_BITS
  181232. # define PNG_DITHER_BLUE_BITS 5
  181233. #endif
  181234. /* This controls how fine the gamma correction becomes when you
  181235. * are only interested in 8 bits anyway. Increasing this value
  181236. * results in more memory being used, and more pow() functions
  181237. * being called to fill in the gamma tables. Don't set this value
  181238. * less then 8, and even that may not work (I haven't tested it).
  181239. */
  181240. #ifndef PNG_MAX_GAMMA_8
  181241. # define PNG_MAX_GAMMA_8 11
  181242. #endif
  181243. /* This controls how much a difference in gamma we can tolerate before
  181244. * we actually start doing gamma conversion.
  181245. */
  181246. #ifndef PNG_GAMMA_THRESHOLD
  181247. # define PNG_GAMMA_THRESHOLD 0.05
  181248. #endif
  181249. #endif /* PNG_INTERNAL */
  181250. /* The following uses const char * instead of char * for error
  181251. * and warning message functions, so some compilers won't complain.
  181252. * If you do not want to use const, define PNG_NO_CONST here.
  181253. */
  181254. #ifndef PNG_NO_CONST
  181255. # define PNG_CONST const
  181256. #else
  181257. # define PNG_CONST
  181258. #endif
  181259. /* The following defines give you the ability to remove code from the
  181260. * library that you will not be using. I wish I could figure out how to
  181261. * automate this, but I can't do that without making it seriously hard
  181262. * on the users. So if you are not using an ability, change the #define
  181263. * to and #undef, and that part of the library will not be compiled. If
  181264. * your linker can't find a function, you may want to make sure the
  181265. * ability is defined here. Some of these depend upon some others being
  181266. * defined. I haven't figured out all the interactions here, so you may
  181267. * have to experiment awhile to get everything to compile. If you are
  181268. * creating or using a shared library, you probably shouldn't touch this,
  181269. * as it will affect the size of the structures, and this will cause bad
  181270. * things to happen if the library and/or application ever change.
  181271. */
  181272. /* Any features you will not be using can be undef'ed here */
  181273. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181274. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181275. * on the compile line, then pick and choose which ones to define without
  181276. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181277. * if you only want to have a png-compliant reader/writer but don't need
  181278. * any of the extra transformations. This saves about 80 kbytes in a
  181279. * typical installation of the library. (PNG_NO_* form added in version
  181280. * 1.0.1c, for consistency)
  181281. */
  181282. /* The size of the png_text structure changed in libpng-1.0.6 when
  181283. * iTXt support was added. iTXt support was turned off by default through
  181284. * libpng-1.2.x, to support old apps that malloc the png_text structure
  181285. * instead of calling png_set_text() and letting libpng malloc it. It
  181286. * was turned on by default in libpng-1.3.0.
  181287. */
  181288. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181289. # ifndef PNG_NO_iTXt_SUPPORTED
  181290. # define PNG_NO_iTXt_SUPPORTED
  181291. # endif
  181292. # ifndef PNG_NO_READ_iTXt
  181293. # define PNG_NO_READ_iTXt
  181294. # endif
  181295. # ifndef PNG_NO_WRITE_iTXt
  181296. # define PNG_NO_WRITE_iTXt
  181297. # endif
  181298. #endif
  181299. #if !defined(PNG_NO_iTXt_SUPPORTED)
  181300. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  181301. # define PNG_READ_iTXt
  181302. # endif
  181303. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  181304. # define PNG_WRITE_iTXt
  181305. # endif
  181306. #endif
  181307. /* The following support, added after version 1.0.0, can be turned off here en
  181308. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  181309. * with old applications that require the length of png_struct and png_info
  181310. * to remain unchanged.
  181311. */
  181312. #ifdef PNG_LEGACY_SUPPORTED
  181313. # define PNG_NO_FREE_ME
  181314. # define PNG_NO_READ_UNKNOWN_CHUNKS
  181315. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  181316. # define PNG_NO_READ_USER_CHUNKS
  181317. # define PNG_NO_READ_iCCP
  181318. # define PNG_NO_WRITE_iCCP
  181319. # define PNG_NO_READ_iTXt
  181320. # define PNG_NO_WRITE_iTXt
  181321. # define PNG_NO_READ_sCAL
  181322. # define PNG_NO_WRITE_sCAL
  181323. # define PNG_NO_READ_sPLT
  181324. # define PNG_NO_WRITE_sPLT
  181325. # define PNG_NO_INFO_IMAGE
  181326. # define PNG_NO_READ_RGB_TO_GRAY
  181327. # define PNG_NO_READ_USER_TRANSFORM
  181328. # define PNG_NO_WRITE_USER_TRANSFORM
  181329. # define PNG_NO_USER_MEM
  181330. # define PNG_NO_READ_EMPTY_PLTE
  181331. # define PNG_NO_MNG_FEATURES
  181332. # define PNG_NO_FIXED_POINT_SUPPORTED
  181333. #endif
  181334. /* Ignore attempt to turn off both floating and fixed point support */
  181335. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  181336. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  181337. # define PNG_FIXED_POINT_SUPPORTED
  181338. #endif
  181339. #ifndef PNG_NO_FREE_ME
  181340. # define PNG_FREE_ME_SUPPORTED
  181341. #endif
  181342. #if defined(PNG_READ_SUPPORTED)
  181343. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  181344. !defined(PNG_NO_READ_TRANSFORMS)
  181345. # define PNG_READ_TRANSFORMS_SUPPORTED
  181346. #endif
  181347. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  181348. # ifndef PNG_NO_READ_EXPAND
  181349. # define PNG_READ_EXPAND_SUPPORTED
  181350. # endif
  181351. # ifndef PNG_NO_READ_SHIFT
  181352. # define PNG_READ_SHIFT_SUPPORTED
  181353. # endif
  181354. # ifndef PNG_NO_READ_PACK
  181355. # define PNG_READ_PACK_SUPPORTED
  181356. # endif
  181357. # ifndef PNG_NO_READ_BGR
  181358. # define PNG_READ_BGR_SUPPORTED
  181359. # endif
  181360. # ifndef PNG_NO_READ_SWAP
  181361. # define PNG_READ_SWAP_SUPPORTED
  181362. # endif
  181363. # ifndef PNG_NO_READ_PACKSWAP
  181364. # define PNG_READ_PACKSWAP_SUPPORTED
  181365. # endif
  181366. # ifndef PNG_NO_READ_INVERT
  181367. # define PNG_READ_INVERT_SUPPORTED
  181368. # endif
  181369. # ifndef PNG_NO_READ_DITHER
  181370. # define PNG_READ_DITHER_SUPPORTED
  181371. # endif
  181372. # ifndef PNG_NO_READ_BACKGROUND
  181373. # define PNG_READ_BACKGROUND_SUPPORTED
  181374. # endif
  181375. # ifndef PNG_NO_READ_16_TO_8
  181376. # define PNG_READ_16_TO_8_SUPPORTED
  181377. # endif
  181378. # ifndef PNG_NO_READ_FILLER
  181379. # define PNG_READ_FILLER_SUPPORTED
  181380. # endif
  181381. # ifndef PNG_NO_READ_GAMMA
  181382. # define PNG_READ_GAMMA_SUPPORTED
  181383. # endif
  181384. # ifndef PNG_NO_READ_GRAY_TO_RGB
  181385. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  181386. # endif
  181387. # ifndef PNG_NO_READ_SWAP_ALPHA
  181388. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  181389. # endif
  181390. # ifndef PNG_NO_READ_INVERT_ALPHA
  181391. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  181392. # endif
  181393. # ifndef PNG_NO_READ_STRIP_ALPHA
  181394. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  181395. # endif
  181396. # ifndef PNG_NO_READ_USER_TRANSFORM
  181397. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  181398. # endif
  181399. # ifndef PNG_NO_READ_RGB_TO_GRAY
  181400. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  181401. # endif
  181402. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  181403. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  181404. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  181405. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  181406. #endif /* about interlacing capability! You'll */
  181407. /* still have interlacing unless you change the following line: */
  181408. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  181409. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  181410. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  181411. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  181412. # endif
  181413. #endif
  181414. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181415. /* Deprecated, will be removed from version 2.0.0.
  181416. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  181417. #ifndef PNG_NO_READ_EMPTY_PLTE
  181418. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  181419. #endif
  181420. #endif
  181421. #endif /* PNG_READ_SUPPORTED */
  181422. #if defined(PNG_WRITE_SUPPORTED)
  181423. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  181424. !defined(PNG_NO_WRITE_TRANSFORMS)
  181425. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  181426. #endif
  181427. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  181428. # ifndef PNG_NO_WRITE_SHIFT
  181429. # define PNG_WRITE_SHIFT_SUPPORTED
  181430. # endif
  181431. # ifndef PNG_NO_WRITE_PACK
  181432. # define PNG_WRITE_PACK_SUPPORTED
  181433. # endif
  181434. # ifndef PNG_NO_WRITE_BGR
  181435. # define PNG_WRITE_BGR_SUPPORTED
  181436. # endif
  181437. # ifndef PNG_NO_WRITE_SWAP
  181438. # define PNG_WRITE_SWAP_SUPPORTED
  181439. # endif
  181440. # ifndef PNG_NO_WRITE_PACKSWAP
  181441. # define PNG_WRITE_PACKSWAP_SUPPORTED
  181442. # endif
  181443. # ifndef PNG_NO_WRITE_INVERT
  181444. # define PNG_WRITE_INVERT_SUPPORTED
  181445. # endif
  181446. # ifndef PNG_NO_WRITE_FILLER
  181447. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  181448. # endif
  181449. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  181450. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  181451. # endif
  181452. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  181453. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  181454. # endif
  181455. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  181456. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  181457. # endif
  181458. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  181459. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  181460. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  181461. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  181462. encoders, but can cause trouble
  181463. if left undefined */
  181464. #endif
  181465. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  181466. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  181467. defined(PNG_FLOATING_POINT_SUPPORTED)
  181468. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  181469. #endif
  181470. #ifndef PNG_NO_WRITE_FLUSH
  181471. # define PNG_WRITE_FLUSH_SUPPORTED
  181472. #endif
  181473. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  181474. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  181475. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  181476. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  181477. #endif
  181478. #endif
  181479. #endif /* PNG_WRITE_SUPPORTED */
  181480. #ifndef PNG_1_0_X
  181481. # ifndef PNG_NO_ERROR_NUMBERS
  181482. # define PNG_ERROR_NUMBERS_SUPPORTED
  181483. # endif
  181484. #endif /* PNG_1_0_X */
  181485. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  181486. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  181487. # ifndef PNG_NO_USER_TRANSFORM_PTR
  181488. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  181489. # endif
  181490. #endif
  181491. #ifndef PNG_NO_STDIO
  181492. # define PNG_TIME_RFC1123_SUPPORTED
  181493. #endif
  181494. /* This adds extra functions in pngget.c for accessing data from the
  181495. * info pointer (added in version 0.99)
  181496. * png_get_image_width()
  181497. * png_get_image_height()
  181498. * png_get_bit_depth()
  181499. * png_get_color_type()
  181500. * png_get_compression_type()
  181501. * png_get_filter_type()
  181502. * png_get_interlace_type()
  181503. * png_get_pixel_aspect_ratio()
  181504. * png_get_pixels_per_meter()
  181505. * png_get_x_offset_pixels()
  181506. * png_get_y_offset_pixels()
  181507. * png_get_x_offset_microns()
  181508. * png_get_y_offset_microns()
  181509. */
  181510. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  181511. # define PNG_EASY_ACCESS_SUPPORTED
  181512. #endif
  181513. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  181514. * and removed from version 1.2.20. The following will be removed
  181515. * from libpng-1.4.0
  181516. */
  181517. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  181518. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  181519. # define PNG_OPTIMIZED_CODE_SUPPORTED
  181520. # endif
  181521. #endif
  181522. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  181523. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  181524. # define PNG_ASSEMBLER_CODE_SUPPORTED
  181525. # endif
  181526. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  181527. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  181528. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181529. # define PNG_NO_MMX_CODE
  181530. # endif
  181531. # endif
  181532. # if defined(__APPLE__)
  181533. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181534. # define PNG_NO_MMX_CODE
  181535. # endif
  181536. # endif
  181537. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  181538. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181539. # define PNG_NO_MMX_CODE
  181540. # endif
  181541. # endif
  181542. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  181543. # define PNG_MMX_CODE_SUPPORTED
  181544. # endif
  181545. #endif
  181546. /* end of obsolete code to be removed from libpng-1.4.0 */
  181547. #if !defined(PNG_1_0_X)
  181548. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  181549. # define PNG_USER_MEM_SUPPORTED
  181550. #endif
  181551. #endif /* PNG_1_0_X */
  181552. /* Added at libpng-1.2.6 */
  181553. #if !defined(PNG_1_0_X)
  181554. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  181555. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  181556. # define PNG_SET_USER_LIMITS_SUPPORTED
  181557. #endif
  181558. #endif
  181559. #endif /* PNG_1_0_X */
  181560. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  181561. * how large, set these limits to 0x7fffffffL
  181562. */
  181563. #ifndef PNG_USER_WIDTH_MAX
  181564. # define PNG_USER_WIDTH_MAX 1000000L
  181565. #endif
  181566. #ifndef PNG_USER_HEIGHT_MAX
  181567. # define PNG_USER_HEIGHT_MAX 1000000L
  181568. #endif
  181569. /* These are currently experimental features, define them if you want */
  181570. /* very little testing */
  181571. /*
  181572. #ifdef PNG_READ_SUPPORTED
  181573. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181574. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  181575. # endif
  181576. #endif
  181577. */
  181578. /* This is only for PowerPC big-endian and 680x0 systems */
  181579. /* some testing */
  181580. /*
  181581. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  181582. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  181583. #endif
  181584. */
  181585. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  181586. /*
  181587. #define PNG_NO_POINTER_INDEXING
  181588. */
  181589. /* These functions are turned off by default, as they will be phased out. */
  181590. /*
  181591. #define PNG_USELESS_TESTS_SUPPORTED
  181592. #define PNG_CORRECT_PALETTE_SUPPORTED
  181593. */
  181594. /* Any chunks you are not interested in, you can undef here. The
  181595. * ones that allocate memory may be expecially important (hIST,
  181596. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  181597. * a bit smaller.
  181598. */
  181599. #if defined(PNG_READ_SUPPORTED) && \
  181600. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181601. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  181602. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181603. #endif
  181604. #if defined(PNG_WRITE_SUPPORTED) && \
  181605. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  181606. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  181607. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181608. #endif
  181609. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  181610. #ifdef PNG_NO_READ_TEXT
  181611. # define PNG_NO_READ_iTXt
  181612. # define PNG_NO_READ_tEXt
  181613. # define PNG_NO_READ_zTXt
  181614. #endif
  181615. #ifndef PNG_NO_READ_bKGD
  181616. # define PNG_READ_bKGD_SUPPORTED
  181617. # define PNG_bKGD_SUPPORTED
  181618. #endif
  181619. #ifndef PNG_NO_READ_cHRM
  181620. # define PNG_READ_cHRM_SUPPORTED
  181621. # define PNG_cHRM_SUPPORTED
  181622. #endif
  181623. #ifndef PNG_NO_READ_gAMA
  181624. # define PNG_READ_gAMA_SUPPORTED
  181625. # define PNG_gAMA_SUPPORTED
  181626. #endif
  181627. #ifndef PNG_NO_READ_hIST
  181628. # define PNG_READ_hIST_SUPPORTED
  181629. # define PNG_hIST_SUPPORTED
  181630. #endif
  181631. #ifndef PNG_NO_READ_iCCP
  181632. # define PNG_READ_iCCP_SUPPORTED
  181633. # define PNG_iCCP_SUPPORTED
  181634. #endif
  181635. #ifndef PNG_NO_READ_iTXt
  181636. # ifndef PNG_READ_iTXt_SUPPORTED
  181637. # define PNG_READ_iTXt_SUPPORTED
  181638. # endif
  181639. # ifndef PNG_iTXt_SUPPORTED
  181640. # define PNG_iTXt_SUPPORTED
  181641. # endif
  181642. #endif
  181643. #ifndef PNG_NO_READ_oFFs
  181644. # define PNG_READ_oFFs_SUPPORTED
  181645. # define PNG_oFFs_SUPPORTED
  181646. #endif
  181647. #ifndef PNG_NO_READ_pCAL
  181648. # define PNG_READ_pCAL_SUPPORTED
  181649. # define PNG_pCAL_SUPPORTED
  181650. #endif
  181651. #ifndef PNG_NO_READ_sCAL
  181652. # define PNG_READ_sCAL_SUPPORTED
  181653. # define PNG_sCAL_SUPPORTED
  181654. #endif
  181655. #ifndef PNG_NO_READ_pHYs
  181656. # define PNG_READ_pHYs_SUPPORTED
  181657. # define PNG_pHYs_SUPPORTED
  181658. #endif
  181659. #ifndef PNG_NO_READ_sBIT
  181660. # define PNG_READ_sBIT_SUPPORTED
  181661. # define PNG_sBIT_SUPPORTED
  181662. #endif
  181663. #ifndef PNG_NO_READ_sPLT
  181664. # define PNG_READ_sPLT_SUPPORTED
  181665. # define PNG_sPLT_SUPPORTED
  181666. #endif
  181667. #ifndef PNG_NO_READ_sRGB
  181668. # define PNG_READ_sRGB_SUPPORTED
  181669. # define PNG_sRGB_SUPPORTED
  181670. #endif
  181671. #ifndef PNG_NO_READ_tEXt
  181672. # define PNG_READ_tEXt_SUPPORTED
  181673. # define PNG_tEXt_SUPPORTED
  181674. #endif
  181675. #ifndef PNG_NO_READ_tIME
  181676. # define PNG_READ_tIME_SUPPORTED
  181677. # define PNG_tIME_SUPPORTED
  181678. #endif
  181679. #ifndef PNG_NO_READ_tRNS
  181680. # define PNG_READ_tRNS_SUPPORTED
  181681. # define PNG_tRNS_SUPPORTED
  181682. #endif
  181683. #ifndef PNG_NO_READ_zTXt
  181684. # define PNG_READ_zTXt_SUPPORTED
  181685. # define PNG_zTXt_SUPPORTED
  181686. #endif
  181687. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  181688. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  181689. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181690. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181691. # endif
  181692. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181693. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181694. # endif
  181695. #endif
  181696. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  181697. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  181698. # define PNG_READ_USER_CHUNKS_SUPPORTED
  181699. # define PNG_USER_CHUNKS_SUPPORTED
  181700. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  181701. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  181702. # endif
  181703. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  181704. # undef PNG_NO_HANDLE_AS_UNKNOWN
  181705. # endif
  181706. #endif
  181707. #ifndef PNG_NO_READ_OPT_PLTE
  181708. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  181709. #endif /* optional PLTE chunk in RGB and RGBA images */
  181710. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  181711. defined(PNG_READ_zTXt_SUPPORTED)
  181712. # define PNG_READ_TEXT_SUPPORTED
  181713. # define PNG_TEXT_SUPPORTED
  181714. #endif
  181715. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  181716. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  181717. #ifdef PNG_NO_WRITE_TEXT
  181718. # define PNG_NO_WRITE_iTXt
  181719. # define PNG_NO_WRITE_tEXt
  181720. # define PNG_NO_WRITE_zTXt
  181721. #endif
  181722. #ifndef PNG_NO_WRITE_bKGD
  181723. # define PNG_WRITE_bKGD_SUPPORTED
  181724. # ifndef PNG_bKGD_SUPPORTED
  181725. # define PNG_bKGD_SUPPORTED
  181726. # endif
  181727. #endif
  181728. #ifndef PNG_NO_WRITE_cHRM
  181729. # define PNG_WRITE_cHRM_SUPPORTED
  181730. # ifndef PNG_cHRM_SUPPORTED
  181731. # define PNG_cHRM_SUPPORTED
  181732. # endif
  181733. #endif
  181734. #ifndef PNG_NO_WRITE_gAMA
  181735. # define PNG_WRITE_gAMA_SUPPORTED
  181736. # ifndef PNG_gAMA_SUPPORTED
  181737. # define PNG_gAMA_SUPPORTED
  181738. # endif
  181739. #endif
  181740. #ifndef PNG_NO_WRITE_hIST
  181741. # define PNG_WRITE_hIST_SUPPORTED
  181742. # ifndef PNG_hIST_SUPPORTED
  181743. # define PNG_hIST_SUPPORTED
  181744. # endif
  181745. #endif
  181746. #ifndef PNG_NO_WRITE_iCCP
  181747. # define PNG_WRITE_iCCP_SUPPORTED
  181748. # ifndef PNG_iCCP_SUPPORTED
  181749. # define PNG_iCCP_SUPPORTED
  181750. # endif
  181751. #endif
  181752. #ifndef PNG_NO_WRITE_iTXt
  181753. # ifndef PNG_WRITE_iTXt_SUPPORTED
  181754. # define PNG_WRITE_iTXt_SUPPORTED
  181755. # endif
  181756. # ifndef PNG_iTXt_SUPPORTED
  181757. # define PNG_iTXt_SUPPORTED
  181758. # endif
  181759. #endif
  181760. #ifndef PNG_NO_WRITE_oFFs
  181761. # define PNG_WRITE_oFFs_SUPPORTED
  181762. # ifndef PNG_oFFs_SUPPORTED
  181763. # define PNG_oFFs_SUPPORTED
  181764. # endif
  181765. #endif
  181766. #ifndef PNG_NO_WRITE_pCAL
  181767. # define PNG_WRITE_pCAL_SUPPORTED
  181768. # ifndef PNG_pCAL_SUPPORTED
  181769. # define PNG_pCAL_SUPPORTED
  181770. # endif
  181771. #endif
  181772. #ifndef PNG_NO_WRITE_sCAL
  181773. # define PNG_WRITE_sCAL_SUPPORTED
  181774. # ifndef PNG_sCAL_SUPPORTED
  181775. # define PNG_sCAL_SUPPORTED
  181776. # endif
  181777. #endif
  181778. #ifndef PNG_NO_WRITE_pHYs
  181779. # define PNG_WRITE_pHYs_SUPPORTED
  181780. # ifndef PNG_pHYs_SUPPORTED
  181781. # define PNG_pHYs_SUPPORTED
  181782. # endif
  181783. #endif
  181784. #ifndef PNG_NO_WRITE_sBIT
  181785. # define PNG_WRITE_sBIT_SUPPORTED
  181786. # ifndef PNG_sBIT_SUPPORTED
  181787. # define PNG_sBIT_SUPPORTED
  181788. # endif
  181789. #endif
  181790. #ifndef PNG_NO_WRITE_sPLT
  181791. # define PNG_WRITE_sPLT_SUPPORTED
  181792. # ifndef PNG_sPLT_SUPPORTED
  181793. # define PNG_sPLT_SUPPORTED
  181794. # endif
  181795. #endif
  181796. #ifndef PNG_NO_WRITE_sRGB
  181797. # define PNG_WRITE_sRGB_SUPPORTED
  181798. # ifndef PNG_sRGB_SUPPORTED
  181799. # define PNG_sRGB_SUPPORTED
  181800. # endif
  181801. #endif
  181802. #ifndef PNG_NO_WRITE_tEXt
  181803. # define PNG_WRITE_tEXt_SUPPORTED
  181804. # ifndef PNG_tEXt_SUPPORTED
  181805. # define PNG_tEXt_SUPPORTED
  181806. # endif
  181807. #endif
  181808. #ifndef PNG_NO_WRITE_tIME
  181809. # define PNG_WRITE_tIME_SUPPORTED
  181810. # ifndef PNG_tIME_SUPPORTED
  181811. # define PNG_tIME_SUPPORTED
  181812. # endif
  181813. #endif
  181814. #ifndef PNG_NO_WRITE_tRNS
  181815. # define PNG_WRITE_tRNS_SUPPORTED
  181816. # ifndef PNG_tRNS_SUPPORTED
  181817. # define PNG_tRNS_SUPPORTED
  181818. # endif
  181819. #endif
  181820. #ifndef PNG_NO_WRITE_zTXt
  181821. # define PNG_WRITE_zTXt_SUPPORTED
  181822. # ifndef PNG_zTXt_SUPPORTED
  181823. # define PNG_zTXt_SUPPORTED
  181824. # endif
  181825. #endif
  181826. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  181827. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  181828. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  181829. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  181830. # endif
  181831. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  181832. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181833. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  181834. # endif
  181835. # endif
  181836. #endif
  181837. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  181838. defined(PNG_WRITE_zTXt_SUPPORTED)
  181839. # define PNG_WRITE_TEXT_SUPPORTED
  181840. # ifndef PNG_TEXT_SUPPORTED
  181841. # define PNG_TEXT_SUPPORTED
  181842. # endif
  181843. #endif
  181844. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  181845. /* Turn this off to disable png_read_png() and
  181846. * png_write_png() and leave the row_pointers member
  181847. * out of the info structure.
  181848. */
  181849. #ifndef PNG_NO_INFO_IMAGE
  181850. # define PNG_INFO_IMAGE_SUPPORTED
  181851. #endif
  181852. /* need the time information for reading tIME chunks */
  181853. #if defined(PNG_tIME_SUPPORTED)
  181854. # if !defined(_WIN32_WCE)
  181855. /* "time.h" functions are not supported on WindowsCE */
  181856. # include <time.h>
  181857. # endif
  181858. #endif
  181859. /* Some typedefs to get us started. These should be safe on most of the
  181860. * common platforms. The typedefs should be at least as large as the
  181861. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  181862. * don't have to be exactly that size. Some compilers dislike passing
  181863. * unsigned shorts as function parameters, so you may be better off using
  181864. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  181865. * want to have unsigned int for png_uint_32 instead of unsigned long.
  181866. */
  181867. typedef unsigned long png_uint_32;
  181868. typedef long png_int_32;
  181869. typedef unsigned short png_uint_16;
  181870. typedef short png_int_16;
  181871. typedef unsigned char png_byte;
  181872. /* This is usually size_t. It is typedef'ed just in case you need it to
  181873. change (I'm not sure if you will or not, so I thought I'd be safe) */
  181874. #ifdef PNG_SIZE_T
  181875. typedef PNG_SIZE_T png_size_t;
  181876. # define png_sizeof(x) png_convert_size(sizeof (x))
  181877. #else
  181878. typedef size_t png_size_t;
  181879. # define png_sizeof(x) sizeof (x)
  181880. #endif
  181881. /* The following is needed for medium model support. It cannot be in the
  181882. * PNG_INTERNAL section. Needs modification for other compilers besides
  181883. * MSC. Model independent support declares all arrays and pointers to be
  181884. * large using the far keyword. The zlib version used must also support
  181885. * model independent data. As of version zlib 1.0.4, the necessary changes
  181886. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  181887. * changes that are needed. (Tim Wegner)
  181888. */
  181889. /* Separate compiler dependencies (problem here is that zlib.h always
  181890. defines FAR. (SJT) */
  181891. #ifdef __BORLANDC__
  181892. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  181893. # define LDATA 1
  181894. # else
  181895. # define LDATA 0
  181896. # endif
  181897. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  181898. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  181899. # define PNG_MAX_MALLOC_64K
  181900. # if (LDATA != 1)
  181901. # ifndef FAR
  181902. # define FAR __far
  181903. # endif
  181904. # define USE_FAR_KEYWORD
  181905. # endif /* LDATA != 1 */
  181906. /* Possibly useful for moving data out of default segment.
  181907. * Uncomment it if you want. Could also define FARDATA as
  181908. * const if your compiler supports it. (SJT)
  181909. # define FARDATA FAR
  181910. */
  181911. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  181912. #endif /* __BORLANDC__ */
  181913. /* Suggest testing for specific compiler first before testing for
  181914. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  181915. * making reliance oncertain keywords suspect. (SJT)
  181916. */
  181917. /* MSC Medium model */
  181918. #if defined(FAR)
  181919. # if defined(M_I86MM)
  181920. # define USE_FAR_KEYWORD
  181921. # define FARDATA FAR
  181922. # include <dos.h>
  181923. # endif
  181924. #endif
  181925. /* SJT: default case */
  181926. #ifndef FAR
  181927. # define FAR
  181928. #endif
  181929. /* At this point FAR is always defined */
  181930. #ifndef FARDATA
  181931. # define FARDATA
  181932. #endif
  181933. /* Typedef for floating-point numbers that are converted
  181934. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  181935. typedef png_int_32 png_fixed_point;
  181936. /* Add typedefs for pointers */
  181937. typedef void FAR * png_voidp;
  181938. typedef png_byte FAR * png_bytep;
  181939. typedef png_uint_32 FAR * png_uint_32p;
  181940. typedef png_int_32 FAR * png_int_32p;
  181941. typedef png_uint_16 FAR * png_uint_16p;
  181942. typedef png_int_16 FAR * png_int_16p;
  181943. typedef PNG_CONST char FAR * png_const_charp;
  181944. typedef char FAR * png_charp;
  181945. typedef png_fixed_point FAR * png_fixed_point_p;
  181946. #ifndef PNG_NO_STDIO
  181947. #if defined(_WIN32_WCE)
  181948. typedef HANDLE png_FILE_p;
  181949. #else
  181950. typedef FILE * png_FILE_p;
  181951. #endif
  181952. #endif
  181953. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181954. typedef double FAR * png_doublep;
  181955. #endif
  181956. /* Pointers to pointers; i.e. arrays */
  181957. typedef png_byte FAR * FAR * png_bytepp;
  181958. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  181959. typedef png_int_32 FAR * FAR * png_int_32pp;
  181960. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  181961. typedef png_int_16 FAR * FAR * png_int_16pp;
  181962. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  181963. typedef char FAR * FAR * png_charpp;
  181964. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  181965. #ifdef PNG_FLOATING_POINT_SUPPORTED
  181966. typedef double FAR * FAR * png_doublepp;
  181967. #endif
  181968. /* Pointers to pointers to pointers; i.e., pointer to array */
  181969. typedef char FAR * FAR * FAR * png_charppp;
  181970. #if 0
  181971. /* SPC - Is this stuff deprecated? */
  181972. /* It'll be removed as of libpng-1.3.0 - GR-P */
  181973. /* libpng typedefs for types in zlib. If zlib changes
  181974. * or another compression library is used, then change these.
  181975. * Eliminates need to change all the source files.
  181976. */
  181977. typedef charf * png_zcharp;
  181978. typedef charf * FAR * png_zcharpp;
  181979. typedef z_stream FAR * png_zstreamp;
  181980. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  181981. /*
  181982. * Define PNG_BUILD_DLL if the module being built is a Windows
  181983. * LIBPNG DLL.
  181984. *
  181985. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  181986. * It is equivalent to Microsoft predefined macro _DLL that is
  181987. * automatically defined when you compile using the share
  181988. * version of the CRT (C Run-Time library)
  181989. *
  181990. * The cygwin mods make this behavior a little different:
  181991. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  181992. * Define PNG_STATIC if you are building a static library for use with cygwin,
  181993. * -or- if you are building an application that you want to link to the
  181994. * static library.
  181995. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  181996. * the other flags is defined.
  181997. */
  181998. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  181999. # define PNG_DLL
  182000. #endif
  182001. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  182002. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  182003. * command-line override
  182004. */
  182005. #if defined(__CYGWIN__)
  182006. # if !defined(PNG_STATIC)
  182007. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182008. # undef PNG_USE_GLOBAL_ARRAYS
  182009. # endif
  182010. # if !defined(PNG_USE_LOCAL_ARRAYS)
  182011. # define PNG_USE_LOCAL_ARRAYS
  182012. # endif
  182013. # else
  182014. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  182015. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182016. # undef PNG_USE_GLOBAL_ARRAYS
  182017. # endif
  182018. # endif
  182019. # endif
  182020. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182021. # define PNG_USE_LOCAL_ARRAYS
  182022. # endif
  182023. #endif
  182024. /* Do not use global arrays (helps with building DLL's)
  182025. * They are no longer used in libpng itself, since version 1.0.5c,
  182026. * but might be required for some pre-1.0.5c applications.
  182027. */
  182028. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182029. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  182030. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  182031. # define PNG_USE_LOCAL_ARRAYS
  182032. # else
  182033. # define PNG_USE_GLOBAL_ARRAYS
  182034. # endif
  182035. #endif
  182036. #if defined(__CYGWIN__)
  182037. # undef PNGAPI
  182038. # define PNGAPI __cdecl
  182039. # undef PNG_IMPEXP
  182040. # define PNG_IMPEXP
  182041. #endif
  182042. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182043. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182044. * Don't ignore those warnings; you must also reset the default calling
  182045. * convention in your compiler to match your PNGAPI, and you must build
  182046. * zlib and your applications the same way you build libpng.
  182047. */
  182048. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182049. # ifndef PNG_NO_MODULEDEF
  182050. # define PNG_NO_MODULEDEF
  182051. # endif
  182052. #endif
  182053. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182054. # define PNG_IMPEXP
  182055. #endif
  182056. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182057. (( defined(_Windows) || defined(_WINDOWS) || \
  182058. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182059. # ifndef PNGAPI
  182060. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182061. # define PNGAPI __cdecl
  182062. # else
  182063. # define PNGAPI _cdecl
  182064. # endif
  182065. # endif
  182066. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182067. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182068. # define PNG_IMPEXP
  182069. # endif
  182070. # if !defined(PNG_IMPEXP)
  182071. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182072. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182073. /* Borland/Microsoft */
  182074. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182075. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182076. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182077. # else
  182078. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182079. # if defined(PNG_BUILD_DLL)
  182080. # define PNG_IMPEXP __export
  182081. # else
  182082. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182083. VC++ */
  182084. # endif /* Exists in Borland C++ for
  182085. C++ classes (== huge) */
  182086. # endif
  182087. # endif
  182088. # if !defined(PNG_IMPEXP)
  182089. # if defined(PNG_BUILD_DLL)
  182090. # define PNG_IMPEXP __declspec(dllexport)
  182091. # else
  182092. # define PNG_IMPEXP __declspec(dllimport)
  182093. # endif
  182094. # endif
  182095. # endif /* PNG_IMPEXP */
  182096. #else /* !(DLL || non-cygwin WINDOWS) */
  182097. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182098. # ifndef PNGAPI
  182099. # define PNGAPI _System
  182100. # endif
  182101. # else
  182102. # if 0 /* ... other platforms, with other meanings */
  182103. # endif
  182104. # endif
  182105. #endif
  182106. #ifndef PNGAPI
  182107. # define PNGAPI
  182108. #endif
  182109. #ifndef PNG_IMPEXP
  182110. # define PNG_IMPEXP
  182111. #endif
  182112. #ifdef PNG_BUILDSYMS
  182113. # ifndef PNG_EXPORT
  182114. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182115. # endif
  182116. # ifdef PNG_USE_GLOBAL_ARRAYS
  182117. # ifndef PNG_EXPORT_VAR
  182118. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182119. # endif
  182120. # endif
  182121. #endif
  182122. #ifndef PNG_EXPORT
  182123. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182124. #endif
  182125. #ifdef PNG_USE_GLOBAL_ARRAYS
  182126. # ifndef PNG_EXPORT_VAR
  182127. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182128. # endif
  182129. #endif
  182130. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182131. * functions that are passed far data must be model independent.
  182132. */
  182133. #ifndef PNG_ABORT
  182134. # define PNG_ABORT() abort()
  182135. #endif
  182136. #ifdef PNG_SETJMP_SUPPORTED
  182137. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182138. #else
  182139. # define png_jmpbuf(png_ptr) \
  182140. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182141. #endif
  182142. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182143. /* use this to make far-to-near assignments */
  182144. # define CHECK 1
  182145. # define NOCHECK 0
  182146. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182147. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182148. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182149. # define png_strcpy _fstrcpy
  182150. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182151. # define png_strlen _fstrlen
  182152. # define png_memcmp _fmemcmp /* SJT: added */
  182153. # define png_memcpy _fmemcpy
  182154. # define png_memset _fmemset
  182155. #else /* use the usual functions */
  182156. # define CVT_PTR(ptr) (ptr)
  182157. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182158. # ifndef PNG_NO_SNPRINTF
  182159. # ifdef _MSC_VER
  182160. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182161. # define png_snprintf2 _snprintf
  182162. # define png_snprintf6 _snprintf
  182163. # else
  182164. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182165. # define png_snprintf2 snprintf
  182166. # define png_snprintf6 snprintf
  182167. # endif
  182168. # else
  182169. /* You don't have or don't want to use snprintf(). Caution: Using
  182170. * sprintf instead of snprintf exposes your application to accidental
  182171. * or malevolent buffer overflows. If you don't have snprintf()
  182172. * as a general rule you should provide one (you can get one from
  182173. * Portable OpenSSH). */
  182174. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182175. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182176. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182177. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182178. # endif
  182179. # define png_strcpy strcpy
  182180. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182181. # define png_strlen strlen
  182182. # define png_memcmp memcmp /* SJT: added */
  182183. # define png_memcpy memcpy
  182184. # define png_memset memset
  182185. #endif
  182186. /* End of memory model independent support */
  182187. /* Just a little check that someone hasn't tried to define something
  182188. * contradictory.
  182189. */
  182190. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182191. # undef PNG_ZBUF_SIZE
  182192. # define PNG_ZBUF_SIZE 65536L
  182193. #endif
  182194. /* Added at libpng-1.2.8 */
  182195. #endif /* PNG_VERSION_INFO_ONLY */
  182196. #endif /* PNGCONF_H */
  182197. /*** End of inlined file: pngconf.h ***/
  182198. #ifdef _MSC_VER
  182199. #pragma warning (disable: 4996 4100)
  182200. #endif
  182201. /*
  182202. * Added at libpng-1.2.8 */
  182203. /* Ref MSDN: Private as priority over Special
  182204. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182205. * procedures. If this value is given, the StringFileInfo block must
  182206. * contain a PrivateBuild string.
  182207. *
  182208. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182209. * standard release procedures but is a variation of the standard
  182210. * file of the same version number. If this value is given, the
  182211. * StringFileInfo block must contain a SpecialBuild string.
  182212. */
  182213. #if defined(PNG_USER_PRIVATEBUILD)
  182214. # define PNG_LIBPNG_BUILD_TYPE \
  182215. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182216. #else
  182217. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182218. # define PNG_LIBPNG_BUILD_TYPE \
  182219. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182220. # else
  182221. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182222. # endif
  182223. #endif
  182224. #ifndef PNG_VERSION_INFO_ONLY
  182225. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182226. #ifdef __cplusplus
  182227. //extern "C" {
  182228. #endif /* __cplusplus */
  182229. /* This file is arranged in several sections. The first section contains
  182230. * structure and type definitions. The second section contains the external
  182231. * library functions, while the third has the internal library functions,
  182232. * which applications aren't expected to use directly.
  182233. */
  182234. #ifndef PNG_NO_TYPECAST_NULL
  182235. #define int_p_NULL (int *)NULL
  182236. #define png_bytep_NULL (png_bytep)NULL
  182237. #define png_bytepp_NULL (png_bytepp)NULL
  182238. #define png_doublep_NULL (png_doublep)NULL
  182239. #define png_error_ptr_NULL (png_error_ptr)NULL
  182240. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182241. #define png_free_ptr_NULL (png_free_ptr)NULL
  182242. #define png_infopp_NULL (png_infopp)NULL
  182243. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182244. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182245. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182246. #define png_structp_NULL (png_structp)NULL
  182247. #define png_uint_16p_NULL (png_uint_16p)NULL
  182248. #define png_voidp_NULL (png_voidp)NULL
  182249. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182250. #else
  182251. #define int_p_NULL NULL
  182252. #define png_bytep_NULL NULL
  182253. #define png_bytepp_NULL NULL
  182254. #define png_doublep_NULL NULL
  182255. #define png_error_ptr_NULL NULL
  182256. #define png_flush_ptr_NULL NULL
  182257. #define png_free_ptr_NULL NULL
  182258. #define png_infopp_NULL NULL
  182259. #define png_malloc_ptr_NULL NULL
  182260. #define png_read_status_ptr_NULL NULL
  182261. #define png_rw_ptr_NULL NULL
  182262. #define png_structp_NULL NULL
  182263. #define png_uint_16p_NULL NULL
  182264. #define png_voidp_NULL NULL
  182265. #define png_write_status_ptr_NULL NULL
  182266. #endif
  182267. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182268. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182269. /* Version information for C files, stored in png.c. This had better match
  182270. * the version above.
  182271. */
  182272. #ifdef PNG_USE_GLOBAL_ARRAYS
  182273. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182274. /* need room for 99.99.99beta99z */
  182275. #else
  182276. #define png_libpng_ver png_get_header_ver(NULL)
  182277. #endif
  182278. #ifdef PNG_USE_GLOBAL_ARRAYS
  182279. /* This was removed in version 1.0.5c */
  182280. /* Structures to facilitate easy interlacing. See png.c for more details */
  182281. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182282. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  182283. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  182284. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  182285. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  182286. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  182287. /* This isn't currently used. If you need it, see png.c for more details.
  182288. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  182289. */
  182290. #endif
  182291. #endif /* PNG_NO_EXTERN */
  182292. /* Three color definitions. The order of the red, green, and blue, (and the
  182293. * exact size) is not important, although the size of the fields need to
  182294. * be png_byte or png_uint_16 (as defined below).
  182295. */
  182296. typedef struct png_color_struct
  182297. {
  182298. png_byte red;
  182299. png_byte green;
  182300. png_byte blue;
  182301. } png_color;
  182302. typedef png_color FAR * png_colorp;
  182303. typedef png_color FAR * FAR * png_colorpp;
  182304. typedef struct png_color_16_struct
  182305. {
  182306. png_byte index; /* used for palette files */
  182307. png_uint_16 red; /* for use in red green blue files */
  182308. png_uint_16 green;
  182309. png_uint_16 blue;
  182310. png_uint_16 gray; /* for use in grayscale files */
  182311. } png_color_16;
  182312. typedef png_color_16 FAR * png_color_16p;
  182313. typedef png_color_16 FAR * FAR * png_color_16pp;
  182314. typedef struct png_color_8_struct
  182315. {
  182316. png_byte red; /* for use in red green blue files */
  182317. png_byte green;
  182318. png_byte blue;
  182319. png_byte gray; /* for use in grayscale files */
  182320. png_byte alpha; /* for alpha channel files */
  182321. } png_color_8;
  182322. typedef png_color_8 FAR * png_color_8p;
  182323. typedef png_color_8 FAR * FAR * png_color_8pp;
  182324. /*
  182325. * The following two structures are used for the in-core representation
  182326. * of sPLT chunks.
  182327. */
  182328. typedef struct png_sPLT_entry_struct
  182329. {
  182330. png_uint_16 red;
  182331. png_uint_16 green;
  182332. png_uint_16 blue;
  182333. png_uint_16 alpha;
  182334. png_uint_16 frequency;
  182335. } png_sPLT_entry;
  182336. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  182337. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  182338. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  182339. * occupy the LSB of their respective members, and the MSB of each member
  182340. * is zero-filled. The frequency member always occupies the full 16 bits.
  182341. */
  182342. typedef struct png_sPLT_struct
  182343. {
  182344. png_charp name; /* palette name */
  182345. png_byte depth; /* depth of palette samples */
  182346. png_sPLT_entryp entries; /* palette entries */
  182347. png_int_32 nentries; /* number of palette entries */
  182348. } png_sPLT_t;
  182349. typedef png_sPLT_t FAR * png_sPLT_tp;
  182350. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  182351. #ifdef PNG_TEXT_SUPPORTED
  182352. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  182353. * and whether that contents is compressed or not. The "key" field
  182354. * points to a regular zero-terminated C string. The "text", "lang", and
  182355. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  182356. * However, the * structure returned by png_get_text() will always contain
  182357. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  182358. * so they can be safely used in printf() and other string-handling functions.
  182359. */
  182360. typedef struct png_text_struct
  182361. {
  182362. int compression; /* compression value:
  182363. -1: tEXt, none
  182364. 0: zTXt, deflate
  182365. 1: iTXt, none
  182366. 2: iTXt, deflate */
  182367. png_charp key; /* keyword, 1-79 character description of "text" */
  182368. png_charp text; /* comment, may be an empty string (ie "")
  182369. or a NULL pointer */
  182370. png_size_t text_length; /* length of the text string */
  182371. #ifdef PNG_iTXt_SUPPORTED
  182372. png_size_t itxt_length; /* length of the itxt string */
  182373. png_charp lang; /* language code, 0-79 characters
  182374. or a NULL pointer */
  182375. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  182376. chars or a NULL pointer */
  182377. #endif
  182378. } png_text;
  182379. typedef png_text FAR * png_textp;
  182380. typedef png_text FAR * FAR * png_textpp;
  182381. #endif
  182382. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  182383. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  182384. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  182385. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  182386. #define PNG_TEXT_COMPRESSION_NONE -1
  182387. #define PNG_TEXT_COMPRESSION_zTXt 0
  182388. #define PNG_ITXT_COMPRESSION_NONE 1
  182389. #define PNG_ITXT_COMPRESSION_zTXt 2
  182390. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  182391. /* png_time is a way to hold the time in an machine independent way.
  182392. * Two conversions are provided, both from time_t and struct tm. There
  182393. * is no portable way to convert to either of these structures, as far
  182394. * as I know. If you know of a portable way, send it to me. As a side
  182395. * note - PNG has always been Year 2000 compliant!
  182396. */
  182397. typedef struct png_time_struct
  182398. {
  182399. png_uint_16 year; /* full year, as in, 1995 */
  182400. png_byte month; /* month of year, 1 - 12 */
  182401. png_byte day; /* day of month, 1 - 31 */
  182402. png_byte hour; /* hour of day, 0 - 23 */
  182403. png_byte minute; /* minute of hour, 0 - 59 */
  182404. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  182405. } png_time;
  182406. typedef png_time FAR * png_timep;
  182407. typedef png_time FAR * FAR * png_timepp;
  182408. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182409. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  182410. * no specific support. The idea is that we can use this to queue
  182411. * up private chunks for output even though the library doesn't actually
  182412. * know about their semantics.
  182413. */
  182414. typedef struct png_unknown_chunk_t
  182415. {
  182416. png_byte name[5];
  182417. png_byte *data;
  182418. png_size_t size;
  182419. /* libpng-using applications should NOT directly modify this byte. */
  182420. png_byte location; /* mode of operation at read time */
  182421. }
  182422. png_unknown_chunk;
  182423. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  182424. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  182425. #endif
  182426. /* png_info is a structure that holds the information in a PNG file so
  182427. * that the application can find out the characteristics of the image.
  182428. * If you are reading the file, this structure will tell you what is
  182429. * in the PNG file. If you are writing the file, fill in the information
  182430. * you want to put into the PNG file, then call png_write_info().
  182431. * The names chosen should be very close to the PNG specification, so
  182432. * consult that document for information about the meaning of each field.
  182433. *
  182434. * With libpng < 0.95, it was only possible to directly set and read the
  182435. * the values in the png_info_struct, which meant that the contents and
  182436. * order of the values had to remain fixed. With libpng 0.95 and later,
  182437. * however, there are now functions that abstract the contents of
  182438. * png_info_struct from the application, so this makes it easier to use
  182439. * libpng with dynamic libraries, and even makes it possible to use
  182440. * libraries that don't have all of the libpng ancillary chunk-handing
  182441. * functionality.
  182442. *
  182443. * In any case, the order of the parameters in png_info_struct should NOT
  182444. * be changed for as long as possible to keep compatibility with applications
  182445. * that use the old direct-access method with png_info_struct.
  182446. *
  182447. * The following members may have allocated storage attached that should be
  182448. * cleaned up before the structure is discarded: palette, trans, text,
  182449. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  182450. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  182451. * are automatically freed when the info structure is deallocated, if they were
  182452. * allocated internally by libpng. This behavior can be changed by means
  182453. * of the png_data_freer() function.
  182454. *
  182455. * More allocation details: all the chunk-reading functions that
  182456. * change these members go through the corresponding png_set_*
  182457. * functions. A function to clear these members is available: see
  182458. * png_free_data(). The png_set_* functions do not depend on being
  182459. * able to point info structure members to any of the storage they are
  182460. * passed (they make their own copies), EXCEPT that the png_set_text
  182461. * functions use the same storage passed to them in the text_ptr or
  182462. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  182463. * functions do not make their own copies.
  182464. */
  182465. typedef struct png_info_struct
  182466. {
  182467. /* the following are necessary for every PNG file */
  182468. png_uint_32 width; /* width of image in pixels (from IHDR) */
  182469. png_uint_32 height; /* height of image in pixels (from IHDR) */
  182470. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  182471. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  182472. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  182473. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  182474. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  182475. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  182476. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  182477. /* The following three should have been named *_method not *_type */
  182478. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  182479. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  182480. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182481. /* The following is informational only on read, and not used on writes. */
  182482. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  182483. png_byte pixel_depth; /* number of bits per pixel */
  182484. png_byte spare_byte; /* to align the data, and for future use */
  182485. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  182486. /* The rest of the data is optional. If you are reading, check the
  182487. * valid field to see if the information in these are valid. If you
  182488. * are writing, set the valid field to those chunks you want written,
  182489. * and initialize the appropriate fields below.
  182490. */
  182491. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  182492. /* The gAMA chunk describes the gamma characteristics of the system
  182493. * on which the image was created, normally in the range [1.0, 2.5].
  182494. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  182495. */
  182496. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  182497. #endif
  182498. #if defined(PNG_sRGB_SUPPORTED)
  182499. /* GR-P, 0.96a */
  182500. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  182501. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  182502. #endif
  182503. #if defined(PNG_TEXT_SUPPORTED)
  182504. /* The tEXt, and zTXt chunks contain human-readable textual data in
  182505. * uncompressed, compressed, and optionally compressed forms, respectively.
  182506. * The data in "text" is an array of pointers to uncompressed,
  182507. * null-terminated C strings. Each chunk has a keyword that describes the
  182508. * textual data contained in that chunk. Keywords are not required to be
  182509. * unique, and the text string may be empty. Any number of text chunks may
  182510. * be in an image.
  182511. */
  182512. int num_text; /* number of comments read/to write */
  182513. int max_text; /* current size of text array */
  182514. png_textp text; /* array of comments read/to write */
  182515. #endif /* PNG_TEXT_SUPPORTED */
  182516. #if defined(PNG_tIME_SUPPORTED)
  182517. /* The tIME chunk holds the last time the displayed image data was
  182518. * modified. See the png_time struct for the contents of this struct.
  182519. */
  182520. png_time mod_time;
  182521. #endif
  182522. #if defined(PNG_sBIT_SUPPORTED)
  182523. /* The sBIT chunk specifies the number of significant high-order bits
  182524. * in the pixel data. Values are in the range [1, bit_depth], and are
  182525. * only specified for the channels in the pixel data. The contents of
  182526. * the low-order bits is not specified. Data is valid if
  182527. * (valid & PNG_INFO_sBIT) is non-zero.
  182528. */
  182529. png_color_8 sig_bit; /* significant bits in color channels */
  182530. #endif
  182531. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  182532. defined(PNG_READ_BACKGROUND_SUPPORTED)
  182533. /* The tRNS chunk supplies transparency data for paletted images and
  182534. * other image types that don't need a full alpha channel. There are
  182535. * "num_trans" transparency values for a paletted image, stored in the
  182536. * same order as the palette colors, starting from index 0. Values
  182537. * for the data are in the range [0, 255], ranging from fully transparent
  182538. * to fully opaque, respectively. For non-paletted images, there is a
  182539. * single color specified that should be treated as fully transparent.
  182540. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  182541. */
  182542. png_bytep trans; /* transparent values for paletted image */
  182543. png_color_16 trans_values; /* transparent color for non-palette image */
  182544. #endif
  182545. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182546. /* The bKGD chunk gives the suggested image background color if the
  182547. * display program does not have its own background color and the image
  182548. * is needs to composited onto a background before display. The colors
  182549. * in "background" are normally in the same color space/depth as the
  182550. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  182551. */
  182552. png_color_16 background;
  182553. #endif
  182554. #if defined(PNG_oFFs_SUPPORTED)
  182555. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  182556. * and downwards from the top-left corner of the display, page, or other
  182557. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  182558. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  182559. */
  182560. png_int_32 x_offset; /* x offset on page */
  182561. png_int_32 y_offset; /* y offset on page */
  182562. png_byte offset_unit_type; /* offset units type */
  182563. #endif
  182564. #if defined(PNG_pHYs_SUPPORTED)
  182565. /* The pHYs chunk gives the physical pixel density of the image for
  182566. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  182567. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  182568. */
  182569. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  182570. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  182571. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  182572. #endif
  182573. #if defined(PNG_hIST_SUPPORTED)
  182574. /* The hIST chunk contains the relative frequency or importance of the
  182575. * various palette entries, so that a viewer can intelligently select a
  182576. * reduced-color palette, if required. Data is an array of "num_palette"
  182577. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  182578. * is non-zero.
  182579. */
  182580. png_uint_16p hist;
  182581. #endif
  182582. #ifdef PNG_cHRM_SUPPORTED
  182583. /* The cHRM chunk describes the CIE color characteristics of the monitor
  182584. * on which the PNG was created. This data allows the viewer to do gamut
  182585. * mapping of the input image to ensure that the viewer sees the same
  182586. * colors in the image as the creator. Values are in the range
  182587. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  182588. */
  182589. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182590. float x_white;
  182591. float y_white;
  182592. float x_red;
  182593. float y_red;
  182594. float x_green;
  182595. float y_green;
  182596. float x_blue;
  182597. float y_blue;
  182598. #endif
  182599. #endif
  182600. #if defined(PNG_pCAL_SUPPORTED)
  182601. /* The pCAL chunk describes a transformation between the stored pixel
  182602. * values and original physical data values used to create the image.
  182603. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  182604. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  182605. * (possibly non-linear) transformation function given by "pcal_type"
  182606. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  182607. * defines below, and the PNG-Group's PNG extensions document for a
  182608. * complete description of the transformations and how they should be
  182609. * implemented, and for a description of the ASCII parameter strings.
  182610. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  182611. */
  182612. png_charp pcal_purpose; /* pCAL chunk description string */
  182613. png_int_32 pcal_X0; /* minimum value */
  182614. png_int_32 pcal_X1; /* maximum value */
  182615. png_charp pcal_units; /* Latin-1 string giving physical units */
  182616. png_charpp pcal_params; /* ASCII strings containing parameter values */
  182617. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  182618. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  182619. #endif
  182620. /* New members added in libpng-1.0.6 */
  182621. #ifdef PNG_FREE_ME_SUPPORTED
  182622. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  182623. #endif
  182624. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182625. /* storage for unknown chunks that the library doesn't recognize. */
  182626. png_unknown_chunkp unknown_chunks;
  182627. png_size_t unknown_chunks_num;
  182628. #endif
  182629. #if defined(PNG_iCCP_SUPPORTED)
  182630. /* iCCP chunk data. */
  182631. png_charp iccp_name; /* profile name */
  182632. png_charp iccp_profile; /* International Color Consortium profile data */
  182633. /* Note to maintainer: should be png_bytep */
  182634. png_uint_32 iccp_proflen; /* ICC profile data length */
  182635. png_byte iccp_compression; /* Always zero */
  182636. #endif
  182637. #if defined(PNG_sPLT_SUPPORTED)
  182638. /* data on sPLT chunks (there may be more than one). */
  182639. png_sPLT_tp splt_palettes;
  182640. png_uint_32 splt_palettes_num;
  182641. #endif
  182642. #if defined(PNG_sCAL_SUPPORTED)
  182643. /* The sCAL chunk describes the actual physical dimensions of the
  182644. * subject matter of the graphic. The chunk contains a unit specification
  182645. * a byte value, and two ASCII strings representing floating-point
  182646. * values. The values are width and height corresponsing to one pixel
  182647. * in the image. This external representation is converted to double
  182648. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  182649. */
  182650. png_byte scal_unit; /* unit of physical scale */
  182651. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182652. double scal_pixel_width; /* width of one pixel */
  182653. double scal_pixel_height; /* height of one pixel */
  182654. #endif
  182655. #ifdef PNG_FIXED_POINT_SUPPORTED
  182656. png_charp scal_s_width; /* string containing height */
  182657. png_charp scal_s_height; /* string containing width */
  182658. #endif
  182659. #endif
  182660. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  182661. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  182662. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  182663. png_bytepp row_pointers; /* the image bits */
  182664. #endif
  182665. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  182666. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  182667. #endif
  182668. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  182669. png_fixed_point int_x_white;
  182670. png_fixed_point int_y_white;
  182671. png_fixed_point int_x_red;
  182672. png_fixed_point int_y_red;
  182673. png_fixed_point int_x_green;
  182674. png_fixed_point int_y_green;
  182675. png_fixed_point int_x_blue;
  182676. png_fixed_point int_y_blue;
  182677. #endif
  182678. } png_info;
  182679. typedef png_info FAR * png_infop;
  182680. typedef png_info FAR * FAR * png_infopp;
  182681. /* Maximum positive integer used in PNG is (2^31)-1 */
  182682. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  182683. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  182684. #define PNG_SIZE_MAX ((png_size_t)(-1))
  182685. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182686. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  182687. #define PNG_MAX_UINT PNG_UINT_31_MAX
  182688. #endif
  182689. /* These describe the color_type field in png_info. */
  182690. /* color type masks */
  182691. #define PNG_COLOR_MASK_PALETTE 1
  182692. #define PNG_COLOR_MASK_COLOR 2
  182693. #define PNG_COLOR_MASK_ALPHA 4
  182694. /* color types. Note that not all combinations are legal */
  182695. #define PNG_COLOR_TYPE_GRAY 0
  182696. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  182697. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  182698. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  182699. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  182700. /* aliases */
  182701. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  182702. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  182703. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  182704. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  182705. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  182706. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  182707. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  182708. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  182709. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  182710. /* These are for the interlacing type. These values should NOT be changed. */
  182711. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  182712. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  182713. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  182714. /* These are for the oFFs chunk. These values should NOT be changed. */
  182715. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  182716. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  182717. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  182718. /* These are for the pCAL chunk. These values should NOT be changed. */
  182719. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  182720. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  182721. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  182722. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  182723. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  182724. /* These are for the sCAL chunk. These values should NOT be changed. */
  182725. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  182726. #define PNG_SCALE_METER 1 /* meters per pixel */
  182727. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  182728. #define PNG_SCALE_LAST 3 /* Not a valid value */
  182729. /* These are for the pHYs chunk. These values should NOT be changed. */
  182730. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  182731. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  182732. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  182733. /* These are for the sRGB chunk. These values should NOT be changed. */
  182734. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  182735. #define PNG_sRGB_INTENT_RELATIVE 1
  182736. #define PNG_sRGB_INTENT_SATURATION 2
  182737. #define PNG_sRGB_INTENT_ABSOLUTE 3
  182738. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  182739. /* This is for text chunks */
  182740. #define PNG_KEYWORD_MAX_LENGTH 79
  182741. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  182742. #define PNG_MAX_PALETTE_LENGTH 256
  182743. /* These determine if an ancillary chunk's data has been successfully read
  182744. * from the PNG header, or if the application has filled in the corresponding
  182745. * data in the info_struct to be written into the output file. The values
  182746. * of the PNG_INFO_<chunk> defines should NOT be changed.
  182747. */
  182748. #define PNG_INFO_gAMA 0x0001
  182749. #define PNG_INFO_sBIT 0x0002
  182750. #define PNG_INFO_cHRM 0x0004
  182751. #define PNG_INFO_PLTE 0x0008
  182752. #define PNG_INFO_tRNS 0x0010
  182753. #define PNG_INFO_bKGD 0x0020
  182754. #define PNG_INFO_hIST 0x0040
  182755. #define PNG_INFO_pHYs 0x0080
  182756. #define PNG_INFO_oFFs 0x0100
  182757. #define PNG_INFO_tIME 0x0200
  182758. #define PNG_INFO_pCAL 0x0400
  182759. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  182760. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  182761. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  182762. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  182763. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  182764. /* This is used for the transformation routines, as some of them
  182765. * change these values for the row. It also should enable using
  182766. * the routines for other purposes.
  182767. */
  182768. typedef struct png_row_info_struct
  182769. {
  182770. png_uint_32 width; /* width of row */
  182771. png_uint_32 rowbytes; /* number of bytes in row */
  182772. png_byte color_type; /* color type of row */
  182773. png_byte bit_depth; /* bit depth of row */
  182774. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  182775. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  182776. } png_row_info;
  182777. typedef png_row_info FAR * png_row_infop;
  182778. typedef png_row_info FAR * FAR * png_row_infopp;
  182779. /* These are the function types for the I/O functions and for the functions
  182780. * that allow the user to override the default I/O functions with his or her
  182781. * own. The png_error_ptr type should match that of user-supplied warning
  182782. * and error functions, while the png_rw_ptr type should match that of the
  182783. * user read/write data functions.
  182784. */
  182785. typedef struct png_struct_def png_struct;
  182786. typedef png_struct FAR * png_structp;
  182787. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  182788. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  182789. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  182790. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  182791. int));
  182792. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  182793. int));
  182794. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182795. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  182796. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  182797. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  182798. png_uint_32, int));
  182799. #endif
  182800. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182801. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  182802. defined(PNG_LEGACY_SUPPORTED)
  182803. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  182804. png_row_infop, png_bytep));
  182805. #endif
  182806. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  182807. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  182808. #endif
  182809. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  182810. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  182811. #endif
  182812. /* Transform masks for the high-level interface */
  182813. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  182814. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  182815. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  182816. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  182817. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  182818. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  182819. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  182820. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  182821. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  182822. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  182823. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  182824. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  182825. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  182826. /* Flags for MNG supported features */
  182827. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  182828. #define PNG_FLAG_MNG_FILTER_64 0x04
  182829. #define PNG_ALL_MNG_FEATURES 0x05
  182830. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  182831. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  182832. /* The structure that holds the information to read and write PNG files.
  182833. * The only people who need to care about what is inside of this are the
  182834. * people who will be modifying the library for their own special needs.
  182835. * It should NOT be accessed directly by an application, except to store
  182836. * the jmp_buf.
  182837. */
  182838. struct png_struct_def
  182839. {
  182840. #ifdef PNG_SETJMP_SUPPORTED
  182841. jmp_buf jmpbuf; /* used in png_error */
  182842. #endif
  182843. png_error_ptr error_fn; /* function for printing errors and aborting */
  182844. png_error_ptr warning_fn; /* function for printing warnings */
  182845. png_voidp error_ptr; /* user supplied struct for error functions */
  182846. png_rw_ptr write_data_fn; /* function for writing output data */
  182847. png_rw_ptr read_data_fn; /* function for reading input data */
  182848. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  182849. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  182850. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  182851. #endif
  182852. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182853. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  182854. #endif
  182855. /* These were added in libpng-1.0.2 */
  182856. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  182857. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182858. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182859. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  182860. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  182861. png_byte user_transform_channels; /* channels in user transformed pixels */
  182862. #endif
  182863. #endif
  182864. png_uint_32 mode; /* tells us where we are in the PNG file */
  182865. png_uint_32 flags; /* flags indicating various things to libpng */
  182866. png_uint_32 transformations; /* which transformations to perform */
  182867. z_stream zstream; /* pointer to decompression structure (below) */
  182868. png_bytep zbuf; /* buffer for zlib */
  182869. png_size_t zbuf_size; /* size of zbuf */
  182870. int zlib_level; /* holds zlib compression level */
  182871. int zlib_method; /* holds zlib compression method */
  182872. int zlib_window_bits; /* holds zlib compression window bits */
  182873. int zlib_mem_level; /* holds zlib compression memory level */
  182874. int zlib_strategy; /* holds zlib compression strategy */
  182875. png_uint_32 width; /* width of image in pixels */
  182876. png_uint_32 height; /* height of image in pixels */
  182877. png_uint_32 num_rows; /* number of rows in current pass */
  182878. png_uint_32 usr_width; /* width of row at start of write */
  182879. png_uint_32 rowbytes; /* size of row in bytes */
  182880. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  182881. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  182882. png_uint_32 row_number; /* current row in interlace pass */
  182883. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  182884. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  182885. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  182886. png_bytep up_row; /* buffer to save "up" row when filtering */
  182887. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  182888. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  182889. png_row_info row_info; /* used for transformation routines */
  182890. png_uint_32 idat_size; /* current IDAT size for read */
  182891. png_uint_32 crc; /* current chunk CRC value */
  182892. png_colorp palette; /* palette from the input file */
  182893. png_uint_16 num_palette; /* number of color entries in palette */
  182894. png_uint_16 num_trans; /* number of transparency values */
  182895. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  182896. png_byte compression; /* file compression type (always 0) */
  182897. png_byte filter; /* file filter type (always 0) */
  182898. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  182899. png_byte pass; /* current interlace pass (0 - 6) */
  182900. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  182901. png_byte color_type; /* color type of file */
  182902. png_byte bit_depth; /* bit depth of file */
  182903. png_byte usr_bit_depth; /* bit depth of users row */
  182904. png_byte pixel_depth; /* number of bits per pixel */
  182905. png_byte channels; /* number of channels in file */
  182906. png_byte usr_channels; /* channels at start of write */
  182907. png_byte sig_bytes; /* magic bytes read/written from start of file */
  182908. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  182909. #ifdef PNG_LEGACY_SUPPORTED
  182910. png_byte filler; /* filler byte for pixel expansion */
  182911. #else
  182912. png_uint_16 filler; /* filler bytes for pixel expansion */
  182913. #endif
  182914. #endif
  182915. #if defined(PNG_bKGD_SUPPORTED)
  182916. png_byte background_gamma_type;
  182917. # ifdef PNG_FLOATING_POINT_SUPPORTED
  182918. float background_gamma;
  182919. # endif
  182920. png_color_16 background; /* background color in screen gamma space */
  182921. #if defined(PNG_READ_GAMMA_SUPPORTED)
  182922. png_color_16 background_1; /* background normalized to gamma 1.0 */
  182923. #endif
  182924. #endif /* PNG_bKGD_SUPPORTED */
  182925. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  182926. png_flush_ptr output_flush_fn;/* Function for flushing output */
  182927. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  182928. png_uint_32 flush_rows; /* number of rows written since last flush */
  182929. #endif
  182930. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182931. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  182932. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182933. float gamma; /* file gamma value */
  182934. float screen_gamma; /* screen gamma value (display_exponent) */
  182935. #endif
  182936. #endif
  182937. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182938. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  182939. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  182940. png_bytep gamma_to_1; /* converts from file to 1.0 */
  182941. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  182942. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  182943. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  182944. #endif
  182945. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  182946. png_color_8 sig_bit; /* significant bits in each available channel */
  182947. #endif
  182948. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  182949. png_color_8 shift; /* shift for significant bit tranformation */
  182950. #endif
  182951. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  182952. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  182953. png_bytep trans; /* transparency values for paletted files */
  182954. png_color_16 trans_values; /* transparency values for non-paletted files */
  182955. #endif
  182956. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  182957. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  182958. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  182959. png_progressive_info_ptr info_fn; /* called after header data fully read */
  182960. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  182961. png_progressive_end_ptr end_fn; /* called after image is complete */
  182962. png_bytep save_buffer_ptr; /* current location in save_buffer */
  182963. png_bytep save_buffer; /* buffer for previously read data */
  182964. png_bytep current_buffer_ptr; /* current location in current_buffer */
  182965. png_bytep current_buffer; /* buffer for recently used data */
  182966. png_uint_32 push_length; /* size of current input chunk */
  182967. png_uint_32 skip_length; /* bytes to skip in input data */
  182968. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  182969. png_size_t save_buffer_max; /* total size of save_buffer */
  182970. png_size_t buffer_size; /* total amount of available input data */
  182971. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  182972. int process_mode; /* what push library is currently doing */
  182973. int cur_palette; /* current push library palette index */
  182974. # if defined(PNG_TEXT_SUPPORTED)
  182975. png_size_t current_text_size; /* current size of text input data */
  182976. png_size_t current_text_left; /* how much text left to read in input */
  182977. png_charp current_text; /* current text chunk buffer */
  182978. png_charp current_text_ptr; /* current location in current_text */
  182979. # endif /* PNG_TEXT_SUPPORTED */
  182980. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  182981. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  182982. /* for the Borland special 64K segment handler */
  182983. png_bytepp offset_table_ptr;
  182984. png_bytep offset_table;
  182985. png_uint_16 offset_table_number;
  182986. png_uint_16 offset_table_count;
  182987. png_uint_16 offset_table_count_free;
  182988. #endif
  182989. #if defined(PNG_READ_DITHER_SUPPORTED)
  182990. png_bytep palette_lookup; /* lookup table for dithering */
  182991. png_bytep dither_index; /* index translation for palette files */
  182992. #endif
  182993. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  182994. png_uint_16p hist; /* histogram */
  182995. #endif
  182996. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  182997. png_byte heuristic_method; /* heuristic for row filter selection */
  182998. png_byte num_prev_filters; /* number of weights for previous rows */
  182999. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  183000. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  183001. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  183002. png_uint_16p filter_costs; /* relative filter calculation cost */
  183003. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  183004. #endif
  183005. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183006. png_charp time_buffer; /* String to hold RFC 1123 time text */
  183007. #endif
  183008. /* New members added in libpng-1.0.6 */
  183009. #ifdef PNG_FREE_ME_SUPPORTED
  183010. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  183011. #endif
  183012. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  183013. png_voidp user_chunk_ptr;
  183014. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  183015. #endif
  183016. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183017. int num_chunk_list;
  183018. png_bytep chunk_list;
  183019. #endif
  183020. /* New members added in libpng-1.0.3 */
  183021. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183022. png_byte rgb_to_gray_status;
  183023. /* These were changed from png_byte in libpng-1.0.6 */
  183024. png_uint_16 rgb_to_gray_red_coeff;
  183025. png_uint_16 rgb_to_gray_green_coeff;
  183026. png_uint_16 rgb_to_gray_blue_coeff;
  183027. #endif
  183028. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  183029. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  183030. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183031. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183032. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  183033. #ifdef PNG_1_0_X
  183034. png_byte mng_features_permitted;
  183035. #else
  183036. png_uint_32 mng_features_permitted;
  183037. #endif /* PNG_1_0_X */
  183038. #endif
  183039. /* New member added in libpng-1.0.7 */
  183040. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183041. png_fixed_point int_gamma;
  183042. #endif
  183043. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183044. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183045. png_byte filter_type;
  183046. #endif
  183047. #if defined(PNG_1_0_X)
  183048. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183049. png_uint_32 row_buf_size;
  183050. #endif
  183051. /* New members added in libpng-1.2.0 */
  183052. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183053. # if !defined(PNG_1_0_X)
  183054. # if defined(PNG_MMX_CODE_SUPPORTED)
  183055. png_byte mmx_bitdepth_threshold;
  183056. png_uint_32 mmx_rowbytes_threshold;
  183057. # endif
  183058. png_uint_32 asm_flags;
  183059. # endif
  183060. #endif
  183061. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183062. #ifdef PNG_USER_MEM_SUPPORTED
  183063. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183064. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183065. png_free_ptr free_fn; /* function for freeing memory */
  183066. #endif
  183067. /* New member added in libpng-1.0.13 and 1.2.0 */
  183068. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183069. #if defined(PNG_READ_DITHER_SUPPORTED)
  183070. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183071. png_bytep dither_sort; /* working sort array */
  183072. png_bytep index_to_palette; /* where the original index currently is */
  183073. /* in the palette */
  183074. png_bytep palette_to_index; /* which original index points to this */
  183075. /* palette color */
  183076. #endif
  183077. /* New members added in libpng-1.0.16 and 1.2.6 */
  183078. png_byte compression_type;
  183079. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183080. png_uint_32 user_width_max;
  183081. png_uint_32 user_height_max;
  183082. #endif
  183083. /* New member added in libpng-1.0.25 and 1.2.17 */
  183084. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183085. /* storage for unknown chunk that the library doesn't recognize. */
  183086. png_unknown_chunk unknown_chunk;
  183087. #endif
  183088. };
  183089. /* This triggers a compiler error in png.c, if png.c and png.h
  183090. * do not agree upon the version number.
  183091. */
  183092. typedef png_structp version_1_2_21;
  183093. typedef png_struct FAR * FAR * png_structpp;
  183094. /* Here are the function definitions most commonly used. This is not
  183095. * the place to find out how to use libpng. See libpng.txt for the
  183096. * full explanation, see example.c for the summary. This just provides
  183097. * a simple one line description of the use of each function.
  183098. */
  183099. /* Returns the version number of the library */
  183100. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183101. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183102. * Handling more than 8 bytes from the beginning of the file is an error.
  183103. */
  183104. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183105. int num_bytes));
  183106. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183107. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183108. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183109. * start > 7 will always fail (ie return non-zero).
  183110. */
  183111. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183112. png_size_t num_to_check));
  183113. /* Simple signature checking function. This is the same as calling
  183114. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183115. */
  183116. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183117. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183118. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183119. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183120. png_error_ptr error_fn, png_error_ptr warn_fn));
  183121. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183122. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183123. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183124. png_error_ptr error_fn, png_error_ptr warn_fn));
  183125. #ifdef PNG_WRITE_SUPPORTED
  183126. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183127. PNGARG((png_structp png_ptr));
  183128. #endif
  183129. #ifdef PNG_WRITE_SUPPORTED
  183130. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183131. PNGARG((png_structp png_ptr, png_uint_32 size));
  183132. #endif
  183133. /* Reset the compression stream */
  183134. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183135. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183136. #ifdef PNG_USER_MEM_SUPPORTED
  183137. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183138. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183139. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183140. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183141. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183142. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183143. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183144. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183145. #endif
  183146. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183147. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183148. png_bytep chunk_name, png_bytep data, png_size_t length));
  183149. /* Write the start of a PNG chunk - length and chunk name. */
  183150. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183151. png_bytep chunk_name, png_uint_32 length));
  183152. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183153. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183154. png_bytep data, png_size_t length));
  183155. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183156. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183157. /* Allocate and initialize the info structure */
  183158. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183159. PNGARG((png_structp png_ptr));
  183160. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183161. /* Initialize the info structure (old interface - DEPRECATED) */
  183162. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183163. #undef png_info_init
  183164. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183165. png_sizeof(png_info));
  183166. #endif
  183167. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183168. png_size_t png_info_struct_size));
  183169. /* Writes all the PNG information before the image. */
  183170. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183171. png_infop info_ptr));
  183172. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183173. png_infop info_ptr));
  183174. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183175. /* read the information before the actual image data. */
  183176. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183177. png_infop info_ptr));
  183178. #endif
  183179. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183180. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183181. PNGARG((png_structp png_ptr, png_timep ptime));
  183182. #endif
  183183. #if !defined(_WIN32_WCE)
  183184. /* "time.h" functions are not supported on WindowsCE */
  183185. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183186. /* convert from a struct tm to png_time */
  183187. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183188. struct tm FAR * ttime));
  183189. /* convert from time_t to png_time. Uses gmtime() */
  183190. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183191. time_t ttime));
  183192. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183193. #endif /* _WIN32_WCE */
  183194. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183195. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183196. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183197. #if !defined(PNG_1_0_X)
  183198. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183199. png_ptr));
  183200. #endif
  183201. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183202. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183203. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183204. /* Deprecated */
  183205. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183206. #endif
  183207. #endif
  183208. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183209. /* Use blue, green, red order for pixels. */
  183210. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183211. #endif
  183212. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183213. /* Expand the grayscale to 24-bit RGB if necessary. */
  183214. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183215. #endif
  183216. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183217. /* Reduce RGB to grayscale. */
  183218. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183219. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183220. int error_action, double red, double green ));
  183221. #endif
  183222. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183223. int error_action, png_fixed_point red, png_fixed_point green ));
  183224. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183225. png_ptr));
  183226. #endif
  183227. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183228. png_colorp palette));
  183229. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183230. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183231. #endif
  183232. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183233. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183234. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183235. #endif
  183236. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183237. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183238. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183239. #endif
  183240. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183241. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183242. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183243. png_uint_32 filler, int flags));
  183244. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183245. #define PNG_FILLER_BEFORE 0
  183246. #define PNG_FILLER_AFTER 1
  183247. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183248. #if !defined(PNG_1_0_X)
  183249. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183250. png_uint_32 filler, int flags));
  183251. #endif
  183252. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183253. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183254. /* Swap bytes in 16-bit depth files. */
  183255. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183256. #endif
  183257. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183258. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183259. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183260. #endif
  183261. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183262. /* Swap packing order of pixels in bytes. */
  183263. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183264. #endif
  183265. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183266. /* Converts files to legal bit depths. */
  183267. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183268. png_color_8p true_bits));
  183269. #endif
  183270. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183271. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183272. /* Have the code handle the interlacing. Returns the number of passes. */
  183273. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183274. #endif
  183275. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183276. /* Invert monochrome files */
  183277. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183278. #endif
  183279. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183280. /* Handle alpha and tRNS by replacing with a background color. */
  183281. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183282. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  183283. png_color_16p background_color, int background_gamma_code,
  183284. int need_expand, double background_gamma));
  183285. #endif
  183286. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  183287. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  183288. #define PNG_BACKGROUND_GAMMA_FILE 2
  183289. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  183290. #endif
  183291. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  183292. /* strip the second byte of information from a 16-bit depth file. */
  183293. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  183294. #endif
  183295. #if defined(PNG_READ_DITHER_SUPPORTED)
  183296. /* Turn on dithering, and reduce the palette to the number of colors available. */
  183297. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  183298. png_colorp palette, int num_palette, int maximum_colors,
  183299. png_uint_16p histogram, int full_dither));
  183300. #endif
  183301. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183302. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  183303. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183304. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  183305. double screen_gamma, double default_file_gamma));
  183306. #endif
  183307. #endif
  183308. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183309. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183310. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183311. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  183312. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  183313. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  183314. int empty_plte_permitted));
  183315. #endif
  183316. #endif
  183317. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183318. /* Set how many lines between output flushes - 0 for no flushing */
  183319. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  183320. /* Flush the current PNG output buffer */
  183321. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  183322. #endif
  183323. /* optional update palette with requested transformations */
  183324. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  183325. /* optional call to update the users info structure */
  183326. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  183327. png_infop info_ptr));
  183328. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183329. /* read one or more rows of image data. */
  183330. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  183331. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  183332. #endif
  183333. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183334. /* read a row of data. */
  183335. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  183336. png_bytep row,
  183337. png_bytep display_row));
  183338. #endif
  183339. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183340. /* read the whole image into memory at once. */
  183341. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  183342. png_bytepp image));
  183343. #endif
  183344. /* write a row of image data */
  183345. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  183346. png_bytep row));
  183347. /* write a few rows of image data */
  183348. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  183349. png_bytepp row, png_uint_32 num_rows));
  183350. /* write the image data */
  183351. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  183352. png_bytepp image));
  183353. /* writes the end of the PNG file. */
  183354. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  183355. png_infop info_ptr));
  183356. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183357. /* read the end of the PNG file. */
  183358. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  183359. png_infop info_ptr));
  183360. #endif
  183361. /* free any memory associated with the png_info_struct */
  183362. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  183363. png_infopp info_ptr_ptr));
  183364. /* free any memory associated with the png_struct and the png_info_structs */
  183365. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  183366. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  183367. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  183368. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  183369. png_infop end_info_ptr));
  183370. /* free any memory associated with the png_struct and the png_info_structs */
  183371. extern PNG_EXPORT(void,png_destroy_write_struct)
  183372. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  183373. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  183374. extern void png_write_destroy PNGARG((png_structp png_ptr));
  183375. /* set the libpng method of handling chunk CRC errors */
  183376. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  183377. int crit_action, int ancil_action));
  183378. /* Values for png_set_crc_action() to say how to handle CRC errors in
  183379. * ancillary and critical chunks, and whether to use the data contained
  183380. * therein. Note that it is impossible to "discard" data in a critical
  183381. * chunk. For versions prior to 0.90, the action was always error/quit,
  183382. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  183383. * chunks is warn/discard. These values should NOT be changed.
  183384. *
  183385. * value action:critical action:ancillary
  183386. */
  183387. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  183388. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  183389. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  183390. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  183391. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  183392. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  183393. /* These functions give the user control over the scan-line filtering in
  183394. * libpng and the compression methods used by zlib. These functions are
  183395. * mainly useful for testing, as the defaults should work with most users.
  183396. * Those users who are tight on memory or want faster performance at the
  183397. * expense of compression can modify them. See the compression library
  183398. * header file (zlib.h) for an explination of the compression functions.
  183399. */
  183400. /* set the filtering method(s) used by libpng. Currently, the only valid
  183401. * value for "method" is 0.
  183402. */
  183403. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  183404. int filters));
  183405. /* Flags for png_set_filter() to say which filters to use. The flags
  183406. * are chosen so that they don't conflict with real filter types
  183407. * below, in case they are supplied instead of the #defined constants.
  183408. * These values should NOT be changed.
  183409. */
  183410. #define PNG_NO_FILTERS 0x00
  183411. #define PNG_FILTER_NONE 0x08
  183412. #define PNG_FILTER_SUB 0x10
  183413. #define PNG_FILTER_UP 0x20
  183414. #define PNG_FILTER_AVG 0x40
  183415. #define PNG_FILTER_PAETH 0x80
  183416. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  183417. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  183418. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  183419. * These defines should NOT be changed.
  183420. */
  183421. #define PNG_FILTER_VALUE_NONE 0
  183422. #define PNG_FILTER_VALUE_SUB 1
  183423. #define PNG_FILTER_VALUE_UP 2
  183424. #define PNG_FILTER_VALUE_AVG 3
  183425. #define PNG_FILTER_VALUE_PAETH 4
  183426. #define PNG_FILTER_VALUE_LAST 5
  183427. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  183428. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  183429. * defines, either the default (minimum-sum-of-absolute-differences), or
  183430. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  183431. *
  183432. * Weights are factors >= 1.0, indicating how important it is to keep the
  183433. * filter type consistent between rows. Larger numbers mean the current
  183434. * filter is that many times as likely to be the same as the "num_weights"
  183435. * previous filters. This is cumulative for each previous row with a weight.
  183436. * There needs to be "num_weights" values in "filter_weights", or it can be
  183437. * NULL if the weights aren't being specified. Weights have no influence on
  183438. * the selection of the first row filter. Well chosen weights can (in theory)
  183439. * improve the compression for a given image.
  183440. *
  183441. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  183442. * filter type. Higher costs indicate more decoding expense, and are
  183443. * therefore less likely to be selected over a filter with lower computational
  183444. * costs. There needs to be a value in "filter_costs" for each valid filter
  183445. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  183446. * setting the costs. Costs try to improve the speed of decompression without
  183447. * unduly increasing the compressed image size.
  183448. *
  183449. * A negative weight or cost indicates the default value is to be used, and
  183450. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  183451. * The default values for both weights and costs are currently 1.0, but may
  183452. * change if good general weighting/cost heuristics can be found. If both
  183453. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  183454. * to the UNWEIGHTED method, but with added encoding time/computation.
  183455. */
  183456. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183457. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  183458. int heuristic_method, int num_weights, png_doublep filter_weights,
  183459. png_doublep filter_costs));
  183460. #endif
  183461. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  183462. /* Heuristic used for row filter selection. These defines should NOT be
  183463. * changed.
  183464. */
  183465. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  183466. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  183467. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  183468. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  183469. /* Set the library compression level. Currently, valid values range from
  183470. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  183471. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  183472. * shown that zlib compression levels 3-6 usually perform as well as level 9
  183473. * for PNG images, and do considerably fewer caclulations. In the future,
  183474. * these values may not correspond directly to the zlib compression levels.
  183475. */
  183476. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  183477. int level));
  183478. extern PNG_EXPORT(void,png_set_compression_mem_level)
  183479. PNGARG((png_structp png_ptr, int mem_level));
  183480. extern PNG_EXPORT(void,png_set_compression_strategy)
  183481. PNGARG((png_structp png_ptr, int strategy));
  183482. extern PNG_EXPORT(void,png_set_compression_window_bits)
  183483. PNGARG((png_structp png_ptr, int window_bits));
  183484. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  183485. int method));
  183486. /* These next functions are called for input/output, memory, and error
  183487. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  183488. * and call standard C I/O routines such as fread(), fwrite(), and
  183489. * fprintf(). These functions can be made to use other I/O routines
  183490. * at run time for those applications that need to handle I/O in a
  183491. * different manner by calling png_set_???_fn(). See libpng.txt for
  183492. * more information.
  183493. */
  183494. #if !defined(PNG_NO_STDIO)
  183495. /* Initialize the input/output for the PNG file to the default functions. */
  183496. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  183497. #endif
  183498. /* Replace the (error and abort), and warning functions with user
  183499. * supplied functions. If no messages are to be printed you must still
  183500. * write and use replacement functions. The replacement error_fn should
  183501. * still do a longjmp to the last setjmp location if you are using this
  183502. * method of error handling. If error_fn or warning_fn is NULL, the
  183503. * default function will be used.
  183504. */
  183505. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  183506. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  183507. /* Return the user pointer associated with the error functions */
  183508. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  183509. /* Replace the default data output functions with a user supplied one(s).
  183510. * If buffered output is not used, then output_flush_fn can be set to NULL.
  183511. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  183512. * output_flush_fn will be ignored (and thus can be NULL).
  183513. */
  183514. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  183515. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  183516. /* Replace the default data input function with a user supplied one. */
  183517. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  183518. png_voidp io_ptr, png_rw_ptr read_data_fn));
  183519. /* Return the user pointer associated with the I/O functions */
  183520. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  183521. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  183522. png_read_status_ptr read_row_fn));
  183523. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  183524. png_write_status_ptr write_row_fn));
  183525. #ifdef PNG_USER_MEM_SUPPORTED
  183526. /* Replace the default memory allocation functions with user supplied one(s). */
  183527. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  183528. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183529. /* Return the user pointer associated with the memory functions */
  183530. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  183531. #endif
  183532. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183533. defined(PNG_LEGACY_SUPPORTED)
  183534. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  183535. png_ptr, png_user_transform_ptr read_user_transform_fn));
  183536. #endif
  183537. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183538. defined(PNG_LEGACY_SUPPORTED)
  183539. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  183540. png_ptr, png_user_transform_ptr write_user_transform_fn));
  183541. #endif
  183542. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183543. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183544. defined(PNG_LEGACY_SUPPORTED)
  183545. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  183546. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  183547. int user_transform_channels));
  183548. /* Return the user pointer associated with the user transform functions */
  183549. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  183550. PNGARG((png_structp png_ptr));
  183551. #endif
  183552. #ifdef PNG_USER_CHUNKS_SUPPORTED
  183553. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  183554. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  183555. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  183556. png_ptr));
  183557. #endif
  183558. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183559. /* Sets the function callbacks for the push reader, and a pointer to a
  183560. * user-defined structure available to the callback functions.
  183561. */
  183562. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  183563. png_voidp progressive_ptr,
  183564. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  183565. png_progressive_end_ptr end_fn));
  183566. /* returns the user pointer associated with the push read functions */
  183567. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  183568. PNGARG((png_structp png_ptr));
  183569. /* function to be called when data becomes available */
  183570. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  183571. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  183572. /* function that combines rows. Not very much different than the
  183573. * png_combine_row() call. Is this even used?????
  183574. */
  183575. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  183576. png_bytep old_row, png_bytep new_row));
  183577. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183578. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  183579. png_uint_32 size));
  183580. #if defined(PNG_1_0_X)
  183581. # define png_malloc_warn png_malloc
  183582. #else
  183583. /* Added at libpng version 1.2.4 */
  183584. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  183585. png_uint_32 size));
  183586. #endif
  183587. /* frees a pointer allocated by png_malloc() */
  183588. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  183589. #if defined(PNG_1_0_X)
  183590. /* Function to allocate memory for zlib. */
  183591. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  183592. uInt size));
  183593. /* Function to free memory for zlib */
  183594. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  183595. #endif
  183596. /* Free data that was allocated internally */
  183597. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  183598. png_infop info_ptr, png_uint_32 free_me, int num));
  183599. #ifdef PNG_FREE_ME_SUPPORTED
  183600. /* Reassign responsibility for freeing existing data, whether allocated
  183601. * by libpng or by the application */
  183602. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  183603. png_infop info_ptr, int freer, png_uint_32 mask));
  183604. #endif
  183605. /* assignments for png_data_freer */
  183606. #define PNG_DESTROY_WILL_FREE_DATA 1
  183607. #define PNG_SET_WILL_FREE_DATA 1
  183608. #define PNG_USER_WILL_FREE_DATA 2
  183609. /* Flags for png_ptr->free_me and info_ptr->free_me */
  183610. #define PNG_FREE_HIST 0x0008
  183611. #define PNG_FREE_ICCP 0x0010
  183612. #define PNG_FREE_SPLT 0x0020
  183613. #define PNG_FREE_ROWS 0x0040
  183614. #define PNG_FREE_PCAL 0x0080
  183615. #define PNG_FREE_SCAL 0x0100
  183616. #define PNG_FREE_UNKN 0x0200
  183617. #define PNG_FREE_LIST 0x0400
  183618. #define PNG_FREE_PLTE 0x1000
  183619. #define PNG_FREE_TRNS 0x2000
  183620. #define PNG_FREE_TEXT 0x4000
  183621. #define PNG_FREE_ALL 0x7fff
  183622. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  183623. #ifdef PNG_USER_MEM_SUPPORTED
  183624. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  183625. png_uint_32 size));
  183626. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  183627. png_voidp ptr));
  183628. #endif
  183629. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  183630. png_voidp s1, png_voidp s2, png_uint_32 size));
  183631. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  183632. png_voidp s1, int value, png_uint_32 size));
  183633. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  183634. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  183635. int check));
  183636. #endif /* USE_FAR_KEYWORD */
  183637. #ifndef PNG_NO_ERROR_TEXT
  183638. /* Fatal error in PNG image of libpng - can't continue */
  183639. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  183640. png_const_charp error_message));
  183641. /* The same, but the chunk name is prepended to the error string. */
  183642. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  183643. png_const_charp error_message));
  183644. #else
  183645. /* Fatal error in PNG image of libpng - can't continue */
  183646. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  183647. #endif
  183648. #ifndef PNG_NO_WARNINGS
  183649. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  183650. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  183651. png_const_charp warning_message));
  183652. #ifdef PNG_READ_SUPPORTED
  183653. /* Non-fatal error in libpng, chunk name is prepended to message. */
  183654. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  183655. png_const_charp warning_message));
  183656. #endif /* PNG_READ_SUPPORTED */
  183657. #endif /* PNG_NO_WARNINGS */
  183658. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  183659. * Similarly, the png_get_<chunk> calls are used to read values from the
  183660. * png_info_struct, either storing the parameters in the passed variables, or
  183661. * setting pointers into the png_info_struct where the data is stored. The
  183662. * png_get_<chunk> functions return a non-zero value if the data was available
  183663. * in info_ptr, or return zero and do not change any of the parameters if the
  183664. * data was not available.
  183665. *
  183666. * These functions should be used instead of directly accessing png_info
  183667. * to avoid problems with future changes in the size and internal layout of
  183668. * png_info_struct.
  183669. */
  183670. /* Returns "flag" if chunk data is valid in info_ptr. */
  183671. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  183672. png_infop info_ptr, png_uint_32 flag));
  183673. /* Returns number of bytes needed to hold a transformed row. */
  183674. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  183675. png_infop info_ptr));
  183676. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183677. /* Returns row_pointers, which is an array of pointers to scanlines that was
  183678. returned from png_read_png(). */
  183679. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  183680. png_infop info_ptr));
  183681. /* Set row_pointers, which is an array of pointers to scanlines for use
  183682. by png_write_png(). */
  183683. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  183684. png_infop info_ptr, png_bytepp row_pointers));
  183685. #endif
  183686. /* Returns number of color channels in image. */
  183687. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  183688. png_infop info_ptr));
  183689. #ifdef PNG_EASY_ACCESS_SUPPORTED
  183690. /* Returns image width in pixels. */
  183691. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  183692. png_ptr, png_infop info_ptr));
  183693. /* Returns image height in pixels. */
  183694. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  183695. png_ptr, png_infop info_ptr));
  183696. /* Returns image bit_depth. */
  183697. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  183698. png_ptr, png_infop info_ptr));
  183699. /* Returns image color_type. */
  183700. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  183701. png_ptr, png_infop info_ptr));
  183702. /* Returns image filter_type. */
  183703. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  183704. png_ptr, png_infop info_ptr));
  183705. /* Returns image interlace_type. */
  183706. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  183707. png_ptr, png_infop info_ptr));
  183708. /* Returns image compression_type. */
  183709. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  183710. png_ptr, png_infop info_ptr));
  183711. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  183712. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  183713. png_ptr, png_infop info_ptr));
  183714. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  183715. png_ptr, png_infop info_ptr));
  183716. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  183717. png_ptr, png_infop info_ptr));
  183718. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  183719. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183720. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  183721. png_ptr, png_infop info_ptr));
  183722. #endif
  183723. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  183724. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  183725. png_ptr, png_infop info_ptr));
  183726. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  183727. png_ptr, png_infop info_ptr));
  183728. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  183729. png_ptr, png_infop info_ptr));
  183730. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  183731. png_ptr, png_infop info_ptr));
  183732. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  183733. /* Returns pointer to signature string read from PNG header */
  183734. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  183735. png_infop info_ptr));
  183736. #if defined(PNG_bKGD_SUPPORTED)
  183737. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  183738. png_infop info_ptr, png_color_16p *background));
  183739. #endif
  183740. #if defined(PNG_bKGD_SUPPORTED)
  183741. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  183742. png_infop info_ptr, png_color_16p background));
  183743. #endif
  183744. #if defined(PNG_cHRM_SUPPORTED)
  183745. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183746. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  183747. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  183748. double *red_y, double *green_x, double *green_y, double *blue_x,
  183749. double *blue_y));
  183750. #endif
  183751. #ifdef PNG_FIXED_POINT_SUPPORTED
  183752. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  183753. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  183754. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  183755. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  183756. *int_blue_x, png_fixed_point *int_blue_y));
  183757. #endif
  183758. #endif
  183759. #if defined(PNG_cHRM_SUPPORTED)
  183760. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183761. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  183762. png_infop info_ptr, double white_x, double white_y, double red_x,
  183763. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  183764. #endif
  183765. #ifdef PNG_FIXED_POINT_SUPPORTED
  183766. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  183767. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  183768. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  183769. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  183770. png_fixed_point int_blue_y));
  183771. #endif
  183772. #endif
  183773. #if defined(PNG_gAMA_SUPPORTED)
  183774. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183775. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  183776. png_infop info_ptr, double *file_gamma));
  183777. #endif
  183778. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  183779. png_infop info_ptr, png_fixed_point *int_file_gamma));
  183780. #endif
  183781. #if defined(PNG_gAMA_SUPPORTED)
  183782. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183783. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  183784. png_infop info_ptr, double file_gamma));
  183785. #endif
  183786. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  183787. png_infop info_ptr, png_fixed_point int_file_gamma));
  183788. #endif
  183789. #if defined(PNG_hIST_SUPPORTED)
  183790. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  183791. png_infop info_ptr, png_uint_16p *hist));
  183792. #endif
  183793. #if defined(PNG_hIST_SUPPORTED)
  183794. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  183795. png_infop info_ptr, png_uint_16p hist));
  183796. #endif
  183797. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  183798. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  183799. int *bit_depth, int *color_type, int *interlace_method,
  183800. int *compression_method, int *filter_method));
  183801. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  183802. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  183803. int color_type, int interlace_method, int compression_method,
  183804. int filter_method));
  183805. #if defined(PNG_oFFs_SUPPORTED)
  183806. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  183807. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  183808. int *unit_type));
  183809. #endif
  183810. #if defined(PNG_oFFs_SUPPORTED)
  183811. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  183812. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  183813. int unit_type));
  183814. #endif
  183815. #if defined(PNG_pCAL_SUPPORTED)
  183816. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  183817. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  183818. int *type, int *nparams, png_charp *units, png_charpp *params));
  183819. #endif
  183820. #if defined(PNG_pCAL_SUPPORTED)
  183821. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  183822. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  183823. int type, int nparams, png_charp units, png_charpp params));
  183824. #endif
  183825. #if defined(PNG_pHYs_SUPPORTED)
  183826. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  183827. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  183828. #endif
  183829. #if defined(PNG_pHYs_SUPPORTED)
  183830. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  183831. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  183832. #endif
  183833. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  183834. png_infop info_ptr, png_colorp *palette, int *num_palette));
  183835. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  183836. png_infop info_ptr, png_colorp palette, int num_palette));
  183837. #if defined(PNG_sBIT_SUPPORTED)
  183838. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  183839. png_infop info_ptr, png_color_8p *sig_bit));
  183840. #endif
  183841. #if defined(PNG_sBIT_SUPPORTED)
  183842. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  183843. png_infop info_ptr, png_color_8p sig_bit));
  183844. #endif
  183845. #if defined(PNG_sRGB_SUPPORTED)
  183846. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  183847. png_infop info_ptr, int *intent));
  183848. #endif
  183849. #if defined(PNG_sRGB_SUPPORTED)
  183850. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  183851. png_infop info_ptr, int intent));
  183852. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  183853. png_infop info_ptr, int intent));
  183854. #endif
  183855. #if defined(PNG_iCCP_SUPPORTED)
  183856. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  183857. png_infop info_ptr, png_charpp name, int *compression_type,
  183858. png_charpp profile, png_uint_32 *proflen));
  183859. /* Note to maintainer: profile should be png_bytepp */
  183860. #endif
  183861. #if defined(PNG_iCCP_SUPPORTED)
  183862. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  183863. png_infop info_ptr, png_charp name, int compression_type,
  183864. png_charp profile, png_uint_32 proflen));
  183865. /* Note to maintainer: profile should be png_bytep */
  183866. #endif
  183867. #if defined(PNG_sPLT_SUPPORTED)
  183868. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  183869. png_infop info_ptr, png_sPLT_tpp entries));
  183870. #endif
  183871. #if defined(PNG_sPLT_SUPPORTED)
  183872. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  183873. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  183874. #endif
  183875. #if defined(PNG_TEXT_SUPPORTED)
  183876. /* png_get_text also returns the number of text chunks in *num_text */
  183877. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  183878. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  183879. #endif
  183880. /*
  183881. * Note while png_set_text() will accept a structure whose text,
  183882. * language, and translated keywords are NULL pointers, the structure
  183883. * returned by png_get_text will always contain regular
  183884. * zero-terminated C strings. They might be empty strings but
  183885. * they will never be NULL pointers.
  183886. */
  183887. #if defined(PNG_TEXT_SUPPORTED)
  183888. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  183889. png_infop info_ptr, png_textp text_ptr, int num_text));
  183890. #endif
  183891. #if defined(PNG_tIME_SUPPORTED)
  183892. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  183893. png_infop info_ptr, png_timep *mod_time));
  183894. #endif
  183895. #if defined(PNG_tIME_SUPPORTED)
  183896. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  183897. png_infop info_ptr, png_timep mod_time));
  183898. #endif
  183899. #if defined(PNG_tRNS_SUPPORTED)
  183900. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  183901. png_infop info_ptr, png_bytep *trans, int *num_trans,
  183902. png_color_16p *trans_values));
  183903. #endif
  183904. #if defined(PNG_tRNS_SUPPORTED)
  183905. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  183906. png_infop info_ptr, png_bytep trans, int num_trans,
  183907. png_color_16p trans_values));
  183908. #endif
  183909. #if defined(PNG_tRNS_SUPPORTED)
  183910. #endif
  183911. #if defined(PNG_sCAL_SUPPORTED)
  183912. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183913. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  183914. png_infop info_ptr, int *unit, double *width, double *height));
  183915. #else
  183916. #ifdef PNG_FIXED_POINT_SUPPORTED
  183917. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  183918. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  183919. #endif
  183920. #endif
  183921. #endif /* PNG_sCAL_SUPPORTED */
  183922. #if defined(PNG_sCAL_SUPPORTED)
  183923. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183924. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  183925. png_infop info_ptr, int unit, double width, double height));
  183926. #else
  183927. #ifdef PNG_FIXED_POINT_SUPPORTED
  183928. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  183929. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  183930. #endif
  183931. #endif
  183932. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  183933. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183934. /* provide a list of chunks and how they are to be handled, if the built-in
  183935. handling or default unknown chunk handling is not desired. Any chunks not
  183936. listed will be handled in the default manner. The IHDR and IEND chunks
  183937. must not be listed.
  183938. keep = 0: follow default behaviour
  183939. = 1: do not keep
  183940. = 2: keep only if safe-to-copy
  183941. = 3: keep even if unsafe-to-copy
  183942. */
  183943. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  183944. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  183945. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  183946. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  183947. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  183948. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  183949. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  183950. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  183951. #endif
  183952. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  183953. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  183954. chunk_name));
  183955. #endif
  183956. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  183957. If you need to turn it off for a chunk that your application has freed,
  183958. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  183959. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  183960. png_infop info_ptr, int mask));
  183961. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183962. /* The "params" pointer is currently not used and is for future expansion. */
  183963. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  183964. png_infop info_ptr,
  183965. int transforms,
  183966. png_voidp params));
  183967. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  183968. png_infop info_ptr,
  183969. int transforms,
  183970. png_voidp params));
  183971. #endif
  183972. /* Define PNG_DEBUG at compile time for debugging information. Higher
  183973. * numbers for PNG_DEBUG mean more debugging information. This has
  183974. * only been added since version 0.95 so it is not implemented throughout
  183975. * libpng yet, but more support will be added as needed.
  183976. */
  183977. #ifdef PNG_DEBUG
  183978. #if (PNG_DEBUG > 0)
  183979. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  183980. #include <crtdbg.h>
  183981. #if (PNG_DEBUG > 1)
  183982. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  183983. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  183984. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  183985. #endif
  183986. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  183987. #ifndef PNG_DEBUG_FILE
  183988. #define PNG_DEBUG_FILE stderr
  183989. #endif /* PNG_DEBUG_FILE */
  183990. #if (PNG_DEBUG > 1)
  183991. #define png_debug(l,m) \
  183992. { \
  183993. int num_tabs=l; \
  183994. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  183995. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  183996. }
  183997. #define png_debug1(l,m,p1) \
  183998. { \
  183999. int num_tabs=l; \
  184000. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184001. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  184002. }
  184003. #define png_debug2(l,m,p1,p2) \
  184004. { \
  184005. int num_tabs=l; \
  184006. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184007. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  184008. }
  184009. #endif /* (PNG_DEBUG > 1) */
  184010. #endif /* _MSC_VER */
  184011. #endif /* (PNG_DEBUG > 0) */
  184012. #endif /* PNG_DEBUG */
  184013. #ifndef png_debug
  184014. #define png_debug(l, m)
  184015. #endif
  184016. #ifndef png_debug1
  184017. #define png_debug1(l, m, p1)
  184018. #endif
  184019. #ifndef png_debug2
  184020. #define png_debug2(l, m, p1, p2)
  184021. #endif
  184022. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  184023. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  184024. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  184025. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  184026. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184027. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  184028. png_ptr, png_uint_32 mng_features_permitted));
  184029. #endif
  184030. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  184031. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  184032. #define PNG_HANDLE_CHUNK_NEVER 1
  184033. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184034. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184035. /* Added to version 1.2.0 */
  184036. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184037. #if defined(PNG_MMX_CODE_SUPPORTED)
  184038. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184039. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184040. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184041. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184042. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184043. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184044. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184045. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184046. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184047. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184048. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184049. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184050. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184051. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184052. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184053. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184054. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184055. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184056. | PNG_MMX_READ_FLAGS \
  184057. | PNG_MMX_WRITE_FLAGS )
  184058. #define PNG_SELECT_READ 1
  184059. #define PNG_SELECT_WRITE 2
  184060. #endif /* PNG_MMX_CODE_SUPPORTED */
  184061. #if !defined(PNG_1_0_X)
  184062. /* pngget.c */
  184063. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184064. PNGARG((int flag_select, int *compilerID));
  184065. /* pngget.c */
  184066. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184067. PNGARG((int flag_select));
  184068. /* pngget.c */
  184069. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184070. PNGARG((png_structp png_ptr));
  184071. /* pngget.c */
  184072. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184073. PNGARG((png_structp png_ptr));
  184074. /* pngget.c */
  184075. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184076. PNGARG((png_structp png_ptr));
  184077. /* pngset.c */
  184078. extern PNG_EXPORT(void,png_set_asm_flags)
  184079. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184080. /* pngset.c */
  184081. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184082. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184083. png_uint_32 mmx_rowbytes_threshold));
  184084. #endif /* PNG_1_0_X */
  184085. #if !defined(PNG_1_0_X)
  184086. /* png.c, pnggccrd.c, or pngvcrd.c */
  184087. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184088. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184089. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184090. * messages before passing them to the error or warning handler. */
  184091. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184092. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184093. png_ptr, png_uint_32 strip_mode));
  184094. #endif
  184095. #endif /* PNG_1_0_X */
  184096. /* Added at libpng-1.2.6 */
  184097. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184098. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184099. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184100. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184101. png_ptr));
  184102. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184103. png_ptr));
  184104. #endif
  184105. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184106. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184107. /* With these routines we avoid an integer divide, which will be slower on
  184108. * most machines. However, it does take more operations than the corresponding
  184109. * divide method, so it may be slower on a few RISC systems. There are two
  184110. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184111. *
  184112. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184113. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184114. * standard method.
  184115. *
  184116. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184117. */
  184118. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184119. # define png_composite(composite, fg, alpha, bg) \
  184120. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184121. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184122. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184123. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184124. # define png_composite_16(composite, fg, alpha, bg) \
  184125. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184126. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184127. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184128. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184129. #else /* standard method using integer division */
  184130. # define png_composite(composite, fg, alpha, bg) \
  184131. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184132. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184133. (png_uint_16)127) / 255)
  184134. # define png_composite_16(composite, fg, alpha, bg) \
  184135. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184136. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184137. (png_uint_32)32767) / (png_uint_32)65535L)
  184138. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184139. /* Inline macros to do direct reads of bytes from the input buffer. These
  184140. * require that you are using an architecture that uses PNG byte ordering
  184141. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184142. * in big-endian mode and 680x0 are the only ones that will support this.
  184143. * The x86 line of processors definitely do not. The png_get_int_32()
  184144. * routine also assumes we are using two's complement format for negative
  184145. * values, which is almost certainly true.
  184146. */
  184147. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184148. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184149. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184150. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184151. #else
  184152. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184153. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184154. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184155. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184156. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184157. PNGARG((png_structp png_ptr, png_bytep buf));
  184158. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184159. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184160. */
  184161. extern PNG_EXPORT(void,png_save_uint_32)
  184162. PNGARG((png_bytep buf, png_uint_32 i));
  184163. extern PNG_EXPORT(void,png_save_int_32)
  184164. PNGARG((png_bytep buf, png_int_32 i));
  184165. /* Place a 16-bit number into a buffer in PNG byte order.
  184166. * The parameter is declared unsigned int, not png_uint_16,
  184167. * just to avoid potential problems on pre-ANSI C compilers.
  184168. */
  184169. extern PNG_EXPORT(void,png_save_uint_16)
  184170. PNGARG((png_bytep buf, unsigned int i));
  184171. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184172. /* ************************************************************************* */
  184173. /* These next functions are used internally in the code. They generally
  184174. * shouldn't be used unless you are writing code to add or replace some
  184175. * functionality in libpng. More information about most functions can
  184176. * be found in the files where the functions are located.
  184177. */
  184178. /* Various modes of operation, that are visible to applications because
  184179. * they are used for unknown chunk location.
  184180. */
  184181. #define PNG_HAVE_IHDR 0x01
  184182. #define PNG_HAVE_PLTE 0x02
  184183. #define PNG_HAVE_IDAT 0x04
  184184. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184185. #define PNG_HAVE_IEND 0x10
  184186. #if defined(PNG_INTERNAL)
  184187. /* More modes of operation. Note that after an init, mode is set to
  184188. * zero automatically when the structure is created.
  184189. */
  184190. #define PNG_HAVE_gAMA 0x20
  184191. #define PNG_HAVE_cHRM 0x40
  184192. #define PNG_HAVE_sRGB 0x80
  184193. #define PNG_HAVE_CHUNK_HEADER 0x100
  184194. #define PNG_WROTE_tIME 0x200
  184195. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184196. #define PNG_BACKGROUND_IS_GRAY 0x800
  184197. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184198. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184199. /* flags for the transformations the PNG library does on the image data */
  184200. #define PNG_BGR 0x0001
  184201. #define PNG_INTERLACE 0x0002
  184202. #define PNG_PACK 0x0004
  184203. #define PNG_SHIFT 0x0008
  184204. #define PNG_SWAP_BYTES 0x0010
  184205. #define PNG_INVERT_MONO 0x0020
  184206. #define PNG_DITHER 0x0040
  184207. #define PNG_BACKGROUND 0x0080
  184208. #define PNG_BACKGROUND_EXPAND 0x0100
  184209. /* 0x0200 unused */
  184210. #define PNG_16_TO_8 0x0400
  184211. #define PNG_RGBA 0x0800
  184212. #define PNG_EXPAND 0x1000
  184213. #define PNG_GAMMA 0x2000
  184214. #define PNG_GRAY_TO_RGB 0x4000
  184215. #define PNG_FILLER 0x8000L
  184216. #define PNG_PACKSWAP 0x10000L
  184217. #define PNG_SWAP_ALPHA 0x20000L
  184218. #define PNG_STRIP_ALPHA 0x40000L
  184219. #define PNG_INVERT_ALPHA 0x80000L
  184220. #define PNG_USER_TRANSFORM 0x100000L
  184221. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184222. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184223. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184224. /* 0x800000L Unused */
  184225. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184226. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184227. /* 0x4000000L unused */
  184228. /* 0x8000000L unused */
  184229. /* 0x10000000L unused */
  184230. /* 0x20000000L unused */
  184231. /* 0x40000000L unused */
  184232. /* flags for png_create_struct */
  184233. #define PNG_STRUCT_PNG 0x0001
  184234. #define PNG_STRUCT_INFO 0x0002
  184235. /* Scaling factor for filter heuristic weighting calculations */
  184236. #define PNG_WEIGHT_SHIFT 8
  184237. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184238. #define PNG_COST_SHIFT 3
  184239. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184240. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184241. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184242. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184243. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184244. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184245. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184246. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184247. #define PNG_FLAG_ROW_INIT 0x0040
  184248. #define PNG_FLAG_FILLER_AFTER 0x0080
  184249. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184250. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184251. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184252. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184253. #define PNG_FLAG_FREE_PLTE 0x1000
  184254. #define PNG_FLAG_FREE_TRNS 0x2000
  184255. #define PNG_FLAG_FREE_HIST 0x4000
  184256. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184257. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184258. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184259. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184260. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184261. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184262. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184263. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184264. /* 0x800000L unused */
  184265. /* 0x1000000L unused */
  184266. /* 0x2000000L unused */
  184267. /* 0x4000000L unused */
  184268. /* 0x8000000L unused */
  184269. /* 0x10000000L unused */
  184270. /* 0x20000000L unused */
  184271. /* 0x40000000L unused */
  184272. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184273. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184274. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184275. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184276. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184277. PNG_FLAG_CRC_CRITICAL_MASK)
  184278. /* save typing and make code easier to understand */
  184279. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184280. abs((int)((c1).green) - (int)((c2).green)) + \
  184281. abs((int)((c1).blue) - (int)((c2).blue)))
  184282. /* Added to libpng-1.2.6 JB */
  184283. #define PNG_ROWBYTES(pixel_bits, width) \
  184284. ((pixel_bits) >= 8 ? \
  184285. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  184286. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  184287. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  184288. ideal-delta..ideal+delta. Each argument is evaluated twice.
  184289. "ideal" and "delta" should be constants, normally simple
  184290. integers, "value" a variable. Added to libpng-1.2.6 JB */
  184291. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  184292. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  184293. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  184294. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  184295. /* place to hold the signature string for a PNG file. */
  184296. #ifdef PNG_USE_GLOBAL_ARRAYS
  184297. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  184298. #else
  184299. #endif
  184300. #endif /* PNG_NO_EXTERN */
  184301. /* Constant strings for known chunk types. If you need to add a chunk,
  184302. * define the name here, and add an invocation of the macro in png.c and
  184303. * wherever it's needed.
  184304. */
  184305. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  184306. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  184307. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  184308. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  184309. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  184310. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  184311. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  184312. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  184313. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  184314. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  184315. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  184316. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  184317. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  184318. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  184319. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  184320. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  184321. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  184322. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  184323. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  184324. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  184325. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  184326. #ifdef PNG_USE_GLOBAL_ARRAYS
  184327. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  184328. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  184329. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  184330. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  184331. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  184332. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  184333. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  184334. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  184335. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  184336. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  184337. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  184338. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  184339. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  184340. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  184341. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  184342. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  184343. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  184344. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  184345. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  184346. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  184347. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  184348. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184349. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184350. /* Initialize png_ptr struct for reading, and allocate any other memory.
  184351. * (old interface - DEPRECATED - use png_create_read_struct instead).
  184352. */
  184353. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  184354. #undef png_read_init
  184355. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  184356. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184357. #endif
  184358. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  184359. png_const_charp user_png_ver, png_size_t png_struct_size));
  184360. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184361. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  184362. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184363. png_info_size));
  184364. #endif
  184365. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184366. /* Initialize png_ptr struct for writing, and allocate any other memory.
  184367. * (old interface - DEPRECATED - use png_create_write_struct instead).
  184368. */
  184369. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  184370. #undef png_write_init
  184371. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  184372. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  184373. #endif
  184374. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  184375. png_const_charp user_png_ver, png_size_t png_struct_size));
  184376. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  184377. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  184378. png_info_size));
  184379. /* Allocate memory for an internal libpng struct */
  184380. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  184381. /* Free memory from internal libpng struct */
  184382. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  184383. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  184384. malloc_fn, png_voidp mem_ptr));
  184385. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  184386. png_free_ptr free_fn, png_voidp mem_ptr));
  184387. /* Free any memory that info_ptr points to and reset struct. */
  184388. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  184389. png_infop info_ptr));
  184390. #ifndef PNG_1_0_X
  184391. /* Function to allocate memory for zlib. */
  184392. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  184393. /* Function to free memory for zlib */
  184394. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  184395. #ifdef PNG_SIZE_T
  184396. /* Function to convert a sizeof an item to png_sizeof item */
  184397. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  184398. #endif
  184399. /* Next four functions are used internally as callbacks. PNGAPI is required
  184400. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  184401. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  184402. png_bytep data, png_size_t length));
  184403. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184404. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  184405. png_bytep buffer, png_size_t length));
  184406. #endif
  184407. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  184408. png_bytep data, png_size_t length));
  184409. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184410. #if !defined(PNG_NO_STDIO)
  184411. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  184412. #endif
  184413. #endif
  184414. #else /* PNG_1_0_X */
  184415. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184416. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  184417. png_bytep buffer, png_size_t length));
  184418. #endif
  184419. #endif /* PNG_1_0_X */
  184420. /* Reset the CRC variable */
  184421. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  184422. /* Write the "data" buffer to whatever output you are using. */
  184423. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  184424. png_size_t length));
  184425. /* Read data from whatever input you are using into the "data" buffer */
  184426. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  184427. png_size_t length));
  184428. /* Read bytes into buf, and update png_ptr->crc */
  184429. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  184430. png_size_t length));
  184431. /* Decompress data in a chunk that uses compression */
  184432. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  184433. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  184434. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  184435. int comp_type, png_charp chunkdata, png_size_t chunklength,
  184436. png_size_t prefix_length, png_size_t *data_length));
  184437. #endif
  184438. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  184439. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  184440. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  184441. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  184442. /* Calculate the CRC over a section of data. Note that we are only
  184443. * passing a maximum of 64K on systems that have this as a memory limit,
  184444. * since this is the maximum buffer size we can specify.
  184445. */
  184446. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  184447. png_size_t length));
  184448. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184449. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  184450. #endif
  184451. /* simple function to write the signature */
  184452. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  184453. /* write various chunks */
  184454. /* Write the IHDR chunk, and update the png_struct with the necessary
  184455. * information.
  184456. */
  184457. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  184458. png_uint_32 height,
  184459. int bit_depth, int color_type, int compression_method, int filter_method,
  184460. int interlace_method));
  184461. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  184462. png_uint_32 num_pal));
  184463. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  184464. png_size_t length));
  184465. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  184466. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  184467. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184468. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  184469. #endif
  184470. #ifdef PNG_FIXED_POINT_SUPPORTED
  184471. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  184472. file_gamma));
  184473. #endif
  184474. #endif
  184475. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  184476. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  184477. int color_type));
  184478. #endif
  184479. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  184480. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184481. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  184482. double white_x, double white_y,
  184483. double red_x, double red_y, double green_x, double green_y,
  184484. double blue_x, double blue_y));
  184485. #endif
  184486. #ifdef PNG_FIXED_POINT_SUPPORTED
  184487. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  184488. png_fixed_point int_white_x, png_fixed_point int_white_y,
  184489. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184490. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184491. png_fixed_point int_blue_y));
  184492. #endif
  184493. #endif
  184494. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  184495. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  184496. int intent));
  184497. #endif
  184498. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  184499. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  184500. png_charp name, int compression_type,
  184501. png_charp profile, int proflen));
  184502. /* Note to maintainer: profile should be png_bytep */
  184503. #endif
  184504. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  184505. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  184506. png_sPLT_tp palette));
  184507. #endif
  184508. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  184509. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  184510. png_color_16p values, int number, int color_type));
  184511. #endif
  184512. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  184513. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  184514. png_color_16p values, int color_type));
  184515. #endif
  184516. #if defined(PNG_WRITE_hIST_SUPPORTED)
  184517. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  184518. int num_hist));
  184519. #endif
  184520. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  184521. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  184522. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  184523. png_charp key, png_charpp new_key));
  184524. #endif
  184525. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  184526. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  184527. png_charp text, png_size_t text_len));
  184528. #endif
  184529. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  184530. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  184531. png_charp text, png_size_t text_len, int compression));
  184532. #endif
  184533. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  184534. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  184535. int compression, png_charp key, png_charp lang, png_charp lang_key,
  184536. png_charp text));
  184537. #endif
  184538. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  184539. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  184540. png_infop info_ptr, png_textp text_ptr, int num_text));
  184541. #endif
  184542. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  184543. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  184544. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  184545. #endif
  184546. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  184547. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  184548. png_int_32 X0, png_int_32 X1, int type, int nparams,
  184549. png_charp units, png_charpp params));
  184550. #endif
  184551. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  184552. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  184553. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  184554. int unit_type));
  184555. #endif
  184556. #if defined(PNG_WRITE_tIME_SUPPORTED)
  184557. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  184558. png_timep mod_time));
  184559. #endif
  184560. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  184561. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  184562. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  184563. int unit, double width, double height));
  184564. #else
  184565. #ifdef PNG_FIXED_POINT_SUPPORTED
  184566. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  184567. int unit, png_charp width, png_charp height));
  184568. #endif
  184569. #endif
  184570. #endif
  184571. /* Called when finished processing a row of data */
  184572. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  184573. /* Internal use only. Called before first row of data */
  184574. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  184575. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184576. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  184577. #endif
  184578. /* combine a row of data, dealing with alpha, etc. if requested */
  184579. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  184580. int mask));
  184581. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  184582. /* expand an interlaced row */
  184583. /* OLD pre-1.0.9 interface:
  184584. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  184585. png_bytep row, int pass, png_uint_32 transformations));
  184586. */
  184587. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  184588. #endif
  184589. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  184590. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  184591. /* grab pixels out of a row for an interlaced pass */
  184592. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  184593. png_bytep row, int pass));
  184594. #endif
  184595. /* unfilter a row */
  184596. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  184597. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  184598. /* Choose the best filter to use and filter the row data */
  184599. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  184600. png_row_infop row_info));
  184601. /* Write out the filtered row. */
  184602. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  184603. png_bytep filtered_row));
  184604. /* finish a row while reading, dealing with interlacing passes, etc. */
  184605. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  184606. /* initialize the row buffers, etc. */
  184607. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  184608. /* optional call to update the users info structure */
  184609. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  184610. png_infop info_ptr));
  184611. /* these are the functions that do the transformations */
  184612. #if defined(PNG_READ_FILLER_SUPPORTED)
  184613. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  184614. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  184615. #endif
  184616. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  184617. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  184618. png_bytep row));
  184619. #endif
  184620. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  184621. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  184622. png_bytep row));
  184623. #endif
  184624. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  184625. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  184626. png_bytep row));
  184627. #endif
  184628. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  184629. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  184630. png_bytep row));
  184631. #endif
  184632. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  184633. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  184634. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  184635. png_bytep row, png_uint_32 flags));
  184636. #endif
  184637. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  184638. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  184639. #endif
  184640. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  184641. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  184642. #endif
  184643. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  184644. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  184645. row_info, png_bytep row));
  184646. #endif
  184647. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  184648. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  184649. png_bytep row));
  184650. #endif
  184651. #if defined(PNG_READ_PACK_SUPPORTED)
  184652. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  184653. #endif
  184654. #if defined(PNG_READ_SHIFT_SUPPORTED)
  184655. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  184656. png_color_8p sig_bits));
  184657. #endif
  184658. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  184659. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  184660. #endif
  184661. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184662. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  184663. #endif
  184664. #if defined(PNG_READ_DITHER_SUPPORTED)
  184665. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  184666. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  184667. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  184668. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  184669. png_colorp palette, int num_palette));
  184670. # endif
  184671. #endif
  184672. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  184673. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  184674. #endif
  184675. #if defined(PNG_WRITE_PACK_SUPPORTED)
  184676. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  184677. png_bytep row, png_uint_32 bit_depth));
  184678. #endif
  184679. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  184680. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  184681. png_color_8p bit_depth));
  184682. #endif
  184683. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  184684. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184685. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184686. png_color_16p trans_values, png_color_16p background,
  184687. png_color_16p background_1,
  184688. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  184689. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  184690. png_uint_16pp gamma_16_to_1, int gamma_shift));
  184691. #else
  184692. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  184693. png_color_16p trans_values, png_color_16p background));
  184694. #endif
  184695. #endif
  184696. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184697. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  184698. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  184699. int gamma_shift));
  184700. #endif
  184701. #if defined(PNG_READ_EXPAND_SUPPORTED)
  184702. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  184703. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  184704. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  184705. png_bytep row, png_color_16p trans_value));
  184706. #endif
  184707. /* The following decodes the appropriate chunks, and does error correction,
  184708. * then calls the appropriate callback for the chunk if it is valid.
  184709. */
  184710. /* decode the IHDR chunk */
  184711. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  184712. png_uint_32 length));
  184713. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  184714. png_uint_32 length));
  184715. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  184716. png_uint_32 length));
  184717. #if defined(PNG_READ_bKGD_SUPPORTED)
  184718. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  184719. png_uint_32 length));
  184720. #endif
  184721. #if defined(PNG_READ_cHRM_SUPPORTED)
  184722. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  184723. png_uint_32 length));
  184724. #endif
  184725. #if defined(PNG_READ_gAMA_SUPPORTED)
  184726. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  184727. png_uint_32 length));
  184728. #endif
  184729. #if defined(PNG_READ_hIST_SUPPORTED)
  184730. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  184731. png_uint_32 length));
  184732. #endif
  184733. #if defined(PNG_READ_iCCP_SUPPORTED)
  184734. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  184735. png_uint_32 length));
  184736. #endif /* PNG_READ_iCCP_SUPPORTED */
  184737. #if defined(PNG_READ_iTXt_SUPPORTED)
  184738. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184739. png_uint_32 length));
  184740. #endif
  184741. #if defined(PNG_READ_oFFs_SUPPORTED)
  184742. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184743. png_uint_32 length));
  184744. #endif
  184745. #if defined(PNG_READ_pCAL_SUPPORTED)
  184746. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184747. png_uint_32 length));
  184748. #endif
  184749. #if defined(PNG_READ_pHYs_SUPPORTED)
  184750. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  184751. png_uint_32 length));
  184752. #endif
  184753. #if defined(PNG_READ_sBIT_SUPPORTED)
  184754. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184755. png_uint_32 length));
  184756. #endif
  184757. #if defined(PNG_READ_sCAL_SUPPORTED)
  184758. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  184759. png_uint_32 length));
  184760. #endif
  184761. #if defined(PNG_READ_sPLT_SUPPORTED)
  184762. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  184763. png_uint_32 length));
  184764. #endif /* PNG_READ_sPLT_SUPPORTED */
  184765. #if defined(PNG_READ_sRGB_SUPPORTED)
  184766. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  184767. png_uint_32 length));
  184768. #endif
  184769. #if defined(PNG_READ_tEXt_SUPPORTED)
  184770. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184771. png_uint_32 length));
  184772. #endif
  184773. #if defined(PNG_READ_tIME_SUPPORTED)
  184774. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  184775. png_uint_32 length));
  184776. #endif
  184777. #if defined(PNG_READ_tRNS_SUPPORTED)
  184778. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  184779. png_uint_32 length));
  184780. #endif
  184781. #if defined(PNG_READ_zTXt_SUPPORTED)
  184782. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  184783. png_uint_32 length));
  184784. #endif
  184785. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  184786. png_infop info_ptr, png_uint_32 length));
  184787. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  184788. png_bytep chunk_name));
  184789. /* handle the transformations for reading and writing */
  184790. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  184791. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  184792. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  184793. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184794. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  184795. png_infop info_ptr));
  184796. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  184797. png_infop info_ptr));
  184798. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  184799. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  184800. png_uint_32 length));
  184801. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  184802. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  184803. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  184804. png_bytep buffer, png_size_t buffer_length));
  184805. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  184806. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  184807. png_bytep buffer, png_size_t buffer_length));
  184808. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  184809. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  184810. png_infop info_ptr, png_uint_32 length));
  184811. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  184812. png_infop info_ptr));
  184813. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  184814. png_infop info_ptr));
  184815. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  184816. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  184817. png_infop info_ptr));
  184818. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  184819. png_infop info_ptr));
  184820. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  184821. #if defined(PNG_READ_tEXt_SUPPORTED)
  184822. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  184823. png_infop info_ptr, png_uint_32 length));
  184824. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  184825. png_infop info_ptr));
  184826. #endif
  184827. #if defined(PNG_READ_zTXt_SUPPORTED)
  184828. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  184829. png_infop info_ptr, png_uint_32 length));
  184830. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  184831. png_infop info_ptr));
  184832. #endif
  184833. #if defined(PNG_READ_iTXt_SUPPORTED)
  184834. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  184835. png_infop info_ptr, png_uint_32 length));
  184836. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  184837. png_infop info_ptr));
  184838. #endif
  184839. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184840. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184841. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  184842. png_bytep row));
  184843. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  184844. png_bytep row));
  184845. #endif
  184846. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184847. #if defined(PNG_MMX_CODE_SUPPORTED)
  184848. /* png.c */ /* PRIVATE */
  184849. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  184850. #endif
  184851. #endif
  184852. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  184853. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  184854. png_infop info_ptr));
  184855. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  184856. png_infop info_ptr));
  184857. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  184858. png_infop info_ptr));
  184859. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  184860. png_infop info_ptr));
  184861. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  184862. png_infop info_ptr));
  184863. #if defined(PNG_pHYs_SUPPORTED)
  184864. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  184865. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184866. #endif /* PNG_pHYs_SUPPORTED */
  184867. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  184868. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  184869. #endif /* PNG_INTERNAL */
  184870. #ifdef __cplusplus
  184871. //}
  184872. #endif
  184873. #endif /* PNG_VERSION_INFO_ONLY */
  184874. /* do not put anything past this line */
  184875. #endif /* PNG_H */
  184876. /*** End of inlined file: png.h ***/
  184877. #define PNG_NO_EXTERN
  184878. /*** Start of inlined file: png.c ***/
  184879. /* png.c - location for general purpose libpng functions
  184880. *
  184881. * Last changed in libpng 1.2.21 [October 4, 2007]
  184882. * For conditions of distribution and use, see copyright notice in png.h
  184883. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  184884. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  184885. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  184886. */
  184887. #define PNG_INTERNAL
  184888. #define PNG_NO_EXTERN
  184889. /* Generate a compiler error if there is an old png.h in the search path. */
  184890. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  184891. /* Version information for C files. This had better match the version
  184892. * string defined in png.h. */
  184893. #ifdef PNG_USE_GLOBAL_ARRAYS
  184894. /* png_libpng_ver was changed to a function in version 1.0.5c */
  184895. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  184896. #ifdef PNG_READ_SUPPORTED
  184897. /* png_sig was changed to a function in version 1.0.5c */
  184898. /* Place to hold the signature string for a PNG file. */
  184899. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184900. #endif /* PNG_READ_SUPPORTED */
  184901. /* Invoke global declarations for constant strings for known chunk types */
  184902. PNG_IHDR;
  184903. PNG_IDAT;
  184904. PNG_IEND;
  184905. PNG_PLTE;
  184906. PNG_bKGD;
  184907. PNG_cHRM;
  184908. PNG_gAMA;
  184909. PNG_hIST;
  184910. PNG_iCCP;
  184911. PNG_iTXt;
  184912. PNG_oFFs;
  184913. PNG_pCAL;
  184914. PNG_sCAL;
  184915. PNG_pHYs;
  184916. PNG_sBIT;
  184917. PNG_sPLT;
  184918. PNG_sRGB;
  184919. PNG_tEXt;
  184920. PNG_tIME;
  184921. PNG_tRNS;
  184922. PNG_zTXt;
  184923. #ifdef PNG_READ_SUPPORTED
  184924. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  184925. /* start of interlace block */
  184926. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  184927. /* offset to next interlace block */
  184928. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  184929. /* start of interlace block in the y direction */
  184930. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  184931. /* offset to next interlace block in the y direction */
  184932. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  184933. /* Height of interlace block. This is not currently used - if you need
  184934. * it, uncomment it here and in png.h
  184935. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  184936. */
  184937. /* Mask to determine which pixels are valid in a pass */
  184938. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  184939. /* Mask to determine which pixels to overwrite while displaying */
  184940. PNG_CONST int FARDATA png_pass_dsp_mask[]
  184941. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  184942. #endif /* PNG_READ_SUPPORTED */
  184943. #endif /* PNG_USE_GLOBAL_ARRAYS */
  184944. /* Tells libpng that we have already handled the first "num_bytes" bytes
  184945. * of the PNG file signature. If the PNG data is embedded into another
  184946. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  184947. * or write any of the magic bytes before it starts on the IHDR.
  184948. */
  184949. #ifdef PNG_READ_SUPPORTED
  184950. void PNGAPI
  184951. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  184952. {
  184953. if(png_ptr == NULL) return;
  184954. png_debug(1, "in png_set_sig_bytes\n");
  184955. if (num_bytes > 8)
  184956. png_error(png_ptr, "Too many bytes for PNG signature.");
  184957. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  184958. }
  184959. /* Checks whether the supplied bytes match the PNG signature. We allow
  184960. * checking less than the full 8-byte signature so that those apps that
  184961. * already read the first few bytes of a file to determine the file type
  184962. * can simply check the remaining bytes for extra assurance. Returns
  184963. * an integer less than, equal to, or greater than zero if sig is found,
  184964. * respectively, to be less than, to match, or be greater than the correct
  184965. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  184966. */
  184967. int PNGAPI
  184968. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  184969. {
  184970. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  184971. if (num_to_check > 8)
  184972. num_to_check = 8;
  184973. else if (num_to_check < 1)
  184974. return (-1);
  184975. if (start > 7)
  184976. return (-1);
  184977. if (start + num_to_check > 8)
  184978. num_to_check = 8 - start;
  184979. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  184980. }
  184981. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  184982. /* (Obsolete) function to check signature bytes. It does not allow one
  184983. * to check a partial signature. This function might be removed in the
  184984. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  184985. */
  184986. int PNGAPI
  184987. png_check_sig(png_bytep sig, int num)
  184988. {
  184989. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  184990. }
  184991. #endif
  184992. #endif /* PNG_READ_SUPPORTED */
  184993. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  184994. /* Function to allocate memory for zlib and clear it to 0. */
  184995. #ifdef PNG_1_0_X
  184996. voidpf PNGAPI
  184997. #else
  184998. voidpf /* private */
  184999. #endif
  185000. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  185001. {
  185002. png_voidp ptr;
  185003. png_structp p=(png_structp)png_ptr;
  185004. png_uint_32 save_flags=p->flags;
  185005. png_uint_32 num_bytes;
  185006. if(png_ptr == NULL) return (NULL);
  185007. if (items > PNG_UINT_32_MAX/size)
  185008. {
  185009. png_warning (p, "Potential overflow in png_zalloc()");
  185010. return (NULL);
  185011. }
  185012. num_bytes = (png_uint_32)items * size;
  185013. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  185014. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  185015. p->flags=save_flags;
  185016. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  185017. if (ptr == NULL)
  185018. return ((voidpf)ptr);
  185019. if (num_bytes > (png_uint_32)0x8000L)
  185020. {
  185021. png_memset(ptr, 0, (png_size_t)0x8000L);
  185022. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  185023. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  185024. }
  185025. else
  185026. {
  185027. png_memset(ptr, 0, (png_size_t)num_bytes);
  185028. }
  185029. #endif
  185030. return ((voidpf)ptr);
  185031. }
  185032. /* function to free memory for zlib */
  185033. #ifdef PNG_1_0_X
  185034. void PNGAPI
  185035. #else
  185036. void /* private */
  185037. #endif
  185038. png_zfree(voidpf png_ptr, voidpf ptr)
  185039. {
  185040. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185041. }
  185042. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185043. * in case CRC is > 32 bits to leave the top bits 0.
  185044. */
  185045. void /* PRIVATE */
  185046. png_reset_crc(png_structp png_ptr)
  185047. {
  185048. png_ptr->crc = crc32(0, Z_NULL, 0);
  185049. }
  185050. /* Calculate the CRC over a section of data. We can only pass as
  185051. * much data to this routine as the largest single buffer size. We
  185052. * also check that this data will actually be used before going to the
  185053. * trouble of calculating it.
  185054. */
  185055. void /* PRIVATE */
  185056. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185057. {
  185058. int need_crc = 1;
  185059. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185060. {
  185061. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185062. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185063. need_crc = 0;
  185064. }
  185065. else /* critical */
  185066. {
  185067. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185068. need_crc = 0;
  185069. }
  185070. if (need_crc)
  185071. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185072. }
  185073. /* Allocate the memory for an info_struct for the application. We don't
  185074. * really need the png_ptr, but it could potentially be useful in the
  185075. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185076. * and png_info_init() so that applications that want to use a shared
  185077. * libpng don't have to be recompiled if png_info changes size.
  185078. */
  185079. png_infop PNGAPI
  185080. png_create_info_struct(png_structp png_ptr)
  185081. {
  185082. png_infop info_ptr;
  185083. png_debug(1, "in png_create_info_struct\n");
  185084. if(png_ptr == NULL) return (NULL);
  185085. #ifdef PNG_USER_MEM_SUPPORTED
  185086. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185087. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185088. #else
  185089. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185090. #endif
  185091. if (info_ptr != NULL)
  185092. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185093. return (info_ptr);
  185094. }
  185095. /* This function frees the memory associated with a single info struct.
  185096. * Normally, one would use either png_destroy_read_struct() or
  185097. * png_destroy_write_struct() to free an info struct, but this may be
  185098. * useful for some applications.
  185099. */
  185100. void PNGAPI
  185101. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185102. {
  185103. png_infop info_ptr = NULL;
  185104. if(png_ptr == NULL) return;
  185105. png_debug(1, "in png_destroy_info_struct\n");
  185106. if (info_ptr_ptr != NULL)
  185107. info_ptr = *info_ptr_ptr;
  185108. if (info_ptr != NULL)
  185109. {
  185110. png_info_destroy(png_ptr, info_ptr);
  185111. #ifdef PNG_USER_MEM_SUPPORTED
  185112. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185113. png_ptr->mem_ptr);
  185114. #else
  185115. png_destroy_struct((png_voidp)info_ptr);
  185116. #endif
  185117. *info_ptr_ptr = NULL;
  185118. }
  185119. }
  185120. /* Initialize the info structure. This is now an internal function (0.89)
  185121. * and applications using it are urged to use png_create_info_struct()
  185122. * instead.
  185123. */
  185124. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185125. #undef png_info_init
  185126. void PNGAPI
  185127. png_info_init(png_infop info_ptr)
  185128. {
  185129. /* We only come here via pre-1.0.12-compiled applications */
  185130. png_info_init_3(&info_ptr, 0);
  185131. }
  185132. #endif
  185133. void PNGAPI
  185134. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185135. {
  185136. png_infop info_ptr = *ptr_ptr;
  185137. if(info_ptr == NULL) return;
  185138. png_debug(1, "in png_info_init_3\n");
  185139. if(png_sizeof(png_info) > png_info_struct_size)
  185140. {
  185141. png_destroy_struct(info_ptr);
  185142. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185143. *ptr_ptr = info_ptr;
  185144. }
  185145. /* set everything to 0 */
  185146. png_memset(info_ptr, 0, png_sizeof (png_info));
  185147. }
  185148. #ifdef PNG_FREE_ME_SUPPORTED
  185149. void PNGAPI
  185150. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185151. int freer, png_uint_32 mask)
  185152. {
  185153. png_debug(1, "in png_data_freer\n");
  185154. if (png_ptr == NULL || info_ptr == NULL)
  185155. return;
  185156. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185157. info_ptr->free_me |= mask;
  185158. else if(freer == PNG_USER_WILL_FREE_DATA)
  185159. info_ptr->free_me &= ~mask;
  185160. else
  185161. png_warning(png_ptr,
  185162. "Unknown freer parameter in png_data_freer.");
  185163. }
  185164. #endif
  185165. void PNGAPI
  185166. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185167. int num)
  185168. {
  185169. png_debug(1, "in png_free_data\n");
  185170. if (png_ptr == NULL || info_ptr == NULL)
  185171. return;
  185172. #if defined(PNG_TEXT_SUPPORTED)
  185173. /* free text item num or (if num == -1) all text items */
  185174. #ifdef PNG_FREE_ME_SUPPORTED
  185175. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185176. #else
  185177. if (mask & PNG_FREE_TEXT)
  185178. #endif
  185179. {
  185180. if (num != -1)
  185181. {
  185182. if (info_ptr->text && info_ptr->text[num].key)
  185183. {
  185184. png_free(png_ptr, info_ptr->text[num].key);
  185185. info_ptr->text[num].key = NULL;
  185186. }
  185187. }
  185188. else
  185189. {
  185190. int i;
  185191. for (i = 0; i < info_ptr->num_text; i++)
  185192. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185193. png_free(png_ptr, info_ptr->text);
  185194. info_ptr->text = NULL;
  185195. info_ptr->num_text=0;
  185196. }
  185197. }
  185198. #endif
  185199. #if defined(PNG_tRNS_SUPPORTED)
  185200. /* free any tRNS entry */
  185201. #ifdef PNG_FREE_ME_SUPPORTED
  185202. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185203. #else
  185204. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185205. #endif
  185206. {
  185207. png_free(png_ptr, info_ptr->trans);
  185208. info_ptr->valid &= ~PNG_INFO_tRNS;
  185209. #ifndef PNG_FREE_ME_SUPPORTED
  185210. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185211. #endif
  185212. info_ptr->trans = NULL;
  185213. }
  185214. #endif
  185215. #if defined(PNG_sCAL_SUPPORTED)
  185216. /* free any sCAL entry */
  185217. #ifdef PNG_FREE_ME_SUPPORTED
  185218. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185219. #else
  185220. if (mask & PNG_FREE_SCAL)
  185221. #endif
  185222. {
  185223. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185224. png_free(png_ptr, info_ptr->scal_s_width);
  185225. png_free(png_ptr, info_ptr->scal_s_height);
  185226. info_ptr->scal_s_width = NULL;
  185227. info_ptr->scal_s_height = NULL;
  185228. #endif
  185229. info_ptr->valid &= ~PNG_INFO_sCAL;
  185230. }
  185231. #endif
  185232. #if defined(PNG_pCAL_SUPPORTED)
  185233. /* free any pCAL entry */
  185234. #ifdef PNG_FREE_ME_SUPPORTED
  185235. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185236. #else
  185237. if (mask & PNG_FREE_PCAL)
  185238. #endif
  185239. {
  185240. png_free(png_ptr, info_ptr->pcal_purpose);
  185241. png_free(png_ptr, info_ptr->pcal_units);
  185242. info_ptr->pcal_purpose = NULL;
  185243. info_ptr->pcal_units = NULL;
  185244. if (info_ptr->pcal_params != NULL)
  185245. {
  185246. int i;
  185247. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185248. {
  185249. png_free(png_ptr, info_ptr->pcal_params[i]);
  185250. info_ptr->pcal_params[i]=NULL;
  185251. }
  185252. png_free(png_ptr, info_ptr->pcal_params);
  185253. info_ptr->pcal_params = NULL;
  185254. }
  185255. info_ptr->valid &= ~PNG_INFO_pCAL;
  185256. }
  185257. #endif
  185258. #if defined(PNG_iCCP_SUPPORTED)
  185259. /* free any iCCP entry */
  185260. #ifdef PNG_FREE_ME_SUPPORTED
  185261. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185262. #else
  185263. if (mask & PNG_FREE_ICCP)
  185264. #endif
  185265. {
  185266. png_free(png_ptr, info_ptr->iccp_name);
  185267. png_free(png_ptr, info_ptr->iccp_profile);
  185268. info_ptr->iccp_name = NULL;
  185269. info_ptr->iccp_profile = NULL;
  185270. info_ptr->valid &= ~PNG_INFO_iCCP;
  185271. }
  185272. #endif
  185273. #if defined(PNG_sPLT_SUPPORTED)
  185274. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185275. #ifdef PNG_FREE_ME_SUPPORTED
  185276. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185277. #else
  185278. if (mask & PNG_FREE_SPLT)
  185279. #endif
  185280. {
  185281. if (num != -1)
  185282. {
  185283. if(info_ptr->splt_palettes)
  185284. {
  185285. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  185286. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  185287. info_ptr->splt_palettes[num].name = NULL;
  185288. info_ptr->splt_palettes[num].entries = NULL;
  185289. }
  185290. }
  185291. else
  185292. {
  185293. if(info_ptr->splt_palettes_num)
  185294. {
  185295. int i;
  185296. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  185297. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  185298. png_free(png_ptr, info_ptr->splt_palettes);
  185299. info_ptr->splt_palettes = NULL;
  185300. info_ptr->splt_palettes_num = 0;
  185301. }
  185302. info_ptr->valid &= ~PNG_INFO_sPLT;
  185303. }
  185304. }
  185305. #endif
  185306. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185307. if(png_ptr->unknown_chunk.data)
  185308. {
  185309. png_free(png_ptr, png_ptr->unknown_chunk.data);
  185310. png_ptr->unknown_chunk.data = NULL;
  185311. }
  185312. #ifdef PNG_FREE_ME_SUPPORTED
  185313. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  185314. #else
  185315. if (mask & PNG_FREE_UNKN)
  185316. #endif
  185317. {
  185318. if (num != -1)
  185319. {
  185320. if(info_ptr->unknown_chunks)
  185321. {
  185322. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  185323. info_ptr->unknown_chunks[num].data = NULL;
  185324. }
  185325. }
  185326. else
  185327. {
  185328. int i;
  185329. if(info_ptr->unknown_chunks_num)
  185330. {
  185331. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  185332. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  185333. png_free(png_ptr, info_ptr->unknown_chunks);
  185334. info_ptr->unknown_chunks = NULL;
  185335. info_ptr->unknown_chunks_num = 0;
  185336. }
  185337. }
  185338. }
  185339. #endif
  185340. #if defined(PNG_hIST_SUPPORTED)
  185341. /* free any hIST entry */
  185342. #ifdef PNG_FREE_ME_SUPPORTED
  185343. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  185344. #else
  185345. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  185346. #endif
  185347. {
  185348. png_free(png_ptr, info_ptr->hist);
  185349. info_ptr->hist = NULL;
  185350. info_ptr->valid &= ~PNG_INFO_hIST;
  185351. #ifndef PNG_FREE_ME_SUPPORTED
  185352. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  185353. #endif
  185354. }
  185355. #endif
  185356. /* free any PLTE entry that was internally allocated */
  185357. #ifdef PNG_FREE_ME_SUPPORTED
  185358. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  185359. #else
  185360. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  185361. #endif
  185362. {
  185363. png_zfree(png_ptr, info_ptr->palette);
  185364. info_ptr->palette = NULL;
  185365. info_ptr->valid &= ~PNG_INFO_PLTE;
  185366. #ifndef PNG_FREE_ME_SUPPORTED
  185367. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  185368. #endif
  185369. info_ptr->num_palette = 0;
  185370. }
  185371. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185372. /* free any image bits attached to the info structure */
  185373. #ifdef PNG_FREE_ME_SUPPORTED
  185374. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  185375. #else
  185376. if (mask & PNG_FREE_ROWS)
  185377. #endif
  185378. {
  185379. if(info_ptr->row_pointers)
  185380. {
  185381. int row;
  185382. for (row = 0; row < (int)info_ptr->height; row++)
  185383. {
  185384. png_free(png_ptr, info_ptr->row_pointers[row]);
  185385. info_ptr->row_pointers[row]=NULL;
  185386. }
  185387. png_free(png_ptr, info_ptr->row_pointers);
  185388. info_ptr->row_pointers=NULL;
  185389. }
  185390. info_ptr->valid &= ~PNG_INFO_IDAT;
  185391. }
  185392. #endif
  185393. #ifdef PNG_FREE_ME_SUPPORTED
  185394. if(num == -1)
  185395. info_ptr->free_me &= ~mask;
  185396. else
  185397. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  185398. #endif
  185399. }
  185400. /* This is an internal routine to free any memory that the info struct is
  185401. * pointing to before re-using it or freeing the struct itself. Recall
  185402. * that png_free() checks for NULL pointers for us.
  185403. */
  185404. void /* PRIVATE */
  185405. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  185406. {
  185407. png_debug(1, "in png_info_destroy\n");
  185408. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  185409. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  185410. if (png_ptr->num_chunk_list)
  185411. {
  185412. png_free(png_ptr, png_ptr->chunk_list);
  185413. png_ptr->chunk_list=NULL;
  185414. png_ptr->num_chunk_list=0;
  185415. }
  185416. #endif
  185417. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185418. }
  185419. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185420. /* This function returns a pointer to the io_ptr associated with the user
  185421. * functions. The application should free any memory associated with this
  185422. * pointer before png_write_destroy() or png_read_destroy() are called.
  185423. */
  185424. png_voidp PNGAPI
  185425. png_get_io_ptr(png_structp png_ptr)
  185426. {
  185427. if(png_ptr == NULL) return (NULL);
  185428. return (png_ptr->io_ptr);
  185429. }
  185430. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185431. #if !defined(PNG_NO_STDIO)
  185432. /* Initialize the default input/output functions for the PNG file. If you
  185433. * use your own read or write routines, you can call either png_set_read_fn()
  185434. * or png_set_write_fn() instead of png_init_io(). If you have defined
  185435. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  185436. * necessarily available.
  185437. */
  185438. void PNGAPI
  185439. png_init_io(png_structp png_ptr, png_FILE_p fp)
  185440. {
  185441. png_debug(1, "in png_init_io\n");
  185442. if(png_ptr == NULL) return;
  185443. png_ptr->io_ptr = (png_voidp)fp;
  185444. }
  185445. #endif
  185446. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  185447. /* Convert the supplied time into an RFC 1123 string suitable for use in
  185448. * a "Creation Time" or other text-based time string.
  185449. */
  185450. png_charp PNGAPI
  185451. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  185452. {
  185453. static PNG_CONST char short_months[12][4] =
  185454. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  185455. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  185456. if(png_ptr == NULL) return (NULL);
  185457. if (png_ptr->time_buffer == NULL)
  185458. {
  185459. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  185460. png_sizeof(char)));
  185461. }
  185462. #if defined(_WIN32_WCE)
  185463. {
  185464. wchar_t time_buf[29];
  185465. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  185466. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185467. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185468. ptime->second % 61);
  185469. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  185470. NULL, NULL);
  185471. }
  185472. #else
  185473. #ifdef USE_FAR_KEYWORD
  185474. {
  185475. char near_time_buf[29];
  185476. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  185477. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185478. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185479. ptime->second % 61);
  185480. png_memcpy(png_ptr->time_buffer, near_time_buf,
  185481. 29*png_sizeof(char));
  185482. }
  185483. #else
  185484. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  185485. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  185486. ptime->year, ptime->hour % 24, ptime->minute % 60,
  185487. ptime->second % 61);
  185488. #endif
  185489. #endif /* _WIN32_WCE */
  185490. return ((png_charp)png_ptr->time_buffer);
  185491. }
  185492. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  185493. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185494. png_charp PNGAPI
  185495. png_get_copyright(png_structp png_ptr)
  185496. {
  185497. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185498. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  185499. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  185500. Copyright (c) 1996-1997 Andreas Dilger\n\
  185501. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  185502. }
  185503. /* The following return the library version as a short string in the
  185504. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  185505. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  185506. * is defined in png.h.
  185507. * Note: now there is no difference between png_get_libpng_ver() and
  185508. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  185509. * it is guaranteed that png.c uses the correct version of png.h.
  185510. */
  185511. png_charp PNGAPI
  185512. png_get_libpng_ver(png_structp png_ptr)
  185513. {
  185514. /* Version of *.c files used when building libpng */
  185515. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185516. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185517. }
  185518. png_charp PNGAPI
  185519. png_get_header_ver(png_structp png_ptr)
  185520. {
  185521. /* Version of *.h files used when building libpng */
  185522. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185523. return ((png_charp) PNG_LIBPNG_VER_STRING);
  185524. }
  185525. png_charp PNGAPI
  185526. png_get_header_version(png_structp png_ptr)
  185527. {
  185528. /* Returns longer string containing both version and date */
  185529. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  185530. return ((png_charp) PNG_HEADER_VERSION_STRING
  185531. #ifndef PNG_READ_SUPPORTED
  185532. " (NO READ SUPPORT)"
  185533. #endif
  185534. "\n");
  185535. }
  185536. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185537. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  185538. int PNGAPI
  185539. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  185540. {
  185541. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  185542. int i;
  185543. png_bytep p;
  185544. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  185545. return 0;
  185546. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  185547. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  185548. if (!png_memcmp(chunk_name, p, 4))
  185549. return ((int)*(p+4));
  185550. return 0;
  185551. }
  185552. #endif
  185553. /* This function, added to libpng-1.0.6g, is untested. */
  185554. int PNGAPI
  185555. png_reset_zstream(png_structp png_ptr)
  185556. {
  185557. if (png_ptr == NULL) return Z_STREAM_ERROR;
  185558. return (inflateReset(&png_ptr->zstream));
  185559. }
  185560. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185561. /* This function was added to libpng-1.0.7 */
  185562. png_uint_32 PNGAPI
  185563. png_access_version_number(void)
  185564. {
  185565. /* Version of *.c files used when building libpng */
  185566. return((png_uint_32) PNG_LIBPNG_VER);
  185567. }
  185568. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185569. #if !defined(PNG_1_0_X)
  185570. /* this function was added to libpng 1.2.0 */
  185571. int PNGAPI
  185572. png_mmx_support(void)
  185573. {
  185574. /* obsolete, to be removed from libpng-1.4.0 */
  185575. return -1;
  185576. }
  185577. #endif /* PNG_1_0_X */
  185578. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  185579. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185580. #ifdef PNG_SIZE_T
  185581. /* Added at libpng version 1.2.6 */
  185582. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185583. png_size_t PNGAPI
  185584. png_convert_size(size_t size)
  185585. {
  185586. if (size > (png_size_t)-1)
  185587. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  185588. return ((png_size_t)size);
  185589. }
  185590. #endif /* PNG_SIZE_T */
  185591. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  185592. /*** End of inlined file: png.c ***/
  185593. /*** Start of inlined file: pngerror.c ***/
  185594. /* pngerror.c - stub functions for i/o and memory allocation
  185595. *
  185596. * Last changed in libpng 1.2.20 October 4, 2007
  185597. * For conditions of distribution and use, see copyright notice in png.h
  185598. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185599. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185600. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185601. *
  185602. * This file provides a location for all error handling. Users who
  185603. * need special error handling are expected to write replacement functions
  185604. * and use png_set_error_fn() to use those functions. See the instructions
  185605. * at each function.
  185606. */
  185607. #define PNG_INTERNAL
  185608. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185609. static void /* PRIVATE */
  185610. png_default_error PNGARG((png_structp png_ptr,
  185611. png_const_charp error_message));
  185612. #ifndef PNG_NO_WARNINGS
  185613. static void /* PRIVATE */
  185614. png_default_warning PNGARG((png_structp png_ptr,
  185615. png_const_charp warning_message));
  185616. #endif /* PNG_NO_WARNINGS */
  185617. /* This function is called whenever there is a fatal error. This function
  185618. * should not be changed. If there is a need to handle errors differently,
  185619. * you should supply a replacement error function and use png_set_error_fn()
  185620. * to replace the error function at run-time.
  185621. */
  185622. #ifndef PNG_NO_ERROR_TEXT
  185623. void PNGAPI
  185624. png_error(png_structp png_ptr, png_const_charp error_message)
  185625. {
  185626. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185627. char msg[16];
  185628. if (png_ptr != NULL)
  185629. {
  185630. if (png_ptr->flags&
  185631. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185632. {
  185633. if (*error_message == '#')
  185634. {
  185635. int offset;
  185636. for (offset=1; offset<15; offset++)
  185637. if (*(error_message+offset) == ' ')
  185638. break;
  185639. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185640. {
  185641. int i;
  185642. for (i=0; i<offset-1; i++)
  185643. msg[i]=error_message[i+1];
  185644. msg[i]='\0';
  185645. error_message=msg;
  185646. }
  185647. else
  185648. error_message+=offset;
  185649. }
  185650. else
  185651. {
  185652. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  185653. {
  185654. msg[0]='0';
  185655. msg[1]='\0';
  185656. error_message=msg;
  185657. }
  185658. }
  185659. }
  185660. }
  185661. #endif
  185662. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185663. (*(png_ptr->error_fn))(png_ptr, error_message);
  185664. /* If the custom handler doesn't exist, or if it returns,
  185665. use the default handler, which will not return. */
  185666. png_default_error(png_ptr, error_message);
  185667. }
  185668. #else
  185669. void PNGAPI
  185670. png_err(png_structp png_ptr)
  185671. {
  185672. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  185673. (*(png_ptr->error_fn))(png_ptr, '\0');
  185674. /* If the custom handler doesn't exist, or if it returns,
  185675. use the default handler, which will not return. */
  185676. png_default_error(png_ptr, '\0');
  185677. }
  185678. #endif /* PNG_NO_ERROR_TEXT */
  185679. #ifndef PNG_NO_WARNINGS
  185680. /* This function is called whenever there is a non-fatal error. This function
  185681. * should not be changed. If there is a need to handle warnings differently,
  185682. * you should supply a replacement warning function and use
  185683. * png_set_error_fn() to replace the warning function at run-time.
  185684. */
  185685. void PNGAPI
  185686. png_warning(png_structp png_ptr, png_const_charp warning_message)
  185687. {
  185688. int offset = 0;
  185689. if (png_ptr != NULL)
  185690. {
  185691. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185692. if (png_ptr->flags&
  185693. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  185694. #endif
  185695. {
  185696. if (*warning_message == '#')
  185697. {
  185698. for (offset=1; offset<15; offset++)
  185699. if (*(warning_message+offset) == ' ')
  185700. break;
  185701. }
  185702. }
  185703. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  185704. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  185705. }
  185706. else
  185707. png_default_warning(png_ptr, warning_message+offset);
  185708. }
  185709. #endif /* PNG_NO_WARNINGS */
  185710. /* These utilities are used internally to build an error message that relates
  185711. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  185712. * this is used to prefix the message. The message is limited in length
  185713. * to 63 bytes, the name characters are output as hex digits wrapped in []
  185714. * if the character is invalid.
  185715. */
  185716. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  185717. /*static PNG_CONST char png_digit[16] = {
  185718. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  185719. 'A', 'B', 'C', 'D', 'E', 'F'
  185720. };*/
  185721. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  185722. static void /* PRIVATE */
  185723. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  185724. error_message)
  185725. {
  185726. int iout = 0, iin = 0;
  185727. while (iin < 4)
  185728. {
  185729. int c = png_ptr->chunk_name[iin++];
  185730. if (isnonalpha(c))
  185731. {
  185732. buffer[iout++] = '[';
  185733. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  185734. buffer[iout++] = png_digit[c & 0x0f];
  185735. buffer[iout++] = ']';
  185736. }
  185737. else
  185738. {
  185739. buffer[iout++] = (png_byte)c;
  185740. }
  185741. }
  185742. if (error_message == NULL)
  185743. buffer[iout] = 0;
  185744. else
  185745. {
  185746. buffer[iout++] = ':';
  185747. buffer[iout++] = ' ';
  185748. png_strncpy(buffer+iout, error_message, 63);
  185749. buffer[iout+63] = 0;
  185750. }
  185751. }
  185752. #ifdef PNG_READ_SUPPORTED
  185753. void PNGAPI
  185754. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  185755. {
  185756. char msg[18+64];
  185757. if (png_ptr == NULL)
  185758. png_error(png_ptr, error_message);
  185759. else
  185760. {
  185761. png_format_buffer(png_ptr, msg, error_message);
  185762. png_error(png_ptr, msg);
  185763. }
  185764. }
  185765. #endif /* PNG_READ_SUPPORTED */
  185766. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  185767. #ifndef PNG_NO_WARNINGS
  185768. void PNGAPI
  185769. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  185770. {
  185771. char msg[18+64];
  185772. if (png_ptr == NULL)
  185773. png_warning(png_ptr, warning_message);
  185774. else
  185775. {
  185776. png_format_buffer(png_ptr, msg, warning_message);
  185777. png_warning(png_ptr, msg);
  185778. }
  185779. }
  185780. #endif /* PNG_NO_WARNINGS */
  185781. /* This is the default error handling function. Note that replacements for
  185782. * this function MUST NOT RETURN, or the program will likely crash. This
  185783. * function is used by default, or if the program supplies NULL for the
  185784. * error function pointer in png_set_error_fn().
  185785. */
  185786. static void /* PRIVATE */
  185787. png_default_error(png_structp, png_const_charp error_message)
  185788. {
  185789. #ifndef PNG_NO_CONSOLE_IO
  185790. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185791. if (*error_message == '#')
  185792. {
  185793. int offset;
  185794. char error_number[16];
  185795. for (offset=0; offset<15; offset++)
  185796. {
  185797. error_number[offset] = *(error_message+offset+1);
  185798. if (*(error_message+offset) == ' ')
  185799. break;
  185800. }
  185801. if((offset > 1) && (offset < 15))
  185802. {
  185803. error_number[offset-1]='\0';
  185804. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  185805. error_message+offset);
  185806. }
  185807. else
  185808. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  185809. }
  185810. else
  185811. #endif
  185812. fprintf(stderr, "libpng error: %s\n", error_message);
  185813. #endif
  185814. #ifdef PNG_SETJMP_SUPPORTED
  185815. if (png_ptr)
  185816. {
  185817. # ifdef USE_FAR_KEYWORD
  185818. {
  185819. jmp_buf jmpbuf;
  185820. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  185821. longjmp(jmpbuf, 1);
  185822. }
  185823. # else
  185824. longjmp(png_ptr->jmpbuf, 1);
  185825. # endif
  185826. }
  185827. #else
  185828. PNG_ABORT();
  185829. #endif
  185830. #ifdef PNG_NO_CONSOLE_IO
  185831. error_message = error_message; /* make compiler happy */
  185832. #endif
  185833. }
  185834. #ifndef PNG_NO_WARNINGS
  185835. /* This function is called when there is a warning, but the library thinks
  185836. * it can continue anyway. Replacement functions don't have to do anything
  185837. * here if you don't want them to. In the default configuration, png_ptr is
  185838. * not used, but it is passed in case it may be useful.
  185839. */
  185840. static void /* PRIVATE */
  185841. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  185842. {
  185843. #ifndef PNG_NO_CONSOLE_IO
  185844. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185845. if (*warning_message == '#')
  185846. {
  185847. int offset;
  185848. char warning_number[16];
  185849. for (offset=0; offset<15; offset++)
  185850. {
  185851. warning_number[offset]=*(warning_message+offset+1);
  185852. if (*(warning_message+offset) == ' ')
  185853. break;
  185854. }
  185855. if((offset > 1) && (offset < 15))
  185856. {
  185857. warning_number[offset-1]='\0';
  185858. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  185859. warning_message+offset);
  185860. }
  185861. else
  185862. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185863. }
  185864. else
  185865. # endif
  185866. fprintf(stderr, "libpng warning: %s\n", warning_message);
  185867. #else
  185868. warning_message = warning_message; /* make compiler happy */
  185869. #endif
  185870. png_ptr = png_ptr; /* make compiler happy */
  185871. }
  185872. #endif /* PNG_NO_WARNINGS */
  185873. /* This function is called when the application wants to use another method
  185874. * of handling errors and warnings. Note that the error function MUST NOT
  185875. * return to the calling routine or serious problems will occur. The return
  185876. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  185877. */
  185878. void PNGAPI
  185879. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  185880. png_error_ptr error_fn, png_error_ptr warning_fn)
  185881. {
  185882. if (png_ptr == NULL)
  185883. return;
  185884. png_ptr->error_ptr = error_ptr;
  185885. png_ptr->error_fn = error_fn;
  185886. png_ptr->warning_fn = warning_fn;
  185887. }
  185888. /* This function returns a pointer to the error_ptr associated with the user
  185889. * functions. The application should free any memory associated with this
  185890. * pointer before png_write_destroy and png_read_destroy are called.
  185891. */
  185892. png_voidp PNGAPI
  185893. png_get_error_ptr(png_structp png_ptr)
  185894. {
  185895. if (png_ptr == NULL)
  185896. return NULL;
  185897. return ((png_voidp)png_ptr->error_ptr);
  185898. }
  185899. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  185900. void PNGAPI
  185901. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  185902. {
  185903. if(png_ptr != NULL)
  185904. {
  185905. png_ptr->flags &=
  185906. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  185907. }
  185908. }
  185909. #endif
  185910. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  185911. /*** End of inlined file: pngerror.c ***/
  185912. /*** Start of inlined file: pngget.c ***/
  185913. /* pngget.c - retrieval of values from info struct
  185914. *
  185915. * Last changed in libpng 1.2.15 January 5, 2007
  185916. * For conditions of distribution and use, see copyright notice in png.h
  185917. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185918. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185919. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185920. */
  185921. #define PNG_INTERNAL
  185922. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185923. png_uint_32 PNGAPI
  185924. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  185925. {
  185926. if (png_ptr != NULL && info_ptr != NULL)
  185927. return(info_ptr->valid & flag);
  185928. else
  185929. return(0);
  185930. }
  185931. png_uint_32 PNGAPI
  185932. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  185933. {
  185934. if (png_ptr != NULL && info_ptr != NULL)
  185935. return(info_ptr->rowbytes);
  185936. else
  185937. return(0);
  185938. }
  185939. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  185940. png_bytepp PNGAPI
  185941. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  185942. {
  185943. if (png_ptr != NULL && info_ptr != NULL)
  185944. return(info_ptr->row_pointers);
  185945. else
  185946. return(0);
  185947. }
  185948. #endif
  185949. #ifdef PNG_EASY_ACCESS_SUPPORTED
  185950. /* easy access to info, added in libpng-0.99 */
  185951. png_uint_32 PNGAPI
  185952. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  185953. {
  185954. if (png_ptr != NULL && info_ptr != NULL)
  185955. {
  185956. return info_ptr->width;
  185957. }
  185958. return (0);
  185959. }
  185960. png_uint_32 PNGAPI
  185961. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  185962. {
  185963. if (png_ptr != NULL && info_ptr != NULL)
  185964. {
  185965. return info_ptr->height;
  185966. }
  185967. return (0);
  185968. }
  185969. png_byte PNGAPI
  185970. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  185971. {
  185972. if (png_ptr != NULL && info_ptr != NULL)
  185973. {
  185974. return info_ptr->bit_depth;
  185975. }
  185976. return (0);
  185977. }
  185978. png_byte PNGAPI
  185979. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  185980. {
  185981. if (png_ptr != NULL && info_ptr != NULL)
  185982. {
  185983. return info_ptr->color_type;
  185984. }
  185985. return (0);
  185986. }
  185987. png_byte PNGAPI
  185988. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  185989. {
  185990. if (png_ptr != NULL && info_ptr != NULL)
  185991. {
  185992. return info_ptr->filter_type;
  185993. }
  185994. return (0);
  185995. }
  185996. png_byte PNGAPI
  185997. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  185998. {
  185999. if (png_ptr != NULL && info_ptr != NULL)
  186000. {
  186001. return info_ptr->interlace_type;
  186002. }
  186003. return (0);
  186004. }
  186005. png_byte PNGAPI
  186006. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  186007. {
  186008. if (png_ptr != NULL && info_ptr != NULL)
  186009. {
  186010. return info_ptr->compression_type;
  186011. }
  186012. return (0);
  186013. }
  186014. png_uint_32 PNGAPI
  186015. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186016. {
  186017. if (png_ptr != NULL && info_ptr != NULL)
  186018. #if defined(PNG_pHYs_SUPPORTED)
  186019. if (info_ptr->valid & PNG_INFO_pHYs)
  186020. {
  186021. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  186022. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186023. return (0);
  186024. else return (info_ptr->x_pixels_per_unit);
  186025. }
  186026. #else
  186027. return (0);
  186028. #endif
  186029. return (0);
  186030. }
  186031. png_uint_32 PNGAPI
  186032. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186033. {
  186034. if (png_ptr != NULL && info_ptr != NULL)
  186035. #if defined(PNG_pHYs_SUPPORTED)
  186036. if (info_ptr->valid & PNG_INFO_pHYs)
  186037. {
  186038. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186039. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186040. return (0);
  186041. else return (info_ptr->y_pixels_per_unit);
  186042. }
  186043. #else
  186044. return (0);
  186045. #endif
  186046. return (0);
  186047. }
  186048. png_uint_32 PNGAPI
  186049. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186050. {
  186051. if (png_ptr != NULL && info_ptr != NULL)
  186052. #if defined(PNG_pHYs_SUPPORTED)
  186053. if (info_ptr->valid & PNG_INFO_pHYs)
  186054. {
  186055. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186056. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186057. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186058. return (0);
  186059. else return (info_ptr->x_pixels_per_unit);
  186060. }
  186061. #else
  186062. return (0);
  186063. #endif
  186064. return (0);
  186065. }
  186066. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186067. float PNGAPI
  186068. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186069. {
  186070. if (png_ptr != NULL && info_ptr != NULL)
  186071. #if defined(PNG_pHYs_SUPPORTED)
  186072. if (info_ptr->valid & PNG_INFO_pHYs)
  186073. {
  186074. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186075. if (info_ptr->x_pixels_per_unit == 0)
  186076. return ((float)0.0);
  186077. else
  186078. return ((float)((float)info_ptr->y_pixels_per_unit
  186079. /(float)info_ptr->x_pixels_per_unit));
  186080. }
  186081. #else
  186082. return (0.0);
  186083. #endif
  186084. return ((float)0.0);
  186085. }
  186086. #endif
  186087. png_int_32 PNGAPI
  186088. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186089. {
  186090. if (png_ptr != NULL && info_ptr != NULL)
  186091. #if defined(PNG_oFFs_SUPPORTED)
  186092. if (info_ptr->valid & PNG_INFO_oFFs)
  186093. {
  186094. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186095. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186096. return (0);
  186097. else return (info_ptr->x_offset);
  186098. }
  186099. #else
  186100. return (0);
  186101. #endif
  186102. return (0);
  186103. }
  186104. png_int_32 PNGAPI
  186105. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186106. {
  186107. if (png_ptr != NULL && info_ptr != NULL)
  186108. #if defined(PNG_oFFs_SUPPORTED)
  186109. if (info_ptr->valid & PNG_INFO_oFFs)
  186110. {
  186111. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186112. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186113. return (0);
  186114. else return (info_ptr->y_offset);
  186115. }
  186116. #else
  186117. return (0);
  186118. #endif
  186119. return (0);
  186120. }
  186121. png_int_32 PNGAPI
  186122. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186123. {
  186124. if (png_ptr != NULL && info_ptr != NULL)
  186125. #if defined(PNG_oFFs_SUPPORTED)
  186126. if (info_ptr->valid & PNG_INFO_oFFs)
  186127. {
  186128. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186129. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186130. return (0);
  186131. else return (info_ptr->x_offset);
  186132. }
  186133. #else
  186134. return (0);
  186135. #endif
  186136. return (0);
  186137. }
  186138. png_int_32 PNGAPI
  186139. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186140. {
  186141. if (png_ptr != NULL && info_ptr != NULL)
  186142. #if defined(PNG_oFFs_SUPPORTED)
  186143. if (info_ptr->valid & PNG_INFO_oFFs)
  186144. {
  186145. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186146. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186147. return (0);
  186148. else return (info_ptr->y_offset);
  186149. }
  186150. #else
  186151. return (0);
  186152. #endif
  186153. return (0);
  186154. }
  186155. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186156. png_uint_32 PNGAPI
  186157. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186158. {
  186159. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186160. *.0254 +.5));
  186161. }
  186162. png_uint_32 PNGAPI
  186163. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186164. {
  186165. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186166. *.0254 +.5));
  186167. }
  186168. png_uint_32 PNGAPI
  186169. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186170. {
  186171. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186172. *.0254 +.5));
  186173. }
  186174. float PNGAPI
  186175. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186176. {
  186177. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186178. *.00003937);
  186179. }
  186180. float PNGAPI
  186181. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186182. {
  186183. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186184. *.00003937);
  186185. }
  186186. #if defined(PNG_pHYs_SUPPORTED)
  186187. png_uint_32 PNGAPI
  186188. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186189. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186190. {
  186191. png_uint_32 retval = 0;
  186192. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186193. {
  186194. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186195. if (res_x != NULL)
  186196. {
  186197. *res_x = info_ptr->x_pixels_per_unit;
  186198. retval |= PNG_INFO_pHYs;
  186199. }
  186200. if (res_y != NULL)
  186201. {
  186202. *res_y = info_ptr->y_pixels_per_unit;
  186203. retval |= PNG_INFO_pHYs;
  186204. }
  186205. if (unit_type != NULL)
  186206. {
  186207. *unit_type = (int)info_ptr->phys_unit_type;
  186208. retval |= PNG_INFO_pHYs;
  186209. if(*unit_type == 1)
  186210. {
  186211. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186212. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186213. }
  186214. }
  186215. }
  186216. return (retval);
  186217. }
  186218. #endif /* PNG_pHYs_SUPPORTED */
  186219. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186220. /* png_get_channels really belongs in here, too, but it's been around longer */
  186221. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186222. png_byte PNGAPI
  186223. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186224. {
  186225. if (png_ptr != NULL && info_ptr != NULL)
  186226. return(info_ptr->channels);
  186227. else
  186228. return (0);
  186229. }
  186230. png_bytep PNGAPI
  186231. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186232. {
  186233. if (png_ptr != NULL && info_ptr != NULL)
  186234. return(info_ptr->signature);
  186235. else
  186236. return (NULL);
  186237. }
  186238. #if defined(PNG_bKGD_SUPPORTED)
  186239. png_uint_32 PNGAPI
  186240. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186241. png_color_16p *background)
  186242. {
  186243. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186244. && background != NULL)
  186245. {
  186246. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186247. *background = &(info_ptr->background);
  186248. return (PNG_INFO_bKGD);
  186249. }
  186250. return (0);
  186251. }
  186252. #endif
  186253. #if defined(PNG_cHRM_SUPPORTED)
  186254. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186255. png_uint_32 PNGAPI
  186256. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186257. double *white_x, double *white_y, double *red_x, double *red_y,
  186258. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186259. {
  186260. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186261. {
  186262. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186263. if (white_x != NULL)
  186264. *white_x = (double)info_ptr->x_white;
  186265. if (white_y != NULL)
  186266. *white_y = (double)info_ptr->y_white;
  186267. if (red_x != NULL)
  186268. *red_x = (double)info_ptr->x_red;
  186269. if (red_y != NULL)
  186270. *red_y = (double)info_ptr->y_red;
  186271. if (green_x != NULL)
  186272. *green_x = (double)info_ptr->x_green;
  186273. if (green_y != NULL)
  186274. *green_y = (double)info_ptr->y_green;
  186275. if (blue_x != NULL)
  186276. *blue_x = (double)info_ptr->x_blue;
  186277. if (blue_y != NULL)
  186278. *blue_y = (double)info_ptr->y_blue;
  186279. return (PNG_INFO_cHRM);
  186280. }
  186281. return (0);
  186282. }
  186283. #endif
  186284. #ifdef PNG_FIXED_POINT_SUPPORTED
  186285. png_uint_32 PNGAPI
  186286. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  186287. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  186288. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  186289. png_fixed_point *blue_x, png_fixed_point *blue_y)
  186290. {
  186291. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186292. {
  186293. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186294. if (white_x != NULL)
  186295. *white_x = info_ptr->int_x_white;
  186296. if (white_y != NULL)
  186297. *white_y = info_ptr->int_y_white;
  186298. if (red_x != NULL)
  186299. *red_x = info_ptr->int_x_red;
  186300. if (red_y != NULL)
  186301. *red_y = info_ptr->int_y_red;
  186302. if (green_x != NULL)
  186303. *green_x = info_ptr->int_x_green;
  186304. if (green_y != NULL)
  186305. *green_y = info_ptr->int_y_green;
  186306. if (blue_x != NULL)
  186307. *blue_x = info_ptr->int_x_blue;
  186308. if (blue_y != NULL)
  186309. *blue_y = info_ptr->int_y_blue;
  186310. return (PNG_INFO_cHRM);
  186311. }
  186312. return (0);
  186313. }
  186314. #endif
  186315. #endif
  186316. #if defined(PNG_gAMA_SUPPORTED)
  186317. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186318. png_uint_32 PNGAPI
  186319. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  186320. {
  186321. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186322. && file_gamma != NULL)
  186323. {
  186324. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186325. *file_gamma = (double)info_ptr->gamma;
  186326. return (PNG_INFO_gAMA);
  186327. }
  186328. return (0);
  186329. }
  186330. #endif
  186331. #ifdef PNG_FIXED_POINT_SUPPORTED
  186332. png_uint_32 PNGAPI
  186333. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  186334. png_fixed_point *int_file_gamma)
  186335. {
  186336. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  186337. && int_file_gamma != NULL)
  186338. {
  186339. png_debug1(1, "in %s retrieval function\n", "gAMA");
  186340. *int_file_gamma = info_ptr->int_gamma;
  186341. return (PNG_INFO_gAMA);
  186342. }
  186343. return (0);
  186344. }
  186345. #endif
  186346. #endif
  186347. #if defined(PNG_sRGB_SUPPORTED)
  186348. png_uint_32 PNGAPI
  186349. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  186350. {
  186351. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  186352. && file_srgb_intent != NULL)
  186353. {
  186354. png_debug1(1, "in %s retrieval function\n", "sRGB");
  186355. *file_srgb_intent = (int)info_ptr->srgb_intent;
  186356. return (PNG_INFO_sRGB);
  186357. }
  186358. return (0);
  186359. }
  186360. #endif
  186361. #if defined(PNG_iCCP_SUPPORTED)
  186362. png_uint_32 PNGAPI
  186363. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  186364. png_charpp name, int *compression_type,
  186365. png_charpp profile, png_uint_32 *proflen)
  186366. {
  186367. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  186368. && name != NULL && profile != NULL && proflen != NULL)
  186369. {
  186370. png_debug1(1, "in %s retrieval function\n", "iCCP");
  186371. *name = info_ptr->iccp_name;
  186372. *profile = info_ptr->iccp_profile;
  186373. /* compression_type is a dummy so the API won't have to change
  186374. if we introduce multiple compression types later. */
  186375. *proflen = (int)info_ptr->iccp_proflen;
  186376. *compression_type = (int)info_ptr->iccp_compression;
  186377. return (PNG_INFO_iCCP);
  186378. }
  186379. return (0);
  186380. }
  186381. #endif
  186382. #if defined(PNG_sPLT_SUPPORTED)
  186383. png_uint_32 PNGAPI
  186384. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  186385. png_sPLT_tpp spalettes)
  186386. {
  186387. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  186388. {
  186389. *spalettes = info_ptr->splt_palettes;
  186390. return ((png_uint_32)info_ptr->splt_palettes_num);
  186391. }
  186392. return (0);
  186393. }
  186394. #endif
  186395. #if defined(PNG_hIST_SUPPORTED)
  186396. png_uint_32 PNGAPI
  186397. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  186398. {
  186399. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  186400. && hist != NULL)
  186401. {
  186402. png_debug1(1, "in %s retrieval function\n", "hIST");
  186403. *hist = info_ptr->hist;
  186404. return (PNG_INFO_hIST);
  186405. }
  186406. return (0);
  186407. }
  186408. #endif
  186409. png_uint_32 PNGAPI
  186410. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  186411. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  186412. int *color_type, int *interlace_type, int *compression_type,
  186413. int *filter_type)
  186414. {
  186415. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  186416. bit_depth != NULL && color_type != NULL)
  186417. {
  186418. png_debug1(1, "in %s retrieval function\n", "IHDR");
  186419. *width = info_ptr->width;
  186420. *height = info_ptr->height;
  186421. *bit_depth = info_ptr->bit_depth;
  186422. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  186423. png_error(png_ptr, "Invalid bit depth");
  186424. *color_type = info_ptr->color_type;
  186425. if (info_ptr->color_type > 6)
  186426. png_error(png_ptr, "Invalid color type");
  186427. if (compression_type != NULL)
  186428. *compression_type = info_ptr->compression_type;
  186429. if (filter_type != NULL)
  186430. *filter_type = info_ptr->filter_type;
  186431. if (interlace_type != NULL)
  186432. *interlace_type = info_ptr->interlace_type;
  186433. /* check for potential overflow of rowbytes */
  186434. if (*width == 0 || *width > PNG_UINT_31_MAX)
  186435. png_error(png_ptr, "Invalid image width");
  186436. if (*height == 0 || *height > PNG_UINT_31_MAX)
  186437. png_error(png_ptr, "Invalid image height");
  186438. if (info_ptr->width > (PNG_UINT_32_MAX
  186439. >> 3) /* 8-byte RGBA pixels */
  186440. - 64 /* bigrowbuf hack */
  186441. - 1 /* filter byte */
  186442. - 7*8 /* rounding of width to multiple of 8 pixels */
  186443. - 8) /* extra max_pixel_depth pad */
  186444. {
  186445. png_warning(png_ptr,
  186446. "Width too large for libpng to process image data.");
  186447. }
  186448. return (1);
  186449. }
  186450. return (0);
  186451. }
  186452. #if defined(PNG_oFFs_SUPPORTED)
  186453. png_uint_32 PNGAPI
  186454. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  186455. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  186456. {
  186457. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  186458. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  186459. {
  186460. png_debug1(1, "in %s retrieval function\n", "oFFs");
  186461. *offset_x = info_ptr->x_offset;
  186462. *offset_y = info_ptr->y_offset;
  186463. *unit_type = (int)info_ptr->offset_unit_type;
  186464. return (PNG_INFO_oFFs);
  186465. }
  186466. return (0);
  186467. }
  186468. #endif
  186469. #if defined(PNG_pCAL_SUPPORTED)
  186470. png_uint_32 PNGAPI
  186471. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  186472. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  186473. png_charp *units, png_charpp *params)
  186474. {
  186475. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  186476. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  186477. nparams != NULL && units != NULL && params != NULL)
  186478. {
  186479. png_debug1(1, "in %s retrieval function\n", "pCAL");
  186480. *purpose = info_ptr->pcal_purpose;
  186481. *X0 = info_ptr->pcal_X0;
  186482. *X1 = info_ptr->pcal_X1;
  186483. *type = (int)info_ptr->pcal_type;
  186484. *nparams = (int)info_ptr->pcal_nparams;
  186485. *units = info_ptr->pcal_units;
  186486. *params = info_ptr->pcal_params;
  186487. return (PNG_INFO_pCAL);
  186488. }
  186489. return (0);
  186490. }
  186491. #endif
  186492. #if defined(PNG_sCAL_SUPPORTED)
  186493. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186494. png_uint_32 PNGAPI
  186495. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  186496. int *unit, double *width, double *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_pixel_width;
  186503. *height = info_ptr->scal_pixel_height;
  186504. return (PNG_INFO_sCAL);
  186505. }
  186506. return(0);
  186507. }
  186508. #else
  186509. #ifdef PNG_FIXED_POINT_SUPPORTED
  186510. png_uint_32 PNGAPI
  186511. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  186512. int *unit, png_charpp width, png_charpp height)
  186513. {
  186514. if (png_ptr != NULL && info_ptr != NULL &&
  186515. (info_ptr->valid & PNG_INFO_sCAL))
  186516. {
  186517. *unit = info_ptr->scal_unit;
  186518. *width = info_ptr->scal_s_width;
  186519. *height = info_ptr->scal_s_height;
  186520. return (PNG_INFO_sCAL);
  186521. }
  186522. return(0);
  186523. }
  186524. #endif
  186525. #endif
  186526. #endif
  186527. #if defined(PNG_pHYs_SUPPORTED)
  186528. png_uint_32 PNGAPI
  186529. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  186530. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186531. {
  186532. png_uint_32 retval = 0;
  186533. if (png_ptr != NULL && info_ptr != NULL &&
  186534. (info_ptr->valid & PNG_INFO_pHYs))
  186535. {
  186536. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186537. if (res_x != NULL)
  186538. {
  186539. *res_x = info_ptr->x_pixels_per_unit;
  186540. retval |= PNG_INFO_pHYs;
  186541. }
  186542. if (res_y != NULL)
  186543. {
  186544. *res_y = info_ptr->y_pixels_per_unit;
  186545. retval |= PNG_INFO_pHYs;
  186546. }
  186547. if (unit_type != NULL)
  186548. {
  186549. *unit_type = (int)info_ptr->phys_unit_type;
  186550. retval |= PNG_INFO_pHYs;
  186551. }
  186552. }
  186553. return (retval);
  186554. }
  186555. #endif
  186556. png_uint_32 PNGAPI
  186557. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  186558. int *num_palette)
  186559. {
  186560. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  186561. && palette != NULL)
  186562. {
  186563. png_debug1(1, "in %s retrieval function\n", "PLTE");
  186564. *palette = info_ptr->palette;
  186565. *num_palette = info_ptr->num_palette;
  186566. png_debug1(3, "num_palette = %d\n", *num_palette);
  186567. return (PNG_INFO_PLTE);
  186568. }
  186569. return (0);
  186570. }
  186571. #if defined(PNG_sBIT_SUPPORTED)
  186572. png_uint_32 PNGAPI
  186573. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  186574. {
  186575. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  186576. && sig_bit != NULL)
  186577. {
  186578. png_debug1(1, "in %s retrieval function\n", "sBIT");
  186579. *sig_bit = &(info_ptr->sig_bit);
  186580. return (PNG_INFO_sBIT);
  186581. }
  186582. return (0);
  186583. }
  186584. #endif
  186585. #if defined(PNG_TEXT_SUPPORTED)
  186586. png_uint_32 PNGAPI
  186587. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  186588. int *num_text)
  186589. {
  186590. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  186591. {
  186592. png_debug1(1, "in %s retrieval function\n",
  186593. (png_ptr->chunk_name[0] == '\0' ? "text"
  186594. : (png_const_charp)png_ptr->chunk_name));
  186595. if (text_ptr != NULL)
  186596. *text_ptr = info_ptr->text;
  186597. if (num_text != NULL)
  186598. *num_text = info_ptr->num_text;
  186599. return ((png_uint_32)info_ptr->num_text);
  186600. }
  186601. if (num_text != NULL)
  186602. *num_text = 0;
  186603. return(0);
  186604. }
  186605. #endif
  186606. #if defined(PNG_tIME_SUPPORTED)
  186607. png_uint_32 PNGAPI
  186608. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  186609. {
  186610. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  186611. && mod_time != NULL)
  186612. {
  186613. png_debug1(1, "in %s retrieval function\n", "tIME");
  186614. *mod_time = &(info_ptr->mod_time);
  186615. return (PNG_INFO_tIME);
  186616. }
  186617. return (0);
  186618. }
  186619. #endif
  186620. #if defined(PNG_tRNS_SUPPORTED)
  186621. png_uint_32 PNGAPI
  186622. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  186623. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  186624. {
  186625. png_uint_32 retval = 0;
  186626. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  186627. {
  186628. png_debug1(1, "in %s retrieval function\n", "tRNS");
  186629. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  186630. {
  186631. if (trans != NULL)
  186632. {
  186633. *trans = info_ptr->trans;
  186634. retval |= PNG_INFO_tRNS;
  186635. }
  186636. if (trans_values != NULL)
  186637. *trans_values = &(info_ptr->trans_values);
  186638. }
  186639. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  186640. {
  186641. if (trans_values != NULL)
  186642. {
  186643. *trans_values = &(info_ptr->trans_values);
  186644. retval |= PNG_INFO_tRNS;
  186645. }
  186646. if(trans != NULL)
  186647. *trans = NULL;
  186648. }
  186649. if(num_trans != NULL)
  186650. {
  186651. *num_trans = info_ptr->num_trans;
  186652. retval |= PNG_INFO_tRNS;
  186653. }
  186654. }
  186655. return (retval);
  186656. }
  186657. #endif
  186658. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186659. png_uint_32 PNGAPI
  186660. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  186661. png_unknown_chunkpp unknowns)
  186662. {
  186663. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  186664. {
  186665. *unknowns = info_ptr->unknown_chunks;
  186666. return ((png_uint_32)info_ptr->unknown_chunks_num);
  186667. }
  186668. return (0);
  186669. }
  186670. #endif
  186671. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  186672. png_byte PNGAPI
  186673. png_get_rgb_to_gray_status (png_structp png_ptr)
  186674. {
  186675. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  186676. }
  186677. #endif
  186678. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  186679. png_voidp PNGAPI
  186680. png_get_user_chunk_ptr(png_structp png_ptr)
  186681. {
  186682. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  186683. }
  186684. #endif
  186685. #ifdef PNG_WRITE_SUPPORTED
  186686. png_uint_32 PNGAPI
  186687. png_get_compression_buffer_size(png_structp png_ptr)
  186688. {
  186689. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  186690. }
  186691. #endif
  186692. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  186693. #ifndef PNG_1_0_X
  186694. /* this function was added to libpng 1.2.0 and should exist by default */
  186695. png_uint_32 PNGAPI
  186696. png_get_asm_flags (png_structp png_ptr)
  186697. {
  186698. /* obsolete, to be removed from libpng-1.4.0 */
  186699. return (png_ptr? 0L: 0L);
  186700. }
  186701. /* this function was added to libpng 1.2.0 and should exist by default */
  186702. png_uint_32 PNGAPI
  186703. png_get_asm_flagmask (int flag_select)
  186704. {
  186705. /* obsolete, to be removed from libpng-1.4.0 */
  186706. flag_select=flag_select;
  186707. return 0L;
  186708. }
  186709. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  186710. /* this function was added to libpng 1.2.0 */
  186711. png_uint_32 PNGAPI
  186712. png_get_mmx_flagmask (int flag_select, int *compilerID)
  186713. {
  186714. /* obsolete, to be removed from libpng-1.4.0 */
  186715. flag_select=flag_select;
  186716. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  186717. return 0L;
  186718. }
  186719. /* this function was added to libpng 1.2.0 */
  186720. png_byte PNGAPI
  186721. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  186722. {
  186723. /* obsolete, to be removed from libpng-1.4.0 */
  186724. return (png_ptr? 0: 0);
  186725. }
  186726. /* this function was added to libpng 1.2.0 */
  186727. png_uint_32 PNGAPI
  186728. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  186729. {
  186730. /* obsolete, to be removed from libpng-1.4.0 */
  186731. return (png_ptr? 0L: 0L);
  186732. }
  186733. #endif /* ?PNG_1_0_X */
  186734. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  186735. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  186736. /* these functions were added to libpng 1.2.6 */
  186737. png_uint_32 PNGAPI
  186738. png_get_user_width_max (png_structp png_ptr)
  186739. {
  186740. return (png_ptr? png_ptr->user_width_max : 0);
  186741. }
  186742. png_uint_32 PNGAPI
  186743. png_get_user_height_max (png_structp png_ptr)
  186744. {
  186745. return (png_ptr? png_ptr->user_height_max : 0);
  186746. }
  186747. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  186748. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186749. /*** End of inlined file: pngget.c ***/
  186750. /*** Start of inlined file: pngmem.c ***/
  186751. /* pngmem.c - stub functions for memory allocation
  186752. *
  186753. * Last changed in libpng 1.2.13 November 13, 2006
  186754. * For conditions of distribution and use, see copyright notice in png.h
  186755. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  186756. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186757. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186758. *
  186759. * This file provides a location for all memory allocation. Users who
  186760. * need special memory handling are expected to supply replacement
  186761. * functions for png_malloc() and png_free(), and to use
  186762. * png_create_read_struct_2() and png_create_write_struct_2() to
  186763. * identify the replacement functions.
  186764. */
  186765. #define PNG_INTERNAL
  186766. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186767. /* Borland DOS special memory handler */
  186768. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  186769. /* if you change this, be sure to change the one in png.h also */
  186770. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  186771. by a single call to calloc() if this is thought to improve performance. */
  186772. png_voidp /* PRIVATE */
  186773. png_create_struct(int type)
  186774. {
  186775. #ifdef PNG_USER_MEM_SUPPORTED
  186776. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  186777. }
  186778. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  186779. png_voidp /* PRIVATE */
  186780. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  186781. {
  186782. #endif /* PNG_USER_MEM_SUPPORTED */
  186783. png_size_t size;
  186784. png_voidp struct_ptr;
  186785. if (type == PNG_STRUCT_INFO)
  186786. size = png_sizeof(png_info);
  186787. else if (type == PNG_STRUCT_PNG)
  186788. size = png_sizeof(png_struct);
  186789. else
  186790. return (png_get_copyright(NULL));
  186791. #ifdef PNG_USER_MEM_SUPPORTED
  186792. if(malloc_fn != NULL)
  186793. {
  186794. png_struct dummy_struct;
  186795. png_structp png_ptr = &dummy_struct;
  186796. png_ptr->mem_ptr=mem_ptr;
  186797. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  186798. }
  186799. else
  186800. #endif /* PNG_USER_MEM_SUPPORTED */
  186801. struct_ptr = (png_voidp)farmalloc(size);
  186802. if (struct_ptr != NULL)
  186803. png_memset(struct_ptr, 0, size);
  186804. return (struct_ptr);
  186805. }
  186806. /* Free memory allocated by a png_create_struct() call */
  186807. void /* PRIVATE */
  186808. png_destroy_struct(png_voidp struct_ptr)
  186809. {
  186810. #ifdef PNG_USER_MEM_SUPPORTED
  186811. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  186812. }
  186813. /* Free memory allocated by a png_create_struct() call */
  186814. void /* PRIVATE */
  186815. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  186816. png_voidp mem_ptr)
  186817. {
  186818. #endif
  186819. if (struct_ptr != NULL)
  186820. {
  186821. #ifdef PNG_USER_MEM_SUPPORTED
  186822. if(free_fn != NULL)
  186823. {
  186824. png_struct dummy_struct;
  186825. png_structp png_ptr = &dummy_struct;
  186826. png_ptr->mem_ptr=mem_ptr;
  186827. (*(free_fn))(png_ptr, struct_ptr);
  186828. return;
  186829. }
  186830. #endif /* PNG_USER_MEM_SUPPORTED */
  186831. farfree (struct_ptr);
  186832. }
  186833. }
  186834. /* Allocate memory. For reasonable files, size should never exceed
  186835. * 64K. However, zlib may allocate more then 64K if you don't tell
  186836. * it not to. See zconf.h and png.h for more information. zlib does
  186837. * need to allocate exactly 64K, so whatever you call here must
  186838. * have the ability to do that.
  186839. *
  186840. * Borland seems to have a problem in DOS mode for exactly 64K.
  186841. * It gives you a segment with an offset of 8 (perhaps to store its
  186842. * memory stuff). zlib doesn't like this at all, so we have to
  186843. * detect and deal with it. This code should not be needed in
  186844. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  186845. * been updated by Alexander Lehmann for version 0.89 to waste less
  186846. * memory.
  186847. *
  186848. * Note that we can't use png_size_t for the "size" declaration,
  186849. * since on some systems a png_size_t is a 16-bit quantity, and as a
  186850. * result, we would be truncating potentially larger memory requests
  186851. * (which should cause a fatal error) and introducing major problems.
  186852. */
  186853. png_voidp PNGAPI
  186854. png_malloc(png_structp png_ptr, png_uint_32 size)
  186855. {
  186856. png_voidp ret;
  186857. if (png_ptr == NULL || size == 0)
  186858. return (NULL);
  186859. #ifdef PNG_USER_MEM_SUPPORTED
  186860. if(png_ptr->malloc_fn != NULL)
  186861. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  186862. else
  186863. ret = (png_malloc_default(png_ptr, size));
  186864. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186865. png_error(png_ptr, "Out of memory!");
  186866. return (ret);
  186867. }
  186868. png_voidp PNGAPI
  186869. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  186870. {
  186871. png_voidp ret;
  186872. #endif /* PNG_USER_MEM_SUPPORTED */
  186873. if (png_ptr == NULL || size == 0)
  186874. return (NULL);
  186875. #ifdef PNG_MAX_MALLOC_64K
  186876. if (size > (png_uint_32)65536L)
  186877. {
  186878. png_warning(png_ptr, "Cannot Allocate > 64K");
  186879. ret = NULL;
  186880. }
  186881. else
  186882. #endif
  186883. if (size != (size_t)size)
  186884. ret = NULL;
  186885. else if (size == (png_uint_32)65536L)
  186886. {
  186887. if (png_ptr->offset_table == NULL)
  186888. {
  186889. /* try to see if we need to do any of this fancy stuff */
  186890. ret = farmalloc(size);
  186891. if (ret == NULL || ((png_size_t)ret & 0xffff))
  186892. {
  186893. int num_blocks;
  186894. png_uint_32 total_size;
  186895. png_bytep table;
  186896. int i;
  186897. png_byte huge * hptr;
  186898. if (ret != NULL)
  186899. {
  186900. farfree(ret);
  186901. ret = NULL;
  186902. }
  186903. if(png_ptr->zlib_window_bits > 14)
  186904. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  186905. else
  186906. num_blocks = 1;
  186907. if (png_ptr->zlib_mem_level >= 7)
  186908. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  186909. else
  186910. num_blocks++;
  186911. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  186912. table = farmalloc(total_size);
  186913. if (table == NULL)
  186914. {
  186915. #ifndef PNG_USER_MEM_SUPPORTED
  186916. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186917. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  186918. else
  186919. png_warning(png_ptr, "Out Of Memory.");
  186920. #endif
  186921. return (NULL);
  186922. }
  186923. if ((png_size_t)table & 0xfff0)
  186924. {
  186925. #ifndef PNG_USER_MEM_SUPPORTED
  186926. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186927. png_error(png_ptr,
  186928. "Farmalloc didn't return normalized pointer");
  186929. else
  186930. png_warning(png_ptr,
  186931. "Farmalloc didn't return normalized pointer");
  186932. #endif
  186933. return (NULL);
  186934. }
  186935. png_ptr->offset_table = table;
  186936. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  186937. png_sizeof (png_bytep));
  186938. if (png_ptr->offset_table_ptr == NULL)
  186939. {
  186940. #ifndef PNG_USER_MEM_SUPPORTED
  186941. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186942. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  186943. else
  186944. png_warning(png_ptr, "Out Of memory.");
  186945. #endif
  186946. return (NULL);
  186947. }
  186948. hptr = (png_byte huge *)table;
  186949. if ((png_size_t)hptr & 0xf)
  186950. {
  186951. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  186952. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  186953. }
  186954. for (i = 0; i < num_blocks; i++)
  186955. {
  186956. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  186957. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  186958. }
  186959. png_ptr->offset_table_number = num_blocks;
  186960. png_ptr->offset_table_count = 0;
  186961. png_ptr->offset_table_count_free = 0;
  186962. }
  186963. }
  186964. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  186965. {
  186966. #ifndef PNG_USER_MEM_SUPPORTED
  186967. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186968. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  186969. else
  186970. png_warning(png_ptr, "Out of Memory.");
  186971. #endif
  186972. return (NULL);
  186973. }
  186974. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  186975. }
  186976. else
  186977. ret = farmalloc(size);
  186978. #ifndef PNG_USER_MEM_SUPPORTED
  186979. if (ret == NULL)
  186980. {
  186981. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  186982. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186983. else
  186984. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  186985. }
  186986. #endif
  186987. return (ret);
  186988. }
  186989. /* free a pointer allocated by png_malloc(). In the default
  186990. configuration, png_ptr is not used, but is passed in case it
  186991. is needed. If ptr is NULL, return without taking any action. */
  186992. void PNGAPI
  186993. png_free(png_structp png_ptr, png_voidp ptr)
  186994. {
  186995. if (png_ptr == NULL || ptr == NULL)
  186996. return;
  186997. #ifdef PNG_USER_MEM_SUPPORTED
  186998. if (png_ptr->free_fn != NULL)
  186999. {
  187000. (*(png_ptr->free_fn))(png_ptr, ptr);
  187001. return;
  187002. }
  187003. else png_free_default(png_ptr, ptr);
  187004. }
  187005. void PNGAPI
  187006. png_free_default(png_structp png_ptr, png_voidp ptr)
  187007. {
  187008. #endif /* PNG_USER_MEM_SUPPORTED */
  187009. if(png_ptr == NULL) return;
  187010. if (png_ptr->offset_table != NULL)
  187011. {
  187012. int i;
  187013. for (i = 0; i < png_ptr->offset_table_count; i++)
  187014. {
  187015. if (ptr == png_ptr->offset_table_ptr[i])
  187016. {
  187017. ptr = NULL;
  187018. png_ptr->offset_table_count_free++;
  187019. break;
  187020. }
  187021. }
  187022. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  187023. {
  187024. farfree(png_ptr->offset_table);
  187025. farfree(png_ptr->offset_table_ptr);
  187026. png_ptr->offset_table = NULL;
  187027. png_ptr->offset_table_ptr = NULL;
  187028. }
  187029. }
  187030. if (ptr != NULL)
  187031. {
  187032. farfree(ptr);
  187033. }
  187034. }
  187035. #else /* Not the Borland DOS special memory handler */
  187036. /* Allocate memory for a png_struct or a png_info. The malloc and
  187037. memset can be replaced by a single call to calloc() if this is thought
  187038. to improve performance noticably. */
  187039. png_voidp /* PRIVATE */
  187040. png_create_struct(int type)
  187041. {
  187042. #ifdef PNG_USER_MEM_SUPPORTED
  187043. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187044. }
  187045. /* Allocate memory for a png_struct or a png_info. The malloc and
  187046. memset can be replaced by a single call to calloc() if this is thought
  187047. to improve performance noticably. */
  187048. png_voidp /* PRIVATE */
  187049. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187050. {
  187051. #endif /* PNG_USER_MEM_SUPPORTED */
  187052. png_size_t size;
  187053. png_voidp struct_ptr;
  187054. if (type == PNG_STRUCT_INFO)
  187055. size = png_sizeof(png_info);
  187056. else if (type == PNG_STRUCT_PNG)
  187057. size = png_sizeof(png_struct);
  187058. else
  187059. return (NULL);
  187060. #ifdef PNG_USER_MEM_SUPPORTED
  187061. if(malloc_fn != NULL)
  187062. {
  187063. png_struct dummy_struct;
  187064. png_structp png_ptr = &dummy_struct;
  187065. png_ptr->mem_ptr=mem_ptr;
  187066. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187067. if (struct_ptr != NULL)
  187068. png_memset(struct_ptr, 0, size);
  187069. return (struct_ptr);
  187070. }
  187071. #endif /* PNG_USER_MEM_SUPPORTED */
  187072. #if defined(__TURBOC__) && !defined(__FLAT__)
  187073. struct_ptr = (png_voidp)farmalloc(size);
  187074. #else
  187075. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187076. struct_ptr = (png_voidp)halloc(size,1);
  187077. # else
  187078. struct_ptr = (png_voidp)malloc(size);
  187079. # endif
  187080. #endif
  187081. if (struct_ptr != NULL)
  187082. png_memset(struct_ptr, 0, size);
  187083. return (struct_ptr);
  187084. }
  187085. /* Free memory allocated by a png_create_struct() call */
  187086. void /* PRIVATE */
  187087. png_destroy_struct(png_voidp struct_ptr)
  187088. {
  187089. #ifdef PNG_USER_MEM_SUPPORTED
  187090. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187091. }
  187092. /* Free memory allocated by a png_create_struct() call */
  187093. void /* PRIVATE */
  187094. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187095. png_voidp mem_ptr)
  187096. {
  187097. #endif /* PNG_USER_MEM_SUPPORTED */
  187098. if (struct_ptr != NULL)
  187099. {
  187100. #ifdef PNG_USER_MEM_SUPPORTED
  187101. if(free_fn != NULL)
  187102. {
  187103. png_struct dummy_struct;
  187104. png_structp png_ptr = &dummy_struct;
  187105. png_ptr->mem_ptr=mem_ptr;
  187106. (*(free_fn))(png_ptr, struct_ptr);
  187107. return;
  187108. }
  187109. #endif /* PNG_USER_MEM_SUPPORTED */
  187110. #if defined(__TURBOC__) && !defined(__FLAT__)
  187111. farfree(struct_ptr);
  187112. #else
  187113. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187114. hfree(struct_ptr);
  187115. # else
  187116. free(struct_ptr);
  187117. # endif
  187118. #endif
  187119. }
  187120. }
  187121. /* Allocate memory. For reasonable files, size should never exceed
  187122. 64K. However, zlib may allocate more then 64K if you don't tell
  187123. it not to. See zconf.h and png.h for more information. zlib does
  187124. need to allocate exactly 64K, so whatever you call here must
  187125. have the ability to do that. */
  187126. png_voidp PNGAPI
  187127. png_malloc(png_structp png_ptr, png_uint_32 size)
  187128. {
  187129. png_voidp ret;
  187130. #ifdef PNG_USER_MEM_SUPPORTED
  187131. if (png_ptr == NULL || size == 0)
  187132. return (NULL);
  187133. if(png_ptr->malloc_fn != NULL)
  187134. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187135. else
  187136. ret = (png_malloc_default(png_ptr, size));
  187137. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187138. png_error(png_ptr, "Out of Memory!");
  187139. return (ret);
  187140. }
  187141. png_voidp PNGAPI
  187142. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187143. {
  187144. png_voidp ret;
  187145. #endif /* PNG_USER_MEM_SUPPORTED */
  187146. if (png_ptr == NULL || size == 0)
  187147. return (NULL);
  187148. #ifdef PNG_MAX_MALLOC_64K
  187149. if (size > (png_uint_32)65536L)
  187150. {
  187151. #ifndef PNG_USER_MEM_SUPPORTED
  187152. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187153. png_error(png_ptr, "Cannot Allocate > 64K");
  187154. else
  187155. #endif
  187156. return NULL;
  187157. }
  187158. #endif
  187159. /* Check for overflow */
  187160. #if defined(__TURBOC__) && !defined(__FLAT__)
  187161. if (size != (unsigned long)size)
  187162. ret = NULL;
  187163. else
  187164. ret = farmalloc(size);
  187165. #else
  187166. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187167. if (size != (unsigned long)size)
  187168. ret = NULL;
  187169. else
  187170. ret = halloc(size, 1);
  187171. # else
  187172. if (size != (size_t)size)
  187173. ret = NULL;
  187174. else
  187175. ret = malloc((size_t)size);
  187176. # endif
  187177. #endif
  187178. #ifndef PNG_USER_MEM_SUPPORTED
  187179. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187180. png_error(png_ptr, "Out of Memory");
  187181. #endif
  187182. return (ret);
  187183. }
  187184. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187185. without taking any action. */
  187186. void PNGAPI
  187187. png_free(png_structp png_ptr, png_voidp ptr)
  187188. {
  187189. if (png_ptr == NULL || ptr == NULL)
  187190. return;
  187191. #ifdef PNG_USER_MEM_SUPPORTED
  187192. if (png_ptr->free_fn != NULL)
  187193. {
  187194. (*(png_ptr->free_fn))(png_ptr, ptr);
  187195. return;
  187196. }
  187197. else png_free_default(png_ptr, ptr);
  187198. }
  187199. void PNGAPI
  187200. png_free_default(png_structp png_ptr, png_voidp ptr)
  187201. {
  187202. if (png_ptr == NULL || ptr == NULL)
  187203. return;
  187204. #endif /* PNG_USER_MEM_SUPPORTED */
  187205. #if defined(__TURBOC__) && !defined(__FLAT__)
  187206. farfree(ptr);
  187207. #else
  187208. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187209. hfree(ptr);
  187210. # else
  187211. free(ptr);
  187212. # endif
  187213. #endif
  187214. }
  187215. #endif /* Not Borland DOS special memory handler */
  187216. #if defined(PNG_1_0_X)
  187217. # define png_malloc_warn png_malloc
  187218. #else
  187219. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187220. * function will set up png_malloc() to issue a png_warning and return NULL
  187221. * instead of issuing a png_error, if it fails to allocate the requested
  187222. * memory.
  187223. */
  187224. png_voidp PNGAPI
  187225. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187226. {
  187227. png_voidp ptr;
  187228. png_uint_32 save_flags;
  187229. if(png_ptr == NULL) return (NULL);
  187230. save_flags=png_ptr->flags;
  187231. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187232. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187233. png_ptr->flags=save_flags;
  187234. return(ptr);
  187235. }
  187236. #endif
  187237. png_voidp PNGAPI
  187238. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187239. png_uint_32 length)
  187240. {
  187241. png_size_t size;
  187242. size = (png_size_t)length;
  187243. if ((png_uint_32)size != length)
  187244. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187245. return(png_memcpy (s1, s2, size));
  187246. }
  187247. png_voidp PNGAPI
  187248. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187249. png_uint_32 length)
  187250. {
  187251. png_size_t size;
  187252. size = (png_size_t)length;
  187253. if ((png_uint_32)size != length)
  187254. png_error(png_ptr,"Overflow in png_memset_check.");
  187255. return (png_memset (s1, value, size));
  187256. }
  187257. #ifdef PNG_USER_MEM_SUPPORTED
  187258. /* This function is called when the application wants to use another method
  187259. * of allocating and freeing memory.
  187260. */
  187261. void PNGAPI
  187262. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187263. malloc_fn, png_free_ptr free_fn)
  187264. {
  187265. if(png_ptr != NULL) {
  187266. png_ptr->mem_ptr = mem_ptr;
  187267. png_ptr->malloc_fn = malloc_fn;
  187268. png_ptr->free_fn = free_fn;
  187269. }
  187270. }
  187271. /* This function returns a pointer to the mem_ptr associated with the user
  187272. * functions. The application should free any memory associated with this
  187273. * pointer before png_write_destroy and png_read_destroy are called.
  187274. */
  187275. png_voidp PNGAPI
  187276. png_get_mem_ptr(png_structp png_ptr)
  187277. {
  187278. if(png_ptr == NULL) return (NULL);
  187279. return ((png_voidp)png_ptr->mem_ptr);
  187280. }
  187281. #endif /* PNG_USER_MEM_SUPPORTED */
  187282. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187283. /*** End of inlined file: pngmem.c ***/
  187284. /*** Start of inlined file: pngread.c ***/
  187285. /* pngread.c - read a PNG file
  187286. *
  187287. * Last changed in libpng 1.2.20 September 7, 2007
  187288. * For conditions of distribution and use, see copyright notice in png.h
  187289. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  187290. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187291. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187292. *
  187293. * This file contains routines that an application calls directly to
  187294. * read a PNG file or stream.
  187295. */
  187296. #define PNG_INTERNAL
  187297. #if defined(PNG_READ_SUPPORTED)
  187298. /* Create a PNG structure for reading, and allocate any memory needed. */
  187299. png_structp PNGAPI
  187300. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  187301. png_error_ptr error_fn, png_error_ptr warn_fn)
  187302. {
  187303. #ifdef PNG_USER_MEM_SUPPORTED
  187304. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  187305. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  187306. }
  187307. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  187308. png_structp PNGAPI
  187309. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  187310. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  187311. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  187312. {
  187313. #endif /* PNG_USER_MEM_SUPPORTED */
  187314. png_structp png_ptr;
  187315. #ifdef PNG_SETJMP_SUPPORTED
  187316. #ifdef USE_FAR_KEYWORD
  187317. jmp_buf jmpbuf;
  187318. #endif
  187319. #endif
  187320. int i;
  187321. png_debug(1, "in png_create_read_struct\n");
  187322. #ifdef PNG_USER_MEM_SUPPORTED
  187323. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  187324. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  187325. #else
  187326. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187327. #endif
  187328. if (png_ptr == NULL)
  187329. return (NULL);
  187330. /* added at libpng-1.2.6 */
  187331. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187332. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187333. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187334. #endif
  187335. #ifdef PNG_SETJMP_SUPPORTED
  187336. #ifdef USE_FAR_KEYWORD
  187337. if (setjmp(jmpbuf))
  187338. #else
  187339. if (setjmp(png_ptr->jmpbuf))
  187340. #endif
  187341. {
  187342. png_free(png_ptr, png_ptr->zbuf);
  187343. png_ptr->zbuf=NULL;
  187344. #ifdef PNG_USER_MEM_SUPPORTED
  187345. png_destroy_struct_2((png_voidp)png_ptr,
  187346. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  187347. #else
  187348. png_destroy_struct((png_voidp)png_ptr);
  187349. #endif
  187350. return (NULL);
  187351. }
  187352. #ifdef USE_FAR_KEYWORD
  187353. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187354. #endif
  187355. #endif
  187356. #ifdef PNG_USER_MEM_SUPPORTED
  187357. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  187358. #endif
  187359. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  187360. i=0;
  187361. do
  187362. {
  187363. if(user_png_ver[i] != png_libpng_ver[i])
  187364. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187365. } while (png_libpng_ver[i++]);
  187366. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  187367. {
  187368. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  187369. * we must recompile any applications that use any older library version.
  187370. * For versions after libpng 1.0, we will be compatible, so we need
  187371. * only check the first digit.
  187372. */
  187373. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  187374. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  187375. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  187376. {
  187377. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187378. char msg[80];
  187379. if (user_png_ver)
  187380. {
  187381. png_snprintf(msg, 80,
  187382. "Application was compiled with png.h from libpng-%.20s",
  187383. user_png_ver);
  187384. png_warning(png_ptr, msg);
  187385. }
  187386. png_snprintf(msg, 80,
  187387. "Application is running with png.c from libpng-%.20s",
  187388. png_libpng_ver);
  187389. png_warning(png_ptr, msg);
  187390. #endif
  187391. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187392. png_ptr->flags=0;
  187393. #endif
  187394. png_error(png_ptr,
  187395. "Incompatible libpng version in application and library");
  187396. }
  187397. }
  187398. /* initialize zbuf - compression buffer */
  187399. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187400. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187401. (png_uint_32)png_ptr->zbuf_size);
  187402. png_ptr->zstream.zalloc = png_zalloc;
  187403. png_ptr->zstream.zfree = png_zfree;
  187404. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187405. switch (inflateInit(&png_ptr->zstream))
  187406. {
  187407. case Z_OK: /* Do nothing */ break;
  187408. case Z_MEM_ERROR:
  187409. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  187410. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  187411. default: png_error(png_ptr, "Unknown zlib error");
  187412. }
  187413. png_ptr->zstream.next_out = png_ptr->zbuf;
  187414. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187415. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187416. #ifdef PNG_SETJMP_SUPPORTED
  187417. /* Applications that neglect to set up their own setjmp() and then encounter
  187418. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  187419. abort instead of returning. */
  187420. #ifdef USE_FAR_KEYWORD
  187421. if (setjmp(jmpbuf))
  187422. PNG_ABORT();
  187423. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  187424. #else
  187425. if (setjmp(png_ptr->jmpbuf))
  187426. PNG_ABORT();
  187427. #endif
  187428. #endif
  187429. return (png_ptr);
  187430. }
  187431. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  187432. /* Initialize PNG structure for reading, and allocate any memory needed.
  187433. This interface is deprecated in favour of the png_create_read_struct(),
  187434. and it will disappear as of libpng-1.3.0. */
  187435. #undef png_read_init
  187436. void PNGAPI
  187437. png_read_init(png_structp png_ptr)
  187438. {
  187439. /* We only come here via pre-1.0.7-compiled applications */
  187440. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  187441. }
  187442. void PNGAPI
  187443. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  187444. png_size_t png_struct_size, png_size_t png_info_size)
  187445. {
  187446. /* We only come here via pre-1.0.12-compiled applications */
  187447. if(png_ptr == NULL) return;
  187448. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  187449. if(png_sizeof(png_struct) > png_struct_size ||
  187450. png_sizeof(png_info) > png_info_size)
  187451. {
  187452. char msg[80];
  187453. png_ptr->warning_fn=NULL;
  187454. if (user_png_ver)
  187455. {
  187456. png_snprintf(msg, 80,
  187457. "Application was compiled with png.h from libpng-%.20s",
  187458. user_png_ver);
  187459. png_warning(png_ptr, msg);
  187460. }
  187461. png_snprintf(msg, 80,
  187462. "Application is running with png.c from libpng-%.20s",
  187463. png_libpng_ver);
  187464. png_warning(png_ptr, msg);
  187465. }
  187466. #endif
  187467. if(png_sizeof(png_struct) > png_struct_size)
  187468. {
  187469. png_ptr->error_fn=NULL;
  187470. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187471. png_ptr->flags=0;
  187472. #endif
  187473. png_error(png_ptr,
  187474. "The png struct allocated by the application for reading is too small.");
  187475. }
  187476. if(png_sizeof(png_info) > png_info_size)
  187477. {
  187478. png_ptr->error_fn=NULL;
  187479. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  187480. png_ptr->flags=0;
  187481. #endif
  187482. png_error(png_ptr,
  187483. "The info struct allocated by application for reading is too small.");
  187484. }
  187485. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  187486. }
  187487. #endif /* PNG_1_0_X || PNG_1_2_X */
  187488. void PNGAPI
  187489. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  187490. png_size_t png_struct_size)
  187491. {
  187492. #ifdef PNG_SETJMP_SUPPORTED
  187493. jmp_buf tmp_jmp; /* to save current jump buffer */
  187494. #endif
  187495. int i=0;
  187496. png_structp png_ptr=*ptr_ptr;
  187497. if(png_ptr == NULL) return;
  187498. do
  187499. {
  187500. if(user_png_ver[i] != png_libpng_ver[i])
  187501. {
  187502. #ifdef PNG_LEGACY_SUPPORTED
  187503. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  187504. #else
  187505. png_ptr->warning_fn=NULL;
  187506. png_warning(png_ptr,
  187507. "Application uses deprecated png_read_init() and should be recompiled.");
  187508. break;
  187509. #endif
  187510. }
  187511. } while (png_libpng_ver[i++]);
  187512. png_debug(1, "in png_read_init_3\n");
  187513. #ifdef PNG_SETJMP_SUPPORTED
  187514. /* save jump buffer and error functions */
  187515. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  187516. #endif
  187517. if(png_sizeof(png_struct) > png_struct_size)
  187518. {
  187519. png_destroy_struct(png_ptr);
  187520. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  187521. png_ptr = *ptr_ptr;
  187522. }
  187523. /* reset all variables to 0 */
  187524. png_memset(png_ptr, 0, png_sizeof (png_struct));
  187525. #ifdef PNG_SETJMP_SUPPORTED
  187526. /* restore jump buffer */
  187527. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  187528. #endif
  187529. /* added at libpng-1.2.6 */
  187530. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187531. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  187532. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  187533. #endif
  187534. /* initialize zbuf - compression buffer */
  187535. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  187536. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  187537. (png_uint_32)png_ptr->zbuf_size);
  187538. png_ptr->zstream.zalloc = png_zalloc;
  187539. png_ptr->zstream.zfree = png_zfree;
  187540. png_ptr->zstream.opaque = (voidpf)png_ptr;
  187541. switch (inflateInit(&png_ptr->zstream))
  187542. {
  187543. case Z_OK: /* Do nothing */ break;
  187544. case Z_MEM_ERROR:
  187545. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  187546. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  187547. default: png_error(png_ptr, "Unknown zlib error");
  187548. }
  187549. png_ptr->zstream.next_out = png_ptr->zbuf;
  187550. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  187551. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  187552. }
  187553. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187554. /* Read the information before the actual image data. This has been
  187555. * changed in v0.90 to allow reading a file that already has the magic
  187556. * bytes read from the stream. You can tell libpng how many bytes have
  187557. * been read from the beginning of the stream (up to the maximum of 8)
  187558. * via png_set_sig_bytes(), and we will only check the remaining bytes
  187559. * here. The application can then have access to the signature bytes we
  187560. * read if it is determined that this isn't a valid PNG file.
  187561. */
  187562. void PNGAPI
  187563. png_read_info(png_structp png_ptr, png_infop info_ptr)
  187564. {
  187565. if(png_ptr == NULL) return;
  187566. png_debug(1, "in png_read_info\n");
  187567. /* If we haven't checked all of the PNG signature bytes, do so now. */
  187568. if (png_ptr->sig_bytes < 8)
  187569. {
  187570. png_size_t num_checked = png_ptr->sig_bytes,
  187571. num_to_check = 8 - num_checked;
  187572. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  187573. png_ptr->sig_bytes = 8;
  187574. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  187575. {
  187576. if (num_checked < 4 &&
  187577. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  187578. png_error(png_ptr, "Not a PNG file");
  187579. else
  187580. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  187581. }
  187582. if (num_checked < 3)
  187583. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  187584. }
  187585. for(;;)
  187586. {
  187587. #ifdef PNG_USE_LOCAL_ARRAYS
  187588. PNG_CONST PNG_IHDR;
  187589. PNG_CONST PNG_IDAT;
  187590. PNG_CONST PNG_IEND;
  187591. PNG_CONST PNG_PLTE;
  187592. #if defined(PNG_READ_bKGD_SUPPORTED)
  187593. PNG_CONST PNG_bKGD;
  187594. #endif
  187595. #if defined(PNG_READ_cHRM_SUPPORTED)
  187596. PNG_CONST PNG_cHRM;
  187597. #endif
  187598. #if defined(PNG_READ_gAMA_SUPPORTED)
  187599. PNG_CONST PNG_gAMA;
  187600. #endif
  187601. #if defined(PNG_READ_hIST_SUPPORTED)
  187602. PNG_CONST PNG_hIST;
  187603. #endif
  187604. #if defined(PNG_READ_iCCP_SUPPORTED)
  187605. PNG_CONST PNG_iCCP;
  187606. #endif
  187607. #if defined(PNG_READ_iTXt_SUPPORTED)
  187608. PNG_CONST PNG_iTXt;
  187609. #endif
  187610. #if defined(PNG_READ_oFFs_SUPPORTED)
  187611. PNG_CONST PNG_oFFs;
  187612. #endif
  187613. #if defined(PNG_READ_pCAL_SUPPORTED)
  187614. PNG_CONST PNG_pCAL;
  187615. #endif
  187616. #if defined(PNG_READ_pHYs_SUPPORTED)
  187617. PNG_CONST PNG_pHYs;
  187618. #endif
  187619. #if defined(PNG_READ_sBIT_SUPPORTED)
  187620. PNG_CONST PNG_sBIT;
  187621. #endif
  187622. #if defined(PNG_READ_sCAL_SUPPORTED)
  187623. PNG_CONST PNG_sCAL;
  187624. #endif
  187625. #if defined(PNG_READ_sPLT_SUPPORTED)
  187626. PNG_CONST PNG_sPLT;
  187627. #endif
  187628. #if defined(PNG_READ_sRGB_SUPPORTED)
  187629. PNG_CONST PNG_sRGB;
  187630. #endif
  187631. #if defined(PNG_READ_tEXt_SUPPORTED)
  187632. PNG_CONST PNG_tEXt;
  187633. #endif
  187634. #if defined(PNG_READ_tIME_SUPPORTED)
  187635. PNG_CONST PNG_tIME;
  187636. #endif
  187637. #if defined(PNG_READ_tRNS_SUPPORTED)
  187638. PNG_CONST PNG_tRNS;
  187639. #endif
  187640. #if defined(PNG_READ_zTXt_SUPPORTED)
  187641. PNG_CONST PNG_zTXt;
  187642. #endif
  187643. #endif /* PNG_USE_LOCAL_ARRAYS */
  187644. png_byte chunk_length[4];
  187645. png_uint_32 length;
  187646. png_read_data(png_ptr, chunk_length, 4);
  187647. length = png_get_uint_31(png_ptr,chunk_length);
  187648. png_reset_crc(png_ptr);
  187649. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187650. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  187651. length);
  187652. /* This should be a binary subdivision search or a hash for
  187653. * matching the chunk name rather than a linear search.
  187654. */
  187655. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187656. if(png_ptr->mode & PNG_AFTER_IDAT)
  187657. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  187658. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  187659. png_handle_IHDR(png_ptr, info_ptr, length);
  187660. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  187661. png_handle_IEND(png_ptr, info_ptr, length);
  187662. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  187663. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  187664. {
  187665. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187666. png_ptr->mode |= PNG_HAVE_IDAT;
  187667. png_handle_unknown(png_ptr, info_ptr, length);
  187668. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187669. png_ptr->mode |= PNG_HAVE_PLTE;
  187670. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187671. {
  187672. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187673. png_error(png_ptr, "Missing IHDR before IDAT");
  187674. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187675. !(png_ptr->mode & PNG_HAVE_PLTE))
  187676. png_error(png_ptr, "Missing PLTE before IDAT");
  187677. break;
  187678. }
  187679. }
  187680. #endif
  187681. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  187682. png_handle_PLTE(png_ptr, info_ptr, length);
  187683. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187684. {
  187685. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  187686. png_error(png_ptr, "Missing IHDR before IDAT");
  187687. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  187688. !(png_ptr->mode & PNG_HAVE_PLTE))
  187689. png_error(png_ptr, "Missing PLTE before IDAT");
  187690. png_ptr->idat_size = length;
  187691. png_ptr->mode |= PNG_HAVE_IDAT;
  187692. break;
  187693. }
  187694. #if defined(PNG_READ_bKGD_SUPPORTED)
  187695. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  187696. png_handle_bKGD(png_ptr, info_ptr, length);
  187697. #endif
  187698. #if defined(PNG_READ_cHRM_SUPPORTED)
  187699. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  187700. png_handle_cHRM(png_ptr, info_ptr, length);
  187701. #endif
  187702. #if defined(PNG_READ_gAMA_SUPPORTED)
  187703. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  187704. png_handle_gAMA(png_ptr, info_ptr, length);
  187705. #endif
  187706. #if defined(PNG_READ_hIST_SUPPORTED)
  187707. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  187708. png_handle_hIST(png_ptr, info_ptr, length);
  187709. #endif
  187710. #if defined(PNG_READ_oFFs_SUPPORTED)
  187711. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  187712. png_handle_oFFs(png_ptr, info_ptr, length);
  187713. #endif
  187714. #if defined(PNG_READ_pCAL_SUPPORTED)
  187715. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  187716. png_handle_pCAL(png_ptr, info_ptr, length);
  187717. #endif
  187718. #if defined(PNG_READ_sCAL_SUPPORTED)
  187719. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  187720. png_handle_sCAL(png_ptr, info_ptr, length);
  187721. #endif
  187722. #if defined(PNG_READ_pHYs_SUPPORTED)
  187723. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  187724. png_handle_pHYs(png_ptr, info_ptr, length);
  187725. #endif
  187726. #if defined(PNG_READ_sBIT_SUPPORTED)
  187727. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  187728. png_handle_sBIT(png_ptr, info_ptr, length);
  187729. #endif
  187730. #if defined(PNG_READ_sRGB_SUPPORTED)
  187731. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  187732. png_handle_sRGB(png_ptr, info_ptr, length);
  187733. #endif
  187734. #if defined(PNG_READ_iCCP_SUPPORTED)
  187735. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  187736. png_handle_iCCP(png_ptr, info_ptr, length);
  187737. #endif
  187738. #if defined(PNG_READ_sPLT_SUPPORTED)
  187739. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  187740. png_handle_sPLT(png_ptr, info_ptr, length);
  187741. #endif
  187742. #if defined(PNG_READ_tEXt_SUPPORTED)
  187743. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  187744. png_handle_tEXt(png_ptr, info_ptr, length);
  187745. #endif
  187746. #if defined(PNG_READ_tIME_SUPPORTED)
  187747. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  187748. png_handle_tIME(png_ptr, info_ptr, length);
  187749. #endif
  187750. #if defined(PNG_READ_tRNS_SUPPORTED)
  187751. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  187752. png_handle_tRNS(png_ptr, info_ptr, length);
  187753. #endif
  187754. #if defined(PNG_READ_zTXt_SUPPORTED)
  187755. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  187756. png_handle_zTXt(png_ptr, info_ptr, length);
  187757. #endif
  187758. #if defined(PNG_READ_iTXt_SUPPORTED)
  187759. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  187760. png_handle_iTXt(png_ptr, info_ptr, length);
  187761. #endif
  187762. else
  187763. png_handle_unknown(png_ptr, info_ptr, length);
  187764. }
  187765. }
  187766. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187767. /* optional call to update the users info_ptr structure */
  187768. void PNGAPI
  187769. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  187770. {
  187771. png_debug(1, "in png_read_update_info\n");
  187772. if(png_ptr == NULL) return;
  187773. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187774. png_read_start_row(png_ptr);
  187775. else
  187776. png_warning(png_ptr,
  187777. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  187778. png_read_transform_info(png_ptr, info_ptr);
  187779. }
  187780. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187781. /* Initialize palette, background, etc, after transformations
  187782. * are set, but before any reading takes place. This allows
  187783. * the user to obtain a gamma-corrected palette, for example.
  187784. * If the user doesn't call this, we will do it ourselves.
  187785. */
  187786. void PNGAPI
  187787. png_start_read_image(png_structp png_ptr)
  187788. {
  187789. png_debug(1, "in png_start_read_image\n");
  187790. if(png_ptr == NULL) return;
  187791. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187792. png_read_start_row(png_ptr);
  187793. }
  187794. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  187795. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  187796. void PNGAPI
  187797. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  187798. {
  187799. #ifdef PNG_USE_LOCAL_ARRAYS
  187800. PNG_CONST PNG_IDAT;
  187801. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  187802. 0xff};
  187803. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  187804. #endif
  187805. int ret;
  187806. if(png_ptr == NULL) return;
  187807. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  187808. png_ptr->row_number, png_ptr->pass);
  187809. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  187810. png_read_start_row(png_ptr);
  187811. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  187812. {
  187813. /* check for transforms that have been set but were defined out */
  187814. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  187815. if (png_ptr->transformations & PNG_INVERT_MONO)
  187816. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  187817. #endif
  187818. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  187819. if (png_ptr->transformations & PNG_FILLER)
  187820. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  187821. #endif
  187822. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  187823. if (png_ptr->transformations & PNG_PACKSWAP)
  187824. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  187825. #endif
  187826. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  187827. if (png_ptr->transformations & PNG_PACK)
  187828. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  187829. #endif
  187830. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  187831. if (png_ptr->transformations & PNG_SHIFT)
  187832. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  187833. #endif
  187834. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  187835. if (png_ptr->transformations & PNG_BGR)
  187836. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  187837. #endif
  187838. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  187839. if (png_ptr->transformations & PNG_SWAP_BYTES)
  187840. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  187841. #endif
  187842. }
  187843. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187844. /* if interlaced and we do not need a new row, combine row and return */
  187845. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  187846. {
  187847. switch (png_ptr->pass)
  187848. {
  187849. case 0:
  187850. if (png_ptr->row_number & 0x07)
  187851. {
  187852. if (dsp_row != NULL)
  187853. png_combine_row(png_ptr, dsp_row,
  187854. png_pass_dsp_mask[png_ptr->pass]);
  187855. png_read_finish_row(png_ptr);
  187856. return;
  187857. }
  187858. break;
  187859. case 1:
  187860. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  187861. {
  187862. if (dsp_row != NULL)
  187863. png_combine_row(png_ptr, dsp_row,
  187864. png_pass_dsp_mask[png_ptr->pass]);
  187865. png_read_finish_row(png_ptr);
  187866. return;
  187867. }
  187868. break;
  187869. case 2:
  187870. if ((png_ptr->row_number & 0x07) != 4)
  187871. {
  187872. if (dsp_row != NULL && (png_ptr->row_number & 4))
  187873. png_combine_row(png_ptr, dsp_row,
  187874. png_pass_dsp_mask[png_ptr->pass]);
  187875. png_read_finish_row(png_ptr);
  187876. return;
  187877. }
  187878. break;
  187879. case 3:
  187880. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  187881. {
  187882. if (dsp_row != NULL)
  187883. png_combine_row(png_ptr, dsp_row,
  187884. png_pass_dsp_mask[png_ptr->pass]);
  187885. png_read_finish_row(png_ptr);
  187886. return;
  187887. }
  187888. break;
  187889. case 4:
  187890. if ((png_ptr->row_number & 3) != 2)
  187891. {
  187892. if (dsp_row != NULL && (png_ptr->row_number & 2))
  187893. png_combine_row(png_ptr, dsp_row,
  187894. png_pass_dsp_mask[png_ptr->pass]);
  187895. png_read_finish_row(png_ptr);
  187896. return;
  187897. }
  187898. break;
  187899. case 5:
  187900. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  187901. {
  187902. if (dsp_row != NULL)
  187903. png_combine_row(png_ptr, dsp_row,
  187904. png_pass_dsp_mask[png_ptr->pass]);
  187905. png_read_finish_row(png_ptr);
  187906. return;
  187907. }
  187908. break;
  187909. case 6:
  187910. if (!(png_ptr->row_number & 1))
  187911. {
  187912. png_read_finish_row(png_ptr);
  187913. return;
  187914. }
  187915. break;
  187916. }
  187917. }
  187918. #endif
  187919. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  187920. png_error(png_ptr, "Invalid attempt to read row data");
  187921. png_ptr->zstream.next_out = png_ptr->row_buf;
  187922. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  187923. do
  187924. {
  187925. if (!(png_ptr->zstream.avail_in))
  187926. {
  187927. while (!png_ptr->idat_size)
  187928. {
  187929. png_byte chunk_length[4];
  187930. png_crc_finish(png_ptr, 0);
  187931. png_read_data(png_ptr, chunk_length, 4);
  187932. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  187933. png_reset_crc(png_ptr);
  187934. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  187935. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  187936. png_error(png_ptr, "Not enough image data");
  187937. }
  187938. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  187939. png_ptr->zstream.next_in = png_ptr->zbuf;
  187940. if (png_ptr->zbuf_size > png_ptr->idat_size)
  187941. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  187942. png_crc_read(png_ptr, png_ptr->zbuf,
  187943. (png_size_t)png_ptr->zstream.avail_in);
  187944. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  187945. }
  187946. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  187947. if (ret == Z_STREAM_END)
  187948. {
  187949. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  187950. png_ptr->idat_size)
  187951. png_error(png_ptr, "Extra compressed data");
  187952. png_ptr->mode |= PNG_AFTER_IDAT;
  187953. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  187954. break;
  187955. }
  187956. if (ret != Z_OK)
  187957. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  187958. "Decompression error");
  187959. } while (png_ptr->zstream.avail_out);
  187960. png_ptr->row_info.color_type = png_ptr->color_type;
  187961. png_ptr->row_info.width = png_ptr->iwidth;
  187962. png_ptr->row_info.channels = png_ptr->channels;
  187963. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  187964. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  187965. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  187966. png_ptr->row_info.width);
  187967. if(png_ptr->row_buf[0])
  187968. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  187969. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  187970. (int)(png_ptr->row_buf[0]));
  187971. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  187972. png_ptr->rowbytes + 1);
  187973. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  187974. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  187975. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  187976. {
  187977. /* Intrapixel differencing */
  187978. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  187979. }
  187980. #endif
  187981. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  187982. png_do_read_transformations(png_ptr);
  187983. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  187984. /* blow up interlaced rows to full size */
  187985. if (png_ptr->interlaced &&
  187986. (png_ptr->transformations & PNG_INTERLACE))
  187987. {
  187988. if (png_ptr->pass < 6)
  187989. /* old interface (pre-1.0.9):
  187990. png_do_read_interlace(&(png_ptr->row_info),
  187991. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  187992. */
  187993. png_do_read_interlace(png_ptr);
  187994. if (dsp_row != NULL)
  187995. png_combine_row(png_ptr, dsp_row,
  187996. png_pass_dsp_mask[png_ptr->pass]);
  187997. if (row != NULL)
  187998. png_combine_row(png_ptr, row,
  187999. png_pass_mask[png_ptr->pass]);
  188000. }
  188001. else
  188002. #endif
  188003. {
  188004. if (row != NULL)
  188005. png_combine_row(png_ptr, row, 0xff);
  188006. if (dsp_row != NULL)
  188007. png_combine_row(png_ptr, dsp_row, 0xff);
  188008. }
  188009. png_read_finish_row(png_ptr);
  188010. if (png_ptr->read_row_fn != NULL)
  188011. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  188012. }
  188013. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188014. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188015. /* Read one or more rows of image data. If the image is interlaced,
  188016. * and png_set_interlace_handling() has been called, the rows need to
  188017. * contain the contents of the rows from the previous pass. If the
  188018. * image has alpha or transparency, and png_handle_alpha()[*] has been
  188019. * called, the rows contents must be initialized to the contents of the
  188020. * screen.
  188021. *
  188022. * "row" holds the actual image, and pixels are placed in it
  188023. * as they arrive. If the image is displayed after each pass, it will
  188024. * appear to "sparkle" in. "display_row" can be used to display a
  188025. * "chunky" progressive image, with finer detail added as it becomes
  188026. * available. If you do not want this "chunky" display, you may pass
  188027. * NULL for display_row. If you do not want the sparkle display, and
  188028. * you have not called png_handle_alpha(), you may pass NULL for rows.
  188029. * If you have called png_handle_alpha(), and the image has either an
  188030. * alpha channel or a transparency chunk, you must provide a buffer for
  188031. * rows. In this case, you do not have to provide a display_row buffer
  188032. * also, but you may. If the image is not interlaced, or if you have
  188033. * not called png_set_interlace_handling(), the display_row buffer will
  188034. * be ignored, so pass NULL to it.
  188035. *
  188036. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188037. */
  188038. void PNGAPI
  188039. png_read_rows(png_structp png_ptr, png_bytepp row,
  188040. png_bytepp display_row, png_uint_32 num_rows)
  188041. {
  188042. png_uint_32 i;
  188043. png_bytepp rp;
  188044. png_bytepp dp;
  188045. png_debug(1, "in png_read_rows\n");
  188046. if(png_ptr == NULL) return;
  188047. rp = row;
  188048. dp = display_row;
  188049. if (rp != NULL && dp != NULL)
  188050. for (i = 0; i < num_rows; i++)
  188051. {
  188052. png_bytep rptr = *rp++;
  188053. png_bytep dptr = *dp++;
  188054. png_read_row(png_ptr, rptr, dptr);
  188055. }
  188056. else if(rp != NULL)
  188057. for (i = 0; i < num_rows; i++)
  188058. {
  188059. png_bytep rptr = *rp;
  188060. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188061. rp++;
  188062. }
  188063. else if(dp != NULL)
  188064. for (i = 0; i < num_rows; i++)
  188065. {
  188066. png_bytep dptr = *dp;
  188067. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188068. dp++;
  188069. }
  188070. }
  188071. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188072. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188073. /* Read the entire image. If the image has an alpha channel or a tRNS
  188074. * chunk, and you have called png_handle_alpha()[*], you will need to
  188075. * initialize the image to the current image that PNG will be overlaying.
  188076. * We set the num_rows again here, in case it was incorrectly set in
  188077. * png_read_start_row() by a call to png_read_update_info() or
  188078. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188079. * prior to either of these functions like it should have been. You can
  188080. * only call this function once. If you desire to have an image for
  188081. * each pass of a interlaced image, use png_read_rows() instead.
  188082. *
  188083. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188084. */
  188085. void PNGAPI
  188086. png_read_image(png_structp png_ptr, png_bytepp image)
  188087. {
  188088. png_uint_32 i,image_height;
  188089. int pass, j;
  188090. png_bytepp rp;
  188091. png_debug(1, "in png_read_image\n");
  188092. if(png_ptr == NULL) return;
  188093. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188094. pass = png_set_interlace_handling(png_ptr);
  188095. #else
  188096. if (png_ptr->interlaced)
  188097. png_error(png_ptr,
  188098. "Cannot read interlaced image -- interlace handler disabled.");
  188099. pass = 1;
  188100. #endif
  188101. image_height=png_ptr->height;
  188102. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188103. for (j = 0; j < pass; j++)
  188104. {
  188105. rp = image;
  188106. for (i = 0; i < image_height; i++)
  188107. {
  188108. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188109. rp++;
  188110. }
  188111. }
  188112. }
  188113. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188114. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188115. /* Read the end of the PNG file. Will not read past the end of the
  188116. * file, will verify the end is accurate, and will read any comments
  188117. * or time information at the end of the file, if info is not NULL.
  188118. */
  188119. void PNGAPI
  188120. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188121. {
  188122. png_byte chunk_length[4];
  188123. png_uint_32 length;
  188124. png_debug(1, "in png_read_end\n");
  188125. if(png_ptr == NULL) return;
  188126. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188127. do
  188128. {
  188129. #ifdef PNG_USE_LOCAL_ARRAYS
  188130. PNG_CONST PNG_IHDR;
  188131. PNG_CONST PNG_IDAT;
  188132. PNG_CONST PNG_IEND;
  188133. PNG_CONST PNG_PLTE;
  188134. #if defined(PNG_READ_bKGD_SUPPORTED)
  188135. PNG_CONST PNG_bKGD;
  188136. #endif
  188137. #if defined(PNG_READ_cHRM_SUPPORTED)
  188138. PNG_CONST PNG_cHRM;
  188139. #endif
  188140. #if defined(PNG_READ_gAMA_SUPPORTED)
  188141. PNG_CONST PNG_gAMA;
  188142. #endif
  188143. #if defined(PNG_READ_hIST_SUPPORTED)
  188144. PNG_CONST PNG_hIST;
  188145. #endif
  188146. #if defined(PNG_READ_iCCP_SUPPORTED)
  188147. PNG_CONST PNG_iCCP;
  188148. #endif
  188149. #if defined(PNG_READ_iTXt_SUPPORTED)
  188150. PNG_CONST PNG_iTXt;
  188151. #endif
  188152. #if defined(PNG_READ_oFFs_SUPPORTED)
  188153. PNG_CONST PNG_oFFs;
  188154. #endif
  188155. #if defined(PNG_READ_pCAL_SUPPORTED)
  188156. PNG_CONST PNG_pCAL;
  188157. #endif
  188158. #if defined(PNG_READ_pHYs_SUPPORTED)
  188159. PNG_CONST PNG_pHYs;
  188160. #endif
  188161. #if defined(PNG_READ_sBIT_SUPPORTED)
  188162. PNG_CONST PNG_sBIT;
  188163. #endif
  188164. #if defined(PNG_READ_sCAL_SUPPORTED)
  188165. PNG_CONST PNG_sCAL;
  188166. #endif
  188167. #if defined(PNG_READ_sPLT_SUPPORTED)
  188168. PNG_CONST PNG_sPLT;
  188169. #endif
  188170. #if defined(PNG_READ_sRGB_SUPPORTED)
  188171. PNG_CONST PNG_sRGB;
  188172. #endif
  188173. #if defined(PNG_READ_tEXt_SUPPORTED)
  188174. PNG_CONST PNG_tEXt;
  188175. #endif
  188176. #if defined(PNG_READ_tIME_SUPPORTED)
  188177. PNG_CONST PNG_tIME;
  188178. #endif
  188179. #if defined(PNG_READ_tRNS_SUPPORTED)
  188180. PNG_CONST PNG_tRNS;
  188181. #endif
  188182. #if defined(PNG_READ_zTXt_SUPPORTED)
  188183. PNG_CONST PNG_zTXt;
  188184. #endif
  188185. #endif /* PNG_USE_LOCAL_ARRAYS */
  188186. png_read_data(png_ptr, chunk_length, 4);
  188187. length = png_get_uint_31(png_ptr,chunk_length);
  188188. png_reset_crc(png_ptr);
  188189. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188190. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188191. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188192. png_handle_IHDR(png_ptr, info_ptr, length);
  188193. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188194. png_handle_IEND(png_ptr, info_ptr, length);
  188195. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188196. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188197. {
  188198. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188199. {
  188200. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188201. png_error(png_ptr, "Too many IDAT's found");
  188202. }
  188203. png_handle_unknown(png_ptr, info_ptr, length);
  188204. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188205. png_ptr->mode |= PNG_HAVE_PLTE;
  188206. }
  188207. #endif
  188208. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188209. {
  188210. /* Zero length IDATs are legal after the last IDAT has been
  188211. * read, but not after other chunks have been read.
  188212. */
  188213. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188214. png_error(png_ptr, "Too many IDAT's found");
  188215. png_crc_finish(png_ptr, length);
  188216. }
  188217. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188218. png_handle_PLTE(png_ptr, info_ptr, length);
  188219. #if defined(PNG_READ_bKGD_SUPPORTED)
  188220. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188221. png_handle_bKGD(png_ptr, info_ptr, length);
  188222. #endif
  188223. #if defined(PNG_READ_cHRM_SUPPORTED)
  188224. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188225. png_handle_cHRM(png_ptr, info_ptr, length);
  188226. #endif
  188227. #if defined(PNG_READ_gAMA_SUPPORTED)
  188228. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188229. png_handle_gAMA(png_ptr, info_ptr, length);
  188230. #endif
  188231. #if defined(PNG_READ_hIST_SUPPORTED)
  188232. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188233. png_handle_hIST(png_ptr, info_ptr, length);
  188234. #endif
  188235. #if defined(PNG_READ_oFFs_SUPPORTED)
  188236. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188237. png_handle_oFFs(png_ptr, info_ptr, length);
  188238. #endif
  188239. #if defined(PNG_READ_pCAL_SUPPORTED)
  188240. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188241. png_handle_pCAL(png_ptr, info_ptr, length);
  188242. #endif
  188243. #if defined(PNG_READ_sCAL_SUPPORTED)
  188244. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188245. png_handle_sCAL(png_ptr, info_ptr, length);
  188246. #endif
  188247. #if defined(PNG_READ_pHYs_SUPPORTED)
  188248. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188249. png_handle_pHYs(png_ptr, info_ptr, length);
  188250. #endif
  188251. #if defined(PNG_READ_sBIT_SUPPORTED)
  188252. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188253. png_handle_sBIT(png_ptr, info_ptr, length);
  188254. #endif
  188255. #if defined(PNG_READ_sRGB_SUPPORTED)
  188256. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188257. png_handle_sRGB(png_ptr, info_ptr, length);
  188258. #endif
  188259. #if defined(PNG_READ_iCCP_SUPPORTED)
  188260. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188261. png_handle_iCCP(png_ptr, info_ptr, length);
  188262. #endif
  188263. #if defined(PNG_READ_sPLT_SUPPORTED)
  188264. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188265. png_handle_sPLT(png_ptr, info_ptr, length);
  188266. #endif
  188267. #if defined(PNG_READ_tEXt_SUPPORTED)
  188268. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188269. png_handle_tEXt(png_ptr, info_ptr, length);
  188270. #endif
  188271. #if defined(PNG_READ_tIME_SUPPORTED)
  188272. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188273. png_handle_tIME(png_ptr, info_ptr, length);
  188274. #endif
  188275. #if defined(PNG_READ_tRNS_SUPPORTED)
  188276. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188277. png_handle_tRNS(png_ptr, info_ptr, length);
  188278. #endif
  188279. #if defined(PNG_READ_zTXt_SUPPORTED)
  188280. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188281. png_handle_zTXt(png_ptr, info_ptr, length);
  188282. #endif
  188283. #if defined(PNG_READ_iTXt_SUPPORTED)
  188284. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188285. png_handle_iTXt(png_ptr, info_ptr, length);
  188286. #endif
  188287. else
  188288. png_handle_unknown(png_ptr, info_ptr, length);
  188289. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  188290. }
  188291. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188292. /* free all memory used by the read */
  188293. void PNGAPI
  188294. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  188295. png_infopp end_info_ptr_ptr)
  188296. {
  188297. png_structp png_ptr = NULL;
  188298. png_infop info_ptr = NULL, end_info_ptr = NULL;
  188299. #ifdef PNG_USER_MEM_SUPPORTED
  188300. png_free_ptr free_fn;
  188301. png_voidp mem_ptr;
  188302. #endif
  188303. png_debug(1, "in png_destroy_read_struct\n");
  188304. if (png_ptr_ptr != NULL)
  188305. png_ptr = *png_ptr_ptr;
  188306. if (info_ptr_ptr != NULL)
  188307. info_ptr = *info_ptr_ptr;
  188308. if (end_info_ptr_ptr != NULL)
  188309. end_info_ptr = *end_info_ptr_ptr;
  188310. #ifdef PNG_USER_MEM_SUPPORTED
  188311. free_fn = png_ptr->free_fn;
  188312. mem_ptr = png_ptr->mem_ptr;
  188313. #endif
  188314. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  188315. if (info_ptr != NULL)
  188316. {
  188317. #if defined(PNG_TEXT_SUPPORTED)
  188318. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  188319. #endif
  188320. #ifdef PNG_USER_MEM_SUPPORTED
  188321. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  188322. (png_voidp)mem_ptr);
  188323. #else
  188324. png_destroy_struct((png_voidp)info_ptr);
  188325. #endif
  188326. *info_ptr_ptr = NULL;
  188327. }
  188328. if (end_info_ptr != NULL)
  188329. {
  188330. #if defined(PNG_READ_TEXT_SUPPORTED)
  188331. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  188332. #endif
  188333. #ifdef PNG_USER_MEM_SUPPORTED
  188334. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  188335. (png_voidp)mem_ptr);
  188336. #else
  188337. png_destroy_struct((png_voidp)end_info_ptr);
  188338. #endif
  188339. *end_info_ptr_ptr = NULL;
  188340. }
  188341. if (png_ptr != NULL)
  188342. {
  188343. #ifdef PNG_USER_MEM_SUPPORTED
  188344. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  188345. (png_voidp)mem_ptr);
  188346. #else
  188347. png_destroy_struct((png_voidp)png_ptr);
  188348. #endif
  188349. *png_ptr_ptr = NULL;
  188350. }
  188351. }
  188352. /* free all memory used by the read (old method) */
  188353. void /* PRIVATE */
  188354. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  188355. {
  188356. #ifdef PNG_SETJMP_SUPPORTED
  188357. jmp_buf tmp_jmp;
  188358. #endif
  188359. png_error_ptr error_fn;
  188360. png_error_ptr warning_fn;
  188361. png_voidp error_ptr;
  188362. #ifdef PNG_USER_MEM_SUPPORTED
  188363. png_free_ptr free_fn;
  188364. #endif
  188365. png_debug(1, "in png_read_destroy\n");
  188366. if (info_ptr != NULL)
  188367. png_info_destroy(png_ptr, info_ptr);
  188368. if (end_info_ptr != NULL)
  188369. png_info_destroy(png_ptr, end_info_ptr);
  188370. png_free(png_ptr, png_ptr->zbuf);
  188371. png_free(png_ptr, png_ptr->big_row_buf);
  188372. png_free(png_ptr, png_ptr->prev_row);
  188373. #if defined(PNG_READ_DITHER_SUPPORTED)
  188374. png_free(png_ptr, png_ptr->palette_lookup);
  188375. png_free(png_ptr, png_ptr->dither_index);
  188376. #endif
  188377. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188378. png_free(png_ptr, png_ptr->gamma_table);
  188379. #endif
  188380. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188381. png_free(png_ptr, png_ptr->gamma_from_1);
  188382. png_free(png_ptr, png_ptr->gamma_to_1);
  188383. #endif
  188384. #ifdef PNG_FREE_ME_SUPPORTED
  188385. if (png_ptr->free_me & PNG_FREE_PLTE)
  188386. png_zfree(png_ptr, png_ptr->palette);
  188387. png_ptr->free_me &= ~PNG_FREE_PLTE;
  188388. #else
  188389. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  188390. png_zfree(png_ptr, png_ptr->palette);
  188391. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  188392. #endif
  188393. #if defined(PNG_tRNS_SUPPORTED) || \
  188394. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  188395. #ifdef PNG_FREE_ME_SUPPORTED
  188396. if (png_ptr->free_me & PNG_FREE_TRNS)
  188397. png_free(png_ptr, png_ptr->trans);
  188398. png_ptr->free_me &= ~PNG_FREE_TRNS;
  188399. #else
  188400. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  188401. png_free(png_ptr, png_ptr->trans);
  188402. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  188403. #endif
  188404. #endif
  188405. #if defined(PNG_READ_hIST_SUPPORTED)
  188406. #ifdef PNG_FREE_ME_SUPPORTED
  188407. if (png_ptr->free_me & PNG_FREE_HIST)
  188408. png_free(png_ptr, png_ptr->hist);
  188409. png_ptr->free_me &= ~PNG_FREE_HIST;
  188410. #else
  188411. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  188412. png_free(png_ptr, png_ptr->hist);
  188413. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  188414. #endif
  188415. #endif
  188416. #if defined(PNG_READ_GAMMA_SUPPORTED)
  188417. if (png_ptr->gamma_16_table != NULL)
  188418. {
  188419. int i;
  188420. int istop = (1 << (8 - png_ptr->gamma_shift));
  188421. for (i = 0; i < istop; i++)
  188422. {
  188423. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  188424. }
  188425. png_free(png_ptr, png_ptr->gamma_16_table);
  188426. }
  188427. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  188428. if (png_ptr->gamma_16_from_1 != NULL)
  188429. {
  188430. int i;
  188431. int istop = (1 << (8 - png_ptr->gamma_shift));
  188432. for (i = 0; i < istop; i++)
  188433. {
  188434. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  188435. }
  188436. png_free(png_ptr, png_ptr->gamma_16_from_1);
  188437. }
  188438. if (png_ptr->gamma_16_to_1 != NULL)
  188439. {
  188440. int i;
  188441. int istop = (1 << (8 - png_ptr->gamma_shift));
  188442. for (i = 0; i < istop; i++)
  188443. {
  188444. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  188445. }
  188446. png_free(png_ptr, png_ptr->gamma_16_to_1);
  188447. }
  188448. #endif
  188449. #endif
  188450. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  188451. png_free(png_ptr, png_ptr->time_buffer);
  188452. #endif
  188453. inflateEnd(&png_ptr->zstream);
  188454. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188455. png_free(png_ptr, png_ptr->save_buffer);
  188456. #endif
  188457. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188458. #ifdef PNG_TEXT_SUPPORTED
  188459. png_free(png_ptr, png_ptr->current_text);
  188460. #endif /* PNG_TEXT_SUPPORTED */
  188461. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  188462. /* Save the important info out of the png_struct, in case it is
  188463. * being used again.
  188464. */
  188465. #ifdef PNG_SETJMP_SUPPORTED
  188466. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188467. #endif
  188468. error_fn = png_ptr->error_fn;
  188469. warning_fn = png_ptr->warning_fn;
  188470. error_ptr = png_ptr->error_ptr;
  188471. #ifdef PNG_USER_MEM_SUPPORTED
  188472. free_fn = png_ptr->free_fn;
  188473. #endif
  188474. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188475. png_ptr->error_fn = error_fn;
  188476. png_ptr->warning_fn = warning_fn;
  188477. png_ptr->error_ptr = error_ptr;
  188478. #ifdef PNG_USER_MEM_SUPPORTED
  188479. png_ptr->free_fn = free_fn;
  188480. #endif
  188481. #ifdef PNG_SETJMP_SUPPORTED
  188482. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188483. #endif
  188484. }
  188485. void PNGAPI
  188486. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  188487. {
  188488. if(png_ptr == NULL) return;
  188489. png_ptr->read_row_fn = read_row_fn;
  188490. }
  188491. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188492. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  188493. void PNGAPI
  188494. png_read_png(png_structp png_ptr, png_infop info_ptr,
  188495. int transforms,
  188496. voidp params)
  188497. {
  188498. int row;
  188499. if(png_ptr == NULL) return;
  188500. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  188501. /* invert the alpha channel from opacity to transparency
  188502. */
  188503. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  188504. png_set_invert_alpha(png_ptr);
  188505. #endif
  188506. /* png_read_info() gives us all of the information from the
  188507. * PNG file before the first IDAT (image data chunk).
  188508. */
  188509. png_read_info(png_ptr, info_ptr);
  188510. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  188511. png_error(png_ptr,"Image is too high to process with png_read_png()");
  188512. /* -------------- image transformations start here ------------------- */
  188513. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  188514. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  188515. */
  188516. if (transforms & PNG_TRANSFORM_STRIP_16)
  188517. png_set_strip_16(png_ptr);
  188518. #endif
  188519. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  188520. /* Strip alpha bytes from the input data without combining with
  188521. * the background (not recommended).
  188522. */
  188523. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  188524. png_set_strip_alpha(png_ptr);
  188525. #endif
  188526. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  188527. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  188528. * byte into separate bytes (useful for paletted and grayscale images).
  188529. */
  188530. if (transforms & PNG_TRANSFORM_PACKING)
  188531. png_set_packing(png_ptr);
  188532. #endif
  188533. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  188534. /* Change the order of packed pixels to least significant bit first
  188535. * (not useful if you are using png_set_packing).
  188536. */
  188537. if (transforms & PNG_TRANSFORM_PACKSWAP)
  188538. png_set_packswap(png_ptr);
  188539. #endif
  188540. #if defined(PNG_READ_EXPAND_SUPPORTED)
  188541. /* Expand paletted colors into true RGB triplets
  188542. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  188543. * Expand paletted or RGB images with transparency to full alpha
  188544. * channels so the data will be available as RGBA quartets.
  188545. */
  188546. if (transforms & PNG_TRANSFORM_EXPAND)
  188547. if ((png_ptr->bit_depth < 8) ||
  188548. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  188549. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  188550. png_set_expand(png_ptr);
  188551. #endif
  188552. /* We don't handle background color or gamma transformation or dithering.
  188553. */
  188554. #if defined(PNG_READ_INVERT_SUPPORTED)
  188555. /* invert monochrome files to have 0 as white and 1 as black
  188556. */
  188557. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  188558. png_set_invert_mono(png_ptr);
  188559. #endif
  188560. #if defined(PNG_READ_SHIFT_SUPPORTED)
  188561. /* If you want to shift the pixel values from the range [0,255] or
  188562. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  188563. * colors were originally in:
  188564. */
  188565. if ((transforms & PNG_TRANSFORM_SHIFT)
  188566. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  188567. {
  188568. png_color_8p sig_bit;
  188569. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  188570. png_set_shift(png_ptr, sig_bit);
  188571. }
  188572. #endif
  188573. #if defined(PNG_READ_BGR_SUPPORTED)
  188574. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  188575. */
  188576. if (transforms & PNG_TRANSFORM_BGR)
  188577. png_set_bgr(png_ptr);
  188578. #endif
  188579. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  188580. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  188581. */
  188582. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  188583. png_set_swap_alpha(png_ptr);
  188584. #endif
  188585. #if defined(PNG_READ_SWAP_SUPPORTED)
  188586. /* swap bytes of 16 bit files to least significant byte first
  188587. */
  188588. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  188589. png_set_swap(png_ptr);
  188590. #endif
  188591. /* We don't handle adding filler bytes */
  188592. /* Optional call to gamma correct and add the background to the palette
  188593. * and update info structure. REQUIRED if you are expecting libpng to
  188594. * update the palette for you (i.e., you selected such a transform above).
  188595. */
  188596. png_read_update_info(png_ptr, info_ptr);
  188597. /* -------------- image transformations end here ------------------- */
  188598. #ifdef PNG_FREE_ME_SUPPORTED
  188599. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  188600. #endif
  188601. if(info_ptr->row_pointers == NULL)
  188602. {
  188603. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  188604. info_ptr->height * png_sizeof(png_bytep));
  188605. #ifdef PNG_FREE_ME_SUPPORTED
  188606. info_ptr->free_me |= PNG_FREE_ROWS;
  188607. #endif
  188608. for (row = 0; row < (int)info_ptr->height; row++)
  188609. {
  188610. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  188611. png_get_rowbytes(png_ptr, info_ptr));
  188612. }
  188613. }
  188614. png_read_image(png_ptr, info_ptr->row_pointers);
  188615. info_ptr->valid |= PNG_INFO_IDAT;
  188616. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  188617. png_read_end(png_ptr, info_ptr);
  188618. transforms = transforms; /* quiet compiler warnings */
  188619. params = params;
  188620. }
  188621. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  188622. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188623. #endif /* PNG_READ_SUPPORTED */
  188624. /*** End of inlined file: pngread.c ***/
  188625. /*** Start of inlined file: pngpread.c ***/
  188626. /* pngpread.c - read a png file in push mode
  188627. *
  188628. * Last changed in libpng 1.2.21 October 4, 2007
  188629. * For conditions of distribution and use, see copyright notice in png.h
  188630. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188631. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188632. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188633. */
  188634. #define PNG_INTERNAL
  188635. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  188636. /* push model modes */
  188637. #define PNG_READ_SIG_MODE 0
  188638. #define PNG_READ_CHUNK_MODE 1
  188639. #define PNG_READ_IDAT_MODE 2
  188640. #define PNG_SKIP_MODE 3
  188641. #define PNG_READ_tEXt_MODE 4
  188642. #define PNG_READ_zTXt_MODE 5
  188643. #define PNG_READ_DONE_MODE 6
  188644. #define PNG_READ_iTXt_MODE 7
  188645. #define PNG_ERROR_MODE 8
  188646. void PNGAPI
  188647. png_process_data(png_structp png_ptr, png_infop info_ptr,
  188648. png_bytep buffer, png_size_t buffer_size)
  188649. {
  188650. if(png_ptr == NULL) return;
  188651. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  188652. while (png_ptr->buffer_size)
  188653. {
  188654. png_process_some_data(png_ptr, info_ptr);
  188655. }
  188656. }
  188657. /* What we do with the incoming data depends on what we were previously
  188658. * doing before we ran out of data...
  188659. */
  188660. void /* PRIVATE */
  188661. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  188662. {
  188663. if(png_ptr == NULL) return;
  188664. switch (png_ptr->process_mode)
  188665. {
  188666. case PNG_READ_SIG_MODE:
  188667. {
  188668. png_push_read_sig(png_ptr, info_ptr);
  188669. break;
  188670. }
  188671. case PNG_READ_CHUNK_MODE:
  188672. {
  188673. png_push_read_chunk(png_ptr, info_ptr);
  188674. break;
  188675. }
  188676. case PNG_READ_IDAT_MODE:
  188677. {
  188678. png_push_read_IDAT(png_ptr);
  188679. break;
  188680. }
  188681. #if defined(PNG_READ_tEXt_SUPPORTED)
  188682. case PNG_READ_tEXt_MODE:
  188683. {
  188684. png_push_read_tEXt(png_ptr, info_ptr);
  188685. break;
  188686. }
  188687. #endif
  188688. #if defined(PNG_READ_zTXt_SUPPORTED)
  188689. case PNG_READ_zTXt_MODE:
  188690. {
  188691. png_push_read_zTXt(png_ptr, info_ptr);
  188692. break;
  188693. }
  188694. #endif
  188695. #if defined(PNG_READ_iTXt_SUPPORTED)
  188696. case PNG_READ_iTXt_MODE:
  188697. {
  188698. png_push_read_iTXt(png_ptr, info_ptr);
  188699. break;
  188700. }
  188701. #endif
  188702. case PNG_SKIP_MODE:
  188703. {
  188704. png_push_crc_finish(png_ptr);
  188705. break;
  188706. }
  188707. default:
  188708. {
  188709. png_ptr->buffer_size = 0;
  188710. break;
  188711. }
  188712. }
  188713. }
  188714. /* Read any remaining signature bytes from the stream and compare them with
  188715. * the correct PNG signature. It is possible that this routine is called
  188716. * with bytes already read from the signature, either because they have been
  188717. * checked by the calling application, or because of multiple calls to this
  188718. * routine.
  188719. */
  188720. void /* PRIVATE */
  188721. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  188722. {
  188723. png_size_t num_checked = png_ptr->sig_bytes,
  188724. num_to_check = 8 - num_checked;
  188725. if (png_ptr->buffer_size < num_to_check)
  188726. {
  188727. num_to_check = png_ptr->buffer_size;
  188728. }
  188729. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  188730. num_to_check);
  188731. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  188732. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188733. {
  188734. if (num_checked < 4 &&
  188735. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188736. png_error(png_ptr, "Not a PNG file");
  188737. else
  188738. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188739. }
  188740. else
  188741. {
  188742. if (png_ptr->sig_bytes >= 8)
  188743. {
  188744. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  188745. }
  188746. }
  188747. }
  188748. void /* PRIVATE */
  188749. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  188750. {
  188751. #ifdef PNG_USE_LOCAL_ARRAYS
  188752. PNG_CONST PNG_IHDR;
  188753. PNG_CONST PNG_IDAT;
  188754. PNG_CONST PNG_IEND;
  188755. PNG_CONST PNG_PLTE;
  188756. #if defined(PNG_READ_bKGD_SUPPORTED)
  188757. PNG_CONST PNG_bKGD;
  188758. #endif
  188759. #if defined(PNG_READ_cHRM_SUPPORTED)
  188760. PNG_CONST PNG_cHRM;
  188761. #endif
  188762. #if defined(PNG_READ_gAMA_SUPPORTED)
  188763. PNG_CONST PNG_gAMA;
  188764. #endif
  188765. #if defined(PNG_READ_hIST_SUPPORTED)
  188766. PNG_CONST PNG_hIST;
  188767. #endif
  188768. #if defined(PNG_READ_iCCP_SUPPORTED)
  188769. PNG_CONST PNG_iCCP;
  188770. #endif
  188771. #if defined(PNG_READ_iTXt_SUPPORTED)
  188772. PNG_CONST PNG_iTXt;
  188773. #endif
  188774. #if defined(PNG_READ_oFFs_SUPPORTED)
  188775. PNG_CONST PNG_oFFs;
  188776. #endif
  188777. #if defined(PNG_READ_pCAL_SUPPORTED)
  188778. PNG_CONST PNG_pCAL;
  188779. #endif
  188780. #if defined(PNG_READ_pHYs_SUPPORTED)
  188781. PNG_CONST PNG_pHYs;
  188782. #endif
  188783. #if defined(PNG_READ_sBIT_SUPPORTED)
  188784. PNG_CONST PNG_sBIT;
  188785. #endif
  188786. #if defined(PNG_READ_sCAL_SUPPORTED)
  188787. PNG_CONST PNG_sCAL;
  188788. #endif
  188789. #if defined(PNG_READ_sRGB_SUPPORTED)
  188790. PNG_CONST PNG_sRGB;
  188791. #endif
  188792. #if defined(PNG_READ_sPLT_SUPPORTED)
  188793. PNG_CONST PNG_sPLT;
  188794. #endif
  188795. #if defined(PNG_READ_tEXt_SUPPORTED)
  188796. PNG_CONST PNG_tEXt;
  188797. #endif
  188798. #if defined(PNG_READ_tIME_SUPPORTED)
  188799. PNG_CONST PNG_tIME;
  188800. #endif
  188801. #if defined(PNG_READ_tRNS_SUPPORTED)
  188802. PNG_CONST PNG_tRNS;
  188803. #endif
  188804. #if defined(PNG_READ_zTXt_SUPPORTED)
  188805. PNG_CONST PNG_zTXt;
  188806. #endif
  188807. #endif /* PNG_USE_LOCAL_ARRAYS */
  188808. /* First we make sure we have enough data for the 4 byte chunk name
  188809. * and the 4 byte chunk length before proceeding with decoding the
  188810. * chunk data. To fully decode each of these chunks, we also make
  188811. * sure we have enough data in the buffer for the 4 byte CRC at the
  188812. * end of every chunk (except IDAT, which is handled separately).
  188813. */
  188814. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  188815. {
  188816. png_byte chunk_length[4];
  188817. if (png_ptr->buffer_size < 8)
  188818. {
  188819. png_push_save_buffer(png_ptr);
  188820. return;
  188821. }
  188822. png_push_fill_buffer(png_ptr, chunk_length, 4);
  188823. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  188824. png_reset_crc(png_ptr);
  188825. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188826. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  188827. }
  188828. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188829. if(png_ptr->mode & PNG_AFTER_IDAT)
  188830. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188831. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188832. {
  188833. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188834. {
  188835. png_push_save_buffer(png_ptr);
  188836. return;
  188837. }
  188838. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  188839. }
  188840. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188841. {
  188842. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188843. {
  188844. png_push_save_buffer(png_ptr);
  188845. return;
  188846. }
  188847. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  188848. png_ptr->process_mode = PNG_READ_DONE_MODE;
  188849. png_push_have_end(png_ptr, info_ptr);
  188850. }
  188851. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188852. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188853. {
  188854. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188855. {
  188856. png_push_save_buffer(png_ptr);
  188857. return;
  188858. }
  188859. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188860. png_ptr->mode |= PNG_HAVE_IDAT;
  188861. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  188862. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188863. png_ptr->mode |= PNG_HAVE_PLTE;
  188864. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188865. {
  188866. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188867. png_error(png_ptr, "Missing IHDR before IDAT");
  188868. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188869. !(png_ptr->mode & PNG_HAVE_PLTE))
  188870. png_error(png_ptr, "Missing PLTE before IDAT");
  188871. }
  188872. }
  188873. #endif
  188874. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188875. {
  188876. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188877. {
  188878. png_push_save_buffer(png_ptr);
  188879. return;
  188880. }
  188881. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  188882. }
  188883. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188884. {
  188885. /* If we reach an IDAT chunk, this means we have read all of the
  188886. * header chunks, and we can start reading the image (or if this
  188887. * is called after the image has been read - we have an error).
  188888. */
  188889. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188890. png_error(png_ptr, "Missing IHDR before IDAT");
  188891. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188892. !(png_ptr->mode & PNG_HAVE_PLTE))
  188893. png_error(png_ptr, "Missing PLTE before IDAT");
  188894. if (png_ptr->mode & PNG_HAVE_IDAT)
  188895. {
  188896. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188897. if (png_ptr->push_length == 0)
  188898. return;
  188899. if (png_ptr->mode & PNG_AFTER_IDAT)
  188900. png_error(png_ptr, "Too many IDAT's found");
  188901. }
  188902. png_ptr->idat_size = png_ptr->push_length;
  188903. png_ptr->mode |= PNG_HAVE_IDAT;
  188904. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  188905. png_push_have_info(png_ptr, info_ptr);
  188906. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188907. png_ptr->zstream.next_out = png_ptr->row_buf;
  188908. return;
  188909. }
  188910. #if defined(PNG_READ_gAMA_SUPPORTED)
  188911. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188912. {
  188913. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188914. {
  188915. png_push_save_buffer(png_ptr);
  188916. return;
  188917. }
  188918. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  188919. }
  188920. #endif
  188921. #if defined(PNG_READ_sBIT_SUPPORTED)
  188922. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188923. {
  188924. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188925. {
  188926. png_push_save_buffer(png_ptr);
  188927. return;
  188928. }
  188929. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  188930. }
  188931. #endif
  188932. #if defined(PNG_READ_cHRM_SUPPORTED)
  188933. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188934. {
  188935. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188936. {
  188937. png_push_save_buffer(png_ptr);
  188938. return;
  188939. }
  188940. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  188941. }
  188942. #endif
  188943. #if defined(PNG_READ_sRGB_SUPPORTED)
  188944. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188945. {
  188946. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188947. {
  188948. png_push_save_buffer(png_ptr);
  188949. return;
  188950. }
  188951. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  188952. }
  188953. #endif
  188954. #if defined(PNG_READ_iCCP_SUPPORTED)
  188955. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188956. {
  188957. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188958. {
  188959. png_push_save_buffer(png_ptr);
  188960. return;
  188961. }
  188962. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  188963. }
  188964. #endif
  188965. #if defined(PNG_READ_sPLT_SUPPORTED)
  188966. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188967. {
  188968. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188969. {
  188970. png_push_save_buffer(png_ptr);
  188971. return;
  188972. }
  188973. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  188974. }
  188975. #endif
  188976. #if defined(PNG_READ_tRNS_SUPPORTED)
  188977. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188978. {
  188979. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188980. {
  188981. png_push_save_buffer(png_ptr);
  188982. return;
  188983. }
  188984. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  188985. }
  188986. #endif
  188987. #if defined(PNG_READ_bKGD_SUPPORTED)
  188988. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188989. {
  188990. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  188991. {
  188992. png_push_save_buffer(png_ptr);
  188993. return;
  188994. }
  188995. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  188996. }
  188997. #endif
  188998. #if defined(PNG_READ_hIST_SUPPORTED)
  188999. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  189000. {
  189001. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189002. {
  189003. png_push_save_buffer(png_ptr);
  189004. return;
  189005. }
  189006. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  189007. }
  189008. #endif
  189009. #if defined(PNG_READ_pHYs_SUPPORTED)
  189010. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  189011. {
  189012. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189013. {
  189014. png_push_save_buffer(png_ptr);
  189015. return;
  189016. }
  189017. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  189018. }
  189019. #endif
  189020. #if defined(PNG_READ_oFFs_SUPPORTED)
  189021. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  189022. {
  189023. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189024. {
  189025. png_push_save_buffer(png_ptr);
  189026. return;
  189027. }
  189028. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  189029. }
  189030. #endif
  189031. #if defined(PNG_READ_pCAL_SUPPORTED)
  189032. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  189033. {
  189034. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189035. {
  189036. png_push_save_buffer(png_ptr);
  189037. return;
  189038. }
  189039. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189040. }
  189041. #endif
  189042. #if defined(PNG_READ_sCAL_SUPPORTED)
  189043. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189044. {
  189045. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189046. {
  189047. png_push_save_buffer(png_ptr);
  189048. return;
  189049. }
  189050. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189051. }
  189052. #endif
  189053. #if defined(PNG_READ_tIME_SUPPORTED)
  189054. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189055. {
  189056. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189057. {
  189058. png_push_save_buffer(png_ptr);
  189059. return;
  189060. }
  189061. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189062. }
  189063. #endif
  189064. #if defined(PNG_READ_tEXt_SUPPORTED)
  189065. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189066. {
  189067. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189068. {
  189069. png_push_save_buffer(png_ptr);
  189070. return;
  189071. }
  189072. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189073. }
  189074. #endif
  189075. #if defined(PNG_READ_zTXt_SUPPORTED)
  189076. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189077. {
  189078. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189079. {
  189080. png_push_save_buffer(png_ptr);
  189081. return;
  189082. }
  189083. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189084. }
  189085. #endif
  189086. #if defined(PNG_READ_iTXt_SUPPORTED)
  189087. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189088. {
  189089. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189090. {
  189091. png_push_save_buffer(png_ptr);
  189092. return;
  189093. }
  189094. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189095. }
  189096. #endif
  189097. else
  189098. {
  189099. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189100. {
  189101. png_push_save_buffer(png_ptr);
  189102. return;
  189103. }
  189104. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189105. }
  189106. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189107. }
  189108. void /* PRIVATE */
  189109. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189110. {
  189111. png_ptr->process_mode = PNG_SKIP_MODE;
  189112. png_ptr->skip_length = skip;
  189113. }
  189114. void /* PRIVATE */
  189115. png_push_crc_finish(png_structp png_ptr)
  189116. {
  189117. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189118. {
  189119. png_size_t save_size;
  189120. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189121. save_size = (png_size_t)png_ptr->skip_length;
  189122. else
  189123. save_size = png_ptr->save_buffer_size;
  189124. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189125. png_ptr->skip_length -= save_size;
  189126. png_ptr->buffer_size -= save_size;
  189127. png_ptr->save_buffer_size -= save_size;
  189128. png_ptr->save_buffer_ptr += save_size;
  189129. }
  189130. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189131. {
  189132. png_size_t save_size;
  189133. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189134. save_size = (png_size_t)png_ptr->skip_length;
  189135. else
  189136. save_size = png_ptr->current_buffer_size;
  189137. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189138. png_ptr->skip_length -= save_size;
  189139. png_ptr->buffer_size -= save_size;
  189140. png_ptr->current_buffer_size -= save_size;
  189141. png_ptr->current_buffer_ptr += save_size;
  189142. }
  189143. if (!png_ptr->skip_length)
  189144. {
  189145. if (png_ptr->buffer_size < 4)
  189146. {
  189147. png_push_save_buffer(png_ptr);
  189148. return;
  189149. }
  189150. png_crc_finish(png_ptr, 0);
  189151. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189152. }
  189153. }
  189154. void PNGAPI
  189155. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189156. {
  189157. png_bytep ptr;
  189158. if(png_ptr == NULL) return;
  189159. ptr = buffer;
  189160. if (png_ptr->save_buffer_size)
  189161. {
  189162. png_size_t save_size;
  189163. if (length < png_ptr->save_buffer_size)
  189164. save_size = length;
  189165. else
  189166. save_size = png_ptr->save_buffer_size;
  189167. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189168. length -= save_size;
  189169. ptr += save_size;
  189170. png_ptr->buffer_size -= save_size;
  189171. png_ptr->save_buffer_size -= save_size;
  189172. png_ptr->save_buffer_ptr += save_size;
  189173. }
  189174. if (length && png_ptr->current_buffer_size)
  189175. {
  189176. png_size_t save_size;
  189177. if (length < png_ptr->current_buffer_size)
  189178. save_size = length;
  189179. else
  189180. save_size = png_ptr->current_buffer_size;
  189181. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189182. png_ptr->buffer_size -= save_size;
  189183. png_ptr->current_buffer_size -= save_size;
  189184. png_ptr->current_buffer_ptr += save_size;
  189185. }
  189186. }
  189187. void /* PRIVATE */
  189188. png_push_save_buffer(png_structp png_ptr)
  189189. {
  189190. if (png_ptr->save_buffer_size)
  189191. {
  189192. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189193. {
  189194. png_size_t i,istop;
  189195. png_bytep sp;
  189196. png_bytep dp;
  189197. istop = png_ptr->save_buffer_size;
  189198. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189199. i < istop; i++, sp++, dp++)
  189200. {
  189201. *dp = *sp;
  189202. }
  189203. }
  189204. }
  189205. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189206. png_ptr->save_buffer_max)
  189207. {
  189208. png_size_t new_max;
  189209. png_bytep old_buffer;
  189210. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189211. (png_ptr->current_buffer_size + 256))
  189212. {
  189213. png_error(png_ptr, "Potential overflow of save_buffer");
  189214. }
  189215. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189216. old_buffer = png_ptr->save_buffer;
  189217. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189218. (png_uint_32)new_max);
  189219. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189220. png_free(png_ptr, old_buffer);
  189221. png_ptr->save_buffer_max = new_max;
  189222. }
  189223. if (png_ptr->current_buffer_size)
  189224. {
  189225. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189226. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189227. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189228. png_ptr->current_buffer_size = 0;
  189229. }
  189230. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189231. png_ptr->buffer_size = 0;
  189232. }
  189233. void /* PRIVATE */
  189234. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189235. png_size_t buffer_length)
  189236. {
  189237. png_ptr->current_buffer = buffer;
  189238. png_ptr->current_buffer_size = buffer_length;
  189239. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189240. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189241. }
  189242. void /* PRIVATE */
  189243. png_push_read_IDAT(png_structp png_ptr)
  189244. {
  189245. #ifdef PNG_USE_LOCAL_ARRAYS
  189246. PNG_CONST PNG_IDAT;
  189247. #endif
  189248. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189249. {
  189250. png_byte chunk_length[4];
  189251. if (png_ptr->buffer_size < 8)
  189252. {
  189253. png_push_save_buffer(png_ptr);
  189254. return;
  189255. }
  189256. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189257. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189258. png_reset_crc(png_ptr);
  189259. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189260. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189261. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189262. {
  189263. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189264. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189265. png_error(png_ptr, "Not enough compressed data");
  189266. return;
  189267. }
  189268. png_ptr->idat_size = png_ptr->push_length;
  189269. }
  189270. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189271. {
  189272. png_size_t save_size;
  189273. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189274. {
  189275. save_size = (png_size_t)png_ptr->idat_size;
  189276. /* check for overflow */
  189277. if((png_uint_32)save_size != png_ptr->idat_size)
  189278. png_error(png_ptr, "save_size overflowed in pngpread");
  189279. }
  189280. else
  189281. save_size = png_ptr->save_buffer_size;
  189282. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189283. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189284. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189285. png_ptr->idat_size -= save_size;
  189286. png_ptr->buffer_size -= save_size;
  189287. png_ptr->save_buffer_size -= save_size;
  189288. png_ptr->save_buffer_ptr += save_size;
  189289. }
  189290. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  189291. {
  189292. png_size_t save_size;
  189293. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  189294. {
  189295. save_size = (png_size_t)png_ptr->idat_size;
  189296. /* check for overflow */
  189297. if((png_uint_32)save_size != png_ptr->idat_size)
  189298. png_error(png_ptr, "save_size overflowed in pngpread");
  189299. }
  189300. else
  189301. save_size = png_ptr->current_buffer_size;
  189302. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189303. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189304. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189305. png_ptr->idat_size -= save_size;
  189306. png_ptr->buffer_size -= save_size;
  189307. png_ptr->current_buffer_size -= save_size;
  189308. png_ptr->current_buffer_ptr += save_size;
  189309. }
  189310. if (!png_ptr->idat_size)
  189311. {
  189312. if (png_ptr->buffer_size < 4)
  189313. {
  189314. png_push_save_buffer(png_ptr);
  189315. return;
  189316. }
  189317. png_crc_finish(png_ptr, 0);
  189318. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189319. png_ptr->mode |= PNG_AFTER_IDAT;
  189320. }
  189321. }
  189322. void /* PRIVATE */
  189323. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  189324. png_size_t buffer_length)
  189325. {
  189326. int ret;
  189327. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  189328. png_error(png_ptr, "Extra compression data");
  189329. png_ptr->zstream.next_in = buffer;
  189330. png_ptr->zstream.avail_in = (uInt)buffer_length;
  189331. for(;;)
  189332. {
  189333. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189334. if (ret != Z_OK)
  189335. {
  189336. if (ret == Z_STREAM_END)
  189337. {
  189338. if (png_ptr->zstream.avail_in)
  189339. png_error(png_ptr, "Extra compressed data");
  189340. if (!(png_ptr->zstream.avail_out))
  189341. {
  189342. png_push_process_row(png_ptr);
  189343. }
  189344. png_ptr->mode |= PNG_AFTER_IDAT;
  189345. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189346. break;
  189347. }
  189348. else if (ret == Z_BUF_ERROR)
  189349. break;
  189350. else
  189351. png_error(png_ptr, "Decompression Error");
  189352. }
  189353. if (!(png_ptr->zstream.avail_out))
  189354. {
  189355. if ((
  189356. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189357. png_ptr->interlaced && png_ptr->pass > 6) ||
  189358. (!png_ptr->interlaced &&
  189359. #endif
  189360. png_ptr->row_number == png_ptr->num_rows))
  189361. {
  189362. if (png_ptr->zstream.avail_in)
  189363. {
  189364. png_warning(png_ptr, "Too much data in IDAT chunks");
  189365. }
  189366. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  189367. break;
  189368. }
  189369. png_push_process_row(png_ptr);
  189370. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189371. png_ptr->zstream.next_out = png_ptr->row_buf;
  189372. }
  189373. else
  189374. break;
  189375. }
  189376. }
  189377. void /* PRIVATE */
  189378. png_push_process_row(png_structp png_ptr)
  189379. {
  189380. png_ptr->row_info.color_type = png_ptr->color_type;
  189381. png_ptr->row_info.width = png_ptr->iwidth;
  189382. png_ptr->row_info.channels = png_ptr->channels;
  189383. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  189384. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  189385. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  189386. png_ptr->row_info.width);
  189387. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  189388. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  189389. (int)(png_ptr->row_buf[0]));
  189390. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  189391. png_ptr->rowbytes + 1);
  189392. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  189393. png_do_read_transformations(png_ptr);
  189394. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  189395. /* blow up interlaced rows to full size */
  189396. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  189397. {
  189398. if (png_ptr->pass < 6)
  189399. /* old interface (pre-1.0.9):
  189400. png_do_read_interlace(&(png_ptr->row_info),
  189401. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  189402. */
  189403. png_do_read_interlace(png_ptr);
  189404. switch (png_ptr->pass)
  189405. {
  189406. case 0:
  189407. {
  189408. int i;
  189409. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  189410. {
  189411. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189412. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  189413. }
  189414. if (png_ptr->pass == 2) /* pass 1 might be empty */
  189415. {
  189416. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189417. {
  189418. png_push_have_row(png_ptr, png_bytep_NULL);
  189419. png_read_push_finish_row(png_ptr);
  189420. }
  189421. }
  189422. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  189423. {
  189424. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189425. {
  189426. png_push_have_row(png_ptr, png_bytep_NULL);
  189427. png_read_push_finish_row(png_ptr);
  189428. }
  189429. }
  189430. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  189431. {
  189432. png_push_have_row(png_ptr, png_bytep_NULL);
  189433. png_read_push_finish_row(png_ptr);
  189434. }
  189435. break;
  189436. }
  189437. case 1:
  189438. {
  189439. int i;
  189440. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  189441. {
  189442. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189443. png_read_push_finish_row(png_ptr);
  189444. }
  189445. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  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. }
  189453. break;
  189454. }
  189455. case 2:
  189456. {
  189457. int i;
  189458. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189459. {
  189460. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189461. png_read_push_finish_row(png_ptr);
  189462. }
  189463. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  189464. {
  189465. png_push_have_row(png_ptr, png_bytep_NULL);
  189466. png_read_push_finish_row(png_ptr);
  189467. }
  189468. if (png_ptr->pass == 4) /* pass 3 might be empty */
  189469. {
  189470. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189471. {
  189472. png_push_have_row(png_ptr, png_bytep_NULL);
  189473. png_read_push_finish_row(png_ptr);
  189474. }
  189475. }
  189476. break;
  189477. }
  189478. case 3:
  189479. {
  189480. int i;
  189481. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  189482. {
  189483. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189484. png_read_push_finish_row(png_ptr);
  189485. }
  189486. if (png_ptr->pass == 4) /* skip top two generated rows */
  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. }
  189494. break;
  189495. }
  189496. case 4:
  189497. {
  189498. int i;
  189499. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189500. {
  189501. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189502. png_read_push_finish_row(png_ptr);
  189503. }
  189504. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  189505. {
  189506. png_push_have_row(png_ptr, png_bytep_NULL);
  189507. png_read_push_finish_row(png_ptr);
  189508. }
  189509. if (png_ptr->pass == 6) /* pass 5 might be empty */
  189510. {
  189511. png_push_have_row(png_ptr, png_bytep_NULL);
  189512. png_read_push_finish_row(png_ptr);
  189513. }
  189514. break;
  189515. }
  189516. case 5:
  189517. {
  189518. int i;
  189519. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  189520. {
  189521. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189522. png_read_push_finish_row(png_ptr);
  189523. }
  189524. if (png_ptr->pass == 6) /* skip top generated row */
  189525. {
  189526. png_push_have_row(png_ptr, png_bytep_NULL);
  189527. png_read_push_finish_row(png_ptr);
  189528. }
  189529. break;
  189530. }
  189531. case 6:
  189532. {
  189533. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189534. png_read_push_finish_row(png_ptr);
  189535. if (png_ptr->pass != 6)
  189536. break;
  189537. png_push_have_row(png_ptr, png_bytep_NULL);
  189538. png_read_push_finish_row(png_ptr);
  189539. }
  189540. }
  189541. }
  189542. else
  189543. #endif
  189544. {
  189545. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  189546. png_read_push_finish_row(png_ptr);
  189547. }
  189548. }
  189549. void /* PRIVATE */
  189550. png_read_push_finish_row(png_structp png_ptr)
  189551. {
  189552. #ifdef PNG_USE_LOCAL_ARRAYS
  189553. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  189554. /* start of interlace block */
  189555. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  189556. /* offset to next interlace block */
  189557. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  189558. /* start of interlace block in the y direction */
  189559. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  189560. /* offset to next interlace block in the y direction */
  189561. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  189562. /* Height of interlace block. This is not currently used - if you need
  189563. * it, uncomment it here and in png.h
  189564. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  189565. */
  189566. #endif
  189567. png_ptr->row_number++;
  189568. if (png_ptr->row_number < png_ptr->num_rows)
  189569. return;
  189570. if (png_ptr->interlaced)
  189571. {
  189572. png_ptr->row_number = 0;
  189573. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  189574. png_ptr->rowbytes + 1);
  189575. do
  189576. {
  189577. png_ptr->pass++;
  189578. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  189579. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  189580. (png_ptr->pass == 5 && png_ptr->width < 2))
  189581. png_ptr->pass++;
  189582. if (png_ptr->pass > 7)
  189583. png_ptr->pass--;
  189584. if (png_ptr->pass >= 7)
  189585. break;
  189586. png_ptr->iwidth = (png_ptr->width +
  189587. png_pass_inc[png_ptr->pass] - 1 -
  189588. png_pass_start[png_ptr->pass]) /
  189589. png_pass_inc[png_ptr->pass];
  189590. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  189591. png_ptr->iwidth) + 1;
  189592. if (png_ptr->transformations & PNG_INTERLACE)
  189593. break;
  189594. png_ptr->num_rows = (png_ptr->height +
  189595. png_pass_yinc[png_ptr->pass] - 1 -
  189596. png_pass_ystart[png_ptr->pass]) /
  189597. png_pass_yinc[png_ptr->pass];
  189598. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  189599. }
  189600. }
  189601. #if defined(PNG_READ_tEXt_SUPPORTED)
  189602. void /* PRIVATE */
  189603. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189604. length)
  189605. {
  189606. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189607. {
  189608. png_error(png_ptr, "Out of place tEXt");
  189609. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189610. }
  189611. #ifdef PNG_MAX_MALLOC_64K
  189612. png_ptr->skip_length = 0; /* This may not be necessary */
  189613. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189614. {
  189615. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  189616. png_ptr->skip_length = length - (png_uint_32)65535L;
  189617. length = (png_uint_32)65535L;
  189618. }
  189619. #endif
  189620. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189621. (png_uint_32)(length+1));
  189622. png_ptr->current_text[length] = '\0';
  189623. png_ptr->current_text_ptr = png_ptr->current_text;
  189624. png_ptr->current_text_size = (png_size_t)length;
  189625. png_ptr->current_text_left = (png_size_t)length;
  189626. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  189627. }
  189628. void /* PRIVATE */
  189629. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  189630. {
  189631. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189632. {
  189633. png_size_t text_size;
  189634. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189635. text_size = png_ptr->buffer_size;
  189636. else
  189637. text_size = png_ptr->current_text_left;
  189638. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189639. png_ptr->current_text_left -= text_size;
  189640. png_ptr->current_text_ptr += text_size;
  189641. }
  189642. if (!(png_ptr->current_text_left))
  189643. {
  189644. png_textp text_ptr;
  189645. png_charp text;
  189646. png_charp key;
  189647. int ret;
  189648. if (png_ptr->buffer_size < 4)
  189649. {
  189650. png_push_save_buffer(png_ptr);
  189651. return;
  189652. }
  189653. png_push_crc_finish(png_ptr);
  189654. #if defined(PNG_MAX_MALLOC_64K)
  189655. if (png_ptr->skip_length)
  189656. return;
  189657. #endif
  189658. key = png_ptr->current_text;
  189659. for (text = key; *text; text++)
  189660. /* empty loop */ ;
  189661. if (text < key + png_ptr->current_text_size)
  189662. text++;
  189663. text_ptr = (png_textp)png_malloc(png_ptr,
  189664. (png_uint_32)png_sizeof(png_text));
  189665. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  189666. text_ptr->key = key;
  189667. #ifdef PNG_iTXt_SUPPORTED
  189668. text_ptr->lang = NULL;
  189669. text_ptr->lang_key = NULL;
  189670. #endif
  189671. text_ptr->text = text;
  189672. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189673. png_free(png_ptr, key);
  189674. png_free(png_ptr, text_ptr);
  189675. png_ptr->current_text = NULL;
  189676. if (ret)
  189677. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189678. }
  189679. }
  189680. #endif
  189681. #if defined(PNG_READ_zTXt_SUPPORTED)
  189682. void /* PRIVATE */
  189683. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189684. length)
  189685. {
  189686. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189687. {
  189688. png_error(png_ptr, "Out of place zTXt");
  189689. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189690. }
  189691. #ifdef PNG_MAX_MALLOC_64K
  189692. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  189693. * to be able to store the uncompressed data. Actually, the threshold
  189694. * is probably around 32K, but it isn't as definite as 64K is.
  189695. */
  189696. if (length > (png_uint_32)65535L)
  189697. {
  189698. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  189699. png_push_crc_skip(png_ptr, length);
  189700. return;
  189701. }
  189702. #endif
  189703. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189704. (png_uint_32)(length+1));
  189705. png_ptr->current_text[length] = '\0';
  189706. png_ptr->current_text_ptr = png_ptr->current_text;
  189707. png_ptr->current_text_size = (png_size_t)length;
  189708. png_ptr->current_text_left = (png_size_t)length;
  189709. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  189710. }
  189711. void /* PRIVATE */
  189712. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  189713. {
  189714. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189715. {
  189716. png_size_t text_size;
  189717. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  189718. text_size = png_ptr->buffer_size;
  189719. else
  189720. text_size = png_ptr->current_text_left;
  189721. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189722. png_ptr->current_text_left -= text_size;
  189723. png_ptr->current_text_ptr += text_size;
  189724. }
  189725. if (!(png_ptr->current_text_left))
  189726. {
  189727. png_textp text_ptr;
  189728. png_charp text;
  189729. png_charp key;
  189730. int ret;
  189731. png_size_t text_size, key_size;
  189732. if (png_ptr->buffer_size < 4)
  189733. {
  189734. png_push_save_buffer(png_ptr);
  189735. return;
  189736. }
  189737. png_push_crc_finish(png_ptr);
  189738. key = png_ptr->current_text;
  189739. for (text = key; *text; text++)
  189740. /* empty loop */ ;
  189741. /* zTXt can't have zero text */
  189742. if (text >= key + png_ptr->current_text_size)
  189743. {
  189744. png_ptr->current_text = NULL;
  189745. png_free(png_ptr, key);
  189746. return;
  189747. }
  189748. text++;
  189749. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  189750. {
  189751. png_ptr->current_text = NULL;
  189752. png_free(png_ptr, key);
  189753. return;
  189754. }
  189755. text++;
  189756. png_ptr->zstream.next_in = (png_bytep )text;
  189757. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  189758. (text - key));
  189759. png_ptr->zstream.next_out = png_ptr->zbuf;
  189760. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189761. key_size = text - key;
  189762. text_size = 0;
  189763. text = NULL;
  189764. ret = Z_STREAM_END;
  189765. while (png_ptr->zstream.avail_in)
  189766. {
  189767. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  189768. if (ret != Z_OK && ret != Z_STREAM_END)
  189769. {
  189770. inflateReset(&png_ptr->zstream);
  189771. png_ptr->zstream.avail_in = 0;
  189772. png_ptr->current_text = NULL;
  189773. png_free(png_ptr, key);
  189774. png_free(png_ptr, text);
  189775. return;
  189776. }
  189777. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  189778. {
  189779. if (text == NULL)
  189780. {
  189781. text = (png_charp)png_malloc(png_ptr,
  189782. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189783. + key_size + 1));
  189784. png_memcpy(text + key_size, png_ptr->zbuf,
  189785. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189786. png_memcpy(text, key, key_size);
  189787. text_size = key_size + png_ptr->zbuf_size -
  189788. png_ptr->zstream.avail_out;
  189789. *(text + text_size) = '\0';
  189790. }
  189791. else
  189792. {
  189793. png_charp tmp;
  189794. tmp = text;
  189795. text = (png_charp)png_malloc(png_ptr, text_size +
  189796. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  189797. + 1));
  189798. png_memcpy(text, tmp, text_size);
  189799. png_free(png_ptr, tmp);
  189800. png_memcpy(text + text_size, png_ptr->zbuf,
  189801. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  189802. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  189803. *(text + text_size) = '\0';
  189804. }
  189805. if (ret != Z_STREAM_END)
  189806. {
  189807. png_ptr->zstream.next_out = png_ptr->zbuf;
  189808. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  189809. }
  189810. }
  189811. else
  189812. {
  189813. break;
  189814. }
  189815. if (ret == Z_STREAM_END)
  189816. break;
  189817. }
  189818. inflateReset(&png_ptr->zstream);
  189819. png_ptr->zstream.avail_in = 0;
  189820. if (ret != Z_STREAM_END)
  189821. {
  189822. png_ptr->current_text = NULL;
  189823. png_free(png_ptr, key);
  189824. png_free(png_ptr, text);
  189825. return;
  189826. }
  189827. png_ptr->current_text = NULL;
  189828. png_free(png_ptr, key);
  189829. key = text;
  189830. text += key_size;
  189831. text_ptr = (png_textp)png_malloc(png_ptr,
  189832. (png_uint_32)png_sizeof(png_text));
  189833. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  189834. text_ptr->key = key;
  189835. #ifdef PNG_iTXt_SUPPORTED
  189836. text_ptr->lang = NULL;
  189837. text_ptr->lang_key = NULL;
  189838. #endif
  189839. text_ptr->text = text;
  189840. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189841. png_free(png_ptr, key);
  189842. png_free(png_ptr, text_ptr);
  189843. if (ret)
  189844. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  189845. }
  189846. }
  189847. #endif
  189848. #if defined(PNG_READ_iTXt_SUPPORTED)
  189849. void /* PRIVATE */
  189850. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189851. length)
  189852. {
  189853. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  189854. {
  189855. png_error(png_ptr, "Out of place iTXt");
  189856. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189857. }
  189858. #ifdef PNG_MAX_MALLOC_64K
  189859. png_ptr->skip_length = 0; /* This may not be necessary */
  189860. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  189861. {
  189862. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  189863. png_ptr->skip_length = length - (png_uint_32)65535L;
  189864. length = (png_uint_32)65535L;
  189865. }
  189866. #endif
  189867. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  189868. (png_uint_32)(length+1));
  189869. png_ptr->current_text[length] = '\0';
  189870. png_ptr->current_text_ptr = png_ptr->current_text;
  189871. png_ptr->current_text_size = (png_size_t)length;
  189872. png_ptr->current_text_left = (png_size_t)length;
  189873. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  189874. }
  189875. void /* PRIVATE */
  189876. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  189877. {
  189878. if (png_ptr->buffer_size && png_ptr->current_text_left)
  189879. {
  189880. png_size_t text_size;
  189881. if (png_ptr->buffer_size < png_ptr->current_text_left)
  189882. text_size = png_ptr->buffer_size;
  189883. else
  189884. text_size = png_ptr->current_text_left;
  189885. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  189886. png_ptr->current_text_left -= text_size;
  189887. png_ptr->current_text_ptr += text_size;
  189888. }
  189889. if (!(png_ptr->current_text_left))
  189890. {
  189891. png_textp text_ptr;
  189892. png_charp key;
  189893. int comp_flag;
  189894. png_charp lang;
  189895. png_charp lang_key;
  189896. png_charp text;
  189897. int ret;
  189898. if (png_ptr->buffer_size < 4)
  189899. {
  189900. png_push_save_buffer(png_ptr);
  189901. return;
  189902. }
  189903. png_push_crc_finish(png_ptr);
  189904. #if defined(PNG_MAX_MALLOC_64K)
  189905. if (png_ptr->skip_length)
  189906. return;
  189907. #endif
  189908. key = png_ptr->current_text;
  189909. for (lang = key; *lang; lang++)
  189910. /* empty loop */ ;
  189911. if (lang < key + png_ptr->current_text_size - 3)
  189912. lang++;
  189913. comp_flag = *lang++;
  189914. lang++; /* skip comp_type, always zero */
  189915. for (lang_key = lang; *lang_key; lang_key++)
  189916. /* empty loop */ ;
  189917. lang_key++; /* skip NUL separator */
  189918. text=lang_key;
  189919. if (lang_key < key + png_ptr->current_text_size - 1)
  189920. {
  189921. for (; *text; text++)
  189922. /* empty loop */ ;
  189923. }
  189924. if (text < key + png_ptr->current_text_size)
  189925. text++;
  189926. text_ptr = (png_textp)png_malloc(png_ptr,
  189927. (png_uint_32)png_sizeof(png_text));
  189928. text_ptr->compression = comp_flag + 2;
  189929. text_ptr->key = key;
  189930. text_ptr->lang = lang;
  189931. text_ptr->lang_key = lang_key;
  189932. text_ptr->text = text;
  189933. text_ptr->text_length = 0;
  189934. text_ptr->itxt_length = png_strlen(text);
  189935. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  189936. png_ptr->current_text = NULL;
  189937. png_free(png_ptr, text_ptr);
  189938. if (ret)
  189939. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  189940. }
  189941. }
  189942. #endif
  189943. /* This function is called when we haven't found a handler for this
  189944. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  189945. * name or a critical chunk), the chunk is (currently) silently ignored.
  189946. */
  189947. void /* PRIVATE */
  189948. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  189949. length)
  189950. {
  189951. png_uint_32 skip=0;
  189952. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  189953. if (!(png_ptr->chunk_name[0] & 0x20))
  189954. {
  189955. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189956. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189957. PNG_HANDLE_CHUNK_ALWAYS
  189958. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189959. && png_ptr->read_user_chunk_fn == NULL
  189960. #endif
  189961. )
  189962. #endif
  189963. png_chunk_error(png_ptr, "unknown critical chunk");
  189964. info_ptr = info_ptr; /* to quiet some compiler warnings */
  189965. }
  189966. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  189967. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  189968. {
  189969. #ifdef PNG_MAX_MALLOC_64K
  189970. if (length > (png_uint_32)65535L)
  189971. {
  189972. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  189973. skip = length - (png_uint_32)65535L;
  189974. length = (png_uint_32)65535L;
  189975. }
  189976. #endif
  189977. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  189978. (png_charp)png_ptr->chunk_name, 5);
  189979. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  189980. png_ptr->unknown_chunk.size = (png_size_t)length;
  189981. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  189982. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  189983. if(png_ptr->read_user_chunk_fn != NULL)
  189984. {
  189985. /* callback to user unknown chunk handler */
  189986. int ret;
  189987. ret = (*(png_ptr->read_user_chunk_fn))
  189988. (png_ptr, &png_ptr->unknown_chunk);
  189989. if (ret < 0)
  189990. png_chunk_error(png_ptr, "error in user chunk");
  189991. if (ret == 0)
  189992. {
  189993. if (!(png_ptr->chunk_name[0] & 0x20))
  189994. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  189995. PNG_HANDLE_CHUNK_ALWAYS)
  189996. png_chunk_error(png_ptr, "unknown critical chunk");
  189997. png_set_unknown_chunks(png_ptr, info_ptr,
  189998. &png_ptr->unknown_chunk, 1);
  189999. }
  190000. }
  190001. #else
  190002. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  190003. #endif
  190004. png_free(png_ptr, png_ptr->unknown_chunk.data);
  190005. png_ptr->unknown_chunk.data = NULL;
  190006. }
  190007. else
  190008. #endif
  190009. skip=length;
  190010. png_push_crc_skip(png_ptr, skip);
  190011. }
  190012. void /* PRIVATE */
  190013. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  190014. {
  190015. if (png_ptr->info_fn != NULL)
  190016. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  190017. }
  190018. void /* PRIVATE */
  190019. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  190020. {
  190021. if (png_ptr->end_fn != NULL)
  190022. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  190023. }
  190024. void /* PRIVATE */
  190025. png_push_have_row(png_structp png_ptr, png_bytep row)
  190026. {
  190027. if (png_ptr->row_fn != NULL)
  190028. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  190029. (int)png_ptr->pass);
  190030. }
  190031. void PNGAPI
  190032. png_progressive_combine_row (png_structp png_ptr,
  190033. png_bytep old_row, png_bytep new_row)
  190034. {
  190035. #ifdef PNG_USE_LOCAL_ARRAYS
  190036. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190037. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190038. #endif
  190039. if(png_ptr == NULL) return;
  190040. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190041. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190042. }
  190043. void PNGAPI
  190044. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190045. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190046. png_progressive_end_ptr end_fn)
  190047. {
  190048. if(png_ptr == NULL) return;
  190049. png_ptr->info_fn = info_fn;
  190050. png_ptr->row_fn = row_fn;
  190051. png_ptr->end_fn = end_fn;
  190052. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190053. }
  190054. png_voidp PNGAPI
  190055. png_get_progressive_ptr(png_structp png_ptr)
  190056. {
  190057. if(png_ptr == NULL) return (NULL);
  190058. return png_ptr->io_ptr;
  190059. }
  190060. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190061. /*** End of inlined file: pngpread.c ***/
  190062. /*** Start of inlined file: pngrio.c ***/
  190063. /* pngrio.c - functions for data input
  190064. *
  190065. * Last changed in libpng 1.2.13 November 13, 2006
  190066. * For conditions of distribution and use, see copyright notice in png.h
  190067. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190068. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190069. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190070. *
  190071. * This file provides a location for all input. Users who need
  190072. * special handling are expected to write a function that has the same
  190073. * arguments as this and performs a similar function, but that possibly
  190074. * has a different input method. Note that you shouldn't change this
  190075. * function, but rather write a replacement function and then make
  190076. * libpng use it at run time with png_set_read_fn(...).
  190077. */
  190078. #define PNG_INTERNAL
  190079. #if defined(PNG_READ_SUPPORTED)
  190080. /* Read the data from whatever input you are using. The default routine
  190081. reads from a file pointer. Note that this routine sometimes gets called
  190082. with very small lengths, so you should implement some kind of simple
  190083. buffering if you are using unbuffered reads. This should never be asked
  190084. to read more then 64K on a 16 bit machine. */
  190085. void /* PRIVATE */
  190086. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190087. {
  190088. png_debug1(4,"reading %d bytes\n", (int)length);
  190089. if (png_ptr->read_data_fn != NULL)
  190090. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190091. else
  190092. png_error(png_ptr, "Call to NULL read function");
  190093. }
  190094. #if !defined(PNG_NO_STDIO)
  190095. /* This is the function that does the actual reading of data. If you are
  190096. not reading from a standard C stream, you should create a replacement
  190097. read_data function and use it at run time with png_set_read_fn(), rather
  190098. than changing the library. */
  190099. #ifndef USE_FAR_KEYWORD
  190100. void PNGAPI
  190101. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190102. {
  190103. png_size_t check;
  190104. if(png_ptr == NULL) return;
  190105. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190106. * instead of an int, which is what fread() actually returns.
  190107. */
  190108. #if defined(_WIN32_WCE)
  190109. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190110. check = 0;
  190111. #else
  190112. check = (png_size_t)fread(data, (png_size_t)1, length,
  190113. (png_FILE_p)png_ptr->io_ptr);
  190114. #endif
  190115. if (check != length)
  190116. png_error(png_ptr, "Read Error");
  190117. }
  190118. #else
  190119. /* this is the model-independent version. Since the standard I/O library
  190120. can't handle far buffers in the medium and small models, we have to copy
  190121. the data.
  190122. */
  190123. #define NEAR_BUF_SIZE 1024
  190124. #define MIN(a,b) (a <= b ? a : b)
  190125. static void PNGAPI
  190126. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190127. {
  190128. int check;
  190129. png_byte *n_data;
  190130. png_FILE_p io_ptr;
  190131. if(png_ptr == NULL) return;
  190132. /* Check if data really is near. If so, use usual code. */
  190133. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190134. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190135. if ((png_bytep)n_data == data)
  190136. {
  190137. #if defined(_WIN32_WCE)
  190138. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190139. check = 0;
  190140. #else
  190141. check = fread(n_data, 1, length, io_ptr);
  190142. #endif
  190143. }
  190144. else
  190145. {
  190146. png_byte buf[NEAR_BUF_SIZE];
  190147. png_size_t read, remaining, err;
  190148. check = 0;
  190149. remaining = length;
  190150. do
  190151. {
  190152. read = MIN(NEAR_BUF_SIZE, remaining);
  190153. #if defined(_WIN32_WCE)
  190154. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190155. err = 0;
  190156. #else
  190157. err = fread(buf, (png_size_t)1, read, io_ptr);
  190158. #endif
  190159. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190160. if(err != read)
  190161. break;
  190162. else
  190163. check += err;
  190164. data += read;
  190165. remaining -= read;
  190166. }
  190167. while (remaining != 0);
  190168. }
  190169. if ((png_uint_32)check != (png_uint_32)length)
  190170. png_error(png_ptr, "read Error");
  190171. }
  190172. #endif
  190173. #endif
  190174. /* This function allows the application to supply a new input function
  190175. for libpng if standard C streams aren't being used.
  190176. This function takes as its arguments:
  190177. png_ptr - pointer to a png input data structure
  190178. io_ptr - pointer to user supplied structure containing info about
  190179. the input functions. May be NULL.
  190180. read_data_fn - pointer to a new input function that takes as its
  190181. arguments a pointer to a png_struct, a pointer to
  190182. a location where input data can be stored, and a 32-bit
  190183. unsigned int that is the number of bytes to be read.
  190184. To exit and output any fatal error messages the new write
  190185. function should call png_error(png_ptr, "Error msg"). */
  190186. void PNGAPI
  190187. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190188. png_rw_ptr read_data_fn)
  190189. {
  190190. if(png_ptr == NULL) return;
  190191. png_ptr->io_ptr = io_ptr;
  190192. #if !defined(PNG_NO_STDIO)
  190193. if (read_data_fn != NULL)
  190194. png_ptr->read_data_fn = read_data_fn;
  190195. else
  190196. png_ptr->read_data_fn = png_default_read_data;
  190197. #else
  190198. png_ptr->read_data_fn = read_data_fn;
  190199. #endif
  190200. /* It is an error to write to a read device */
  190201. if (png_ptr->write_data_fn != NULL)
  190202. {
  190203. png_ptr->write_data_fn = NULL;
  190204. png_warning(png_ptr,
  190205. "It's an error to set both read_data_fn and write_data_fn in the ");
  190206. png_warning(png_ptr,
  190207. "same structure. Resetting write_data_fn to NULL.");
  190208. }
  190209. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190210. png_ptr->output_flush_fn = NULL;
  190211. #endif
  190212. }
  190213. #endif /* PNG_READ_SUPPORTED */
  190214. /*** End of inlined file: pngrio.c ***/
  190215. /*** Start of inlined file: pngrtran.c ***/
  190216. /* pngrtran.c - transforms the data in a row for PNG readers
  190217. *
  190218. * Last changed in libpng 1.2.21 [October 4, 2007]
  190219. * For conditions of distribution and use, see copyright notice in png.h
  190220. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190221. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190222. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190223. *
  190224. * This file contains functions optionally called by an application
  190225. * in order to tell libpng how to handle data when reading a PNG.
  190226. * Transformations that are used in both reading and writing are
  190227. * in pngtrans.c.
  190228. */
  190229. #define PNG_INTERNAL
  190230. #if defined(PNG_READ_SUPPORTED)
  190231. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190232. void PNGAPI
  190233. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190234. {
  190235. png_debug(1, "in png_set_crc_action\n");
  190236. /* Tell libpng how we react to CRC errors in critical chunks */
  190237. if(png_ptr == NULL) return;
  190238. switch (crit_action)
  190239. {
  190240. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190241. break;
  190242. case PNG_CRC_WARN_USE: /* warn/use data */
  190243. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190244. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190245. break;
  190246. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190247. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190248. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190249. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190250. break;
  190251. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190252. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190253. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190254. case PNG_CRC_DEFAULT:
  190255. default:
  190256. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190257. break;
  190258. }
  190259. switch (ancil_action)
  190260. {
  190261. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190262. break;
  190263. case PNG_CRC_WARN_USE: /* warn/use data */
  190264. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190265. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190266. break;
  190267. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190268. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190269. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190270. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190271. break;
  190272. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190273. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190274. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190275. break;
  190276. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190277. case PNG_CRC_DEFAULT:
  190278. default:
  190279. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190280. break;
  190281. }
  190282. }
  190283. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  190284. defined(PNG_FLOATING_POINT_SUPPORTED)
  190285. /* handle alpha and tRNS via a background color */
  190286. void PNGAPI
  190287. png_set_background(png_structp png_ptr,
  190288. png_color_16p background_color, int background_gamma_code,
  190289. int need_expand, double background_gamma)
  190290. {
  190291. png_debug(1, "in png_set_background\n");
  190292. if(png_ptr == NULL) return;
  190293. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  190294. {
  190295. png_warning(png_ptr, "Application must supply a known background gamma");
  190296. return;
  190297. }
  190298. png_ptr->transformations |= PNG_BACKGROUND;
  190299. png_memcpy(&(png_ptr->background), background_color,
  190300. png_sizeof(png_color_16));
  190301. png_ptr->background_gamma = (float)background_gamma;
  190302. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  190303. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  190304. }
  190305. #endif
  190306. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  190307. /* strip 16 bit depth files to 8 bit depth */
  190308. void PNGAPI
  190309. png_set_strip_16(png_structp png_ptr)
  190310. {
  190311. png_debug(1, "in png_set_strip_16\n");
  190312. if(png_ptr == NULL) return;
  190313. png_ptr->transformations |= PNG_16_TO_8;
  190314. }
  190315. #endif
  190316. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  190317. void PNGAPI
  190318. png_set_strip_alpha(png_structp png_ptr)
  190319. {
  190320. png_debug(1, "in png_set_strip_alpha\n");
  190321. if(png_ptr == NULL) return;
  190322. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  190323. }
  190324. #endif
  190325. #if defined(PNG_READ_DITHER_SUPPORTED)
  190326. /* Dither file to 8 bit. Supply a palette, the current number
  190327. * of elements in the palette, the maximum number of elements
  190328. * allowed, and a histogram if possible. If the current number
  190329. * of colors is greater then the maximum number, the palette will be
  190330. * modified to fit in the maximum number. "full_dither" indicates
  190331. * whether we need a dithering cube set up for RGB images, or if we
  190332. * simply are reducing the number of colors in a paletted image.
  190333. */
  190334. typedef struct png_dsort_struct
  190335. {
  190336. struct png_dsort_struct FAR * next;
  190337. png_byte left;
  190338. png_byte right;
  190339. } png_dsort;
  190340. typedef png_dsort FAR * png_dsortp;
  190341. typedef png_dsort FAR * FAR * png_dsortpp;
  190342. void PNGAPI
  190343. png_set_dither(png_structp png_ptr, png_colorp palette,
  190344. int num_palette, int maximum_colors, png_uint_16p histogram,
  190345. int full_dither)
  190346. {
  190347. png_debug(1, "in png_set_dither\n");
  190348. if(png_ptr == NULL) return;
  190349. png_ptr->transformations |= PNG_DITHER;
  190350. if (!full_dither)
  190351. {
  190352. int i;
  190353. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  190354. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190355. for (i = 0; i < num_palette; i++)
  190356. png_ptr->dither_index[i] = (png_byte)i;
  190357. }
  190358. if (num_palette > maximum_colors)
  190359. {
  190360. if (histogram != NULL)
  190361. {
  190362. /* This is easy enough, just throw out the least used colors.
  190363. Perhaps not the best solution, but good enough. */
  190364. int i;
  190365. /* initialize an array to sort colors */
  190366. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  190367. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190368. /* initialize the dither_sort array */
  190369. for (i = 0; i < num_palette; i++)
  190370. png_ptr->dither_sort[i] = (png_byte)i;
  190371. /* Find the least used palette entries by starting a
  190372. bubble sort, and running it until we have sorted
  190373. out enough colors. Note that we don't care about
  190374. sorting all the colors, just finding which are
  190375. least used. */
  190376. for (i = num_palette - 1; i >= maximum_colors; i--)
  190377. {
  190378. int done; /* to stop early if the list is pre-sorted */
  190379. int j;
  190380. done = 1;
  190381. for (j = 0; j < i; j++)
  190382. {
  190383. if (histogram[png_ptr->dither_sort[j]]
  190384. < histogram[png_ptr->dither_sort[j + 1]])
  190385. {
  190386. png_byte t;
  190387. t = png_ptr->dither_sort[j];
  190388. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  190389. png_ptr->dither_sort[j + 1] = t;
  190390. done = 0;
  190391. }
  190392. }
  190393. if (done)
  190394. break;
  190395. }
  190396. /* swap the palette around, and set up a table, if necessary */
  190397. if (full_dither)
  190398. {
  190399. int j = num_palette;
  190400. /* put all the useful colors within the max, but don't
  190401. move the others */
  190402. for (i = 0; i < maximum_colors; i++)
  190403. {
  190404. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190405. {
  190406. do
  190407. j--;
  190408. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190409. palette[i] = palette[j];
  190410. }
  190411. }
  190412. }
  190413. else
  190414. {
  190415. int j = num_palette;
  190416. /* move all the used colors inside the max limit, and
  190417. develop a translation table */
  190418. for (i = 0; i < maximum_colors; i++)
  190419. {
  190420. /* only move the colors we need to */
  190421. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  190422. {
  190423. png_color tmp_color;
  190424. do
  190425. j--;
  190426. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  190427. tmp_color = palette[j];
  190428. palette[j] = palette[i];
  190429. palette[i] = tmp_color;
  190430. /* indicate where the color went */
  190431. png_ptr->dither_index[j] = (png_byte)i;
  190432. png_ptr->dither_index[i] = (png_byte)j;
  190433. }
  190434. }
  190435. /* find closest color for those colors we are not using */
  190436. for (i = 0; i < num_palette; i++)
  190437. {
  190438. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  190439. {
  190440. int min_d, k, min_k, d_index;
  190441. /* find the closest color to one we threw out */
  190442. d_index = png_ptr->dither_index[i];
  190443. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  190444. for (k = 1, min_k = 0; k < maximum_colors; k++)
  190445. {
  190446. int d;
  190447. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  190448. if (d < min_d)
  190449. {
  190450. min_d = d;
  190451. min_k = k;
  190452. }
  190453. }
  190454. /* point to closest color */
  190455. png_ptr->dither_index[i] = (png_byte)min_k;
  190456. }
  190457. }
  190458. }
  190459. png_free(png_ptr, png_ptr->dither_sort);
  190460. png_ptr->dither_sort=NULL;
  190461. }
  190462. else
  190463. {
  190464. /* This is much harder to do simply (and quickly). Perhaps
  190465. we need to go through a median cut routine, but those
  190466. don't always behave themselves with only a few colors
  190467. as input. So we will just find the closest two colors,
  190468. and throw out one of them (chosen somewhat randomly).
  190469. [We don't understand this at all, so if someone wants to
  190470. work on improving it, be our guest - AED, GRP]
  190471. */
  190472. int i;
  190473. int max_d;
  190474. int num_new_palette;
  190475. png_dsortp t;
  190476. png_dsortpp hash;
  190477. t=NULL;
  190478. /* initialize palette index arrays */
  190479. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  190480. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190481. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  190482. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  190483. /* initialize the sort array */
  190484. for (i = 0; i < num_palette; i++)
  190485. {
  190486. png_ptr->index_to_palette[i] = (png_byte)i;
  190487. png_ptr->palette_to_index[i] = (png_byte)i;
  190488. }
  190489. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  190490. png_sizeof (png_dsortp)));
  190491. for (i = 0; i < 769; i++)
  190492. hash[i] = NULL;
  190493. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  190494. num_new_palette = num_palette;
  190495. /* initial wild guess at how far apart the farthest pixel
  190496. pair we will be eliminating will be. Larger
  190497. numbers mean more areas will be allocated, Smaller
  190498. numbers run the risk of not saving enough data, and
  190499. having to do this all over again.
  190500. I have not done extensive checking on this number.
  190501. */
  190502. max_d = 96;
  190503. while (num_new_palette > maximum_colors)
  190504. {
  190505. for (i = 0; i < num_new_palette - 1; i++)
  190506. {
  190507. int j;
  190508. for (j = i + 1; j < num_new_palette; j++)
  190509. {
  190510. int d;
  190511. d = PNG_COLOR_DIST(palette[i], palette[j]);
  190512. if (d <= max_d)
  190513. {
  190514. t = (png_dsortp)png_malloc_warn(png_ptr,
  190515. (png_uint_32)(png_sizeof(png_dsort)));
  190516. if (t == NULL)
  190517. break;
  190518. t->next = hash[d];
  190519. t->left = (png_byte)i;
  190520. t->right = (png_byte)j;
  190521. hash[d] = t;
  190522. }
  190523. }
  190524. if (t == NULL)
  190525. break;
  190526. }
  190527. if (t != NULL)
  190528. for (i = 0; i <= max_d; i++)
  190529. {
  190530. if (hash[i] != NULL)
  190531. {
  190532. png_dsortp p;
  190533. for (p = hash[i]; p; p = p->next)
  190534. {
  190535. if ((int)png_ptr->index_to_palette[p->left]
  190536. < num_new_palette &&
  190537. (int)png_ptr->index_to_palette[p->right]
  190538. < num_new_palette)
  190539. {
  190540. int j, next_j;
  190541. if (num_new_palette & 0x01)
  190542. {
  190543. j = p->left;
  190544. next_j = p->right;
  190545. }
  190546. else
  190547. {
  190548. j = p->right;
  190549. next_j = p->left;
  190550. }
  190551. num_new_palette--;
  190552. palette[png_ptr->index_to_palette[j]]
  190553. = palette[num_new_palette];
  190554. if (!full_dither)
  190555. {
  190556. int k;
  190557. for (k = 0; k < num_palette; k++)
  190558. {
  190559. if (png_ptr->dither_index[k] ==
  190560. png_ptr->index_to_palette[j])
  190561. png_ptr->dither_index[k] =
  190562. png_ptr->index_to_palette[next_j];
  190563. if ((int)png_ptr->dither_index[k] ==
  190564. num_new_palette)
  190565. png_ptr->dither_index[k] =
  190566. png_ptr->index_to_palette[j];
  190567. }
  190568. }
  190569. png_ptr->index_to_palette[png_ptr->palette_to_index
  190570. [num_new_palette]] = png_ptr->index_to_palette[j];
  190571. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  190572. = png_ptr->palette_to_index[num_new_palette];
  190573. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  190574. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  190575. }
  190576. if (num_new_palette <= maximum_colors)
  190577. break;
  190578. }
  190579. if (num_new_palette <= maximum_colors)
  190580. break;
  190581. }
  190582. }
  190583. for (i = 0; i < 769; i++)
  190584. {
  190585. if (hash[i] != NULL)
  190586. {
  190587. png_dsortp p = hash[i];
  190588. while (p)
  190589. {
  190590. t = p->next;
  190591. png_free(png_ptr, p);
  190592. p = t;
  190593. }
  190594. }
  190595. hash[i] = 0;
  190596. }
  190597. max_d += 96;
  190598. }
  190599. png_free(png_ptr, hash);
  190600. png_free(png_ptr, png_ptr->palette_to_index);
  190601. png_free(png_ptr, png_ptr->index_to_palette);
  190602. png_ptr->palette_to_index=NULL;
  190603. png_ptr->index_to_palette=NULL;
  190604. }
  190605. num_palette = maximum_colors;
  190606. }
  190607. if (png_ptr->palette == NULL)
  190608. {
  190609. png_ptr->palette = palette;
  190610. }
  190611. png_ptr->num_palette = (png_uint_16)num_palette;
  190612. if (full_dither)
  190613. {
  190614. int i;
  190615. png_bytep distance;
  190616. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  190617. PNG_DITHER_BLUE_BITS;
  190618. int num_red = (1 << PNG_DITHER_RED_BITS);
  190619. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  190620. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  190621. png_size_t num_entries = ((png_size_t)1 << total_bits);
  190622. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  190623. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  190624. png_memset(png_ptr->palette_lookup, 0, num_entries *
  190625. png_sizeof (png_byte));
  190626. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  190627. png_sizeof(png_byte)));
  190628. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  190629. for (i = 0; i < num_palette; i++)
  190630. {
  190631. int ir, ig, ib;
  190632. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  190633. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  190634. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  190635. for (ir = 0; ir < num_red; ir++)
  190636. {
  190637. /* int dr = abs(ir - r); */
  190638. int dr = ((ir > r) ? ir - r : r - ir);
  190639. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  190640. for (ig = 0; ig < num_green; ig++)
  190641. {
  190642. /* int dg = abs(ig - g); */
  190643. int dg = ((ig > g) ? ig - g : g - ig);
  190644. int dt = dr + dg;
  190645. int dm = ((dr > dg) ? dr : dg);
  190646. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  190647. for (ib = 0; ib < num_blue; ib++)
  190648. {
  190649. int d_index = index_g | ib;
  190650. /* int db = abs(ib - b); */
  190651. int db = ((ib > b) ? ib - b : b - ib);
  190652. int dmax = ((dm > db) ? dm : db);
  190653. int d = dmax + dt + db;
  190654. if (d < (int)distance[d_index])
  190655. {
  190656. distance[d_index] = (png_byte)d;
  190657. png_ptr->palette_lookup[d_index] = (png_byte)i;
  190658. }
  190659. }
  190660. }
  190661. }
  190662. }
  190663. png_free(png_ptr, distance);
  190664. }
  190665. }
  190666. #endif
  190667. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190668. /* Transform the image from the file_gamma to the screen_gamma. We
  190669. * only do transformations on images where the file_gamma and screen_gamma
  190670. * are not close reciprocals, otherwise it slows things down slightly, and
  190671. * also needlessly introduces small errors.
  190672. *
  190673. * We will turn off gamma transformation later if no semitransparent entries
  190674. * are present in the tRNS array for palette images. We can't do it here
  190675. * because we don't necessarily have the tRNS chunk yet.
  190676. */
  190677. void PNGAPI
  190678. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  190679. {
  190680. png_debug(1, "in png_set_gamma\n");
  190681. if(png_ptr == NULL) return;
  190682. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  190683. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  190684. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  190685. png_ptr->transformations |= PNG_GAMMA;
  190686. png_ptr->gamma = (float)file_gamma;
  190687. png_ptr->screen_gamma = (float)scrn_gamma;
  190688. }
  190689. #endif
  190690. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190691. /* Expand paletted images to RGB, expand grayscale images of
  190692. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  190693. * to alpha channels.
  190694. */
  190695. void PNGAPI
  190696. png_set_expand(png_structp png_ptr)
  190697. {
  190698. png_debug(1, "in png_set_expand\n");
  190699. if(png_ptr == NULL) return;
  190700. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190701. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190702. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190703. #endif
  190704. }
  190705. /* GRR 19990627: the following three functions currently are identical
  190706. * to png_set_expand(). However, it is entirely reasonable that someone
  190707. * might wish to expand an indexed image to RGB but *not* expand a single,
  190708. * fully transparent palette entry to a full alpha channel--perhaps instead
  190709. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  190710. * the transparent color with a particular RGB value, or drop tRNS entirely.
  190711. * IOW, a future version of the library may make the transformations flag
  190712. * a bit more fine-grained, with separate bits for each of these three
  190713. * functions.
  190714. *
  190715. * More to the point, these functions make it obvious what libpng will be
  190716. * doing, whereas "expand" can (and does) mean any number of things.
  190717. *
  190718. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  190719. * to expand only the sample depth but not to expand the tRNS to alpha.
  190720. */
  190721. /* Expand paletted images to RGB. */
  190722. void PNGAPI
  190723. png_set_palette_to_rgb(png_structp png_ptr)
  190724. {
  190725. png_debug(1, "in png_set_palette_to_rgb\n");
  190726. if(png_ptr == NULL) return;
  190727. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190728. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190729. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  190730. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190731. #endif
  190732. }
  190733. #if !defined(PNG_1_0_X)
  190734. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190735. void PNGAPI
  190736. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  190737. {
  190738. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  190739. if(png_ptr == NULL) return;
  190740. png_ptr->transformations |= PNG_EXPAND;
  190741. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190742. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190743. #endif
  190744. }
  190745. #endif
  190746. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  190747. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  190748. /* Deprecated as of libpng-1.2.9 */
  190749. void PNGAPI
  190750. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  190751. {
  190752. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  190753. if(png_ptr == NULL) return;
  190754. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190755. }
  190756. #endif
  190757. /* Expand tRNS chunks to alpha channels. */
  190758. void PNGAPI
  190759. png_set_tRNS_to_alpha(png_structp png_ptr)
  190760. {
  190761. png_debug(1, "in png_set_tRNS_to_alpha\n");
  190762. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  190763. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190764. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190765. #endif
  190766. }
  190767. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  190768. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190769. void PNGAPI
  190770. png_set_gray_to_rgb(png_structp png_ptr)
  190771. {
  190772. png_debug(1, "in png_set_gray_to_rgb\n");
  190773. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  190774. #ifdef PNG_WARN_UNINITIALIZED_ROW
  190775. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  190776. #endif
  190777. }
  190778. #endif
  190779. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  190780. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  190781. /* Convert a RGB image to a grayscale of the same width. This allows us,
  190782. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  190783. */
  190784. void PNGAPI
  190785. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  190786. double green)
  190787. {
  190788. int red_fixed = (int)((float)red*100000.0 + 0.5);
  190789. int green_fixed = (int)((float)green*100000.0 + 0.5);
  190790. if(png_ptr == NULL) return;
  190791. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  190792. }
  190793. #endif
  190794. void PNGAPI
  190795. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  190796. png_fixed_point red, png_fixed_point green)
  190797. {
  190798. png_debug(1, "in png_set_rgb_to_gray\n");
  190799. if(png_ptr == NULL) return;
  190800. switch(error_action)
  190801. {
  190802. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  190803. break;
  190804. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  190805. break;
  190806. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  190807. }
  190808. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  190809. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190810. png_ptr->transformations |= PNG_EXPAND;
  190811. #else
  190812. {
  190813. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  190814. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  190815. }
  190816. #endif
  190817. {
  190818. png_uint_16 red_int, green_int;
  190819. if(red < 0 || green < 0)
  190820. {
  190821. red_int = 6968; /* .212671 * 32768 + .5 */
  190822. green_int = 23434; /* .715160 * 32768 + .5 */
  190823. }
  190824. else if(red + green < 100000L)
  190825. {
  190826. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  190827. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  190828. }
  190829. else
  190830. {
  190831. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  190832. red_int = 6968;
  190833. green_int = 23434;
  190834. }
  190835. png_ptr->rgb_to_gray_red_coeff = red_int;
  190836. png_ptr->rgb_to_gray_green_coeff = green_int;
  190837. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  190838. }
  190839. }
  190840. #endif
  190841. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  190842. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  190843. defined(PNG_LEGACY_SUPPORTED)
  190844. void PNGAPI
  190845. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  190846. read_user_transform_fn)
  190847. {
  190848. png_debug(1, "in png_set_read_user_transform_fn\n");
  190849. if(png_ptr == NULL) return;
  190850. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  190851. png_ptr->transformations |= PNG_USER_TRANSFORM;
  190852. png_ptr->read_user_transform_fn = read_user_transform_fn;
  190853. #endif
  190854. #ifdef PNG_LEGACY_SUPPORTED
  190855. if(read_user_transform_fn)
  190856. png_warning(png_ptr,
  190857. "This version of libpng does not support user transforms");
  190858. #endif
  190859. }
  190860. #endif
  190861. /* Initialize everything needed for the read. This includes modifying
  190862. * the palette.
  190863. */
  190864. void /* PRIVATE */
  190865. png_init_read_transformations(png_structp png_ptr)
  190866. {
  190867. png_debug(1, "in png_init_read_transformations\n");
  190868. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  190869. if(png_ptr != NULL)
  190870. #endif
  190871. {
  190872. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  190873. || defined(PNG_READ_GAMMA_SUPPORTED)
  190874. int color_type = png_ptr->color_type;
  190875. #endif
  190876. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  190877. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  190878. /* Detect gray background and attempt to enable optimization
  190879. * for gray --> RGB case */
  190880. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  190881. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  190882. * background color might actually be gray yet not be flagged as such.
  190883. * This is not a problem for the current code, which uses
  190884. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  190885. * png_do_gray_to_rgb() transformation.
  190886. */
  190887. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190888. !(color_type & PNG_COLOR_MASK_COLOR))
  190889. {
  190890. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190891. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  190892. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190893. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  190894. png_ptr->background.red == png_ptr->background.green &&
  190895. png_ptr->background.red == png_ptr->background.blue)
  190896. {
  190897. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  190898. png_ptr->background.gray = png_ptr->background.red;
  190899. }
  190900. #endif
  190901. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  190902. (png_ptr->transformations & PNG_EXPAND))
  190903. {
  190904. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  190905. {
  190906. /* expand background and tRNS chunks */
  190907. switch (png_ptr->bit_depth)
  190908. {
  190909. case 1:
  190910. png_ptr->background.gray *= (png_uint_16)0xff;
  190911. png_ptr->background.red = png_ptr->background.green
  190912. = png_ptr->background.blue = png_ptr->background.gray;
  190913. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190914. {
  190915. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  190916. png_ptr->trans_values.red = png_ptr->trans_values.green
  190917. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190918. }
  190919. break;
  190920. case 2:
  190921. png_ptr->background.gray *= (png_uint_16)0x55;
  190922. png_ptr->background.red = png_ptr->background.green
  190923. = png_ptr->background.blue = png_ptr->background.gray;
  190924. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190925. {
  190926. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  190927. png_ptr->trans_values.red = png_ptr->trans_values.green
  190928. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190929. }
  190930. break;
  190931. case 4:
  190932. png_ptr->background.gray *= (png_uint_16)0x11;
  190933. png_ptr->background.red = png_ptr->background.green
  190934. = png_ptr->background.blue = png_ptr->background.gray;
  190935. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190936. {
  190937. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  190938. png_ptr->trans_values.red = png_ptr->trans_values.green
  190939. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  190940. }
  190941. break;
  190942. case 8:
  190943. case 16:
  190944. png_ptr->background.red = png_ptr->background.green
  190945. = png_ptr->background.blue = png_ptr->background.gray;
  190946. break;
  190947. }
  190948. }
  190949. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  190950. {
  190951. png_ptr->background.red =
  190952. png_ptr->palette[png_ptr->background.index].red;
  190953. png_ptr->background.green =
  190954. png_ptr->palette[png_ptr->background.index].green;
  190955. png_ptr->background.blue =
  190956. png_ptr->palette[png_ptr->background.index].blue;
  190957. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  190958. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  190959. {
  190960. #if defined(PNG_READ_EXPAND_SUPPORTED)
  190961. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  190962. #endif
  190963. {
  190964. /* invert the alpha channel (in tRNS) unless the pixels are
  190965. going to be expanded, in which case leave it for later */
  190966. int i,istop;
  190967. istop=(int)png_ptr->num_trans;
  190968. for (i=0; i<istop; i++)
  190969. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  190970. }
  190971. }
  190972. #endif
  190973. }
  190974. }
  190975. #endif
  190976. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  190977. png_ptr->background_1 = png_ptr->background;
  190978. #endif
  190979. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  190980. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  190981. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  190982. < PNG_GAMMA_THRESHOLD))
  190983. {
  190984. int i,k;
  190985. k=0;
  190986. for (i=0; i<png_ptr->num_trans; i++)
  190987. {
  190988. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  190989. k=1; /* partial transparency is present */
  190990. }
  190991. if (k == 0)
  190992. png_ptr->transformations &= (~PNG_GAMMA);
  190993. }
  190994. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  190995. png_ptr->gamma != 0.0)
  190996. {
  190997. png_build_gamma_table(png_ptr);
  190998. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  190999. if (png_ptr->transformations & PNG_BACKGROUND)
  191000. {
  191001. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191002. {
  191003. /* could skip if no transparency and
  191004. */
  191005. png_color back, back_1;
  191006. png_colorp palette = png_ptr->palette;
  191007. int num_palette = png_ptr->num_palette;
  191008. int i;
  191009. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191010. {
  191011. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191012. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191013. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191014. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191015. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191016. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191017. }
  191018. else
  191019. {
  191020. double g, gs;
  191021. switch (png_ptr->background_gamma_type)
  191022. {
  191023. case PNG_BACKGROUND_GAMMA_SCREEN:
  191024. g = (png_ptr->screen_gamma);
  191025. gs = 1.0;
  191026. break;
  191027. case PNG_BACKGROUND_GAMMA_FILE:
  191028. g = 1.0 / (png_ptr->gamma);
  191029. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191030. break;
  191031. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191032. g = 1.0 / (png_ptr->background_gamma);
  191033. gs = 1.0 / (png_ptr->background_gamma *
  191034. png_ptr->screen_gamma);
  191035. break;
  191036. default:
  191037. g = 1.0; /* back_1 */
  191038. gs = 1.0; /* back */
  191039. }
  191040. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191041. {
  191042. back.red = (png_byte)png_ptr->background.red;
  191043. back.green = (png_byte)png_ptr->background.green;
  191044. back.blue = (png_byte)png_ptr->background.blue;
  191045. }
  191046. else
  191047. {
  191048. back.red = (png_byte)(pow(
  191049. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191050. back.green = (png_byte)(pow(
  191051. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191052. back.blue = (png_byte)(pow(
  191053. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191054. }
  191055. back_1.red = (png_byte)(pow(
  191056. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191057. back_1.green = (png_byte)(pow(
  191058. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191059. back_1.blue = (png_byte)(pow(
  191060. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191061. }
  191062. for (i = 0; i < num_palette; i++)
  191063. {
  191064. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191065. {
  191066. if (png_ptr->trans[i] == 0)
  191067. {
  191068. palette[i] = back;
  191069. }
  191070. else /* if (png_ptr->trans[i] != 0xff) */
  191071. {
  191072. png_byte v, w;
  191073. v = png_ptr->gamma_to_1[palette[i].red];
  191074. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191075. palette[i].red = png_ptr->gamma_from_1[w];
  191076. v = png_ptr->gamma_to_1[palette[i].green];
  191077. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191078. palette[i].green = png_ptr->gamma_from_1[w];
  191079. v = png_ptr->gamma_to_1[palette[i].blue];
  191080. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191081. palette[i].blue = png_ptr->gamma_from_1[w];
  191082. }
  191083. }
  191084. else
  191085. {
  191086. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191087. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191088. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191089. }
  191090. }
  191091. }
  191092. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191093. else
  191094. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191095. {
  191096. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191097. double g = 1.0;
  191098. double gs = 1.0;
  191099. switch (png_ptr->background_gamma_type)
  191100. {
  191101. case PNG_BACKGROUND_GAMMA_SCREEN:
  191102. g = (png_ptr->screen_gamma);
  191103. gs = 1.0;
  191104. break;
  191105. case PNG_BACKGROUND_GAMMA_FILE:
  191106. g = 1.0 / (png_ptr->gamma);
  191107. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191108. break;
  191109. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191110. g = 1.0 / (png_ptr->background_gamma);
  191111. gs = 1.0 / (png_ptr->background_gamma *
  191112. png_ptr->screen_gamma);
  191113. break;
  191114. }
  191115. png_ptr->background_1.gray = (png_uint_16)(pow(
  191116. (double)png_ptr->background.gray / m, g) * m + .5);
  191117. png_ptr->background.gray = (png_uint_16)(pow(
  191118. (double)png_ptr->background.gray / m, gs) * m + .5);
  191119. if ((png_ptr->background.red != png_ptr->background.green) ||
  191120. (png_ptr->background.red != png_ptr->background.blue) ||
  191121. (png_ptr->background.red != png_ptr->background.gray))
  191122. {
  191123. /* RGB or RGBA with color background */
  191124. png_ptr->background_1.red = (png_uint_16)(pow(
  191125. (double)png_ptr->background.red / m, g) * m + .5);
  191126. png_ptr->background_1.green = (png_uint_16)(pow(
  191127. (double)png_ptr->background.green / m, g) * m + .5);
  191128. png_ptr->background_1.blue = (png_uint_16)(pow(
  191129. (double)png_ptr->background.blue / m, g) * m + .5);
  191130. png_ptr->background.red = (png_uint_16)(pow(
  191131. (double)png_ptr->background.red / m, gs) * m + .5);
  191132. png_ptr->background.green = (png_uint_16)(pow(
  191133. (double)png_ptr->background.green / m, gs) * m + .5);
  191134. png_ptr->background.blue = (png_uint_16)(pow(
  191135. (double)png_ptr->background.blue / m, gs) * m + .5);
  191136. }
  191137. else
  191138. {
  191139. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191140. png_ptr->background_1.red = png_ptr->background_1.green
  191141. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191142. png_ptr->background.red = png_ptr->background.green
  191143. = png_ptr->background.blue = png_ptr->background.gray;
  191144. }
  191145. }
  191146. }
  191147. else
  191148. /* transformation does not include PNG_BACKGROUND */
  191149. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191150. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191151. {
  191152. png_colorp palette = png_ptr->palette;
  191153. int num_palette = png_ptr->num_palette;
  191154. int i;
  191155. for (i = 0; i < num_palette; i++)
  191156. {
  191157. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191158. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191159. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191160. }
  191161. }
  191162. }
  191163. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191164. else
  191165. #endif
  191166. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191167. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191168. /* No GAMMA transformation */
  191169. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191170. (color_type == PNG_COLOR_TYPE_PALETTE))
  191171. {
  191172. int i;
  191173. int istop = (int)png_ptr->num_trans;
  191174. png_color back;
  191175. png_colorp palette = png_ptr->palette;
  191176. back.red = (png_byte)png_ptr->background.red;
  191177. back.green = (png_byte)png_ptr->background.green;
  191178. back.blue = (png_byte)png_ptr->background.blue;
  191179. for (i = 0; i < istop; i++)
  191180. {
  191181. if (png_ptr->trans[i] == 0)
  191182. {
  191183. palette[i] = back;
  191184. }
  191185. else if (png_ptr->trans[i] != 0xff)
  191186. {
  191187. /* The png_composite() macro is defined in png.h */
  191188. png_composite(palette[i].red, palette[i].red,
  191189. png_ptr->trans[i], back.red);
  191190. png_composite(palette[i].green, palette[i].green,
  191191. png_ptr->trans[i], back.green);
  191192. png_composite(palette[i].blue, palette[i].blue,
  191193. png_ptr->trans[i], back.blue);
  191194. }
  191195. }
  191196. }
  191197. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191198. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191199. if ((png_ptr->transformations & PNG_SHIFT) &&
  191200. (color_type == PNG_COLOR_TYPE_PALETTE))
  191201. {
  191202. png_uint_16 i;
  191203. png_uint_16 istop = png_ptr->num_palette;
  191204. int sr = 8 - png_ptr->sig_bit.red;
  191205. int sg = 8 - png_ptr->sig_bit.green;
  191206. int sb = 8 - png_ptr->sig_bit.blue;
  191207. if (sr < 0 || sr > 8)
  191208. sr = 0;
  191209. if (sg < 0 || sg > 8)
  191210. sg = 0;
  191211. if (sb < 0 || sb > 8)
  191212. sb = 0;
  191213. for (i = 0; i < istop; i++)
  191214. {
  191215. png_ptr->palette[i].red >>= sr;
  191216. png_ptr->palette[i].green >>= sg;
  191217. png_ptr->palette[i].blue >>= sb;
  191218. }
  191219. }
  191220. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191221. }
  191222. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191223. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191224. if(png_ptr)
  191225. return;
  191226. #endif
  191227. }
  191228. /* Modify the info structure to reflect the transformations. The
  191229. * info should be updated so a PNG file could be written with it,
  191230. * assuming the transformations result in valid PNG data.
  191231. */
  191232. void /* PRIVATE */
  191233. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191234. {
  191235. png_debug(1, "in png_read_transform_info\n");
  191236. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191237. if (png_ptr->transformations & PNG_EXPAND)
  191238. {
  191239. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191240. {
  191241. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191242. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191243. else
  191244. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191245. info_ptr->bit_depth = 8;
  191246. info_ptr->num_trans = 0;
  191247. }
  191248. else
  191249. {
  191250. if (png_ptr->num_trans)
  191251. {
  191252. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191253. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191254. else
  191255. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191256. }
  191257. if (info_ptr->bit_depth < 8)
  191258. info_ptr->bit_depth = 8;
  191259. info_ptr->num_trans = 0;
  191260. }
  191261. }
  191262. #endif
  191263. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191264. if (png_ptr->transformations & PNG_BACKGROUND)
  191265. {
  191266. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191267. info_ptr->num_trans = 0;
  191268. info_ptr->background = png_ptr->background;
  191269. }
  191270. #endif
  191271. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191272. if (png_ptr->transformations & PNG_GAMMA)
  191273. {
  191274. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191275. info_ptr->gamma = png_ptr->gamma;
  191276. #endif
  191277. #ifdef PNG_FIXED_POINT_SUPPORTED
  191278. info_ptr->int_gamma = png_ptr->int_gamma;
  191279. #endif
  191280. }
  191281. #endif
  191282. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191283. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  191284. info_ptr->bit_depth = 8;
  191285. #endif
  191286. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191287. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  191288. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191289. #endif
  191290. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191291. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191292. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  191293. #endif
  191294. #if defined(PNG_READ_DITHER_SUPPORTED)
  191295. if (png_ptr->transformations & PNG_DITHER)
  191296. {
  191297. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191298. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  191299. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  191300. {
  191301. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  191302. }
  191303. }
  191304. #endif
  191305. #if defined(PNG_READ_PACK_SUPPORTED)
  191306. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  191307. info_ptr->bit_depth = 8;
  191308. #endif
  191309. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191310. info_ptr->channels = 1;
  191311. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  191312. info_ptr->channels = 3;
  191313. else
  191314. info_ptr->channels = 1;
  191315. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191316. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191317. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191318. #endif
  191319. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  191320. info_ptr->channels++;
  191321. #if defined(PNG_READ_FILLER_SUPPORTED)
  191322. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  191323. if ((png_ptr->transformations & PNG_FILLER) &&
  191324. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  191325. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  191326. {
  191327. info_ptr->channels++;
  191328. /* if adding a true alpha channel not just filler */
  191329. #if !defined(PNG_1_0_X)
  191330. if (png_ptr->transformations & PNG_ADD_ALPHA)
  191331. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191332. #endif
  191333. }
  191334. #endif
  191335. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  191336. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191337. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  191338. {
  191339. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  191340. info_ptr->bit_depth = png_ptr->user_transform_depth;
  191341. if(info_ptr->channels < png_ptr->user_transform_channels)
  191342. info_ptr->channels = png_ptr->user_transform_channels;
  191343. }
  191344. #endif
  191345. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  191346. info_ptr->bit_depth);
  191347. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  191348. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  191349. if(png_ptr)
  191350. return;
  191351. #endif
  191352. }
  191353. /* Transform the row. The order of transformations is significant,
  191354. * and is very touchy. If you add a transformation, take care to
  191355. * decide how it fits in with the other transformations here.
  191356. */
  191357. void /* PRIVATE */
  191358. png_do_read_transformations(png_structp png_ptr)
  191359. {
  191360. png_debug(1, "in png_do_read_transformations\n");
  191361. if (png_ptr->row_buf == NULL)
  191362. {
  191363. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  191364. char msg[50];
  191365. png_snprintf2(msg, 50,
  191366. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  191367. png_ptr->pass);
  191368. png_error(png_ptr, msg);
  191369. #else
  191370. png_error(png_ptr, "NULL row buffer");
  191371. #endif
  191372. }
  191373. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191374. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  191375. /* Application has failed to call either png_read_start_image()
  191376. * or png_read_update_info() after setting transforms that expand
  191377. * pixels. This check added to libpng-1.2.19 */
  191378. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  191379. png_error(png_ptr, "Uninitialized row");
  191380. #else
  191381. png_warning(png_ptr, "Uninitialized row");
  191382. #endif
  191383. #endif
  191384. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191385. if (png_ptr->transformations & PNG_EXPAND)
  191386. {
  191387. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  191388. {
  191389. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191390. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  191391. }
  191392. else
  191393. {
  191394. if (png_ptr->num_trans &&
  191395. (png_ptr->transformations & PNG_EXPAND_tRNS))
  191396. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191397. &(png_ptr->trans_values));
  191398. else
  191399. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191400. NULL);
  191401. }
  191402. }
  191403. #endif
  191404. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191405. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  191406. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191407. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  191408. #endif
  191409. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191410. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  191411. {
  191412. int rgb_error =
  191413. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  191414. if(rgb_error)
  191415. {
  191416. png_ptr->rgb_to_gray_status=1;
  191417. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191418. PNG_RGB_TO_GRAY_WARN)
  191419. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191420. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  191421. PNG_RGB_TO_GRAY_ERR)
  191422. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  191423. }
  191424. }
  191425. #endif
  191426. /*
  191427. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  191428. In most cases, the "simple transparency" should be done prior to doing
  191429. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  191430. pixel is transparent. You would also need to make sure that the
  191431. transparency information is upgraded to RGB.
  191432. To summarize, the current flow is:
  191433. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  191434. with background "in place" if transparent,
  191435. convert to RGB if necessary
  191436. - Gray + alpha -> composite with gray background and remove alpha bytes,
  191437. convert to RGB if necessary
  191438. To support RGB backgrounds for gray images we need:
  191439. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  191440. 3 or 6 bytes and composite with background
  191441. "in place" if transparent (3x compare/pixel
  191442. compared to doing composite with gray bkgrnd)
  191443. - Gray + alpha -> convert to RGB + alpha, composite with background and
  191444. remove alpha bytes (3x float operations/pixel
  191445. compared with composite on gray background)
  191446. Greg's change will do this. The reason it wasn't done before is for
  191447. performance, as this increases the per-pixel operations. If we would check
  191448. in advance if the background was gray or RGB, and position the gray-to-RGB
  191449. transform appropriately, then it would save a lot of work/time.
  191450. */
  191451. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191452. /* if gray -> RGB, do so now only if background is non-gray; else do later
  191453. * for performance reasons */
  191454. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191455. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191456. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191457. #endif
  191458. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191459. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191460. ((png_ptr->num_trans != 0 ) ||
  191461. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  191462. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191463. &(png_ptr->trans_values), &(png_ptr->background)
  191464. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191465. , &(png_ptr->background_1),
  191466. png_ptr->gamma_table, png_ptr->gamma_from_1,
  191467. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  191468. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  191469. png_ptr->gamma_shift
  191470. #endif
  191471. );
  191472. #endif
  191473. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191474. if ((png_ptr->transformations & PNG_GAMMA) &&
  191475. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191476. !((png_ptr->transformations & PNG_BACKGROUND) &&
  191477. ((png_ptr->num_trans != 0) ||
  191478. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  191479. #endif
  191480. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  191481. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191482. png_ptr->gamma_table, png_ptr->gamma_16_table,
  191483. png_ptr->gamma_shift);
  191484. #endif
  191485. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191486. if (png_ptr->transformations & PNG_16_TO_8)
  191487. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191488. #endif
  191489. #if defined(PNG_READ_DITHER_SUPPORTED)
  191490. if (png_ptr->transformations & PNG_DITHER)
  191491. {
  191492. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  191493. png_ptr->palette_lookup, png_ptr->dither_index);
  191494. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  191495. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  191496. }
  191497. #endif
  191498. #if defined(PNG_READ_INVERT_SUPPORTED)
  191499. if (png_ptr->transformations & PNG_INVERT_MONO)
  191500. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191501. #endif
  191502. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191503. if (png_ptr->transformations & PNG_SHIFT)
  191504. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191505. &(png_ptr->shift));
  191506. #endif
  191507. #if defined(PNG_READ_PACK_SUPPORTED)
  191508. if (png_ptr->transformations & PNG_PACK)
  191509. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191510. #endif
  191511. #if defined(PNG_READ_BGR_SUPPORTED)
  191512. if (png_ptr->transformations & PNG_BGR)
  191513. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191514. #endif
  191515. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  191516. if (png_ptr->transformations & PNG_PACKSWAP)
  191517. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191518. #endif
  191519. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191520. /* if gray -> RGB, do so now only if we did not do so above */
  191521. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191522. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  191523. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191524. #endif
  191525. #if defined(PNG_READ_FILLER_SUPPORTED)
  191526. if (png_ptr->transformations & PNG_FILLER)
  191527. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  191528. (png_uint_32)png_ptr->filler, png_ptr->flags);
  191529. #endif
  191530. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191531. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191532. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191533. #endif
  191534. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191535. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  191536. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191537. #endif
  191538. #if defined(PNG_READ_SWAP_SUPPORTED)
  191539. if (png_ptr->transformations & PNG_SWAP_BYTES)
  191540. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  191541. #endif
  191542. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191543. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  191544. {
  191545. if(png_ptr->read_user_transform_fn != NULL)
  191546. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  191547. (png_ptr, /* png_ptr */
  191548. &(png_ptr->row_info), /* row_info: */
  191549. /* png_uint_32 width; width of row */
  191550. /* png_uint_32 rowbytes; number of bytes in row */
  191551. /* png_byte color_type; color type of pixels */
  191552. /* png_byte bit_depth; bit depth of samples */
  191553. /* png_byte channels; number of channels (1-4) */
  191554. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  191555. png_ptr->row_buf + 1); /* start of pixel data for row */
  191556. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  191557. if(png_ptr->user_transform_depth)
  191558. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  191559. if(png_ptr->user_transform_channels)
  191560. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  191561. #endif
  191562. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  191563. png_ptr->row_info.channels);
  191564. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  191565. png_ptr->row_info.width);
  191566. }
  191567. #endif
  191568. }
  191569. #if defined(PNG_READ_PACK_SUPPORTED)
  191570. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  191571. * without changing the actual values. Thus, if you had a row with
  191572. * a bit depth of 1, you would end up with bytes that only contained
  191573. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  191574. * png_do_shift() after this.
  191575. */
  191576. void /* PRIVATE */
  191577. png_do_unpack(png_row_infop row_info, png_bytep row)
  191578. {
  191579. png_debug(1, "in png_do_unpack\n");
  191580. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191581. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  191582. #else
  191583. if (row_info->bit_depth < 8)
  191584. #endif
  191585. {
  191586. png_uint_32 i;
  191587. png_uint_32 row_width=row_info->width;
  191588. switch (row_info->bit_depth)
  191589. {
  191590. case 1:
  191591. {
  191592. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  191593. png_bytep dp = row + (png_size_t)row_width - 1;
  191594. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  191595. for (i = 0; i < row_width; i++)
  191596. {
  191597. *dp = (png_byte)((*sp >> shift) & 0x01);
  191598. if (shift == 7)
  191599. {
  191600. shift = 0;
  191601. sp--;
  191602. }
  191603. else
  191604. shift++;
  191605. dp--;
  191606. }
  191607. break;
  191608. }
  191609. case 2:
  191610. {
  191611. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  191612. png_bytep dp = row + (png_size_t)row_width - 1;
  191613. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  191614. for (i = 0; i < row_width; i++)
  191615. {
  191616. *dp = (png_byte)((*sp >> shift) & 0x03);
  191617. if (shift == 6)
  191618. {
  191619. shift = 0;
  191620. sp--;
  191621. }
  191622. else
  191623. shift += 2;
  191624. dp--;
  191625. }
  191626. break;
  191627. }
  191628. case 4:
  191629. {
  191630. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  191631. png_bytep dp = row + (png_size_t)row_width - 1;
  191632. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  191633. for (i = 0; i < row_width; i++)
  191634. {
  191635. *dp = (png_byte)((*sp >> shift) & 0x0f);
  191636. if (shift == 4)
  191637. {
  191638. shift = 0;
  191639. sp--;
  191640. }
  191641. else
  191642. shift = 4;
  191643. dp--;
  191644. }
  191645. break;
  191646. }
  191647. }
  191648. row_info->bit_depth = 8;
  191649. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191650. row_info->rowbytes = row_width * row_info->channels;
  191651. }
  191652. }
  191653. #endif
  191654. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191655. /* Reverse the effects of png_do_shift. This routine merely shifts the
  191656. * pixels back to their significant bits values. Thus, if you have
  191657. * a row of bit depth 8, but only 5 are significant, this will shift
  191658. * the values back to 0 through 31.
  191659. */
  191660. void /* PRIVATE */
  191661. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  191662. {
  191663. png_debug(1, "in png_do_unshift\n");
  191664. if (
  191665. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191666. row != NULL && row_info != NULL && sig_bits != NULL &&
  191667. #endif
  191668. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  191669. {
  191670. int shift[4];
  191671. int channels = 0;
  191672. int c;
  191673. png_uint_16 value = 0;
  191674. png_uint_32 row_width = row_info->width;
  191675. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  191676. {
  191677. shift[channels++] = row_info->bit_depth - sig_bits->red;
  191678. shift[channels++] = row_info->bit_depth - sig_bits->green;
  191679. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  191680. }
  191681. else
  191682. {
  191683. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  191684. }
  191685. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  191686. {
  191687. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  191688. }
  191689. for (c = 0; c < channels; c++)
  191690. {
  191691. if (shift[c] <= 0)
  191692. shift[c] = 0;
  191693. else
  191694. value = 1;
  191695. }
  191696. if (!value)
  191697. return;
  191698. switch (row_info->bit_depth)
  191699. {
  191700. case 2:
  191701. {
  191702. png_bytep bp;
  191703. png_uint_32 i;
  191704. png_uint_32 istop = row_info->rowbytes;
  191705. for (bp = row, i = 0; i < istop; i++)
  191706. {
  191707. *bp >>= 1;
  191708. *bp++ &= 0x55;
  191709. }
  191710. break;
  191711. }
  191712. case 4:
  191713. {
  191714. png_bytep bp = row;
  191715. png_uint_32 i;
  191716. png_uint_32 istop = row_info->rowbytes;
  191717. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  191718. (png_byte)((int)0xf >> shift[0]));
  191719. for (i = 0; i < istop; i++)
  191720. {
  191721. *bp >>= shift[0];
  191722. *bp++ &= mask;
  191723. }
  191724. break;
  191725. }
  191726. case 8:
  191727. {
  191728. png_bytep bp = row;
  191729. png_uint_32 i;
  191730. png_uint_32 istop = row_width * channels;
  191731. for (i = 0; i < istop; i++)
  191732. {
  191733. *bp++ >>= shift[i%channels];
  191734. }
  191735. break;
  191736. }
  191737. case 16:
  191738. {
  191739. png_bytep bp = row;
  191740. png_uint_32 i;
  191741. png_uint_32 istop = channels * row_width;
  191742. for (i = 0; i < istop; i++)
  191743. {
  191744. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  191745. value >>= shift[i%channels];
  191746. *bp++ = (png_byte)(value >> 8);
  191747. *bp++ = (png_byte)(value & 0xff);
  191748. }
  191749. break;
  191750. }
  191751. }
  191752. }
  191753. }
  191754. #endif
  191755. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191756. /* chop rows of bit depth 16 down to 8 */
  191757. void /* PRIVATE */
  191758. png_do_chop(png_row_infop row_info, png_bytep row)
  191759. {
  191760. png_debug(1, "in png_do_chop\n");
  191761. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191762. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  191763. #else
  191764. if (row_info->bit_depth == 16)
  191765. #endif
  191766. {
  191767. png_bytep sp = row;
  191768. png_bytep dp = row;
  191769. png_uint_32 i;
  191770. png_uint_32 istop = row_info->width * row_info->channels;
  191771. for (i = 0; i<istop; i++, sp += 2, dp++)
  191772. {
  191773. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  191774. /* This does a more accurate scaling of the 16-bit color
  191775. * value, rather than a simple low-byte truncation.
  191776. *
  191777. * What the ideal calculation should be:
  191778. * *dp = (((((png_uint_32)(*sp) << 8) |
  191779. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  191780. *
  191781. * GRR: no, I think this is what it really should be:
  191782. * *dp = (((((png_uint_32)(*sp) << 8) |
  191783. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  191784. *
  191785. * GRR: here's the exact calculation with shifts:
  191786. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  191787. * *dp = (temp - (temp >> 8)) >> 8;
  191788. *
  191789. * Approximate calculation with shift/add instead of multiply/divide:
  191790. * *dp = ((((png_uint_32)(*sp) << 8) |
  191791. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  191792. *
  191793. * What we actually do to avoid extra shifting and conversion:
  191794. */
  191795. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  191796. #else
  191797. /* Simply discard the low order byte */
  191798. *dp = *sp;
  191799. #endif
  191800. }
  191801. row_info->bit_depth = 8;
  191802. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  191803. row_info->rowbytes = row_info->width * row_info->channels;
  191804. }
  191805. }
  191806. #endif
  191807. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  191808. void /* PRIVATE */
  191809. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  191810. {
  191811. png_debug(1, "in png_do_read_swap_alpha\n");
  191812. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191813. if (row != NULL && row_info != NULL)
  191814. #endif
  191815. {
  191816. png_uint_32 row_width = row_info->width;
  191817. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191818. {
  191819. /* This converts from RGBA to ARGB */
  191820. if (row_info->bit_depth == 8)
  191821. {
  191822. png_bytep sp = row + row_info->rowbytes;
  191823. png_bytep dp = sp;
  191824. png_byte save;
  191825. png_uint_32 i;
  191826. for (i = 0; i < row_width; i++)
  191827. {
  191828. save = *(--sp);
  191829. *(--dp) = *(--sp);
  191830. *(--dp) = *(--sp);
  191831. *(--dp) = *(--sp);
  191832. *(--dp) = save;
  191833. }
  191834. }
  191835. /* This converts from RRGGBBAA to AARRGGBB */
  191836. else
  191837. {
  191838. png_bytep sp = row + row_info->rowbytes;
  191839. png_bytep dp = sp;
  191840. png_byte save[2];
  191841. png_uint_32 i;
  191842. for (i = 0; i < row_width; i++)
  191843. {
  191844. save[0] = *(--sp);
  191845. save[1] = *(--sp);
  191846. *(--dp) = *(--sp);
  191847. *(--dp) = *(--sp);
  191848. *(--dp) = *(--sp);
  191849. *(--dp) = *(--sp);
  191850. *(--dp) = *(--sp);
  191851. *(--dp) = *(--sp);
  191852. *(--dp) = save[0];
  191853. *(--dp) = save[1];
  191854. }
  191855. }
  191856. }
  191857. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191858. {
  191859. /* This converts from GA to AG */
  191860. if (row_info->bit_depth == 8)
  191861. {
  191862. png_bytep sp = row + row_info->rowbytes;
  191863. png_bytep dp = sp;
  191864. png_byte save;
  191865. png_uint_32 i;
  191866. for (i = 0; i < row_width; i++)
  191867. {
  191868. save = *(--sp);
  191869. *(--dp) = *(--sp);
  191870. *(--dp) = save;
  191871. }
  191872. }
  191873. /* This converts from GGAA to AAGG */
  191874. else
  191875. {
  191876. png_bytep sp = row + row_info->rowbytes;
  191877. png_bytep dp = sp;
  191878. png_byte save[2];
  191879. png_uint_32 i;
  191880. for (i = 0; i < row_width; i++)
  191881. {
  191882. save[0] = *(--sp);
  191883. save[1] = *(--sp);
  191884. *(--dp) = *(--sp);
  191885. *(--dp) = *(--sp);
  191886. *(--dp) = save[0];
  191887. *(--dp) = save[1];
  191888. }
  191889. }
  191890. }
  191891. }
  191892. }
  191893. #endif
  191894. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191895. void /* PRIVATE */
  191896. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  191897. {
  191898. png_debug(1, "in png_do_read_invert_alpha\n");
  191899. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191900. if (row != NULL && row_info != NULL)
  191901. #endif
  191902. {
  191903. png_uint_32 row_width = row_info->width;
  191904. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  191905. {
  191906. /* This inverts the alpha channel in RGBA */
  191907. if (row_info->bit_depth == 8)
  191908. {
  191909. png_bytep sp = row + row_info->rowbytes;
  191910. png_bytep dp = sp;
  191911. png_uint_32 i;
  191912. for (i = 0; i < row_width; i++)
  191913. {
  191914. *(--dp) = (png_byte)(255 - *(--sp));
  191915. /* This does nothing:
  191916. *(--dp) = *(--sp);
  191917. *(--dp) = *(--sp);
  191918. *(--dp) = *(--sp);
  191919. We can replace it with:
  191920. */
  191921. sp-=3;
  191922. dp=sp;
  191923. }
  191924. }
  191925. /* This inverts the alpha channel in RRGGBBAA */
  191926. else
  191927. {
  191928. png_bytep sp = row + row_info->rowbytes;
  191929. png_bytep dp = sp;
  191930. png_uint_32 i;
  191931. for (i = 0; i < row_width; i++)
  191932. {
  191933. *(--dp) = (png_byte)(255 - *(--sp));
  191934. *(--dp) = (png_byte)(255 - *(--sp));
  191935. /* This does nothing:
  191936. *(--dp) = *(--sp);
  191937. *(--dp) = *(--sp);
  191938. *(--dp) = *(--sp);
  191939. *(--dp) = *(--sp);
  191940. *(--dp) = *(--sp);
  191941. *(--dp) = *(--sp);
  191942. We can replace it with:
  191943. */
  191944. sp-=6;
  191945. dp=sp;
  191946. }
  191947. }
  191948. }
  191949. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  191950. {
  191951. /* This inverts the alpha channel in GA */
  191952. if (row_info->bit_depth == 8)
  191953. {
  191954. png_bytep sp = row + row_info->rowbytes;
  191955. png_bytep dp = sp;
  191956. png_uint_32 i;
  191957. for (i = 0; i < row_width; i++)
  191958. {
  191959. *(--dp) = (png_byte)(255 - *(--sp));
  191960. *(--dp) = *(--sp);
  191961. }
  191962. }
  191963. /* This inverts the alpha channel in GGAA */
  191964. else
  191965. {
  191966. png_bytep sp = row + row_info->rowbytes;
  191967. png_bytep dp = sp;
  191968. png_uint_32 i;
  191969. for (i = 0; i < row_width; i++)
  191970. {
  191971. *(--dp) = (png_byte)(255 - *(--sp));
  191972. *(--dp) = (png_byte)(255 - *(--sp));
  191973. /*
  191974. *(--dp) = *(--sp);
  191975. *(--dp) = *(--sp);
  191976. */
  191977. sp-=2;
  191978. dp=sp;
  191979. }
  191980. }
  191981. }
  191982. }
  191983. }
  191984. #endif
  191985. #if defined(PNG_READ_FILLER_SUPPORTED)
  191986. /* Add filler channel if we have RGB color */
  191987. void /* PRIVATE */
  191988. png_do_read_filler(png_row_infop row_info, png_bytep row,
  191989. png_uint_32 filler, png_uint_32 flags)
  191990. {
  191991. png_uint_32 i;
  191992. png_uint_32 row_width = row_info->width;
  191993. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  191994. png_byte lo_filler = (png_byte)(filler & 0xff);
  191995. png_debug(1, "in png_do_read_filler\n");
  191996. if (
  191997. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191998. row != NULL && row_info != NULL &&
  191999. #endif
  192000. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192001. {
  192002. if(row_info->bit_depth == 8)
  192003. {
  192004. /* This changes the data from G to GX */
  192005. if (flags & PNG_FLAG_FILLER_AFTER)
  192006. {
  192007. png_bytep sp = row + (png_size_t)row_width;
  192008. png_bytep dp = sp + (png_size_t)row_width;
  192009. for (i = 1; i < row_width; i++)
  192010. {
  192011. *(--dp) = lo_filler;
  192012. *(--dp) = *(--sp);
  192013. }
  192014. *(--dp) = lo_filler;
  192015. row_info->channels = 2;
  192016. row_info->pixel_depth = 16;
  192017. row_info->rowbytes = row_width * 2;
  192018. }
  192019. /* This changes the data from G to XG */
  192020. else
  192021. {
  192022. png_bytep sp = row + (png_size_t)row_width;
  192023. png_bytep dp = sp + (png_size_t)row_width;
  192024. for (i = 0; i < row_width; i++)
  192025. {
  192026. *(--dp) = *(--sp);
  192027. *(--dp) = lo_filler;
  192028. }
  192029. row_info->channels = 2;
  192030. row_info->pixel_depth = 16;
  192031. row_info->rowbytes = row_width * 2;
  192032. }
  192033. }
  192034. else if(row_info->bit_depth == 16)
  192035. {
  192036. /* This changes the data from GG to GGXX */
  192037. if (flags & PNG_FLAG_FILLER_AFTER)
  192038. {
  192039. png_bytep sp = row + (png_size_t)row_width * 2;
  192040. png_bytep dp = sp + (png_size_t)row_width * 2;
  192041. for (i = 1; i < row_width; i++)
  192042. {
  192043. *(--dp) = hi_filler;
  192044. *(--dp) = lo_filler;
  192045. *(--dp) = *(--sp);
  192046. *(--dp) = *(--sp);
  192047. }
  192048. *(--dp) = hi_filler;
  192049. *(--dp) = lo_filler;
  192050. row_info->channels = 2;
  192051. row_info->pixel_depth = 32;
  192052. row_info->rowbytes = row_width * 4;
  192053. }
  192054. /* This changes the data from GG to XXGG */
  192055. else
  192056. {
  192057. png_bytep sp = row + (png_size_t)row_width * 2;
  192058. png_bytep dp = sp + (png_size_t)row_width * 2;
  192059. for (i = 0; i < row_width; i++)
  192060. {
  192061. *(--dp) = *(--sp);
  192062. *(--dp) = *(--sp);
  192063. *(--dp) = hi_filler;
  192064. *(--dp) = lo_filler;
  192065. }
  192066. row_info->channels = 2;
  192067. row_info->pixel_depth = 32;
  192068. row_info->rowbytes = row_width * 4;
  192069. }
  192070. }
  192071. } /* COLOR_TYPE == GRAY */
  192072. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192073. {
  192074. if(row_info->bit_depth == 8)
  192075. {
  192076. /* This changes the data from RGB to RGBX */
  192077. if (flags & PNG_FLAG_FILLER_AFTER)
  192078. {
  192079. png_bytep sp = row + (png_size_t)row_width * 3;
  192080. png_bytep dp = sp + (png_size_t)row_width;
  192081. for (i = 1; i < row_width; i++)
  192082. {
  192083. *(--dp) = lo_filler;
  192084. *(--dp) = *(--sp);
  192085. *(--dp) = *(--sp);
  192086. *(--dp) = *(--sp);
  192087. }
  192088. *(--dp) = lo_filler;
  192089. row_info->channels = 4;
  192090. row_info->pixel_depth = 32;
  192091. row_info->rowbytes = row_width * 4;
  192092. }
  192093. /* This changes the data from RGB to XRGB */
  192094. else
  192095. {
  192096. png_bytep sp = row + (png_size_t)row_width * 3;
  192097. png_bytep dp = sp + (png_size_t)row_width;
  192098. for (i = 0; i < row_width; i++)
  192099. {
  192100. *(--dp) = *(--sp);
  192101. *(--dp) = *(--sp);
  192102. *(--dp) = *(--sp);
  192103. *(--dp) = lo_filler;
  192104. }
  192105. row_info->channels = 4;
  192106. row_info->pixel_depth = 32;
  192107. row_info->rowbytes = row_width * 4;
  192108. }
  192109. }
  192110. else if(row_info->bit_depth == 16)
  192111. {
  192112. /* This changes the data from RRGGBB to RRGGBBXX */
  192113. if (flags & PNG_FLAG_FILLER_AFTER)
  192114. {
  192115. png_bytep sp = row + (png_size_t)row_width * 6;
  192116. png_bytep dp = sp + (png_size_t)row_width * 2;
  192117. for (i = 1; i < row_width; i++)
  192118. {
  192119. *(--dp) = hi_filler;
  192120. *(--dp) = lo_filler;
  192121. *(--dp) = *(--sp);
  192122. *(--dp) = *(--sp);
  192123. *(--dp) = *(--sp);
  192124. *(--dp) = *(--sp);
  192125. *(--dp) = *(--sp);
  192126. *(--dp) = *(--sp);
  192127. }
  192128. *(--dp) = hi_filler;
  192129. *(--dp) = lo_filler;
  192130. row_info->channels = 4;
  192131. row_info->pixel_depth = 64;
  192132. row_info->rowbytes = row_width * 8;
  192133. }
  192134. /* This changes the data from RRGGBB to XXRRGGBB */
  192135. else
  192136. {
  192137. png_bytep sp = row + (png_size_t)row_width * 6;
  192138. png_bytep dp = sp + (png_size_t)row_width * 2;
  192139. for (i = 0; i < row_width; i++)
  192140. {
  192141. *(--dp) = *(--sp);
  192142. *(--dp) = *(--sp);
  192143. *(--dp) = *(--sp);
  192144. *(--dp) = *(--sp);
  192145. *(--dp) = *(--sp);
  192146. *(--dp) = *(--sp);
  192147. *(--dp) = hi_filler;
  192148. *(--dp) = lo_filler;
  192149. }
  192150. row_info->channels = 4;
  192151. row_info->pixel_depth = 64;
  192152. row_info->rowbytes = row_width * 8;
  192153. }
  192154. }
  192155. } /* COLOR_TYPE == RGB */
  192156. }
  192157. #endif
  192158. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192159. /* expand grayscale files to RGB, with or without alpha */
  192160. void /* PRIVATE */
  192161. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192162. {
  192163. png_uint_32 i;
  192164. png_uint_32 row_width = row_info->width;
  192165. png_debug(1, "in png_do_gray_to_rgb\n");
  192166. if (row_info->bit_depth >= 8 &&
  192167. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192168. row != NULL && row_info != NULL &&
  192169. #endif
  192170. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192171. {
  192172. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192173. {
  192174. if (row_info->bit_depth == 8)
  192175. {
  192176. png_bytep sp = row + (png_size_t)row_width - 1;
  192177. png_bytep dp = sp + (png_size_t)row_width * 2;
  192178. for (i = 0; i < row_width; i++)
  192179. {
  192180. *(dp--) = *sp;
  192181. *(dp--) = *sp;
  192182. *(dp--) = *(sp--);
  192183. }
  192184. }
  192185. else
  192186. {
  192187. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192188. png_bytep dp = sp + (png_size_t)row_width * 4;
  192189. for (i = 0; i < row_width; i++)
  192190. {
  192191. *(dp--) = *sp;
  192192. *(dp--) = *(sp - 1);
  192193. *(dp--) = *sp;
  192194. *(dp--) = *(sp - 1);
  192195. *(dp--) = *(sp--);
  192196. *(dp--) = *(sp--);
  192197. }
  192198. }
  192199. }
  192200. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192201. {
  192202. if (row_info->bit_depth == 8)
  192203. {
  192204. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192205. png_bytep dp = sp + (png_size_t)row_width * 2;
  192206. for (i = 0; i < row_width; i++)
  192207. {
  192208. *(dp--) = *(sp--);
  192209. *(dp--) = *sp;
  192210. *(dp--) = *sp;
  192211. *(dp--) = *(sp--);
  192212. }
  192213. }
  192214. else
  192215. {
  192216. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192217. png_bytep dp = sp + (png_size_t)row_width * 4;
  192218. for (i = 0; i < row_width; i++)
  192219. {
  192220. *(dp--) = *(sp--);
  192221. *(dp--) = *(sp--);
  192222. *(dp--) = *sp;
  192223. *(dp--) = *(sp - 1);
  192224. *(dp--) = *sp;
  192225. *(dp--) = *(sp - 1);
  192226. *(dp--) = *(sp--);
  192227. *(dp--) = *(sp--);
  192228. }
  192229. }
  192230. }
  192231. row_info->channels += (png_byte)2;
  192232. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192233. row_info->pixel_depth = (png_byte)(row_info->channels *
  192234. row_info->bit_depth);
  192235. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192236. }
  192237. }
  192238. #endif
  192239. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192240. /* reduce RGB files to grayscale, with or without alpha
  192241. * using the equation given in Poynton's ColorFAQ at
  192242. * <http://www.inforamp.net/~poynton/>
  192243. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192244. *
  192245. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192246. *
  192247. * We approximate this with
  192248. *
  192249. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192250. *
  192251. * which can be expressed with integers as
  192252. *
  192253. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192254. *
  192255. * The calculation is to be done in a linear colorspace.
  192256. *
  192257. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192258. */
  192259. int /* PRIVATE */
  192260. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192261. {
  192262. png_uint_32 i;
  192263. png_uint_32 row_width = row_info->width;
  192264. int rgb_error = 0;
  192265. png_debug(1, "in png_do_rgb_to_gray\n");
  192266. if (
  192267. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192268. row != NULL && row_info != NULL &&
  192269. #endif
  192270. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192271. {
  192272. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192273. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192274. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192275. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192276. {
  192277. if (row_info->bit_depth == 8)
  192278. {
  192279. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192280. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192281. {
  192282. png_bytep sp = row;
  192283. png_bytep dp = row;
  192284. for (i = 0; i < row_width; i++)
  192285. {
  192286. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192287. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192288. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192289. if(red != green || red != blue)
  192290. {
  192291. rgb_error |= 1;
  192292. *(dp++) = png_ptr->gamma_from_1[
  192293. (rc*red+gc*green+bc*blue)>>15];
  192294. }
  192295. else
  192296. *(dp++) = *(sp-1);
  192297. }
  192298. }
  192299. else
  192300. #endif
  192301. {
  192302. png_bytep sp = row;
  192303. png_bytep dp = row;
  192304. for (i = 0; i < row_width; i++)
  192305. {
  192306. png_byte red = *(sp++);
  192307. png_byte green = *(sp++);
  192308. png_byte blue = *(sp++);
  192309. if(red != green || red != blue)
  192310. {
  192311. rgb_error |= 1;
  192312. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  192313. }
  192314. else
  192315. *(dp++) = *(sp-1);
  192316. }
  192317. }
  192318. }
  192319. else /* RGB bit_depth == 16 */
  192320. {
  192321. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192322. if (png_ptr->gamma_16_to_1 != NULL &&
  192323. png_ptr->gamma_16_from_1 != NULL)
  192324. {
  192325. png_bytep sp = row;
  192326. png_bytep dp = row;
  192327. for (i = 0; i < row_width; i++)
  192328. {
  192329. png_uint_16 red, green, blue, w;
  192330. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192331. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192332. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192333. if(red == green && red == blue)
  192334. w = red;
  192335. else
  192336. {
  192337. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192338. png_ptr->gamma_shift][red>>8];
  192339. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192340. png_ptr->gamma_shift][green>>8];
  192341. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192342. png_ptr->gamma_shift][blue>>8];
  192343. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  192344. + bc*blue_1)>>15);
  192345. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192346. png_ptr->gamma_shift][gray16 >> 8];
  192347. rgb_error |= 1;
  192348. }
  192349. *(dp++) = (png_byte)((w>>8) & 0xff);
  192350. *(dp++) = (png_byte)(w & 0xff);
  192351. }
  192352. }
  192353. else
  192354. #endif
  192355. {
  192356. png_bytep sp = row;
  192357. png_bytep dp = row;
  192358. for (i = 0; i < row_width; i++)
  192359. {
  192360. png_uint_16 red, green, blue, gray16;
  192361. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192362. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192363. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192364. if(red != green || red != blue)
  192365. rgb_error |= 1;
  192366. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192367. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192368. *(dp++) = (png_byte)(gray16 & 0xff);
  192369. }
  192370. }
  192371. }
  192372. }
  192373. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192374. {
  192375. if (row_info->bit_depth == 8)
  192376. {
  192377. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192378. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192379. {
  192380. png_bytep sp = row;
  192381. png_bytep dp = row;
  192382. for (i = 0; i < row_width; i++)
  192383. {
  192384. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  192385. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  192386. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  192387. if(red != green || red != blue)
  192388. rgb_error |= 1;
  192389. *(dp++) = png_ptr->gamma_from_1
  192390. [(rc*red + gc*green + bc*blue)>>15];
  192391. *(dp++) = *(sp++); /* alpha */
  192392. }
  192393. }
  192394. else
  192395. #endif
  192396. {
  192397. png_bytep sp = row;
  192398. png_bytep dp = row;
  192399. for (i = 0; i < row_width; i++)
  192400. {
  192401. png_byte red = *(sp++);
  192402. png_byte green = *(sp++);
  192403. png_byte blue = *(sp++);
  192404. if(red != green || red != blue)
  192405. rgb_error |= 1;
  192406. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  192407. *(dp++) = *(sp++); /* alpha */
  192408. }
  192409. }
  192410. }
  192411. else /* RGBA bit_depth == 16 */
  192412. {
  192413. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192414. if (png_ptr->gamma_16_to_1 != NULL &&
  192415. png_ptr->gamma_16_from_1 != NULL)
  192416. {
  192417. png_bytep sp = row;
  192418. png_bytep dp = row;
  192419. for (i = 0; i < row_width; i++)
  192420. {
  192421. png_uint_16 red, green, blue, w;
  192422. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192423. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192424. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  192425. if(red == green && red == blue)
  192426. w = red;
  192427. else
  192428. {
  192429. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  192430. png_ptr->gamma_shift][red>>8];
  192431. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  192432. png_ptr->gamma_shift][green>>8];
  192433. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  192434. png_ptr->gamma_shift][blue>>8];
  192435. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  192436. + gc * green_1 + bc * blue_1)>>15);
  192437. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  192438. png_ptr->gamma_shift][gray16 >> 8];
  192439. rgb_error |= 1;
  192440. }
  192441. *(dp++) = (png_byte)((w>>8) & 0xff);
  192442. *(dp++) = (png_byte)(w & 0xff);
  192443. *(dp++) = *(sp++); /* alpha */
  192444. *(dp++) = *(sp++);
  192445. }
  192446. }
  192447. else
  192448. #endif
  192449. {
  192450. png_bytep sp = row;
  192451. png_bytep dp = row;
  192452. for (i = 0; i < row_width; i++)
  192453. {
  192454. png_uint_16 red, green, blue, gray16;
  192455. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192456. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192457. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  192458. if(red != green || red != blue)
  192459. rgb_error |= 1;
  192460. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  192461. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  192462. *(dp++) = (png_byte)(gray16 & 0xff);
  192463. *(dp++) = *(sp++); /* alpha */
  192464. *(dp++) = *(sp++);
  192465. }
  192466. }
  192467. }
  192468. }
  192469. row_info->channels -= (png_byte)2;
  192470. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  192471. row_info->pixel_depth = (png_byte)(row_info->channels *
  192472. row_info->bit_depth);
  192473. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192474. }
  192475. return rgb_error;
  192476. }
  192477. #endif
  192478. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  192479. * large of png_color. This lets grayscale images be treated as
  192480. * paletted. Most useful for gamma correction and simplification
  192481. * of code.
  192482. */
  192483. void PNGAPI
  192484. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  192485. {
  192486. int num_palette;
  192487. int color_inc;
  192488. int i;
  192489. int v;
  192490. png_debug(1, "in png_do_build_grayscale_palette\n");
  192491. if (palette == NULL)
  192492. return;
  192493. switch (bit_depth)
  192494. {
  192495. case 1:
  192496. num_palette = 2;
  192497. color_inc = 0xff;
  192498. break;
  192499. case 2:
  192500. num_palette = 4;
  192501. color_inc = 0x55;
  192502. break;
  192503. case 4:
  192504. num_palette = 16;
  192505. color_inc = 0x11;
  192506. break;
  192507. case 8:
  192508. num_palette = 256;
  192509. color_inc = 1;
  192510. break;
  192511. default:
  192512. num_palette = 0;
  192513. color_inc = 0;
  192514. break;
  192515. }
  192516. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  192517. {
  192518. palette[i].red = (png_byte)v;
  192519. palette[i].green = (png_byte)v;
  192520. palette[i].blue = (png_byte)v;
  192521. }
  192522. }
  192523. /* This function is currently unused. Do we really need it? */
  192524. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  192525. void /* PRIVATE */
  192526. png_correct_palette(png_structp png_ptr, png_colorp palette,
  192527. int num_palette)
  192528. {
  192529. png_debug(1, "in png_correct_palette\n");
  192530. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  192531. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  192532. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  192533. {
  192534. png_color back, back_1;
  192535. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  192536. {
  192537. back.red = png_ptr->gamma_table[png_ptr->background.red];
  192538. back.green = png_ptr->gamma_table[png_ptr->background.green];
  192539. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  192540. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  192541. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  192542. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  192543. }
  192544. else
  192545. {
  192546. double g;
  192547. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  192548. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  192549. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  192550. {
  192551. back.red = png_ptr->background.red;
  192552. back.green = png_ptr->background.green;
  192553. back.blue = png_ptr->background.blue;
  192554. }
  192555. else
  192556. {
  192557. back.red =
  192558. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192559. 255.0 + 0.5);
  192560. back.green =
  192561. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192562. 255.0 + 0.5);
  192563. back.blue =
  192564. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192565. 255.0 + 0.5);
  192566. }
  192567. g = 1.0 / png_ptr->background_gamma;
  192568. back_1.red =
  192569. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  192570. 255.0 + 0.5);
  192571. back_1.green =
  192572. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  192573. 255.0 + 0.5);
  192574. back_1.blue =
  192575. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  192576. 255.0 + 0.5);
  192577. }
  192578. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192579. {
  192580. png_uint_32 i;
  192581. for (i = 0; i < (png_uint_32)num_palette; i++)
  192582. {
  192583. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  192584. {
  192585. palette[i] = back;
  192586. }
  192587. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  192588. {
  192589. png_byte v, w;
  192590. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  192591. png_composite(w, v, png_ptr->trans[i], back_1.red);
  192592. palette[i].red = png_ptr->gamma_from_1[w];
  192593. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  192594. png_composite(w, v, png_ptr->trans[i], back_1.green);
  192595. palette[i].green = png_ptr->gamma_from_1[w];
  192596. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  192597. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  192598. palette[i].blue = png_ptr->gamma_from_1[w];
  192599. }
  192600. else
  192601. {
  192602. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192603. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192604. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192605. }
  192606. }
  192607. }
  192608. else
  192609. {
  192610. int i;
  192611. for (i = 0; i < num_palette; i++)
  192612. {
  192613. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  192614. {
  192615. palette[i] = back;
  192616. }
  192617. else
  192618. {
  192619. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192620. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192621. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192622. }
  192623. }
  192624. }
  192625. }
  192626. else
  192627. #endif
  192628. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192629. if (png_ptr->transformations & PNG_GAMMA)
  192630. {
  192631. int i;
  192632. for (i = 0; i < num_palette; i++)
  192633. {
  192634. palette[i].red = png_ptr->gamma_table[palette[i].red];
  192635. palette[i].green = png_ptr->gamma_table[palette[i].green];
  192636. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  192637. }
  192638. }
  192639. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192640. else
  192641. #endif
  192642. #endif
  192643. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192644. if (png_ptr->transformations & PNG_BACKGROUND)
  192645. {
  192646. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192647. {
  192648. png_color back;
  192649. back.red = (png_byte)png_ptr->background.red;
  192650. back.green = (png_byte)png_ptr->background.green;
  192651. back.blue = (png_byte)png_ptr->background.blue;
  192652. for (i = 0; i < (int)png_ptr->num_trans; i++)
  192653. {
  192654. if (png_ptr->trans[i] == 0)
  192655. {
  192656. palette[i].red = back.red;
  192657. palette[i].green = back.green;
  192658. palette[i].blue = back.blue;
  192659. }
  192660. else if (png_ptr->trans[i] != 0xff)
  192661. {
  192662. png_composite(palette[i].red, png_ptr->palette[i].red,
  192663. png_ptr->trans[i], back.red);
  192664. png_composite(palette[i].green, png_ptr->palette[i].green,
  192665. png_ptr->trans[i], back.green);
  192666. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  192667. png_ptr->trans[i], back.blue);
  192668. }
  192669. }
  192670. }
  192671. else /* assume grayscale palette (what else could it be?) */
  192672. {
  192673. int i;
  192674. for (i = 0; i < num_palette; i++)
  192675. {
  192676. if (i == (png_byte)png_ptr->trans_values.gray)
  192677. {
  192678. palette[i].red = (png_byte)png_ptr->background.red;
  192679. palette[i].green = (png_byte)png_ptr->background.green;
  192680. palette[i].blue = (png_byte)png_ptr->background.blue;
  192681. }
  192682. }
  192683. }
  192684. }
  192685. #endif
  192686. }
  192687. #endif
  192688. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192689. /* Replace any alpha or transparency with the supplied background color.
  192690. * "background" is already in the screen gamma, while "background_1" is
  192691. * at a gamma of 1.0. Paletted files have already been taken care of.
  192692. */
  192693. void /* PRIVATE */
  192694. png_do_background(png_row_infop row_info, png_bytep row,
  192695. png_color_16p trans_values, png_color_16p background
  192696. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192697. , png_color_16p background_1,
  192698. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  192699. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  192700. png_uint_16pp gamma_16_to_1, int gamma_shift
  192701. #endif
  192702. )
  192703. {
  192704. png_bytep sp, dp;
  192705. png_uint_32 i;
  192706. png_uint_32 row_width=row_info->width;
  192707. int shift;
  192708. png_debug(1, "in png_do_background\n");
  192709. if (background != NULL &&
  192710. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192711. row != NULL && row_info != NULL &&
  192712. #endif
  192713. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  192714. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  192715. {
  192716. switch (row_info->color_type)
  192717. {
  192718. case PNG_COLOR_TYPE_GRAY:
  192719. {
  192720. switch (row_info->bit_depth)
  192721. {
  192722. case 1:
  192723. {
  192724. sp = row;
  192725. shift = 7;
  192726. for (i = 0; i < row_width; i++)
  192727. {
  192728. if ((png_uint_16)((*sp >> shift) & 0x01)
  192729. == trans_values->gray)
  192730. {
  192731. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  192732. *sp |= (png_byte)(background->gray << shift);
  192733. }
  192734. if (!shift)
  192735. {
  192736. shift = 7;
  192737. sp++;
  192738. }
  192739. else
  192740. shift--;
  192741. }
  192742. break;
  192743. }
  192744. case 2:
  192745. {
  192746. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192747. if (gamma_table != NULL)
  192748. {
  192749. sp = row;
  192750. shift = 6;
  192751. for (i = 0; i < row_width; i++)
  192752. {
  192753. if ((png_uint_16)((*sp >> shift) & 0x03)
  192754. == trans_values->gray)
  192755. {
  192756. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192757. *sp |= (png_byte)(background->gray << shift);
  192758. }
  192759. else
  192760. {
  192761. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  192762. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  192763. (p << 4) | (p << 6)] >> 6) & 0x03);
  192764. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192765. *sp |= (png_byte)(g << shift);
  192766. }
  192767. if (!shift)
  192768. {
  192769. shift = 6;
  192770. sp++;
  192771. }
  192772. else
  192773. shift -= 2;
  192774. }
  192775. }
  192776. else
  192777. #endif
  192778. {
  192779. sp = row;
  192780. shift = 6;
  192781. for (i = 0; i < row_width; i++)
  192782. {
  192783. if ((png_uint_16)((*sp >> shift) & 0x03)
  192784. == trans_values->gray)
  192785. {
  192786. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  192787. *sp |= (png_byte)(background->gray << shift);
  192788. }
  192789. if (!shift)
  192790. {
  192791. shift = 6;
  192792. sp++;
  192793. }
  192794. else
  192795. shift -= 2;
  192796. }
  192797. }
  192798. break;
  192799. }
  192800. case 4:
  192801. {
  192802. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192803. if (gamma_table != NULL)
  192804. {
  192805. sp = row;
  192806. shift = 4;
  192807. for (i = 0; i < row_width; i++)
  192808. {
  192809. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192810. == trans_values->gray)
  192811. {
  192812. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192813. *sp |= (png_byte)(background->gray << shift);
  192814. }
  192815. else
  192816. {
  192817. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  192818. png_byte g = (png_byte)((gamma_table[p |
  192819. (p << 4)] >> 4) & 0x0f);
  192820. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192821. *sp |= (png_byte)(g << shift);
  192822. }
  192823. if (!shift)
  192824. {
  192825. shift = 4;
  192826. sp++;
  192827. }
  192828. else
  192829. shift -= 4;
  192830. }
  192831. }
  192832. else
  192833. #endif
  192834. {
  192835. sp = row;
  192836. shift = 4;
  192837. for (i = 0; i < row_width; i++)
  192838. {
  192839. if ((png_uint_16)((*sp >> shift) & 0x0f)
  192840. == trans_values->gray)
  192841. {
  192842. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  192843. *sp |= (png_byte)(background->gray << shift);
  192844. }
  192845. if (!shift)
  192846. {
  192847. shift = 4;
  192848. sp++;
  192849. }
  192850. else
  192851. shift -= 4;
  192852. }
  192853. }
  192854. break;
  192855. }
  192856. case 8:
  192857. {
  192858. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192859. if (gamma_table != NULL)
  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. else
  192869. {
  192870. *sp = gamma_table[*sp];
  192871. }
  192872. }
  192873. }
  192874. else
  192875. #endif
  192876. {
  192877. sp = row;
  192878. for (i = 0; i < row_width; i++, sp++)
  192879. {
  192880. if (*sp == trans_values->gray)
  192881. {
  192882. *sp = (png_byte)background->gray;
  192883. }
  192884. }
  192885. }
  192886. break;
  192887. }
  192888. case 16:
  192889. {
  192890. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192891. if (gamma_16 != NULL)
  192892. {
  192893. sp = row;
  192894. for (i = 0; i < row_width; i++, sp += 2)
  192895. {
  192896. png_uint_16 v;
  192897. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192898. if (v == trans_values->gray)
  192899. {
  192900. /* background is already in screen gamma */
  192901. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192902. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192903. }
  192904. else
  192905. {
  192906. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  192907. *sp = (png_byte)((v >> 8) & 0xff);
  192908. *(sp + 1) = (png_byte)(v & 0xff);
  192909. }
  192910. }
  192911. }
  192912. else
  192913. #endif
  192914. {
  192915. sp = row;
  192916. for (i = 0; i < row_width; i++, sp += 2)
  192917. {
  192918. png_uint_16 v;
  192919. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192920. if (v == trans_values->gray)
  192921. {
  192922. *sp = (png_byte)((background->gray >> 8) & 0xff);
  192923. *(sp + 1) = (png_byte)(background->gray & 0xff);
  192924. }
  192925. }
  192926. }
  192927. break;
  192928. }
  192929. }
  192930. break;
  192931. }
  192932. case PNG_COLOR_TYPE_RGB:
  192933. {
  192934. if (row_info->bit_depth == 8)
  192935. {
  192936. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192937. if (gamma_table != NULL)
  192938. {
  192939. sp = row;
  192940. for (i = 0; i < row_width; i++, sp += 3)
  192941. {
  192942. if (*sp == trans_values->red &&
  192943. *(sp + 1) == trans_values->green &&
  192944. *(sp + 2) == trans_values->blue)
  192945. {
  192946. *sp = (png_byte)background->red;
  192947. *(sp + 1) = (png_byte)background->green;
  192948. *(sp + 2) = (png_byte)background->blue;
  192949. }
  192950. else
  192951. {
  192952. *sp = gamma_table[*sp];
  192953. *(sp + 1) = gamma_table[*(sp + 1)];
  192954. *(sp + 2) = gamma_table[*(sp + 2)];
  192955. }
  192956. }
  192957. }
  192958. else
  192959. #endif
  192960. {
  192961. sp = row;
  192962. for (i = 0; i < row_width; i++, sp += 3)
  192963. {
  192964. if (*sp == trans_values->red &&
  192965. *(sp + 1) == trans_values->green &&
  192966. *(sp + 2) == trans_values->blue)
  192967. {
  192968. *sp = (png_byte)background->red;
  192969. *(sp + 1) = (png_byte)background->green;
  192970. *(sp + 2) = (png_byte)background->blue;
  192971. }
  192972. }
  192973. }
  192974. }
  192975. else /* if (row_info->bit_depth == 16) */
  192976. {
  192977. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192978. if (gamma_16 != NULL)
  192979. {
  192980. sp = row;
  192981. for (i = 0; i < row_width; i++, sp += 6)
  192982. {
  192983. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  192984. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  192985. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  192986. if (r == trans_values->red && g == trans_values->green &&
  192987. b == trans_values->blue)
  192988. {
  192989. /* background is already in screen gamma */
  192990. *sp = (png_byte)((background->red >> 8) & 0xff);
  192991. *(sp + 1) = (png_byte)(background->red & 0xff);
  192992. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  192993. *(sp + 3) = (png_byte)(background->green & 0xff);
  192994. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  192995. *(sp + 5) = (png_byte)(background->blue & 0xff);
  192996. }
  192997. else
  192998. {
  192999. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193000. *sp = (png_byte)((v >> 8) & 0xff);
  193001. *(sp + 1) = (png_byte)(v & 0xff);
  193002. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193003. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  193004. *(sp + 3) = (png_byte)(v & 0xff);
  193005. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193006. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  193007. *(sp + 5) = (png_byte)(v & 0xff);
  193008. }
  193009. }
  193010. }
  193011. else
  193012. #endif
  193013. {
  193014. sp = row;
  193015. for (i = 0; i < row_width; i++, sp += 6)
  193016. {
  193017. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  193018. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193019. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  193020. if (r == trans_values->red && g == trans_values->green &&
  193021. b == trans_values->blue)
  193022. {
  193023. *sp = (png_byte)((background->red >> 8) & 0xff);
  193024. *(sp + 1) = (png_byte)(background->red & 0xff);
  193025. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193026. *(sp + 3) = (png_byte)(background->green & 0xff);
  193027. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193028. *(sp + 5) = (png_byte)(background->blue & 0xff);
  193029. }
  193030. }
  193031. }
  193032. }
  193033. break;
  193034. }
  193035. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193036. {
  193037. if (row_info->bit_depth == 8)
  193038. {
  193039. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193040. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193041. gamma_table != NULL)
  193042. {
  193043. sp = row;
  193044. dp = row;
  193045. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193046. {
  193047. png_uint_16 a = *(sp + 1);
  193048. if (a == 0xff)
  193049. {
  193050. *dp = gamma_table[*sp];
  193051. }
  193052. else if (a == 0)
  193053. {
  193054. /* background is already in screen gamma */
  193055. *dp = (png_byte)background->gray;
  193056. }
  193057. else
  193058. {
  193059. png_byte v, w;
  193060. v = gamma_to_1[*sp];
  193061. png_composite(w, v, a, background_1->gray);
  193062. *dp = gamma_from_1[w];
  193063. }
  193064. }
  193065. }
  193066. else
  193067. #endif
  193068. {
  193069. sp = row;
  193070. dp = row;
  193071. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193072. {
  193073. png_byte a = *(sp + 1);
  193074. if (a == 0xff)
  193075. {
  193076. *dp = *sp;
  193077. }
  193078. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193079. else if (a == 0)
  193080. {
  193081. *dp = (png_byte)background->gray;
  193082. }
  193083. else
  193084. {
  193085. png_composite(*dp, *sp, a, background_1->gray);
  193086. }
  193087. #else
  193088. *dp = (png_byte)background->gray;
  193089. #endif
  193090. }
  193091. }
  193092. }
  193093. else /* if (png_ptr->bit_depth == 16) */
  193094. {
  193095. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193096. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193097. gamma_16_to_1 != NULL)
  193098. {
  193099. sp = row;
  193100. dp = row;
  193101. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193102. {
  193103. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193104. if (a == (png_uint_16)0xffff)
  193105. {
  193106. png_uint_16 v;
  193107. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193108. *dp = (png_byte)((v >> 8) & 0xff);
  193109. *(dp + 1) = (png_byte)(v & 0xff);
  193110. }
  193111. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193112. else if (a == 0)
  193113. #else
  193114. else
  193115. #endif
  193116. {
  193117. /* background is already in screen gamma */
  193118. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193119. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193120. }
  193121. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193122. else
  193123. {
  193124. png_uint_16 g, v, w;
  193125. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193126. png_composite_16(v, g, a, background_1->gray);
  193127. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193128. *dp = (png_byte)((w >> 8) & 0xff);
  193129. *(dp + 1) = (png_byte)(w & 0xff);
  193130. }
  193131. #endif
  193132. }
  193133. }
  193134. else
  193135. #endif
  193136. {
  193137. sp = row;
  193138. dp = row;
  193139. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193140. {
  193141. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193142. if (a == (png_uint_16)0xffff)
  193143. {
  193144. png_memcpy(dp, sp, 2);
  193145. }
  193146. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193147. else if (a == 0)
  193148. #else
  193149. else
  193150. #endif
  193151. {
  193152. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193153. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193154. }
  193155. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193156. else
  193157. {
  193158. png_uint_16 g, v;
  193159. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193160. png_composite_16(v, g, a, background_1->gray);
  193161. *dp = (png_byte)((v >> 8) & 0xff);
  193162. *(dp + 1) = (png_byte)(v & 0xff);
  193163. }
  193164. #endif
  193165. }
  193166. }
  193167. }
  193168. break;
  193169. }
  193170. case PNG_COLOR_TYPE_RGB_ALPHA:
  193171. {
  193172. if (row_info->bit_depth == 8)
  193173. {
  193174. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193175. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193176. gamma_table != NULL)
  193177. {
  193178. sp = row;
  193179. dp = row;
  193180. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193181. {
  193182. png_byte a = *(sp + 3);
  193183. if (a == 0xff)
  193184. {
  193185. *dp = gamma_table[*sp];
  193186. *(dp + 1) = gamma_table[*(sp + 1)];
  193187. *(dp + 2) = gamma_table[*(sp + 2)];
  193188. }
  193189. else if (a == 0)
  193190. {
  193191. /* background is already in screen gamma */
  193192. *dp = (png_byte)background->red;
  193193. *(dp + 1) = (png_byte)background->green;
  193194. *(dp + 2) = (png_byte)background->blue;
  193195. }
  193196. else
  193197. {
  193198. png_byte v, w;
  193199. v = gamma_to_1[*sp];
  193200. png_composite(w, v, a, background_1->red);
  193201. *dp = gamma_from_1[w];
  193202. v = gamma_to_1[*(sp + 1)];
  193203. png_composite(w, v, a, background_1->green);
  193204. *(dp + 1) = gamma_from_1[w];
  193205. v = gamma_to_1[*(sp + 2)];
  193206. png_composite(w, v, a, background_1->blue);
  193207. *(dp + 2) = gamma_from_1[w];
  193208. }
  193209. }
  193210. }
  193211. else
  193212. #endif
  193213. {
  193214. sp = row;
  193215. dp = row;
  193216. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193217. {
  193218. png_byte a = *(sp + 3);
  193219. if (a == 0xff)
  193220. {
  193221. *dp = *sp;
  193222. *(dp + 1) = *(sp + 1);
  193223. *(dp + 2) = *(sp + 2);
  193224. }
  193225. else if (a == 0)
  193226. {
  193227. *dp = (png_byte)background->red;
  193228. *(dp + 1) = (png_byte)background->green;
  193229. *(dp + 2) = (png_byte)background->blue;
  193230. }
  193231. else
  193232. {
  193233. png_composite(*dp, *sp, a, background->red);
  193234. png_composite(*(dp + 1), *(sp + 1), a,
  193235. background->green);
  193236. png_composite(*(dp + 2), *(sp + 2), a,
  193237. background->blue);
  193238. }
  193239. }
  193240. }
  193241. }
  193242. else /* if (row_info->bit_depth == 16) */
  193243. {
  193244. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193245. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193246. gamma_16_to_1 != NULL)
  193247. {
  193248. sp = row;
  193249. dp = row;
  193250. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193251. {
  193252. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193253. << 8) + (png_uint_16)(*(sp + 7)));
  193254. if (a == (png_uint_16)0xffff)
  193255. {
  193256. png_uint_16 v;
  193257. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193258. *dp = (png_byte)((v >> 8) & 0xff);
  193259. *(dp + 1) = (png_byte)(v & 0xff);
  193260. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193261. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193262. *(dp + 3) = (png_byte)(v & 0xff);
  193263. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193264. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193265. *(dp + 5) = (png_byte)(v & 0xff);
  193266. }
  193267. else if (a == 0)
  193268. {
  193269. /* background is already in screen gamma */
  193270. *dp = (png_byte)((background->red >> 8) & 0xff);
  193271. *(dp + 1) = (png_byte)(background->red & 0xff);
  193272. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193273. *(dp + 3) = (png_byte)(background->green & 0xff);
  193274. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193275. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193276. }
  193277. else
  193278. {
  193279. png_uint_16 v, w, x;
  193280. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193281. png_composite_16(w, v, a, background_1->red);
  193282. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193283. *dp = (png_byte)((x >> 8) & 0xff);
  193284. *(dp + 1) = (png_byte)(x & 0xff);
  193285. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193286. png_composite_16(w, v, a, background_1->green);
  193287. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  193288. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  193289. *(dp + 3) = (png_byte)(x & 0xff);
  193290. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193291. png_composite_16(w, v, a, background_1->blue);
  193292. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  193293. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  193294. *(dp + 5) = (png_byte)(x & 0xff);
  193295. }
  193296. }
  193297. }
  193298. else
  193299. #endif
  193300. {
  193301. sp = row;
  193302. dp = row;
  193303. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193304. {
  193305. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193306. << 8) + (png_uint_16)(*(sp + 7)));
  193307. if (a == (png_uint_16)0xffff)
  193308. {
  193309. png_memcpy(dp, sp, 6);
  193310. }
  193311. else if (a == 0)
  193312. {
  193313. *dp = (png_byte)((background->red >> 8) & 0xff);
  193314. *(dp + 1) = (png_byte)(background->red & 0xff);
  193315. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193316. *(dp + 3) = (png_byte)(background->green & 0xff);
  193317. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193318. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193319. }
  193320. else
  193321. {
  193322. png_uint_16 v;
  193323. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193324. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  193325. + *(sp + 3));
  193326. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  193327. + *(sp + 5));
  193328. png_composite_16(v, r, a, background->red);
  193329. *dp = (png_byte)((v >> 8) & 0xff);
  193330. *(dp + 1) = (png_byte)(v & 0xff);
  193331. png_composite_16(v, g, a, background->green);
  193332. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193333. *(dp + 3) = (png_byte)(v & 0xff);
  193334. png_composite_16(v, b, a, background->blue);
  193335. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193336. *(dp + 5) = (png_byte)(v & 0xff);
  193337. }
  193338. }
  193339. }
  193340. }
  193341. break;
  193342. }
  193343. }
  193344. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  193345. {
  193346. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  193347. row_info->channels--;
  193348. row_info->pixel_depth = (png_byte)(row_info->channels *
  193349. row_info->bit_depth);
  193350. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193351. }
  193352. }
  193353. }
  193354. #endif
  193355. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193356. /* Gamma correct the image, avoiding the alpha channel. Make sure
  193357. * you do this after you deal with the transparency issue on grayscale
  193358. * or RGB images. If your bit depth is 8, use gamma_table, if it
  193359. * is 16, use gamma_16_table and gamma_shift. Build these with
  193360. * build_gamma_table().
  193361. */
  193362. void /* PRIVATE */
  193363. png_do_gamma(png_row_infop row_info, png_bytep row,
  193364. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  193365. int gamma_shift)
  193366. {
  193367. png_bytep sp;
  193368. png_uint_32 i;
  193369. png_uint_32 row_width=row_info->width;
  193370. png_debug(1, "in png_do_gamma\n");
  193371. if (
  193372. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193373. row != NULL && row_info != NULL &&
  193374. #endif
  193375. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  193376. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  193377. {
  193378. switch (row_info->color_type)
  193379. {
  193380. case PNG_COLOR_TYPE_RGB:
  193381. {
  193382. if (row_info->bit_depth == 8)
  193383. {
  193384. sp = row;
  193385. for (i = 0; i < row_width; i++)
  193386. {
  193387. *sp = gamma_table[*sp];
  193388. sp++;
  193389. *sp = gamma_table[*sp];
  193390. sp++;
  193391. *sp = gamma_table[*sp];
  193392. sp++;
  193393. }
  193394. }
  193395. else /* if (row_info->bit_depth == 16) */
  193396. {
  193397. sp = row;
  193398. for (i = 0; i < row_width; i++)
  193399. {
  193400. png_uint_16 v;
  193401. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193402. *sp = (png_byte)((v >> 8) & 0xff);
  193403. *(sp + 1) = (png_byte)(v & 0xff);
  193404. sp += 2;
  193405. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193406. *sp = (png_byte)((v >> 8) & 0xff);
  193407. *(sp + 1) = (png_byte)(v & 0xff);
  193408. sp += 2;
  193409. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193410. *sp = (png_byte)((v >> 8) & 0xff);
  193411. *(sp + 1) = (png_byte)(v & 0xff);
  193412. sp += 2;
  193413. }
  193414. }
  193415. break;
  193416. }
  193417. case PNG_COLOR_TYPE_RGB_ALPHA:
  193418. {
  193419. if (row_info->bit_depth == 8)
  193420. {
  193421. sp = row;
  193422. for (i = 0; i < row_width; i++)
  193423. {
  193424. *sp = gamma_table[*sp];
  193425. sp++;
  193426. *sp = gamma_table[*sp];
  193427. sp++;
  193428. *sp = gamma_table[*sp];
  193429. sp++;
  193430. sp++;
  193431. }
  193432. }
  193433. else /* if (row_info->bit_depth == 16) */
  193434. {
  193435. sp = row;
  193436. for (i = 0; i < row_width; i++)
  193437. {
  193438. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193439. *sp = (png_byte)((v >> 8) & 0xff);
  193440. *(sp + 1) = (png_byte)(v & 0xff);
  193441. sp += 2;
  193442. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193443. *sp = (png_byte)((v >> 8) & 0xff);
  193444. *(sp + 1) = (png_byte)(v & 0xff);
  193445. sp += 2;
  193446. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193447. *sp = (png_byte)((v >> 8) & 0xff);
  193448. *(sp + 1) = (png_byte)(v & 0xff);
  193449. sp += 4;
  193450. }
  193451. }
  193452. break;
  193453. }
  193454. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193455. {
  193456. if (row_info->bit_depth == 8)
  193457. {
  193458. sp = row;
  193459. for (i = 0; i < row_width; i++)
  193460. {
  193461. *sp = gamma_table[*sp];
  193462. sp += 2;
  193463. }
  193464. }
  193465. else /* if (row_info->bit_depth == 16) */
  193466. {
  193467. sp = row;
  193468. for (i = 0; i < row_width; i++)
  193469. {
  193470. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193471. *sp = (png_byte)((v >> 8) & 0xff);
  193472. *(sp + 1) = (png_byte)(v & 0xff);
  193473. sp += 4;
  193474. }
  193475. }
  193476. break;
  193477. }
  193478. case PNG_COLOR_TYPE_GRAY:
  193479. {
  193480. if (row_info->bit_depth == 2)
  193481. {
  193482. sp = row;
  193483. for (i = 0; i < row_width; i += 4)
  193484. {
  193485. int a = *sp & 0xc0;
  193486. int b = *sp & 0x30;
  193487. int c = *sp & 0x0c;
  193488. int d = *sp & 0x03;
  193489. *sp = (png_byte)(
  193490. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  193491. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  193492. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  193493. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  193494. sp++;
  193495. }
  193496. }
  193497. if (row_info->bit_depth == 4)
  193498. {
  193499. sp = row;
  193500. for (i = 0; i < row_width; i += 2)
  193501. {
  193502. int msb = *sp & 0xf0;
  193503. int lsb = *sp & 0x0f;
  193504. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  193505. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  193506. sp++;
  193507. }
  193508. }
  193509. else if (row_info->bit_depth == 8)
  193510. {
  193511. sp = row;
  193512. for (i = 0; i < row_width; i++)
  193513. {
  193514. *sp = gamma_table[*sp];
  193515. sp++;
  193516. }
  193517. }
  193518. else if (row_info->bit_depth == 16)
  193519. {
  193520. sp = row;
  193521. for (i = 0; i < row_width; i++)
  193522. {
  193523. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  193524. *sp = (png_byte)((v >> 8) & 0xff);
  193525. *(sp + 1) = (png_byte)(v & 0xff);
  193526. sp += 2;
  193527. }
  193528. }
  193529. break;
  193530. }
  193531. }
  193532. }
  193533. }
  193534. #endif
  193535. #if defined(PNG_READ_EXPAND_SUPPORTED)
  193536. /* Expands a palette row to an RGB or RGBA row depending
  193537. * upon whether you supply trans and num_trans.
  193538. */
  193539. void /* PRIVATE */
  193540. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  193541. png_colorp palette, png_bytep trans, int num_trans)
  193542. {
  193543. int shift, value;
  193544. png_bytep sp, dp;
  193545. png_uint_32 i;
  193546. png_uint_32 row_width=row_info->width;
  193547. png_debug(1, "in png_do_expand_palette\n");
  193548. if (
  193549. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193550. row != NULL && row_info != NULL &&
  193551. #endif
  193552. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  193553. {
  193554. if (row_info->bit_depth < 8)
  193555. {
  193556. switch (row_info->bit_depth)
  193557. {
  193558. case 1:
  193559. {
  193560. sp = row + (png_size_t)((row_width - 1) >> 3);
  193561. dp = row + (png_size_t)row_width - 1;
  193562. shift = 7 - (int)((row_width + 7) & 0x07);
  193563. for (i = 0; i < row_width; i++)
  193564. {
  193565. if ((*sp >> shift) & 0x01)
  193566. *dp = 1;
  193567. else
  193568. *dp = 0;
  193569. if (shift == 7)
  193570. {
  193571. shift = 0;
  193572. sp--;
  193573. }
  193574. else
  193575. shift++;
  193576. dp--;
  193577. }
  193578. break;
  193579. }
  193580. case 2:
  193581. {
  193582. sp = row + (png_size_t)((row_width - 1) >> 2);
  193583. dp = row + (png_size_t)row_width - 1;
  193584. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193585. for (i = 0; i < row_width; i++)
  193586. {
  193587. value = (*sp >> shift) & 0x03;
  193588. *dp = (png_byte)value;
  193589. if (shift == 6)
  193590. {
  193591. shift = 0;
  193592. sp--;
  193593. }
  193594. else
  193595. shift += 2;
  193596. dp--;
  193597. }
  193598. break;
  193599. }
  193600. case 4:
  193601. {
  193602. sp = row + (png_size_t)((row_width - 1) >> 1);
  193603. dp = row + (png_size_t)row_width - 1;
  193604. shift = (int)((row_width & 0x01) << 2);
  193605. for (i = 0; i < row_width; i++)
  193606. {
  193607. value = (*sp >> shift) & 0x0f;
  193608. *dp = (png_byte)value;
  193609. if (shift == 4)
  193610. {
  193611. shift = 0;
  193612. sp--;
  193613. }
  193614. else
  193615. shift += 4;
  193616. dp--;
  193617. }
  193618. break;
  193619. }
  193620. }
  193621. row_info->bit_depth = 8;
  193622. row_info->pixel_depth = 8;
  193623. row_info->rowbytes = row_width;
  193624. }
  193625. switch (row_info->bit_depth)
  193626. {
  193627. case 8:
  193628. {
  193629. if (trans != NULL)
  193630. {
  193631. sp = row + (png_size_t)row_width - 1;
  193632. dp = row + (png_size_t)(row_width << 2) - 1;
  193633. for (i = 0; i < row_width; i++)
  193634. {
  193635. if ((int)(*sp) >= num_trans)
  193636. *dp-- = 0xff;
  193637. else
  193638. *dp-- = trans[*sp];
  193639. *dp-- = palette[*sp].blue;
  193640. *dp-- = palette[*sp].green;
  193641. *dp-- = palette[*sp].red;
  193642. sp--;
  193643. }
  193644. row_info->bit_depth = 8;
  193645. row_info->pixel_depth = 32;
  193646. row_info->rowbytes = row_width * 4;
  193647. row_info->color_type = 6;
  193648. row_info->channels = 4;
  193649. }
  193650. else
  193651. {
  193652. sp = row + (png_size_t)row_width - 1;
  193653. dp = row + (png_size_t)(row_width * 3) - 1;
  193654. for (i = 0; i < row_width; i++)
  193655. {
  193656. *dp-- = palette[*sp].blue;
  193657. *dp-- = palette[*sp].green;
  193658. *dp-- = palette[*sp].red;
  193659. sp--;
  193660. }
  193661. row_info->bit_depth = 8;
  193662. row_info->pixel_depth = 24;
  193663. row_info->rowbytes = row_width * 3;
  193664. row_info->color_type = 2;
  193665. row_info->channels = 3;
  193666. }
  193667. break;
  193668. }
  193669. }
  193670. }
  193671. }
  193672. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  193673. * expanded transparency value is supplied, an alpha channel is built.
  193674. */
  193675. void /* PRIVATE */
  193676. png_do_expand(png_row_infop row_info, png_bytep row,
  193677. png_color_16p trans_value)
  193678. {
  193679. int shift, value;
  193680. png_bytep sp, dp;
  193681. png_uint_32 i;
  193682. png_uint_32 row_width=row_info->width;
  193683. png_debug(1, "in png_do_expand\n");
  193684. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193685. if (row != NULL && row_info != NULL)
  193686. #endif
  193687. {
  193688. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  193689. {
  193690. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  193691. if (row_info->bit_depth < 8)
  193692. {
  193693. switch (row_info->bit_depth)
  193694. {
  193695. case 1:
  193696. {
  193697. gray = (png_uint_16)((gray&0x01)*0xff);
  193698. sp = row + (png_size_t)((row_width - 1) >> 3);
  193699. dp = row + (png_size_t)row_width - 1;
  193700. shift = 7 - (int)((row_width + 7) & 0x07);
  193701. for (i = 0; i < row_width; i++)
  193702. {
  193703. if ((*sp >> shift) & 0x01)
  193704. *dp = 0xff;
  193705. else
  193706. *dp = 0;
  193707. if (shift == 7)
  193708. {
  193709. shift = 0;
  193710. sp--;
  193711. }
  193712. else
  193713. shift++;
  193714. dp--;
  193715. }
  193716. break;
  193717. }
  193718. case 2:
  193719. {
  193720. gray = (png_uint_16)((gray&0x03)*0x55);
  193721. sp = row + (png_size_t)((row_width - 1) >> 2);
  193722. dp = row + (png_size_t)row_width - 1;
  193723. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  193724. for (i = 0; i < row_width; i++)
  193725. {
  193726. value = (*sp >> shift) & 0x03;
  193727. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  193728. (value << 6));
  193729. if (shift == 6)
  193730. {
  193731. shift = 0;
  193732. sp--;
  193733. }
  193734. else
  193735. shift += 2;
  193736. dp--;
  193737. }
  193738. break;
  193739. }
  193740. case 4:
  193741. {
  193742. gray = (png_uint_16)((gray&0x0f)*0x11);
  193743. sp = row + (png_size_t)((row_width - 1) >> 1);
  193744. dp = row + (png_size_t)row_width - 1;
  193745. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  193746. for (i = 0; i < row_width; i++)
  193747. {
  193748. value = (*sp >> shift) & 0x0f;
  193749. *dp = (png_byte)(value | (value << 4));
  193750. if (shift == 4)
  193751. {
  193752. shift = 0;
  193753. sp--;
  193754. }
  193755. else
  193756. shift = 4;
  193757. dp--;
  193758. }
  193759. break;
  193760. }
  193761. }
  193762. row_info->bit_depth = 8;
  193763. row_info->pixel_depth = 8;
  193764. row_info->rowbytes = row_width;
  193765. }
  193766. if (trans_value != NULL)
  193767. {
  193768. if (row_info->bit_depth == 8)
  193769. {
  193770. gray = gray & 0xff;
  193771. sp = row + (png_size_t)row_width - 1;
  193772. dp = row + (png_size_t)(row_width << 1) - 1;
  193773. for (i = 0; i < row_width; i++)
  193774. {
  193775. if (*sp == gray)
  193776. *dp-- = 0;
  193777. else
  193778. *dp-- = 0xff;
  193779. *dp-- = *sp--;
  193780. }
  193781. }
  193782. else if (row_info->bit_depth == 16)
  193783. {
  193784. png_byte gray_high = (gray >> 8) & 0xff;
  193785. png_byte gray_low = gray & 0xff;
  193786. sp = row + row_info->rowbytes - 1;
  193787. dp = row + (row_info->rowbytes << 1) - 1;
  193788. for (i = 0; i < row_width; i++)
  193789. {
  193790. if (*(sp-1) == gray_high && *(sp) == gray_low)
  193791. {
  193792. *dp-- = 0;
  193793. *dp-- = 0;
  193794. }
  193795. else
  193796. {
  193797. *dp-- = 0xff;
  193798. *dp-- = 0xff;
  193799. }
  193800. *dp-- = *sp--;
  193801. *dp-- = *sp--;
  193802. }
  193803. }
  193804. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  193805. row_info->channels = 2;
  193806. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  193807. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  193808. row_width);
  193809. }
  193810. }
  193811. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  193812. {
  193813. if (row_info->bit_depth == 8)
  193814. {
  193815. png_byte red = trans_value->red & 0xff;
  193816. png_byte green = trans_value->green & 0xff;
  193817. png_byte blue = trans_value->blue & 0xff;
  193818. sp = row + (png_size_t)row_info->rowbytes - 1;
  193819. dp = row + (png_size_t)(row_width << 2) - 1;
  193820. for (i = 0; i < row_width; i++)
  193821. {
  193822. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  193823. *dp-- = 0;
  193824. else
  193825. *dp-- = 0xff;
  193826. *dp-- = *sp--;
  193827. *dp-- = *sp--;
  193828. *dp-- = *sp--;
  193829. }
  193830. }
  193831. else if (row_info->bit_depth == 16)
  193832. {
  193833. png_byte red_high = (trans_value->red >> 8) & 0xff;
  193834. png_byte green_high = (trans_value->green >> 8) & 0xff;
  193835. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  193836. png_byte red_low = trans_value->red & 0xff;
  193837. png_byte green_low = trans_value->green & 0xff;
  193838. png_byte blue_low = trans_value->blue & 0xff;
  193839. sp = row + row_info->rowbytes - 1;
  193840. dp = row + (png_size_t)(row_width << 3) - 1;
  193841. for (i = 0; i < row_width; i++)
  193842. {
  193843. if (*(sp - 5) == red_high &&
  193844. *(sp - 4) == red_low &&
  193845. *(sp - 3) == green_high &&
  193846. *(sp - 2) == green_low &&
  193847. *(sp - 1) == blue_high &&
  193848. *(sp ) == blue_low)
  193849. {
  193850. *dp-- = 0;
  193851. *dp-- = 0;
  193852. }
  193853. else
  193854. {
  193855. *dp-- = 0xff;
  193856. *dp-- = 0xff;
  193857. }
  193858. *dp-- = *sp--;
  193859. *dp-- = *sp--;
  193860. *dp-- = *sp--;
  193861. *dp-- = *sp--;
  193862. *dp-- = *sp--;
  193863. *dp-- = *sp--;
  193864. }
  193865. }
  193866. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  193867. row_info->channels = 4;
  193868. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  193869. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193870. }
  193871. }
  193872. }
  193873. #endif
  193874. #if defined(PNG_READ_DITHER_SUPPORTED)
  193875. void /* PRIVATE */
  193876. png_do_dither(png_row_infop row_info, png_bytep row,
  193877. png_bytep palette_lookup, png_bytep dither_lookup)
  193878. {
  193879. png_bytep sp, dp;
  193880. png_uint_32 i;
  193881. png_uint_32 row_width=row_info->width;
  193882. png_debug(1, "in png_do_dither\n");
  193883. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193884. if (row != NULL && row_info != NULL)
  193885. #endif
  193886. {
  193887. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  193888. palette_lookup && row_info->bit_depth == 8)
  193889. {
  193890. int r, g, b, p;
  193891. sp = row;
  193892. dp = row;
  193893. for (i = 0; i < row_width; i++)
  193894. {
  193895. r = *sp++;
  193896. g = *sp++;
  193897. b = *sp++;
  193898. /* this looks real messy, but the compiler will reduce
  193899. it down to a reasonable formula. For example, with
  193900. 5 bits per color, we get:
  193901. p = (((r >> 3) & 0x1f) << 10) |
  193902. (((g >> 3) & 0x1f) << 5) |
  193903. ((b >> 3) & 0x1f);
  193904. */
  193905. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193906. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193907. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193908. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193909. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193910. (PNG_DITHER_BLUE_BITS)) |
  193911. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193912. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193913. *dp++ = palette_lookup[p];
  193914. }
  193915. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193916. row_info->channels = 1;
  193917. row_info->pixel_depth = row_info->bit_depth;
  193918. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193919. }
  193920. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  193921. palette_lookup != NULL && row_info->bit_depth == 8)
  193922. {
  193923. int r, g, b, p;
  193924. sp = row;
  193925. dp = row;
  193926. for (i = 0; i < row_width; i++)
  193927. {
  193928. r = *sp++;
  193929. g = *sp++;
  193930. b = *sp++;
  193931. sp++;
  193932. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  193933. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  193934. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  193935. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  193936. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  193937. (PNG_DITHER_BLUE_BITS)) |
  193938. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  193939. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  193940. *dp++ = palette_lookup[p];
  193941. }
  193942. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  193943. row_info->channels = 1;
  193944. row_info->pixel_depth = row_info->bit_depth;
  193945. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193946. }
  193947. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  193948. dither_lookup && row_info->bit_depth == 8)
  193949. {
  193950. sp = row;
  193951. for (i = 0; i < row_width; i++, sp++)
  193952. {
  193953. *sp = dither_lookup[*sp];
  193954. }
  193955. }
  193956. }
  193957. }
  193958. #endif
  193959. #ifdef PNG_FLOATING_POINT_SUPPORTED
  193960. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193961. static PNG_CONST int png_gamma_shift[] =
  193962. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  193963. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  193964. * tables, we don't make a full table if we are reducing to 8-bit in
  193965. * the future. Note also how the gamma_16 tables are segmented so that
  193966. * we don't need to allocate > 64K chunks for a full 16-bit table.
  193967. */
  193968. void /* PRIVATE */
  193969. png_build_gamma_table(png_structp png_ptr)
  193970. {
  193971. png_debug(1, "in png_build_gamma_table\n");
  193972. if (png_ptr->bit_depth <= 8)
  193973. {
  193974. int i;
  193975. double g;
  193976. if (png_ptr->screen_gamma > .000001)
  193977. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  193978. else
  193979. g = 1.0;
  193980. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  193981. (png_uint_32)256);
  193982. for (i = 0; i < 256; i++)
  193983. {
  193984. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  193985. g) * 255.0 + .5);
  193986. }
  193987. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  193988. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  193989. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  193990. {
  193991. g = 1.0 / (png_ptr->gamma);
  193992. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  193993. (png_uint_32)256);
  193994. for (i = 0; i < 256; i++)
  193995. {
  193996. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  193997. g) * 255.0 + .5);
  193998. }
  193999. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  194000. (png_uint_32)256);
  194001. if(png_ptr->screen_gamma > 0.000001)
  194002. g = 1.0 / png_ptr->screen_gamma;
  194003. else
  194004. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194005. for (i = 0; i < 256; i++)
  194006. {
  194007. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  194008. g) * 255.0 + .5);
  194009. }
  194010. }
  194011. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194012. }
  194013. else
  194014. {
  194015. double g;
  194016. int i, j, shift, num;
  194017. int sig_bit;
  194018. png_uint_32 ig;
  194019. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194020. {
  194021. sig_bit = (int)png_ptr->sig_bit.red;
  194022. if ((int)png_ptr->sig_bit.green > sig_bit)
  194023. sig_bit = png_ptr->sig_bit.green;
  194024. if ((int)png_ptr->sig_bit.blue > sig_bit)
  194025. sig_bit = png_ptr->sig_bit.blue;
  194026. }
  194027. else
  194028. {
  194029. sig_bit = (int)png_ptr->sig_bit.gray;
  194030. }
  194031. if (sig_bit > 0)
  194032. shift = 16 - sig_bit;
  194033. else
  194034. shift = 0;
  194035. if (png_ptr->transformations & PNG_16_TO_8)
  194036. {
  194037. if (shift < (16 - PNG_MAX_GAMMA_8))
  194038. shift = (16 - PNG_MAX_GAMMA_8);
  194039. }
  194040. if (shift > 8)
  194041. shift = 8;
  194042. if (shift < 0)
  194043. shift = 0;
  194044. png_ptr->gamma_shift = (png_byte)shift;
  194045. num = (1 << (8 - shift));
  194046. if (png_ptr->screen_gamma > .000001)
  194047. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194048. else
  194049. g = 1.0;
  194050. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194051. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194052. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194053. {
  194054. double fin, fout;
  194055. png_uint_32 last, max;
  194056. for (i = 0; i < num; i++)
  194057. {
  194058. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194059. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194060. }
  194061. g = 1.0 / g;
  194062. last = 0;
  194063. for (i = 0; i < 256; i++)
  194064. {
  194065. fout = ((double)i + 0.5) / 256.0;
  194066. fin = pow(fout, g);
  194067. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194068. while (last <= max)
  194069. {
  194070. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194071. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194072. (png_uint_16)i | ((png_uint_16)i << 8));
  194073. last++;
  194074. }
  194075. }
  194076. while (last < ((png_uint_32)num << 8))
  194077. {
  194078. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194079. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194080. last++;
  194081. }
  194082. }
  194083. else
  194084. {
  194085. for (i = 0; i < num; i++)
  194086. {
  194087. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194088. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194089. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194090. for (j = 0; j < 256; j++)
  194091. {
  194092. png_ptr->gamma_16_table[i][j] =
  194093. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194094. 65535.0, g) * 65535.0 + .5);
  194095. }
  194096. }
  194097. }
  194098. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194099. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194100. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194101. {
  194102. g = 1.0 / (png_ptr->gamma);
  194103. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194104. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194105. for (i = 0; i < num; i++)
  194106. {
  194107. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194108. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194109. ig = (((png_uint_32)i *
  194110. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194111. for (j = 0; j < 256; j++)
  194112. {
  194113. png_ptr->gamma_16_to_1[i][j] =
  194114. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194115. 65535.0, g) * 65535.0 + .5);
  194116. }
  194117. }
  194118. if(png_ptr->screen_gamma > 0.000001)
  194119. g = 1.0 / png_ptr->screen_gamma;
  194120. else
  194121. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194122. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194123. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194124. for (i = 0; i < num; i++)
  194125. {
  194126. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194127. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194128. ig = (((png_uint_32)i *
  194129. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194130. for (j = 0; j < 256; j++)
  194131. {
  194132. png_ptr->gamma_16_from_1[i][j] =
  194133. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194134. 65535.0, g) * 65535.0 + .5);
  194135. }
  194136. }
  194137. }
  194138. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194139. }
  194140. }
  194141. #endif
  194142. /* To do: install integer version of png_build_gamma_table here */
  194143. #endif
  194144. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194145. /* undoes intrapixel differencing */
  194146. void /* PRIVATE */
  194147. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194148. {
  194149. png_debug(1, "in png_do_read_intrapixel\n");
  194150. if (
  194151. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194152. row != NULL && row_info != NULL &&
  194153. #endif
  194154. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194155. {
  194156. int bytes_per_pixel;
  194157. png_uint_32 row_width = row_info->width;
  194158. if (row_info->bit_depth == 8)
  194159. {
  194160. png_bytep rp;
  194161. png_uint_32 i;
  194162. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194163. bytes_per_pixel = 3;
  194164. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194165. bytes_per_pixel = 4;
  194166. else
  194167. return;
  194168. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194169. {
  194170. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194171. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194172. }
  194173. }
  194174. else if (row_info->bit_depth == 16)
  194175. {
  194176. png_bytep rp;
  194177. png_uint_32 i;
  194178. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194179. bytes_per_pixel = 6;
  194180. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194181. bytes_per_pixel = 8;
  194182. else
  194183. return;
  194184. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194185. {
  194186. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194187. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194188. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194189. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194190. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194191. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194192. *(rp+1) = (png_byte)(red & 0xff);
  194193. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194194. *(rp+5) = (png_byte)(blue & 0xff);
  194195. }
  194196. }
  194197. }
  194198. }
  194199. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194200. #endif /* PNG_READ_SUPPORTED */
  194201. /*** End of inlined file: pngrtran.c ***/
  194202. /*** Start of inlined file: pngrutil.c ***/
  194203. /* pngrutil.c - utilities to read a PNG file
  194204. *
  194205. * Last changed in libpng 1.2.21 [October 4, 2007]
  194206. * For conditions of distribution and use, see copyright notice in png.h
  194207. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194208. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194209. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194210. *
  194211. * This file contains routines that are only called from within
  194212. * libpng itself during the course of reading an image.
  194213. */
  194214. #define PNG_INTERNAL
  194215. #if defined(PNG_READ_SUPPORTED)
  194216. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194217. # define WIN32_WCE_OLD
  194218. #endif
  194219. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194220. # if defined(WIN32_WCE_OLD)
  194221. /* strtod() function is not supported on WindowsCE */
  194222. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194223. {
  194224. double result = 0;
  194225. int len;
  194226. wchar_t *str, *end;
  194227. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194228. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194229. if ( NULL != str )
  194230. {
  194231. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194232. result = wcstod(str, &end);
  194233. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194234. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194235. png_free(png_ptr, str);
  194236. }
  194237. return result;
  194238. }
  194239. # else
  194240. # define png_strtod(p,a,b) strtod(a,b)
  194241. # endif
  194242. #endif
  194243. png_uint_32 PNGAPI
  194244. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194245. {
  194246. png_uint_32 i = png_get_uint_32(buf);
  194247. if (i > PNG_UINT_31_MAX)
  194248. png_error(png_ptr, "PNG unsigned integer out of range.");
  194249. return (i);
  194250. }
  194251. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194252. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194253. png_uint_32 PNGAPI
  194254. png_get_uint_32(png_bytep buf)
  194255. {
  194256. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194257. ((png_uint_32)(*(buf + 1)) << 16) +
  194258. ((png_uint_32)(*(buf + 2)) << 8) +
  194259. (png_uint_32)(*(buf + 3));
  194260. return (i);
  194261. }
  194262. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194263. * data is stored in the PNG file in two's complement format, and it is
  194264. * assumed that the machine format for signed integers is the same. */
  194265. png_int_32 PNGAPI
  194266. png_get_int_32(png_bytep buf)
  194267. {
  194268. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194269. ((png_int_32)(*(buf + 1)) << 16) +
  194270. ((png_int_32)(*(buf + 2)) << 8) +
  194271. (png_int_32)(*(buf + 3));
  194272. return (i);
  194273. }
  194274. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194275. png_uint_16 PNGAPI
  194276. png_get_uint_16(png_bytep buf)
  194277. {
  194278. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194279. (png_uint_16)(*(buf + 1)));
  194280. return (i);
  194281. }
  194282. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  194283. /* Read data, and (optionally) run it through the CRC. */
  194284. void /* PRIVATE */
  194285. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  194286. {
  194287. if(png_ptr == NULL) return;
  194288. png_read_data(png_ptr, buf, length);
  194289. png_calculate_crc(png_ptr, buf, length);
  194290. }
  194291. /* Optionally skip data and then check the CRC. Depending on whether we
  194292. are reading a ancillary or critical chunk, and how the program has set
  194293. things up, we may calculate the CRC on the data and print a message.
  194294. Returns '1' if there was a CRC error, '0' otherwise. */
  194295. int /* PRIVATE */
  194296. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  194297. {
  194298. png_size_t i;
  194299. png_size_t istop = png_ptr->zbuf_size;
  194300. for (i = (png_size_t)skip; i > istop; i -= istop)
  194301. {
  194302. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  194303. }
  194304. if (i)
  194305. {
  194306. png_crc_read(png_ptr, png_ptr->zbuf, i);
  194307. }
  194308. if (png_crc_error(png_ptr))
  194309. {
  194310. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  194311. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  194312. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  194313. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  194314. {
  194315. png_chunk_warning(png_ptr, "CRC error");
  194316. }
  194317. else
  194318. {
  194319. png_chunk_error(png_ptr, "CRC error");
  194320. }
  194321. return (1);
  194322. }
  194323. return (0);
  194324. }
  194325. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  194326. the data it has read thus far. */
  194327. int /* PRIVATE */
  194328. png_crc_error(png_structp png_ptr)
  194329. {
  194330. png_byte crc_bytes[4];
  194331. png_uint_32 crc;
  194332. int need_crc = 1;
  194333. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  194334. {
  194335. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  194336. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194337. need_crc = 0;
  194338. }
  194339. else /* critical */
  194340. {
  194341. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  194342. need_crc = 0;
  194343. }
  194344. png_read_data(png_ptr, crc_bytes, 4);
  194345. if (need_crc)
  194346. {
  194347. crc = png_get_uint_32(crc_bytes);
  194348. return ((int)(crc != png_ptr->crc));
  194349. }
  194350. else
  194351. return (0);
  194352. }
  194353. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  194354. defined(PNG_READ_iCCP_SUPPORTED)
  194355. /*
  194356. * Decompress trailing data in a chunk. The assumption is that chunkdata
  194357. * points at an allocated area holding the contents of a chunk with a
  194358. * trailing compressed part. What we get back is an allocated area
  194359. * holding the original prefix part and an uncompressed version of the
  194360. * trailing part (the malloc area passed in is freed).
  194361. */
  194362. png_charp /* PRIVATE */
  194363. png_decompress_chunk(png_structp png_ptr, int comp_type,
  194364. png_charp chunkdata, png_size_t chunklength,
  194365. png_size_t prefix_size, png_size_t *newlength)
  194366. {
  194367. static PNG_CONST char msg[] = "Error decoding compressed text";
  194368. png_charp text;
  194369. png_size_t text_size;
  194370. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  194371. {
  194372. int ret = Z_OK;
  194373. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  194374. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  194375. png_ptr->zstream.next_out = png_ptr->zbuf;
  194376. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194377. text_size = 0;
  194378. text = NULL;
  194379. while (png_ptr->zstream.avail_in)
  194380. {
  194381. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  194382. if (ret != Z_OK && ret != Z_STREAM_END)
  194383. {
  194384. if (png_ptr->zstream.msg != NULL)
  194385. png_warning(png_ptr, png_ptr->zstream.msg);
  194386. else
  194387. png_warning(png_ptr, msg);
  194388. inflateReset(&png_ptr->zstream);
  194389. png_ptr->zstream.avail_in = 0;
  194390. if (text == NULL)
  194391. {
  194392. text_size = prefix_size + png_sizeof(msg) + 1;
  194393. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  194394. if (text == NULL)
  194395. {
  194396. png_free(png_ptr,chunkdata);
  194397. png_error(png_ptr,"Not enough memory to decompress chunk");
  194398. }
  194399. png_memcpy(text, chunkdata, prefix_size);
  194400. }
  194401. text[text_size - 1] = 0x00;
  194402. /* Copy what we can of the error message into the text chunk */
  194403. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  194404. text_size = png_sizeof(msg) > text_size ? text_size :
  194405. png_sizeof(msg);
  194406. png_memcpy(text + prefix_size, msg, text_size + 1);
  194407. break;
  194408. }
  194409. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  194410. {
  194411. if (text == NULL)
  194412. {
  194413. text_size = prefix_size +
  194414. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194415. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  194416. if (text == NULL)
  194417. {
  194418. png_free(png_ptr,chunkdata);
  194419. png_error(png_ptr,"Not enough memory to decompress chunk.");
  194420. }
  194421. png_memcpy(text + prefix_size, png_ptr->zbuf,
  194422. text_size - prefix_size);
  194423. png_memcpy(text, chunkdata, prefix_size);
  194424. *(text + text_size) = 0x00;
  194425. }
  194426. else
  194427. {
  194428. png_charp tmp;
  194429. tmp = text;
  194430. text = (png_charp)png_malloc_warn(png_ptr,
  194431. (png_uint_32)(text_size +
  194432. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  194433. if (text == NULL)
  194434. {
  194435. png_free(png_ptr, tmp);
  194436. png_free(png_ptr, chunkdata);
  194437. png_error(png_ptr,"Not enough memory to decompress chunk..");
  194438. }
  194439. png_memcpy(text, tmp, text_size);
  194440. png_free(png_ptr, tmp);
  194441. png_memcpy(text + text_size, png_ptr->zbuf,
  194442. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  194443. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  194444. *(text + text_size) = 0x00;
  194445. }
  194446. if (ret == Z_STREAM_END)
  194447. break;
  194448. else
  194449. {
  194450. png_ptr->zstream.next_out = png_ptr->zbuf;
  194451. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  194452. }
  194453. }
  194454. }
  194455. if (ret != Z_STREAM_END)
  194456. {
  194457. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194458. char umsg[52];
  194459. if (ret == Z_BUF_ERROR)
  194460. png_snprintf(umsg, 52,
  194461. "Buffer error in compressed datastream in %s chunk",
  194462. png_ptr->chunk_name);
  194463. else if (ret == Z_DATA_ERROR)
  194464. png_snprintf(umsg, 52,
  194465. "Data error in compressed datastream in %s chunk",
  194466. png_ptr->chunk_name);
  194467. else
  194468. png_snprintf(umsg, 52,
  194469. "Incomplete compressed datastream in %s chunk",
  194470. png_ptr->chunk_name);
  194471. png_warning(png_ptr, umsg);
  194472. #else
  194473. png_warning(png_ptr,
  194474. "Incomplete compressed datastream in chunk other than IDAT");
  194475. #endif
  194476. text_size=prefix_size;
  194477. if (text == NULL)
  194478. {
  194479. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  194480. if (text == NULL)
  194481. {
  194482. png_free(png_ptr, chunkdata);
  194483. png_error(png_ptr,"Not enough memory for text.");
  194484. }
  194485. png_memcpy(text, chunkdata, prefix_size);
  194486. }
  194487. *(text + text_size) = 0x00;
  194488. }
  194489. inflateReset(&png_ptr->zstream);
  194490. png_ptr->zstream.avail_in = 0;
  194491. png_free(png_ptr, chunkdata);
  194492. chunkdata = text;
  194493. *newlength=text_size;
  194494. }
  194495. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  194496. {
  194497. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  194498. char umsg[50];
  194499. png_snprintf(umsg, 50,
  194500. "Unknown zTXt compression type %d", comp_type);
  194501. png_warning(png_ptr, umsg);
  194502. #else
  194503. png_warning(png_ptr, "Unknown zTXt compression type");
  194504. #endif
  194505. *(chunkdata + prefix_size) = 0x00;
  194506. *newlength=prefix_size;
  194507. }
  194508. return chunkdata;
  194509. }
  194510. #endif
  194511. /* read and check the IDHR chunk */
  194512. void /* PRIVATE */
  194513. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194514. {
  194515. png_byte buf[13];
  194516. png_uint_32 width, height;
  194517. int bit_depth, color_type, compression_type, filter_type;
  194518. int interlace_type;
  194519. png_debug(1, "in png_handle_IHDR\n");
  194520. if (png_ptr->mode & PNG_HAVE_IHDR)
  194521. png_error(png_ptr, "Out of place IHDR");
  194522. /* check the length */
  194523. if (length != 13)
  194524. png_error(png_ptr, "Invalid IHDR chunk");
  194525. png_ptr->mode |= PNG_HAVE_IHDR;
  194526. png_crc_read(png_ptr, buf, 13);
  194527. png_crc_finish(png_ptr, 0);
  194528. width = png_get_uint_31(png_ptr, buf);
  194529. height = png_get_uint_31(png_ptr, buf + 4);
  194530. bit_depth = buf[8];
  194531. color_type = buf[9];
  194532. compression_type = buf[10];
  194533. filter_type = buf[11];
  194534. interlace_type = buf[12];
  194535. /* set internal variables */
  194536. png_ptr->width = width;
  194537. png_ptr->height = height;
  194538. png_ptr->bit_depth = (png_byte)bit_depth;
  194539. png_ptr->interlaced = (png_byte)interlace_type;
  194540. png_ptr->color_type = (png_byte)color_type;
  194541. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194542. png_ptr->filter_type = (png_byte)filter_type;
  194543. #endif
  194544. png_ptr->compression_type = (png_byte)compression_type;
  194545. /* find number of channels */
  194546. switch (png_ptr->color_type)
  194547. {
  194548. case PNG_COLOR_TYPE_GRAY:
  194549. case PNG_COLOR_TYPE_PALETTE:
  194550. png_ptr->channels = 1;
  194551. break;
  194552. case PNG_COLOR_TYPE_RGB:
  194553. png_ptr->channels = 3;
  194554. break;
  194555. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194556. png_ptr->channels = 2;
  194557. break;
  194558. case PNG_COLOR_TYPE_RGB_ALPHA:
  194559. png_ptr->channels = 4;
  194560. break;
  194561. }
  194562. /* set up other useful info */
  194563. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  194564. png_ptr->channels);
  194565. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  194566. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  194567. png_debug1(3,"channels = %d\n", png_ptr->channels);
  194568. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  194569. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  194570. color_type, interlace_type, compression_type, filter_type);
  194571. }
  194572. /* read and check the palette */
  194573. void /* PRIVATE */
  194574. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194575. {
  194576. png_color palette[PNG_MAX_PALETTE_LENGTH];
  194577. int num, i;
  194578. #ifndef PNG_NO_POINTER_INDEXING
  194579. png_colorp pal_ptr;
  194580. #endif
  194581. png_debug(1, "in png_handle_PLTE\n");
  194582. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194583. png_error(png_ptr, "Missing IHDR before PLTE");
  194584. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194585. {
  194586. png_warning(png_ptr, "Invalid PLTE after IDAT");
  194587. png_crc_finish(png_ptr, length);
  194588. return;
  194589. }
  194590. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194591. png_error(png_ptr, "Duplicate PLTE chunk");
  194592. png_ptr->mode |= PNG_HAVE_PLTE;
  194593. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  194594. {
  194595. png_warning(png_ptr,
  194596. "Ignoring PLTE chunk in grayscale PNG");
  194597. png_crc_finish(png_ptr, length);
  194598. return;
  194599. }
  194600. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194601. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194602. {
  194603. png_crc_finish(png_ptr, length);
  194604. return;
  194605. }
  194606. #endif
  194607. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  194608. {
  194609. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  194610. {
  194611. png_warning(png_ptr, "Invalid palette chunk");
  194612. png_crc_finish(png_ptr, length);
  194613. return;
  194614. }
  194615. else
  194616. {
  194617. png_error(png_ptr, "Invalid palette chunk");
  194618. }
  194619. }
  194620. num = (int)length / 3;
  194621. #ifndef PNG_NO_POINTER_INDEXING
  194622. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  194623. {
  194624. png_byte buf[3];
  194625. png_crc_read(png_ptr, buf, 3);
  194626. pal_ptr->red = buf[0];
  194627. pal_ptr->green = buf[1];
  194628. pal_ptr->blue = buf[2];
  194629. }
  194630. #else
  194631. for (i = 0; i < num; i++)
  194632. {
  194633. png_byte buf[3];
  194634. png_crc_read(png_ptr, buf, 3);
  194635. /* don't depend upon png_color being any order */
  194636. palette[i].red = buf[0];
  194637. palette[i].green = buf[1];
  194638. palette[i].blue = buf[2];
  194639. }
  194640. #endif
  194641. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  194642. whatever the normal CRC configuration tells us. However, if we
  194643. have an RGB image, the PLTE can be considered ancillary, so
  194644. we will act as though it is. */
  194645. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194646. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194647. #endif
  194648. {
  194649. png_crc_finish(png_ptr, 0);
  194650. }
  194651. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  194652. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  194653. {
  194654. /* If we don't want to use the data from an ancillary chunk,
  194655. we have two options: an error abort, or a warning and we
  194656. ignore the data in this chunk (which should be OK, since
  194657. it's considered ancillary for a RGB or RGBA image). */
  194658. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  194659. {
  194660. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  194661. {
  194662. png_chunk_error(png_ptr, "CRC error");
  194663. }
  194664. else
  194665. {
  194666. png_chunk_warning(png_ptr, "CRC error");
  194667. return;
  194668. }
  194669. }
  194670. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  194671. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  194672. {
  194673. png_chunk_warning(png_ptr, "CRC error");
  194674. }
  194675. }
  194676. #endif
  194677. png_set_PLTE(png_ptr, info_ptr, palette, num);
  194678. #if defined(PNG_READ_tRNS_SUPPORTED)
  194679. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194680. {
  194681. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  194682. {
  194683. if (png_ptr->num_trans > (png_uint_16)num)
  194684. {
  194685. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  194686. png_ptr->num_trans = (png_uint_16)num;
  194687. }
  194688. if (info_ptr->num_trans > (png_uint_16)num)
  194689. {
  194690. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  194691. info_ptr->num_trans = (png_uint_16)num;
  194692. }
  194693. }
  194694. }
  194695. #endif
  194696. }
  194697. void /* PRIVATE */
  194698. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194699. {
  194700. png_debug(1, "in png_handle_IEND\n");
  194701. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  194702. {
  194703. png_error(png_ptr, "No image in file");
  194704. }
  194705. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  194706. if (length != 0)
  194707. {
  194708. png_warning(png_ptr, "Incorrect IEND chunk length");
  194709. }
  194710. png_crc_finish(png_ptr, length);
  194711. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  194712. }
  194713. #if defined(PNG_READ_gAMA_SUPPORTED)
  194714. void /* PRIVATE */
  194715. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194716. {
  194717. png_fixed_point igamma;
  194718. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194719. float file_gamma;
  194720. #endif
  194721. png_byte buf[4];
  194722. png_debug(1, "in png_handle_gAMA\n");
  194723. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194724. png_error(png_ptr, "Missing IHDR before gAMA");
  194725. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194726. {
  194727. png_warning(png_ptr, "Invalid gAMA after IDAT");
  194728. png_crc_finish(png_ptr, length);
  194729. return;
  194730. }
  194731. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194732. /* Should be an error, but we can cope with it */
  194733. png_warning(png_ptr, "Out of place gAMA chunk");
  194734. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  194735. #if defined(PNG_READ_sRGB_SUPPORTED)
  194736. && !(info_ptr->valid & PNG_INFO_sRGB)
  194737. #endif
  194738. )
  194739. {
  194740. png_warning(png_ptr, "Duplicate gAMA chunk");
  194741. png_crc_finish(png_ptr, length);
  194742. return;
  194743. }
  194744. if (length != 4)
  194745. {
  194746. png_warning(png_ptr, "Incorrect gAMA chunk length");
  194747. png_crc_finish(png_ptr, length);
  194748. return;
  194749. }
  194750. png_crc_read(png_ptr, buf, 4);
  194751. if (png_crc_finish(png_ptr, 0))
  194752. return;
  194753. igamma = (png_fixed_point)png_get_uint_32(buf);
  194754. /* check for zero gamma */
  194755. if (igamma == 0)
  194756. {
  194757. png_warning(png_ptr,
  194758. "Ignoring gAMA chunk with gamma=0");
  194759. return;
  194760. }
  194761. #if defined(PNG_READ_sRGB_SUPPORTED)
  194762. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  194763. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  194764. {
  194765. png_warning(png_ptr,
  194766. "Ignoring incorrect gAMA value when sRGB is also present");
  194767. #ifndef PNG_NO_CONSOLE_IO
  194768. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  194769. #endif
  194770. return;
  194771. }
  194772. #endif /* PNG_READ_sRGB_SUPPORTED */
  194773. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194774. file_gamma = (float)igamma / (float)100000.0;
  194775. # ifdef PNG_READ_GAMMA_SUPPORTED
  194776. png_ptr->gamma = file_gamma;
  194777. # endif
  194778. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  194779. #endif
  194780. #ifdef PNG_FIXED_POINT_SUPPORTED
  194781. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  194782. #endif
  194783. }
  194784. #endif
  194785. #if defined(PNG_READ_sBIT_SUPPORTED)
  194786. void /* PRIVATE */
  194787. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194788. {
  194789. png_size_t truelen;
  194790. png_byte buf[4];
  194791. png_debug(1, "in png_handle_sBIT\n");
  194792. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  194793. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194794. png_error(png_ptr, "Missing IHDR before sBIT");
  194795. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194796. {
  194797. png_warning(png_ptr, "Invalid sBIT after IDAT");
  194798. png_crc_finish(png_ptr, length);
  194799. return;
  194800. }
  194801. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194802. {
  194803. /* Should be an error, but we can cope with it */
  194804. png_warning(png_ptr, "Out of place sBIT chunk");
  194805. }
  194806. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  194807. {
  194808. png_warning(png_ptr, "Duplicate sBIT chunk");
  194809. png_crc_finish(png_ptr, length);
  194810. return;
  194811. }
  194812. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  194813. truelen = 3;
  194814. else
  194815. truelen = (png_size_t)png_ptr->channels;
  194816. if (length != truelen || length > 4)
  194817. {
  194818. png_warning(png_ptr, "Incorrect sBIT chunk length");
  194819. png_crc_finish(png_ptr, length);
  194820. return;
  194821. }
  194822. png_crc_read(png_ptr, buf, truelen);
  194823. if (png_crc_finish(png_ptr, 0))
  194824. return;
  194825. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194826. {
  194827. png_ptr->sig_bit.red = buf[0];
  194828. png_ptr->sig_bit.green = buf[1];
  194829. png_ptr->sig_bit.blue = buf[2];
  194830. png_ptr->sig_bit.alpha = buf[3];
  194831. }
  194832. else
  194833. {
  194834. png_ptr->sig_bit.gray = buf[0];
  194835. png_ptr->sig_bit.red = buf[0];
  194836. png_ptr->sig_bit.green = buf[0];
  194837. png_ptr->sig_bit.blue = buf[0];
  194838. png_ptr->sig_bit.alpha = buf[1];
  194839. }
  194840. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  194841. }
  194842. #endif
  194843. #if defined(PNG_READ_cHRM_SUPPORTED)
  194844. void /* PRIVATE */
  194845. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194846. {
  194847. png_byte buf[4];
  194848. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194849. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  194850. #endif
  194851. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194852. int_y_green, int_x_blue, int_y_blue;
  194853. png_uint_32 uint_x, uint_y;
  194854. png_debug(1, "in png_handle_cHRM\n");
  194855. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194856. png_error(png_ptr, "Missing IHDR before cHRM");
  194857. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194858. {
  194859. png_warning(png_ptr, "Invalid cHRM after IDAT");
  194860. png_crc_finish(png_ptr, length);
  194861. return;
  194862. }
  194863. else if (png_ptr->mode & PNG_HAVE_PLTE)
  194864. /* Should be an error, but we can cope with it */
  194865. png_warning(png_ptr, "Missing PLTE before cHRM");
  194866. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  194867. #if defined(PNG_READ_sRGB_SUPPORTED)
  194868. && !(info_ptr->valid & PNG_INFO_sRGB)
  194869. #endif
  194870. )
  194871. {
  194872. png_warning(png_ptr, "Duplicate cHRM chunk");
  194873. png_crc_finish(png_ptr, length);
  194874. return;
  194875. }
  194876. if (length != 32)
  194877. {
  194878. png_warning(png_ptr, "Incorrect cHRM chunk length");
  194879. png_crc_finish(png_ptr, length);
  194880. return;
  194881. }
  194882. png_crc_read(png_ptr, buf, 4);
  194883. uint_x = png_get_uint_32(buf);
  194884. png_crc_read(png_ptr, buf, 4);
  194885. uint_y = png_get_uint_32(buf);
  194886. if (uint_x > 80000L || uint_y > 80000L ||
  194887. uint_x + uint_y > 100000L)
  194888. {
  194889. png_warning(png_ptr, "Invalid cHRM white point");
  194890. png_crc_finish(png_ptr, 24);
  194891. return;
  194892. }
  194893. int_x_white = (png_fixed_point)uint_x;
  194894. int_y_white = (png_fixed_point)uint_y;
  194895. png_crc_read(png_ptr, buf, 4);
  194896. uint_x = png_get_uint_32(buf);
  194897. png_crc_read(png_ptr, buf, 4);
  194898. uint_y = png_get_uint_32(buf);
  194899. if (uint_x + uint_y > 100000L)
  194900. {
  194901. png_warning(png_ptr, "Invalid cHRM red point");
  194902. png_crc_finish(png_ptr, 16);
  194903. return;
  194904. }
  194905. int_x_red = (png_fixed_point)uint_x;
  194906. int_y_red = (png_fixed_point)uint_y;
  194907. png_crc_read(png_ptr, buf, 4);
  194908. uint_x = png_get_uint_32(buf);
  194909. png_crc_read(png_ptr, buf, 4);
  194910. uint_y = png_get_uint_32(buf);
  194911. if (uint_x + uint_y > 100000L)
  194912. {
  194913. png_warning(png_ptr, "Invalid cHRM green point");
  194914. png_crc_finish(png_ptr, 8);
  194915. return;
  194916. }
  194917. int_x_green = (png_fixed_point)uint_x;
  194918. int_y_green = (png_fixed_point)uint_y;
  194919. png_crc_read(png_ptr, buf, 4);
  194920. uint_x = png_get_uint_32(buf);
  194921. png_crc_read(png_ptr, buf, 4);
  194922. uint_y = png_get_uint_32(buf);
  194923. if (uint_x + uint_y > 100000L)
  194924. {
  194925. png_warning(png_ptr, "Invalid cHRM blue point");
  194926. png_crc_finish(png_ptr, 0);
  194927. return;
  194928. }
  194929. int_x_blue = (png_fixed_point)uint_x;
  194930. int_y_blue = (png_fixed_point)uint_y;
  194931. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194932. white_x = (float)int_x_white / (float)100000.0;
  194933. white_y = (float)int_y_white / (float)100000.0;
  194934. red_x = (float)int_x_red / (float)100000.0;
  194935. red_y = (float)int_y_red / (float)100000.0;
  194936. green_x = (float)int_x_green / (float)100000.0;
  194937. green_y = (float)int_y_green / (float)100000.0;
  194938. blue_x = (float)int_x_blue / (float)100000.0;
  194939. blue_y = (float)int_y_blue / (float)100000.0;
  194940. #endif
  194941. #if defined(PNG_READ_sRGB_SUPPORTED)
  194942. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  194943. {
  194944. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  194945. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  194946. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  194947. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  194948. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  194949. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  194950. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  194951. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  194952. {
  194953. png_warning(png_ptr,
  194954. "Ignoring incorrect cHRM value when sRGB is also present");
  194955. #ifndef PNG_NO_CONSOLE_IO
  194956. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194957. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  194958. white_x, white_y, red_x, red_y);
  194959. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  194960. green_x, green_y, blue_x, blue_y);
  194961. #else
  194962. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  194963. int_x_white, int_y_white, int_x_red, int_y_red);
  194964. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  194965. int_x_green, int_y_green, int_x_blue, int_y_blue);
  194966. #endif
  194967. #endif /* PNG_NO_CONSOLE_IO */
  194968. }
  194969. png_crc_finish(png_ptr, 0);
  194970. return;
  194971. }
  194972. #endif /* PNG_READ_sRGB_SUPPORTED */
  194973. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194974. png_set_cHRM(png_ptr, info_ptr,
  194975. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  194976. #endif
  194977. #ifdef PNG_FIXED_POINT_SUPPORTED
  194978. png_set_cHRM_fixed(png_ptr, info_ptr,
  194979. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  194980. int_y_green, int_x_blue, int_y_blue);
  194981. #endif
  194982. if (png_crc_finish(png_ptr, 0))
  194983. return;
  194984. }
  194985. #endif
  194986. #if defined(PNG_READ_sRGB_SUPPORTED)
  194987. void /* PRIVATE */
  194988. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  194989. {
  194990. int intent;
  194991. png_byte buf[1];
  194992. png_debug(1, "in png_handle_sRGB\n");
  194993. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  194994. png_error(png_ptr, "Missing IHDR before sRGB");
  194995. else if (png_ptr->mode & PNG_HAVE_IDAT)
  194996. {
  194997. png_warning(png_ptr, "Invalid sRGB after IDAT");
  194998. png_crc_finish(png_ptr, length);
  194999. return;
  195000. }
  195001. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195002. /* Should be an error, but we can cope with it */
  195003. png_warning(png_ptr, "Out of place sRGB chunk");
  195004. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  195005. {
  195006. png_warning(png_ptr, "Duplicate sRGB chunk");
  195007. png_crc_finish(png_ptr, length);
  195008. return;
  195009. }
  195010. if (length != 1)
  195011. {
  195012. png_warning(png_ptr, "Incorrect sRGB chunk length");
  195013. png_crc_finish(png_ptr, length);
  195014. return;
  195015. }
  195016. png_crc_read(png_ptr, buf, 1);
  195017. if (png_crc_finish(png_ptr, 0))
  195018. return;
  195019. intent = buf[0];
  195020. /* check for bad intent */
  195021. if (intent >= PNG_sRGB_INTENT_LAST)
  195022. {
  195023. png_warning(png_ptr, "Unknown sRGB intent");
  195024. return;
  195025. }
  195026. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  195027. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  195028. {
  195029. png_fixed_point igamma;
  195030. #ifdef PNG_FIXED_POINT_SUPPORTED
  195031. igamma=info_ptr->int_gamma;
  195032. #else
  195033. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195034. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195035. # endif
  195036. #endif
  195037. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195038. {
  195039. png_warning(png_ptr,
  195040. "Ignoring incorrect gAMA value when sRGB is also present");
  195041. #ifndef PNG_NO_CONSOLE_IO
  195042. # ifdef PNG_FIXED_POINT_SUPPORTED
  195043. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195044. # else
  195045. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195046. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195047. # endif
  195048. # endif
  195049. #endif
  195050. }
  195051. }
  195052. #endif /* PNG_READ_gAMA_SUPPORTED */
  195053. #ifdef PNG_READ_cHRM_SUPPORTED
  195054. #ifdef PNG_FIXED_POINT_SUPPORTED
  195055. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195056. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195057. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195058. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195059. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195060. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195061. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195062. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195063. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195064. {
  195065. png_warning(png_ptr,
  195066. "Ignoring incorrect cHRM value when sRGB is also present");
  195067. }
  195068. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195069. #endif /* PNG_READ_cHRM_SUPPORTED */
  195070. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195071. }
  195072. #endif /* PNG_READ_sRGB_SUPPORTED */
  195073. #if defined(PNG_READ_iCCP_SUPPORTED)
  195074. void /* PRIVATE */
  195075. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195076. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195077. {
  195078. png_charp chunkdata;
  195079. png_byte compression_type;
  195080. png_bytep pC;
  195081. png_charp profile;
  195082. png_uint_32 skip = 0;
  195083. png_uint_32 profile_size, profile_length;
  195084. png_size_t slength, prefix_length, data_length;
  195085. png_debug(1, "in png_handle_iCCP\n");
  195086. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195087. png_error(png_ptr, "Missing IHDR before iCCP");
  195088. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195089. {
  195090. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195091. png_crc_finish(png_ptr, length);
  195092. return;
  195093. }
  195094. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195095. /* Should be an error, but we can cope with it */
  195096. png_warning(png_ptr, "Out of place iCCP chunk");
  195097. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195098. {
  195099. png_warning(png_ptr, "Duplicate iCCP chunk");
  195100. png_crc_finish(png_ptr, length);
  195101. return;
  195102. }
  195103. #ifdef PNG_MAX_MALLOC_64K
  195104. if (length > (png_uint_32)65535L)
  195105. {
  195106. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195107. skip = length - (png_uint_32)65535L;
  195108. length = (png_uint_32)65535L;
  195109. }
  195110. #endif
  195111. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195112. slength = (png_size_t)length;
  195113. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195114. if (png_crc_finish(png_ptr, skip))
  195115. {
  195116. png_free(png_ptr, chunkdata);
  195117. return;
  195118. }
  195119. chunkdata[slength] = 0x00;
  195120. for (profile = chunkdata; *profile; profile++)
  195121. /* empty loop to find end of name */ ;
  195122. ++profile;
  195123. /* there should be at least one zero (the compression type byte)
  195124. following the separator, and we should be on it */
  195125. if ( profile >= chunkdata + slength - 1)
  195126. {
  195127. png_free(png_ptr, chunkdata);
  195128. png_warning(png_ptr, "Malformed iCCP chunk");
  195129. return;
  195130. }
  195131. /* compression_type should always be zero */
  195132. compression_type = *profile++;
  195133. if (compression_type)
  195134. {
  195135. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195136. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195137. wrote nonzero) */
  195138. }
  195139. prefix_length = profile - chunkdata;
  195140. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195141. slength, prefix_length, &data_length);
  195142. profile_length = data_length - prefix_length;
  195143. if ( prefix_length > data_length || profile_length < 4)
  195144. {
  195145. png_free(png_ptr, chunkdata);
  195146. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195147. return;
  195148. }
  195149. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195150. pC = (png_bytep)(chunkdata+prefix_length);
  195151. profile_size = ((*(pC ))<<24) |
  195152. ((*(pC+1))<<16) |
  195153. ((*(pC+2))<< 8) |
  195154. ((*(pC+3)) );
  195155. if(profile_size < profile_length)
  195156. profile_length = profile_size;
  195157. if(profile_size > profile_length)
  195158. {
  195159. png_free(png_ptr, chunkdata);
  195160. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195161. return;
  195162. }
  195163. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195164. chunkdata + prefix_length, profile_length);
  195165. png_free(png_ptr, chunkdata);
  195166. }
  195167. #endif /* PNG_READ_iCCP_SUPPORTED */
  195168. #if defined(PNG_READ_sPLT_SUPPORTED)
  195169. void /* PRIVATE */
  195170. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195171. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195172. {
  195173. png_bytep chunkdata;
  195174. png_bytep entry_start;
  195175. png_sPLT_t new_palette;
  195176. #ifdef PNG_NO_POINTER_INDEXING
  195177. png_sPLT_entryp pp;
  195178. #endif
  195179. int data_length, entry_size, i;
  195180. png_uint_32 skip = 0;
  195181. png_size_t slength;
  195182. png_debug(1, "in png_handle_sPLT\n");
  195183. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195184. png_error(png_ptr, "Missing IHDR before sPLT");
  195185. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195186. {
  195187. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195188. png_crc_finish(png_ptr, length);
  195189. return;
  195190. }
  195191. #ifdef PNG_MAX_MALLOC_64K
  195192. if (length > (png_uint_32)65535L)
  195193. {
  195194. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195195. skip = length - (png_uint_32)65535L;
  195196. length = (png_uint_32)65535L;
  195197. }
  195198. #endif
  195199. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195200. slength = (png_size_t)length;
  195201. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195202. if (png_crc_finish(png_ptr, skip))
  195203. {
  195204. png_free(png_ptr, chunkdata);
  195205. return;
  195206. }
  195207. chunkdata[slength] = 0x00;
  195208. for (entry_start = chunkdata; *entry_start; entry_start++)
  195209. /* empty loop to find end of name */ ;
  195210. ++entry_start;
  195211. /* a sample depth should follow the separator, and we should be on it */
  195212. if (entry_start > chunkdata + slength - 2)
  195213. {
  195214. png_free(png_ptr, chunkdata);
  195215. png_warning(png_ptr, "malformed sPLT chunk");
  195216. return;
  195217. }
  195218. new_palette.depth = *entry_start++;
  195219. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195220. data_length = (slength - (entry_start - chunkdata));
  195221. /* integrity-check the data length */
  195222. if (data_length % entry_size)
  195223. {
  195224. png_free(png_ptr, chunkdata);
  195225. png_warning(png_ptr, "sPLT chunk has bad length");
  195226. return;
  195227. }
  195228. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195229. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195230. png_sizeof(png_sPLT_entry)))
  195231. {
  195232. png_warning(png_ptr, "sPLT chunk too long");
  195233. return;
  195234. }
  195235. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195236. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195237. if (new_palette.entries == NULL)
  195238. {
  195239. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195240. return;
  195241. }
  195242. #ifndef PNG_NO_POINTER_INDEXING
  195243. for (i = 0; i < new_palette.nentries; i++)
  195244. {
  195245. png_sPLT_entryp pp = new_palette.entries + i;
  195246. if (new_palette.depth == 8)
  195247. {
  195248. pp->red = *entry_start++;
  195249. pp->green = *entry_start++;
  195250. pp->blue = *entry_start++;
  195251. pp->alpha = *entry_start++;
  195252. }
  195253. else
  195254. {
  195255. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195256. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195257. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195258. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195259. }
  195260. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195261. }
  195262. #else
  195263. pp = new_palette.entries;
  195264. for (i = 0; i < new_palette.nentries; i++)
  195265. {
  195266. if (new_palette.depth == 8)
  195267. {
  195268. pp[i].red = *entry_start++;
  195269. pp[i].green = *entry_start++;
  195270. pp[i].blue = *entry_start++;
  195271. pp[i].alpha = *entry_start++;
  195272. }
  195273. else
  195274. {
  195275. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195276. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195277. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195278. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195279. }
  195280. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195281. }
  195282. #endif
  195283. /* discard all chunk data except the name and stash that */
  195284. new_palette.name = (png_charp)chunkdata;
  195285. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  195286. png_free(png_ptr, chunkdata);
  195287. png_free(png_ptr, new_palette.entries);
  195288. }
  195289. #endif /* PNG_READ_sPLT_SUPPORTED */
  195290. #if defined(PNG_READ_tRNS_SUPPORTED)
  195291. void /* PRIVATE */
  195292. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195293. {
  195294. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  195295. int bit_mask;
  195296. png_debug(1, "in png_handle_tRNS\n");
  195297. /* For non-indexed color, mask off any bits in the tRNS value that
  195298. * exceed the bit depth. Some creators were writing extra bits there.
  195299. * This is not needed for indexed color. */
  195300. bit_mask = (1 << png_ptr->bit_depth) - 1;
  195301. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195302. png_error(png_ptr, "Missing IHDR before tRNS");
  195303. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195304. {
  195305. png_warning(png_ptr, "Invalid tRNS after IDAT");
  195306. png_crc_finish(png_ptr, length);
  195307. return;
  195308. }
  195309. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195310. {
  195311. png_warning(png_ptr, "Duplicate tRNS chunk");
  195312. png_crc_finish(png_ptr, length);
  195313. return;
  195314. }
  195315. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  195316. {
  195317. png_byte buf[2];
  195318. if (length != 2)
  195319. {
  195320. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195321. png_crc_finish(png_ptr, length);
  195322. return;
  195323. }
  195324. png_crc_read(png_ptr, buf, 2);
  195325. png_ptr->num_trans = 1;
  195326. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  195327. }
  195328. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  195329. {
  195330. png_byte buf[6];
  195331. if (length != 6)
  195332. {
  195333. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195334. png_crc_finish(png_ptr, length);
  195335. return;
  195336. }
  195337. png_crc_read(png_ptr, buf, (png_size_t)length);
  195338. png_ptr->num_trans = 1;
  195339. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  195340. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  195341. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  195342. }
  195343. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195344. {
  195345. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195346. {
  195347. /* Should be an error, but we can cope with it. */
  195348. png_warning(png_ptr, "Missing PLTE before tRNS");
  195349. }
  195350. if (length > (png_uint_32)png_ptr->num_palette ||
  195351. length > PNG_MAX_PALETTE_LENGTH)
  195352. {
  195353. png_warning(png_ptr, "Incorrect tRNS chunk length");
  195354. png_crc_finish(png_ptr, length);
  195355. return;
  195356. }
  195357. if (length == 0)
  195358. {
  195359. png_warning(png_ptr, "Zero length tRNS chunk");
  195360. png_crc_finish(png_ptr, length);
  195361. return;
  195362. }
  195363. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  195364. png_ptr->num_trans = (png_uint_16)length;
  195365. }
  195366. else
  195367. {
  195368. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  195369. png_crc_finish(png_ptr, length);
  195370. return;
  195371. }
  195372. if (png_crc_finish(png_ptr, 0))
  195373. {
  195374. png_ptr->num_trans = 0;
  195375. return;
  195376. }
  195377. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  195378. &(png_ptr->trans_values));
  195379. }
  195380. #endif
  195381. #if defined(PNG_READ_bKGD_SUPPORTED)
  195382. void /* PRIVATE */
  195383. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195384. {
  195385. png_size_t truelen;
  195386. png_byte buf[6];
  195387. png_debug(1, "in png_handle_bKGD\n");
  195388. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195389. png_error(png_ptr, "Missing IHDR before bKGD");
  195390. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195391. {
  195392. png_warning(png_ptr, "Invalid bKGD after IDAT");
  195393. png_crc_finish(png_ptr, length);
  195394. return;
  195395. }
  195396. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  195397. !(png_ptr->mode & PNG_HAVE_PLTE))
  195398. {
  195399. png_warning(png_ptr, "Missing PLTE before bKGD");
  195400. png_crc_finish(png_ptr, length);
  195401. return;
  195402. }
  195403. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  195404. {
  195405. png_warning(png_ptr, "Duplicate bKGD chunk");
  195406. png_crc_finish(png_ptr, length);
  195407. return;
  195408. }
  195409. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195410. truelen = 1;
  195411. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195412. truelen = 6;
  195413. else
  195414. truelen = 2;
  195415. if (length != truelen)
  195416. {
  195417. png_warning(png_ptr, "Incorrect bKGD chunk length");
  195418. png_crc_finish(png_ptr, length);
  195419. return;
  195420. }
  195421. png_crc_read(png_ptr, buf, truelen);
  195422. if (png_crc_finish(png_ptr, 0))
  195423. return;
  195424. /* We convert the index value into RGB components so that we can allow
  195425. * arbitrary RGB values for background when we have transparency, and
  195426. * so it is easy to determine the RGB values of the background color
  195427. * from the info_ptr struct. */
  195428. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195429. {
  195430. png_ptr->background.index = buf[0];
  195431. if(info_ptr->num_palette)
  195432. {
  195433. if(buf[0] > info_ptr->num_palette)
  195434. {
  195435. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  195436. return;
  195437. }
  195438. png_ptr->background.red =
  195439. (png_uint_16)png_ptr->palette[buf[0]].red;
  195440. png_ptr->background.green =
  195441. (png_uint_16)png_ptr->palette[buf[0]].green;
  195442. png_ptr->background.blue =
  195443. (png_uint_16)png_ptr->palette[buf[0]].blue;
  195444. }
  195445. }
  195446. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  195447. {
  195448. png_ptr->background.red =
  195449. png_ptr->background.green =
  195450. png_ptr->background.blue =
  195451. png_ptr->background.gray = png_get_uint_16(buf);
  195452. }
  195453. else
  195454. {
  195455. png_ptr->background.red = png_get_uint_16(buf);
  195456. png_ptr->background.green = png_get_uint_16(buf + 2);
  195457. png_ptr->background.blue = png_get_uint_16(buf + 4);
  195458. }
  195459. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  195460. }
  195461. #endif
  195462. #if defined(PNG_READ_hIST_SUPPORTED)
  195463. void /* PRIVATE */
  195464. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195465. {
  195466. unsigned int num, i;
  195467. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  195468. png_debug(1, "in png_handle_hIST\n");
  195469. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195470. png_error(png_ptr, "Missing IHDR before hIST");
  195471. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195472. {
  195473. png_warning(png_ptr, "Invalid hIST after IDAT");
  195474. png_crc_finish(png_ptr, length);
  195475. return;
  195476. }
  195477. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  195478. {
  195479. png_warning(png_ptr, "Missing PLTE before hIST");
  195480. png_crc_finish(png_ptr, length);
  195481. return;
  195482. }
  195483. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  195484. {
  195485. png_warning(png_ptr, "Duplicate hIST chunk");
  195486. png_crc_finish(png_ptr, length);
  195487. return;
  195488. }
  195489. num = length / 2 ;
  195490. if (num != (unsigned int) png_ptr->num_palette || num >
  195491. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  195492. {
  195493. png_warning(png_ptr, "Incorrect hIST chunk length");
  195494. png_crc_finish(png_ptr, length);
  195495. return;
  195496. }
  195497. for (i = 0; i < num; i++)
  195498. {
  195499. png_byte buf[2];
  195500. png_crc_read(png_ptr, buf, 2);
  195501. readbuf[i] = png_get_uint_16(buf);
  195502. }
  195503. if (png_crc_finish(png_ptr, 0))
  195504. return;
  195505. png_set_hIST(png_ptr, info_ptr, readbuf);
  195506. }
  195507. #endif
  195508. #if defined(PNG_READ_pHYs_SUPPORTED)
  195509. void /* PRIVATE */
  195510. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195511. {
  195512. png_byte buf[9];
  195513. png_uint_32 res_x, res_y;
  195514. int unit_type;
  195515. png_debug(1, "in png_handle_pHYs\n");
  195516. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195517. png_error(png_ptr, "Missing IHDR before pHYs");
  195518. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195519. {
  195520. png_warning(png_ptr, "Invalid pHYs after IDAT");
  195521. png_crc_finish(png_ptr, length);
  195522. return;
  195523. }
  195524. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  195525. {
  195526. png_warning(png_ptr, "Duplicate pHYs chunk");
  195527. png_crc_finish(png_ptr, length);
  195528. return;
  195529. }
  195530. if (length != 9)
  195531. {
  195532. png_warning(png_ptr, "Incorrect pHYs chunk length");
  195533. png_crc_finish(png_ptr, length);
  195534. return;
  195535. }
  195536. png_crc_read(png_ptr, buf, 9);
  195537. if (png_crc_finish(png_ptr, 0))
  195538. return;
  195539. res_x = png_get_uint_32(buf);
  195540. res_y = png_get_uint_32(buf + 4);
  195541. unit_type = buf[8];
  195542. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  195543. }
  195544. #endif
  195545. #if defined(PNG_READ_oFFs_SUPPORTED)
  195546. void /* PRIVATE */
  195547. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195548. {
  195549. png_byte buf[9];
  195550. png_int_32 offset_x, offset_y;
  195551. int unit_type;
  195552. png_debug(1, "in png_handle_oFFs\n");
  195553. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195554. png_error(png_ptr, "Missing IHDR before oFFs");
  195555. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195556. {
  195557. png_warning(png_ptr, "Invalid oFFs after IDAT");
  195558. png_crc_finish(png_ptr, length);
  195559. return;
  195560. }
  195561. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  195562. {
  195563. png_warning(png_ptr, "Duplicate oFFs chunk");
  195564. png_crc_finish(png_ptr, length);
  195565. return;
  195566. }
  195567. if (length != 9)
  195568. {
  195569. png_warning(png_ptr, "Incorrect oFFs chunk length");
  195570. png_crc_finish(png_ptr, length);
  195571. return;
  195572. }
  195573. png_crc_read(png_ptr, buf, 9);
  195574. if (png_crc_finish(png_ptr, 0))
  195575. return;
  195576. offset_x = png_get_int_32(buf);
  195577. offset_y = png_get_int_32(buf + 4);
  195578. unit_type = buf[8];
  195579. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  195580. }
  195581. #endif
  195582. #if defined(PNG_READ_pCAL_SUPPORTED)
  195583. /* read the pCAL chunk (described in the PNG Extensions document) */
  195584. void /* PRIVATE */
  195585. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195586. {
  195587. png_charp purpose;
  195588. png_int_32 X0, X1;
  195589. png_byte type, nparams;
  195590. png_charp buf, units, endptr;
  195591. png_charpp params;
  195592. png_size_t slength;
  195593. int i;
  195594. png_debug(1, "in png_handle_pCAL\n");
  195595. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195596. png_error(png_ptr, "Missing IHDR before pCAL");
  195597. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195598. {
  195599. png_warning(png_ptr, "Invalid pCAL after IDAT");
  195600. png_crc_finish(png_ptr, length);
  195601. return;
  195602. }
  195603. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  195604. {
  195605. png_warning(png_ptr, "Duplicate pCAL chunk");
  195606. png_crc_finish(png_ptr, length);
  195607. return;
  195608. }
  195609. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  195610. length + 1);
  195611. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195612. if (purpose == NULL)
  195613. {
  195614. png_warning(png_ptr, "No memory for pCAL purpose.");
  195615. return;
  195616. }
  195617. slength = (png_size_t)length;
  195618. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  195619. if (png_crc_finish(png_ptr, 0))
  195620. {
  195621. png_free(png_ptr, purpose);
  195622. return;
  195623. }
  195624. purpose[slength] = 0x00; /* null terminate the last string */
  195625. png_debug(3, "Finding end of pCAL purpose string\n");
  195626. for (buf = purpose; *buf; buf++)
  195627. /* empty loop */ ;
  195628. endptr = purpose + slength;
  195629. /* We need to have at least 12 bytes after the purpose string
  195630. in order to get the parameter information. */
  195631. if (endptr <= buf + 12)
  195632. {
  195633. png_warning(png_ptr, "Invalid pCAL data");
  195634. png_free(png_ptr, purpose);
  195635. return;
  195636. }
  195637. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  195638. X0 = png_get_int_32((png_bytep)buf+1);
  195639. X1 = png_get_int_32((png_bytep)buf+5);
  195640. type = buf[9];
  195641. nparams = buf[10];
  195642. units = buf + 11;
  195643. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  195644. /* Check that we have the right number of parameters for known
  195645. equation types. */
  195646. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  195647. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  195648. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  195649. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  195650. {
  195651. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  195652. png_free(png_ptr, purpose);
  195653. return;
  195654. }
  195655. else if (type >= PNG_EQUATION_LAST)
  195656. {
  195657. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  195658. }
  195659. for (buf = units; *buf; buf++)
  195660. /* Empty loop to move past the units string. */ ;
  195661. png_debug(3, "Allocating pCAL parameters array\n");
  195662. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  195663. *png_sizeof(png_charp))) ;
  195664. if (params == NULL)
  195665. {
  195666. png_free(png_ptr, purpose);
  195667. png_warning(png_ptr, "No memory for pCAL params.");
  195668. return;
  195669. }
  195670. /* Get pointers to the start of each parameter string. */
  195671. for (i = 0; i < (int)nparams; i++)
  195672. {
  195673. buf++; /* Skip the null string terminator from previous parameter. */
  195674. png_debug1(3, "Reading pCAL parameter %d\n", i);
  195675. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  195676. /* Empty loop to move past each parameter string */ ;
  195677. /* Make sure we haven't run out of data yet */
  195678. if (buf > endptr)
  195679. {
  195680. png_warning(png_ptr, "Invalid pCAL data");
  195681. png_free(png_ptr, purpose);
  195682. png_free(png_ptr, params);
  195683. return;
  195684. }
  195685. }
  195686. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  195687. units, params);
  195688. png_free(png_ptr, purpose);
  195689. png_free(png_ptr, params);
  195690. }
  195691. #endif
  195692. #if defined(PNG_READ_sCAL_SUPPORTED)
  195693. /* read the sCAL chunk */
  195694. void /* PRIVATE */
  195695. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195696. {
  195697. png_charp buffer, ep;
  195698. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195699. double width, height;
  195700. png_charp vp;
  195701. #else
  195702. #ifdef PNG_FIXED_POINT_SUPPORTED
  195703. png_charp swidth, sheight;
  195704. #endif
  195705. #endif
  195706. png_size_t slength;
  195707. png_debug(1, "in png_handle_sCAL\n");
  195708. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195709. png_error(png_ptr, "Missing IHDR before sCAL");
  195710. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195711. {
  195712. png_warning(png_ptr, "Invalid sCAL after IDAT");
  195713. png_crc_finish(png_ptr, length);
  195714. return;
  195715. }
  195716. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  195717. {
  195718. png_warning(png_ptr, "Duplicate sCAL chunk");
  195719. png_crc_finish(png_ptr, length);
  195720. return;
  195721. }
  195722. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  195723. length + 1);
  195724. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195725. if (buffer == NULL)
  195726. {
  195727. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  195728. return;
  195729. }
  195730. slength = (png_size_t)length;
  195731. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  195732. if (png_crc_finish(png_ptr, 0))
  195733. {
  195734. png_free(png_ptr, buffer);
  195735. return;
  195736. }
  195737. buffer[slength] = 0x00; /* null terminate the last string */
  195738. ep = buffer + 1; /* skip unit byte */
  195739. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195740. width = png_strtod(png_ptr, ep, &vp);
  195741. if (*vp)
  195742. {
  195743. png_warning(png_ptr, "malformed width string in sCAL chunk");
  195744. return;
  195745. }
  195746. #else
  195747. #ifdef PNG_FIXED_POINT_SUPPORTED
  195748. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195749. if (swidth == NULL)
  195750. {
  195751. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  195752. return;
  195753. }
  195754. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  195755. #endif
  195756. #endif
  195757. for (ep = buffer; *ep; ep++)
  195758. /* empty loop */ ;
  195759. ep++;
  195760. if (buffer + slength < ep)
  195761. {
  195762. png_warning(png_ptr, "Truncated sCAL chunk");
  195763. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  195764. !defined(PNG_FLOATING_POINT_SUPPORTED)
  195765. png_free(png_ptr, swidth);
  195766. #endif
  195767. png_free(png_ptr, buffer);
  195768. return;
  195769. }
  195770. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195771. height = png_strtod(png_ptr, ep, &vp);
  195772. if (*vp)
  195773. {
  195774. png_warning(png_ptr, "malformed height string in sCAL chunk");
  195775. return;
  195776. }
  195777. #else
  195778. #ifdef PNG_FIXED_POINT_SUPPORTED
  195779. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  195780. if (swidth == NULL)
  195781. {
  195782. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  195783. return;
  195784. }
  195785. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  195786. #endif
  195787. #endif
  195788. if (buffer + slength < ep
  195789. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195790. || width <= 0. || height <= 0.
  195791. #endif
  195792. )
  195793. {
  195794. png_warning(png_ptr, "Invalid sCAL data");
  195795. png_free(png_ptr, buffer);
  195796. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195797. png_free(png_ptr, swidth);
  195798. png_free(png_ptr, sheight);
  195799. #endif
  195800. return;
  195801. }
  195802. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195803. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  195804. #else
  195805. #ifdef PNG_FIXED_POINT_SUPPORTED
  195806. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  195807. #endif
  195808. #endif
  195809. png_free(png_ptr, buffer);
  195810. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  195811. png_free(png_ptr, swidth);
  195812. png_free(png_ptr, sheight);
  195813. #endif
  195814. }
  195815. #endif
  195816. #if defined(PNG_READ_tIME_SUPPORTED)
  195817. void /* PRIVATE */
  195818. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195819. {
  195820. png_byte buf[7];
  195821. png_time mod_time;
  195822. png_debug(1, "in png_handle_tIME\n");
  195823. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195824. png_error(png_ptr, "Out of place tIME chunk");
  195825. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  195826. {
  195827. png_warning(png_ptr, "Duplicate tIME chunk");
  195828. png_crc_finish(png_ptr, length);
  195829. return;
  195830. }
  195831. if (png_ptr->mode & PNG_HAVE_IDAT)
  195832. png_ptr->mode |= PNG_AFTER_IDAT;
  195833. if (length != 7)
  195834. {
  195835. png_warning(png_ptr, "Incorrect tIME chunk length");
  195836. png_crc_finish(png_ptr, length);
  195837. return;
  195838. }
  195839. png_crc_read(png_ptr, buf, 7);
  195840. if (png_crc_finish(png_ptr, 0))
  195841. return;
  195842. mod_time.second = buf[6];
  195843. mod_time.minute = buf[5];
  195844. mod_time.hour = buf[4];
  195845. mod_time.day = buf[3];
  195846. mod_time.month = buf[2];
  195847. mod_time.year = png_get_uint_16(buf);
  195848. png_set_tIME(png_ptr, info_ptr, &mod_time);
  195849. }
  195850. #endif
  195851. #if defined(PNG_READ_tEXt_SUPPORTED)
  195852. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195853. void /* PRIVATE */
  195854. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195855. {
  195856. png_textp text_ptr;
  195857. png_charp key;
  195858. png_charp text;
  195859. png_uint_32 skip = 0;
  195860. png_size_t slength;
  195861. int ret;
  195862. png_debug(1, "in png_handle_tEXt\n");
  195863. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195864. png_error(png_ptr, "Missing IHDR before tEXt");
  195865. if (png_ptr->mode & PNG_HAVE_IDAT)
  195866. png_ptr->mode |= PNG_AFTER_IDAT;
  195867. #ifdef PNG_MAX_MALLOC_64K
  195868. if (length > (png_uint_32)65535L)
  195869. {
  195870. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  195871. skip = length - (png_uint_32)65535L;
  195872. length = (png_uint_32)65535L;
  195873. }
  195874. #endif
  195875. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195876. if (key == NULL)
  195877. {
  195878. png_warning(png_ptr, "No memory to process text chunk.");
  195879. return;
  195880. }
  195881. slength = (png_size_t)length;
  195882. png_crc_read(png_ptr, (png_bytep)key, slength);
  195883. if (png_crc_finish(png_ptr, skip))
  195884. {
  195885. png_free(png_ptr, key);
  195886. return;
  195887. }
  195888. key[slength] = 0x00;
  195889. for (text = key; *text; text++)
  195890. /* empty loop to find end of key */ ;
  195891. if (text != key + slength)
  195892. text++;
  195893. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195894. (png_uint_32)png_sizeof(png_text));
  195895. if (text_ptr == NULL)
  195896. {
  195897. png_warning(png_ptr, "Not enough memory to process text chunk.");
  195898. png_free(png_ptr, key);
  195899. return;
  195900. }
  195901. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  195902. text_ptr->key = key;
  195903. #ifdef PNG_iTXt_SUPPORTED
  195904. text_ptr->lang = NULL;
  195905. text_ptr->lang_key = NULL;
  195906. text_ptr->itxt_length = 0;
  195907. #endif
  195908. text_ptr->text = text;
  195909. text_ptr->text_length = png_strlen(text);
  195910. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195911. png_free(png_ptr, key);
  195912. png_free(png_ptr, text_ptr);
  195913. if (ret)
  195914. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  195915. }
  195916. #endif
  195917. #if defined(PNG_READ_zTXt_SUPPORTED)
  195918. /* note: this does not correctly handle chunks that are > 64K under DOS */
  195919. void /* PRIVATE */
  195920. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195921. {
  195922. png_textp text_ptr;
  195923. png_charp chunkdata;
  195924. png_charp text;
  195925. int comp_type;
  195926. int ret;
  195927. png_size_t slength, prefix_len, data_len;
  195928. png_debug(1, "in png_handle_zTXt\n");
  195929. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195930. png_error(png_ptr, "Missing IHDR before zTXt");
  195931. if (png_ptr->mode & PNG_HAVE_IDAT)
  195932. png_ptr->mode |= PNG_AFTER_IDAT;
  195933. #ifdef PNG_MAX_MALLOC_64K
  195934. /* We will no doubt have problems with chunks even half this size, but
  195935. there is no hard and fast rule to tell us where to stop. */
  195936. if (length > (png_uint_32)65535L)
  195937. {
  195938. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  195939. png_crc_finish(png_ptr, length);
  195940. return;
  195941. }
  195942. #endif
  195943. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  195944. if (chunkdata == NULL)
  195945. {
  195946. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  195947. return;
  195948. }
  195949. slength = (png_size_t)length;
  195950. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195951. if (png_crc_finish(png_ptr, 0))
  195952. {
  195953. png_free(png_ptr, chunkdata);
  195954. return;
  195955. }
  195956. chunkdata[slength] = 0x00;
  195957. for (text = chunkdata; *text; text++)
  195958. /* empty loop */ ;
  195959. /* zTXt must have some text after the chunkdataword */
  195960. if (text >= chunkdata + slength - 2)
  195961. {
  195962. png_warning(png_ptr, "Truncated zTXt chunk");
  195963. png_free(png_ptr, chunkdata);
  195964. return;
  195965. }
  195966. else
  195967. {
  195968. comp_type = *(++text);
  195969. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  195970. {
  195971. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  195972. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  195973. }
  195974. text++; /* skip the compression_method byte */
  195975. }
  195976. prefix_len = text - chunkdata;
  195977. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  195978. (png_size_t)length, prefix_len, &data_len);
  195979. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  195980. (png_uint_32)png_sizeof(png_text));
  195981. if (text_ptr == NULL)
  195982. {
  195983. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  195984. png_free(png_ptr, chunkdata);
  195985. return;
  195986. }
  195987. text_ptr->compression = comp_type;
  195988. text_ptr->key = chunkdata;
  195989. #ifdef PNG_iTXt_SUPPORTED
  195990. text_ptr->lang = NULL;
  195991. text_ptr->lang_key = NULL;
  195992. text_ptr->itxt_length = 0;
  195993. #endif
  195994. text_ptr->text = chunkdata + prefix_len;
  195995. text_ptr->text_length = data_len;
  195996. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  195997. png_free(png_ptr, text_ptr);
  195998. png_free(png_ptr, chunkdata);
  195999. if (ret)
  196000. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  196001. }
  196002. #endif
  196003. #if defined(PNG_READ_iTXt_SUPPORTED)
  196004. /* note: this does not correctly handle chunks that are > 64K under DOS */
  196005. void /* PRIVATE */
  196006. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196007. {
  196008. png_textp text_ptr;
  196009. png_charp chunkdata;
  196010. png_charp key, lang, text, lang_key;
  196011. int comp_flag;
  196012. int comp_type = 0;
  196013. int ret;
  196014. png_size_t slength, prefix_len, data_len;
  196015. png_debug(1, "in png_handle_iTXt\n");
  196016. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196017. png_error(png_ptr, "Missing IHDR before iTXt");
  196018. if (png_ptr->mode & PNG_HAVE_IDAT)
  196019. png_ptr->mode |= PNG_AFTER_IDAT;
  196020. #ifdef PNG_MAX_MALLOC_64K
  196021. /* We will no doubt have problems with chunks even half this size, but
  196022. there is no hard and fast rule to tell us where to stop. */
  196023. if (length > (png_uint_32)65535L)
  196024. {
  196025. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  196026. png_crc_finish(png_ptr, length);
  196027. return;
  196028. }
  196029. #endif
  196030. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196031. if (chunkdata == NULL)
  196032. {
  196033. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196034. return;
  196035. }
  196036. slength = (png_size_t)length;
  196037. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196038. if (png_crc_finish(png_ptr, 0))
  196039. {
  196040. png_free(png_ptr, chunkdata);
  196041. return;
  196042. }
  196043. chunkdata[slength] = 0x00;
  196044. for (lang = chunkdata; *lang; lang++)
  196045. /* empty loop */ ;
  196046. lang++; /* skip NUL separator */
  196047. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196048. translated keyword (possibly empty), and possibly some text after the
  196049. keyword */
  196050. if (lang >= chunkdata + slength - 3)
  196051. {
  196052. png_warning(png_ptr, "Truncated iTXt chunk");
  196053. png_free(png_ptr, chunkdata);
  196054. return;
  196055. }
  196056. else
  196057. {
  196058. comp_flag = *lang++;
  196059. comp_type = *lang++;
  196060. }
  196061. for (lang_key = lang; *lang_key; lang_key++)
  196062. /* empty loop */ ;
  196063. lang_key++; /* skip NUL separator */
  196064. if (lang_key >= chunkdata + slength)
  196065. {
  196066. png_warning(png_ptr, "Truncated iTXt chunk");
  196067. png_free(png_ptr, chunkdata);
  196068. return;
  196069. }
  196070. for (text = lang_key; *text; text++)
  196071. /* empty loop */ ;
  196072. text++; /* skip NUL separator */
  196073. if (text >= chunkdata + slength)
  196074. {
  196075. png_warning(png_ptr, "Malformed iTXt chunk");
  196076. png_free(png_ptr, chunkdata);
  196077. return;
  196078. }
  196079. prefix_len = text - chunkdata;
  196080. key=chunkdata;
  196081. if (comp_flag)
  196082. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196083. (size_t)length, prefix_len, &data_len);
  196084. else
  196085. data_len=png_strlen(chunkdata + prefix_len);
  196086. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196087. (png_uint_32)png_sizeof(png_text));
  196088. if (text_ptr == NULL)
  196089. {
  196090. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196091. png_free(png_ptr, chunkdata);
  196092. return;
  196093. }
  196094. text_ptr->compression = (int)comp_flag + 1;
  196095. text_ptr->lang_key = chunkdata+(lang_key-key);
  196096. text_ptr->lang = chunkdata+(lang-key);
  196097. text_ptr->itxt_length = data_len;
  196098. text_ptr->text_length = 0;
  196099. text_ptr->key = chunkdata;
  196100. text_ptr->text = chunkdata + prefix_len;
  196101. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196102. png_free(png_ptr, text_ptr);
  196103. png_free(png_ptr, chunkdata);
  196104. if (ret)
  196105. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196106. }
  196107. #endif
  196108. /* This function is called when we haven't found a handler for a
  196109. chunk. If there isn't a problem with the chunk itself (ie bad
  196110. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196111. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196112. case it will be saved away to be written out later. */
  196113. void /* PRIVATE */
  196114. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196115. {
  196116. png_uint_32 skip = 0;
  196117. png_debug(1, "in png_handle_unknown\n");
  196118. if (png_ptr->mode & PNG_HAVE_IDAT)
  196119. {
  196120. #ifdef PNG_USE_LOCAL_ARRAYS
  196121. PNG_CONST PNG_IDAT;
  196122. #endif
  196123. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196124. png_ptr->mode |= PNG_AFTER_IDAT;
  196125. }
  196126. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196127. if (!(png_ptr->chunk_name[0] & 0x20))
  196128. {
  196129. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196130. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196131. PNG_HANDLE_CHUNK_ALWAYS
  196132. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196133. && png_ptr->read_user_chunk_fn == NULL
  196134. #endif
  196135. )
  196136. #endif
  196137. png_chunk_error(png_ptr, "unknown critical chunk");
  196138. }
  196139. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196140. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196141. (png_ptr->read_user_chunk_fn != NULL))
  196142. {
  196143. #ifdef PNG_MAX_MALLOC_64K
  196144. if (length > (png_uint_32)65535L)
  196145. {
  196146. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196147. skip = length - (png_uint_32)65535L;
  196148. length = (png_uint_32)65535L;
  196149. }
  196150. #endif
  196151. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196152. (png_charp)png_ptr->chunk_name, 5);
  196153. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196154. png_ptr->unknown_chunk.size = (png_size_t)length;
  196155. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196156. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196157. if(png_ptr->read_user_chunk_fn != NULL)
  196158. {
  196159. /* callback to user unknown chunk handler */
  196160. int ret;
  196161. ret = (*(png_ptr->read_user_chunk_fn))
  196162. (png_ptr, &png_ptr->unknown_chunk);
  196163. if (ret < 0)
  196164. png_chunk_error(png_ptr, "error in user chunk");
  196165. if (ret == 0)
  196166. {
  196167. if (!(png_ptr->chunk_name[0] & 0x20))
  196168. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196169. PNG_HANDLE_CHUNK_ALWAYS)
  196170. png_chunk_error(png_ptr, "unknown critical chunk");
  196171. png_set_unknown_chunks(png_ptr, info_ptr,
  196172. &png_ptr->unknown_chunk, 1);
  196173. }
  196174. }
  196175. #else
  196176. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196177. #endif
  196178. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196179. png_ptr->unknown_chunk.data = NULL;
  196180. }
  196181. else
  196182. #endif
  196183. skip = length;
  196184. png_crc_finish(png_ptr, skip);
  196185. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196186. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196187. #endif
  196188. }
  196189. /* This function is called to verify that a chunk name is valid.
  196190. This function can't have the "critical chunk check" incorporated
  196191. into it, since in the future we will need to be able to call user
  196192. functions to handle unknown critical chunks after we check that
  196193. the chunk name itself is valid. */
  196194. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196195. void /* PRIVATE */
  196196. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196197. {
  196198. png_debug(1, "in png_check_chunk_name\n");
  196199. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196200. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196201. {
  196202. png_chunk_error(png_ptr, "invalid chunk type");
  196203. }
  196204. }
  196205. /* Combines the row recently read in with the existing pixels in the
  196206. row. This routine takes care of alpha and transparency if requested.
  196207. This routine also handles the two methods of progressive display
  196208. of interlaced images, depending on the mask value.
  196209. The mask value describes which pixels are to be combined with
  196210. the row. The pattern always repeats every 8 pixels, so just 8
  196211. bits are needed. A one indicates the pixel is to be combined,
  196212. a zero indicates the pixel is to be skipped. This is in addition
  196213. to any alpha or transparency value associated with the pixel. If
  196214. you want all pixels to be combined, pass 0xff (255) in mask. */
  196215. void /* PRIVATE */
  196216. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196217. {
  196218. png_debug(1,"in png_combine_row\n");
  196219. if (mask == 0xff)
  196220. {
  196221. png_memcpy(row, png_ptr->row_buf + 1,
  196222. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196223. }
  196224. else
  196225. {
  196226. switch (png_ptr->row_info.pixel_depth)
  196227. {
  196228. case 1:
  196229. {
  196230. png_bytep sp = png_ptr->row_buf + 1;
  196231. png_bytep dp = row;
  196232. int s_inc, s_start, s_end;
  196233. int m = 0x80;
  196234. int shift;
  196235. png_uint_32 i;
  196236. png_uint_32 row_width = png_ptr->width;
  196237. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196238. if (png_ptr->transformations & PNG_PACKSWAP)
  196239. {
  196240. s_start = 0;
  196241. s_end = 7;
  196242. s_inc = 1;
  196243. }
  196244. else
  196245. #endif
  196246. {
  196247. s_start = 7;
  196248. s_end = 0;
  196249. s_inc = -1;
  196250. }
  196251. shift = s_start;
  196252. for (i = 0; i < row_width; i++)
  196253. {
  196254. if (m & mask)
  196255. {
  196256. int value;
  196257. value = (*sp >> shift) & 0x01;
  196258. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196259. *dp |= (png_byte)(value << shift);
  196260. }
  196261. if (shift == s_end)
  196262. {
  196263. shift = s_start;
  196264. sp++;
  196265. dp++;
  196266. }
  196267. else
  196268. shift += s_inc;
  196269. if (m == 1)
  196270. m = 0x80;
  196271. else
  196272. m >>= 1;
  196273. }
  196274. break;
  196275. }
  196276. case 2:
  196277. {
  196278. png_bytep sp = png_ptr->row_buf + 1;
  196279. png_bytep dp = row;
  196280. int s_start, s_end, s_inc;
  196281. int m = 0x80;
  196282. int shift;
  196283. png_uint_32 i;
  196284. png_uint_32 row_width = png_ptr->width;
  196285. int value;
  196286. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196287. if (png_ptr->transformations & PNG_PACKSWAP)
  196288. {
  196289. s_start = 0;
  196290. s_end = 6;
  196291. s_inc = 2;
  196292. }
  196293. else
  196294. #endif
  196295. {
  196296. s_start = 6;
  196297. s_end = 0;
  196298. s_inc = -2;
  196299. }
  196300. shift = s_start;
  196301. for (i = 0; i < row_width; i++)
  196302. {
  196303. if (m & mask)
  196304. {
  196305. value = (*sp >> shift) & 0x03;
  196306. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  196307. *dp |= (png_byte)(value << shift);
  196308. }
  196309. if (shift == s_end)
  196310. {
  196311. shift = s_start;
  196312. sp++;
  196313. dp++;
  196314. }
  196315. else
  196316. shift += s_inc;
  196317. if (m == 1)
  196318. m = 0x80;
  196319. else
  196320. m >>= 1;
  196321. }
  196322. break;
  196323. }
  196324. case 4:
  196325. {
  196326. png_bytep sp = png_ptr->row_buf + 1;
  196327. png_bytep dp = row;
  196328. int s_start, s_end, s_inc;
  196329. int m = 0x80;
  196330. int shift;
  196331. png_uint_32 i;
  196332. png_uint_32 row_width = png_ptr->width;
  196333. int value;
  196334. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196335. if (png_ptr->transformations & PNG_PACKSWAP)
  196336. {
  196337. s_start = 0;
  196338. s_end = 4;
  196339. s_inc = 4;
  196340. }
  196341. else
  196342. #endif
  196343. {
  196344. s_start = 4;
  196345. s_end = 0;
  196346. s_inc = -4;
  196347. }
  196348. shift = s_start;
  196349. for (i = 0; i < row_width; i++)
  196350. {
  196351. if (m & mask)
  196352. {
  196353. value = (*sp >> shift) & 0xf;
  196354. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  196355. *dp |= (png_byte)(value << shift);
  196356. }
  196357. if (shift == s_end)
  196358. {
  196359. shift = s_start;
  196360. sp++;
  196361. dp++;
  196362. }
  196363. else
  196364. shift += s_inc;
  196365. if (m == 1)
  196366. m = 0x80;
  196367. else
  196368. m >>= 1;
  196369. }
  196370. break;
  196371. }
  196372. default:
  196373. {
  196374. png_bytep sp = png_ptr->row_buf + 1;
  196375. png_bytep dp = row;
  196376. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  196377. png_uint_32 i;
  196378. png_uint_32 row_width = png_ptr->width;
  196379. png_byte m = 0x80;
  196380. for (i = 0; i < row_width; i++)
  196381. {
  196382. if (m & mask)
  196383. {
  196384. png_memcpy(dp, sp, pixel_bytes);
  196385. }
  196386. sp += pixel_bytes;
  196387. dp += pixel_bytes;
  196388. if (m == 1)
  196389. m = 0x80;
  196390. else
  196391. m >>= 1;
  196392. }
  196393. break;
  196394. }
  196395. }
  196396. }
  196397. }
  196398. #ifdef PNG_READ_INTERLACING_SUPPORTED
  196399. /* OLD pre-1.0.9 interface:
  196400. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  196401. png_uint_32 transformations)
  196402. */
  196403. void /* PRIVATE */
  196404. png_do_read_interlace(png_structp png_ptr)
  196405. {
  196406. png_row_infop row_info = &(png_ptr->row_info);
  196407. png_bytep row = png_ptr->row_buf + 1;
  196408. int pass = png_ptr->pass;
  196409. png_uint_32 transformations = png_ptr->transformations;
  196410. #ifdef PNG_USE_LOCAL_ARRAYS
  196411. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196412. /* offset to next interlace block */
  196413. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196414. #endif
  196415. png_debug(1,"in png_do_read_interlace\n");
  196416. if (row != NULL && row_info != NULL)
  196417. {
  196418. png_uint_32 final_width;
  196419. final_width = row_info->width * png_pass_inc[pass];
  196420. switch (row_info->pixel_depth)
  196421. {
  196422. case 1:
  196423. {
  196424. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  196425. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  196426. int sshift, dshift;
  196427. int s_start, s_end, s_inc;
  196428. int jstop = png_pass_inc[pass];
  196429. png_byte v;
  196430. png_uint_32 i;
  196431. int j;
  196432. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196433. if (transformations & PNG_PACKSWAP)
  196434. {
  196435. sshift = (int)((row_info->width + 7) & 0x07);
  196436. dshift = (int)((final_width + 7) & 0x07);
  196437. s_start = 7;
  196438. s_end = 0;
  196439. s_inc = -1;
  196440. }
  196441. else
  196442. #endif
  196443. {
  196444. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  196445. dshift = 7 - (int)((final_width + 7) & 0x07);
  196446. s_start = 0;
  196447. s_end = 7;
  196448. s_inc = 1;
  196449. }
  196450. for (i = 0; i < row_info->width; i++)
  196451. {
  196452. v = (png_byte)((*sp >> sshift) & 0x01);
  196453. for (j = 0; j < jstop; j++)
  196454. {
  196455. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  196456. *dp |= (png_byte)(v << dshift);
  196457. if (dshift == s_end)
  196458. {
  196459. dshift = s_start;
  196460. dp--;
  196461. }
  196462. else
  196463. dshift += s_inc;
  196464. }
  196465. if (sshift == s_end)
  196466. {
  196467. sshift = s_start;
  196468. sp--;
  196469. }
  196470. else
  196471. sshift += s_inc;
  196472. }
  196473. break;
  196474. }
  196475. case 2:
  196476. {
  196477. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  196478. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  196479. int sshift, dshift;
  196480. int s_start, s_end, s_inc;
  196481. int jstop = png_pass_inc[pass];
  196482. png_uint_32 i;
  196483. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196484. if (transformations & PNG_PACKSWAP)
  196485. {
  196486. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  196487. dshift = (int)(((final_width + 3) & 0x03) << 1);
  196488. s_start = 6;
  196489. s_end = 0;
  196490. s_inc = -2;
  196491. }
  196492. else
  196493. #endif
  196494. {
  196495. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  196496. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  196497. s_start = 0;
  196498. s_end = 6;
  196499. s_inc = 2;
  196500. }
  196501. for (i = 0; i < row_info->width; i++)
  196502. {
  196503. png_byte v;
  196504. int j;
  196505. v = (png_byte)((*sp >> sshift) & 0x03);
  196506. for (j = 0; j < jstop; j++)
  196507. {
  196508. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  196509. *dp |= (png_byte)(v << dshift);
  196510. if (dshift == s_end)
  196511. {
  196512. dshift = s_start;
  196513. dp--;
  196514. }
  196515. else
  196516. dshift += s_inc;
  196517. }
  196518. if (sshift == s_end)
  196519. {
  196520. sshift = s_start;
  196521. sp--;
  196522. }
  196523. else
  196524. sshift += s_inc;
  196525. }
  196526. break;
  196527. }
  196528. case 4:
  196529. {
  196530. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  196531. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  196532. int sshift, dshift;
  196533. int s_start, s_end, s_inc;
  196534. png_uint_32 i;
  196535. int jstop = png_pass_inc[pass];
  196536. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196537. if (transformations & PNG_PACKSWAP)
  196538. {
  196539. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  196540. dshift = (int)(((final_width + 1) & 0x01) << 2);
  196541. s_start = 4;
  196542. s_end = 0;
  196543. s_inc = -4;
  196544. }
  196545. else
  196546. #endif
  196547. {
  196548. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  196549. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  196550. s_start = 0;
  196551. s_end = 4;
  196552. s_inc = 4;
  196553. }
  196554. for (i = 0; i < row_info->width; i++)
  196555. {
  196556. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  196557. int j;
  196558. for (j = 0; j < jstop; j++)
  196559. {
  196560. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  196561. *dp |= (png_byte)(v << dshift);
  196562. if (dshift == s_end)
  196563. {
  196564. dshift = s_start;
  196565. dp--;
  196566. }
  196567. else
  196568. dshift += s_inc;
  196569. }
  196570. if (sshift == s_end)
  196571. {
  196572. sshift = s_start;
  196573. sp--;
  196574. }
  196575. else
  196576. sshift += s_inc;
  196577. }
  196578. break;
  196579. }
  196580. default:
  196581. {
  196582. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  196583. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  196584. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  196585. int jstop = png_pass_inc[pass];
  196586. png_uint_32 i;
  196587. for (i = 0; i < row_info->width; i++)
  196588. {
  196589. png_byte v[8];
  196590. int j;
  196591. png_memcpy(v, sp, pixel_bytes);
  196592. for (j = 0; j < jstop; j++)
  196593. {
  196594. png_memcpy(dp, v, pixel_bytes);
  196595. dp -= pixel_bytes;
  196596. }
  196597. sp -= pixel_bytes;
  196598. }
  196599. break;
  196600. }
  196601. }
  196602. row_info->width = final_width;
  196603. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  196604. }
  196605. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  196606. transformations = transformations; /* silence compiler warning */
  196607. #endif
  196608. }
  196609. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  196610. void /* PRIVATE */
  196611. png_read_filter_row(png_structp, png_row_infop row_info, png_bytep row,
  196612. png_bytep prev_row, int filter)
  196613. {
  196614. png_debug(1, "in png_read_filter_row\n");
  196615. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  196616. switch (filter)
  196617. {
  196618. case PNG_FILTER_VALUE_NONE:
  196619. break;
  196620. case PNG_FILTER_VALUE_SUB:
  196621. {
  196622. png_uint_32 i;
  196623. png_uint_32 istop = row_info->rowbytes;
  196624. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196625. png_bytep rp = row + bpp;
  196626. png_bytep lp = row;
  196627. for (i = bpp; i < istop; i++)
  196628. {
  196629. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  196630. rp++;
  196631. }
  196632. break;
  196633. }
  196634. case PNG_FILTER_VALUE_UP:
  196635. {
  196636. png_uint_32 i;
  196637. png_uint_32 istop = row_info->rowbytes;
  196638. png_bytep rp = row;
  196639. png_bytep pp = prev_row;
  196640. for (i = 0; i < istop; i++)
  196641. {
  196642. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196643. rp++;
  196644. }
  196645. break;
  196646. }
  196647. case PNG_FILTER_VALUE_AVG:
  196648. {
  196649. png_uint_32 i;
  196650. png_bytep rp = row;
  196651. png_bytep pp = prev_row;
  196652. png_bytep lp = row;
  196653. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196654. png_uint_32 istop = row_info->rowbytes - bpp;
  196655. for (i = 0; i < bpp; i++)
  196656. {
  196657. *rp = (png_byte)(((int)(*rp) +
  196658. ((int)(*pp++) / 2 )) & 0xff);
  196659. rp++;
  196660. }
  196661. for (i = 0; i < istop; i++)
  196662. {
  196663. *rp = (png_byte)(((int)(*rp) +
  196664. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  196665. rp++;
  196666. }
  196667. break;
  196668. }
  196669. case PNG_FILTER_VALUE_PAETH:
  196670. {
  196671. png_uint_32 i;
  196672. png_bytep rp = row;
  196673. png_bytep pp = prev_row;
  196674. png_bytep lp = row;
  196675. png_bytep cp = prev_row;
  196676. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  196677. png_uint_32 istop=row_info->rowbytes - bpp;
  196678. for (i = 0; i < bpp; i++)
  196679. {
  196680. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  196681. rp++;
  196682. }
  196683. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  196684. {
  196685. int a, b, c, pa, pb, pc, p;
  196686. a = *lp++;
  196687. b = *pp++;
  196688. c = *cp++;
  196689. p = b - c;
  196690. pc = a - c;
  196691. #ifdef PNG_USE_ABS
  196692. pa = abs(p);
  196693. pb = abs(pc);
  196694. pc = abs(p + pc);
  196695. #else
  196696. pa = p < 0 ? -p : p;
  196697. pb = pc < 0 ? -pc : pc;
  196698. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  196699. #endif
  196700. /*
  196701. if (pa <= pb && pa <= pc)
  196702. p = a;
  196703. else if (pb <= pc)
  196704. p = b;
  196705. else
  196706. p = c;
  196707. */
  196708. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  196709. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  196710. rp++;
  196711. }
  196712. break;
  196713. }
  196714. default:
  196715. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  196716. *row=0;
  196717. break;
  196718. }
  196719. }
  196720. void /* PRIVATE */
  196721. png_read_finish_row(png_structp png_ptr)
  196722. {
  196723. #ifdef PNG_USE_LOCAL_ARRAYS
  196724. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196725. /* start of interlace block */
  196726. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196727. /* offset to next interlace block */
  196728. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196729. /* start of interlace block in the y direction */
  196730. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196731. /* offset to next interlace block in the y direction */
  196732. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196733. #endif
  196734. png_debug(1, "in png_read_finish_row\n");
  196735. png_ptr->row_number++;
  196736. if (png_ptr->row_number < png_ptr->num_rows)
  196737. return;
  196738. if (png_ptr->interlaced)
  196739. {
  196740. png_ptr->row_number = 0;
  196741. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  196742. png_ptr->rowbytes + 1);
  196743. do
  196744. {
  196745. png_ptr->pass++;
  196746. if (png_ptr->pass >= 7)
  196747. break;
  196748. png_ptr->iwidth = (png_ptr->width +
  196749. png_pass_inc[png_ptr->pass] - 1 -
  196750. png_pass_start[png_ptr->pass]) /
  196751. png_pass_inc[png_ptr->pass];
  196752. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  196753. png_ptr->iwidth) + 1;
  196754. if (!(png_ptr->transformations & PNG_INTERLACE))
  196755. {
  196756. png_ptr->num_rows = (png_ptr->height +
  196757. png_pass_yinc[png_ptr->pass] - 1 -
  196758. png_pass_ystart[png_ptr->pass]) /
  196759. png_pass_yinc[png_ptr->pass];
  196760. if (!(png_ptr->num_rows))
  196761. continue;
  196762. }
  196763. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  196764. break;
  196765. } while (png_ptr->iwidth == 0);
  196766. if (png_ptr->pass < 7)
  196767. return;
  196768. }
  196769. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  196770. {
  196771. #ifdef PNG_USE_LOCAL_ARRAYS
  196772. PNG_CONST PNG_IDAT;
  196773. #endif
  196774. char extra;
  196775. int ret;
  196776. png_ptr->zstream.next_out = (Bytef *)&extra;
  196777. png_ptr->zstream.avail_out = (uInt)1;
  196778. for(;;)
  196779. {
  196780. if (!(png_ptr->zstream.avail_in))
  196781. {
  196782. while (!png_ptr->idat_size)
  196783. {
  196784. png_byte chunk_length[4];
  196785. png_crc_finish(png_ptr, 0);
  196786. png_read_data(png_ptr, chunk_length, 4);
  196787. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  196788. png_reset_crc(png_ptr);
  196789. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  196790. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  196791. png_error(png_ptr, "Not enough image data");
  196792. }
  196793. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  196794. png_ptr->zstream.next_in = png_ptr->zbuf;
  196795. if (png_ptr->zbuf_size > png_ptr->idat_size)
  196796. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  196797. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  196798. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  196799. }
  196800. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  196801. if (ret == Z_STREAM_END)
  196802. {
  196803. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  196804. png_ptr->idat_size)
  196805. png_warning(png_ptr, "Extra compressed data");
  196806. png_ptr->mode |= PNG_AFTER_IDAT;
  196807. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196808. break;
  196809. }
  196810. if (ret != Z_OK)
  196811. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  196812. "Decompression Error");
  196813. if (!(png_ptr->zstream.avail_out))
  196814. {
  196815. png_warning(png_ptr, "Extra compressed data.");
  196816. png_ptr->mode |= PNG_AFTER_IDAT;
  196817. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  196818. break;
  196819. }
  196820. }
  196821. png_ptr->zstream.avail_out = 0;
  196822. }
  196823. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  196824. png_warning(png_ptr, "Extra compression data");
  196825. inflateReset(&png_ptr->zstream);
  196826. png_ptr->mode |= PNG_AFTER_IDAT;
  196827. }
  196828. void /* PRIVATE */
  196829. png_read_start_row(png_structp png_ptr)
  196830. {
  196831. #ifdef PNG_USE_LOCAL_ARRAYS
  196832. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  196833. /* start of interlace block */
  196834. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  196835. /* offset to next interlace block */
  196836. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  196837. /* start of interlace block in the y direction */
  196838. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  196839. /* offset to next interlace block in the y direction */
  196840. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  196841. #endif
  196842. int max_pixel_depth;
  196843. png_uint_32 row_bytes;
  196844. png_debug(1, "in png_read_start_row\n");
  196845. png_ptr->zstream.avail_in = 0;
  196846. png_init_read_transformations(png_ptr);
  196847. if (png_ptr->interlaced)
  196848. {
  196849. if (!(png_ptr->transformations & PNG_INTERLACE))
  196850. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  196851. png_pass_ystart[0]) / png_pass_yinc[0];
  196852. else
  196853. png_ptr->num_rows = png_ptr->height;
  196854. png_ptr->iwidth = (png_ptr->width +
  196855. png_pass_inc[png_ptr->pass] - 1 -
  196856. png_pass_start[png_ptr->pass]) /
  196857. png_pass_inc[png_ptr->pass];
  196858. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  196859. png_ptr->irowbytes = (png_size_t)row_bytes;
  196860. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  196861. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  196862. }
  196863. else
  196864. {
  196865. png_ptr->num_rows = png_ptr->height;
  196866. png_ptr->iwidth = png_ptr->width;
  196867. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  196868. }
  196869. max_pixel_depth = png_ptr->pixel_depth;
  196870. #if defined(PNG_READ_PACK_SUPPORTED)
  196871. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  196872. max_pixel_depth = 8;
  196873. #endif
  196874. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196875. if (png_ptr->transformations & PNG_EXPAND)
  196876. {
  196877. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196878. {
  196879. if (png_ptr->num_trans)
  196880. max_pixel_depth = 32;
  196881. else
  196882. max_pixel_depth = 24;
  196883. }
  196884. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196885. {
  196886. if (max_pixel_depth < 8)
  196887. max_pixel_depth = 8;
  196888. if (png_ptr->num_trans)
  196889. max_pixel_depth *= 2;
  196890. }
  196891. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196892. {
  196893. if (png_ptr->num_trans)
  196894. {
  196895. max_pixel_depth *= 4;
  196896. max_pixel_depth /= 3;
  196897. }
  196898. }
  196899. }
  196900. #endif
  196901. #if defined(PNG_READ_FILLER_SUPPORTED)
  196902. if (png_ptr->transformations & (PNG_FILLER))
  196903. {
  196904. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196905. max_pixel_depth = 32;
  196906. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196907. {
  196908. if (max_pixel_depth <= 8)
  196909. max_pixel_depth = 16;
  196910. else
  196911. max_pixel_depth = 32;
  196912. }
  196913. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196914. {
  196915. if (max_pixel_depth <= 32)
  196916. max_pixel_depth = 32;
  196917. else
  196918. max_pixel_depth = 64;
  196919. }
  196920. }
  196921. #endif
  196922. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  196923. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  196924. {
  196925. if (
  196926. #if defined(PNG_READ_EXPAND_SUPPORTED)
  196927. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  196928. #endif
  196929. #if defined(PNG_READ_FILLER_SUPPORTED)
  196930. (png_ptr->transformations & (PNG_FILLER)) ||
  196931. #endif
  196932. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  196933. {
  196934. if (max_pixel_depth <= 16)
  196935. max_pixel_depth = 32;
  196936. else
  196937. max_pixel_depth = 64;
  196938. }
  196939. else
  196940. {
  196941. if (max_pixel_depth <= 8)
  196942. {
  196943. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196944. max_pixel_depth = 32;
  196945. else
  196946. max_pixel_depth = 24;
  196947. }
  196948. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  196949. max_pixel_depth = 64;
  196950. else
  196951. max_pixel_depth = 48;
  196952. }
  196953. }
  196954. #endif
  196955. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  196956. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  196957. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  196958. {
  196959. int user_pixel_depth=png_ptr->user_transform_depth*
  196960. png_ptr->user_transform_channels;
  196961. if(user_pixel_depth > max_pixel_depth)
  196962. max_pixel_depth=user_pixel_depth;
  196963. }
  196964. #endif
  196965. /* align the width on the next larger 8 pixels. Mainly used
  196966. for interlacing */
  196967. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  196968. /* calculate the maximum bytes needed, adding a byte and a pixel
  196969. for safety's sake */
  196970. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  196971. 1 + ((max_pixel_depth + 7) >> 3);
  196972. #ifdef PNG_MAX_MALLOC_64K
  196973. if (row_bytes > (png_uint_32)65536L)
  196974. png_error(png_ptr, "This image requires a row greater than 64KB");
  196975. #endif
  196976. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  196977. png_ptr->row_buf = png_ptr->big_row_buf+32;
  196978. #ifdef PNG_MAX_MALLOC_64K
  196979. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  196980. png_error(png_ptr, "This image requires a row greater than 64KB");
  196981. #endif
  196982. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  196983. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  196984. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  196985. png_ptr->rowbytes + 1));
  196986. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  196987. png_debug1(3, "width = %lu,\n", png_ptr->width);
  196988. png_debug1(3, "height = %lu,\n", png_ptr->height);
  196989. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  196990. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  196991. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  196992. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  196993. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  196994. }
  196995. #endif /* PNG_READ_SUPPORTED */
  196996. /*** End of inlined file: pngrutil.c ***/
  196997. /*** Start of inlined file: pngset.c ***/
  196998. /* pngset.c - storage of image information into info struct
  196999. *
  197000. * Last changed in libpng 1.2.21 [October 4, 2007]
  197001. * For conditions of distribution and use, see copyright notice in png.h
  197002. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197003. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197004. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197005. *
  197006. * The functions here are used during reads to store data from the file
  197007. * into the info struct, and during writes to store application data
  197008. * into the info struct for writing into the file. This abstracts the
  197009. * info struct and allows us to change the structure in the future.
  197010. */
  197011. #define PNG_INTERNAL
  197012. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197013. #if defined(PNG_bKGD_SUPPORTED)
  197014. void PNGAPI
  197015. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  197016. {
  197017. png_debug1(1, "in %s storage function\n", "bKGD");
  197018. if (png_ptr == NULL || info_ptr == NULL)
  197019. return;
  197020. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  197021. info_ptr->valid |= PNG_INFO_bKGD;
  197022. }
  197023. #endif
  197024. #if defined(PNG_cHRM_SUPPORTED)
  197025. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197026. void PNGAPI
  197027. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  197028. double white_x, double white_y, double red_x, double red_y,
  197029. double green_x, double green_y, double blue_x, double blue_y)
  197030. {
  197031. png_debug1(1, "in %s storage function\n", "cHRM");
  197032. if (png_ptr == NULL || info_ptr == NULL)
  197033. return;
  197034. if (white_x < 0.0 || white_y < 0.0 ||
  197035. red_x < 0.0 || red_y < 0.0 ||
  197036. green_x < 0.0 || green_y < 0.0 ||
  197037. blue_x < 0.0 || blue_y < 0.0)
  197038. {
  197039. png_warning(png_ptr,
  197040. "Ignoring attempt to set negative chromaticity value");
  197041. return;
  197042. }
  197043. if (white_x > 21474.83 || white_y > 21474.83 ||
  197044. red_x > 21474.83 || red_y > 21474.83 ||
  197045. green_x > 21474.83 || green_y > 21474.83 ||
  197046. blue_x > 21474.83 || blue_y > 21474.83)
  197047. {
  197048. png_warning(png_ptr,
  197049. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197050. return;
  197051. }
  197052. info_ptr->x_white = (float)white_x;
  197053. info_ptr->y_white = (float)white_y;
  197054. info_ptr->x_red = (float)red_x;
  197055. info_ptr->y_red = (float)red_y;
  197056. info_ptr->x_green = (float)green_x;
  197057. info_ptr->y_green = (float)green_y;
  197058. info_ptr->x_blue = (float)blue_x;
  197059. info_ptr->y_blue = (float)blue_y;
  197060. #ifdef PNG_FIXED_POINT_SUPPORTED
  197061. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197062. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197063. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197064. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197065. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197066. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197067. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197068. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197069. #endif
  197070. info_ptr->valid |= PNG_INFO_cHRM;
  197071. }
  197072. #endif
  197073. #ifdef PNG_FIXED_POINT_SUPPORTED
  197074. void PNGAPI
  197075. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197076. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197077. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197078. png_fixed_point blue_x, png_fixed_point blue_y)
  197079. {
  197080. png_debug1(1, "in %s storage function\n", "cHRM");
  197081. if (png_ptr == NULL || info_ptr == NULL)
  197082. return;
  197083. if (white_x < 0 || white_y < 0 ||
  197084. red_x < 0 || red_y < 0 ||
  197085. green_x < 0 || green_y < 0 ||
  197086. blue_x < 0 || blue_y < 0)
  197087. {
  197088. png_warning(png_ptr,
  197089. "Ignoring attempt to set negative chromaticity value");
  197090. return;
  197091. }
  197092. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197093. if (white_x > (double) PNG_UINT_31_MAX ||
  197094. white_y > (double) PNG_UINT_31_MAX ||
  197095. red_x > (double) PNG_UINT_31_MAX ||
  197096. red_y > (double) PNG_UINT_31_MAX ||
  197097. green_x > (double) PNG_UINT_31_MAX ||
  197098. green_y > (double) PNG_UINT_31_MAX ||
  197099. blue_x > (double) PNG_UINT_31_MAX ||
  197100. blue_y > (double) PNG_UINT_31_MAX)
  197101. #else
  197102. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197103. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197104. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197105. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197106. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197107. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197108. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197109. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197110. #endif
  197111. {
  197112. png_warning(png_ptr,
  197113. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197114. return;
  197115. }
  197116. info_ptr->int_x_white = white_x;
  197117. info_ptr->int_y_white = white_y;
  197118. info_ptr->int_x_red = red_x;
  197119. info_ptr->int_y_red = red_y;
  197120. info_ptr->int_x_green = green_x;
  197121. info_ptr->int_y_green = green_y;
  197122. info_ptr->int_x_blue = blue_x;
  197123. info_ptr->int_y_blue = blue_y;
  197124. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197125. info_ptr->x_white = (float)(white_x/100000.);
  197126. info_ptr->y_white = (float)(white_y/100000.);
  197127. info_ptr->x_red = (float)( red_x/100000.);
  197128. info_ptr->y_red = (float)( red_y/100000.);
  197129. info_ptr->x_green = (float)(green_x/100000.);
  197130. info_ptr->y_green = (float)(green_y/100000.);
  197131. info_ptr->x_blue = (float)( blue_x/100000.);
  197132. info_ptr->y_blue = (float)( blue_y/100000.);
  197133. #endif
  197134. info_ptr->valid |= PNG_INFO_cHRM;
  197135. }
  197136. #endif
  197137. #endif
  197138. #if defined(PNG_gAMA_SUPPORTED)
  197139. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197140. void PNGAPI
  197141. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197142. {
  197143. double gamma;
  197144. png_debug1(1, "in %s storage function\n", "gAMA");
  197145. if (png_ptr == NULL || info_ptr == NULL)
  197146. return;
  197147. /* Check for overflow */
  197148. if (file_gamma > 21474.83)
  197149. {
  197150. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197151. gamma=21474.83;
  197152. }
  197153. else
  197154. gamma=file_gamma;
  197155. info_ptr->gamma = (float)gamma;
  197156. #ifdef PNG_FIXED_POINT_SUPPORTED
  197157. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197158. #endif
  197159. info_ptr->valid |= PNG_INFO_gAMA;
  197160. if(gamma == 0.0)
  197161. png_warning(png_ptr, "Setting gamma=0");
  197162. }
  197163. #endif
  197164. void PNGAPI
  197165. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197166. int_gamma)
  197167. {
  197168. png_fixed_point gamma;
  197169. png_debug1(1, "in %s storage function\n", "gAMA");
  197170. if (png_ptr == NULL || info_ptr == NULL)
  197171. return;
  197172. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197173. {
  197174. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197175. gamma=PNG_UINT_31_MAX;
  197176. }
  197177. else
  197178. {
  197179. if (int_gamma < 0)
  197180. {
  197181. png_warning(png_ptr, "Setting negative gamma to zero");
  197182. gamma=0;
  197183. }
  197184. else
  197185. gamma=int_gamma;
  197186. }
  197187. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197188. info_ptr->gamma = (float)(gamma/100000.);
  197189. #endif
  197190. #ifdef PNG_FIXED_POINT_SUPPORTED
  197191. info_ptr->int_gamma = gamma;
  197192. #endif
  197193. info_ptr->valid |= PNG_INFO_gAMA;
  197194. if(gamma == 0)
  197195. png_warning(png_ptr, "Setting gamma=0");
  197196. }
  197197. #endif
  197198. #if defined(PNG_hIST_SUPPORTED)
  197199. void PNGAPI
  197200. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197201. {
  197202. int i;
  197203. png_debug1(1, "in %s storage function\n", "hIST");
  197204. if (png_ptr == NULL || info_ptr == NULL)
  197205. return;
  197206. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197207. > PNG_MAX_PALETTE_LENGTH)
  197208. {
  197209. png_warning(png_ptr,
  197210. "Invalid palette size, hIST allocation skipped.");
  197211. return;
  197212. }
  197213. #ifdef PNG_FREE_ME_SUPPORTED
  197214. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197215. #endif
  197216. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197217. 1.2.1 */
  197218. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197219. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197220. if (png_ptr->hist == NULL)
  197221. {
  197222. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197223. return;
  197224. }
  197225. for (i = 0; i < info_ptr->num_palette; i++)
  197226. png_ptr->hist[i] = hist[i];
  197227. info_ptr->hist = png_ptr->hist;
  197228. info_ptr->valid |= PNG_INFO_hIST;
  197229. #ifdef PNG_FREE_ME_SUPPORTED
  197230. info_ptr->free_me |= PNG_FREE_HIST;
  197231. #else
  197232. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197233. #endif
  197234. }
  197235. #endif
  197236. void PNGAPI
  197237. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197238. png_uint_32 width, png_uint_32 height, int bit_depth,
  197239. int color_type, int interlace_type, int compression_type,
  197240. int filter_type)
  197241. {
  197242. png_debug1(1, "in %s storage function\n", "IHDR");
  197243. if (png_ptr == NULL || info_ptr == NULL)
  197244. return;
  197245. /* check for width and height valid values */
  197246. if (width == 0 || height == 0)
  197247. png_error(png_ptr, "Image width or height is zero in IHDR");
  197248. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197249. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197250. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197251. #else
  197252. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197253. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197254. #endif
  197255. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197256. png_error(png_ptr, "Invalid image size in IHDR");
  197257. if ( width > (PNG_UINT_32_MAX
  197258. >> 3) /* 8-byte RGBA pixels */
  197259. - 64 /* bigrowbuf hack */
  197260. - 1 /* filter byte */
  197261. - 7*8 /* rounding of width to multiple of 8 pixels */
  197262. - 8) /* extra max_pixel_depth pad */
  197263. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197264. /* check other values */
  197265. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197266. bit_depth != 8 && bit_depth != 16)
  197267. png_error(png_ptr, "Invalid bit depth in IHDR");
  197268. if (color_type < 0 || color_type == 1 ||
  197269. color_type == 5 || color_type > 6)
  197270. png_error(png_ptr, "Invalid color type in IHDR");
  197271. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197272. ((color_type == PNG_COLOR_TYPE_RGB ||
  197273. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197274. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197275. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197276. if (interlace_type >= PNG_INTERLACE_LAST)
  197277. png_error(png_ptr, "Unknown interlace method in IHDR");
  197278. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197279. png_error(png_ptr, "Unknown compression method in IHDR");
  197280. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197281. /* Accept filter_method 64 (intrapixel differencing) only if
  197282. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  197283. * 2. Libpng did not read a PNG signature (this filter_method is only
  197284. * used in PNG datastreams that are embedded in MNG datastreams) and
  197285. * 3. The application called png_permit_mng_features with a mask that
  197286. * included PNG_FLAG_MNG_FILTER_64 and
  197287. * 4. The filter_method is 64 and
  197288. * 5. The color_type is RGB or RGBA
  197289. */
  197290. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  197291. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  197292. if(filter_type != PNG_FILTER_TYPE_BASE)
  197293. {
  197294. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  197295. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  197296. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  197297. (color_type == PNG_COLOR_TYPE_RGB ||
  197298. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  197299. png_error(png_ptr, "Unknown filter method in IHDR");
  197300. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  197301. png_warning(png_ptr, "Invalid filter method in IHDR");
  197302. }
  197303. #else
  197304. if(filter_type != PNG_FILTER_TYPE_BASE)
  197305. png_error(png_ptr, "Unknown filter method in IHDR");
  197306. #endif
  197307. info_ptr->width = width;
  197308. info_ptr->height = height;
  197309. info_ptr->bit_depth = (png_byte)bit_depth;
  197310. info_ptr->color_type =(png_byte) color_type;
  197311. info_ptr->compression_type = (png_byte)compression_type;
  197312. info_ptr->filter_type = (png_byte)filter_type;
  197313. info_ptr->interlace_type = (png_byte)interlace_type;
  197314. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197315. info_ptr->channels = 1;
  197316. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  197317. info_ptr->channels = 3;
  197318. else
  197319. info_ptr->channels = 1;
  197320. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  197321. info_ptr->channels++;
  197322. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  197323. /* check for potential overflow */
  197324. if (width > (PNG_UINT_32_MAX
  197325. >> 3) /* 8-byte RGBA pixels */
  197326. - 64 /* bigrowbuf hack */
  197327. - 1 /* filter byte */
  197328. - 7*8 /* rounding of width to multiple of 8 pixels */
  197329. - 8) /* extra max_pixel_depth pad */
  197330. info_ptr->rowbytes = (png_size_t)0;
  197331. else
  197332. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  197333. }
  197334. #if defined(PNG_oFFs_SUPPORTED)
  197335. void PNGAPI
  197336. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  197337. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  197338. {
  197339. png_debug1(1, "in %s storage function\n", "oFFs");
  197340. if (png_ptr == NULL || info_ptr == NULL)
  197341. return;
  197342. info_ptr->x_offset = offset_x;
  197343. info_ptr->y_offset = offset_y;
  197344. info_ptr->offset_unit_type = (png_byte)unit_type;
  197345. info_ptr->valid |= PNG_INFO_oFFs;
  197346. }
  197347. #endif
  197348. #if defined(PNG_pCAL_SUPPORTED)
  197349. void PNGAPI
  197350. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  197351. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  197352. png_charp units, png_charpp params)
  197353. {
  197354. png_uint_32 length;
  197355. int i;
  197356. png_debug1(1, "in %s storage function\n", "pCAL");
  197357. if (png_ptr == NULL || info_ptr == NULL)
  197358. return;
  197359. length = png_strlen(purpose) + 1;
  197360. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  197361. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  197362. if (info_ptr->pcal_purpose == NULL)
  197363. {
  197364. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  197365. return;
  197366. }
  197367. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  197368. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  197369. info_ptr->pcal_X0 = X0;
  197370. info_ptr->pcal_X1 = X1;
  197371. info_ptr->pcal_type = (png_byte)type;
  197372. info_ptr->pcal_nparams = (png_byte)nparams;
  197373. length = png_strlen(units) + 1;
  197374. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  197375. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  197376. if (info_ptr->pcal_units == NULL)
  197377. {
  197378. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  197379. return;
  197380. }
  197381. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  197382. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  197383. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  197384. if (info_ptr->pcal_params == NULL)
  197385. {
  197386. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  197387. return;
  197388. }
  197389. info_ptr->pcal_params[nparams] = NULL;
  197390. for (i = 0; i < nparams; i++)
  197391. {
  197392. length = png_strlen(params[i]) + 1;
  197393. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  197394. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  197395. if (info_ptr->pcal_params[i] == NULL)
  197396. {
  197397. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  197398. return;
  197399. }
  197400. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  197401. }
  197402. info_ptr->valid |= PNG_INFO_pCAL;
  197403. #ifdef PNG_FREE_ME_SUPPORTED
  197404. info_ptr->free_me |= PNG_FREE_PCAL;
  197405. #endif
  197406. }
  197407. #endif
  197408. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  197409. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197410. void PNGAPI
  197411. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  197412. int unit, double width, double height)
  197413. {
  197414. png_debug1(1, "in %s storage function\n", "sCAL");
  197415. if (png_ptr == NULL || info_ptr == NULL)
  197416. return;
  197417. info_ptr->scal_unit = (png_byte)unit;
  197418. info_ptr->scal_pixel_width = width;
  197419. info_ptr->scal_pixel_height = height;
  197420. info_ptr->valid |= PNG_INFO_sCAL;
  197421. }
  197422. #else
  197423. #ifdef PNG_FIXED_POINT_SUPPORTED
  197424. void PNGAPI
  197425. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  197426. int unit, png_charp swidth, png_charp sheight)
  197427. {
  197428. png_uint_32 length;
  197429. png_debug1(1, "in %s storage function\n", "sCAL");
  197430. if (png_ptr == NULL || info_ptr == NULL)
  197431. return;
  197432. info_ptr->scal_unit = (png_byte)unit;
  197433. length = png_strlen(swidth) + 1;
  197434. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197435. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  197436. if (info_ptr->scal_s_width == NULL)
  197437. {
  197438. png_warning(png_ptr,
  197439. "Memory allocation failed while processing sCAL.");
  197440. }
  197441. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  197442. length = png_strlen(sheight) + 1;
  197443. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  197444. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  197445. if (info_ptr->scal_s_height == NULL)
  197446. {
  197447. png_free (png_ptr, info_ptr->scal_s_width);
  197448. png_warning(png_ptr,
  197449. "Memory allocation failed while processing sCAL.");
  197450. }
  197451. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  197452. info_ptr->valid |= PNG_INFO_sCAL;
  197453. #ifdef PNG_FREE_ME_SUPPORTED
  197454. info_ptr->free_me |= PNG_FREE_SCAL;
  197455. #endif
  197456. }
  197457. #endif
  197458. #endif
  197459. #endif
  197460. #if defined(PNG_pHYs_SUPPORTED)
  197461. void PNGAPI
  197462. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  197463. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  197464. {
  197465. png_debug1(1, "in %s storage function\n", "pHYs");
  197466. if (png_ptr == NULL || info_ptr == NULL)
  197467. return;
  197468. info_ptr->x_pixels_per_unit = res_x;
  197469. info_ptr->y_pixels_per_unit = res_y;
  197470. info_ptr->phys_unit_type = (png_byte)unit_type;
  197471. info_ptr->valid |= PNG_INFO_pHYs;
  197472. }
  197473. #endif
  197474. void PNGAPI
  197475. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  197476. png_colorp palette, int num_palette)
  197477. {
  197478. png_debug1(1, "in %s storage function\n", "PLTE");
  197479. if (png_ptr == NULL || info_ptr == NULL)
  197480. return;
  197481. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  197482. {
  197483. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197484. png_error(png_ptr, "Invalid palette length");
  197485. else
  197486. {
  197487. png_warning(png_ptr, "Invalid palette length");
  197488. return;
  197489. }
  197490. }
  197491. /*
  197492. * It may not actually be necessary to set png_ptr->palette here;
  197493. * we do it for backward compatibility with the way the png_handle_tRNS
  197494. * function used to do the allocation.
  197495. */
  197496. #ifdef PNG_FREE_ME_SUPPORTED
  197497. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  197498. #endif
  197499. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  197500. of num_palette entries,
  197501. in case of an invalid PNG file that has too-large sample values. */
  197502. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  197503. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  197504. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  197505. png_sizeof(png_color));
  197506. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  197507. info_ptr->palette = png_ptr->palette;
  197508. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  197509. #ifdef PNG_FREE_ME_SUPPORTED
  197510. info_ptr->free_me |= PNG_FREE_PLTE;
  197511. #else
  197512. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  197513. #endif
  197514. info_ptr->valid |= PNG_INFO_PLTE;
  197515. }
  197516. #if defined(PNG_sBIT_SUPPORTED)
  197517. void PNGAPI
  197518. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  197519. png_color_8p sig_bit)
  197520. {
  197521. png_debug1(1, "in %s storage function\n", "sBIT");
  197522. if (png_ptr == NULL || info_ptr == NULL)
  197523. return;
  197524. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  197525. info_ptr->valid |= PNG_INFO_sBIT;
  197526. }
  197527. #endif
  197528. #if defined(PNG_sRGB_SUPPORTED)
  197529. void PNGAPI
  197530. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  197531. {
  197532. png_debug1(1, "in %s storage function\n", "sRGB");
  197533. if (png_ptr == NULL || info_ptr == NULL)
  197534. return;
  197535. info_ptr->srgb_intent = (png_byte)intent;
  197536. info_ptr->valid |= PNG_INFO_sRGB;
  197537. }
  197538. void PNGAPI
  197539. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  197540. int intent)
  197541. {
  197542. #if defined(PNG_gAMA_SUPPORTED)
  197543. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197544. float file_gamma;
  197545. #endif
  197546. #ifdef PNG_FIXED_POINT_SUPPORTED
  197547. png_fixed_point int_file_gamma;
  197548. #endif
  197549. #endif
  197550. #if defined(PNG_cHRM_SUPPORTED)
  197551. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197552. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  197553. #endif
  197554. #ifdef PNG_FIXED_POINT_SUPPORTED
  197555. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  197556. int_green_y, int_blue_x, int_blue_y;
  197557. #endif
  197558. #endif
  197559. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  197560. if (png_ptr == NULL || info_ptr == NULL)
  197561. return;
  197562. png_set_sRGB(png_ptr, info_ptr, intent);
  197563. #if defined(PNG_gAMA_SUPPORTED)
  197564. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197565. file_gamma = (float).45455;
  197566. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  197567. #endif
  197568. #ifdef PNG_FIXED_POINT_SUPPORTED
  197569. int_file_gamma = 45455L;
  197570. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  197571. #endif
  197572. #endif
  197573. #if defined(PNG_cHRM_SUPPORTED)
  197574. #ifdef PNG_FIXED_POINT_SUPPORTED
  197575. int_white_x = 31270L;
  197576. int_white_y = 32900L;
  197577. int_red_x = 64000L;
  197578. int_red_y = 33000L;
  197579. int_green_x = 30000L;
  197580. int_green_y = 60000L;
  197581. int_blue_x = 15000L;
  197582. int_blue_y = 6000L;
  197583. png_set_cHRM_fixed(png_ptr, info_ptr,
  197584. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  197585. int_blue_x, int_blue_y);
  197586. #endif
  197587. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197588. white_x = (float).3127;
  197589. white_y = (float).3290;
  197590. red_x = (float).64;
  197591. red_y = (float).33;
  197592. green_x = (float).30;
  197593. green_y = (float).60;
  197594. blue_x = (float).15;
  197595. blue_y = (float).06;
  197596. png_set_cHRM(png_ptr, info_ptr,
  197597. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  197598. #endif
  197599. #endif
  197600. }
  197601. #endif
  197602. #if defined(PNG_iCCP_SUPPORTED)
  197603. void PNGAPI
  197604. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  197605. png_charp name, int compression_type,
  197606. png_charp profile, png_uint_32 proflen)
  197607. {
  197608. png_charp new_iccp_name;
  197609. png_charp new_iccp_profile;
  197610. png_debug1(1, "in %s storage function\n", "iCCP");
  197611. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  197612. return;
  197613. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  197614. if (new_iccp_name == NULL)
  197615. {
  197616. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  197617. return;
  197618. }
  197619. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  197620. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  197621. if (new_iccp_profile == NULL)
  197622. {
  197623. png_free (png_ptr, new_iccp_name);
  197624. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  197625. return;
  197626. }
  197627. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  197628. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  197629. info_ptr->iccp_proflen = proflen;
  197630. info_ptr->iccp_name = new_iccp_name;
  197631. info_ptr->iccp_profile = new_iccp_profile;
  197632. /* Compression is always zero but is here so the API and info structure
  197633. * does not have to change if we introduce multiple compression types */
  197634. info_ptr->iccp_compression = (png_byte)compression_type;
  197635. #ifdef PNG_FREE_ME_SUPPORTED
  197636. info_ptr->free_me |= PNG_FREE_ICCP;
  197637. #endif
  197638. info_ptr->valid |= PNG_INFO_iCCP;
  197639. }
  197640. #endif
  197641. #if defined(PNG_TEXT_SUPPORTED)
  197642. void PNGAPI
  197643. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197644. int num_text)
  197645. {
  197646. int ret;
  197647. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  197648. if (ret)
  197649. png_error(png_ptr, "Insufficient memory to store text");
  197650. }
  197651. int /* PRIVATE */
  197652. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  197653. int num_text)
  197654. {
  197655. int i;
  197656. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  197657. "text" : (png_const_charp)png_ptr->chunk_name));
  197658. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  197659. return(0);
  197660. /* Make sure we have enough space in the "text" array in info_struct
  197661. * to hold all of the incoming text_ptr objects.
  197662. */
  197663. if (info_ptr->num_text + num_text > info_ptr->max_text)
  197664. {
  197665. if (info_ptr->text != NULL)
  197666. {
  197667. png_textp old_text;
  197668. int old_max;
  197669. old_max = info_ptr->max_text;
  197670. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  197671. old_text = info_ptr->text;
  197672. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197673. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197674. if (info_ptr->text == NULL)
  197675. {
  197676. png_free(png_ptr, old_text);
  197677. return(1);
  197678. }
  197679. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  197680. png_sizeof(png_text)));
  197681. png_free(png_ptr, old_text);
  197682. }
  197683. else
  197684. {
  197685. info_ptr->max_text = num_text + 8;
  197686. info_ptr->num_text = 0;
  197687. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  197688. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  197689. if (info_ptr->text == NULL)
  197690. return(1);
  197691. #ifdef PNG_FREE_ME_SUPPORTED
  197692. info_ptr->free_me |= PNG_FREE_TEXT;
  197693. #endif
  197694. }
  197695. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  197696. info_ptr->max_text);
  197697. }
  197698. for (i = 0; i < num_text; i++)
  197699. {
  197700. png_size_t text_length,key_len;
  197701. png_size_t lang_len,lang_key_len;
  197702. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  197703. if (text_ptr[i].key == NULL)
  197704. continue;
  197705. key_len = png_strlen(text_ptr[i].key);
  197706. if(text_ptr[i].compression <= 0)
  197707. {
  197708. lang_len = 0;
  197709. lang_key_len = 0;
  197710. }
  197711. else
  197712. #ifdef PNG_iTXt_SUPPORTED
  197713. {
  197714. /* set iTXt data */
  197715. if (text_ptr[i].lang != NULL)
  197716. lang_len = png_strlen(text_ptr[i].lang);
  197717. else
  197718. lang_len = 0;
  197719. if (text_ptr[i].lang_key != NULL)
  197720. lang_key_len = png_strlen(text_ptr[i].lang_key);
  197721. else
  197722. lang_key_len = 0;
  197723. }
  197724. #else
  197725. {
  197726. png_warning(png_ptr, "iTXt chunk not supported.");
  197727. continue;
  197728. }
  197729. #endif
  197730. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  197731. {
  197732. text_length = 0;
  197733. #ifdef PNG_iTXt_SUPPORTED
  197734. if(text_ptr[i].compression > 0)
  197735. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  197736. else
  197737. #endif
  197738. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  197739. }
  197740. else
  197741. {
  197742. text_length = png_strlen(text_ptr[i].text);
  197743. textp->compression = text_ptr[i].compression;
  197744. }
  197745. textp->key = (png_charp)png_malloc_warn(png_ptr,
  197746. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  197747. if (textp->key == NULL)
  197748. return(1);
  197749. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  197750. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  197751. (int)textp->key);
  197752. png_memcpy(textp->key, text_ptr[i].key,
  197753. (png_size_t)(key_len));
  197754. *(textp->key+key_len) = '\0';
  197755. #ifdef PNG_iTXt_SUPPORTED
  197756. if (text_ptr[i].compression > 0)
  197757. {
  197758. textp->lang=textp->key + key_len + 1;
  197759. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  197760. *(textp->lang+lang_len) = '\0';
  197761. textp->lang_key=textp->lang + lang_len + 1;
  197762. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  197763. *(textp->lang_key+lang_key_len) = '\0';
  197764. textp->text=textp->lang_key + lang_key_len + 1;
  197765. }
  197766. else
  197767. #endif
  197768. {
  197769. #ifdef PNG_iTXt_SUPPORTED
  197770. textp->lang=NULL;
  197771. textp->lang_key=NULL;
  197772. #endif
  197773. textp->text=textp->key + key_len + 1;
  197774. }
  197775. if(text_length)
  197776. png_memcpy(textp->text, text_ptr[i].text,
  197777. (png_size_t)(text_length));
  197778. *(textp->text+text_length) = '\0';
  197779. #ifdef PNG_iTXt_SUPPORTED
  197780. if(textp->compression > 0)
  197781. {
  197782. textp->text_length = 0;
  197783. textp->itxt_length = text_length;
  197784. }
  197785. else
  197786. #endif
  197787. {
  197788. textp->text_length = text_length;
  197789. #ifdef PNG_iTXt_SUPPORTED
  197790. textp->itxt_length = 0;
  197791. #endif
  197792. }
  197793. info_ptr->num_text++;
  197794. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  197795. }
  197796. return(0);
  197797. }
  197798. #endif
  197799. #if defined(PNG_tIME_SUPPORTED)
  197800. void PNGAPI
  197801. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  197802. {
  197803. png_debug1(1, "in %s storage function\n", "tIME");
  197804. if (png_ptr == NULL || info_ptr == NULL ||
  197805. (png_ptr->mode & PNG_WROTE_tIME))
  197806. return;
  197807. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  197808. info_ptr->valid |= PNG_INFO_tIME;
  197809. }
  197810. #endif
  197811. #if defined(PNG_tRNS_SUPPORTED)
  197812. void PNGAPI
  197813. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  197814. png_bytep trans, int num_trans, png_color_16p trans_values)
  197815. {
  197816. png_debug1(1, "in %s storage function\n", "tRNS");
  197817. if (png_ptr == NULL || info_ptr == NULL)
  197818. return;
  197819. if (trans != NULL)
  197820. {
  197821. /*
  197822. * It may not actually be necessary to set png_ptr->trans here;
  197823. * we do it for backward compatibility with the way the png_handle_tRNS
  197824. * function used to do the allocation.
  197825. */
  197826. #ifdef PNG_FREE_ME_SUPPORTED
  197827. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  197828. #endif
  197829. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  197830. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  197831. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  197832. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  197833. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  197834. #ifdef PNG_FREE_ME_SUPPORTED
  197835. info_ptr->free_me |= PNG_FREE_TRNS;
  197836. #else
  197837. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  197838. #endif
  197839. }
  197840. if (trans_values != NULL)
  197841. {
  197842. png_memcpy(&(info_ptr->trans_values), trans_values,
  197843. png_sizeof(png_color_16));
  197844. if (num_trans == 0)
  197845. num_trans = 1;
  197846. }
  197847. info_ptr->num_trans = (png_uint_16)num_trans;
  197848. info_ptr->valid |= PNG_INFO_tRNS;
  197849. }
  197850. #endif
  197851. #if defined(PNG_sPLT_SUPPORTED)
  197852. void PNGAPI
  197853. png_set_sPLT(png_structp png_ptr,
  197854. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  197855. {
  197856. png_sPLT_tp np;
  197857. int i;
  197858. if (png_ptr == NULL || info_ptr == NULL)
  197859. return;
  197860. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  197861. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  197862. if (np == NULL)
  197863. {
  197864. png_warning(png_ptr, "No memory for sPLT palettes.");
  197865. return;
  197866. }
  197867. png_memcpy(np, info_ptr->splt_palettes,
  197868. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  197869. png_free(png_ptr, info_ptr->splt_palettes);
  197870. info_ptr->splt_palettes=NULL;
  197871. for (i = 0; i < nentries; i++)
  197872. {
  197873. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  197874. png_sPLT_tp from = entries + i;
  197875. to->name = (png_charp)png_malloc_warn(png_ptr,
  197876. png_strlen(from->name) + 1);
  197877. if (to->name == NULL)
  197878. {
  197879. png_warning(png_ptr,
  197880. "Out of memory while processing sPLT chunk");
  197881. }
  197882. /* TODO: use png_malloc_warn */
  197883. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  197884. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  197885. from->nentries * png_sizeof(png_sPLT_entry));
  197886. /* TODO: use png_malloc_warn */
  197887. png_memcpy(to->entries, from->entries,
  197888. from->nentries * png_sizeof(png_sPLT_entry));
  197889. if (to->entries == NULL)
  197890. {
  197891. png_warning(png_ptr,
  197892. "Out of memory while processing sPLT chunk");
  197893. png_free(png_ptr,to->name);
  197894. to->name = NULL;
  197895. }
  197896. to->nentries = from->nentries;
  197897. to->depth = from->depth;
  197898. }
  197899. info_ptr->splt_palettes = np;
  197900. info_ptr->splt_palettes_num += nentries;
  197901. info_ptr->valid |= PNG_INFO_sPLT;
  197902. #ifdef PNG_FREE_ME_SUPPORTED
  197903. info_ptr->free_me |= PNG_FREE_SPLT;
  197904. #endif
  197905. }
  197906. #endif /* PNG_sPLT_SUPPORTED */
  197907. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197908. void PNGAPI
  197909. png_set_unknown_chunks(png_structp png_ptr,
  197910. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  197911. {
  197912. png_unknown_chunkp np;
  197913. int i;
  197914. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  197915. return;
  197916. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  197917. (info_ptr->unknown_chunks_num + num_unknowns) *
  197918. png_sizeof(png_unknown_chunk));
  197919. if (np == NULL)
  197920. {
  197921. png_warning(png_ptr,
  197922. "Out of memory while processing unknown chunk.");
  197923. return;
  197924. }
  197925. png_memcpy(np, info_ptr->unknown_chunks,
  197926. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  197927. png_free(png_ptr, info_ptr->unknown_chunks);
  197928. info_ptr->unknown_chunks=NULL;
  197929. for (i = 0; i < num_unknowns; i++)
  197930. {
  197931. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  197932. png_unknown_chunkp from = unknowns + i;
  197933. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  197934. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  197935. if (to->data == NULL)
  197936. {
  197937. png_warning(png_ptr,
  197938. "Out of memory while processing unknown chunk.");
  197939. }
  197940. else
  197941. {
  197942. png_memcpy(to->data, from->data, from->size);
  197943. to->size = from->size;
  197944. /* note our location in the read or write sequence */
  197945. to->location = (png_byte)(png_ptr->mode & 0xff);
  197946. }
  197947. }
  197948. info_ptr->unknown_chunks = np;
  197949. info_ptr->unknown_chunks_num += num_unknowns;
  197950. #ifdef PNG_FREE_ME_SUPPORTED
  197951. info_ptr->free_me |= PNG_FREE_UNKN;
  197952. #endif
  197953. }
  197954. void PNGAPI
  197955. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  197956. int chunk, int location)
  197957. {
  197958. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  197959. (int)info_ptr->unknown_chunks_num)
  197960. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  197961. }
  197962. #endif
  197963. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  197964. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  197965. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  197966. void PNGAPI
  197967. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  197968. {
  197969. /* This function is deprecated in favor of png_permit_mng_features()
  197970. and will be removed from libpng-1.3.0 */
  197971. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  197972. if (png_ptr == NULL)
  197973. return;
  197974. png_ptr->mng_features_permitted = (png_byte)
  197975. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  197976. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  197977. }
  197978. #endif
  197979. #endif
  197980. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197981. png_uint_32 PNGAPI
  197982. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  197983. {
  197984. png_debug(1, "in png_permit_mng_features\n");
  197985. if (png_ptr == NULL)
  197986. return (png_uint_32)0;
  197987. png_ptr->mng_features_permitted =
  197988. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  197989. return (png_uint_32)png_ptr->mng_features_permitted;
  197990. }
  197991. #endif
  197992. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  197993. void PNGAPI
  197994. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  197995. chunk_list, int num_chunks)
  197996. {
  197997. png_bytep new_list, p;
  197998. int i, old_num_chunks;
  197999. if (png_ptr == NULL)
  198000. return;
  198001. if (num_chunks == 0)
  198002. {
  198003. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  198004. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  198005. else
  198006. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  198007. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  198008. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  198009. else
  198010. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  198011. return;
  198012. }
  198013. if (chunk_list == NULL)
  198014. return;
  198015. old_num_chunks=png_ptr->num_chunk_list;
  198016. new_list=(png_bytep)png_malloc(png_ptr,
  198017. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  198018. if(png_ptr->chunk_list != NULL)
  198019. {
  198020. png_memcpy(new_list, png_ptr->chunk_list,
  198021. (png_size_t)(5*old_num_chunks));
  198022. png_free(png_ptr, png_ptr->chunk_list);
  198023. png_ptr->chunk_list=NULL;
  198024. }
  198025. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  198026. (png_size_t)(5*num_chunks));
  198027. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  198028. *p=(png_byte)keep;
  198029. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  198030. png_ptr->chunk_list=new_list;
  198031. #ifdef PNG_FREE_ME_SUPPORTED
  198032. png_ptr->free_me |= PNG_FREE_LIST;
  198033. #endif
  198034. }
  198035. #endif
  198036. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198037. void PNGAPI
  198038. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198039. png_user_chunk_ptr read_user_chunk_fn)
  198040. {
  198041. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198042. if (png_ptr == NULL)
  198043. return;
  198044. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198045. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198046. }
  198047. #endif
  198048. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198049. void PNGAPI
  198050. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198051. {
  198052. png_debug1(1, "in %s storage function\n", "rows");
  198053. if (png_ptr == NULL || info_ptr == NULL)
  198054. return;
  198055. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198056. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198057. info_ptr->row_pointers = row_pointers;
  198058. if(row_pointers)
  198059. info_ptr->valid |= PNG_INFO_IDAT;
  198060. }
  198061. #endif
  198062. #ifdef PNG_WRITE_SUPPORTED
  198063. void PNGAPI
  198064. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198065. {
  198066. if (png_ptr == NULL)
  198067. return;
  198068. if(png_ptr->zbuf)
  198069. png_free(png_ptr, png_ptr->zbuf);
  198070. png_ptr->zbuf_size = (png_size_t)size;
  198071. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198072. png_ptr->zstream.next_out = png_ptr->zbuf;
  198073. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198074. }
  198075. #endif
  198076. void PNGAPI
  198077. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198078. {
  198079. if (png_ptr && info_ptr)
  198080. info_ptr->valid &= ~(mask);
  198081. }
  198082. #ifndef PNG_1_0_X
  198083. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198084. /* function was added to libpng 1.2.0 and should always exist by default */
  198085. void PNGAPI
  198086. png_set_asm_flags (png_structp png_ptr, png_uint_32)
  198087. {
  198088. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198089. if (png_ptr != NULL)
  198090. png_ptr->asm_flags = 0;
  198091. }
  198092. /* this function was added to libpng 1.2.0 */
  198093. void PNGAPI
  198094. png_set_mmx_thresholds (png_structp png_ptr,
  198095. png_byte,
  198096. png_uint_32)
  198097. {
  198098. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198099. if (png_ptr == NULL)
  198100. return;
  198101. }
  198102. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198103. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198104. /* this function was added to libpng 1.2.6 */
  198105. void PNGAPI
  198106. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198107. png_uint_32 user_height_max)
  198108. {
  198109. /* Images with dimensions larger than these limits will be
  198110. * rejected by png_set_IHDR(). To accept any PNG datastream
  198111. * regardless of dimensions, set both limits to 0x7ffffffL.
  198112. */
  198113. if(png_ptr == NULL) return;
  198114. png_ptr->user_width_max = user_width_max;
  198115. png_ptr->user_height_max = user_height_max;
  198116. }
  198117. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198118. #endif /* ?PNG_1_0_X */
  198119. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198120. /*** End of inlined file: pngset.c ***/
  198121. /*** Start of inlined file: pngtrans.c ***/
  198122. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198123. *
  198124. * Last changed in libpng 1.2.17 May 15, 2007
  198125. * For conditions of distribution and use, see copyright notice in png.h
  198126. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198127. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198128. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198129. */
  198130. #define PNG_INTERNAL
  198131. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198132. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198133. /* turn on BGR-to-RGB mapping */
  198134. void PNGAPI
  198135. png_set_bgr(png_structp png_ptr)
  198136. {
  198137. png_debug(1, "in png_set_bgr\n");
  198138. if(png_ptr == NULL) return;
  198139. png_ptr->transformations |= PNG_BGR;
  198140. }
  198141. #endif
  198142. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198143. /* turn on 16 bit byte swapping */
  198144. void PNGAPI
  198145. png_set_swap(png_structp png_ptr)
  198146. {
  198147. png_debug(1, "in png_set_swap\n");
  198148. if(png_ptr == NULL) return;
  198149. if (png_ptr->bit_depth == 16)
  198150. png_ptr->transformations |= PNG_SWAP_BYTES;
  198151. }
  198152. #endif
  198153. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198154. /* turn on pixel packing */
  198155. void PNGAPI
  198156. png_set_packing(png_structp png_ptr)
  198157. {
  198158. png_debug(1, "in png_set_packing\n");
  198159. if(png_ptr == NULL) return;
  198160. if (png_ptr->bit_depth < 8)
  198161. {
  198162. png_ptr->transformations |= PNG_PACK;
  198163. png_ptr->usr_bit_depth = 8;
  198164. }
  198165. }
  198166. #endif
  198167. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198168. /* turn on packed pixel swapping */
  198169. void PNGAPI
  198170. png_set_packswap(png_structp png_ptr)
  198171. {
  198172. png_debug(1, "in png_set_packswap\n");
  198173. if(png_ptr == NULL) return;
  198174. if (png_ptr->bit_depth < 8)
  198175. png_ptr->transformations |= PNG_PACKSWAP;
  198176. }
  198177. #endif
  198178. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198179. void PNGAPI
  198180. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198181. {
  198182. png_debug(1, "in png_set_shift\n");
  198183. if(png_ptr == NULL) return;
  198184. png_ptr->transformations |= PNG_SHIFT;
  198185. png_ptr->shift = *true_bits;
  198186. }
  198187. #endif
  198188. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198189. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198190. int PNGAPI
  198191. png_set_interlace_handling(png_structp png_ptr)
  198192. {
  198193. png_debug(1, "in png_set_interlace handling\n");
  198194. if (png_ptr && png_ptr->interlaced)
  198195. {
  198196. png_ptr->transformations |= PNG_INTERLACE;
  198197. return (7);
  198198. }
  198199. return (1);
  198200. }
  198201. #endif
  198202. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198203. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198204. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198205. * for 48-bit input data, as well as to avoid problems with some compilers
  198206. * that don't like bytes as parameters.
  198207. */
  198208. void PNGAPI
  198209. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198210. {
  198211. png_debug(1, "in png_set_filler\n");
  198212. if(png_ptr == NULL) return;
  198213. png_ptr->transformations |= PNG_FILLER;
  198214. png_ptr->filler = (png_byte)filler;
  198215. if (filler_loc == PNG_FILLER_AFTER)
  198216. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198217. else
  198218. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198219. /* This should probably go in the "do_read_filler" routine.
  198220. * I attempted to do that in libpng-1.0.1a but that caused problems
  198221. * so I restored it in libpng-1.0.2a
  198222. */
  198223. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198224. {
  198225. png_ptr->usr_channels = 4;
  198226. }
  198227. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198228. * a less-than-8-bit grayscale to GA? */
  198229. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198230. {
  198231. png_ptr->usr_channels = 2;
  198232. }
  198233. }
  198234. #if !defined(PNG_1_0_X)
  198235. /* Added to libpng-1.2.7 */
  198236. void PNGAPI
  198237. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198238. {
  198239. png_debug(1, "in png_set_add_alpha\n");
  198240. if(png_ptr == NULL) return;
  198241. png_set_filler(png_ptr, filler, filler_loc);
  198242. png_ptr->transformations |= PNG_ADD_ALPHA;
  198243. }
  198244. #endif
  198245. #endif
  198246. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198247. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198248. void PNGAPI
  198249. png_set_swap_alpha(png_structp png_ptr)
  198250. {
  198251. png_debug(1, "in png_set_swap_alpha\n");
  198252. if(png_ptr == NULL) return;
  198253. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198254. }
  198255. #endif
  198256. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198257. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198258. void PNGAPI
  198259. png_set_invert_alpha(png_structp png_ptr)
  198260. {
  198261. png_debug(1, "in png_set_invert_alpha\n");
  198262. if(png_ptr == NULL) return;
  198263. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198264. }
  198265. #endif
  198266. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198267. void PNGAPI
  198268. png_set_invert_mono(png_structp png_ptr)
  198269. {
  198270. png_debug(1, "in png_set_invert_mono\n");
  198271. if(png_ptr == NULL) return;
  198272. png_ptr->transformations |= PNG_INVERT_MONO;
  198273. }
  198274. /* invert monochrome grayscale data */
  198275. void /* PRIVATE */
  198276. png_do_invert(png_row_infop row_info, png_bytep row)
  198277. {
  198278. png_debug(1, "in png_do_invert\n");
  198279. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198280. * if (row_info->bit_depth == 1 &&
  198281. */
  198282. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198283. if (row == NULL || row_info == NULL)
  198284. return;
  198285. #endif
  198286. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  198287. {
  198288. png_bytep rp = row;
  198289. png_uint_32 i;
  198290. png_uint_32 istop = row_info->rowbytes;
  198291. for (i = 0; i < istop; i++)
  198292. {
  198293. *rp = (png_byte)(~(*rp));
  198294. rp++;
  198295. }
  198296. }
  198297. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198298. row_info->bit_depth == 8)
  198299. {
  198300. png_bytep rp = row;
  198301. png_uint_32 i;
  198302. png_uint_32 istop = row_info->rowbytes;
  198303. for (i = 0; i < istop; i+=2)
  198304. {
  198305. *rp = (png_byte)(~(*rp));
  198306. rp+=2;
  198307. }
  198308. }
  198309. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198310. row_info->bit_depth == 16)
  198311. {
  198312. png_bytep rp = row;
  198313. png_uint_32 i;
  198314. png_uint_32 istop = row_info->rowbytes;
  198315. for (i = 0; i < istop; i+=4)
  198316. {
  198317. *rp = (png_byte)(~(*rp));
  198318. *(rp+1) = (png_byte)(~(*(rp+1)));
  198319. rp+=4;
  198320. }
  198321. }
  198322. }
  198323. #endif
  198324. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198325. /* swaps byte order on 16 bit depth images */
  198326. void /* PRIVATE */
  198327. png_do_swap(png_row_infop row_info, png_bytep row)
  198328. {
  198329. png_debug(1, "in png_do_swap\n");
  198330. if (
  198331. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198332. row != NULL && row_info != NULL &&
  198333. #endif
  198334. row_info->bit_depth == 16)
  198335. {
  198336. png_bytep rp = row;
  198337. png_uint_32 i;
  198338. png_uint_32 istop= row_info->width * row_info->channels;
  198339. for (i = 0; i < istop; i++, rp += 2)
  198340. {
  198341. png_byte t = *rp;
  198342. *rp = *(rp + 1);
  198343. *(rp + 1) = t;
  198344. }
  198345. }
  198346. }
  198347. #endif
  198348. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198349. static PNG_CONST png_byte onebppswaptable[256] = {
  198350. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  198351. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  198352. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  198353. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  198354. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  198355. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  198356. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  198357. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  198358. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  198359. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  198360. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  198361. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  198362. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  198363. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  198364. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  198365. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  198366. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  198367. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  198368. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  198369. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  198370. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  198371. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  198372. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  198373. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  198374. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  198375. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  198376. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  198377. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  198378. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  198379. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  198380. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  198381. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  198382. };
  198383. static PNG_CONST png_byte twobppswaptable[256] = {
  198384. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  198385. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  198386. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  198387. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  198388. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  198389. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  198390. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  198391. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  198392. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  198393. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  198394. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  198395. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  198396. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  198397. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  198398. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  198399. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  198400. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  198401. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  198402. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  198403. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  198404. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  198405. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  198406. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  198407. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  198408. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  198409. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  198410. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  198411. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  198412. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  198413. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  198414. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  198415. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  198416. };
  198417. static PNG_CONST png_byte fourbppswaptable[256] = {
  198418. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  198419. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  198420. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  198421. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  198422. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  198423. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  198424. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  198425. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  198426. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  198427. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  198428. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  198429. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  198430. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  198431. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  198432. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  198433. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  198434. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  198435. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  198436. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  198437. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  198438. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  198439. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  198440. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  198441. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  198442. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  198443. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  198444. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  198445. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  198446. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  198447. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  198448. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  198449. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  198450. };
  198451. /* swaps pixel packing order within bytes */
  198452. void /* PRIVATE */
  198453. png_do_packswap(png_row_infop row_info, png_bytep row)
  198454. {
  198455. png_debug(1, "in png_do_packswap\n");
  198456. if (
  198457. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198458. row != NULL && row_info != NULL &&
  198459. #endif
  198460. row_info->bit_depth < 8)
  198461. {
  198462. png_bytep rp, end, table;
  198463. end = row + row_info->rowbytes;
  198464. if (row_info->bit_depth == 1)
  198465. table = (png_bytep)onebppswaptable;
  198466. else if (row_info->bit_depth == 2)
  198467. table = (png_bytep)twobppswaptable;
  198468. else if (row_info->bit_depth == 4)
  198469. table = (png_bytep)fourbppswaptable;
  198470. else
  198471. return;
  198472. for (rp = row; rp < end; rp++)
  198473. *rp = table[*rp];
  198474. }
  198475. }
  198476. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  198477. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  198478. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  198479. /* remove filler or alpha byte(s) */
  198480. void /* PRIVATE */
  198481. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  198482. {
  198483. png_debug(1, "in png_do_strip_filler\n");
  198484. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198485. if (row != NULL && row_info != NULL)
  198486. #endif
  198487. {
  198488. png_bytep sp=row;
  198489. png_bytep dp=row;
  198490. png_uint_32 row_width=row_info->width;
  198491. png_uint_32 i;
  198492. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  198493. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  198494. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198495. row_info->channels == 4)
  198496. {
  198497. if (row_info->bit_depth == 8)
  198498. {
  198499. /* This converts from RGBX or RGBA to RGB */
  198500. if (flags & PNG_FLAG_FILLER_AFTER)
  198501. {
  198502. dp+=3; sp+=4;
  198503. for (i = 1; i < row_width; i++)
  198504. {
  198505. *dp++ = *sp++;
  198506. *dp++ = *sp++;
  198507. *dp++ = *sp++;
  198508. sp++;
  198509. }
  198510. }
  198511. /* This converts from XRGB or ARGB to RGB */
  198512. else
  198513. {
  198514. for (i = 0; i < row_width; i++)
  198515. {
  198516. sp++;
  198517. *dp++ = *sp++;
  198518. *dp++ = *sp++;
  198519. *dp++ = *sp++;
  198520. }
  198521. }
  198522. row_info->pixel_depth = 24;
  198523. row_info->rowbytes = row_width * 3;
  198524. }
  198525. else /* if (row_info->bit_depth == 16) */
  198526. {
  198527. if (flags & PNG_FLAG_FILLER_AFTER)
  198528. {
  198529. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  198530. sp += 8; dp += 6;
  198531. for (i = 1; i < row_width; i++)
  198532. {
  198533. /* This could be (although png_memcpy is probably slower):
  198534. png_memcpy(dp, sp, 6);
  198535. sp += 8;
  198536. dp += 6;
  198537. */
  198538. *dp++ = *sp++;
  198539. *dp++ = *sp++;
  198540. *dp++ = *sp++;
  198541. *dp++ = *sp++;
  198542. *dp++ = *sp++;
  198543. *dp++ = *sp++;
  198544. sp += 2;
  198545. }
  198546. }
  198547. else
  198548. {
  198549. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  198550. for (i = 0; i < row_width; i++)
  198551. {
  198552. /* This could be (although png_memcpy is probably slower):
  198553. png_memcpy(dp, sp, 6);
  198554. sp += 8;
  198555. dp += 6;
  198556. */
  198557. sp+=2;
  198558. *dp++ = *sp++;
  198559. *dp++ = *sp++;
  198560. *dp++ = *sp++;
  198561. *dp++ = *sp++;
  198562. *dp++ = *sp++;
  198563. *dp++ = *sp++;
  198564. }
  198565. }
  198566. row_info->pixel_depth = 48;
  198567. row_info->rowbytes = row_width * 6;
  198568. }
  198569. row_info->channels = 3;
  198570. }
  198571. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  198572. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  198573. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  198574. row_info->channels == 2)
  198575. {
  198576. if (row_info->bit_depth == 8)
  198577. {
  198578. /* This converts from GX or GA to G */
  198579. if (flags & PNG_FLAG_FILLER_AFTER)
  198580. {
  198581. for (i = 0; i < row_width; i++)
  198582. {
  198583. *dp++ = *sp++;
  198584. sp++;
  198585. }
  198586. }
  198587. /* This converts from XG or AG to G */
  198588. else
  198589. {
  198590. for (i = 0; i < row_width; i++)
  198591. {
  198592. sp++;
  198593. *dp++ = *sp++;
  198594. }
  198595. }
  198596. row_info->pixel_depth = 8;
  198597. row_info->rowbytes = row_width;
  198598. }
  198599. else /* if (row_info->bit_depth == 16) */
  198600. {
  198601. if (flags & PNG_FLAG_FILLER_AFTER)
  198602. {
  198603. /* This converts from GGXX or GGAA to GG */
  198604. sp += 4; dp += 2;
  198605. for (i = 1; i < row_width; i++)
  198606. {
  198607. *dp++ = *sp++;
  198608. *dp++ = *sp++;
  198609. sp += 2;
  198610. }
  198611. }
  198612. else
  198613. {
  198614. /* This converts from XXGG or AAGG to GG */
  198615. for (i = 0; i < row_width; i++)
  198616. {
  198617. sp += 2;
  198618. *dp++ = *sp++;
  198619. *dp++ = *sp++;
  198620. }
  198621. }
  198622. row_info->pixel_depth = 16;
  198623. row_info->rowbytes = row_width * 2;
  198624. }
  198625. row_info->channels = 1;
  198626. }
  198627. if (flags & PNG_FLAG_STRIP_ALPHA)
  198628. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  198629. }
  198630. }
  198631. #endif
  198632. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198633. /* swaps red and blue bytes within a pixel */
  198634. void /* PRIVATE */
  198635. png_do_bgr(png_row_infop row_info, png_bytep row)
  198636. {
  198637. png_debug(1, "in png_do_bgr\n");
  198638. if (
  198639. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  198640. row != NULL && row_info != NULL &&
  198641. #endif
  198642. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  198643. {
  198644. png_uint_32 row_width = row_info->width;
  198645. if (row_info->bit_depth == 8)
  198646. {
  198647. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198648. {
  198649. png_bytep rp;
  198650. png_uint_32 i;
  198651. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  198652. {
  198653. png_byte save = *rp;
  198654. *rp = *(rp + 2);
  198655. *(rp + 2) = save;
  198656. }
  198657. }
  198658. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198659. {
  198660. png_bytep rp;
  198661. png_uint_32 i;
  198662. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  198663. {
  198664. png_byte save = *rp;
  198665. *rp = *(rp + 2);
  198666. *(rp + 2) = save;
  198667. }
  198668. }
  198669. }
  198670. else if (row_info->bit_depth == 16)
  198671. {
  198672. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  198673. {
  198674. png_bytep rp;
  198675. png_uint_32 i;
  198676. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  198677. {
  198678. png_byte save = *rp;
  198679. *rp = *(rp + 4);
  198680. *(rp + 4) = save;
  198681. save = *(rp + 1);
  198682. *(rp + 1) = *(rp + 5);
  198683. *(rp + 5) = save;
  198684. }
  198685. }
  198686. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  198687. {
  198688. png_bytep rp;
  198689. png_uint_32 i;
  198690. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  198691. {
  198692. png_byte save = *rp;
  198693. *rp = *(rp + 4);
  198694. *(rp + 4) = save;
  198695. save = *(rp + 1);
  198696. *(rp + 1) = *(rp + 5);
  198697. *(rp + 5) = save;
  198698. }
  198699. }
  198700. }
  198701. }
  198702. }
  198703. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  198704. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  198705. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  198706. defined(PNG_LEGACY_SUPPORTED)
  198707. void PNGAPI
  198708. png_set_user_transform_info(png_structp png_ptr, png_voidp
  198709. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  198710. {
  198711. png_debug(1, "in png_set_user_transform_info\n");
  198712. if(png_ptr == NULL) return;
  198713. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198714. png_ptr->user_transform_ptr = user_transform_ptr;
  198715. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  198716. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  198717. #else
  198718. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  198719. png_warning(png_ptr,
  198720. "This version of libpng does not support user transform info");
  198721. #endif
  198722. }
  198723. #endif
  198724. /* This function returns a pointer to the user_transform_ptr associated with
  198725. * the user transform functions. The application should free any memory
  198726. * associated with this pointer before png_write_destroy and png_read_destroy
  198727. * are called.
  198728. */
  198729. png_voidp PNGAPI
  198730. png_get_user_transform_ptr(png_structp png_ptr)
  198731. {
  198732. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  198733. if (png_ptr == NULL) return (NULL);
  198734. return ((png_voidp)png_ptr->user_transform_ptr);
  198735. #else
  198736. return (NULL);
  198737. #endif
  198738. }
  198739. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198740. /*** End of inlined file: pngtrans.c ***/
  198741. /*** Start of inlined file: pngwio.c ***/
  198742. /* pngwio.c - functions for data output
  198743. *
  198744. * Last changed in libpng 1.2.13 November 13, 2006
  198745. * For conditions of distribution and use, see copyright notice in png.h
  198746. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  198747. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198748. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198749. *
  198750. * This file provides a location for all output. Users who need
  198751. * special handling are expected to write functions that have the same
  198752. * arguments as these and perform similar functions, but that possibly
  198753. * use different output methods. Note that you shouldn't change these
  198754. * functions, but rather write replacement functions and then change
  198755. * them at run time with png_set_write_fn(...).
  198756. */
  198757. #define PNG_INTERNAL
  198758. #ifdef PNG_WRITE_SUPPORTED
  198759. /* Write the data to whatever output you are using. The default routine
  198760. writes to a file pointer. Note that this routine sometimes gets called
  198761. with very small lengths, so you should implement some kind of simple
  198762. buffering if you are using unbuffered writes. This should never be asked
  198763. to write more than 64K on a 16 bit machine. */
  198764. void /* PRIVATE */
  198765. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198766. {
  198767. if (png_ptr->write_data_fn != NULL )
  198768. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  198769. else
  198770. png_error(png_ptr, "Call to NULL write function");
  198771. }
  198772. #if !defined(PNG_NO_STDIO)
  198773. /* This is the function that does the actual writing of data. If you are
  198774. not writing to a standard C stream, you should create a replacement
  198775. write_data function and use it at run time with png_set_write_fn(), rather
  198776. than changing the library. */
  198777. #ifndef USE_FAR_KEYWORD
  198778. void PNGAPI
  198779. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198780. {
  198781. png_uint_32 check;
  198782. if(png_ptr == NULL) return;
  198783. #if defined(_WIN32_WCE)
  198784. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  198785. check = 0;
  198786. #else
  198787. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  198788. #endif
  198789. if (check != length)
  198790. png_error(png_ptr, "Write Error");
  198791. }
  198792. #else
  198793. /* this is the model-independent version. Since the standard I/O library
  198794. can't handle far buffers in the medium and small models, we have to copy
  198795. the data.
  198796. */
  198797. #define NEAR_BUF_SIZE 1024
  198798. #define MIN(a,b) (a <= b ? a : b)
  198799. void PNGAPI
  198800. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  198801. {
  198802. png_uint_32 check;
  198803. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  198804. png_FILE_p io_ptr;
  198805. if(png_ptr == NULL) return;
  198806. /* Check if data really is near. If so, use usual code. */
  198807. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  198808. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  198809. if ((png_bytep)near_data == data)
  198810. {
  198811. #if defined(_WIN32_WCE)
  198812. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  198813. check = 0;
  198814. #else
  198815. check = fwrite(near_data, 1, length, io_ptr);
  198816. #endif
  198817. }
  198818. else
  198819. {
  198820. png_byte buf[NEAR_BUF_SIZE];
  198821. png_size_t written, remaining, err;
  198822. check = 0;
  198823. remaining = length;
  198824. do
  198825. {
  198826. written = MIN(NEAR_BUF_SIZE, remaining);
  198827. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  198828. #if defined(_WIN32_WCE)
  198829. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  198830. err = 0;
  198831. #else
  198832. err = fwrite(buf, 1, written, io_ptr);
  198833. #endif
  198834. if (err != written)
  198835. break;
  198836. else
  198837. check += err;
  198838. data += written;
  198839. remaining -= written;
  198840. }
  198841. while (remaining != 0);
  198842. }
  198843. if (check != length)
  198844. png_error(png_ptr, "Write Error");
  198845. }
  198846. #endif
  198847. #endif
  198848. /* This function is called to output any data pending writing (normally
  198849. to disk). After png_flush is called, there should be no data pending
  198850. writing in any buffers. */
  198851. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198852. void /* PRIVATE */
  198853. png_flush(png_structp png_ptr)
  198854. {
  198855. if (png_ptr->output_flush_fn != NULL)
  198856. (*(png_ptr->output_flush_fn))(png_ptr);
  198857. }
  198858. #if !defined(PNG_NO_STDIO)
  198859. void PNGAPI
  198860. png_default_flush(png_structp png_ptr)
  198861. {
  198862. #if !defined(_WIN32_WCE)
  198863. png_FILE_p io_ptr;
  198864. #endif
  198865. if(png_ptr == NULL) return;
  198866. #if !defined(_WIN32_WCE)
  198867. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  198868. if (io_ptr != NULL)
  198869. fflush(io_ptr);
  198870. #endif
  198871. }
  198872. #endif
  198873. #endif
  198874. /* This function allows the application to supply new output functions for
  198875. libpng if standard C streams aren't being used.
  198876. This function takes as its arguments:
  198877. png_ptr - pointer to a png output data structure
  198878. io_ptr - pointer to user supplied structure containing info about
  198879. the output functions. May be NULL.
  198880. write_data_fn - pointer to a new output function that takes as its
  198881. arguments a pointer to a png_struct, a pointer to
  198882. data to be written, and a 32-bit unsigned int that is
  198883. the number of bytes to be written. The new write
  198884. function should call png_error(png_ptr, "Error msg")
  198885. to exit and output any fatal error messages.
  198886. flush_data_fn - pointer to a new flush function that takes as its
  198887. arguments a pointer to a png_struct. After a call to
  198888. the flush function, there should be no data in any buffers
  198889. or pending transmission. If the output method doesn't do
  198890. any buffering of ouput, a function prototype must still be
  198891. supplied although it doesn't have to do anything. If
  198892. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  198893. time, output_flush_fn will be ignored, although it must be
  198894. supplied for compatibility. */
  198895. void PNGAPI
  198896. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  198897. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  198898. {
  198899. if(png_ptr == NULL) return;
  198900. png_ptr->io_ptr = io_ptr;
  198901. #if !defined(PNG_NO_STDIO)
  198902. if (write_data_fn != NULL)
  198903. png_ptr->write_data_fn = write_data_fn;
  198904. else
  198905. png_ptr->write_data_fn = png_default_write_data;
  198906. #else
  198907. png_ptr->write_data_fn = write_data_fn;
  198908. #endif
  198909. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  198910. #if !defined(PNG_NO_STDIO)
  198911. if (output_flush_fn != NULL)
  198912. png_ptr->output_flush_fn = output_flush_fn;
  198913. else
  198914. png_ptr->output_flush_fn = png_default_flush;
  198915. #else
  198916. png_ptr->output_flush_fn = output_flush_fn;
  198917. #endif
  198918. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  198919. /* It is an error to read while writing a png file */
  198920. if (png_ptr->read_data_fn != NULL)
  198921. {
  198922. png_ptr->read_data_fn = NULL;
  198923. png_warning(png_ptr,
  198924. "Attempted to set both read_data_fn and write_data_fn in");
  198925. png_warning(png_ptr,
  198926. "the same structure. Resetting read_data_fn to NULL.");
  198927. }
  198928. }
  198929. #if defined(USE_FAR_KEYWORD)
  198930. #if defined(_MSC_VER)
  198931. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198932. {
  198933. void *near_ptr;
  198934. void FAR *far_ptr;
  198935. FP_OFF(near_ptr) = FP_OFF(ptr);
  198936. far_ptr = (void FAR *)near_ptr;
  198937. if(check != 0)
  198938. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  198939. png_error(png_ptr,"segment lost in conversion");
  198940. return(near_ptr);
  198941. }
  198942. # else
  198943. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  198944. {
  198945. void *near_ptr;
  198946. void FAR *far_ptr;
  198947. near_ptr = (void FAR *)ptr;
  198948. far_ptr = (void FAR *)near_ptr;
  198949. if(check != 0)
  198950. if(far_ptr != ptr)
  198951. png_error(png_ptr,"segment lost in conversion");
  198952. return(near_ptr);
  198953. }
  198954. # endif
  198955. # endif
  198956. #endif /* PNG_WRITE_SUPPORTED */
  198957. /*** End of inlined file: pngwio.c ***/
  198958. /*** Start of inlined file: pngwrite.c ***/
  198959. /* pngwrite.c - general routines to write a PNG file
  198960. *
  198961. * Last changed in libpng 1.2.15 January 5, 2007
  198962. * For conditions of distribution and use, see copyright notice in png.h
  198963. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198964. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198965. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198966. */
  198967. /* get internal access to png.h */
  198968. #define PNG_INTERNAL
  198969. #ifdef PNG_WRITE_SUPPORTED
  198970. /* Writes all the PNG information. This is the suggested way to use the
  198971. * library. If you have a new chunk to add, make a function to write it,
  198972. * and put it in the correct location here. If you want the chunk written
  198973. * after the image data, put it in png_write_end(). I strongly encourage
  198974. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  198975. * the chunk, as that will keep the code from breaking if you want to just
  198976. * write a plain PNG file. If you have long comments, I suggest writing
  198977. * them in png_write_end(), and compressing them.
  198978. */
  198979. void PNGAPI
  198980. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  198981. {
  198982. png_debug(1, "in png_write_info_before_PLTE\n");
  198983. if (png_ptr == NULL || info_ptr == NULL)
  198984. return;
  198985. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  198986. {
  198987. png_write_sig(png_ptr); /* write PNG signature */
  198988. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198989. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  198990. {
  198991. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198992. png_ptr->mng_features_permitted=0;
  198993. }
  198994. #endif
  198995. /* write IHDR information. */
  198996. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  198997. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  198998. info_ptr->filter_type,
  198999. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199000. info_ptr->interlace_type);
  199001. #else
  199002. 0);
  199003. #endif
  199004. /* the rest of these check to see if the valid field has the appropriate
  199005. flag set, and if it does, writes the chunk. */
  199006. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  199007. if (info_ptr->valid & PNG_INFO_gAMA)
  199008. {
  199009. # ifdef PNG_FLOATING_POINT_SUPPORTED
  199010. png_write_gAMA(png_ptr, info_ptr->gamma);
  199011. #else
  199012. #ifdef PNG_FIXED_POINT_SUPPORTED
  199013. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  199014. # endif
  199015. #endif
  199016. }
  199017. #endif
  199018. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  199019. if (info_ptr->valid & PNG_INFO_sRGB)
  199020. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  199021. #endif
  199022. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  199023. if (info_ptr->valid & PNG_INFO_iCCP)
  199024. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  199025. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  199026. #endif
  199027. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  199028. if (info_ptr->valid & PNG_INFO_sBIT)
  199029. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  199030. #endif
  199031. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  199032. if (info_ptr->valid & PNG_INFO_cHRM)
  199033. {
  199034. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199035. png_write_cHRM(png_ptr,
  199036. info_ptr->x_white, info_ptr->y_white,
  199037. info_ptr->x_red, info_ptr->y_red,
  199038. info_ptr->x_green, info_ptr->y_green,
  199039. info_ptr->x_blue, info_ptr->y_blue);
  199040. #else
  199041. # ifdef PNG_FIXED_POINT_SUPPORTED
  199042. png_write_cHRM_fixed(png_ptr,
  199043. info_ptr->int_x_white, info_ptr->int_y_white,
  199044. info_ptr->int_x_red, info_ptr->int_y_red,
  199045. info_ptr->int_x_green, info_ptr->int_y_green,
  199046. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199047. # endif
  199048. #endif
  199049. }
  199050. #endif
  199051. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199052. if (info_ptr->unknown_chunks_num)
  199053. {
  199054. png_unknown_chunk *up;
  199055. png_debug(5, "writing extra chunks\n");
  199056. for (up = info_ptr->unknown_chunks;
  199057. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199058. up++)
  199059. {
  199060. int keep=png_handle_as_unknown(png_ptr, up->name);
  199061. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199062. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199063. !(up->location & PNG_HAVE_IDAT) &&
  199064. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199065. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199066. {
  199067. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199068. }
  199069. }
  199070. }
  199071. #endif
  199072. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199073. }
  199074. }
  199075. void PNGAPI
  199076. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199077. {
  199078. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199079. int i;
  199080. #endif
  199081. png_debug(1, "in png_write_info\n");
  199082. if (png_ptr == NULL || info_ptr == NULL)
  199083. return;
  199084. png_write_info_before_PLTE(png_ptr, info_ptr);
  199085. if (info_ptr->valid & PNG_INFO_PLTE)
  199086. png_write_PLTE(png_ptr, info_ptr->palette,
  199087. (png_uint_32)info_ptr->num_palette);
  199088. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199089. png_error(png_ptr, "Valid palette required for paletted images");
  199090. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199091. if (info_ptr->valid & PNG_INFO_tRNS)
  199092. {
  199093. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199094. /* invert the alpha channel (in tRNS) */
  199095. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199096. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199097. {
  199098. int j;
  199099. for (j=0; j<(int)info_ptr->num_trans; j++)
  199100. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199101. }
  199102. #endif
  199103. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199104. info_ptr->num_trans, info_ptr->color_type);
  199105. }
  199106. #endif
  199107. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199108. if (info_ptr->valid & PNG_INFO_bKGD)
  199109. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199110. #endif
  199111. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199112. if (info_ptr->valid & PNG_INFO_hIST)
  199113. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199114. #endif
  199115. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199116. if (info_ptr->valid & PNG_INFO_oFFs)
  199117. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199118. info_ptr->offset_unit_type);
  199119. #endif
  199120. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199121. if (info_ptr->valid & PNG_INFO_pCAL)
  199122. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199123. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199124. info_ptr->pcal_units, info_ptr->pcal_params);
  199125. #endif
  199126. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199127. if (info_ptr->valid & PNG_INFO_sCAL)
  199128. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199129. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199130. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199131. #else
  199132. #ifdef PNG_FIXED_POINT_SUPPORTED
  199133. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199134. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199135. #else
  199136. png_warning(png_ptr,
  199137. "png_write_sCAL not supported; sCAL chunk not written.");
  199138. #endif
  199139. #endif
  199140. #endif
  199141. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199142. if (info_ptr->valid & PNG_INFO_pHYs)
  199143. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199144. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199145. #endif
  199146. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199147. if (info_ptr->valid & PNG_INFO_tIME)
  199148. {
  199149. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199150. png_ptr->mode |= PNG_WROTE_tIME;
  199151. }
  199152. #endif
  199153. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199154. if (info_ptr->valid & PNG_INFO_sPLT)
  199155. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199156. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199157. #endif
  199158. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199159. /* Check to see if we need to write text chunks */
  199160. for (i = 0; i < info_ptr->num_text; i++)
  199161. {
  199162. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199163. info_ptr->text[i].compression);
  199164. /* an internationalized chunk? */
  199165. if (info_ptr->text[i].compression > 0)
  199166. {
  199167. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199168. /* write international chunk */
  199169. png_write_iTXt(png_ptr,
  199170. info_ptr->text[i].compression,
  199171. info_ptr->text[i].key,
  199172. info_ptr->text[i].lang,
  199173. info_ptr->text[i].lang_key,
  199174. info_ptr->text[i].text);
  199175. #else
  199176. png_warning(png_ptr, "Unable to write international text");
  199177. #endif
  199178. /* Mark this chunk as written */
  199179. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199180. }
  199181. /* If we want a compressed text chunk */
  199182. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199183. {
  199184. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199185. /* write compressed chunk */
  199186. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199187. info_ptr->text[i].text, 0,
  199188. info_ptr->text[i].compression);
  199189. #else
  199190. png_warning(png_ptr, "Unable to write compressed text");
  199191. #endif
  199192. /* Mark this chunk as written */
  199193. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199194. }
  199195. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199196. {
  199197. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199198. /* write uncompressed chunk */
  199199. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199200. info_ptr->text[i].text,
  199201. 0);
  199202. #else
  199203. png_warning(png_ptr, "Unable to write uncompressed text");
  199204. #endif
  199205. /* Mark this chunk as written */
  199206. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199207. }
  199208. }
  199209. #endif
  199210. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199211. if (info_ptr->unknown_chunks_num)
  199212. {
  199213. png_unknown_chunk *up;
  199214. png_debug(5, "writing extra chunks\n");
  199215. for (up = info_ptr->unknown_chunks;
  199216. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199217. up++)
  199218. {
  199219. int keep=png_handle_as_unknown(png_ptr, up->name);
  199220. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199221. up->location && (up->location & PNG_HAVE_PLTE) &&
  199222. !(up->location & PNG_HAVE_IDAT) &&
  199223. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199224. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199225. {
  199226. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199227. }
  199228. }
  199229. }
  199230. #endif
  199231. }
  199232. /* Writes the end of the PNG file. If you don't want to write comments or
  199233. * time information, you can pass NULL for info. If you already wrote these
  199234. * in png_write_info(), do not write them again here. If you have long
  199235. * comments, I suggest writing them here, and compressing them.
  199236. */
  199237. void PNGAPI
  199238. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199239. {
  199240. png_debug(1, "in png_write_end\n");
  199241. if (png_ptr == NULL)
  199242. return;
  199243. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199244. png_error(png_ptr, "No IDATs written into file");
  199245. /* see if user wants us to write information chunks */
  199246. if (info_ptr != NULL)
  199247. {
  199248. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199249. int i; /* local index variable */
  199250. #endif
  199251. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199252. /* check to see if user has supplied a time chunk */
  199253. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199254. !(png_ptr->mode & PNG_WROTE_tIME))
  199255. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199256. #endif
  199257. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199258. /* loop through comment chunks */
  199259. for (i = 0; i < info_ptr->num_text; i++)
  199260. {
  199261. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199262. info_ptr->text[i].compression);
  199263. /* an internationalized chunk? */
  199264. if (info_ptr->text[i].compression > 0)
  199265. {
  199266. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199267. /* write international chunk */
  199268. png_write_iTXt(png_ptr,
  199269. info_ptr->text[i].compression,
  199270. info_ptr->text[i].key,
  199271. info_ptr->text[i].lang,
  199272. info_ptr->text[i].lang_key,
  199273. info_ptr->text[i].text);
  199274. #else
  199275. png_warning(png_ptr, "Unable to write international text");
  199276. #endif
  199277. /* Mark this chunk as written */
  199278. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199279. }
  199280. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199281. {
  199282. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199283. /* write compressed chunk */
  199284. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199285. info_ptr->text[i].text, 0,
  199286. info_ptr->text[i].compression);
  199287. #else
  199288. png_warning(png_ptr, "Unable to write compressed text");
  199289. #endif
  199290. /* Mark this chunk as written */
  199291. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199292. }
  199293. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199294. {
  199295. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199296. /* write uncompressed chunk */
  199297. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199298. info_ptr->text[i].text, 0);
  199299. #else
  199300. png_warning(png_ptr, "Unable to write uncompressed text");
  199301. #endif
  199302. /* Mark this chunk as written */
  199303. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199304. }
  199305. }
  199306. #endif
  199307. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199308. if (info_ptr->unknown_chunks_num)
  199309. {
  199310. png_unknown_chunk *up;
  199311. png_debug(5, "writing extra chunks\n");
  199312. for (up = info_ptr->unknown_chunks;
  199313. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199314. up++)
  199315. {
  199316. int keep=png_handle_as_unknown(png_ptr, up->name);
  199317. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199318. up->location && (up->location & PNG_AFTER_IDAT) &&
  199319. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199320. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199321. {
  199322. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199323. }
  199324. }
  199325. }
  199326. #endif
  199327. }
  199328. png_ptr->mode |= PNG_AFTER_IDAT;
  199329. /* write end of PNG file */
  199330. png_write_IEND(png_ptr);
  199331. }
  199332. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199333. #if !defined(_WIN32_WCE)
  199334. /* "time.h" functions are not supported on WindowsCE */
  199335. void PNGAPI
  199336. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  199337. {
  199338. png_debug(1, "in png_convert_from_struct_tm\n");
  199339. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  199340. ptime->month = (png_byte)(ttime->tm_mon + 1);
  199341. ptime->day = (png_byte)ttime->tm_mday;
  199342. ptime->hour = (png_byte)ttime->tm_hour;
  199343. ptime->minute = (png_byte)ttime->tm_min;
  199344. ptime->second = (png_byte)ttime->tm_sec;
  199345. }
  199346. void PNGAPI
  199347. png_convert_from_time_t(png_timep ptime, time_t ttime)
  199348. {
  199349. struct tm *tbuf;
  199350. png_debug(1, "in png_convert_from_time_t\n");
  199351. tbuf = gmtime(&ttime);
  199352. png_convert_from_struct_tm(ptime, tbuf);
  199353. }
  199354. #endif
  199355. #endif
  199356. /* Initialize png_ptr structure, and allocate any memory needed */
  199357. png_structp PNGAPI
  199358. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  199359. png_error_ptr error_fn, png_error_ptr warn_fn)
  199360. {
  199361. #ifdef PNG_USER_MEM_SUPPORTED
  199362. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  199363. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  199364. }
  199365. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  199366. png_structp PNGAPI
  199367. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  199368. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  199369. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  199370. {
  199371. #endif /* PNG_USER_MEM_SUPPORTED */
  199372. png_structp png_ptr;
  199373. #ifdef PNG_SETJMP_SUPPORTED
  199374. #ifdef USE_FAR_KEYWORD
  199375. jmp_buf jmpbuf;
  199376. #endif
  199377. #endif
  199378. int i;
  199379. png_debug(1, "in png_create_write_struct\n");
  199380. #ifdef PNG_USER_MEM_SUPPORTED
  199381. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  199382. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  199383. #else
  199384. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199385. #endif /* PNG_USER_MEM_SUPPORTED */
  199386. if (png_ptr == NULL)
  199387. return (NULL);
  199388. /* added at libpng-1.2.6 */
  199389. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199390. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199391. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199392. #endif
  199393. #ifdef PNG_SETJMP_SUPPORTED
  199394. #ifdef USE_FAR_KEYWORD
  199395. if (setjmp(jmpbuf))
  199396. #else
  199397. if (setjmp(png_ptr->jmpbuf))
  199398. #endif
  199399. {
  199400. png_free(png_ptr, png_ptr->zbuf);
  199401. png_ptr->zbuf=NULL;
  199402. png_destroy_struct(png_ptr);
  199403. return (NULL);
  199404. }
  199405. #ifdef USE_FAR_KEYWORD
  199406. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199407. #endif
  199408. #endif
  199409. #ifdef PNG_USER_MEM_SUPPORTED
  199410. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  199411. #endif /* PNG_USER_MEM_SUPPORTED */
  199412. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  199413. i=0;
  199414. do
  199415. {
  199416. if(user_png_ver[i] != png_libpng_ver[i])
  199417. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199418. } while (png_libpng_ver[i++]);
  199419. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  199420. {
  199421. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  199422. * we must recompile any applications that use any older library version.
  199423. * For versions after libpng 1.0, we will be compatible, so we need
  199424. * only check the first digit.
  199425. */
  199426. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  199427. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  199428. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  199429. {
  199430. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199431. char msg[80];
  199432. if (user_png_ver)
  199433. {
  199434. png_snprintf(msg, 80,
  199435. "Application was compiled with png.h from libpng-%.20s",
  199436. user_png_ver);
  199437. png_warning(png_ptr, msg);
  199438. }
  199439. png_snprintf(msg, 80,
  199440. "Application is running with png.c from libpng-%.20s",
  199441. png_libpng_ver);
  199442. png_warning(png_ptr, msg);
  199443. #endif
  199444. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199445. png_ptr->flags=0;
  199446. #endif
  199447. png_error(png_ptr,
  199448. "Incompatible libpng version in application and library");
  199449. }
  199450. }
  199451. /* initialize zbuf - compression buffer */
  199452. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199453. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199454. (png_uint_32)png_ptr->zbuf_size);
  199455. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199456. png_flush_ptr_NULL);
  199457. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199458. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199459. 1, png_doublep_NULL, png_doublep_NULL);
  199460. #endif
  199461. #ifdef PNG_SETJMP_SUPPORTED
  199462. /* Applications that neglect to set up their own setjmp() and then encounter
  199463. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  199464. abort instead of returning. */
  199465. #ifdef USE_FAR_KEYWORD
  199466. if (setjmp(jmpbuf))
  199467. PNG_ABORT();
  199468. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  199469. #else
  199470. if (setjmp(png_ptr->jmpbuf))
  199471. PNG_ABORT();
  199472. #endif
  199473. #endif
  199474. return (png_ptr);
  199475. }
  199476. /* Initialize png_ptr structure, and allocate any memory needed */
  199477. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  199478. /* Deprecated. */
  199479. #undef png_write_init
  199480. void PNGAPI
  199481. png_write_init(png_structp png_ptr)
  199482. {
  199483. /* We only come here via pre-1.0.7-compiled applications */
  199484. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  199485. }
  199486. void PNGAPI
  199487. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  199488. png_size_t png_struct_size, png_size_t png_info_size)
  199489. {
  199490. /* We only come here via pre-1.0.12-compiled applications */
  199491. if(png_ptr == NULL) return;
  199492. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  199493. if(png_sizeof(png_struct) > png_struct_size ||
  199494. png_sizeof(png_info) > png_info_size)
  199495. {
  199496. char msg[80];
  199497. png_ptr->warning_fn=NULL;
  199498. if (user_png_ver)
  199499. {
  199500. png_snprintf(msg, 80,
  199501. "Application was compiled with png.h from libpng-%.20s",
  199502. user_png_ver);
  199503. png_warning(png_ptr, msg);
  199504. }
  199505. png_snprintf(msg, 80,
  199506. "Application is running with png.c from libpng-%.20s",
  199507. png_libpng_ver);
  199508. png_warning(png_ptr, msg);
  199509. }
  199510. #endif
  199511. if(png_sizeof(png_struct) > png_struct_size)
  199512. {
  199513. png_ptr->error_fn=NULL;
  199514. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199515. png_ptr->flags=0;
  199516. #endif
  199517. png_error(png_ptr,
  199518. "The png struct allocated by the application for writing is too small.");
  199519. }
  199520. if(png_sizeof(png_info) > png_info_size)
  199521. {
  199522. png_ptr->error_fn=NULL;
  199523. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  199524. png_ptr->flags=0;
  199525. #endif
  199526. png_error(png_ptr,
  199527. "The info struct allocated by the application for writing is too small.");
  199528. }
  199529. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  199530. }
  199531. #endif /* PNG_1_0_X || PNG_1_2_X */
  199532. void PNGAPI
  199533. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  199534. png_size_t png_struct_size)
  199535. {
  199536. png_structp png_ptr=*ptr_ptr;
  199537. #ifdef PNG_SETJMP_SUPPORTED
  199538. jmp_buf tmp_jmp; /* to save current jump buffer */
  199539. #endif
  199540. int i = 0;
  199541. if (png_ptr == NULL)
  199542. return;
  199543. do
  199544. {
  199545. if (user_png_ver[i] != png_libpng_ver[i])
  199546. {
  199547. #ifdef PNG_LEGACY_SUPPORTED
  199548. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  199549. #else
  199550. png_ptr->warning_fn=NULL;
  199551. png_warning(png_ptr,
  199552. "Application uses deprecated png_write_init() and should be recompiled.");
  199553. break;
  199554. #endif
  199555. }
  199556. } while (png_libpng_ver[i++]);
  199557. png_debug(1, "in png_write_init_3\n");
  199558. #ifdef PNG_SETJMP_SUPPORTED
  199559. /* save jump buffer and error functions */
  199560. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199561. #endif
  199562. if (png_sizeof(png_struct) > png_struct_size)
  199563. {
  199564. png_destroy_struct(png_ptr);
  199565. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  199566. *ptr_ptr = png_ptr;
  199567. }
  199568. /* reset all variables to 0 */
  199569. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199570. /* added at libpng-1.2.6 */
  199571. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  199572. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  199573. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  199574. #endif
  199575. #ifdef PNG_SETJMP_SUPPORTED
  199576. /* restore jump buffer */
  199577. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199578. #endif
  199579. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  199580. png_flush_ptr_NULL);
  199581. /* initialize zbuf - compression buffer */
  199582. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  199583. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  199584. (png_uint_32)png_ptr->zbuf_size);
  199585. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199586. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  199587. 1, png_doublep_NULL, png_doublep_NULL);
  199588. #endif
  199589. }
  199590. /* Write a few rows of image data. If the image is interlaced,
  199591. * either you will have to write the 7 sub images, or, if you
  199592. * have called png_set_interlace_handling(), you will have to
  199593. * "write" the image seven times.
  199594. */
  199595. void PNGAPI
  199596. png_write_rows(png_structp png_ptr, png_bytepp row,
  199597. png_uint_32 num_rows)
  199598. {
  199599. png_uint_32 i; /* row counter */
  199600. png_bytepp rp; /* row pointer */
  199601. png_debug(1, "in png_write_rows\n");
  199602. if (png_ptr == NULL)
  199603. return;
  199604. /* loop through the rows */
  199605. for (i = 0, rp = row; i < num_rows; i++, rp++)
  199606. {
  199607. png_write_row(png_ptr, *rp);
  199608. }
  199609. }
  199610. /* Write the image. You only need to call this function once, even
  199611. * if you are writing an interlaced image.
  199612. */
  199613. void PNGAPI
  199614. png_write_image(png_structp png_ptr, png_bytepp image)
  199615. {
  199616. png_uint_32 i; /* row index */
  199617. int pass, num_pass; /* pass variables */
  199618. png_bytepp rp; /* points to current row */
  199619. if (png_ptr == NULL)
  199620. return;
  199621. png_debug(1, "in png_write_image\n");
  199622. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199623. /* intialize interlace handling. If image is not interlaced,
  199624. this will set pass to 1 */
  199625. num_pass = png_set_interlace_handling(png_ptr);
  199626. #else
  199627. num_pass = 1;
  199628. #endif
  199629. /* loop through passes */
  199630. for (pass = 0; pass < num_pass; pass++)
  199631. {
  199632. /* loop through image */
  199633. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  199634. {
  199635. png_write_row(png_ptr, *rp);
  199636. }
  199637. }
  199638. }
  199639. /* called by user to write a row of image data */
  199640. void PNGAPI
  199641. png_write_row(png_structp png_ptr, png_bytep row)
  199642. {
  199643. if (png_ptr == NULL)
  199644. return;
  199645. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  199646. png_ptr->row_number, png_ptr->pass);
  199647. /* initialize transformations and other stuff if first time */
  199648. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  199649. {
  199650. /* make sure we wrote the header info */
  199651. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199652. png_error(png_ptr,
  199653. "png_write_info was never called before png_write_row.");
  199654. /* check for transforms that have been set but were defined out */
  199655. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  199656. if (png_ptr->transformations & PNG_INVERT_MONO)
  199657. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  199658. #endif
  199659. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  199660. if (png_ptr->transformations & PNG_FILLER)
  199661. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  199662. #endif
  199663. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  199664. if (png_ptr->transformations & PNG_PACKSWAP)
  199665. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  199666. #endif
  199667. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  199668. if (png_ptr->transformations & PNG_PACK)
  199669. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  199670. #endif
  199671. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  199672. if (png_ptr->transformations & PNG_SHIFT)
  199673. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  199674. #endif
  199675. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  199676. if (png_ptr->transformations & PNG_BGR)
  199677. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  199678. #endif
  199679. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  199680. if (png_ptr->transformations & PNG_SWAP_BYTES)
  199681. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  199682. #endif
  199683. png_write_start_row(png_ptr);
  199684. }
  199685. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199686. /* if interlaced and not interested in row, return */
  199687. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  199688. {
  199689. switch (png_ptr->pass)
  199690. {
  199691. case 0:
  199692. if (png_ptr->row_number & 0x07)
  199693. {
  199694. png_write_finish_row(png_ptr);
  199695. return;
  199696. }
  199697. break;
  199698. case 1:
  199699. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  199700. {
  199701. png_write_finish_row(png_ptr);
  199702. return;
  199703. }
  199704. break;
  199705. case 2:
  199706. if ((png_ptr->row_number & 0x07) != 4)
  199707. {
  199708. png_write_finish_row(png_ptr);
  199709. return;
  199710. }
  199711. break;
  199712. case 3:
  199713. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  199714. {
  199715. png_write_finish_row(png_ptr);
  199716. return;
  199717. }
  199718. break;
  199719. case 4:
  199720. if ((png_ptr->row_number & 0x03) != 2)
  199721. {
  199722. png_write_finish_row(png_ptr);
  199723. return;
  199724. }
  199725. break;
  199726. case 5:
  199727. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  199728. {
  199729. png_write_finish_row(png_ptr);
  199730. return;
  199731. }
  199732. break;
  199733. case 6:
  199734. if (!(png_ptr->row_number & 0x01))
  199735. {
  199736. png_write_finish_row(png_ptr);
  199737. return;
  199738. }
  199739. break;
  199740. }
  199741. }
  199742. #endif
  199743. /* set up row info for transformations */
  199744. png_ptr->row_info.color_type = png_ptr->color_type;
  199745. png_ptr->row_info.width = png_ptr->usr_width;
  199746. png_ptr->row_info.channels = png_ptr->usr_channels;
  199747. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  199748. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  199749. png_ptr->row_info.channels);
  199750. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  199751. png_ptr->row_info.width);
  199752. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  199753. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  199754. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  199755. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  199756. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  199757. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  199758. /* Copy user's row into buffer, leaving room for filter byte. */
  199759. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  199760. png_ptr->row_info.rowbytes);
  199761. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199762. /* handle interlacing */
  199763. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  199764. (png_ptr->transformations & PNG_INTERLACE))
  199765. {
  199766. png_do_write_interlace(&(png_ptr->row_info),
  199767. png_ptr->row_buf + 1, png_ptr->pass);
  199768. /* this should always get caught above, but still ... */
  199769. if (!(png_ptr->row_info.width))
  199770. {
  199771. png_write_finish_row(png_ptr);
  199772. return;
  199773. }
  199774. }
  199775. #endif
  199776. /* handle other transformations */
  199777. if (png_ptr->transformations)
  199778. png_do_write_transformations(png_ptr);
  199779. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199780. /* Write filter_method 64 (intrapixel differencing) only if
  199781. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  199782. * 2. Libpng did not write a PNG signature (this filter_method is only
  199783. * used in PNG datastreams that are embedded in MNG datastreams) and
  199784. * 3. The application called png_permit_mng_features with a mask that
  199785. * included PNG_FLAG_MNG_FILTER_64 and
  199786. * 4. The filter_method is 64 and
  199787. * 5. The color_type is RGB or RGBA
  199788. */
  199789. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199790. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  199791. {
  199792. /* Intrapixel differencing */
  199793. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  199794. }
  199795. #endif
  199796. /* Find a filter if necessary, filter the row and write it out. */
  199797. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  199798. if (png_ptr->write_row_fn != NULL)
  199799. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  199800. }
  199801. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199802. /* Set the automatic flush interval or 0 to turn flushing off */
  199803. void PNGAPI
  199804. png_set_flush(png_structp png_ptr, int nrows)
  199805. {
  199806. png_debug(1, "in png_set_flush\n");
  199807. if (png_ptr == NULL)
  199808. return;
  199809. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  199810. }
  199811. /* flush the current output buffers now */
  199812. void PNGAPI
  199813. png_write_flush(png_structp png_ptr)
  199814. {
  199815. int wrote_IDAT;
  199816. png_debug(1, "in png_write_flush\n");
  199817. if (png_ptr == NULL)
  199818. return;
  199819. /* We have already written out all of the data */
  199820. if (png_ptr->row_number >= png_ptr->num_rows)
  199821. return;
  199822. do
  199823. {
  199824. int ret;
  199825. /* compress the data */
  199826. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  199827. wrote_IDAT = 0;
  199828. /* check for compression errors */
  199829. if (ret != Z_OK)
  199830. {
  199831. if (png_ptr->zstream.msg != NULL)
  199832. png_error(png_ptr, png_ptr->zstream.msg);
  199833. else
  199834. png_error(png_ptr, "zlib error");
  199835. }
  199836. if (!(png_ptr->zstream.avail_out))
  199837. {
  199838. /* write the IDAT and reset the zlib output buffer */
  199839. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199840. png_ptr->zbuf_size);
  199841. png_ptr->zstream.next_out = png_ptr->zbuf;
  199842. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199843. wrote_IDAT = 1;
  199844. }
  199845. } while(wrote_IDAT == 1);
  199846. /* If there is any data left to be output, write it into a new IDAT */
  199847. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  199848. {
  199849. /* write the IDAT and reset the zlib output buffer */
  199850. png_write_IDAT(png_ptr, png_ptr->zbuf,
  199851. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  199852. png_ptr->zstream.next_out = png_ptr->zbuf;
  199853. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  199854. }
  199855. png_ptr->flush_rows = 0;
  199856. png_flush(png_ptr);
  199857. }
  199858. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199859. /* free all memory used by the write */
  199860. void PNGAPI
  199861. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  199862. {
  199863. png_structp png_ptr = NULL;
  199864. png_infop info_ptr = NULL;
  199865. #ifdef PNG_USER_MEM_SUPPORTED
  199866. png_free_ptr free_fn = NULL;
  199867. png_voidp mem_ptr = NULL;
  199868. #endif
  199869. png_debug(1, "in png_destroy_write_struct\n");
  199870. if (png_ptr_ptr != NULL)
  199871. {
  199872. png_ptr = *png_ptr_ptr;
  199873. #ifdef PNG_USER_MEM_SUPPORTED
  199874. free_fn = png_ptr->free_fn;
  199875. mem_ptr = png_ptr->mem_ptr;
  199876. #endif
  199877. }
  199878. if (info_ptr_ptr != NULL)
  199879. info_ptr = *info_ptr_ptr;
  199880. if (info_ptr != NULL)
  199881. {
  199882. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  199883. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  199884. if (png_ptr->num_chunk_list)
  199885. {
  199886. png_free(png_ptr, png_ptr->chunk_list);
  199887. png_ptr->chunk_list=NULL;
  199888. png_ptr->num_chunk_list=0;
  199889. }
  199890. #endif
  199891. #ifdef PNG_USER_MEM_SUPPORTED
  199892. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  199893. (png_voidp)mem_ptr);
  199894. #else
  199895. png_destroy_struct((png_voidp)info_ptr);
  199896. #endif
  199897. *info_ptr_ptr = NULL;
  199898. }
  199899. if (png_ptr != NULL)
  199900. {
  199901. png_write_destroy(png_ptr);
  199902. #ifdef PNG_USER_MEM_SUPPORTED
  199903. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  199904. (png_voidp)mem_ptr);
  199905. #else
  199906. png_destroy_struct((png_voidp)png_ptr);
  199907. #endif
  199908. *png_ptr_ptr = NULL;
  199909. }
  199910. }
  199911. /* Free any memory used in png_ptr struct (old method) */
  199912. void /* PRIVATE */
  199913. png_write_destroy(png_structp png_ptr)
  199914. {
  199915. #ifdef PNG_SETJMP_SUPPORTED
  199916. jmp_buf tmp_jmp; /* save jump buffer */
  199917. #endif
  199918. png_error_ptr error_fn;
  199919. png_error_ptr warning_fn;
  199920. png_voidp error_ptr;
  199921. #ifdef PNG_USER_MEM_SUPPORTED
  199922. png_free_ptr free_fn;
  199923. #endif
  199924. png_debug(1, "in png_write_destroy\n");
  199925. /* free any memory zlib uses */
  199926. deflateEnd(&png_ptr->zstream);
  199927. /* free our memory. png_free checks NULL for us. */
  199928. png_free(png_ptr, png_ptr->zbuf);
  199929. png_free(png_ptr, png_ptr->row_buf);
  199930. png_free(png_ptr, png_ptr->prev_row);
  199931. png_free(png_ptr, png_ptr->sub_row);
  199932. png_free(png_ptr, png_ptr->up_row);
  199933. png_free(png_ptr, png_ptr->avg_row);
  199934. png_free(png_ptr, png_ptr->paeth_row);
  199935. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  199936. png_free(png_ptr, png_ptr->time_buffer);
  199937. #endif
  199938. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  199939. png_free(png_ptr, png_ptr->prev_filters);
  199940. png_free(png_ptr, png_ptr->filter_weights);
  199941. png_free(png_ptr, png_ptr->inv_filter_weights);
  199942. png_free(png_ptr, png_ptr->filter_costs);
  199943. png_free(png_ptr, png_ptr->inv_filter_costs);
  199944. #endif
  199945. #ifdef PNG_SETJMP_SUPPORTED
  199946. /* reset structure */
  199947. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  199948. #endif
  199949. error_fn = png_ptr->error_fn;
  199950. warning_fn = png_ptr->warning_fn;
  199951. error_ptr = png_ptr->error_ptr;
  199952. #ifdef PNG_USER_MEM_SUPPORTED
  199953. free_fn = png_ptr->free_fn;
  199954. #endif
  199955. png_memset(png_ptr, 0, png_sizeof (png_struct));
  199956. png_ptr->error_fn = error_fn;
  199957. png_ptr->warning_fn = warning_fn;
  199958. png_ptr->error_ptr = error_ptr;
  199959. #ifdef PNG_USER_MEM_SUPPORTED
  199960. png_ptr->free_fn = free_fn;
  199961. #endif
  199962. #ifdef PNG_SETJMP_SUPPORTED
  199963. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  199964. #endif
  199965. }
  199966. /* Allow the application to select one or more row filters to use. */
  199967. void PNGAPI
  199968. png_set_filter(png_structp png_ptr, int method, int filters)
  199969. {
  199970. png_debug(1, "in png_set_filter\n");
  199971. if (png_ptr == NULL)
  199972. return;
  199973. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199974. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  199975. (method == PNG_INTRAPIXEL_DIFFERENCING))
  199976. method = PNG_FILTER_TYPE_BASE;
  199977. #endif
  199978. if (method == PNG_FILTER_TYPE_BASE)
  199979. {
  199980. switch (filters & (PNG_ALL_FILTERS | 0x07))
  199981. {
  199982. #ifndef PNG_NO_WRITE_FILTER
  199983. case 5:
  199984. case 6:
  199985. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  199986. #endif /* PNG_NO_WRITE_FILTER */
  199987. case PNG_FILTER_VALUE_NONE:
  199988. png_ptr->do_filter=PNG_FILTER_NONE; break;
  199989. #ifndef PNG_NO_WRITE_FILTER
  199990. case PNG_FILTER_VALUE_SUB:
  199991. png_ptr->do_filter=PNG_FILTER_SUB; break;
  199992. case PNG_FILTER_VALUE_UP:
  199993. png_ptr->do_filter=PNG_FILTER_UP; break;
  199994. case PNG_FILTER_VALUE_AVG:
  199995. png_ptr->do_filter=PNG_FILTER_AVG; break;
  199996. case PNG_FILTER_VALUE_PAETH:
  199997. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  199998. default: png_ptr->do_filter = (png_byte)filters; break;
  199999. #else
  200000. default: png_warning(png_ptr, "Unknown row filter for method 0");
  200001. #endif /* PNG_NO_WRITE_FILTER */
  200002. }
  200003. /* If we have allocated the row_buf, this means we have already started
  200004. * with the image and we should have allocated all of the filter buffers
  200005. * that have been selected. If prev_row isn't already allocated, then
  200006. * it is too late to start using the filters that need it, since we
  200007. * will be missing the data in the previous row. If an application
  200008. * wants to start and stop using particular filters during compression,
  200009. * it should start out with all of the filters, and then add and
  200010. * remove them after the start of compression.
  200011. */
  200012. if (png_ptr->row_buf != NULL)
  200013. {
  200014. #ifndef PNG_NO_WRITE_FILTER
  200015. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  200016. {
  200017. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  200018. (png_ptr->rowbytes + 1));
  200019. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  200020. }
  200021. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  200022. {
  200023. if (png_ptr->prev_row == NULL)
  200024. {
  200025. png_warning(png_ptr, "Can't add Up filter after starting");
  200026. png_ptr->do_filter &= ~PNG_FILTER_UP;
  200027. }
  200028. else
  200029. {
  200030. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  200031. (png_ptr->rowbytes + 1));
  200032. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  200033. }
  200034. }
  200035. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200036. {
  200037. if (png_ptr->prev_row == NULL)
  200038. {
  200039. png_warning(png_ptr, "Can't add Average filter after starting");
  200040. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200041. }
  200042. else
  200043. {
  200044. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200045. (png_ptr->rowbytes + 1));
  200046. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200047. }
  200048. }
  200049. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200050. png_ptr->paeth_row == NULL)
  200051. {
  200052. if (png_ptr->prev_row == NULL)
  200053. {
  200054. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200055. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200056. }
  200057. else
  200058. {
  200059. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200060. (png_ptr->rowbytes + 1));
  200061. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200062. }
  200063. }
  200064. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200065. #endif /* PNG_NO_WRITE_FILTER */
  200066. png_ptr->do_filter = PNG_FILTER_NONE;
  200067. }
  200068. }
  200069. else
  200070. png_error(png_ptr, "Unknown custom filter method");
  200071. }
  200072. /* This allows us to influence the way in which libpng chooses the "best"
  200073. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200074. * differences metric is relatively fast and effective, there is some
  200075. * question as to whether it can be improved upon by trying to keep the
  200076. * filtered data going to zlib more consistent, hopefully resulting in
  200077. * better compression.
  200078. */
  200079. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200080. void PNGAPI
  200081. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200082. int num_weights, png_doublep filter_weights,
  200083. png_doublep filter_costs)
  200084. {
  200085. int i;
  200086. png_debug(1, "in png_set_filter_heuristics\n");
  200087. if (png_ptr == NULL)
  200088. return;
  200089. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200090. {
  200091. png_warning(png_ptr, "Unknown filter heuristic method");
  200092. return;
  200093. }
  200094. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200095. {
  200096. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200097. }
  200098. if (num_weights < 0 || filter_weights == NULL ||
  200099. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200100. {
  200101. num_weights = 0;
  200102. }
  200103. png_ptr->num_prev_filters = (png_byte)num_weights;
  200104. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200105. if (num_weights > 0)
  200106. {
  200107. if (png_ptr->prev_filters == NULL)
  200108. {
  200109. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200110. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200111. /* To make sure that the weighting starts out fairly */
  200112. for (i = 0; i < num_weights; i++)
  200113. {
  200114. png_ptr->prev_filters[i] = 255;
  200115. }
  200116. }
  200117. if (png_ptr->filter_weights == NULL)
  200118. {
  200119. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200120. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200121. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200122. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200123. for (i = 0; i < num_weights; i++)
  200124. {
  200125. png_ptr->inv_filter_weights[i] =
  200126. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200127. }
  200128. }
  200129. for (i = 0; i < num_weights; i++)
  200130. {
  200131. if (filter_weights[i] < 0.0)
  200132. {
  200133. png_ptr->inv_filter_weights[i] =
  200134. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200135. }
  200136. else
  200137. {
  200138. png_ptr->inv_filter_weights[i] =
  200139. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200140. png_ptr->filter_weights[i] =
  200141. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200142. }
  200143. }
  200144. }
  200145. /* If, in the future, there are other filter methods, this would
  200146. * need to be based on png_ptr->filter.
  200147. */
  200148. if (png_ptr->filter_costs == NULL)
  200149. {
  200150. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200151. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200152. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200153. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200154. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200155. {
  200156. png_ptr->inv_filter_costs[i] =
  200157. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200158. }
  200159. }
  200160. /* Here is where we set the relative costs of the different filters. We
  200161. * should take the desired compression level into account when setting
  200162. * the costs, so that Paeth, for instance, has a high relative cost at low
  200163. * compression levels, while it has a lower relative cost at higher
  200164. * compression settings. The filter types are in order of increasing
  200165. * relative cost, so it would be possible to do this with an algorithm.
  200166. */
  200167. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200168. {
  200169. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200170. {
  200171. png_ptr->inv_filter_costs[i] =
  200172. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200173. }
  200174. else if (filter_costs[i] >= 1.0)
  200175. {
  200176. png_ptr->inv_filter_costs[i] =
  200177. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200178. png_ptr->filter_costs[i] =
  200179. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200180. }
  200181. }
  200182. }
  200183. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200184. void PNGAPI
  200185. png_set_compression_level(png_structp png_ptr, int level)
  200186. {
  200187. png_debug(1, "in png_set_compression_level\n");
  200188. if (png_ptr == NULL)
  200189. return;
  200190. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200191. png_ptr->zlib_level = level;
  200192. }
  200193. void PNGAPI
  200194. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200195. {
  200196. png_debug(1, "in png_set_compression_mem_level\n");
  200197. if (png_ptr == NULL)
  200198. return;
  200199. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200200. png_ptr->zlib_mem_level = mem_level;
  200201. }
  200202. void PNGAPI
  200203. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200204. {
  200205. png_debug(1, "in png_set_compression_strategy\n");
  200206. if (png_ptr == NULL)
  200207. return;
  200208. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200209. png_ptr->zlib_strategy = strategy;
  200210. }
  200211. void PNGAPI
  200212. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200213. {
  200214. if (png_ptr == NULL)
  200215. return;
  200216. if (window_bits > 15)
  200217. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200218. else if (window_bits < 8)
  200219. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200220. #ifndef WBITS_8_OK
  200221. /* avoid libpng bug with 256-byte windows */
  200222. if (window_bits == 8)
  200223. {
  200224. png_warning(png_ptr, "Compression window is being reset to 512");
  200225. window_bits=9;
  200226. }
  200227. #endif
  200228. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200229. png_ptr->zlib_window_bits = window_bits;
  200230. }
  200231. void PNGAPI
  200232. png_set_compression_method(png_structp png_ptr, int method)
  200233. {
  200234. png_debug(1, "in png_set_compression_method\n");
  200235. if (png_ptr == NULL)
  200236. return;
  200237. if (method != 8)
  200238. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200239. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200240. png_ptr->zlib_method = method;
  200241. }
  200242. void PNGAPI
  200243. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200244. {
  200245. if (png_ptr == NULL)
  200246. return;
  200247. png_ptr->write_row_fn = write_row_fn;
  200248. }
  200249. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200250. void PNGAPI
  200251. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200252. write_user_transform_fn)
  200253. {
  200254. png_debug(1, "in png_set_write_user_transform_fn\n");
  200255. if (png_ptr == NULL)
  200256. return;
  200257. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200258. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200259. }
  200260. #endif
  200261. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200262. void PNGAPI
  200263. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200264. int transforms, voidp params)
  200265. {
  200266. if (png_ptr == NULL || info_ptr == NULL)
  200267. return;
  200268. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200269. /* invert the alpha channel from opacity to transparency */
  200270. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200271. png_set_invert_alpha(png_ptr);
  200272. #endif
  200273. /* Write the file header information. */
  200274. png_write_info(png_ptr, info_ptr);
  200275. /* ------ these transformations don't touch the info structure ------- */
  200276. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200277. /* invert monochrome pixels */
  200278. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200279. png_set_invert_mono(png_ptr);
  200280. #endif
  200281. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200282. /* Shift the pixels up to a legal bit depth and fill in
  200283. * as appropriate to correctly scale the image.
  200284. */
  200285. if ((transforms & PNG_TRANSFORM_SHIFT)
  200286. && (info_ptr->valid & PNG_INFO_sBIT))
  200287. png_set_shift(png_ptr, &info_ptr->sig_bit);
  200288. #endif
  200289. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200290. /* pack pixels into bytes */
  200291. if (transforms & PNG_TRANSFORM_PACKING)
  200292. png_set_packing(png_ptr);
  200293. #endif
  200294. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200295. /* swap location of alpha bytes from ARGB to RGBA */
  200296. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  200297. png_set_swap_alpha(png_ptr);
  200298. #endif
  200299. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200300. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  200301. * RGB (4 channels -> 3 channels). The second parameter is not used.
  200302. */
  200303. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  200304. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  200305. #endif
  200306. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200307. /* flip BGR pixels to RGB */
  200308. if (transforms & PNG_TRANSFORM_BGR)
  200309. png_set_bgr(png_ptr);
  200310. #endif
  200311. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200312. /* swap bytes of 16-bit files to most significant byte first */
  200313. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  200314. png_set_swap(png_ptr);
  200315. #endif
  200316. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200317. /* swap bits of 1, 2, 4 bit packed pixel formats */
  200318. if (transforms & PNG_TRANSFORM_PACKSWAP)
  200319. png_set_packswap(png_ptr);
  200320. #endif
  200321. /* ----------------------- end of transformations ------------------- */
  200322. /* write the bits */
  200323. if (info_ptr->valid & PNG_INFO_IDAT)
  200324. png_write_image(png_ptr, info_ptr->row_pointers);
  200325. /* It is REQUIRED to call this to finish writing the rest of the file */
  200326. png_write_end(png_ptr, info_ptr);
  200327. transforms = transforms; /* quiet compiler warnings */
  200328. params = params;
  200329. }
  200330. #endif
  200331. #endif /* PNG_WRITE_SUPPORTED */
  200332. /*** End of inlined file: pngwrite.c ***/
  200333. /*** Start of inlined file: pngwtran.c ***/
  200334. /* pngwtran.c - transforms the data in a row for PNG writers
  200335. *
  200336. * Last changed in libpng 1.2.9 April 14, 2006
  200337. * For conditions of distribution and use, see copyright notice in png.h
  200338. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  200339. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200340. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200341. */
  200342. #define PNG_INTERNAL
  200343. #ifdef PNG_WRITE_SUPPORTED
  200344. /* Transform the data according to the user's wishes. The order of
  200345. * transformations is significant.
  200346. */
  200347. void /* PRIVATE */
  200348. png_do_write_transformations(png_structp png_ptr)
  200349. {
  200350. png_debug(1, "in png_do_write_transformations\n");
  200351. if (png_ptr == NULL)
  200352. return;
  200353. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200354. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  200355. if(png_ptr->write_user_transform_fn != NULL)
  200356. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  200357. (png_ptr, /* png_ptr */
  200358. &(png_ptr->row_info), /* row_info: */
  200359. /* png_uint_32 width; width of row */
  200360. /* png_uint_32 rowbytes; number of bytes in row */
  200361. /* png_byte color_type; color type of pixels */
  200362. /* png_byte bit_depth; bit depth of samples */
  200363. /* png_byte channels; number of channels (1-4) */
  200364. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  200365. png_ptr->row_buf + 1); /* start of pixel data for row */
  200366. #endif
  200367. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  200368. if (png_ptr->transformations & PNG_FILLER)
  200369. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200370. png_ptr->flags);
  200371. #endif
  200372. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  200373. if (png_ptr->transformations & PNG_PACKSWAP)
  200374. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200375. #endif
  200376. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200377. if (png_ptr->transformations & PNG_PACK)
  200378. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200379. (png_uint_32)png_ptr->bit_depth);
  200380. #endif
  200381. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  200382. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200383. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200384. #endif
  200385. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200386. if (png_ptr->transformations & PNG_SHIFT)
  200387. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  200388. &(png_ptr->shift));
  200389. #endif
  200390. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200391. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  200392. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200393. #endif
  200394. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200395. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  200396. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200397. #endif
  200398. #if defined(PNG_WRITE_BGR_SUPPORTED)
  200399. if (png_ptr->transformations & PNG_BGR)
  200400. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200401. #endif
  200402. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200403. if (png_ptr->transformations & PNG_INVERT_MONO)
  200404. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200405. #endif
  200406. }
  200407. #if defined(PNG_WRITE_PACK_SUPPORTED)
  200408. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  200409. * row_info bit depth should be 8 (one pixel per byte). The channels
  200410. * should be 1 (this only happens on grayscale and paletted images).
  200411. */
  200412. void /* PRIVATE */
  200413. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  200414. {
  200415. png_debug(1, "in png_do_pack\n");
  200416. if (row_info->bit_depth == 8 &&
  200417. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200418. row != NULL && row_info != NULL &&
  200419. #endif
  200420. row_info->channels == 1)
  200421. {
  200422. switch ((int)bit_depth)
  200423. {
  200424. case 1:
  200425. {
  200426. png_bytep sp, dp;
  200427. int mask, v;
  200428. png_uint_32 i;
  200429. png_uint_32 row_width = row_info->width;
  200430. sp = row;
  200431. dp = row;
  200432. mask = 0x80;
  200433. v = 0;
  200434. for (i = 0; i < row_width; i++)
  200435. {
  200436. if (*sp != 0)
  200437. v |= mask;
  200438. sp++;
  200439. if (mask > 1)
  200440. mask >>= 1;
  200441. else
  200442. {
  200443. mask = 0x80;
  200444. *dp = (png_byte)v;
  200445. dp++;
  200446. v = 0;
  200447. }
  200448. }
  200449. if (mask != 0x80)
  200450. *dp = (png_byte)v;
  200451. break;
  200452. }
  200453. case 2:
  200454. {
  200455. png_bytep sp, dp;
  200456. int shift, v;
  200457. png_uint_32 i;
  200458. png_uint_32 row_width = row_info->width;
  200459. sp = row;
  200460. dp = row;
  200461. shift = 6;
  200462. v = 0;
  200463. for (i = 0; i < row_width; i++)
  200464. {
  200465. png_byte value;
  200466. value = (png_byte)(*sp & 0x03);
  200467. v |= (value << shift);
  200468. if (shift == 0)
  200469. {
  200470. shift = 6;
  200471. *dp = (png_byte)v;
  200472. dp++;
  200473. v = 0;
  200474. }
  200475. else
  200476. shift -= 2;
  200477. sp++;
  200478. }
  200479. if (shift != 6)
  200480. *dp = (png_byte)v;
  200481. break;
  200482. }
  200483. case 4:
  200484. {
  200485. png_bytep sp, dp;
  200486. int shift, v;
  200487. png_uint_32 i;
  200488. png_uint_32 row_width = row_info->width;
  200489. sp = row;
  200490. dp = row;
  200491. shift = 4;
  200492. v = 0;
  200493. for (i = 0; i < row_width; i++)
  200494. {
  200495. png_byte value;
  200496. value = (png_byte)(*sp & 0x0f);
  200497. v |= (value << shift);
  200498. if (shift == 0)
  200499. {
  200500. shift = 4;
  200501. *dp = (png_byte)v;
  200502. dp++;
  200503. v = 0;
  200504. }
  200505. else
  200506. shift -= 4;
  200507. sp++;
  200508. }
  200509. if (shift != 4)
  200510. *dp = (png_byte)v;
  200511. break;
  200512. }
  200513. }
  200514. row_info->bit_depth = (png_byte)bit_depth;
  200515. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  200516. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  200517. row_info->width);
  200518. }
  200519. }
  200520. #endif
  200521. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200522. /* Shift pixel values to take advantage of whole range. Pass the
  200523. * true number of bits in bit_depth. The row should be packed
  200524. * according to row_info->bit_depth. Thus, if you had a row of
  200525. * bit depth 4, but the pixels only had values from 0 to 7, you
  200526. * would pass 3 as bit_depth, and this routine would translate the
  200527. * data to 0 to 15.
  200528. */
  200529. void /* PRIVATE */
  200530. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  200531. {
  200532. png_debug(1, "in png_do_shift\n");
  200533. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200534. if (row != NULL && row_info != NULL &&
  200535. #else
  200536. if (
  200537. #endif
  200538. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  200539. {
  200540. int shift_start[4], shift_dec[4];
  200541. int channels = 0;
  200542. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  200543. {
  200544. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  200545. shift_dec[channels] = bit_depth->red;
  200546. channels++;
  200547. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  200548. shift_dec[channels] = bit_depth->green;
  200549. channels++;
  200550. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  200551. shift_dec[channels] = bit_depth->blue;
  200552. channels++;
  200553. }
  200554. else
  200555. {
  200556. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  200557. shift_dec[channels] = bit_depth->gray;
  200558. channels++;
  200559. }
  200560. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  200561. {
  200562. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  200563. shift_dec[channels] = bit_depth->alpha;
  200564. channels++;
  200565. }
  200566. /* with low row depths, could only be grayscale, so one channel */
  200567. if (row_info->bit_depth < 8)
  200568. {
  200569. png_bytep bp = row;
  200570. png_uint_32 i;
  200571. png_byte mask;
  200572. png_uint_32 row_bytes = row_info->rowbytes;
  200573. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  200574. mask = 0x55;
  200575. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  200576. mask = 0x11;
  200577. else
  200578. mask = 0xff;
  200579. for (i = 0; i < row_bytes; i++, bp++)
  200580. {
  200581. png_uint_16 v;
  200582. int j;
  200583. v = *bp;
  200584. *bp = 0;
  200585. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  200586. {
  200587. if (j > 0)
  200588. *bp |= (png_byte)((v << j) & 0xff);
  200589. else
  200590. *bp |= (png_byte)((v >> (-j)) & mask);
  200591. }
  200592. }
  200593. }
  200594. else if (row_info->bit_depth == 8)
  200595. {
  200596. png_bytep bp = row;
  200597. png_uint_32 i;
  200598. png_uint_32 istop = channels * row_info->width;
  200599. for (i = 0; i < istop; i++, bp++)
  200600. {
  200601. png_uint_16 v;
  200602. int j;
  200603. int c = (int)(i%channels);
  200604. v = *bp;
  200605. *bp = 0;
  200606. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200607. {
  200608. if (j > 0)
  200609. *bp |= (png_byte)((v << j) & 0xff);
  200610. else
  200611. *bp |= (png_byte)((v >> (-j)) & 0xff);
  200612. }
  200613. }
  200614. }
  200615. else
  200616. {
  200617. png_bytep bp;
  200618. png_uint_32 i;
  200619. png_uint_32 istop = channels * row_info->width;
  200620. for (bp = row, i = 0; i < istop; i++)
  200621. {
  200622. int c = (int)(i%channels);
  200623. png_uint_16 value, v;
  200624. int j;
  200625. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  200626. value = 0;
  200627. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  200628. {
  200629. if (j > 0)
  200630. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  200631. else
  200632. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  200633. }
  200634. *bp++ = (png_byte)(value >> 8);
  200635. *bp++ = (png_byte)(value & 0xff);
  200636. }
  200637. }
  200638. }
  200639. }
  200640. #endif
  200641. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  200642. void /* PRIVATE */
  200643. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  200644. {
  200645. png_debug(1, "in png_do_write_swap_alpha\n");
  200646. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200647. if (row != NULL && row_info != NULL)
  200648. #endif
  200649. {
  200650. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200651. {
  200652. /* This converts from ARGB to RGBA */
  200653. if (row_info->bit_depth == 8)
  200654. {
  200655. png_bytep sp, dp;
  200656. png_uint_32 i;
  200657. png_uint_32 row_width = row_info->width;
  200658. for (i = 0, sp = dp = row; i < row_width; i++)
  200659. {
  200660. png_byte save = *(sp++);
  200661. *(dp++) = *(sp++);
  200662. *(dp++) = *(sp++);
  200663. *(dp++) = *(sp++);
  200664. *(dp++) = save;
  200665. }
  200666. }
  200667. /* This converts from AARRGGBB to RRGGBBAA */
  200668. else
  200669. {
  200670. png_bytep sp, dp;
  200671. png_uint_32 i;
  200672. png_uint_32 row_width = row_info->width;
  200673. for (i = 0, sp = dp = row; i < row_width; i++)
  200674. {
  200675. png_byte save[2];
  200676. save[0] = *(sp++);
  200677. save[1] = *(sp++);
  200678. *(dp++) = *(sp++);
  200679. *(dp++) = *(sp++);
  200680. *(dp++) = *(sp++);
  200681. *(dp++) = *(sp++);
  200682. *(dp++) = *(sp++);
  200683. *(dp++) = *(sp++);
  200684. *(dp++) = save[0];
  200685. *(dp++) = save[1];
  200686. }
  200687. }
  200688. }
  200689. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200690. {
  200691. /* This converts from AG to GA */
  200692. if (row_info->bit_depth == 8)
  200693. {
  200694. png_bytep sp, dp;
  200695. png_uint_32 i;
  200696. png_uint_32 row_width = row_info->width;
  200697. for (i = 0, sp = dp = row; i < row_width; i++)
  200698. {
  200699. png_byte save = *(sp++);
  200700. *(dp++) = *(sp++);
  200701. *(dp++) = save;
  200702. }
  200703. }
  200704. /* This converts from AAGG to GGAA */
  200705. else
  200706. {
  200707. png_bytep sp, dp;
  200708. png_uint_32 i;
  200709. png_uint_32 row_width = row_info->width;
  200710. for (i = 0, sp = dp = row; i < row_width; i++)
  200711. {
  200712. png_byte save[2];
  200713. save[0] = *(sp++);
  200714. save[1] = *(sp++);
  200715. *(dp++) = *(sp++);
  200716. *(dp++) = *(sp++);
  200717. *(dp++) = save[0];
  200718. *(dp++) = save[1];
  200719. }
  200720. }
  200721. }
  200722. }
  200723. }
  200724. #endif
  200725. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200726. void /* PRIVATE */
  200727. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  200728. {
  200729. png_debug(1, "in png_do_write_invert_alpha\n");
  200730. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200731. if (row != NULL && row_info != NULL)
  200732. #endif
  200733. {
  200734. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200735. {
  200736. /* This inverts the alpha channel in RGBA */
  200737. if (row_info->bit_depth == 8)
  200738. {
  200739. png_bytep sp, dp;
  200740. png_uint_32 i;
  200741. png_uint_32 row_width = row_info->width;
  200742. for (i = 0, sp = dp = row; i < row_width; i++)
  200743. {
  200744. /* does nothing
  200745. *(dp++) = *(sp++);
  200746. *(dp++) = *(sp++);
  200747. *(dp++) = *(sp++);
  200748. */
  200749. sp+=3; dp = sp;
  200750. *(dp++) = (png_byte)(255 - *(sp++));
  200751. }
  200752. }
  200753. /* This inverts the alpha channel in RRGGBBAA */
  200754. else
  200755. {
  200756. png_bytep sp, dp;
  200757. png_uint_32 i;
  200758. png_uint_32 row_width = row_info->width;
  200759. for (i = 0, sp = dp = row; i < row_width; i++)
  200760. {
  200761. /* does nothing
  200762. *(dp++) = *(sp++);
  200763. *(dp++) = *(sp++);
  200764. *(dp++) = *(sp++);
  200765. *(dp++) = *(sp++);
  200766. *(dp++) = *(sp++);
  200767. *(dp++) = *(sp++);
  200768. */
  200769. sp+=6; dp = sp;
  200770. *(dp++) = (png_byte)(255 - *(sp++));
  200771. *(dp++) = (png_byte)(255 - *(sp++));
  200772. }
  200773. }
  200774. }
  200775. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  200776. {
  200777. /* This inverts the alpha channel in GA */
  200778. if (row_info->bit_depth == 8)
  200779. {
  200780. png_bytep sp, dp;
  200781. png_uint_32 i;
  200782. png_uint_32 row_width = row_info->width;
  200783. for (i = 0, sp = dp = row; i < row_width; i++)
  200784. {
  200785. *(dp++) = *(sp++);
  200786. *(dp++) = (png_byte)(255 - *(sp++));
  200787. }
  200788. }
  200789. /* This inverts the alpha channel in GGAA */
  200790. else
  200791. {
  200792. png_bytep sp, dp;
  200793. png_uint_32 i;
  200794. png_uint_32 row_width = row_info->width;
  200795. for (i = 0, sp = dp = row; i < row_width; i++)
  200796. {
  200797. /* does nothing
  200798. *(dp++) = *(sp++);
  200799. *(dp++) = *(sp++);
  200800. */
  200801. sp+=2; dp = sp;
  200802. *(dp++) = (png_byte)(255 - *(sp++));
  200803. *(dp++) = (png_byte)(255 - *(sp++));
  200804. }
  200805. }
  200806. }
  200807. }
  200808. }
  200809. #endif
  200810. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200811. /* undoes intrapixel differencing */
  200812. void /* PRIVATE */
  200813. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  200814. {
  200815. png_debug(1, "in png_do_write_intrapixel\n");
  200816. if (
  200817. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  200818. row != NULL && row_info != NULL &&
  200819. #endif
  200820. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  200821. {
  200822. int bytes_per_pixel;
  200823. png_uint_32 row_width = row_info->width;
  200824. if (row_info->bit_depth == 8)
  200825. {
  200826. png_bytep rp;
  200827. png_uint_32 i;
  200828. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200829. bytes_per_pixel = 3;
  200830. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200831. bytes_per_pixel = 4;
  200832. else
  200833. return;
  200834. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200835. {
  200836. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  200837. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  200838. }
  200839. }
  200840. else if (row_info->bit_depth == 16)
  200841. {
  200842. png_bytep rp;
  200843. png_uint_32 i;
  200844. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  200845. bytes_per_pixel = 6;
  200846. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  200847. bytes_per_pixel = 8;
  200848. else
  200849. return;
  200850. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  200851. {
  200852. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  200853. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  200854. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  200855. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  200856. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  200857. *(rp ) = (png_byte)((red >> 8) & 0xff);
  200858. *(rp+1) = (png_byte)(red & 0xff);
  200859. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  200860. *(rp+5) = (png_byte)(blue & 0xff);
  200861. }
  200862. }
  200863. }
  200864. }
  200865. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  200866. #endif /* PNG_WRITE_SUPPORTED */
  200867. /*** End of inlined file: pngwtran.c ***/
  200868. /*** Start of inlined file: pngwutil.c ***/
  200869. /* pngwutil.c - utilities to write a PNG file
  200870. *
  200871. * Last changed in libpng 1.2.20 Septhember 3, 2007
  200872. * For conditions of distribution and use, see copyright notice in png.h
  200873. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  200874. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  200875. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  200876. */
  200877. #define PNG_INTERNAL
  200878. #ifdef PNG_WRITE_SUPPORTED
  200879. /* Place a 32-bit number into a buffer in PNG byte order. We work
  200880. * with unsigned numbers for convenience, although one supported
  200881. * ancillary chunk uses signed (two's complement) numbers.
  200882. */
  200883. void PNGAPI
  200884. png_save_uint_32(png_bytep buf, png_uint_32 i)
  200885. {
  200886. buf[0] = (png_byte)((i >> 24) & 0xff);
  200887. buf[1] = (png_byte)((i >> 16) & 0xff);
  200888. buf[2] = (png_byte)((i >> 8) & 0xff);
  200889. buf[3] = (png_byte)(i & 0xff);
  200890. }
  200891. /* The png_save_int_32 function assumes integers are stored in two's
  200892. * complement format. If this isn't the case, then this routine needs to
  200893. * be modified to write data in two's complement format.
  200894. */
  200895. void PNGAPI
  200896. png_save_int_32(png_bytep buf, png_int_32 i)
  200897. {
  200898. buf[0] = (png_byte)((i >> 24) & 0xff);
  200899. buf[1] = (png_byte)((i >> 16) & 0xff);
  200900. buf[2] = (png_byte)((i >> 8) & 0xff);
  200901. buf[3] = (png_byte)(i & 0xff);
  200902. }
  200903. /* Place a 16-bit number into a buffer in PNG byte order.
  200904. * The parameter is declared unsigned int, not png_uint_16,
  200905. * just to avoid potential problems on pre-ANSI C compilers.
  200906. */
  200907. void PNGAPI
  200908. png_save_uint_16(png_bytep buf, unsigned int i)
  200909. {
  200910. buf[0] = (png_byte)((i >> 8) & 0xff);
  200911. buf[1] = (png_byte)(i & 0xff);
  200912. }
  200913. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  200914. * representing the chunk name. The array must be at least 4 bytes in
  200915. * length, and does not need to be null terminated. To be safe, pass the
  200916. * pre-defined chunk names here, and if you need a new one, define it
  200917. * where the others are defined. The length is the length of the data.
  200918. * All the data must be present. If that is not possible, use the
  200919. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  200920. * functions instead.
  200921. */
  200922. void PNGAPI
  200923. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  200924. png_bytep data, png_size_t length)
  200925. {
  200926. if(png_ptr == NULL) return;
  200927. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  200928. png_write_chunk_data(png_ptr, data, length);
  200929. png_write_chunk_end(png_ptr);
  200930. }
  200931. /* Write the start of a PNG chunk. The type is the chunk type.
  200932. * The total_length is the sum of the lengths of all the data you will be
  200933. * passing in png_write_chunk_data().
  200934. */
  200935. void PNGAPI
  200936. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  200937. png_uint_32 length)
  200938. {
  200939. png_byte buf[4];
  200940. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  200941. if(png_ptr == NULL) return;
  200942. /* write the length */
  200943. png_save_uint_32(buf, length);
  200944. png_write_data(png_ptr, buf, (png_size_t)4);
  200945. /* write the chunk name */
  200946. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  200947. /* reset the crc and run it over the chunk name */
  200948. png_reset_crc(png_ptr);
  200949. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  200950. }
  200951. /* Write the data of a PNG chunk started with png_write_chunk_start().
  200952. * Note that multiple calls to this function are allowed, and that the
  200953. * sum of the lengths from these calls *must* add up to the total_length
  200954. * given to png_write_chunk_start().
  200955. */
  200956. void PNGAPI
  200957. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  200958. {
  200959. /* write the data, and run the CRC over it */
  200960. if(png_ptr == NULL) return;
  200961. if (data != NULL && length > 0)
  200962. {
  200963. png_calculate_crc(png_ptr, data, length);
  200964. png_write_data(png_ptr, data, length);
  200965. }
  200966. }
  200967. /* Finish a chunk started with png_write_chunk_start(). */
  200968. void PNGAPI
  200969. png_write_chunk_end(png_structp png_ptr)
  200970. {
  200971. png_byte buf[4];
  200972. if(png_ptr == NULL) return;
  200973. /* write the crc */
  200974. png_save_uint_32(buf, png_ptr->crc);
  200975. png_write_data(png_ptr, buf, (png_size_t)4);
  200976. }
  200977. /* Simple function to write the signature. If we have already written
  200978. * the magic bytes of the signature, or more likely, the PNG stream is
  200979. * being embedded into another stream and doesn't need its own signature,
  200980. * we should call png_set_sig_bytes() to tell libpng how many of the
  200981. * bytes have already been written.
  200982. */
  200983. void /* PRIVATE */
  200984. png_write_sig(png_structp png_ptr)
  200985. {
  200986. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  200987. /* write the rest of the 8 byte signature */
  200988. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  200989. (png_size_t)8 - png_ptr->sig_bytes);
  200990. if(png_ptr->sig_bytes < 3)
  200991. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  200992. }
  200993. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  200994. /*
  200995. * This pair of functions encapsulates the operation of (a) compressing a
  200996. * text string, and (b) issuing it later as a series of chunk data writes.
  200997. * The compression_state structure is shared context for these functions
  200998. * set up by the caller in order to make the whole mess thread-safe.
  200999. */
  201000. typedef struct
  201001. {
  201002. char *input; /* the uncompressed input data */
  201003. int input_len; /* its length */
  201004. int num_output_ptr; /* number of output pointers used */
  201005. int max_output_ptr; /* size of output_ptr */
  201006. png_charpp output_ptr; /* array of pointers to output */
  201007. } compression_state;
  201008. /* compress given text into storage in the png_ptr structure */
  201009. static int /* PRIVATE */
  201010. png_text_compress(png_structp png_ptr,
  201011. png_charp text, png_size_t text_len, int compression,
  201012. compression_state *comp)
  201013. {
  201014. int ret;
  201015. comp->num_output_ptr = 0;
  201016. comp->max_output_ptr = 0;
  201017. comp->output_ptr = NULL;
  201018. comp->input = NULL;
  201019. comp->input_len = 0;
  201020. /* we may just want to pass the text right through */
  201021. if (compression == PNG_TEXT_COMPRESSION_NONE)
  201022. {
  201023. comp->input = text;
  201024. comp->input_len = text_len;
  201025. return((int)text_len);
  201026. }
  201027. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  201028. {
  201029. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201030. char msg[50];
  201031. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  201032. png_warning(png_ptr, msg);
  201033. #else
  201034. png_warning(png_ptr, "Unknown compression type");
  201035. #endif
  201036. }
  201037. /* We can't write the chunk until we find out how much data we have,
  201038. * which means we need to run the compressor first and save the
  201039. * output. This shouldn't be a problem, as the vast majority of
  201040. * comments should be reasonable, but we will set up an array of
  201041. * malloc'd pointers to be sure.
  201042. *
  201043. * If we knew the application was well behaved, we could simplify this
  201044. * greatly by assuming we can always malloc an output buffer large
  201045. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201046. * and malloc this directly. The only time this would be a bad idea is
  201047. * if we can't malloc more than 64K and we have 64K of random input
  201048. * data, or if the input string is incredibly large (although this
  201049. * wouldn't cause a failure, just a slowdown due to swapping).
  201050. */
  201051. /* set up the compression buffers */
  201052. png_ptr->zstream.avail_in = (uInt)text_len;
  201053. png_ptr->zstream.next_in = (Bytef *)text;
  201054. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201055. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201056. /* this is the same compression loop as in png_write_row() */
  201057. do
  201058. {
  201059. /* compress the data */
  201060. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201061. if (ret != Z_OK)
  201062. {
  201063. /* error */
  201064. if (png_ptr->zstream.msg != NULL)
  201065. png_error(png_ptr, png_ptr->zstream.msg);
  201066. else
  201067. png_error(png_ptr, "zlib error");
  201068. }
  201069. /* check to see if we need more room */
  201070. if (!(png_ptr->zstream.avail_out))
  201071. {
  201072. /* make sure the output array has room */
  201073. if (comp->num_output_ptr >= comp->max_output_ptr)
  201074. {
  201075. int old_max;
  201076. old_max = comp->max_output_ptr;
  201077. comp->max_output_ptr = comp->num_output_ptr + 4;
  201078. if (comp->output_ptr != NULL)
  201079. {
  201080. png_charpp old_ptr;
  201081. old_ptr = comp->output_ptr;
  201082. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201083. (png_uint_32)(comp->max_output_ptr *
  201084. png_sizeof (png_charpp)));
  201085. png_memcpy(comp->output_ptr, old_ptr, old_max
  201086. * png_sizeof (png_charp));
  201087. png_free(png_ptr, old_ptr);
  201088. }
  201089. else
  201090. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201091. (png_uint_32)(comp->max_output_ptr *
  201092. png_sizeof (png_charp)));
  201093. }
  201094. /* save the data */
  201095. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201096. (png_uint_32)png_ptr->zbuf_size);
  201097. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201098. png_ptr->zbuf_size);
  201099. comp->num_output_ptr++;
  201100. /* and reset the buffer */
  201101. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201102. png_ptr->zstream.next_out = png_ptr->zbuf;
  201103. }
  201104. /* continue until we don't have any more to compress */
  201105. } while (png_ptr->zstream.avail_in);
  201106. /* finish the compression */
  201107. do
  201108. {
  201109. /* tell zlib we are finished */
  201110. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201111. if (ret == Z_OK)
  201112. {
  201113. /* check to see if we need more room */
  201114. if (!(png_ptr->zstream.avail_out))
  201115. {
  201116. /* check to make sure our output array has room */
  201117. if (comp->num_output_ptr >= comp->max_output_ptr)
  201118. {
  201119. int old_max;
  201120. old_max = comp->max_output_ptr;
  201121. comp->max_output_ptr = comp->num_output_ptr + 4;
  201122. if (comp->output_ptr != NULL)
  201123. {
  201124. png_charpp old_ptr;
  201125. old_ptr = comp->output_ptr;
  201126. /* This could be optimized to realloc() */
  201127. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201128. (png_uint_32)(comp->max_output_ptr *
  201129. png_sizeof (png_charpp)));
  201130. png_memcpy(comp->output_ptr, old_ptr,
  201131. old_max * png_sizeof (png_charp));
  201132. png_free(png_ptr, old_ptr);
  201133. }
  201134. else
  201135. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201136. (png_uint_32)(comp->max_output_ptr *
  201137. png_sizeof (png_charp)));
  201138. }
  201139. /* save off the data */
  201140. comp->output_ptr[comp->num_output_ptr] =
  201141. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201142. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201143. png_ptr->zbuf_size);
  201144. comp->num_output_ptr++;
  201145. /* and reset the buffer pointers */
  201146. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201147. png_ptr->zstream.next_out = png_ptr->zbuf;
  201148. }
  201149. }
  201150. else if (ret != Z_STREAM_END)
  201151. {
  201152. /* we got an error */
  201153. if (png_ptr->zstream.msg != NULL)
  201154. png_error(png_ptr, png_ptr->zstream.msg);
  201155. else
  201156. png_error(png_ptr, "zlib error");
  201157. }
  201158. } while (ret != Z_STREAM_END);
  201159. /* text length is number of buffers plus last buffer */
  201160. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201161. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201162. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201163. return((int)text_len);
  201164. }
  201165. /* ship the compressed text out via chunk writes */
  201166. static void /* PRIVATE */
  201167. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201168. {
  201169. int i;
  201170. /* handle the no-compression case */
  201171. if (comp->input)
  201172. {
  201173. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201174. (png_size_t)comp->input_len);
  201175. return;
  201176. }
  201177. /* write saved output buffers, if any */
  201178. for (i = 0; i < comp->num_output_ptr; i++)
  201179. {
  201180. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201181. png_ptr->zbuf_size);
  201182. png_free(png_ptr, comp->output_ptr[i]);
  201183. comp->output_ptr[i]=NULL;
  201184. }
  201185. if (comp->max_output_ptr != 0)
  201186. png_free(png_ptr, comp->output_ptr);
  201187. comp->output_ptr=NULL;
  201188. /* write anything left in zbuf */
  201189. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201190. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201191. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201192. /* reset zlib for another zTXt/iTXt or image data */
  201193. deflateReset(&png_ptr->zstream);
  201194. png_ptr->zstream.data_type = Z_BINARY;
  201195. }
  201196. #endif
  201197. /* Write the IHDR chunk, and update the png_struct with the necessary
  201198. * information. Note that the rest of this code depends upon this
  201199. * information being correct.
  201200. */
  201201. void /* PRIVATE */
  201202. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201203. int bit_depth, int color_type, int compression_type, int filter_type,
  201204. int interlace_type)
  201205. {
  201206. #ifdef PNG_USE_LOCAL_ARRAYS
  201207. PNG_IHDR;
  201208. #endif
  201209. png_byte buf[13]; /* buffer to store the IHDR info */
  201210. png_debug(1, "in png_write_IHDR\n");
  201211. /* Check that we have valid input data from the application info */
  201212. switch (color_type)
  201213. {
  201214. case PNG_COLOR_TYPE_GRAY:
  201215. switch (bit_depth)
  201216. {
  201217. case 1:
  201218. case 2:
  201219. case 4:
  201220. case 8:
  201221. case 16: png_ptr->channels = 1; break;
  201222. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201223. }
  201224. break;
  201225. case PNG_COLOR_TYPE_RGB:
  201226. if (bit_depth != 8 && bit_depth != 16)
  201227. png_error(png_ptr, "Invalid bit depth for RGB image");
  201228. png_ptr->channels = 3;
  201229. break;
  201230. case PNG_COLOR_TYPE_PALETTE:
  201231. switch (bit_depth)
  201232. {
  201233. case 1:
  201234. case 2:
  201235. case 4:
  201236. case 8: png_ptr->channels = 1; break;
  201237. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201238. }
  201239. break;
  201240. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201241. if (bit_depth != 8 && bit_depth != 16)
  201242. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201243. png_ptr->channels = 2;
  201244. break;
  201245. case PNG_COLOR_TYPE_RGB_ALPHA:
  201246. if (bit_depth != 8 && bit_depth != 16)
  201247. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201248. png_ptr->channels = 4;
  201249. break;
  201250. default:
  201251. png_error(png_ptr, "Invalid image color type specified");
  201252. }
  201253. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201254. {
  201255. png_warning(png_ptr, "Invalid compression type specified");
  201256. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201257. }
  201258. /* Write filter_method 64 (intrapixel differencing) only if
  201259. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201260. * 2. Libpng did not write a PNG signature (this filter_method is only
  201261. * used in PNG datastreams that are embedded in MNG datastreams) and
  201262. * 3. The application called png_permit_mng_features with a mask that
  201263. * included PNG_FLAG_MNG_FILTER_64 and
  201264. * 4. The filter_method is 64 and
  201265. * 5. The color_type is RGB or RGBA
  201266. */
  201267. if (
  201268. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201269. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201270. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201271. (color_type == PNG_COLOR_TYPE_RGB ||
  201272. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201273. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201274. #endif
  201275. filter_type != PNG_FILTER_TYPE_BASE)
  201276. {
  201277. png_warning(png_ptr, "Invalid filter type specified");
  201278. filter_type = PNG_FILTER_TYPE_BASE;
  201279. }
  201280. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201281. if (interlace_type != PNG_INTERLACE_NONE &&
  201282. interlace_type != PNG_INTERLACE_ADAM7)
  201283. {
  201284. png_warning(png_ptr, "Invalid interlace type specified");
  201285. interlace_type = PNG_INTERLACE_ADAM7;
  201286. }
  201287. #else
  201288. interlace_type=PNG_INTERLACE_NONE;
  201289. #endif
  201290. /* save off the relevent information */
  201291. png_ptr->bit_depth = (png_byte)bit_depth;
  201292. png_ptr->color_type = (png_byte)color_type;
  201293. png_ptr->interlaced = (png_byte)interlace_type;
  201294. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201295. png_ptr->filter_type = (png_byte)filter_type;
  201296. #endif
  201297. png_ptr->compression_type = (png_byte)compression_type;
  201298. png_ptr->width = width;
  201299. png_ptr->height = height;
  201300. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  201301. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  201302. /* set the usr info, so any transformations can modify it */
  201303. png_ptr->usr_width = png_ptr->width;
  201304. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  201305. png_ptr->usr_channels = png_ptr->channels;
  201306. /* pack the header information into the buffer */
  201307. png_save_uint_32(buf, width);
  201308. png_save_uint_32(buf + 4, height);
  201309. buf[8] = (png_byte)bit_depth;
  201310. buf[9] = (png_byte)color_type;
  201311. buf[10] = (png_byte)compression_type;
  201312. buf[11] = (png_byte)filter_type;
  201313. buf[12] = (png_byte)interlace_type;
  201314. /* write the chunk */
  201315. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  201316. /* initialize zlib with PNG info */
  201317. png_ptr->zstream.zalloc = png_zalloc;
  201318. png_ptr->zstream.zfree = png_zfree;
  201319. png_ptr->zstream.opaque = (voidpf)png_ptr;
  201320. if (!(png_ptr->do_filter))
  201321. {
  201322. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  201323. png_ptr->bit_depth < 8)
  201324. png_ptr->do_filter = PNG_FILTER_NONE;
  201325. else
  201326. png_ptr->do_filter = PNG_ALL_FILTERS;
  201327. }
  201328. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  201329. {
  201330. if (png_ptr->do_filter != PNG_FILTER_NONE)
  201331. png_ptr->zlib_strategy = Z_FILTERED;
  201332. else
  201333. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  201334. }
  201335. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  201336. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  201337. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  201338. png_ptr->zlib_mem_level = 8;
  201339. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  201340. png_ptr->zlib_window_bits = 15;
  201341. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  201342. png_ptr->zlib_method = 8;
  201343. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  201344. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  201345. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  201346. png_error(png_ptr, "zlib failed to initialize compressor");
  201347. png_ptr->zstream.next_out = png_ptr->zbuf;
  201348. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201349. /* libpng is not interested in zstream.data_type */
  201350. /* set it to a predefined value, to avoid its evaluation inside zlib */
  201351. png_ptr->zstream.data_type = Z_BINARY;
  201352. png_ptr->mode = PNG_HAVE_IHDR;
  201353. }
  201354. /* write the palette. We are careful not to trust png_color to be in the
  201355. * correct order for PNG, so people can redefine it to any convenient
  201356. * structure.
  201357. */
  201358. void /* PRIVATE */
  201359. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  201360. {
  201361. #ifdef PNG_USE_LOCAL_ARRAYS
  201362. PNG_PLTE;
  201363. #endif
  201364. png_uint_32 i;
  201365. png_colorp pal_ptr;
  201366. png_byte buf[3];
  201367. png_debug(1, "in png_write_PLTE\n");
  201368. if ((
  201369. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201370. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  201371. #endif
  201372. num_pal == 0) || num_pal > 256)
  201373. {
  201374. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  201375. {
  201376. png_error(png_ptr, "Invalid number of colors in palette");
  201377. }
  201378. else
  201379. {
  201380. png_warning(png_ptr, "Invalid number of colors in palette");
  201381. return;
  201382. }
  201383. }
  201384. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  201385. {
  201386. png_warning(png_ptr,
  201387. "Ignoring request to write a PLTE chunk in grayscale PNG");
  201388. return;
  201389. }
  201390. png_ptr->num_palette = (png_uint_16)num_pal;
  201391. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  201392. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  201393. #ifndef PNG_NO_POINTER_INDEXING
  201394. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  201395. {
  201396. buf[0] = pal_ptr->red;
  201397. buf[1] = pal_ptr->green;
  201398. buf[2] = pal_ptr->blue;
  201399. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201400. }
  201401. #else
  201402. /* This is a little slower but some buggy compilers need to do this instead */
  201403. pal_ptr=palette;
  201404. for (i = 0; i < num_pal; i++)
  201405. {
  201406. buf[0] = pal_ptr[i].red;
  201407. buf[1] = pal_ptr[i].green;
  201408. buf[2] = pal_ptr[i].blue;
  201409. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  201410. }
  201411. #endif
  201412. png_write_chunk_end(png_ptr);
  201413. png_ptr->mode |= PNG_HAVE_PLTE;
  201414. }
  201415. /* write an IDAT chunk */
  201416. void /* PRIVATE */
  201417. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  201418. {
  201419. #ifdef PNG_USE_LOCAL_ARRAYS
  201420. PNG_IDAT;
  201421. #endif
  201422. png_debug(1, "in png_write_IDAT\n");
  201423. /* Optimize the CMF field in the zlib stream. */
  201424. /* This hack of the zlib stream is compliant to the stream specification. */
  201425. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  201426. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  201427. {
  201428. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  201429. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  201430. {
  201431. /* Avoid memory underflows and multiplication overflows. */
  201432. /* The conditions below are practically always satisfied;
  201433. however, they still must be checked. */
  201434. if (length >= 2 &&
  201435. png_ptr->height < 16384 && png_ptr->width < 16384)
  201436. {
  201437. png_uint_32 uncompressed_idat_size = png_ptr->height *
  201438. ((png_ptr->width *
  201439. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  201440. unsigned int z_cinfo = z_cmf >> 4;
  201441. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  201442. while (uncompressed_idat_size <= half_z_window_size &&
  201443. half_z_window_size >= 256)
  201444. {
  201445. z_cinfo--;
  201446. half_z_window_size >>= 1;
  201447. }
  201448. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  201449. if (data[0] != (png_byte)z_cmf)
  201450. {
  201451. data[0] = (png_byte)z_cmf;
  201452. data[1] &= 0xe0;
  201453. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  201454. }
  201455. }
  201456. }
  201457. else
  201458. png_error(png_ptr,
  201459. "Invalid zlib compression method or flags in IDAT");
  201460. }
  201461. png_write_chunk(png_ptr, png_IDAT, data, length);
  201462. png_ptr->mode |= PNG_HAVE_IDAT;
  201463. }
  201464. /* write an IEND chunk */
  201465. void /* PRIVATE */
  201466. png_write_IEND(png_structp png_ptr)
  201467. {
  201468. #ifdef PNG_USE_LOCAL_ARRAYS
  201469. PNG_IEND;
  201470. #endif
  201471. png_debug(1, "in png_write_IEND\n");
  201472. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  201473. (png_size_t)0);
  201474. png_ptr->mode |= PNG_HAVE_IEND;
  201475. }
  201476. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  201477. /* write a gAMA chunk */
  201478. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201479. void /* PRIVATE */
  201480. png_write_gAMA(png_structp png_ptr, double file_gamma)
  201481. {
  201482. #ifdef PNG_USE_LOCAL_ARRAYS
  201483. PNG_gAMA;
  201484. #endif
  201485. png_uint_32 igamma;
  201486. png_byte buf[4];
  201487. png_debug(1, "in png_write_gAMA\n");
  201488. /* file_gamma is saved in 1/100,000ths */
  201489. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  201490. png_save_uint_32(buf, igamma);
  201491. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201492. }
  201493. #endif
  201494. #ifdef PNG_FIXED_POINT_SUPPORTED
  201495. void /* PRIVATE */
  201496. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  201497. {
  201498. #ifdef PNG_USE_LOCAL_ARRAYS
  201499. PNG_gAMA;
  201500. #endif
  201501. png_byte buf[4];
  201502. png_debug(1, "in png_write_gAMA\n");
  201503. /* file_gamma is saved in 1/100,000ths */
  201504. png_save_uint_32(buf, (png_uint_32)file_gamma);
  201505. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  201506. }
  201507. #endif
  201508. #endif
  201509. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  201510. /* write a sRGB chunk */
  201511. void /* PRIVATE */
  201512. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  201513. {
  201514. #ifdef PNG_USE_LOCAL_ARRAYS
  201515. PNG_sRGB;
  201516. #endif
  201517. png_byte buf[1];
  201518. png_debug(1, "in png_write_sRGB\n");
  201519. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  201520. png_warning(png_ptr,
  201521. "Invalid sRGB rendering intent specified");
  201522. buf[0]=(png_byte)srgb_intent;
  201523. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  201524. }
  201525. #endif
  201526. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  201527. /* write an iCCP chunk */
  201528. void /* PRIVATE */
  201529. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  201530. png_charp profile, int profile_len)
  201531. {
  201532. #ifdef PNG_USE_LOCAL_ARRAYS
  201533. PNG_iCCP;
  201534. #endif
  201535. png_size_t name_len;
  201536. png_charp new_name;
  201537. compression_state comp;
  201538. int embedded_profile_len = 0;
  201539. png_debug(1, "in png_write_iCCP\n");
  201540. comp.num_output_ptr = 0;
  201541. comp.max_output_ptr = 0;
  201542. comp.output_ptr = NULL;
  201543. comp.input = NULL;
  201544. comp.input_len = 0;
  201545. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  201546. &new_name)) == 0)
  201547. {
  201548. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  201549. return;
  201550. }
  201551. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201552. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  201553. if (profile == NULL)
  201554. profile_len = 0;
  201555. if (profile_len > 3)
  201556. embedded_profile_len =
  201557. ((*( (png_bytep)profile ))<<24) |
  201558. ((*( (png_bytep)profile+1))<<16) |
  201559. ((*( (png_bytep)profile+2))<< 8) |
  201560. ((*( (png_bytep)profile+3)) );
  201561. if (profile_len < embedded_profile_len)
  201562. {
  201563. png_warning(png_ptr,
  201564. "Embedded profile length too large in iCCP chunk");
  201565. return;
  201566. }
  201567. if (profile_len > embedded_profile_len)
  201568. {
  201569. png_warning(png_ptr,
  201570. "Truncating profile to actual length in iCCP chunk");
  201571. profile_len = embedded_profile_len;
  201572. }
  201573. if (profile_len)
  201574. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  201575. PNG_COMPRESSION_TYPE_BASE, &comp);
  201576. /* make sure we include the NULL after the name and the compression type */
  201577. png_write_chunk_start(png_ptr, png_iCCP,
  201578. (png_uint_32)name_len+profile_len+2);
  201579. new_name[name_len+1]=0x00;
  201580. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  201581. if (profile_len)
  201582. png_write_compressed_data_out(png_ptr, &comp);
  201583. png_write_chunk_end(png_ptr);
  201584. png_free(png_ptr, new_name);
  201585. }
  201586. #endif
  201587. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  201588. /* write a sPLT chunk */
  201589. void /* PRIVATE */
  201590. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  201591. {
  201592. #ifdef PNG_USE_LOCAL_ARRAYS
  201593. PNG_sPLT;
  201594. #endif
  201595. png_size_t name_len;
  201596. png_charp new_name;
  201597. png_byte entrybuf[10];
  201598. int entry_size = (spalette->depth == 8 ? 6 : 10);
  201599. int palette_size = entry_size * spalette->nentries;
  201600. png_sPLT_entryp ep;
  201601. #ifdef PNG_NO_POINTER_INDEXING
  201602. int i;
  201603. #endif
  201604. png_debug(1, "in png_write_sPLT\n");
  201605. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  201606. spalette->name, &new_name))==0)
  201607. {
  201608. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  201609. return;
  201610. }
  201611. /* make sure we include the NULL after the name */
  201612. png_write_chunk_start(png_ptr, png_sPLT,
  201613. (png_uint_32)(name_len + 2 + palette_size));
  201614. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  201615. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  201616. /* loop through each palette entry, writing appropriately */
  201617. #ifndef PNG_NO_POINTER_INDEXING
  201618. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  201619. {
  201620. if (spalette->depth == 8)
  201621. {
  201622. entrybuf[0] = (png_byte)ep->red;
  201623. entrybuf[1] = (png_byte)ep->green;
  201624. entrybuf[2] = (png_byte)ep->blue;
  201625. entrybuf[3] = (png_byte)ep->alpha;
  201626. png_save_uint_16(entrybuf + 4, ep->frequency);
  201627. }
  201628. else
  201629. {
  201630. png_save_uint_16(entrybuf + 0, ep->red);
  201631. png_save_uint_16(entrybuf + 2, ep->green);
  201632. png_save_uint_16(entrybuf + 4, ep->blue);
  201633. png_save_uint_16(entrybuf + 6, ep->alpha);
  201634. png_save_uint_16(entrybuf + 8, ep->frequency);
  201635. }
  201636. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  201637. }
  201638. #else
  201639. ep=spalette->entries;
  201640. for (i=0; i>spalette->nentries; i++)
  201641. {
  201642. if (spalette->depth == 8)
  201643. {
  201644. entrybuf[0] = (png_byte)ep[i].red;
  201645. entrybuf[1] = (png_byte)ep[i].green;
  201646. entrybuf[2] = (png_byte)ep[i].blue;
  201647. entrybuf[3] = (png_byte)ep[i].alpha;
  201648. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  201649. }
  201650. else
  201651. {
  201652. png_save_uint_16(entrybuf + 0, ep[i].red);
  201653. png_save_uint_16(entrybuf + 2, ep[i].green);
  201654. png_save_uint_16(entrybuf + 4, ep[i].blue);
  201655. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  201656. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  201657. }
  201658. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  201659. }
  201660. #endif
  201661. png_write_chunk_end(png_ptr);
  201662. png_free(png_ptr, new_name);
  201663. }
  201664. #endif
  201665. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  201666. /* write the sBIT chunk */
  201667. void /* PRIVATE */
  201668. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  201669. {
  201670. #ifdef PNG_USE_LOCAL_ARRAYS
  201671. PNG_sBIT;
  201672. #endif
  201673. png_byte buf[4];
  201674. png_size_t size;
  201675. png_debug(1, "in png_write_sBIT\n");
  201676. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  201677. if (color_type & PNG_COLOR_MASK_COLOR)
  201678. {
  201679. png_byte maxbits;
  201680. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  201681. png_ptr->usr_bit_depth);
  201682. if (sbit->red == 0 || sbit->red > maxbits ||
  201683. sbit->green == 0 || sbit->green > maxbits ||
  201684. sbit->blue == 0 || sbit->blue > maxbits)
  201685. {
  201686. png_warning(png_ptr, "Invalid sBIT depth specified");
  201687. return;
  201688. }
  201689. buf[0] = sbit->red;
  201690. buf[1] = sbit->green;
  201691. buf[2] = sbit->blue;
  201692. size = 3;
  201693. }
  201694. else
  201695. {
  201696. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  201697. {
  201698. png_warning(png_ptr, "Invalid sBIT depth specified");
  201699. return;
  201700. }
  201701. buf[0] = sbit->gray;
  201702. size = 1;
  201703. }
  201704. if (color_type & PNG_COLOR_MASK_ALPHA)
  201705. {
  201706. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  201707. {
  201708. png_warning(png_ptr, "Invalid sBIT depth specified");
  201709. return;
  201710. }
  201711. buf[size++] = sbit->alpha;
  201712. }
  201713. png_write_chunk(png_ptr, png_sBIT, buf, size);
  201714. }
  201715. #endif
  201716. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  201717. /* write the cHRM chunk */
  201718. #ifdef PNG_FLOATING_POINT_SUPPORTED
  201719. void /* PRIVATE */
  201720. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  201721. double red_x, double red_y, double green_x, double green_y,
  201722. double blue_x, double blue_y)
  201723. {
  201724. #ifdef PNG_USE_LOCAL_ARRAYS
  201725. PNG_cHRM;
  201726. #endif
  201727. png_byte buf[32];
  201728. png_uint_32 itemp;
  201729. png_debug(1, "in png_write_cHRM\n");
  201730. /* each value is saved in 1/100,000ths */
  201731. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  201732. white_x + white_y > 1.0)
  201733. {
  201734. png_warning(png_ptr, "Invalid cHRM white point specified");
  201735. #if !defined(PNG_NO_CONSOLE_IO)
  201736. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  201737. #endif
  201738. return;
  201739. }
  201740. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  201741. png_save_uint_32(buf, itemp);
  201742. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  201743. png_save_uint_32(buf + 4, itemp);
  201744. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  201745. {
  201746. png_warning(png_ptr, "Invalid cHRM red point specified");
  201747. return;
  201748. }
  201749. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  201750. png_save_uint_32(buf + 8, itemp);
  201751. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  201752. png_save_uint_32(buf + 12, itemp);
  201753. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  201754. {
  201755. png_warning(png_ptr, "Invalid cHRM green point specified");
  201756. return;
  201757. }
  201758. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  201759. png_save_uint_32(buf + 16, itemp);
  201760. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  201761. png_save_uint_32(buf + 20, itemp);
  201762. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  201763. {
  201764. png_warning(png_ptr, "Invalid cHRM blue point specified");
  201765. return;
  201766. }
  201767. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  201768. png_save_uint_32(buf + 24, itemp);
  201769. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  201770. png_save_uint_32(buf + 28, itemp);
  201771. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201772. }
  201773. #endif
  201774. #ifdef PNG_FIXED_POINT_SUPPORTED
  201775. void /* PRIVATE */
  201776. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  201777. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  201778. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  201779. png_fixed_point blue_y)
  201780. {
  201781. #ifdef PNG_USE_LOCAL_ARRAYS
  201782. PNG_cHRM;
  201783. #endif
  201784. png_byte buf[32];
  201785. png_debug(1, "in png_write_cHRM\n");
  201786. /* each value is saved in 1/100,000ths */
  201787. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  201788. {
  201789. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  201790. #if !defined(PNG_NO_CONSOLE_IO)
  201791. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  201792. #endif
  201793. return;
  201794. }
  201795. png_save_uint_32(buf, (png_uint_32)white_x);
  201796. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  201797. if (red_x + red_y > 100000L)
  201798. {
  201799. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  201800. return;
  201801. }
  201802. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  201803. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  201804. if (green_x + green_y > 100000L)
  201805. {
  201806. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  201807. return;
  201808. }
  201809. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  201810. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  201811. if (blue_x + blue_y > 100000L)
  201812. {
  201813. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  201814. return;
  201815. }
  201816. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  201817. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  201818. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  201819. }
  201820. #endif
  201821. #endif
  201822. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  201823. /* write the tRNS chunk */
  201824. void /* PRIVATE */
  201825. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  201826. int num_trans, int color_type)
  201827. {
  201828. #ifdef PNG_USE_LOCAL_ARRAYS
  201829. PNG_tRNS;
  201830. #endif
  201831. png_byte buf[6];
  201832. png_debug(1, "in png_write_tRNS\n");
  201833. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201834. {
  201835. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  201836. {
  201837. png_warning(png_ptr,"Invalid number of transparent colors specified");
  201838. return;
  201839. }
  201840. /* write the chunk out as it is */
  201841. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  201842. }
  201843. else if (color_type == PNG_COLOR_TYPE_GRAY)
  201844. {
  201845. /* one 16 bit value */
  201846. if(tran->gray >= (1 << png_ptr->bit_depth))
  201847. {
  201848. png_warning(png_ptr,
  201849. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  201850. return;
  201851. }
  201852. png_save_uint_16(buf, tran->gray);
  201853. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  201854. }
  201855. else if (color_type == PNG_COLOR_TYPE_RGB)
  201856. {
  201857. /* three 16 bit values */
  201858. png_save_uint_16(buf, tran->red);
  201859. png_save_uint_16(buf + 2, tran->green);
  201860. png_save_uint_16(buf + 4, tran->blue);
  201861. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201862. {
  201863. png_warning(png_ptr,
  201864. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  201865. return;
  201866. }
  201867. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  201868. }
  201869. else
  201870. {
  201871. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  201872. }
  201873. }
  201874. #endif
  201875. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  201876. /* write the background chunk */
  201877. void /* PRIVATE */
  201878. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  201879. {
  201880. #ifdef PNG_USE_LOCAL_ARRAYS
  201881. PNG_bKGD;
  201882. #endif
  201883. png_byte buf[6];
  201884. png_debug(1, "in png_write_bKGD\n");
  201885. if (color_type == PNG_COLOR_TYPE_PALETTE)
  201886. {
  201887. if (
  201888. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201889. (png_ptr->num_palette ||
  201890. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  201891. #endif
  201892. back->index > png_ptr->num_palette)
  201893. {
  201894. png_warning(png_ptr, "Invalid background palette index");
  201895. return;
  201896. }
  201897. buf[0] = back->index;
  201898. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  201899. }
  201900. else if (color_type & PNG_COLOR_MASK_COLOR)
  201901. {
  201902. png_save_uint_16(buf, back->red);
  201903. png_save_uint_16(buf + 2, back->green);
  201904. png_save_uint_16(buf + 4, back->blue);
  201905. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  201906. {
  201907. png_warning(png_ptr,
  201908. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  201909. return;
  201910. }
  201911. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  201912. }
  201913. else
  201914. {
  201915. if(back->gray >= (1 << png_ptr->bit_depth))
  201916. {
  201917. png_warning(png_ptr,
  201918. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  201919. return;
  201920. }
  201921. png_save_uint_16(buf, back->gray);
  201922. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  201923. }
  201924. }
  201925. #endif
  201926. #if defined(PNG_WRITE_hIST_SUPPORTED)
  201927. /* write the histogram */
  201928. void /* PRIVATE */
  201929. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  201930. {
  201931. #ifdef PNG_USE_LOCAL_ARRAYS
  201932. PNG_hIST;
  201933. #endif
  201934. int i;
  201935. png_byte buf[3];
  201936. png_debug(1, "in png_write_hIST\n");
  201937. if (num_hist > (int)png_ptr->num_palette)
  201938. {
  201939. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  201940. png_ptr->num_palette);
  201941. png_warning(png_ptr, "Invalid number of histogram entries specified");
  201942. return;
  201943. }
  201944. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  201945. for (i = 0; i < num_hist; i++)
  201946. {
  201947. png_save_uint_16(buf, hist[i]);
  201948. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  201949. }
  201950. png_write_chunk_end(png_ptr);
  201951. }
  201952. #endif
  201953. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  201954. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  201955. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  201956. * and if invalid, correct the keyword rather than discarding the entire
  201957. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  201958. * length, forbids leading or trailing whitespace, multiple internal spaces,
  201959. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  201960. *
  201961. * The new_key is allocated to hold the corrected keyword and must be freed
  201962. * by the calling routine. This avoids problems with trying to write to
  201963. * static keywords without having to have duplicate copies of the strings.
  201964. */
  201965. png_size_t /* PRIVATE */
  201966. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  201967. {
  201968. png_size_t key_len;
  201969. png_charp kp, dp;
  201970. int kflag;
  201971. int kwarn=0;
  201972. png_debug(1, "in png_check_keyword\n");
  201973. *new_key = NULL;
  201974. if (key == NULL || (key_len = png_strlen(key)) == 0)
  201975. {
  201976. png_warning(png_ptr, "zero length keyword");
  201977. return ((png_size_t)0);
  201978. }
  201979. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  201980. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  201981. if (*new_key == NULL)
  201982. {
  201983. png_warning(png_ptr, "Out of memory while procesing keyword");
  201984. return ((png_size_t)0);
  201985. }
  201986. /* Replace non-printing characters with a blank and print a warning */
  201987. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  201988. {
  201989. if ((png_byte)*kp < 0x20 ||
  201990. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  201991. {
  201992. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201993. char msg[40];
  201994. png_snprintf(msg, 40,
  201995. "invalid keyword character 0x%02X", (png_byte)*kp);
  201996. png_warning(png_ptr, msg);
  201997. #else
  201998. png_warning(png_ptr, "invalid character in keyword");
  201999. #endif
  202000. *dp = ' ';
  202001. }
  202002. else
  202003. {
  202004. *dp = *kp;
  202005. }
  202006. }
  202007. *dp = '\0';
  202008. /* Remove any trailing white space. */
  202009. kp = *new_key + key_len - 1;
  202010. if (*kp == ' ')
  202011. {
  202012. png_warning(png_ptr, "trailing spaces removed from keyword");
  202013. while (*kp == ' ')
  202014. {
  202015. *(kp--) = '\0';
  202016. key_len--;
  202017. }
  202018. }
  202019. /* Remove any leading white space. */
  202020. kp = *new_key;
  202021. if (*kp == ' ')
  202022. {
  202023. png_warning(png_ptr, "leading spaces removed from keyword");
  202024. while (*kp == ' ')
  202025. {
  202026. kp++;
  202027. key_len--;
  202028. }
  202029. }
  202030. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  202031. /* Remove multiple internal spaces. */
  202032. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  202033. {
  202034. if (*kp == ' ' && kflag == 0)
  202035. {
  202036. *(dp++) = *kp;
  202037. kflag = 1;
  202038. }
  202039. else if (*kp == ' ')
  202040. {
  202041. key_len--;
  202042. kwarn=1;
  202043. }
  202044. else
  202045. {
  202046. *(dp++) = *kp;
  202047. kflag = 0;
  202048. }
  202049. }
  202050. *dp = '\0';
  202051. if(kwarn)
  202052. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202053. if (key_len == 0)
  202054. {
  202055. png_free(png_ptr, *new_key);
  202056. *new_key=NULL;
  202057. png_warning(png_ptr, "Zero length keyword");
  202058. }
  202059. if (key_len > 79)
  202060. {
  202061. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202062. new_key[79] = '\0';
  202063. key_len = 79;
  202064. }
  202065. return (key_len);
  202066. }
  202067. #endif
  202068. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202069. /* write a tEXt chunk */
  202070. void /* PRIVATE */
  202071. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202072. png_size_t text_len)
  202073. {
  202074. #ifdef PNG_USE_LOCAL_ARRAYS
  202075. PNG_tEXt;
  202076. #endif
  202077. png_size_t key_len;
  202078. png_charp new_key;
  202079. png_debug(1, "in png_write_tEXt\n");
  202080. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202081. {
  202082. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202083. return;
  202084. }
  202085. if (text == NULL || *text == '\0')
  202086. text_len = 0;
  202087. else
  202088. text_len = png_strlen(text);
  202089. /* make sure we include the 0 after the key */
  202090. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202091. /*
  202092. * We leave it to the application to meet PNG-1.0 requirements on the
  202093. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202094. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202095. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202096. */
  202097. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202098. if (text_len)
  202099. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202100. png_write_chunk_end(png_ptr);
  202101. png_free(png_ptr, new_key);
  202102. }
  202103. #endif
  202104. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202105. /* write a compressed text chunk */
  202106. void /* PRIVATE */
  202107. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202108. png_size_t text_len, int compression)
  202109. {
  202110. #ifdef PNG_USE_LOCAL_ARRAYS
  202111. PNG_zTXt;
  202112. #endif
  202113. png_size_t key_len;
  202114. char buf[1];
  202115. png_charp new_key;
  202116. compression_state comp;
  202117. png_debug(1, "in png_write_zTXt\n");
  202118. comp.num_output_ptr = 0;
  202119. comp.max_output_ptr = 0;
  202120. comp.output_ptr = NULL;
  202121. comp.input = NULL;
  202122. comp.input_len = 0;
  202123. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202124. {
  202125. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202126. return;
  202127. }
  202128. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202129. {
  202130. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202131. png_free(png_ptr, new_key);
  202132. return;
  202133. }
  202134. text_len = png_strlen(text);
  202135. /* compute the compressed data; do it now for the length */
  202136. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202137. &comp);
  202138. /* write start of chunk */
  202139. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202140. (key_len+text_len+2));
  202141. /* write key */
  202142. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202143. png_free(png_ptr, new_key);
  202144. buf[0] = (png_byte)compression;
  202145. /* write compression */
  202146. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202147. /* write the compressed data */
  202148. png_write_compressed_data_out(png_ptr, &comp);
  202149. /* close the chunk */
  202150. png_write_chunk_end(png_ptr);
  202151. }
  202152. #endif
  202153. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202154. /* write an iTXt chunk */
  202155. void /* PRIVATE */
  202156. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202157. png_charp lang, png_charp lang_key, png_charp text)
  202158. {
  202159. #ifdef PNG_USE_LOCAL_ARRAYS
  202160. PNG_iTXt;
  202161. #endif
  202162. png_size_t lang_len, key_len, lang_key_len, text_len;
  202163. png_charp new_lang, new_key;
  202164. png_byte cbuf[2];
  202165. compression_state comp;
  202166. png_debug(1, "in png_write_iTXt\n");
  202167. comp.num_output_ptr = 0;
  202168. comp.max_output_ptr = 0;
  202169. comp.output_ptr = NULL;
  202170. comp.input = NULL;
  202171. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202172. {
  202173. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202174. return;
  202175. }
  202176. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202177. {
  202178. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202179. new_lang = NULL;
  202180. lang_len = 0;
  202181. }
  202182. if (lang_key == NULL)
  202183. lang_key_len = 0;
  202184. else
  202185. lang_key_len = png_strlen(lang_key);
  202186. if (text == NULL)
  202187. text_len = 0;
  202188. else
  202189. text_len = png_strlen(text);
  202190. /* compute the compressed data; do it now for the length */
  202191. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202192. &comp);
  202193. /* make sure we include the compression flag, the compression byte,
  202194. * and the NULs after the key, lang, and lang_key parts */
  202195. png_write_chunk_start(png_ptr, png_iTXt,
  202196. (png_uint_32)(
  202197. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202198. + key_len
  202199. + lang_len
  202200. + lang_key_len
  202201. + text_len));
  202202. /*
  202203. * We leave it to the application to meet PNG-1.0 requirements on the
  202204. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202205. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202206. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202207. */
  202208. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202209. /* set the compression flag */
  202210. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202211. compression == PNG_TEXT_COMPRESSION_NONE)
  202212. cbuf[0] = 0;
  202213. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202214. cbuf[0] = 1;
  202215. /* set the compression method */
  202216. cbuf[1] = 0;
  202217. png_write_chunk_data(png_ptr, cbuf, 2);
  202218. cbuf[0] = 0;
  202219. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202220. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202221. png_write_compressed_data_out(png_ptr, &comp);
  202222. png_write_chunk_end(png_ptr);
  202223. png_free(png_ptr, new_key);
  202224. if (new_lang)
  202225. png_free(png_ptr, new_lang);
  202226. }
  202227. #endif
  202228. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202229. /* write the oFFs chunk */
  202230. void /* PRIVATE */
  202231. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202232. int unit_type)
  202233. {
  202234. #ifdef PNG_USE_LOCAL_ARRAYS
  202235. PNG_oFFs;
  202236. #endif
  202237. png_byte buf[9];
  202238. png_debug(1, "in png_write_oFFs\n");
  202239. if (unit_type >= PNG_OFFSET_LAST)
  202240. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202241. png_save_int_32(buf, x_offset);
  202242. png_save_int_32(buf + 4, y_offset);
  202243. buf[8] = (png_byte)unit_type;
  202244. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202245. }
  202246. #endif
  202247. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202248. /* write the pCAL chunk (described in the PNG extensions document) */
  202249. void /* PRIVATE */
  202250. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202251. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202252. {
  202253. #ifdef PNG_USE_LOCAL_ARRAYS
  202254. PNG_pCAL;
  202255. #endif
  202256. png_size_t purpose_len, units_len, total_len;
  202257. png_uint_32p params_len;
  202258. png_byte buf[10];
  202259. png_charp new_purpose;
  202260. int i;
  202261. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202262. if (type >= PNG_EQUATION_LAST)
  202263. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202264. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202265. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202266. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202267. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202268. total_len = purpose_len + units_len + 10;
  202269. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202270. *png_sizeof(png_uint_32)));
  202271. /* Find the length of each parameter, making sure we don't count the
  202272. null terminator for the last parameter. */
  202273. for (i = 0; i < nparams; i++)
  202274. {
  202275. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202276. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202277. total_len += (png_size_t)params_len[i];
  202278. }
  202279. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202280. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202281. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202282. png_save_int_32(buf, X0);
  202283. png_save_int_32(buf + 4, X1);
  202284. buf[8] = (png_byte)type;
  202285. buf[9] = (png_byte)nparams;
  202286. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  202287. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  202288. png_free(png_ptr, new_purpose);
  202289. for (i = 0; i < nparams; i++)
  202290. {
  202291. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  202292. (png_size_t)params_len[i]);
  202293. }
  202294. png_free(png_ptr, params_len);
  202295. png_write_chunk_end(png_ptr);
  202296. }
  202297. #endif
  202298. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  202299. /* write the sCAL chunk */
  202300. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  202301. void /* PRIVATE */
  202302. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  202303. {
  202304. #ifdef PNG_USE_LOCAL_ARRAYS
  202305. PNG_sCAL;
  202306. #endif
  202307. char buf[64];
  202308. png_size_t total_len;
  202309. png_debug(1, "in png_write_sCAL\n");
  202310. buf[0] = (char)unit;
  202311. #if defined(_WIN32_WCE)
  202312. /* sprintf() function is not supported on WindowsCE */
  202313. {
  202314. wchar_t wc_buf[32];
  202315. size_t wc_len;
  202316. swprintf(wc_buf, TEXT("%12.12e"), width);
  202317. wc_len = wcslen(wc_buf);
  202318. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  202319. total_len = wc_len + 2;
  202320. swprintf(wc_buf, TEXT("%12.12e"), height);
  202321. wc_len = wcslen(wc_buf);
  202322. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  202323. NULL, NULL);
  202324. total_len += wc_len;
  202325. }
  202326. #else
  202327. png_snprintf(buf + 1, 63, "%12.12e", width);
  202328. total_len = 1 + png_strlen(buf + 1) + 1;
  202329. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  202330. total_len += png_strlen(buf + total_len);
  202331. #endif
  202332. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202333. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  202334. }
  202335. #else
  202336. #ifdef PNG_FIXED_POINT_SUPPORTED
  202337. void /* PRIVATE */
  202338. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  202339. png_charp height)
  202340. {
  202341. #ifdef PNG_USE_LOCAL_ARRAYS
  202342. PNG_sCAL;
  202343. #endif
  202344. png_byte buf[64];
  202345. png_size_t wlen, hlen, total_len;
  202346. png_debug(1, "in png_write_sCAL_s\n");
  202347. wlen = png_strlen(width);
  202348. hlen = png_strlen(height);
  202349. total_len = wlen + hlen + 2;
  202350. if (total_len > 64)
  202351. {
  202352. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  202353. return;
  202354. }
  202355. buf[0] = (png_byte)unit;
  202356. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  202357. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  202358. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  202359. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  202360. }
  202361. #endif
  202362. #endif
  202363. #endif
  202364. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  202365. /* write the pHYs chunk */
  202366. void /* PRIVATE */
  202367. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  202368. png_uint_32 y_pixels_per_unit,
  202369. int unit_type)
  202370. {
  202371. #ifdef PNG_USE_LOCAL_ARRAYS
  202372. PNG_pHYs;
  202373. #endif
  202374. png_byte buf[9];
  202375. png_debug(1, "in png_write_pHYs\n");
  202376. if (unit_type >= PNG_RESOLUTION_LAST)
  202377. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  202378. png_save_uint_32(buf, x_pixels_per_unit);
  202379. png_save_uint_32(buf + 4, y_pixels_per_unit);
  202380. buf[8] = (png_byte)unit_type;
  202381. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  202382. }
  202383. #endif
  202384. #if defined(PNG_WRITE_tIME_SUPPORTED)
  202385. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  202386. * or png_convert_from_time_t(), or fill in the structure yourself.
  202387. */
  202388. void /* PRIVATE */
  202389. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  202390. {
  202391. #ifdef PNG_USE_LOCAL_ARRAYS
  202392. PNG_tIME;
  202393. #endif
  202394. png_byte buf[7];
  202395. png_debug(1, "in png_write_tIME\n");
  202396. if (mod_time->month > 12 || mod_time->month < 1 ||
  202397. mod_time->day > 31 || mod_time->day < 1 ||
  202398. mod_time->hour > 23 || mod_time->second > 60)
  202399. {
  202400. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  202401. return;
  202402. }
  202403. png_save_uint_16(buf, mod_time->year);
  202404. buf[2] = mod_time->month;
  202405. buf[3] = mod_time->day;
  202406. buf[4] = mod_time->hour;
  202407. buf[5] = mod_time->minute;
  202408. buf[6] = mod_time->second;
  202409. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  202410. }
  202411. #endif
  202412. /* initializes the row writing capability of libpng */
  202413. void /* PRIVATE */
  202414. png_write_start_row(png_structp png_ptr)
  202415. {
  202416. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202417. #ifdef PNG_USE_LOCAL_ARRAYS
  202418. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202419. /* start of interlace block */
  202420. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202421. /* offset to next interlace block */
  202422. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202423. /* start of interlace block in the y direction */
  202424. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202425. /* offset to next interlace block in the y direction */
  202426. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202427. #endif
  202428. #endif
  202429. png_size_t buf_size;
  202430. png_debug(1, "in png_write_start_row\n");
  202431. buf_size = (png_size_t)(PNG_ROWBYTES(
  202432. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  202433. /* set up row buffer */
  202434. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202435. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  202436. #ifndef PNG_NO_WRITE_FILTERING
  202437. /* set up filtering buffer, if using this filter */
  202438. if (png_ptr->do_filter & PNG_FILTER_SUB)
  202439. {
  202440. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  202441. (png_ptr->rowbytes + 1));
  202442. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  202443. }
  202444. /* We only need to keep the previous row if we are using one of these. */
  202445. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  202446. {
  202447. /* set up previous row buffer */
  202448. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  202449. png_memset(png_ptr->prev_row, 0, buf_size);
  202450. if (png_ptr->do_filter & PNG_FILTER_UP)
  202451. {
  202452. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  202453. (png_ptr->rowbytes + 1));
  202454. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  202455. }
  202456. if (png_ptr->do_filter & PNG_FILTER_AVG)
  202457. {
  202458. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  202459. (png_ptr->rowbytes + 1));
  202460. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  202461. }
  202462. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  202463. {
  202464. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  202465. (png_ptr->rowbytes + 1));
  202466. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  202467. }
  202468. #endif /* PNG_NO_WRITE_FILTERING */
  202469. }
  202470. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202471. /* if interlaced, we need to set up width and height of pass */
  202472. if (png_ptr->interlaced)
  202473. {
  202474. if (!(png_ptr->transformations & PNG_INTERLACE))
  202475. {
  202476. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  202477. png_pass_ystart[0]) / png_pass_yinc[0];
  202478. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  202479. png_pass_start[0]) / png_pass_inc[0];
  202480. }
  202481. else
  202482. {
  202483. png_ptr->num_rows = png_ptr->height;
  202484. png_ptr->usr_width = png_ptr->width;
  202485. }
  202486. }
  202487. else
  202488. #endif
  202489. {
  202490. png_ptr->num_rows = png_ptr->height;
  202491. png_ptr->usr_width = png_ptr->width;
  202492. }
  202493. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202494. png_ptr->zstream.next_out = png_ptr->zbuf;
  202495. }
  202496. /* Internal use only. Called when finished processing a row of data. */
  202497. void /* PRIVATE */
  202498. png_write_finish_row(png_structp png_ptr)
  202499. {
  202500. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202501. #ifdef PNG_USE_LOCAL_ARRAYS
  202502. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202503. /* start of interlace block */
  202504. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202505. /* offset to next interlace block */
  202506. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202507. /* start of interlace block in the y direction */
  202508. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  202509. /* offset to next interlace block in the y direction */
  202510. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  202511. #endif
  202512. #endif
  202513. int ret;
  202514. png_debug(1, "in png_write_finish_row\n");
  202515. /* next row */
  202516. png_ptr->row_number++;
  202517. /* see if we are done */
  202518. if (png_ptr->row_number < png_ptr->num_rows)
  202519. return;
  202520. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  202521. /* if interlaced, go to next pass */
  202522. if (png_ptr->interlaced)
  202523. {
  202524. png_ptr->row_number = 0;
  202525. if (png_ptr->transformations & PNG_INTERLACE)
  202526. {
  202527. png_ptr->pass++;
  202528. }
  202529. else
  202530. {
  202531. /* loop until we find a non-zero width or height pass */
  202532. do
  202533. {
  202534. png_ptr->pass++;
  202535. if (png_ptr->pass >= 7)
  202536. break;
  202537. png_ptr->usr_width = (png_ptr->width +
  202538. png_pass_inc[png_ptr->pass] - 1 -
  202539. png_pass_start[png_ptr->pass]) /
  202540. png_pass_inc[png_ptr->pass];
  202541. png_ptr->num_rows = (png_ptr->height +
  202542. png_pass_yinc[png_ptr->pass] - 1 -
  202543. png_pass_ystart[png_ptr->pass]) /
  202544. png_pass_yinc[png_ptr->pass];
  202545. if (png_ptr->transformations & PNG_INTERLACE)
  202546. break;
  202547. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  202548. }
  202549. /* reset the row above the image for the next pass */
  202550. if (png_ptr->pass < 7)
  202551. {
  202552. if (png_ptr->prev_row != NULL)
  202553. png_memset(png_ptr->prev_row, 0,
  202554. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  202555. png_ptr->usr_bit_depth,png_ptr->width))+1);
  202556. return;
  202557. }
  202558. }
  202559. #endif
  202560. /* if we get here, we've just written the last row, so we need
  202561. to flush the compressor */
  202562. do
  202563. {
  202564. /* tell the compressor we are done */
  202565. ret = deflate(&png_ptr->zstream, Z_FINISH);
  202566. /* check for an error */
  202567. if (ret == Z_OK)
  202568. {
  202569. /* check to see if we need more room */
  202570. if (!(png_ptr->zstream.avail_out))
  202571. {
  202572. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  202573. png_ptr->zstream.next_out = png_ptr->zbuf;
  202574. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202575. }
  202576. }
  202577. else if (ret != Z_STREAM_END)
  202578. {
  202579. if (png_ptr->zstream.msg != NULL)
  202580. png_error(png_ptr, png_ptr->zstream.msg);
  202581. else
  202582. png_error(png_ptr, "zlib error");
  202583. }
  202584. } while (ret != Z_STREAM_END);
  202585. /* write any extra space */
  202586. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  202587. {
  202588. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  202589. png_ptr->zstream.avail_out);
  202590. }
  202591. deflateReset(&png_ptr->zstream);
  202592. png_ptr->zstream.data_type = Z_BINARY;
  202593. }
  202594. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  202595. /* Pick out the correct pixels for the interlace pass.
  202596. * The basic idea here is to go through the row with a source
  202597. * pointer and a destination pointer (sp and dp), and copy the
  202598. * correct pixels for the pass. As the row gets compacted,
  202599. * sp will always be >= dp, so we should never overwrite anything.
  202600. * See the default: case for the easiest code to understand.
  202601. */
  202602. void /* PRIVATE */
  202603. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  202604. {
  202605. #ifdef PNG_USE_LOCAL_ARRAYS
  202606. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  202607. /* start of interlace block */
  202608. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  202609. /* offset to next interlace block */
  202610. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  202611. #endif
  202612. png_debug(1, "in png_do_write_interlace\n");
  202613. /* we don't have to do anything on the last pass (6) */
  202614. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  202615. if (row != NULL && row_info != NULL && pass < 6)
  202616. #else
  202617. if (pass < 6)
  202618. #endif
  202619. {
  202620. /* each pixel depth is handled separately */
  202621. switch (row_info->pixel_depth)
  202622. {
  202623. case 1:
  202624. {
  202625. png_bytep sp;
  202626. png_bytep dp;
  202627. int shift;
  202628. int d;
  202629. int value;
  202630. png_uint_32 i;
  202631. png_uint_32 row_width = row_info->width;
  202632. dp = row;
  202633. d = 0;
  202634. shift = 7;
  202635. for (i = png_pass_start[pass]; i < row_width;
  202636. i += png_pass_inc[pass])
  202637. {
  202638. sp = row + (png_size_t)(i >> 3);
  202639. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  202640. d |= (value << shift);
  202641. if (shift == 0)
  202642. {
  202643. shift = 7;
  202644. *dp++ = (png_byte)d;
  202645. d = 0;
  202646. }
  202647. else
  202648. shift--;
  202649. }
  202650. if (shift != 7)
  202651. *dp = (png_byte)d;
  202652. break;
  202653. }
  202654. case 2:
  202655. {
  202656. png_bytep sp;
  202657. png_bytep dp;
  202658. int shift;
  202659. int d;
  202660. int value;
  202661. png_uint_32 i;
  202662. png_uint_32 row_width = row_info->width;
  202663. dp = row;
  202664. shift = 6;
  202665. d = 0;
  202666. for (i = png_pass_start[pass]; i < row_width;
  202667. i += png_pass_inc[pass])
  202668. {
  202669. sp = row + (png_size_t)(i >> 2);
  202670. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  202671. d |= (value << shift);
  202672. if (shift == 0)
  202673. {
  202674. shift = 6;
  202675. *dp++ = (png_byte)d;
  202676. d = 0;
  202677. }
  202678. else
  202679. shift -= 2;
  202680. }
  202681. if (shift != 6)
  202682. *dp = (png_byte)d;
  202683. break;
  202684. }
  202685. case 4:
  202686. {
  202687. png_bytep sp;
  202688. png_bytep dp;
  202689. int shift;
  202690. int d;
  202691. int value;
  202692. png_uint_32 i;
  202693. png_uint_32 row_width = row_info->width;
  202694. dp = row;
  202695. shift = 4;
  202696. d = 0;
  202697. for (i = png_pass_start[pass]; i < row_width;
  202698. i += png_pass_inc[pass])
  202699. {
  202700. sp = row + (png_size_t)(i >> 1);
  202701. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  202702. d |= (value << shift);
  202703. if (shift == 0)
  202704. {
  202705. shift = 4;
  202706. *dp++ = (png_byte)d;
  202707. d = 0;
  202708. }
  202709. else
  202710. shift -= 4;
  202711. }
  202712. if (shift != 4)
  202713. *dp = (png_byte)d;
  202714. break;
  202715. }
  202716. default:
  202717. {
  202718. png_bytep sp;
  202719. png_bytep dp;
  202720. png_uint_32 i;
  202721. png_uint_32 row_width = row_info->width;
  202722. png_size_t pixel_bytes;
  202723. /* start at the beginning */
  202724. dp = row;
  202725. /* find out how many bytes each pixel takes up */
  202726. pixel_bytes = (row_info->pixel_depth >> 3);
  202727. /* loop through the row, only looking at the pixels that
  202728. matter */
  202729. for (i = png_pass_start[pass]; i < row_width;
  202730. i += png_pass_inc[pass])
  202731. {
  202732. /* find out where the original pixel is */
  202733. sp = row + (png_size_t)i * pixel_bytes;
  202734. /* move the pixel */
  202735. if (dp != sp)
  202736. png_memcpy(dp, sp, pixel_bytes);
  202737. /* next pixel */
  202738. dp += pixel_bytes;
  202739. }
  202740. break;
  202741. }
  202742. }
  202743. /* set new row width */
  202744. row_info->width = (row_info->width +
  202745. png_pass_inc[pass] - 1 -
  202746. png_pass_start[pass]) /
  202747. png_pass_inc[pass];
  202748. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  202749. row_info->width);
  202750. }
  202751. }
  202752. #endif
  202753. /* This filters the row, chooses which filter to use, if it has not already
  202754. * been specified by the application, and then writes the row out with the
  202755. * chosen filter.
  202756. */
  202757. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  202758. #define PNG_HISHIFT 10
  202759. #define PNG_LOMASK ((png_uint_32)0xffffL)
  202760. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  202761. void /* PRIVATE */
  202762. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  202763. {
  202764. png_bytep best_row;
  202765. #ifndef PNG_NO_WRITE_FILTER
  202766. png_bytep prev_row, row_buf;
  202767. png_uint_32 mins, bpp;
  202768. png_byte filter_to_do = png_ptr->do_filter;
  202769. png_uint_32 row_bytes = row_info->rowbytes;
  202770. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202771. int num_p_filters = (int)png_ptr->num_prev_filters;
  202772. #endif
  202773. png_debug(1, "in png_write_find_filter\n");
  202774. /* find out how many bytes offset each pixel is */
  202775. bpp = (row_info->pixel_depth + 7) >> 3;
  202776. prev_row = png_ptr->prev_row;
  202777. #endif
  202778. best_row = png_ptr->row_buf;
  202779. #ifndef PNG_NO_WRITE_FILTER
  202780. row_buf = best_row;
  202781. mins = PNG_MAXSUM;
  202782. /* The prediction method we use is to find which method provides the
  202783. * smallest value when summing the absolute values of the distances
  202784. * from zero, using anything >= 128 as negative numbers. This is known
  202785. * as the "minimum sum of absolute differences" heuristic. Other
  202786. * heuristics are the "weighted minimum sum of absolute differences"
  202787. * (experimental and can in theory improve compression), and the "zlib
  202788. * predictive" method (not implemented yet), which does test compressions
  202789. * of lines using different filter methods, and then chooses the
  202790. * (series of) filter(s) that give minimum compressed data size (VERY
  202791. * computationally expensive).
  202792. *
  202793. * GRR 980525: consider also
  202794. * (1) minimum sum of absolute differences from running average (i.e.,
  202795. * keep running sum of non-absolute differences & count of bytes)
  202796. * [track dispersion, too? restart average if dispersion too large?]
  202797. * (1b) minimum sum of absolute differences from sliding average, probably
  202798. * with window size <= deflate window (usually 32K)
  202799. * (2) minimum sum of squared differences from zero or running average
  202800. * (i.e., ~ root-mean-square approach)
  202801. */
  202802. /* We don't need to test the 'no filter' case if this is the only filter
  202803. * that has been chosen, as it doesn't actually do anything to the data.
  202804. */
  202805. if ((filter_to_do & PNG_FILTER_NONE) &&
  202806. filter_to_do != PNG_FILTER_NONE)
  202807. {
  202808. png_bytep rp;
  202809. png_uint_32 sum = 0;
  202810. png_uint_32 i;
  202811. int v;
  202812. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  202813. {
  202814. v = *rp;
  202815. sum += (v < 128) ? v : 256 - v;
  202816. }
  202817. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202818. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202819. {
  202820. png_uint_32 sumhi, sumlo;
  202821. int j;
  202822. sumlo = sum & PNG_LOMASK;
  202823. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  202824. /* Reduce the sum if we match any of the previous rows */
  202825. for (j = 0; j < num_p_filters; j++)
  202826. {
  202827. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  202828. {
  202829. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  202830. PNG_WEIGHT_SHIFT;
  202831. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  202832. PNG_WEIGHT_SHIFT;
  202833. }
  202834. }
  202835. /* Factor in the cost of this filter (this is here for completeness,
  202836. * but it makes no sense to have a "cost" for the NONE filter, as
  202837. * it has the minimum possible computational cost - none).
  202838. */
  202839. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202840. PNG_COST_SHIFT;
  202841. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  202842. PNG_COST_SHIFT;
  202843. if (sumhi > PNG_HIMASK)
  202844. sum = PNG_MAXSUM;
  202845. else
  202846. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202847. }
  202848. #endif
  202849. mins = sum;
  202850. }
  202851. /* sub filter */
  202852. if (filter_to_do == PNG_FILTER_SUB)
  202853. /* it's the only filter so no testing is needed */
  202854. {
  202855. png_bytep rp, lp, dp;
  202856. png_uint_32 i;
  202857. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202858. i++, rp++, dp++)
  202859. {
  202860. *dp = *rp;
  202861. }
  202862. for (lp = row_buf + 1; i < row_bytes;
  202863. i++, rp++, lp++, dp++)
  202864. {
  202865. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202866. }
  202867. best_row = png_ptr->sub_row;
  202868. }
  202869. else if (filter_to_do & PNG_FILTER_SUB)
  202870. {
  202871. png_bytep rp, dp, lp;
  202872. png_uint_32 sum = 0, lmins = mins;
  202873. png_uint_32 i;
  202874. int v;
  202875. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202876. /* We temporarily increase the "minimum sum" by the factor we
  202877. * would reduce the sum of this filter, so that we can do the
  202878. * early exit comparison without scaling the sum each time.
  202879. */
  202880. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202881. {
  202882. int j;
  202883. png_uint_32 lmhi, lmlo;
  202884. lmlo = lmins & PNG_LOMASK;
  202885. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202886. for (j = 0; j < num_p_filters; j++)
  202887. {
  202888. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202889. {
  202890. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202891. PNG_WEIGHT_SHIFT;
  202892. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202893. PNG_WEIGHT_SHIFT;
  202894. }
  202895. }
  202896. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202897. PNG_COST_SHIFT;
  202898. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202899. PNG_COST_SHIFT;
  202900. if (lmhi > PNG_HIMASK)
  202901. lmins = PNG_MAXSUM;
  202902. else
  202903. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202904. }
  202905. #endif
  202906. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  202907. i++, rp++, dp++)
  202908. {
  202909. v = *dp = *rp;
  202910. sum += (v < 128) ? v : 256 - v;
  202911. }
  202912. for (lp = row_buf + 1; i < row_bytes;
  202913. i++, rp++, lp++, dp++)
  202914. {
  202915. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  202916. sum += (v < 128) ? v : 256 - v;
  202917. if (sum > lmins) /* We are already worse, don't continue. */
  202918. break;
  202919. }
  202920. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202921. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202922. {
  202923. int j;
  202924. png_uint_32 sumhi, sumlo;
  202925. sumlo = sum & PNG_LOMASK;
  202926. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  202927. for (j = 0; j < num_p_filters; j++)
  202928. {
  202929. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  202930. {
  202931. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  202932. PNG_WEIGHT_SHIFT;
  202933. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  202934. PNG_WEIGHT_SHIFT;
  202935. }
  202936. }
  202937. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202938. PNG_COST_SHIFT;
  202939. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  202940. PNG_COST_SHIFT;
  202941. if (sumhi > PNG_HIMASK)
  202942. sum = PNG_MAXSUM;
  202943. else
  202944. sum = (sumhi << PNG_HISHIFT) + sumlo;
  202945. }
  202946. #endif
  202947. if (sum < mins)
  202948. {
  202949. mins = sum;
  202950. best_row = png_ptr->sub_row;
  202951. }
  202952. }
  202953. /* up filter */
  202954. if (filter_to_do == PNG_FILTER_UP)
  202955. {
  202956. png_bytep rp, dp, pp;
  202957. png_uint_32 i;
  202958. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  202959. pp = prev_row + 1; i < row_bytes;
  202960. i++, rp++, pp++, dp++)
  202961. {
  202962. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  202963. }
  202964. best_row = png_ptr->up_row;
  202965. }
  202966. else if (filter_to_do & PNG_FILTER_UP)
  202967. {
  202968. png_bytep rp, dp, pp;
  202969. png_uint_32 sum = 0, lmins = mins;
  202970. png_uint_32 i;
  202971. int v;
  202972. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  202973. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  202974. {
  202975. int j;
  202976. png_uint_32 lmhi, lmlo;
  202977. lmlo = lmins & PNG_LOMASK;
  202978. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  202979. for (j = 0; j < num_p_filters; j++)
  202980. {
  202981. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  202982. {
  202983. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  202984. PNG_WEIGHT_SHIFT;
  202985. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  202986. PNG_WEIGHT_SHIFT;
  202987. }
  202988. }
  202989. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202990. PNG_COST_SHIFT;
  202991. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  202992. PNG_COST_SHIFT;
  202993. if (lmhi > PNG_HIMASK)
  202994. lmins = PNG_MAXSUM;
  202995. else
  202996. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  202997. }
  202998. #endif
  202999. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  203000. pp = prev_row + 1; i < row_bytes; i++)
  203001. {
  203002. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203003. sum += (v < 128) ? v : 256 - v;
  203004. if (sum > lmins) /* We are already worse, don't continue. */
  203005. break;
  203006. }
  203007. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203008. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203009. {
  203010. int j;
  203011. png_uint_32 sumhi, sumlo;
  203012. sumlo = sum & PNG_LOMASK;
  203013. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203014. for (j = 0; j < num_p_filters; j++)
  203015. {
  203016. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  203017. {
  203018. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203019. PNG_WEIGHT_SHIFT;
  203020. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203021. PNG_WEIGHT_SHIFT;
  203022. }
  203023. }
  203024. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203025. PNG_COST_SHIFT;
  203026. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203027. PNG_COST_SHIFT;
  203028. if (sumhi > PNG_HIMASK)
  203029. sum = PNG_MAXSUM;
  203030. else
  203031. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203032. }
  203033. #endif
  203034. if (sum < mins)
  203035. {
  203036. mins = sum;
  203037. best_row = png_ptr->up_row;
  203038. }
  203039. }
  203040. /* avg filter */
  203041. if (filter_to_do == PNG_FILTER_AVG)
  203042. {
  203043. png_bytep rp, dp, pp, lp;
  203044. png_uint_32 i;
  203045. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203046. pp = prev_row + 1; i < bpp; i++)
  203047. {
  203048. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203049. }
  203050. for (lp = row_buf + 1; i < row_bytes; i++)
  203051. {
  203052. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203053. & 0xff);
  203054. }
  203055. best_row = png_ptr->avg_row;
  203056. }
  203057. else if (filter_to_do & PNG_FILTER_AVG)
  203058. {
  203059. png_bytep rp, dp, pp, lp;
  203060. png_uint_32 sum = 0, lmins = mins;
  203061. png_uint_32 i;
  203062. int v;
  203063. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203064. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203065. {
  203066. int j;
  203067. png_uint_32 lmhi, lmlo;
  203068. lmlo = lmins & PNG_LOMASK;
  203069. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203070. for (j = 0; j < num_p_filters; j++)
  203071. {
  203072. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203073. {
  203074. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203075. PNG_WEIGHT_SHIFT;
  203076. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203077. PNG_WEIGHT_SHIFT;
  203078. }
  203079. }
  203080. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203081. PNG_COST_SHIFT;
  203082. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203083. PNG_COST_SHIFT;
  203084. if (lmhi > PNG_HIMASK)
  203085. lmins = PNG_MAXSUM;
  203086. else
  203087. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203088. }
  203089. #endif
  203090. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203091. pp = prev_row + 1; i < bpp; i++)
  203092. {
  203093. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203094. sum += (v < 128) ? v : 256 - v;
  203095. }
  203096. for (lp = row_buf + 1; i < row_bytes; i++)
  203097. {
  203098. v = *dp++ =
  203099. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203100. sum += (v < 128) ? v : 256 - v;
  203101. if (sum > lmins) /* We are already worse, don't continue. */
  203102. break;
  203103. }
  203104. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203105. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203106. {
  203107. int j;
  203108. png_uint_32 sumhi, sumlo;
  203109. sumlo = sum & PNG_LOMASK;
  203110. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203111. for (j = 0; j < num_p_filters; j++)
  203112. {
  203113. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203114. {
  203115. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203116. PNG_WEIGHT_SHIFT;
  203117. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203118. PNG_WEIGHT_SHIFT;
  203119. }
  203120. }
  203121. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203122. PNG_COST_SHIFT;
  203123. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203124. PNG_COST_SHIFT;
  203125. if (sumhi > PNG_HIMASK)
  203126. sum = PNG_MAXSUM;
  203127. else
  203128. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203129. }
  203130. #endif
  203131. if (sum < mins)
  203132. {
  203133. mins = sum;
  203134. best_row = png_ptr->avg_row;
  203135. }
  203136. }
  203137. /* Paeth filter */
  203138. if (filter_to_do == PNG_FILTER_PAETH)
  203139. {
  203140. png_bytep rp, dp, pp, cp, lp;
  203141. png_uint_32 i;
  203142. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203143. pp = prev_row + 1; i < bpp; i++)
  203144. {
  203145. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203146. }
  203147. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203148. {
  203149. int a, b, c, pa, pb, pc, p;
  203150. b = *pp++;
  203151. c = *cp++;
  203152. a = *lp++;
  203153. p = b - c;
  203154. pc = a - c;
  203155. #ifdef PNG_USE_ABS
  203156. pa = abs(p);
  203157. pb = abs(pc);
  203158. pc = abs(p + pc);
  203159. #else
  203160. pa = p < 0 ? -p : p;
  203161. pb = pc < 0 ? -pc : pc;
  203162. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203163. #endif
  203164. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203165. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203166. }
  203167. best_row = png_ptr->paeth_row;
  203168. }
  203169. else if (filter_to_do & PNG_FILTER_PAETH)
  203170. {
  203171. png_bytep rp, dp, pp, cp, lp;
  203172. png_uint_32 sum = 0, lmins = mins;
  203173. png_uint_32 i;
  203174. int v;
  203175. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203176. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203177. {
  203178. int j;
  203179. png_uint_32 lmhi, lmlo;
  203180. lmlo = lmins & PNG_LOMASK;
  203181. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203182. for (j = 0; j < num_p_filters; j++)
  203183. {
  203184. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203185. {
  203186. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203187. PNG_WEIGHT_SHIFT;
  203188. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203189. PNG_WEIGHT_SHIFT;
  203190. }
  203191. }
  203192. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203193. PNG_COST_SHIFT;
  203194. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203195. PNG_COST_SHIFT;
  203196. if (lmhi > PNG_HIMASK)
  203197. lmins = PNG_MAXSUM;
  203198. else
  203199. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203200. }
  203201. #endif
  203202. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203203. pp = prev_row + 1; i < bpp; i++)
  203204. {
  203205. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203206. sum += (v < 128) ? v : 256 - v;
  203207. }
  203208. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203209. {
  203210. int a, b, c, pa, pb, pc, p;
  203211. b = *pp++;
  203212. c = *cp++;
  203213. a = *lp++;
  203214. #ifndef PNG_SLOW_PAETH
  203215. p = b - c;
  203216. pc = a - c;
  203217. #ifdef PNG_USE_ABS
  203218. pa = abs(p);
  203219. pb = abs(pc);
  203220. pc = abs(p + pc);
  203221. #else
  203222. pa = p < 0 ? -p : p;
  203223. pb = pc < 0 ? -pc : pc;
  203224. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203225. #endif
  203226. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203227. #else /* PNG_SLOW_PAETH */
  203228. p = a + b - c;
  203229. pa = abs(p - a);
  203230. pb = abs(p - b);
  203231. pc = abs(p - c);
  203232. if (pa <= pb && pa <= pc)
  203233. p = a;
  203234. else if (pb <= pc)
  203235. p = b;
  203236. else
  203237. p = c;
  203238. #endif /* PNG_SLOW_PAETH */
  203239. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203240. sum += (v < 128) ? v : 256 - v;
  203241. if (sum > lmins) /* We are already worse, don't continue. */
  203242. break;
  203243. }
  203244. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203245. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203246. {
  203247. int j;
  203248. png_uint_32 sumhi, sumlo;
  203249. sumlo = sum & PNG_LOMASK;
  203250. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203251. for (j = 0; j < num_p_filters; j++)
  203252. {
  203253. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203254. {
  203255. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203256. PNG_WEIGHT_SHIFT;
  203257. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203258. PNG_WEIGHT_SHIFT;
  203259. }
  203260. }
  203261. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203262. PNG_COST_SHIFT;
  203263. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203264. PNG_COST_SHIFT;
  203265. if (sumhi > PNG_HIMASK)
  203266. sum = PNG_MAXSUM;
  203267. else
  203268. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203269. }
  203270. #endif
  203271. if (sum < mins)
  203272. {
  203273. best_row = png_ptr->paeth_row;
  203274. }
  203275. }
  203276. #endif /* PNG_NO_WRITE_FILTER */
  203277. /* Do the actual writing of the filtered row data from the chosen filter. */
  203278. png_write_filtered_row(png_ptr, best_row);
  203279. #ifndef PNG_NO_WRITE_FILTER
  203280. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203281. /* Save the type of filter we picked this time for future calculations */
  203282. if (png_ptr->num_prev_filters > 0)
  203283. {
  203284. int j;
  203285. for (j = 1; j < num_p_filters; j++)
  203286. {
  203287. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  203288. }
  203289. png_ptr->prev_filters[j] = best_row[0];
  203290. }
  203291. #endif
  203292. #endif /* PNG_NO_WRITE_FILTER */
  203293. }
  203294. /* Do the actual writing of a previously filtered row. */
  203295. void /* PRIVATE */
  203296. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  203297. {
  203298. png_debug(1, "in png_write_filtered_row\n");
  203299. png_debug1(2, "filter = %d\n", filtered_row[0]);
  203300. /* set up the zlib input buffer */
  203301. png_ptr->zstream.next_in = filtered_row;
  203302. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  203303. /* repeat until we have compressed all the data */
  203304. do
  203305. {
  203306. int ret; /* return of zlib */
  203307. /* compress the data */
  203308. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  203309. /* check for compression errors */
  203310. if (ret != Z_OK)
  203311. {
  203312. if (png_ptr->zstream.msg != NULL)
  203313. png_error(png_ptr, png_ptr->zstream.msg);
  203314. else
  203315. png_error(png_ptr, "zlib error");
  203316. }
  203317. /* see if it is time to write another IDAT */
  203318. if (!(png_ptr->zstream.avail_out))
  203319. {
  203320. /* write the IDAT and reset the zlib output buffer */
  203321. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203322. png_ptr->zstream.next_out = png_ptr->zbuf;
  203323. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203324. }
  203325. /* repeat until all data has been compressed */
  203326. } while (png_ptr->zstream.avail_in);
  203327. /* swap the current and previous rows */
  203328. if (png_ptr->prev_row != NULL)
  203329. {
  203330. png_bytep tptr;
  203331. tptr = png_ptr->prev_row;
  203332. png_ptr->prev_row = png_ptr->row_buf;
  203333. png_ptr->row_buf = tptr;
  203334. }
  203335. /* finish row - updates counters and flushes zlib if last row */
  203336. png_write_finish_row(png_ptr);
  203337. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  203338. png_ptr->flush_rows++;
  203339. if (png_ptr->flush_dist > 0 &&
  203340. png_ptr->flush_rows >= png_ptr->flush_dist)
  203341. {
  203342. png_write_flush(png_ptr);
  203343. }
  203344. #endif
  203345. }
  203346. #endif /* PNG_WRITE_SUPPORTED */
  203347. /*** End of inlined file: pngwutil.c ***/
  203348. #else
  203349. extern "C"
  203350. {
  203351. #include <png.h>
  203352. #include <pngconf.h>
  203353. }
  203354. #endif
  203355. }
  203356. #undef max
  203357. #undef min
  203358. #if JUCE_MSVC
  203359. #pragma warning (pop)
  203360. #endif
  203361. BEGIN_JUCE_NAMESPACE
  203362. using ::calloc;
  203363. using ::malloc;
  203364. using ::free;
  203365. namespace PNGHelpers
  203366. {
  203367. using namespace pnglibNamespace;
  203368. static void JUCE_CDECL readCallback (png_structp png, png_bytep data, png_size_t length)
  203369. {
  203370. static_cast<InputStream*> (png_get_io_ptr (png))->read (data, (int) length);
  203371. }
  203372. static void JUCE_CDECL writeDataCallback (png_structp png, png_bytep data, png_size_t length)
  203373. {
  203374. static_cast<OutputStream*> (png_get_io_ptr (png))->write (data, (int) length);
  203375. }
  203376. struct PNGErrorStruct {};
  203377. static void JUCE_CDECL errorCallback (png_structp, png_const_charp)
  203378. {
  203379. throw PNGErrorStruct();
  203380. }
  203381. }
  203382. PNGImageFormat::PNGImageFormat() {}
  203383. PNGImageFormat::~PNGImageFormat() {}
  203384. const String PNGImageFormat::getFormatName()
  203385. {
  203386. return "PNG";
  203387. }
  203388. bool PNGImageFormat::canUnderstand (InputStream& in)
  203389. {
  203390. const int bytesNeeded = 4;
  203391. char header [bytesNeeded];
  203392. return in.read (header, bytesNeeded) == bytesNeeded
  203393. && header[1] == 'P'
  203394. && header[2] == 'N'
  203395. && header[3] == 'G';
  203396. }
  203397. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203398. const Image juce_loadWithCoreImage (InputStream& input);
  203399. #endif
  203400. const Image PNGImageFormat::decodeImage (InputStream& in)
  203401. {
  203402. #if (JUCE_MAC || JUCE_IOS) && USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  203403. return juce_loadWithCoreImage (in);
  203404. #else
  203405. using namespace pnglibNamespace;
  203406. Image image;
  203407. png_structp pngReadStruct;
  203408. png_infop pngInfoStruct;
  203409. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203410. if (pngReadStruct != 0)
  203411. {
  203412. pngInfoStruct = png_create_info_struct (pngReadStruct);
  203413. if (pngInfoStruct == 0)
  203414. {
  203415. png_destroy_read_struct (&pngReadStruct, 0, 0);
  203416. return Image::null;
  203417. }
  203418. png_set_error_fn (pngReadStruct, 0, PNGHelpers::errorCallback, PNGHelpers::errorCallback );
  203419. // read the header..
  203420. png_set_read_fn (pngReadStruct, &in, PNGHelpers::readCallback);
  203421. png_uint_32 width, height;
  203422. int bitDepth, colorType, interlaceType;
  203423. png_read_info (pngReadStruct, pngInfoStruct);
  203424. png_get_IHDR (pngReadStruct, pngInfoStruct,
  203425. &width, &height,
  203426. &bitDepth, &colorType,
  203427. &interlaceType, 0, 0);
  203428. if (bitDepth == 16)
  203429. png_set_strip_16 (pngReadStruct);
  203430. if (colorType == PNG_COLOR_TYPE_PALETTE)
  203431. png_set_expand (pngReadStruct);
  203432. if (bitDepth < 8)
  203433. png_set_expand (pngReadStruct);
  203434. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  203435. png_set_expand (pngReadStruct);
  203436. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  203437. png_set_gray_to_rgb (pngReadStruct);
  203438. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  203439. bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  203440. || pngInfoStruct->num_trans > 0;
  203441. // Load the image into a temp buffer in the pnglib format..
  203442. HeapBlock <uint8> tempBuffer (height * (width << 2));
  203443. {
  203444. HeapBlock <png_bytep> rows (height);
  203445. for (int y = (int) height; --y >= 0;)
  203446. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  203447. png_read_image (pngReadStruct, rows);
  203448. png_read_end (pngReadStruct, pngInfoStruct);
  203449. }
  203450. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  203451. // now convert the data to a juce image format..
  203452. image = Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  203453. (int) width, (int) height, hasAlphaChan);
  203454. image.getProperties()->set ("originalImageHadAlpha", image.hasAlphaChannel());
  203455. hasAlphaChan = image.hasAlphaChannel(); // (the native image creator may not give back what we expect)
  203456. const Image::BitmapData destData (image, true);
  203457. uint8* srcRow = tempBuffer;
  203458. uint8* destRow = destData.data;
  203459. for (int y = 0; y < (int) height; ++y)
  203460. {
  203461. const uint8* src = srcRow;
  203462. srcRow += (width << 2);
  203463. uint8* dest = destRow;
  203464. destRow += destData.lineStride;
  203465. if (hasAlphaChan)
  203466. {
  203467. for (int i = (int) width; --i >= 0;)
  203468. {
  203469. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  203470. ((PixelARGB*) dest)->premultiply();
  203471. dest += destData.pixelStride;
  203472. src += 4;
  203473. }
  203474. }
  203475. else
  203476. {
  203477. for (int i = (int) width; --i >= 0;)
  203478. {
  203479. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  203480. dest += destData.pixelStride;
  203481. src += 4;
  203482. }
  203483. }
  203484. }
  203485. }
  203486. return image;
  203487. #endif
  203488. }
  203489. bool PNGImageFormat::writeImageToStream (const Image& image, OutputStream& out)
  203490. {
  203491. using namespace pnglibNamespace;
  203492. const int width = image.getWidth();
  203493. const int height = image.getHeight();
  203494. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  203495. if (pngWriteStruct == 0)
  203496. return false;
  203497. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  203498. if (pngInfoStruct == 0)
  203499. {
  203500. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  203501. return false;
  203502. }
  203503. png_set_write_fn (pngWriteStruct, &out, PNGHelpers::writeDataCallback, 0);
  203504. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  203505. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  203506. : PNG_COLOR_TYPE_RGB,
  203507. PNG_INTERLACE_NONE,
  203508. PNG_COMPRESSION_TYPE_BASE,
  203509. PNG_FILTER_TYPE_BASE);
  203510. HeapBlock <uint8> rowData (width * 4);
  203511. png_color_8 sig_bit;
  203512. sig_bit.red = 8;
  203513. sig_bit.green = 8;
  203514. sig_bit.blue = 8;
  203515. sig_bit.alpha = 8;
  203516. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  203517. png_write_info (pngWriteStruct, pngInfoStruct);
  203518. png_set_shift (pngWriteStruct, &sig_bit);
  203519. png_set_packing (pngWriteStruct);
  203520. const Image::BitmapData srcData (image, false);
  203521. for (int y = 0; y < height; ++y)
  203522. {
  203523. uint8* dst = rowData;
  203524. const uint8* src = srcData.getLinePointer (y);
  203525. if (image.hasAlphaChannel())
  203526. {
  203527. for (int i = width; --i >= 0;)
  203528. {
  203529. PixelARGB p (*(const PixelARGB*) src);
  203530. p.unpremultiply();
  203531. *dst++ = p.getRed();
  203532. *dst++ = p.getGreen();
  203533. *dst++ = p.getBlue();
  203534. *dst++ = p.getAlpha();
  203535. src += srcData.pixelStride;
  203536. }
  203537. }
  203538. else
  203539. {
  203540. for (int i = width; --i >= 0;)
  203541. {
  203542. *dst++ = ((const PixelRGB*) src)->getRed();
  203543. *dst++ = ((const PixelRGB*) src)->getGreen();
  203544. *dst++ = ((const PixelRGB*) src)->getBlue();
  203545. src += srcData.pixelStride;
  203546. }
  203547. }
  203548. png_bytep rowPtr = rowData;
  203549. png_write_rows (pngWriteStruct, &rowPtr, 1);
  203550. }
  203551. png_write_end (pngWriteStruct, pngInfoStruct);
  203552. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  203553. out.flush();
  203554. return true;
  203555. }
  203556. END_JUCE_NAMESPACE
  203557. /*** End of inlined file: juce_PNGLoader.cpp ***/
  203558. #endif
  203559. //==============================================================================
  203560. #if JUCE_BUILD_NATIVE
  203561. // Non-public headers that are needed by more than one platform must be included
  203562. // before the platform-specific sections..
  203563. BEGIN_JUCE_NAMESPACE
  203564. /*** Start of inlined file: juce_MidiDataConcatenator.h ***/
  203565. #ifndef __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203566. #define __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203567. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  203568. /**
  203569. Helper class that takes chunks of incoming midi bytes, packages them into
  203570. messages, and dispatches them to a midi callback.
  203571. */
  203572. class MidiDataConcatenator
  203573. {
  203574. public:
  203575. MidiDataConcatenator (const int initialBufferSize)
  203576. : pendingData (initialBufferSize),
  203577. pendingBytes (0), pendingDataTime (0)
  203578. {
  203579. }
  203580. void reset()
  203581. {
  203582. pendingBytes = 0;
  203583. pendingDataTime = 0;
  203584. }
  203585. void pushMidiData (const void* data, int numBytes, double time,
  203586. MidiInput* input, MidiInputCallback& callback)
  203587. {
  203588. const uint8* d = static_cast <const uint8*> (data);
  203589. while (numBytes > 0)
  203590. {
  203591. if (pendingBytes > 0 || d[0] == 0xf0)
  203592. {
  203593. processSysex (d, numBytes, time, input, callback);
  203594. }
  203595. else
  203596. {
  203597. int used = 0;
  203598. const MidiMessage m (d, numBytes, used, 0, time);
  203599. if (used <= 0)
  203600. break; // malformed message..
  203601. callback.handleIncomingMidiMessage (input, m);
  203602. numBytes -= used;
  203603. d += used;
  203604. }
  203605. }
  203606. }
  203607. private:
  203608. void processSysex (const uint8*& d, int& numBytes, double time,
  203609. MidiInput* input, MidiInputCallback& callback)
  203610. {
  203611. if (*d == 0xf0)
  203612. {
  203613. pendingBytes = 0;
  203614. pendingDataTime = time;
  203615. }
  203616. pendingData.ensureSize (pendingBytes + numBytes, false);
  203617. uint8* totalMessage = static_cast<uint8*> (pendingData.getData());
  203618. uint8* dest = totalMessage + pendingBytes;
  203619. do
  203620. {
  203621. if (pendingBytes > 0 && *d >= 0x80)
  203622. {
  203623. if (*d >= 0xfa || *d == 0xf8)
  203624. {
  203625. callback.handleIncomingMidiMessage (input, MidiMessage (*d, time));
  203626. ++d;
  203627. --numBytes;
  203628. }
  203629. else
  203630. {
  203631. if (*d == 0xf7)
  203632. {
  203633. *dest++ = *d++;
  203634. pendingBytes++;
  203635. --numBytes;
  203636. }
  203637. break;
  203638. }
  203639. }
  203640. else
  203641. {
  203642. *dest++ = *d++;
  203643. pendingBytes++;
  203644. --numBytes;
  203645. }
  203646. }
  203647. while (numBytes > 0);
  203648. if (pendingBytes > 0)
  203649. {
  203650. if (totalMessage [pendingBytes - 1] == 0xf7)
  203651. {
  203652. callback.handleIncomingMidiMessage (input, MidiMessage (totalMessage, pendingBytes, pendingDataTime));
  203653. pendingBytes = 0;
  203654. }
  203655. else
  203656. {
  203657. callback.handlePartialSysexMessage (input, totalMessage, pendingBytes, pendingDataTime);
  203658. }
  203659. }
  203660. }
  203661. MemoryBlock pendingData;
  203662. int pendingBytes;
  203663. double pendingDataTime;
  203664. MidiDataConcatenator (const MidiDataConcatenator&);
  203665. MidiDataConcatenator& operator= (const MidiDataConcatenator&);
  203666. };
  203667. #endif
  203668. #endif // __JUCE_MIDIDATACONCATENATOR_JUCEHEADER__
  203669. /*** End of inlined file: juce_MidiDataConcatenator.h ***/
  203670. END_JUCE_NAMESPACE
  203671. #if JUCE_WINDOWS
  203672. /*** Start of inlined file: juce_win32_NativeCode.cpp ***/
  203673. /*
  203674. This file wraps together all the win32-specific code, so that
  203675. we can include all the native headers just once, and compile all our
  203676. platform-specific stuff in one big lump, keeping it out of the way of
  203677. the rest of the codebase.
  203678. */
  203679. #if JUCE_WINDOWS
  203680. BEGIN_JUCE_NAMESPACE
  203681. #define JUCE_INCLUDED_FILE 1
  203682. // Now include the actual code files..
  203683. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203684. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203685. // compiled on its own).
  203686. #if JUCE_INCLUDED_FILE
  203687. /*** Start of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203688. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203689. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203690. #ifndef DOXYGEN
  203691. // use with DynamicLibraryLoader to simplify importing functions
  203692. //
  203693. // functionName: function to import
  203694. // localFunctionName: name you want to use to actually call it (must be different)
  203695. // returnType: the return type
  203696. // object: the DynamicLibraryLoader to use
  203697. // params: list of params (bracketed)
  203698. //
  203699. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  203700. typedef returnType (WINAPI *type##localFunctionName) params; \
  203701. type##localFunctionName localFunctionName \
  203702. = (type##localFunctionName)object.findProcAddress (#functionName);
  203703. // loads and unloads a DLL automatically
  203704. class JUCE_API DynamicLibraryLoader
  203705. {
  203706. public:
  203707. DynamicLibraryLoader (const String& name);
  203708. ~DynamicLibraryLoader();
  203709. void* findProcAddress (const String& functionName);
  203710. private:
  203711. void* libHandle;
  203712. };
  203713. #endif
  203714. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  203715. /*** End of inlined file: juce_win32_DynamicLibraryLoader.h ***/
  203716. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  203717. {
  203718. libHandle = LoadLibrary (name);
  203719. }
  203720. DynamicLibraryLoader::~DynamicLibraryLoader()
  203721. {
  203722. FreeLibrary ((HMODULE) libHandle);
  203723. }
  203724. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  203725. {
  203726. return (void*) GetProcAddress ((HMODULE) libHandle, functionName.toCString()); // (void* cast is required for mingw)
  203727. }
  203728. #endif
  203729. /*** End of inlined file: juce_win32_DynamicLibraryLoader.cpp ***/
  203730. /*** Start of inlined file: juce_win32_SystemStats.cpp ***/
  203731. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203732. // compiled on its own).
  203733. #if JUCE_INCLUDED_FILE
  203734. extern void juce_initialiseThreadEvents();
  203735. void Logger::outputDebugString (const String& text)
  203736. {
  203737. OutputDebugString (text + "\n");
  203738. }
  203739. static int64 hiResTicksPerSecond;
  203740. static double hiResTicksScaleFactor;
  203741. #if JUCE_USE_INTRINSICS
  203742. // CPU info functions using intrinsics...
  203743. #pragma intrinsic (__cpuid)
  203744. #pragma intrinsic (__rdtsc)
  203745. const String SystemStats::getCpuVendor()
  203746. {
  203747. int info [4];
  203748. __cpuid (info, 0);
  203749. char v [12];
  203750. memcpy (v, info + 1, 4);
  203751. memcpy (v + 4, info + 3, 4);
  203752. memcpy (v + 8, info + 2, 4);
  203753. return String (v, 12);
  203754. }
  203755. #else
  203756. // CPU info functions using old fashioned inline asm...
  203757. static void juce_getCpuVendor (char* const v)
  203758. {
  203759. int vendor[4];
  203760. zeromem (vendor, 16);
  203761. #ifdef JUCE_64BIT
  203762. #else
  203763. #ifndef __MINGW32__
  203764. __try
  203765. #endif
  203766. {
  203767. #if JUCE_GCC
  203768. unsigned int dummy = 0;
  203769. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  203770. #else
  203771. __asm
  203772. {
  203773. mov eax, 0
  203774. cpuid
  203775. mov [vendor], ebx
  203776. mov [vendor + 4], edx
  203777. mov [vendor + 8], ecx
  203778. }
  203779. #endif
  203780. }
  203781. #ifndef __MINGW32__
  203782. __except (EXCEPTION_EXECUTE_HANDLER)
  203783. {
  203784. *v = 0;
  203785. }
  203786. #endif
  203787. #endif
  203788. memcpy (v, vendor, 16);
  203789. }
  203790. const String SystemStats::getCpuVendor()
  203791. {
  203792. char v [16];
  203793. juce_getCpuVendor (v);
  203794. return String (v, 16);
  203795. }
  203796. #endif
  203797. void SystemStats::initialiseStats()
  203798. {
  203799. juce_initialiseThreadEvents();
  203800. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  203801. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  203802. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  203803. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  203804. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  203805. #else
  203806. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  203807. #endif
  203808. {
  203809. SYSTEM_INFO systemInfo;
  203810. GetSystemInfo (&systemInfo);
  203811. cpuFlags.numCpus = systemInfo.dwNumberOfProcessors;
  203812. }
  203813. LARGE_INTEGER f;
  203814. QueryPerformanceFrequency (&f);
  203815. hiResTicksPerSecond = f.QuadPart;
  203816. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  203817. String s (SystemStats::getJUCEVersion());
  203818. const MMRESULT res = timeBeginPeriod (1);
  203819. (void) res;
  203820. jassert (res == TIMERR_NOERROR);
  203821. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  203822. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  203823. #endif
  203824. }
  203825. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  203826. {
  203827. OSVERSIONINFO info;
  203828. info.dwOSVersionInfoSize = sizeof (info);
  203829. GetVersionEx (&info);
  203830. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  203831. {
  203832. switch (info.dwMajorVersion)
  203833. {
  203834. case 5: return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  203835. case 6: return (info.dwMinorVersion == 0) ? WinVista : Windows7;
  203836. default: jassertfalse; break; // !! not a supported OS!
  203837. }
  203838. }
  203839. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  203840. {
  203841. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  203842. return Win98;
  203843. }
  203844. return UnknownOS;
  203845. }
  203846. const String SystemStats::getOperatingSystemName()
  203847. {
  203848. const char* name = "Unknown OS";
  203849. switch (getOperatingSystemType())
  203850. {
  203851. case Windows7: name = "Windows 7"; break;
  203852. case WinVista: name = "Windows Vista"; break;
  203853. case WinXP: name = "Windows XP"; break;
  203854. case Win2000: name = "Windows 2000"; break;
  203855. case Win98: name = "Windows 98"; break;
  203856. default: jassertfalse; break; // !! new type of OS?
  203857. }
  203858. return name;
  203859. }
  203860. bool SystemStats::isOperatingSystem64Bit()
  203861. {
  203862. #ifdef _WIN64
  203863. return true;
  203864. #else
  203865. typedef BOOL (WINAPI* LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  203866. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  203867. BOOL isWow64 = FALSE;
  203868. return (fnIsWow64Process != 0)
  203869. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  203870. && (isWow64 != FALSE);
  203871. #endif
  203872. }
  203873. int SystemStats::getMemorySizeInMegabytes()
  203874. {
  203875. MEMORYSTATUSEX mem;
  203876. mem.dwLength = sizeof (mem);
  203877. GlobalMemoryStatusEx (&mem);
  203878. return (int) (mem.ullTotalPhys / (1024 * 1024)) + 1;
  203879. }
  203880. uint32 juce_millisecondsSinceStartup() throw()
  203881. {
  203882. return (uint32) timeGetTime();
  203883. }
  203884. int64 Time::getHighResolutionTicks() throw()
  203885. {
  203886. LARGE_INTEGER ticks;
  203887. QueryPerformanceCounter (&ticks);
  203888. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  203889. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  203890. // fix for a very obscure PCI hardware bug that can make the counter
  203891. // sometimes jump forwards by a few seconds..
  203892. static int64 hiResTicksOffset = 0;
  203893. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  203894. if (offsetDrift > (hiResTicksPerSecond >> 1))
  203895. hiResTicksOffset = newOffset;
  203896. return ticks.QuadPart + hiResTicksOffset;
  203897. }
  203898. double Time::getMillisecondCounterHiRes() throw()
  203899. {
  203900. return getHighResolutionTicks() * hiResTicksScaleFactor;
  203901. }
  203902. int64 Time::getHighResolutionTicksPerSecond() throw()
  203903. {
  203904. return hiResTicksPerSecond;
  203905. }
  203906. static int64 juce_getClockCycleCounter() throw()
  203907. {
  203908. #if JUCE_USE_INTRINSICS
  203909. // MS intrinsics version...
  203910. return __rdtsc();
  203911. #elif JUCE_GCC
  203912. // GNU inline asm version...
  203913. unsigned int hi = 0, lo = 0;
  203914. __asm__ __volatile__ (
  203915. "xor %%eax, %%eax \n\
  203916. xor %%edx, %%edx \n\
  203917. rdtsc \n\
  203918. movl %%eax, %[lo] \n\
  203919. movl %%edx, %[hi]"
  203920. :
  203921. : [hi] "m" (hi),
  203922. [lo] "m" (lo)
  203923. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  203924. return (int64) ((((uint64) hi) << 32) | lo);
  203925. #else
  203926. // MSVC inline asm version...
  203927. unsigned int hi = 0, lo = 0;
  203928. __asm
  203929. {
  203930. xor eax, eax
  203931. xor edx, edx
  203932. rdtsc
  203933. mov lo, eax
  203934. mov hi, edx
  203935. }
  203936. return (int64) ((((uint64) hi) << 32) | lo);
  203937. #endif
  203938. }
  203939. int SystemStats::getCpuSpeedInMegaherz()
  203940. {
  203941. const int64 cycles = juce_getClockCycleCounter();
  203942. const uint32 millis = Time::getMillisecondCounter();
  203943. int lastResult = 0;
  203944. for (;;)
  203945. {
  203946. int n = 1000000;
  203947. while (--n > 0) {}
  203948. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  203949. const int64 cyclesNow = juce_getClockCycleCounter();
  203950. if (millisElapsed > 80)
  203951. {
  203952. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  203953. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  203954. return newResult;
  203955. lastResult = newResult;
  203956. }
  203957. }
  203958. }
  203959. bool Time::setSystemTimeToThisTime() const
  203960. {
  203961. SYSTEMTIME st;
  203962. st.wDayOfWeek = 0;
  203963. st.wYear = (WORD) getYear();
  203964. st.wMonth = (WORD) (getMonth() + 1);
  203965. st.wDay = (WORD) getDayOfMonth();
  203966. st.wHour = (WORD) getHours();
  203967. st.wMinute = (WORD) getMinutes();
  203968. st.wSecond = (WORD) getSeconds();
  203969. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  203970. // do this twice because of daylight saving conversion problems - the
  203971. // first one sets it up, the second one kicks it in.
  203972. return SetLocalTime (&st) != 0
  203973. && SetLocalTime (&st) != 0;
  203974. }
  203975. int SystemStats::getPageSize()
  203976. {
  203977. SYSTEM_INFO systemInfo;
  203978. GetSystemInfo (&systemInfo);
  203979. return systemInfo.dwPageSize;
  203980. }
  203981. const String SystemStats::getLogonName()
  203982. {
  203983. TCHAR text [256];
  203984. DWORD len = numElementsInArray (text) - 2;
  203985. zerostruct (text);
  203986. GetUserName (text, &len);
  203987. return String (text, len);
  203988. }
  203989. const String SystemStats::getFullUserName()
  203990. {
  203991. return getLogonName();
  203992. }
  203993. #endif
  203994. /*** End of inlined file: juce_win32_SystemStats.cpp ***/
  203995. /*** Start of inlined file: juce_win32_Threads.cpp ***/
  203996. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  203997. // compiled on its own).
  203998. #if JUCE_INCLUDED_FILE
  203999. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204000. extern HWND juce_messageWindowHandle;
  204001. #endif
  204002. #if ! JUCE_USE_INTRINSICS
  204003. // In newer compilers, the inline versions of these are used (in juce_Atomic.h), but in
  204004. // older ones we have to actually call the ops as win32 functions..
  204005. long juce_InterlockedExchange (volatile long* a, long b) throw() { return InterlockedExchange (a, b); }
  204006. long juce_InterlockedIncrement (volatile long* a) throw() { return InterlockedIncrement (a); }
  204007. long juce_InterlockedDecrement (volatile long* a) throw() { return InterlockedDecrement (a); }
  204008. long juce_InterlockedExchangeAdd (volatile long* a, long b) throw() { return InterlockedExchangeAdd (a, b); }
  204009. long juce_InterlockedCompareExchange (volatile long* a, long b, long c) throw() { return InterlockedCompareExchange (a, b, c); }
  204010. __int64 juce_InterlockedCompareExchange64 (volatile __int64* value, __int64 newValue, __int64 valueToCompare) throw()
  204011. {
  204012. jassertfalse; // This operation isn't available in old MS compiler versions!
  204013. __int64 oldValue = *value;
  204014. if (oldValue == valueToCompare)
  204015. *value = newValue;
  204016. return oldValue;
  204017. }
  204018. #endif
  204019. CriticalSection::CriticalSection() throw()
  204020. {
  204021. // (just to check the MS haven't changed this structure and broken things...)
  204022. #if _MSC_VER >= 1400
  204023. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  204024. #else
  204025. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  204026. #endif
  204027. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  204028. }
  204029. CriticalSection::~CriticalSection() throw()
  204030. {
  204031. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  204032. }
  204033. void CriticalSection::enter() const throw()
  204034. {
  204035. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  204036. }
  204037. bool CriticalSection::tryEnter() const throw()
  204038. {
  204039. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  204040. }
  204041. void CriticalSection::exit() const throw()
  204042. {
  204043. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  204044. }
  204045. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  204046. : internal (CreateEvent (0, manualReset ? TRUE : FALSE, FALSE, 0))
  204047. {
  204048. }
  204049. WaitableEvent::~WaitableEvent() throw()
  204050. {
  204051. CloseHandle (internal);
  204052. }
  204053. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  204054. {
  204055. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204056. }
  204057. void WaitableEvent::signal() const throw()
  204058. {
  204059. SetEvent (internal);
  204060. }
  204061. void WaitableEvent::reset() const throw()
  204062. {
  204063. ResetEvent (internal);
  204064. }
  204065. void JUCE_API juce_threadEntryPoint (void*);
  204066. static unsigned int __stdcall threadEntryProc (void* userData)
  204067. {
  204068. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204069. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204070. GetCurrentThreadId(), TRUE);
  204071. #endif
  204072. juce_threadEntryPoint (userData);
  204073. _endthreadex (0);
  204074. return 0;
  204075. }
  204076. void juce_CloseThreadHandle (void* handle)
  204077. {
  204078. CloseHandle ((HANDLE) handle);
  204079. }
  204080. void* juce_createThread (void* userData)
  204081. {
  204082. unsigned int threadId;
  204083. return (void*) _beginthreadex (0, 0, &threadEntryProc, userData, 0, &threadId);
  204084. }
  204085. void juce_killThread (void* handle)
  204086. {
  204087. if (handle != 0)
  204088. {
  204089. #if JUCE_DEBUG
  204090. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204091. #endif
  204092. TerminateThread (handle, 0);
  204093. }
  204094. }
  204095. void juce_setCurrentThreadName (const String& name)
  204096. {
  204097. #if JUCE_DEBUG && JUCE_MSVC
  204098. struct
  204099. {
  204100. DWORD dwType;
  204101. LPCSTR szName;
  204102. DWORD dwThreadID;
  204103. DWORD dwFlags;
  204104. } info;
  204105. info.dwType = 0x1000;
  204106. info.szName = name.toCString();
  204107. info.dwThreadID = GetCurrentThreadId();
  204108. info.dwFlags = 0;
  204109. __try
  204110. {
  204111. RaiseException (0x406d1388 /*MS_VC_EXCEPTION*/, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204112. }
  204113. __except (EXCEPTION_CONTINUE_EXECUTION)
  204114. {}
  204115. #else
  204116. (void) name;
  204117. #endif
  204118. }
  204119. Thread::ThreadID Thread::getCurrentThreadId()
  204120. {
  204121. return (ThreadID) (pointer_sized_int) GetCurrentThreadId();
  204122. }
  204123. // priority 1 to 10 where 5=normal, 1=low
  204124. bool juce_setThreadPriority (void* threadHandle, int priority)
  204125. {
  204126. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204127. if (priority < 1) pri = THREAD_PRIORITY_IDLE;
  204128. else if (priority < 2) pri = THREAD_PRIORITY_LOWEST;
  204129. else if (priority < 5) pri = THREAD_PRIORITY_BELOW_NORMAL;
  204130. else if (priority < 7) pri = THREAD_PRIORITY_NORMAL;
  204131. else if (priority < 9) pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204132. else if (priority < 10) pri = THREAD_PRIORITY_HIGHEST;
  204133. if (threadHandle == 0)
  204134. threadHandle = GetCurrentThread();
  204135. return SetThreadPriority (threadHandle, pri) != FALSE;
  204136. }
  204137. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  204138. {
  204139. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204140. }
  204141. static HANDLE sleepEvent = 0;
  204142. void juce_initialiseThreadEvents()
  204143. {
  204144. if (sleepEvent == 0)
  204145. #if JUCE_DEBUG
  204146. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  204147. #else
  204148. sleepEvent = CreateEvent (0, 0, 0, 0);
  204149. #endif
  204150. }
  204151. void Thread::yield()
  204152. {
  204153. Sleep (0);
  204154. }
  204155. void JUCE_CALLTYPE Thread::sleep (const int millisecs)
  204156. {
  204157. if (millisecs >= 10)
  204158. {
  204159. Sleep (millisecs);
  204160. }
  204161. else
  204162. {
  204163. jassert (sleepEvent != 0);
  204164. // unlike Sleep() this is guaranteed to return to the current thread after
  204165. // the time expires, so we'll use this for short waits, which are more likely
  204166. // to need to be accurate
  204167. WaitForSingleObject (sleepEvent, millisecs);
  204168. }
  204169. }
  204170. static int lastProcessPriority = -1;
  204171. // called by WindowDriver because Windows does wierd things to process priority
  204172. // when you swap apps, and this forces an update when the app is brought to the front.
  204173. void juce_repeatLastProcessPriority()
  204174. {
  204175. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204176. {
  204177. DWORD p;
  204178. switch (lastProcessPriority)
  204179. {
  204180. case Process::LowPriority: p = IDLE_PRIORITY_CLASS; break;
  204181. case Process::NormalPriority: p = NORMAL_PRIORITY_CLASS; break;
  204182. case Process::HighPriority: p = HIGH_PRIORITY_CLASS; break;
  204183. case Process::RealtimePriority: p = REALTIME_PRIORITY_CLASS; break;
  204184. default: jassertfalse; return; // bad priority value
  204185. }
  204186. SetPriorityClass (GetCurrentProcess(), p);
  204187. }
  204188. }
  204189. void Process::setPriority (ProcessPriority prior)
  204190. {
  204191. if (lastProcessPriority != (int) prior)
  204192. {
  204193. lastProcessPriority = (int) prior;
  204194. juce_repeatLastProcessPriority();
  204195. }
  204196. }
  204197. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  204198. {
  204199. return IsDebuggerPresent() != FALSE;
  204200. }
  204201. bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  204202. {
  204203. return juce_isRunningUnderDebugger();
  204204. }
  204205. void Process::raisePrivilege()
  204206. {
  204207. jassertfalse; // xxx not implemented
  204208. }
  204209. void Process::lowerPrivilege()
  204210. {
  204211. jassertfalse; // xxx not implemented
  204212. }
  204213. void Process::terminate()
  204214. {
  204215. #if JUCE_DEBUG && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204216. _CrtDumpMemoryLeaks();
  204217. #endif
  204218. // bullet in the head in case there's a problem shutting down..
  204219. ExitProcess (0);
  204220. }
  204221. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204222. {
  204223. void* result = 0;
  204224. JUCE_TRY
  204225. {
  204226. result = LoadLibrary (name);
  204227. }
  204228. JUCE_CATCH_ALL
  204229. return result;
  204230. }
  204231. void PlatformUtilities::freeDynamicLibrary (void* h)
  204232. {
  204233. JUCE_TRY
  204234. {
  204235. if (h != 0)
  204236. FreeLibrary ((HMODULE) h);
  204237. }
  204238. JUCE_CATCH_ALL
  204239. }
  204240. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204241. {
  204242. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name.toCString()) : 0; // (void* cast is required for mingw)
  204243. }
  204244. class InterProcessLock::Pimpl
  204245. {
  204246. public:
  204247. Pimpl (const String& name, const int timeOutMillisecs)
  204248. : handle (0), refCount (1)
  204249. {
  204250. handle = CreateMutex (0, TRUE, "Global\\" + name.replaceCharacter ('\\','/'));
  204251. if (handle != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204252. {
  204253. if (timeOutMillisecs == 0)
  204254. {
  204255. close();
  204256. return;
  204257. }
  204258. switch (WaitForSingleObject (handle, timeOutMillisecs < 0 ? INFINITE : timeOutMillisecs))
  204259. {
  204260. case WAIT_OBJECT_0:
  204261. case WAIT_ABANDONED:
  204262. break;
  204263. case WAIT_TIMEOUT:
  204264. default:
  204265. close();
  204266. break;
  204267. }
  204268. }
  204269. }
  204270. ~Pimpl()
  204271. {
  204272. close();
  204273. }
  204274. void close()
  204275. {
  204276. if (handle != 0)
  204277. {
  204278. ReleaseMutex (handle);
  204279. CloseHandle (handle);
  204280. handle = 0;
  204281. }
  204282. }
  204283. HANDLE handle;
  204284. int refCount;
  204285. };
  204286. InterProcessLock::InterProcessLock (const String& name_)
  204287. : name (name_)
  204288. {
  204289. }
  204290. InterProcessLock::~InterProcessLock()
  204291. {
  204292. }
  204293. bool InterProcessLock::enter (const int timeOutMillisecs)
  204294. {
  204295. const ScopedLock sl (lock);
  204296. if (pimpl == 0)
  204297. {
  204298. pimpl = new Pimpl (name, timeOutMillisecs);
  204299. if (pimpl->handle == 0)
  204300. pimpl = 0;
  204301. }
  204302. else
  204303. {
  204304. pimpl->refCount++;
  204305. }
  204306. return pimpl != 0;
  204307. }
  204308. void InterProcessLock::exit()
  204309. {
  204310. const ScopedLock sl (lock);
  204311. // Trying to release the lock too many times!
  204312. jassert (pimpl != 0);
  204313. if (pimpl != 0 && --(pimpl->refCount) == 0)
  204314. pimpl = 0;
  204315. }
  204316. #endif
  204317. /*** End of inlined file: juce_win32_Threads.cpp ***/
  204318. /*** Start of inlined file: juce_win32_Files.cpp ***/
  204319. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204320. // compiled on its own).
  204321. #if JUCE_INCLUDED_FILE
  204322. #ifndef CSIDL_MYMUSIC
  204323. #define CSIDL_MYMUSIC 0x000d
  204324. #endif
  204325. #ifndef CSIDL_MYVIDEO
  204326. #define CSIDL_MYVIDEO 0x000e
  204327. #endif
  204328. #ifndef INVALID_FILE_ATTRIBUTES
  204329. #define INVALID_FILE_ATTRIBUTES ((DWORD) -1)
  204330. #endif
  204331. namespace WindowsFileHelpers
  204332. {
  204333. int64 fileTimeToTime (const FILETIME* const ft)
  204334. {
  204335. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME)); // tell me if this fails!
  204336. return (reinterpret_cast<const ULARGE_INTEGER*> (ft)->QuadPart - literal64bit (116444736000000000)) / 10000;
  204337. }
  204338. void timeToFileTime (const int64 time, FILETIME* const ft)
  204339. {
  204340. reinterpret_cast<ULARGE_INTEGER*> (ft)->QuadPart = time * 10000 + literal64bit (116444736000000000);
  204341. }
  204342. const String getDriveFromPath (const String& path)
  204343. {
  204344. if (path.isNotEmpty() && path[1] == ':')
  204345. return path.substring (0, 2) + '\\';
  204346. return path;
  204347. }
  204348. int64 getDiskSpaceInfo (const String& path, const bool total)
  204349. {
  204350. ULARGE_INTEGER spc, tot, totFree;
  204351. if (GetDiskFreeSpaceEx (getDriveFromPath (path), &spc, &tot, &totFree))
  204352. return total ? (int64) tot.QuadPart
  204353. : (int64) spc.QuadPart;
  204354. return 0;
  204355. }
  204356. unsigned int getWindowsDriveType (const String& path)
  204357. {
  204358. return GetDriveType (getDriveFromPath (path));
  204359. }
  204360. const File getSpecialFolderPath (int type)
  204361. {
  204362. WCHAR path [MAX_PATH + 256];
  204363. if (SHGetSpecialFolderPath (0, path, type, FALSE))
  204364. return File (String (path));
  204365. return File::nonexistent;
  204366. }
  204367. }
  204368. const juce_wchar File::separator = '\\';
  204369. const String File::separatorString ("\\");
  204370. bool File::exists() const
  204371. {
  204372. return fullPath.isNotEmpty()
  204373. && GetFileAttributes (fullPath) != INVALID_FILE_ATTRIBUTES;
  204374. }
  204375. bool File::existsAsFile() const
  204376. {
  204377. return fullPath.isNotEmpty()
  204378. && (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_DIRECTORY) == 0;
  204379. }
  204380. bool File::isDirectory() const
  204381. {
  204382. const DWORD attr = GetFileAttributes (fullPath);
  204383. return ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0) && (attr != INVALID_FILE_ATTRIBUTES);
  204384. }
  204385. bool File::hasWriteAccess() const
  204386. {
  204387. if (exists())
  204388. return (GetFileAttributes (fullPath) & FILE_ATTRIBUTE_READONLY) == 0;
  204389. // on windows, it seems that even read-only directories can still be written into,
  204390. // so checking the parent directory's permissions would return the wrong result..
  204391. return true;
  204392. }
  204393. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  204394. {
  204395. DWORD attr = GetFileAttributes (fullPath);
  204396. if (attr == INVALID_FILE_ATTRIBUTES)
  204397. return false;
  204398. if (shouldBeReadOnly == ((attr & FILE_ATTRIBUTE_READONLY) != 0))
  204399. return true;
  204400. if (shouldBeReadOnly)
  204401. attr |= FILE_ATTRIBUTE_READONLY;
  204402. else
  204403. attr &= ~FILE_ATTRIBUTE_READONLY;
  204404. return SetFileAttributes (fullPath, attr) != FALSE;
  204405. }
  204406. bool File::isHidden() const
  204407. {
  204408. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  204409. }
  204410. bool File::deleteFile() const
  204411. {
  204412. if (! exists())
  204413. return true;
  204414. else if (isDirectory())
  204415. return RemoveDirectory (fullPath) != 0;
  204416. else
  204417. return DeleteFile (fullPath) != 0;
  204418. }
  204419. bool File::moveToTrash() const
  204420. {
  204421. if (! exists())
  204422. return true;
  204423. SHFILEOPSTRUCT fos;
  204424. zerostruct (fos);
  204425. // The string we pass in must be double null terminated..
  204426. String doubleNullTermPath (getFullPathName() + " ");
  204427. TCHAR* const p = const_cast <TCHAR*> (static_cast <const TCHAR*> (doubleNullTermPath));
  204428. p [getFullPathName().length()] = 0;
  204429. fos.wFunc = FO_DELETE;
  204430. fos.pFrom = p;
  204431. fos.fFlags = FOF_ALLOWUNDO | FOF_NOERRORUI | FOF_SILENT | FOF_NOCONFIRMATION
  204432. | FOF_NOCONFIRMMKDIR | FOF_RENAMEONCOLLISION;
  204433. return SHFileOperation (&fos) == 0;
  204434. }
  204435. bool File::copyInternal (const File& dest) const
  204436. {
  204437. return CopyFile (fullPath, dest.getFullPathName(), false) != 0;
  204438. }
  204439. bool File::moveInternal (const File& dest) const
  204440. {
  204441. return MoveFile (fullPath, dest.getFullPathName()) != 0;
  204442. }
  204443. void File::createDirectoryInternal (const String& fileName) const
  204444. {
  204445. CreateDirectory (fileName, 0);
  204446. }
  204447. int64 juce_fileSetPosition (void* handle, int64 pos)
  204448. {
  204449. LARGE_INTEGER li;
  204450. li.QuadPart = pos;
  204451. li.LowPart = SetFilePointer ((HANDLE) handle, li.LowPart, &li.HighPart, FILE_BEGIN); // (returns -1 if it fails)
  204452. return li.QuadPart;
  204453. }
  204454. void FileInputStream::openHandle()
  204455. {
  204456. totalSize = file.getSize();
  204457. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  204458. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  204459. if (h != INVALID_HANDLE_VALUE)
  204460. fileHandle = (void*) h;
  204461. }
  204462. void FileInputStream::closeHandle()
  204463. {
  204464. CloseHandle ((HANDLE) fileHandle);
  204465. }
  204466. size_t FileInputStream::readInternal (void* buffer, size_t numBytes)
  204467. {
  204468. if (fileHandle != 0)
  204469. {
  204470. DWORD actualNum = 0;
  204471. ReadFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204472. return (size_t) actualNum;
  204473. }
  204474. return 0;
  204475. }
  204476. void FileOutputStream::openHandle()
  204477. {
  204478. HANDLE h = CreateFile (file.getFullPathName(), GENERIC_WRITE, FILE_SHARE_READ, 0,
  204479. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204480. if (h != INVALID_HANDLE_VALUE)
  204481. {
  204482. LARGE_INTEGER li;
  204483. li.QuadPart = 0;
  204484. li.LowPart = SetFilePointer (h, 0, &li.HighPart, FILE_END);
  204485. if (li.LowPart != INVALID_SET_FILE_POINTER)
  204486. {
  204487. fileHandle = (void*) h;
  204488. currentPosition = li.QuadPart;
  204489. }
  204490. }
  204491. }
  204492. void FileOutputStream::closeHandle()
  204493. {
  204494. CloseHandle ((HANDLE) fileHandle);
  204495. }
  204496. int FileOutputStream::writeInternal (const void* buffer, int numBytes)
  204497. {
  204498. if (fileHandle != 0)
  204499. {
  204500. DWORD actualNum = 0;
  204501. WriteFile ((HANDLE) fileHandle, buffer, numBytes, &actualNum, 0);
  204502. return (int) actualNum;
  204503. }
  204504. return 0;
  204505. }
  204506. void FileOutputStream::flushInternal()
  204507. {
  204508. if (fileHandle != 0)
  204509. FlushFileBuffers ((HANDLE) fileHandle);
  204510. }
  204511. int64 File::getSize() const
  204512. {
  204513. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204514. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204515. return (((int64) attributes.nFileSizeHigh) << 32) | attributes.nFileSizeLow;
  204516. return 0;
  204517. }
  204518. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  204519. {
  204520. using namespace WindowsFileHelpers;
  204521. WIN32_FILE_ATTRIBUTE_DATA attributes;
  204522. if (GetFileAttributesEx (fullPath, GetFileExInfoStandard, &attributes))
  204523. {
  204524. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  204525. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  204526. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  204527. }
  204528. else
  204529. {
  204530. creationTime = accessTime = modificationTime = 0;
  204531. }
  204532. }
  204533. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 creationTime) const
  204534. {
  204535. using namespace WindowsFileHelpers;
  204536. bool ok = false;
  204537. HANDLE h = CreateFile (fullPath, GENERIC_WRITE, FILE_SHARE_READ, 0,
  204538. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  204539. if (h != INVALID_HANDLE_VALUE)
  204540. {
  204541. FILETIME m, a, c;
  204542. timeToFileTime (modificationTime, &m);
  204543. timeToFileTime (accessTime, &a);
  204544. timeToFileTime (creationTime, &c);
  204545. ok = SetFileTime (h,
  204546. creationTime > 0 ? &c : 0,
  204547. accessTime > 0 ? &a : 0,
  204548. modificationTime > 0 ? &m : 0) != 0;
  204549. CloseHandle (h);
  204550. }
  204551. return ok;
  204552. }
  204553. void File::findFileSystemRoots (Array<File>& destArray)
  204554. {
  204555. TCHAR buffer [2048];
  204556. buffer[0] = 0;
  204557. buffer[1] = 0;
  204558. GetLogicalDriveStrings (2048, buffer);
  204559. const TCHAR* n = buffer;
  204560. StringArray roots;
  204561. while (*n != 0)
  204562. {
  204563. roots.add (String (n));
  204564. while (*n++ != 0)
  204565. {}
  204566. }
  204567. roots.sort (true);
  204568. for (int i = 0; i < roots.size(); ++i)
  204569. destArray.add (roots [i]);
  204570. }
  204571. const String File::getVolumeLabel() const
  204572. {
  204573. TCHAR dest[64];
  204574. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204575. numElementsInArray (dest), 0, 0, 0, 0, 0))
  204576. dest[0] = 0;
  204577. return dest;
  204578. }
  204579. int File::getVolumeSerialNumber() const
  204580. {
  204581. TCHAR dest[64];
  204582. DWORD serialNum;
  204583. if (! GetVolumeInformation (WindowsFileHelpers::getDriveFromPath (getFullPathName()), dest,
  204584. numElementsInArray (dest), &serialNum, 0, 0, 0, 0))
  204585. return 0;
  204586. return (int) serialNum;
  204587. }
  204588. int64 File::getBytesFreeOnVolume() const
  204589. {
  204590. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), false);
  204591. }
  204592. int64 File::getVolumeTotalSize() const
  204593. {
  204594. return WindowsFileHelpers::getDiskSpaceInfo (getFullPathName(), true);
  204595. }
  204596. bool File::isOnCDRomDrive() const
  204597. {
  204598. return WindowsFileHelpers::getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  204599. }
  204600. bool File::isOnHardDisk() const
  204601. {
  204602. if (fullPath.isEmpty())
  204603. return false;
  204604. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204605. if (fullPath.toLowerCase()[0] <= 'b' && fullPath[1] == ':')
  204606. return n != DRIVE_REMOVABLE;
  204607. else
  204608. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  204609. }
  204610. bool File::isOnRemovableDrive() const
  204611. {
  204612. if (fullPath.isEmpty())
  204613. return false;
  204614. const unsigned int n = WindowsFileHelpers::getWindowsDriveType (getFullPathName());
  204615. return n == DRIVE_CDROM
  204616. || n == DRIVE_REMOTE
  204617. || n == DRIVE_REMOVABLE
  204618. || n == DRIVE_RAMDISK;
  204619. }
  204620. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  204621. {
  204622. int csidlType = 0;
  204623. switch (type)
  204624. {
  204625. case userHomeDirectory: csidlType = CSIDL_PROFILE; break;
  204626. case userDocumentsDirectory: csidlType = CSIDL_PERSONAL; break;
  204627. case userDesktopDirectory: csidlType = CSIDL_DESKTOP; break;
  204628. case userApplicationDataDirectory: csidlType = CSIDL_APPDATA; break;
  204629. case commonApplicationDataDirectory: csidlType = CSIDL_COMMON_APPDATA; break;
  204630. case globalApplicationsDirectory: csidlType = CSIDL_PROGRAM_FILES; break;
  204631. case userMusicDirectory: csidlType = CSIDL_MYMUSIC; break;
  204632. case userMoviesDirectory: csidlType = CSIDL_MYVIDEO; break;
  204633. case tempDirectory:
  204634. {
  204635. WCHAR dest [2048];
  204636. dest[0] = 0;
  204637. GetTempPath (numElementsInArray (dest), dest);
  204638. return File (String (dest));
  204639. }
  204640. case invokedExecutableFile:
  204641. case currentExecutableFile:
  204642. case currentApplicationFile:
  204643. {
  204644. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  204645. WCHAR dest [MAX_PATH + 256];
  204646. dest[0] = 0;
  204647. GetModuleFileName (moduleHandle, dest, numElementsInArray (dest));
  204648. return File (String (dest));
  204649. }
  204650. case hostApplicationPath:
  204651. {
  204652. WCHAR dest [MAX_PATH + 256];
  204653. dest[0] = 0;
  204654. GetModuleFileName (0, dest, numElementsInArray (dest));
  204655. return File (String (dest));
  204656. }
  204657. default:
  204658. jassertfalse; // unknown type?
  204659. return File::nonexistent;
  204660. }
  204661. return WindowsFileHelpers::getSpecialFolderPath (csidlType);
  204662. }
  204663. const File File::getCurrentWorkingDirectory()
  204664. {
  204665. WCHAR dest [MAX_PATH + 256];
  204666. dest[0] = 0;
  204667. GetCurrentDirectory (numElementsInArray (dest), dest);
  204668. return File (String (dest));
  204669. }
  204670. bool File::setAsCurrentWorkingDirectory() const
  204671. {
  204672. return SetCurrentDirectory (getFullPathName()) != FALSE;
  204673. }
  204674. const String File::getVersion() const
  204675. {
  204676. String result;
  204677. DWORD handle = 0;
  204678. DWORD bufferSize = GetFileVersionInfoSize (getFullPathName(), &handle);
  204679. HeapBlock<char> buffer;
  204680. buffer.calloc (bufferSize);
  204681. if (GetFileVersionInfo (getFullPathName(), 0, bufferSize, buffer))
  204682. {
  204683. VS_FIXEDFILEINFO* vffi;
  204684. UINT len = 0;
  204685. if (VerQueryValue (buffer, (LPTSTR) _T("\\"), (LPVOID*) &vffi, &len))
  204686. {
  204687. result << (int) HIWORD (vffi->dwFileVersionMS) << '.'
  204688. << (int) LOWORD (vffi->dwFileVersionMS) << '.'
  204689. << (int) HIWORD (vffi->dwFileVersionLS) << '.'
  204690. << (int) LOWORD (vffi->dwFileVersionLS);
  204691. }
  204692. }
  204693. return result;
  204694. }
  204695. const File File::getLinkedTarget() const
  204696. {
  204697. File result (*this);
  204698. String p (getFullPathName());
  204699. if (! exists())
  204700. p += ".lnk";
  204701. else if (getFileExtension() != ".lnk")
  204702. return result;
  204703. ComSmartPtr <IShellLink> shellLink;
  204704. if (SUCCEEDED (shellLink.CoCreateInstance (CLSID_ShellLink)))
  204705. {
  204706. ComSmartPtr <IPersistFile> persistFile;
  204707. if (SUCCEEDED (shellLink.QueryInterface (IID_IPersistFile, persistFile)))
  204708. {
  204709. if (SUCCEEDED (persistFile->Load ((const WCHAR*) p, STGM_READ))
  204710. && SUCCEEDED (shellLink->Resolve (0, SLR_ANY_MATCH | SLR_NO_UI)))
  204711. {
  204712. WIN32_FIND_DATA winFindData;
  204713. WCHAR resolvedPath [MAX_PATH];
  204714. if (SUCCEEDED (shellLink->GetPath (resolvedPath, MAX_PATH, &winFindData, SLGP_UNCPRIORITY)))
  204715. result = File (resolvedPath);
  204716. }
  204717. }
  204718. }
  204719. return result;
  204720. }
  204721. class DirectoryIterator::NativeIterator::Pimpl
  204722. {
  204723. public:
  204724. Pimpl (const File& directory, const String& wildCard)
  204725. : directoryWithWildCard (File::addTrailingSeparator (directory.getFullPathName()) + wildCard),
  204726. handle (INVALID_HANDLE_VALUE)
  204727. {
  204728. }
  204729. ~Pimpl()
  204730. {
  204731. if (handle != INVALID_HANDLE_VALUE)
  204732. FindClose (handle);
  204733. }
  204734. bool next (String& filenameFound,
  204735. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204736. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204737. {
  204738. using namespace WindowsFileHelpers;
  204739. WIN32_FIND_DATA findData;
  204740. if (handle == INVALID_HANDLE_VALUE)
  204741. {
  204742. handle = FindFirstFile (directoryWithWildCard, &findData);
  204743. if (handle == INVALID_HANDLE_VALUE)
  204744. return false;
  204745. }
  204746. else
  204747. {
  204748. if (FindNextFile (handle, &findData) == 0)
  204749. return false;
  204750. }
  204751. filenameFound = findData.cFileName;
  204752. if (isDir != 0) *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204753. if (isHidden != 0) *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  204754. if (fileSize != 0) *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  204755. if (modTime != 0) *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  204756. if (creationTime != 0) *creationTime = fileTimeToTime (&findData.ftCreationTime);
  204757. if (isReadOnly != 0) *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  204758. return true;
  204759. }
  204760. juce_UseDebuggingNewOperator
  204761. private:
  204762. const String directoryWithWildCard;
  204763. HANDLE handle;
  204764. Pimpl (const Pimpl&);
  204765. Pimpl& operator= (const Pimpl&);
  204766. };
  204767. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  204768. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  204769. {
  204770. }
  204771. DirectoryIterator::NativeIterator::~NativeIterator()
  204772. {
  204773. }
  204774. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  204775. bool* const isDir, bool* const isHidden, int64* const fileSize,
  204776. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  204777. {
  204778. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  204779. }
  204780. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  204781. {
  204782. HINSTANCE hInstance = 0;
  204783. JUCE_TRY
  204784. {
  204785. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  204786. }
  204787. JUCE_CATCH_ALL
  204788. return hInstance > (HINSTANCE) 32;
  204789. }
  204790. void File::revealToUser() const
  204791. {
  204792. if (isDirectory())
  204793. startAsProcess();
  204794. else if (getParentDirectory().exists())
  204795. getParentDirectory().startAsProcess();
  204796. }
  204797. class NamedPipeInternal
  204798. {
  204799. public:
  204800. NamedPipeInternal (const String& file, const bool isPipe_)
  204801. : pipeH (0),
  204802. cancelEvent (0),
  204803. connected (false),
  204804. isPipe (isPipe_)
  204805. {
  204806. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  204807. pipeH = isPipe ? CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  204808. PIPE_UNLIMITED_INSTANCES, 4096, 4096, 0, 0)
  204809. : CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0,
  204810. OPEN_EXISTING, FILE_FLAG_OVERLAPPED, 0);
  204811. }
  204812. ~NamedPipeInternal()
  204813. {
  204814. disconnectPipe();
  204815. if (pipeH != 0)
  204816. CloseHandle (pipeH);
  204817. CloseHandle (cancelEvent);
  204818. }
  204819. bool connect (const int timeOutMs)
  204820. {
  204821. if (! isPipe)
  204822. return true;
  204823. if (! connected)
  204824. {
  204825. OVERLAPPED over;
  204826. zerostruct (over);
  204827. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204828. if (ConnectNamedPipe (pipeH, &over))
  204829. {
  204830. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  204831. }
  204832. else
  204833. {
  204834. const int err = GetLastError();
  204835. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  204836. {
  204837. HANDLE handles[] = { over.hEvent, cancelEvent };
  204838. if (WaitForMultipleObjects (2, handles, FALSE,
  204839. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  204840. connected = true;
  204841. }
  204842. else if (err == ERROR_PIPE_CONNECTED)
  204843. {
  204844. connected = true;
  204845. }
  204846. }
  204847. CloseHandle (over.hEvent);
  204848. }
  204849. return connected;
  204850. }
  204851. void disconnectPipe()
  204852. {
  204853. if (connected)
  204854. {
  204855. DisconnectNamedPipe (pipeH);
  204856. connected = false;
  204857. }
  204858. }
  204859. HANDLE pipeH;
  204860. HANDLE cancelEvent;
  204861. bool connected, isPipe;
  204862. };
  204863. void NamedPipe::close()
  204864. {
  204865. cancelPendingReads();
  204866. const ScopedLock sl (lock);
  204867. delete static_cast<NamedPipeInternal*> (internal);
  204868. internal = 0;
  204869. }
  204870. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  204871. {
  204872. close();
  204873. ScopedPointer<NamedPipeInternal> intern (new NamedPipeInternal ("\\\\.\\pipe\\" + pipeName, createPipe));
  204874. if (intern->pipeH != INVALID_HANDLE_VALUE)
  204875. {
  204876. internal = intern.release();
  204877. return true;
  204878. }
  204879. return false;
  204880. }
  204881. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  204882. {
  204883. const ScopedLock sl (lock);
  204884. int bytesRead = -1;
  204885. bool waitAgain = true;
  204886. while (waitAgain && internal != 0)
  204887. {
  204888. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204889. waitAgain = false;
  204890. if (! intern->connect (timeOutMilliseconds))
  204891. break;
  204892. if (maxBytesToRead <= 0)
  204893. return 0;
  204894. OVERLAPPED over;
  204895. zerostruct (over);
  204896. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204897. unsigned long numRead;
  204898. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  204899. {
  204900. bytesRead = (int) numRead;
  204901. }
  204902. else if (GetLastError() == ERROR_IO_PENDING)
  204903. {
  204904. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204905. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204906. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204907. : INFINITE);
  204908. if (waitResult != WAIT_OBJECT_0)
  204909. {
  204910. // if the operation timed out, let's cancel it...
  204911. CancelIo (intern->pipeH);
  204912. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  204913. }
  204914. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  204915. {
  204916. bytesRead = (int) numRead;
  204917. }
  204918. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204919. {
  204920. intern->disconnectPipe();
  204921. waitAgain = true;
  204922. }
  204923. }
  204924. else
  204925. {
  204926. waitAgain = internal != 0;
  204927. Sleep (5);
  204928. }
  204929. CloseHandle (over.hEvent);
  204930. }
  204931. return bytesRead;
  204932. }
  204933. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  204934. {
  204935. int bytesWritten = -1;
  204936. NamedPipeInternal* const intern = static_cast<NamedPipeInternal*> (internal);
  204937. if (intern != 0 && intern->connect (timeOutMilliseconds))
  204938. {
  204939. if (numBytesToWrite <= 0)
  204940. return 0;
  204941. OVERLAPPED over;
  204942. zerostruct (over);
  204943. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  204944. unsigned long numWritten;
  204945. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  204946. {
  204947. bytesWritten = (int) numWritten;
  204948. }
  204949. else if (GetLastError() == ERROR_IO_PENDING)
  204950. {
  204951. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  204952. DWORD waitResult;
  204953. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  204954. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  204955. : INFINITE);
  204956. if (waitResult != WAIT_OBJECT_0)
  204957. {
  204958. CancelIo (intern->pipeH);
  204959. WaitForSingleObject (over.hEvent, INFINITE);
  204960. }
  204961. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  204962. {
  204963. bytesWritten = (int) numWritten;
  204964. }
  204965. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->isPipe)
  204966. {
  204967. intern->disconnectPipe();
  204968. }
  204969. }
  204970. CloseHandle (over.hEvent);
  204971. }
  204972. return bytesWritten;
  204973. }
  204974. void NamedPipe::cancelPendingReads()
  204975. {
  204976. if (internal != 0)
  204977. SetEvent (static_cast<NamedPipeInternal*> (internal)->cancelEvent);
  204978. }
  204979. #endif
  204980. /*** End of inlined file: juce_win32_Files.cpp ***/
  204981. /*** Start of inlined file: juce_win32_Network.cpp ***/
  204982. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204983. // compiled on its own).
  204984. #if JUCE_INCLUDED_FILE
  204985. #ifndef INTERNET_FLAG_NEED_FILE
  204986. #define INTERNET_FLAG_NEED_FILE 0x00000010
  204987. #endif
  204988. #ifndef INTERNET_OPTION_DISABLE_AUTODIAL
  204989. #define INTERNET_OPTION_DISABLE_AUTODIAL 70
  204990. #endif
  204991. struct ConnectionAndRequestStruct
  204992. {
  204993. HINTERNET connection, request;
  204994. };
  204995. static HINTERNET sessionHandle = 0;
  204996. #ifndef WORKAROUND_TIMEOUT_BUG
  204997. //#define WORKAROUND_TIMEOUT_BUG 1
  204998. #endif
  204999. #if WORKAROUND_TIMEOUT_BUG
  205000. // Required because of a Microsoft bug in setting a timeout
  205001. class InternetConnectThread : public Thread
  205002. {
  205003. public:
  205004. InternetConnectThread (URL_COMPONENTS& uc_, HINTERNET& connection_, const bool isFtp_)
  205005. : Thread ("Internet"), uc (uc_), connection (connection_), isFtp (isFtp_)
  205006. {
  205007. startThread();
  205008. }
  205009. ~InternetConnectThread()
  205010. {
  205011. stopThread (60000);
  205012. }
  205013. void run()
  205014. {
  205015. connection = InternetConnect (sessionHandle, uc.lpszHostName,
  205016. uc.nPort, _T(""), _T(""),
  205017. isFtp ? INTERNET_SERVICE_FTP
  205018. : INTERNET_SERVICE_HTTP,
  205019. 0, 0);
  205020. notify();
  205021. }
  205022. juce_UseDebuggingNewOperator
  205023. private:
  205024. URL_COMPONENTS& uc;
  205025. HINTERNET& connection;
  205026. const bool isFtp;
  205027. InternetConnectThread (const InternetConnectThread&);
  205028. InternetConnectThread& operator= (const InternetConnectThread&);
  205029. };
  205030. #endif
  205031. void* juce_openInternetFile (const String& url,
  205032. const String& headers,
  205033. const MemoryBlock& postData,
  205034. const bool isPost,
  205035. URL::OpenStreamProgressCallback* callback,
  205036. void* callbackContext,
  205037. int timeOutMs)
  205038. {
  205039. if (sessionHandle == 0)
  205040. sessionHandle = InternetOpen (_T("juce"),
  205041. INTERNET_OPEN_TYPE_PRECONFIG,
  205042. 0, 0, 0);
  205043. if (sessionHandle != 0)
  205044. {
  205045. // break up the url..
  205046. TCHAR file[1024], server[1024];
  205047. URL_COMPONENTS uc;
  205048. zerostruct (uc);
  205049. uc.dwStructSize = sizeof (uc);
  205050. uc.dwUrlPathLength = sizeof (file);
  205051. uc.dwHostNameLength = sizeof (server);
  205052. uc.lpszUrlPath = file;
  205053. uc.lpszHostName = server;
  205054. if (InternetCrackUrl (url, 0, 0, &uc))
  205055. {
  205056. int disable = 1;
  205057. InternetSetOption (sessionHandle, INTERNET_OPTION_DISABLE_AUTODIAL, &disable, sizeof (disable));
  205058. if (timeOutMs == 0)
  205059. timeOutMs = 30000;
  205060. else if (timeOutMs < 0)
  205061. timeOutMs = -1;
  205062. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205063. const bool isFtp = url.startsWithIgnoreCase ("ftp:");
  205064. #if WORKAROUND_TIMEOUT_BUG
  205065. HINTERNET connection = 0;
  205066. {
  205067. InternetConnectThread connectThread (uc, connection, isFtp);
  205068. connectThread.wait (timeOutMs);
  205069. if (connection == 0)
  205070. {
  205071. InternetCloseHandle (sessionHandle);
  205072. sessionHandle = 0;
  205073. }
  205074. }
  205075. #else
  205076. HINTERNET connection = InternetConnect (sessionHandle,
  205077. uc.lpszHostName,
  205078. uc.nPort,
  205079. _T(""), _T(""),
  205080. isFtp ? INTERNET_SERVICE_FTP
  205081. : INTERNET_SERVICE_HTTP,
  205082. 0, 0);
  205083. #endif
  205084. if (connection != 0)
  205085. {
  205086. if (isFtp)
  205087. {
  205088. HINTERNET request = FtpOpenFile (connection,
  205089. uc.lpszUrlPath,
  205090. GENERIC_READ,
  205091. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  205092. 0);
  205093. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  205094. result->connection = connection;
  205095. result->request = request;
  205096. return result;
  205097. }
  205098. else
  205099. {
  205100. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205101. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_NO_COOKIES;
  205102. if (url.startsWithIgnoreCase ("https:"))
  205103. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205104. // IE7 seems to automatically work out when it's https)
  205105. HINTERNET request = HttpOpenRequest (connection,
  205106. isPost ? _T("POST")
  205107. : _T("GET"),
  205108. uc.lpszUrlPath,
  205109. 0, 0, mimeTypes, flags, 0);
  205110. if (request != 0)
  205111. {
  205112. INTERNET_BUFFERS buffers;
  205113. zerostruct (buffers);
  205114. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205115. buffers.lpcszHeader = (LPCTSTR) headers;
  205116. buffers.dwHeadersLength = headers.length();
  205117. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205118. ConnectionAndRequestStruct* result = 0;
  205119. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205120. {
  205121. int bytesSent = 0;
  205122. for (;;)
  205123. {
  205124. const int bytesToDo = jmin (1024, (int) postData.getSize() - bytesSent);
  205125. DWORD bytesDone = 0;
  205126. if (bytesToDo > 0
  205127. && ! InternetWriteFile (request,
  205128. static_cast <const char*> (postData.getData()) + bytesSent,
  205129. bytesToDo, &bytesDone))
  205130. {
  205131. break;
  205132. }
  205133. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205134. {
  205135. result = new ConnectionAndRequestStruct();
  205136. result->connection = connection;
  205137. result->request = request;
  205138. if (! HttpEndRequest (request, 0, 0, 0))
  205139. break;
  205140. return result;
  205141. }
  205142. bytesSent += bytesDone;
  205143. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  205144. break;
  205145. }
  205146. }
  205147. InternetCloseHandle (request);
  205148. }
  205149. InternetCloseHandle (connection);
  205150. }
  205151. }
  205152. }
  205153. }
  205154. return 0;
  205155. }
  205156. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  205157. {
  205158. DWORD bytesRead = 0;
  205159. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205160. if (crs != 0)
  205161. InternetReadFile (crs->request,
  205162. buffer, bytesToRead,
  205163. &bytesRead);
  205164. return bytesRead;
  205165. }
  205166. int juce_seekInInternetFile (void* handle, int newPosition)
  205167. {
  205168. if (handle != 0)
  205169. {
  205170. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205171. return InternetSetFilePointer (crs->request, newPosition, 0, FILE_BEGIN, 0);
  205172. }
  205173. return -1;
  205174. }
  205175. int64 juce_getInternetFileContentLength (void* handle)
  205176. {
  205177. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205178. if (crs != 0)
  205179. {
  205180. DWORD index = 0, result = 0, size = sizeof (result);
  205181. if (HttpQueryInfo (crs->request, HTTP_QUERY_CONTENT_LENGTH | HTTP_QUERY_FLAG_NUMBER, &result, &size, &index))
  205182. return (int64) result;
  205183. }
  205184. return -1;
  205185. }
  205186. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  205187. {
  205188. const ConnectionAndRequestStruct* const crs = static_cast <ConnectionAndRequestStruct*> (handle);
  205189. if (crs != 0)
  205190. {
  205191. DWORD bufferSizeBytes = 4096;
  205192. for (;;)
  205193. {
  205194. HeapBlock<char> buffer ((size_t) bufferSizeBytes);
  205195. if (HttpQueryInfo (crs->request, HTTP_QUERY_RAW_HEADERS_CRLF, buffer.getData(), &bufferSizeBytes, 0))
  205196. {
  205197. StringArray headersArray;
  205198. headersArray.addLines (reinterpret_cast <const WCHAR*> (buffer.getData()));
  205199. for (int i = 0; i < headersArray.size(); ++i)
  205200. {
  205201. const String& header = headersArray[i];
  205202. const String key (header.upToFirstOccurrenceOf (": ", false, false));
  205203. const String value (header.fromFirstOccurrenceOf (": ", false, false));
  205204. const String previousValue (headers [key]);
  205205. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  205206. }
  205207. break;
  205208. }
  205209. if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
  205210. break;
  205211. }
  205212. }
  205213. }
  205214. void juce_closeInternetFile (void* handle)
  205215. {
  205216. if (handle != 0)
  205217. {
  205218. ScopedPointer <ConnectionAndRequestStruct> crs (static_cast <ConnectionAndRequestStruct*> (handle));
  205219. InternetCloseHandle (crs->request);
  205220. InternetCloseHandle (crs->connection);
  205221. }
  205222. }
  205223. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  205224. {
  205225. int numFound = 0;
  205226. DynamicLibraryLoader dll ("iphlpapi.dll");
  205227. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205228. if (getAdaptersInfo != 0)
  205229. {
  205230. ULONG len = sizeof (IP_ADAPTER_INFO);
  205231. MemoryBlock mb;
  205232. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205233. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205234. {
  205235. mb.setSize (len);
  205236. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205237. }
  205238. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205239. {
  205240. PIP_ADAPTER_INFO adapter = adapterInfo;
  205241. while (adapter != 0)
  205242. {
  205243. int64 mac = 0;
  205244. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205245. mac = (mac << 8) | adapter->Address[i];
  205246. if (littleEndian)
  205247. mac = (int64) ByteOrder::swap ((uint64) mac);
  205248. if (numFound < maxNum && mac != 0)
  205249. addresses [numFound++] = mac;
  205250. adapter = adapter->Next;
  205251. }
  205252. }
  205253. }
  205254. return numFound;
  205255. }
  205256. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205257. {
  205258. int numFound = 0;
  205259. DynamicLibraryLoader dll ("netapi32.dll");
  205260. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205261. if (NetbiosCall != 0)
  205262. {
  205263. NCB ncb;
  205264. zerostruct (ncb);
  205265. struct ASTAT
  205266. {
  205267. ADAPTER_STATUS adapt;
  205268. NAME_BUFFER NameBuff [30];
  205269. };
  205270. ASTAT astat;
  205271. zeromem (&astat, sizeof (astat)); // (can't use zerostruct here in VC6)
  205272. LANA_ENUM enums;
  205273. zerostruct (enums);
  205274. ncb.ncb_command = NCBENUM;
  205275. ncb.ncb_buffer = (unsigned char*) &enums;
  205276. ncb.ncb_length = sizeof (LANA_ENUM);
  205277. NetbiosCall (&ncb);
  205278. for (int i = 0; i < enums.length; ++i)
  205279. {
  205280. zerostruct (ncb);
  205281. ncb.ncb_command = NCBRESET;
  205282. ncb.ncb_lana_num = enums.lana[i];
  205283. if (NetbiosCall (&ncb) == 0)
  205284. {
  205285. zerostruct (ncb);
  205286. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205287. ncb.ncb_command = NCBASTAT;
  205288. ncb.ncb_lana_num = enums.lana[i];
  205289. ncb.ncb_buffer = (unsigned char*) &astat;
  205290. ncb.ncb_length = sizeof (ASTAT);
  205291. if (NetbiosCall (&ncb) == 0)
  205292. {
  205293. if (astat.adapt.adapter_type == 0xfe)
  205294. {
  205295. uint64 mac = 0;
  205296. for (int i = 6; --i >= 0;)
  205297. mac = (mac << 8) | astat.adapt.adapter_address [littleEndian ? i : (5 - i)];
  205298. if (numFound < maxNum && mac != 0)
  205299. addresses [numFound++] = mac;
  205300. }
  205301. }
  205302. }
  205303. }
  205304. }
  205305. return numFound;
  205306. }
  205307. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  205308. {
  205309. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205310. if (numFound == 0)
  205311. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205312. return numFound;
  205313. }
  205314. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205315. const String& emailSubject,
  205316. const String& bodyText,
  205317. const StringArray& filesToAttach)
  205318. {
  205319. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205320. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205321. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205322. bool ok = false;
  205323. if (mapiSendMail != 0)
  205324. {
  205325. MapiMessage message;
  205326. zerostruct (message);
  205327. message.lpszSubject = (LPSTR) emailSubject.toCString();
  205328. message.lpszNoteText = (LPSTR) bodyText.toCString();
  205329. MapiRecipDesc recip;
  205330. zerostruct (recip);
  205331. recip.ulRecipClass = MAPI_TO;
  205332. String targetEmailAddress_ (targetEmailAddress);
  205333. if (targetEmailAddress_.isEmpty())
  205334. targetEmailAddress_ = " "; // (Windows Mail can't deal with a blank address)
  205335. recip.lpszName = (LPSTR) targetEmailAddress_.toCString();
  205336. message.nRecipCount = 1;
  205337. message.lpRecips = &recip;
  205338. HeapBlock <MapiFileDesc> files;
  205339. files.calloc (filesToAttach.size());
  205340. message.nFileCount = filesToAttach.size();
  205341. message.lpFiles = files;
  205342. for (int i = 0; i < filesToAttach.size(); ++i)
  205343. {
  205344. files[i].nPosition = (ULONG) -1;
  205345. files[i].lpszPathName = (LPSTR) filesToAttach[i].toCString();
  205346. }
  205347. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205348. }
  205349. FreeLibrary (h);
  205350. return ok;
  205351. }
  205352. #endif
  205353. /*** End of inlined file: juce_win32_Network.cpp ***/
  205354. /*** Start of inlined file: juce_win32_PlatformUtils.cpp ***/
  205355. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205356. // compiled on its own).
  205357. #if JUCE_INCLUDED_FILE
  205358. namespace
  205359. {
  205360. HKEY findKeyForPath (String name, const bool createForWriting, String& valueName)
  205361. {
  205362. HKEY rootKey = 0;
  205363. if (name.startsWithIgnoreCase ("HKEY_CURRENT_USER\\"))
  205364. rootKey = HKEY_CURRENT_USER;
  205365. else if (name.startsWithIgnoreCase ("HKEY_LOCAL_MACHINE\\"))
  205366. rootKey = HKEY_LOCAL_MACHINE;
  205367. else if (name.startsWithIgnoreCase ("HKEY_CLASSES_ROOT\\"))
  205368. rootKey = HKEY_CLASSES_ROOT;
  205369. if (rootKey != 0)
  205370. {
  205371. name = name.substring (name.indexOfChar ('\\') + 1);
  205372. const int lastSlash = name.lastIndexOfChar ('\\');
  205373. valueName = name.substring (lastSlash + 1);
  205374. name = name.substring (0, lastSlash);
  205375. HKEY key;
  205376. DWORD result;
  205377. if (createForWriting)
  205378. {
  205379. if (RegCreateKeyEx (rootKey, name, 0, 0, REG_OPTION_NON_VOLATILE,
  205380. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205381. return key;
  205382. }
  205383. else
  205384. {
  205385. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205386. return key;
  205387. }
  205388. }
  205389. return 0;
  205390. }
  205391. }
  205392. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205393. const String& defaultValue)
  205394. {
  205395. String valueName, result (defaultValue);
  205396. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205397. if (k != 0)
  205398. {
  205399. WCHAR buffer [2048];
  205400. unsigned long bufferSize = sizeof (buffer);
  205401. DWORD type = REG_SZ;
  205402. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205403. {
  205404. if (type == REG_SZ)
  205405. result = buffer;
  205406. else if (type == REG_DWORD)
  205407. result = String ((int) *(DWORD*) buffer);
  205408. }
  205409. RegCloseKey (k);
  205410. }
  205411. return result;
  205412. }
  205413. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205414. const String& value)
  205415. {
  205416. String valueName;
  205417. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205418. if (k != 0)
  205419. {
  205420. RegSetValueEx (k, valueName, 0, REG_SZ,
  205421. (const BYTE*) (const WCHAR*) value,
  205422. sizeof (WCHAR) * (value.length() + 1));
  205423. RegCloseKey (k);
  205424. }
  205425. }
  205426. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205427. {
  205428. bool exists = false;
  205429. String valueName;
  205430. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205431. if (k != 0)
  205432. {
  205433. unsigned char buffer [2048];
  205434. unsigned long bufferSize = sizeof (buffer);
  205435. DWORD type = 0;
  205436. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205437. exists = true;
  205438. RegCloseKey (k);
  205439. }
  205440. return exists;
  205441. }
  205442. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205443. {
  205444. String valueName;
  205445. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205446. if (k != 0)
  205447. {
  205448. RegDeleteValue (k, valueName);
  205449. RegCloseKey (k);
  205450. }
  205451. }
  205452. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205453. {
  205454. String valueName;
  205455. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205456. if (k != 0)
  205457. {
  205458. RegDeleteKey (k, valueName);
  205459. RegCloseKey (k);
  205460. }
  205461. }
  205462. void PlatformUtilities::registerFileAssociation (const String& fileExtension,
  205463. const String& symbolicDescription,
  205464. const String& fullDescription,
  205465. const File& targetExecutable,
  205466. int iconResourceNumber)
  205467. {
  205468. setRegistryValue ("HKEY_CLASSES_ROOT\\" + fileExtension + "\\", symbolicDescription);
  205469. const String key ("HKEY_CLASSES_ROOT\\" + symbolicDescription);
  205470. if (iconResourceNumber != 0)
  205471. setRegistryValue (key + "\\DefaultIcon\\",
  205472. targetExecutable.getFullPathName() + "," + String (-iconResourceNumber));
  205473. setRegistryValue (key + "\\", fullDescription);
  205474. setRegistryValue (key + "\\shell\\open\\command\\",
  205475. targetExecutable.getFullPathName() + " %1");
  205476. }
  205477. bool juce_IsRunningInWine()
  205478. {
  205479. HKEY key;
  205480. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205481. {
  205482. RegCloseKey (key);
  205483. return true;
  205484. }
  205485. return false;
  205486. }
  205487. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams()
  205488. {
  205489. String s (::GetCommandLineW());
  205490. StringArray tokens;
  205491. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  205492. return tokens.joinIntoString (" ", 1);
  205493. }
  205494. static void* currentModuleHandle = 0;
  205495. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  205496. {
  205497. if (currentModuleHandle == 0)
  205498. currentModuleHandle = GetModuleHandle (0);
  205499. return currentModuleHandle;
  205500. }
  205501. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  205502. {
  205503. currentModuleHandle = newHandle;
  205504. }
  205505. void PlatformUtilities::fpuReset()
  205506. {
  205507. #if JUCE_MSVC
  205508. _clearfp();
  205509. #endif
  205510. }
  205511. void PlatformUtilities::beep()
  205512. {
  205513. MessageBeep (MB_OK);
  205514. }
  205515. #endif
  205516. /*** End of inlined file: juce_win32_PlatformUtils.cpp ***/
  205517. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  205518. /*** Start of inlined file: juce_win32_Messaging.cpp ***/
  205519. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205520. // compiled on its own).
  205521. #if JUCE_INCLUDED_FILE
  205522. static const unsigned int specialId = WM_APP + 0x4400;
  205523. static const unsigned int broadcastId = WM_APP + 0x4403;
  205524. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  205525. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  205526. HWND juce_messageWindowHandle = 0;
  205527. extern long improbableWindowNumber; // defined in windowing.cpp
  205528. #ifndef WM_APPCOMMAND
  205529. #define WM_APPCOMMAND 0x0319
  205530. #endif
  205531. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  205532. const UINT message,
  205533. const WPARAM wParam,
  205534. const LPARAM lParam) throw()
  205535. {
  205536. JUCE_TRY
  205537. {
  205538. if (h == juce_messageWindowHandle)
  205539. {
  205540. if (message == specialCallbackId)
  205541. {
  205542. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  205543. return (LRESULT) (*func) ((void*) lParam);
  205544. }
  205545. else if (message == specialId)
  205546. {
  205547. // these are trapped early in the dispatch call, but must also be checked
  205548. // here in case there are windows modal dialog boxes doing their own
  205549. // dispatch loop and not calling our version
  205550. MessageManager::getInstance()->deliverMessage ((Message*) lParam);
  205551. return 0;
  205552. }
  205553. else if (message == broadcastId)
  205554. {
  205555. const ScopedPointer <String> messageString ((String*) lParam);
  205556. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  205557. return 0;
  205558. }
  205559. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  205560. {
  205561. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  205562. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  205563. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  205564. return 0;
  205565. }
  205566. }
  205567. }
  205568. JUCE_CATCH_EXCEPTION
  205569. return DefWindowProc (h, message, wParam, lParam);
  205570. }
  205571. static bool isEventBlockedByModalComps (MSG& m)
  205572. {
  205573. if (Component::getNumCurrentlyModalComponents() == 0
  205574. || GetWindowLong (m.hwnd, GWLP_USERDATA) == improbableWindowNumber)
  205575. return false;
  205576. switch (m.message)
  205577. {
  205578. case WM_MOUSEMOVE:
  205579. case WM_NCMOUSEMOVE:
  205580. case 0x020A: /* WM_MOUSEWHEEL */
  205581. case 0x020E: /* WM_MOUSEHWHEEL */
  205582. case WM_KEYUP:
  205583. case WM_SYSKEYUP:
  205584. case WM_CHAR:
  205585. case WM_APPCOMMAND:
  205586. case WM_LBUTTONUP:
  205587. case WM_MBUTTONUP:
  205588. case WM_RBUTTONUP:
  205589. case WM_MOUSEACTIVATE:
  205590. case WM_NCMOUSEHOVER:
  205591. case WM_MOUSEHOVER:
  205592. return true;
  205593. case WM_NCLBUTTONDOWN:
  205594. case WM_NCLBUTTONDBLCLK:
  205595. case WM_NCRBUTTONDOWN:
  205596. case WM_NCRBUTTONDBLCLK:
  205597. case WM_NCMBUTTONDOWN:
  205598. case WM_NCMBUTTONDBLCLK:
  205599. case WM_LBUTTONDOWN:
  205600. case WM_LBUTTONDBLCLK:
  205601. case WM_MBUTTONDOWN:
  205602. case WM_MBUTTONDBLCLK:
  205603. case WM_RBUTTONDOWN:
  205604. case WM_RBUTTONDBLCLK:
  205605. case WM_KEYDOWN:
  205606. case WM_SYSKEYDOWN:
  205607. {
  205608. Component* const modal = Component::getCurrentlyModalComponent (0);
  205609. if (modal != 0)
  205610. modal->inputAttemptWhenModal();
  205611. return true;
  205612. }
  205613. default:
  205614. break;
  205615. }
  205616. return false;
  205617. }
  205618. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  205619. {
  205620. MSG m;
  205621. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  205622. return false;
  205623. if (GetMessage (&m, (HWND) 0, 0, 0) >= 0)
  205624. {
  205625. if (m.message == specialId && m.hwnd == juce_messageWindowHandle)
  205626. {
  205627. MessageManager::getInstance()->deliverMessage ((Message*) (void*) m.lParam);
  205628. }
  205629. else if (m.message == WM_QUIT)
  205630. {
  205631. if (JUCEApplication::getInstance() != 0)
  205632. JUCEApplication::getInstance()->systemRequestedQuit();
  205633. }
  205634. else if (! isEventBlockedByModalComps (m))
  205635. {
  205636. if ((m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN)
  205637. && GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber)
  205638. {
  205639. // if it's someone else's window being clicked on, and the focus is
  205640. // currently on a juce window, pass the kb focus over..
  205641. HWND currentFocus = GetFocus();
  205642. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  205643. SetFocus (m.hwnd);
  205644. }
  205645. TranslateMessage (&m);
  205646. DispatchMessage (&m);
  205647. }
  205648. }
  205649. return true;
  205650. }
  205651. bool juce_postMessageToSystemQueue (Message* message)
  205652. {
  205653. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  205654. }
  205655. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  205656. void* userData)
  205657. {
  205658. if (MessageManager::getInstance()->isThisTheMessageThread())
  205659. {
  205660. return (*callback) (userData);
  205661. }
  205662. else
  205663. {
  205664. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  205665. // deadlock because the message manager is blocked from running, and can't
  205666. // call your function..
  205667. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  205668. return (void*) SendMessage (juce_messageWindowHandle,
  205669. specialCallbackId,
  205670. (WPARAM) callback,
  205671. (LPARAM) userData);
  205672. }
  205673. }
  205674. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  205675. {
  205676. if (hwnd != juce_messageWindowHandle)
  205677. reinterpret_cast <Array<void*>*> (lParam)->add ((void*) hwnd);
  205678. return TRUE;
  205679. }
  205680. void MessageManager::broadcastMessage (const String& value)
  205681. {
  205682. Array<void*> windows;
  205683. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  205684. const String localCopy (value);
  205685. COPYDATASTRUCT data;
  205686. data.dwData = broadcastId;
  205687. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  205688. data.lpData = (void*) static_cast <const juce_wchar*> (localCopy);
  205689. for (int i = windows.size(); --i >= 0;)
  205690. {
  205691. HWND hwnd = (HWND) windows.getUnchecked(i);
  205692. TCHAR windowName [64]; // no need to read longer strings than this
  205693. GetWindowText (hwnd, windowName, 64);
  205694. windowName [63] = 0;
  205695. if (String (windowName) == messageWindowName)
  205696. {
  205697. DWORD_PTR result;
  205698. SendMessageTimeout (hwnd, WM_COPYDATA,
  205699. (WPARAM) juce_messageWindowHandle,
  205700. (LPARAM) &data,
  205701. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  205702. 8000,
  205703. &result);
  205704. }
  205705. }
  205706. }
  205707. static const String getMessageWindowClassName()
  205708. {
  205709. // this name has to be different for each app/dll instance because otherwise
  205710. // poor old Win32 can get a bit confused (even despite it not being a process-global
  205711. // window class).
  205712. static int number = 0;
  205713. if (number == 0)
  205714. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  205715. return "JUCEcs_" + String (number);
  205716. }
  205717. void MessageManager::doPlatformSpecificInitialisation()
  205718. {
  205719. OleInitialize (0);
  205720. const String className (getMessageWindowClassName());
  205721. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205722. WNDCLASSEX wc;
  205723. zerostruct (wc);
  205724. wc.cbSize = sizeof (wc);
  205725. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  205726. wc.cbWndExtra = 4;
  205727. wc.hInstance = hmod;
  205728. wc.lpszClassName = className;
  205729. RegisterClassEx (&wc);
  205730. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  205731. messageWindowName,
  205732. 0, 0, 0, 0, 0, 0, 0,
  205733. hmod, 0);
  205734. }
  205735. void MessageManager::doPlatformSpecificShutdown()
  205736. {
  205737. DestroyWindow (juce_messageWindowHandle);
  205738. UnregisterClass (getMessageWindowClassName(), 0);
  205739. OleUninitialize();
  205740. }
  205741. #endif
  205742. /*** End of inlined file: juce_win32_Messaging.cpp ***/
  205743. /*** Start of inlined file: juce_win32_Fonts.cpp ***/
  205744. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205745. // compiled on its own).
  205746. #if JUCE_INCLUDED_FILE
  205747. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  205748. NEWTEXTMETRICEXW*,
  205749. int type,
  205750. LPARAM lParam)
  205751. {
  205752. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205753. {
  205754. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205755. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
  205756. }
  205757. return 1;
  205758. }
  205759. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  205760. NEWTEXTMETRICEXW*,
  205761. int type,
  205762. LPARAM lParam)
  205763. {
  205764. if (lpelfe != 0 && (type & RASTER_FONTTYPE) == 0)
  205765. {
  205766. LOGFONTW lf;
  205767. zerostruct (lf);
  205768. lf.lfWeight = FW_DONTCARE;
  205769. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205770. lf.lfQuality = DEFAULT_QUALITY;
  205771. lf.lfCharSet = DEFAULT_CHARSET;
  205772. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205773. lf.lfPitchAndFamily = FF_DONTCARE;
  205774. const String fontName (lpelfe->elfLogFont.lfFaceName);
  205775. fontName.copyToUnicode (lf.lfFaceName, LF_FACESIZE - 1);
  205776. HDC dc = CreateCompatibleDC (0);
  205777. EnumFontFamiliesEx (dc, &lf,
  205778. (FONTENUMPROCW) &wfontEnum2,
  205779. lParam, 0);
  205780. DeleteDC (dc);
  205781. }
  205782. return 1;
  205783. }
  205784. const StringArray Font::findAllTypefaceNames()
  205785. {
  205786. StringArray results;
  205787. HDC dc = CreateCompatibleDC (0);
  205788. {
  205789. LOGFONTW lf;
  205790. zerostruct (lf);
  205791. lf.lfWeight = FW_DONTCARE;
  205792. lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205793. lf.lfQuality = DEFAULT_QUALITY;
  205794. lf.lfCharSet = DEFAULT_CHARSET;
  205795. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205796. lf.lfPitchAndFamily = FF_DONTCARE;
  205797. lf.lfFaceName[0] = 0;
  205798. EnumFontFamiliesEx (dc, &lf,
  205799. (FONTENUMPROCW) &wfontEnum1,
  205800. (LPARAM) &results, 0);
  205801. }
  205802. DeleteDC (dc);
  205803. results.sort (true);
  205804. return results;
  205805. }
  205806. extern bool juce_IsRunningInWine();
  205807. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  205808. {
  205809. if (juce_IsRunningInWine())
  205810. {
  205811. // If we're running in Wine, then use fonts that might be available on Linux..
  205812. defaultSans = "Bitstream Vera Sans";
  205813. defaultSerif = "Bitstream Vera Serif";
  205814. defaultFixed = "Bitstream Vera Sans Mono";
  205815. }
  205816. else
  205817. {
  205818. defaultSans = "Verdana";
  205819. defaultSerif = "Times";
  205820. defaultFixed = "Lucida Console";
  205821. }
  205822. }
  205823. class FontDCHolder : private DeletedAtShutdown
  205824. {
  205825. public:
  205826. FontDCHolder()
  205827. : dc (0), numKPs (0), size (0),
  205828. bold (false), italic (false)
  205829. {
  205830. }
  205831. ~FontDCHolder()
  205832. {
  205833. if (dc != 0)
  205834. {
  205835. DeleteDC (dc);
  205836. DeleteObject (fontH);
  205837. }
  205838. clearSingletonInstance();
  205839. }
  205840. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  205841. HDC loadFont (const String& fontName_, const bool bold_, const bool italic_, const int size_)
  205842. {
  205843. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  205844. {
  205845. fontName = fontName_;
  205846. bold = bold_;
  205847. italic = italic_;
  205848. size = size_;
  205849. if (dc != 0)
  205850. {
  205851. DeleteDC (dc);
  205852. DeleteObject (fontH);
  205853. kps.free();
  205854. }
  205855. fontH = 0;
  205856. dc = CreateCompatibleDC (0);
  205857. SetMapperFlags (dc, 0);
  205858. SetMapMode (dc, MM_TEXT);
  205859. LOGFONTW lfw;
  205860. zerostruct (lfw);
  205861. lfw.lfCharSet = DEFAULT_CHARSET;
  205862. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  205863. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  205864. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  205865. lfw.lfQuality = PROOF_QUALITY;
  205866. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  205867. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  205868. fontName.copyToUnicode (lfw.lfFaceName, LF_FACESIZE - 1);
  205869. lfw.lfHeight = size > 0 ? size : -256;
  205870. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  205871. if (standardSizedFont != 0)
  205872. {
  205873. if (SelectObject (dc, standardSizedFont) != 0)
  205874. {
  205875. fontH = standardSizedFont;
  205876. if (size == 0)
  205877. {
  205878. OUTLINETEXTMETRIC otm;
  205879. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  205880. {
  205881. lfw.lfHeight = -(int) otm.otmEMSquare;
  205882. fontH = CreateFontIndirect (&lfw);
  205883. SelectObject (dc, fontH);
  205884. DeleteObject (standardSizedFont);
  205885. }
  205886. }
  205887. }
  205888. else
  205889. {
  205890. jassertfalse;
  205891. }
  205892. }
  205893. else
  205894. {
  205895. jassertfalse;
  205896. }
  205897. }
  205898. return dc;
  205899. }
  205900. KERNINGPAIR* getKerningPairs (int& numKPs_)
  205901. {
  205902. if (kps == 0)
  205903. {
  205904. numKPs = GetKerningPairs (dc, 0, 0);
  205905. kps.calloc (numKPs);
  205906. GetKerningPairs (dc, numKPs, kps);
  205907. }
  205908. numKPs_ = numKPs;
  205909. return kps;
  205910. }
  205911. private:
  205912. HFONT fontH;
  205913. HDC dc;
  205914. String fontName;
  205915. HeapBlock <KERNINGPAIR> kps;
  205916. int numKPs, size;
  205917. bool bold, italic;
  205918. FontDCHolder (const FontDCHolder&);
  205919. FontDCHolder& operator= (const FontDCHolder&);
  205920. };
  205921. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  205922. class WindowsTypeface : public CustomTypeface
  205923. {
  205924. public:
  205925. WindowsTypeface (const Font& font)
  205926. {
  205927. HDC dc = FontDCHolder::getInstance()->loadFont (font.getTypefaceName(),
  205928. font.isBold(), font.isItalic(), 0);
  205929. TEXTMETRIC tm;
  205930. tm.tmAscent = tm.tmHeight = 1;
  205931. tm.tmDefaultChar = 0;
  205932. GetTextMetrics (dc, &tm);
  205933. setCharacteristics (font.getTypefaceName(),
  205934. tm.tmAscent / (float) tm.tmHeight,
  205935. font.isBold(), font.isItalic(),
  205936. tm.tmDefaultChar);
  205937. }
  205938. bool loadGlyphIfPossible (juce_wchar character)
  205939. {
  205940. HDC dc = FontDCHolder::getInstance()->loadFont (name, isBold, isItalic, 0);
  205941. GLYPHMETRICS gm;
  205942. {
  205943. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  205944. WORD index = 0;
  205945. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  205946. && index == 0xffff)
  205947. {
  205948. return false;
  205949. }
  205950. }
  205951. Path glyphPath;
  205952. TEXTMETRIC tm;
  205953. if (! GetTextMetrics (dc, &tm))
  205954. {
  205955. addGlyph (character, glyphPath, 0);
  205956. return true;
  205957. }
  205958. const float height = (float) tm.tmHeight;
  205959. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  205960. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  205961. &gm, 0, 0, &identityMatrix);
  205962. if (bufSize > 0)
  205963. {
  205964. HeapBlock<char> data (bufSize);
  205965. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  205966. bufSize, data, &identityMatrix);
  205967. const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
  205968. const float scaleX = 1.0f / height;
  205969. const float scaleY = -1.0f / height;
  205970. while ((char*) pheader < data + bufSize)
  205971. {
  205972. float x = scaleX * pheader->pfxStart.x.value;
  205973. float y = scaleY * pheader->pfxStart.y.value;
  205974. glyphPath.startNewSubPath (x, y);
  205975. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  205976. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  205977. while ((const char*) curve < curveEnd)
  205978. {
  205979. if (curve->wType == TT_PRIM_LINE)
  205980. {
  205981. for (int i = 0; i < curve->cpfx; ++i)
  205982. {
  205983. x = scaleX * curve->apfx[i].x.value;
  205984. y = scaleY * curve->apfx[i].y.value;
  205985. glyphPath.lineTo (x, y);
  205986. }
  205987. }
  205988. else if (curve->wType == TT_PRIM_QSPLINE)
  205989. {
  205990. for (int i = 0; i < curve->cpfx - 1; ++i)
  205991. {
  205992. const float x2 = scaleX * curve->apfx[i].x.value;
  205993. const float y2 = scaleY * curve->apfx[i].y.value;
  205994. float x3, y3;
  205995. if (i < curve->cpfx - 2)
  205996. {
  205997. x3 = 0.5f * (x2 + scaleX * curve->apfx[i + 1].x.value);
  205998. y3 = 0.5f * (y2 + scaleY * curve->apfx[i + 1].y.value);
  205999. }
  206000. else
  206001. {
  206002. x3 = scaleX * curve->apfx[i + 1].x.value;
  206003. y3 = scaleY * curve->apfx[i + 1].y.value;
  206004. }
  206005. glyphPath.quadraticTo (x2, y2, x3, y3);
  206006. x = x3;
  206007. y = y3;
  206008. }
  206009. }
  206010. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  206011. }
  206012. pheader = (const TTPOLYGONHEADER*) curve;
  206013. glyphPath.closeSubPath();
  206014. }
  206015. }
  206016. addGlyph (character, glyphPath, gm.gmCellIncX / height);
  206017. int numKPs;
  206018. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  206019. for (int i = 0; i < numKPs; ++i)
  206020. {
  206021. if (kps[i].wFirst == character)
  206022. addKerningPair (kps[i].wFirst, kps[i].wSecond,
  206023. kps[i].iKernAmount / height);
  206024. }
  206025. return true;
  206026. }
  206027. juce_UseDebuggingNewOperator
  206028. };
  206029. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  206030. {
  206031. return new WindowsTypeface (font);
  206032. }
  206033. #endif
  206034. /*** End of inlined file: juce_win32_Fonts.cpp ***/
  206035. /*** Start of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206036. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206037. // compiled on its own).
  206038. #if JUCE_INCLUDED_FILE && JUCE_DIRECT2D
  206039. class SharedD2DFactory : public DeletedAtShutdown
  206040. {
  206041. public:
  206042. SharedD2DFactory()
  206043. {
  206044. D2D1CreateFactory (D2D1_FACTORY_TYPE_SINGLE_THREADED, &d2dFactory);
  206045. DWriteCreateFactory (DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &directWriteFactory);
  206046. if (directWriteFactory != 0)
  206047. directWriteFactory->GetSystemFontCollection (&systemFonts);
  206048. }
  206049. ~SharedD2DFactory()
  206050. {
  206051. clearSingletonInstance();
  206052. }
  206053. juce_DeclareSingleton (SharedD2DFactory, false);
  206054. ComSmartPtr <ID2D1Factory> d2dFactory;
  206055. ComSmartPtr <IDWriteFactory> directWriteFactory;
  206056. ComSmartPtr <IDWriteFontCollection> systemFonts;
  206057. };
  206058. juce_ImplementSingleton (SharedD2DFactory)
  206059. class Direct2DLowLevelGraphicsContext : public LowLevelGraphicsContext
  206060. {
  206061. public:
  206062. Direct2DLowLevelGraphicsContext (HWND hwnd_)
  206063. : hwnd (hwnd_),
  206064. currentState (0)
  206065. {
  206066. RECT windowRect;
  206067. GetClientRect (hwnd, &windowRect);
  206068. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206069. bounds.setSize (size.width, size.height);
  206070. D2D1_RENDER_TARGET_PROPERTIES props = D2D1::RenderTargetProperties();
  206071. D2D1_HWND_RENDER_TARGET_PROPERTIES propsHwnd = D2D1::HwndRenderTargetProperties (hwnd, size);
  206072. HRESULT hr = SharedD2DFactory::getInstance()->d2dFactory->CreateHwndRenderTarget (props, propsHwnd, &renderingTarget);
  206073. // xxx check for error
  206074. hr = renderingTarget->CreateSolidColorBrush (D2D1::ColorF::ColorF (0.0f, 0.0f, 0.0f, 1.0f), &colourBrush);
  206075. }
  206076. ~Direct2DLowLevelGraphicsContext()
  206077. {
  206078. states.clear();
  206079. }
  206080. void resized()
  206081. {
  206082. RECT windowRect;
  206083. GetClientRect (hwnd, &windowRect);
  206084. D2D1_SIZE_U size = { windowRect.right - windowRect.left, windowRect.bottom - windowRect.top };
  206085. renderingTarget->Resize (size);
  206086. bounds.setSize (size.width, size.height);
  206087. }
  206088. void clear()
  206089. {
  206090. renderingTarget->Clear (D2D1::ColorF (D2D1::ColorF::White, 0.0f)); // xxx why white and not black?
  206091. }
  206092. void start()
  206093. {
  206094. renderingTarget->BeginDraw();
  206095. saveState();
  206096. }
  206097. void end()
  206098. {
  206099. states.clear();
  206100. currentState = 0;
  206101. renderingTarget->EndDraw();
  206102. renderingTarget->CheckWindowState();
  206103. }
  206104. bool isVectorDevice() const { return false; }
  206105. void setOrigin (int x, int y)
  206106. {
  206107. currentState->origin.addXY (x, y);
  206108. }
  206109. bool clipToRectangle (const Rectangle<int>& r)
  206110. {
  206111. currentState->clipToRectangle (r);
  206112. return ! isClipEmpty();
  206113. }
  206114. bool clipToRectangleList (const RectangleList& clipRegion)
  206115. {
  206116. currentState->clipToRectList (rectListToPathGeometry (clipRegion));
  206117. return ! isClipEmpty();
  206118. }
  206119. void excludeClipRectangle (const Rectangle<int>&)
  206120. {
  206121. //xxx
  206122. }
  206123. void clipToPath (const Path& path, const AffineTransform& transform)
  206124. {
  206125. currentState->clipToPath (pathToPathGeometry (path, transform, currentState->origin));
  206126. }
  206127. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  206128. {
  206129. currentState->clipToImage (sourceImage,transform);
  206130. }
  206131. bool clipRegionIntersects (const Rectangle<int>& r)
  206132. {
  206133. const Rectangle<int> r2 (r + currentState->origin);
  206134. return currentState->clipRect.intersects (r2);
  206135. }
  206136. const Rectangle<int> getClipBounds() const
  206137. {
  206138. // xxx could this take into account complex clip regions?
  206139. return currentState->clipRect - currentState->origin;
  206140. }
  206141. bool isClipEmpty() const
  206142. {
  206143. return currentState->clipRect.isEmpty();
  206144. }
  206145. void saveState()
  206146. {
  206147. states.add (new SavedState (*this));
  206148. currentState = states.getLast();
  206149. }
  206150. void restoreState()
  206151. {
  206152. jassert (states.size() > 1) //you should never pop the last state!
  206153. states.removeLast (1);
  206154. currentState = states.getLast();
  206155. }
  206156. void setFill (const FillType& fillType)
  206157. {
  206158. currentState->setFill (fillType);
  206159. }
  206160. void setOpacity (float newOpacity)
  206161. {
  206162. currentState->setOpacity (newOpacity);
  206163. }
  206164. void setInterpolationQuality (Graphics::ResamplingQuality /*quality*/)
  206165. {
  206166. }
  206167. void fillRect (const Rectangle<int>& r, bool replaceExistingContents)
  206168. {
  206169. currentState->createBrush();
  206170. renderingTarget->FillRectangle (rectangleToRectF (r + currentState->origin), currentState->currentBrush);
  206171. }
  206172. void fillPath (const Path& p, const AffineTransform& transform)
  206173. {
  206174. currentState->createBrush();
  206175. ComSmartPtr <ID2D1Geometry> geometry (pathToPathGeometry (p, transform, currentState->origin));
  206176. if (renderingTarget != 0)
  206177. renderingTarget->FillGeometry (geometry, currentState->currentBrush);
  206178. }
  206179. void drawImage (const Image& image, const AffineTransform& transform, bool fillEntireClipAsTiles)
  206180. {
  206181. const int x = currentState->origin.getX();
  206182. const int y = currentState->origin.getY();
  206183. renderingTarget->SetTransform (transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206184. D2D1_SIZE_U size;
  206185. size.width = image.getWidth();
  206186. size.height = image.getHeight();
  206187. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206188. Image img (image.convertedToFormat (Image::ARGB));
  206189. Image::BitmapData bd (img, false);
  206190. bp.pixelFormat = renderingTarget->GetPixelFormat();
  206191. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206192. {
  206193. ComSmartPtr <ID2D1Bitmap> tempBitmap;
  206194. renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &tempBitmap);
  206195. if (tempBitmap != 0)
  206196. renderingTarget->DrawBitmap (tempBitmap);
  206197. }
  206198. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206199. }
  206200. void drawLine (const Line <float>& line)
  206201. {
  206202. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206203. const Line<float> l (line.getStart() + currentState->origin.toFloat(),
  206204. line.getEnd() + currentState->origin.toFloat());
  206205. currentState->createBrush();
  206206. renderingTarget->DrawLine (D2D1::Point2F (l.getStartX(), l.getStartY()),
  206207. D2D1::Point2F (l.getEndX(), l.getEndY()),
  206208. currentState->currentBrush);
  206209. }
  206210. void drawVerticalLine (int x, float top, float bottom)
  206211. {
  206212. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206213. currentState->createBrush();
  206214. x += currentState->origin.getX();
  206215. const int y = currentState->origin.getY();
  206216. renderingTarget->DrawLine (D2D1::Point2F (x, y + top),
  206217. D2D1::Point2F (x, y + bottom),
  206218. currentState->currentBrush);
  206219. }
  206220. void drawHorizontalLine (int y, float left, float right)
  206221. {
  206222. // xxx doesn't seem to be correctly aligned, may need nudging by 0.5 to match the software renderer's behaviour
  206223. currentState->createBrush();
  206224. y += currentState->origin.getY();
  206225. const int x = currentState->origin.getX();
  206226. renderingTarget->DrawLine (D2D1::Point2F (x + left, y),
  206227. D2D1::Point2F (x + right, y),
  206228. currentState->currentBrush);
  206229. }
  206230. void setFont (const Font& newFont)
  206231. {
  206232. currentState->setFont (newFont);
  206233. }
  206234. const Font getFont()
  206235. {
  206236. return currentState->font;
  206237. }
  206238. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  206239. {
  206240. const float x = currentState->origin.getX();
  206241. const float y = currentState->origin.getY();
  206242. currentState->createBrush();
  206243. currentState->createFont();
  206244. float kerning = currentState->font.getExtraKerningFactor(); // xxx why does removing this line mess up the kerning??
  206245. float hScale = currentState->font.getHorizontalScale();
  206246. renderingTarget->SetTransform (D2D1::Matrix3x2F::Scale (hScale, 1) * transfromToMatrix (transform) * D2D1::Matrix3x2F::Translation (x, y));
  206247. float dpiX = 0, dpiY = 0;
  206248. SharedD2DFactory::getInstance()->d2dFactory->GetDesktopDpi (&dpiX, &dpiY);
  206249. UINT32 glyphNum = glyphNumber;
  206250. UINT16 glyphNum1 = 0; // xxx needs a better name - what is this for?
  206251. currentState->currentFontFace->GetGlyphIndices (&glyphNum, 1, &glyphNum1);
  206252. DWRITE_GLYPH_OFFSET offset;
  206253. offset.advanceOffset = 0;
  206254. offset.ascenderOffset = 0;
  206255. float glyphAdvances = 0;
  206256. DWRITE_GLYPH_RUN glyph;
  206257. glyph.fontFace = currentState->currentFontFace;
  206258. glyph.glyphCount = 1;
  206259. glyph.glyphIndices = &glyphNum1;
  206260. glyph.isSideways = FALSE;
  206261. glyph.glyphAdvances = &glyphAdvances;
  206262. glyph.glyphOffsets = &offset;
  206263. glyph.fontEmSize = (float) currentState->font.getHeight() * dpiX / 96.0f * (1 + currentState->fontScaling) / 2;
  206264. renderingTarget->DrawGlyphRun (D2D1::Point2F (0, 0), &glyph, currentState->currentBrush);
  206265. renderingTarget->SetTransform (D2D1::IdentityMatrix());
  206266. }
  206267. class SavedState
  206268. {
  206269. public:
  206270. SavedState (Direct2DLowLevelGraphicsContext& owner_)
  206271. : owner (owner_), currentBrush (0),
  206272. fontScaling (1.0f), currentFontFace (0),
  206273. clipsRect (false), shouldClipRect (false),
  206274. clipsRectList (false), shouldClipRectList (false),
  206275. clipsComplex (false), shouldClipComplex (false),
  206276. clipsBitmap (false), shouldClipBitmap (false)
  206277. {
  206278. if (owner.currentState != 0)
  206279. {
  206280. // xxx seems like a very slow way to create one of these, and this is a performance
  206281. // bottleneck.. Can the same internal objects be shared by multiple state objects, maybe using copy-on-write?
  206282. setFill (owner.currentState->fillType);
  206283. currentBrush = owner.currentState->currentBrush;
  206284. origin = owner.currentState->origin;
  206285. clipRect = owner.currentState->clipRect;
  206286. font = owner.currentState->font;
  206287. currentFontFace = owner.currentState->currentFontFace;
  206288. }
  206289. else
  206290. {
  206291. const D2D1_SIZE_U size (owner.renderingTarget->GetPixelSize());
  206292. clipRect.setSize (size.width, size.height);
  206293. setFill (FillType (Colours::black));
  206294. }
  206295. }
  206296. ~SavedState()
  206297. {
  206298. clearClip();
  206299. clearFont();
  206300. clearFill();
  206301. clearPathClip();
  206302. clearImageClip();
  206303. complexClipLayer = 0;
  206304. bitmapMaskLayer = 0;
  206305. }
  206306. void clearClip()
  206307. {
  206308. popClips();
  206309. shouldClipRect = false;
  206310. }
  206311. void clipToRectangle (const Rectangle<int>& r)
  206312. {
  206313. clearClip();
  206314. clipRect = r + origin;
  206315. shouldClipRect = true;
  206316. pushClips();
  206317. }
  206318. void clearPathClip()
  206319. {
  206320. popClips();
  206321. if (shouldClipComplex)
  206322. {
  206323. complexClipGeometry = 0;
  206324. shouldClipComplex = false;
  206325. }
  206326. }
  206327. void clipToPath (ID2D1Geometry* geometry)
  206328. {
  206329. clearPathClip();
  206330. if (complexClipLayer == 0)
  206331. owner.renderingTarget->CreateLayer (&complexClipLayer);
  206332. complexClipGeometry = geometry;
  206333. shouldClipComplex = true;
  206334. pushClips();
  206335. }
  206336. void clearRectListClip()
  206337. {
  206338. popClips();
  206339. if (shouldClipRectList)
  206340. {
  206341. rectListGeometry = 0;
  206342. shouldClipRectList = false;
  206343. }
  206344. }
  206345. void clipToRectList (ID2D1Geometry* geometry)
  206346. {
  206347. clearRectListClip();
  206348. if (rectListLayer == 0)
  206349. owner.renderingTarget->CreateLayer (&rectListLayer);
  206350. rectListGeometry = geometry;
  206351. shouldClipRectList = true;
  206352. pushClips();
  206353. }
  206354. void clearImageClip()
  206355. {
  206356. popClips();
  206357. if (shouldClipBitmap)
  206358. {
  206359. maskBitmap = 0;
  206360. bitmapMaskBrush = 0;
  206361. shouldClipBitmap = false;
  206362. }
  206363. }
  206364. void clipToImage (const Image& image, const AffineTransform& transform)
  206365. {
  206366. clearImageClip();
  206367. if (bitmapMaskLayer == 0)
  206368. owner.renderingTarget->CreateLayer (&bitmapMaskLayer);
  206369. D2D1_BRUSH_PROPERTIES brushProps;
  206370. brushProps.opacity = 1;
  206371. brushProps.transform = transfromToMatrix (transform);
  206372. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP, D2D1_EXTEND_MODE_WRAP);
  206373. D2D1_SIZE_U size;
  206374. size.width = image.getWidth();
  206375. size.height = image.getHeight();
  206376. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206377. maskImage = image.convertedToFormat (Image::ARGB);
  206378. Image::BitmapData bd (this->image, false); // xxx should be maskImage?
  206379. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206380. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206381. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &maskBitmap);
  206382. hr = owner.renderingTarget->CreateBitmapBrush (maskBitmap, bmProps, brushProps, &bitmapMaskBrush);
  206383. imageMaskLayerParams = D2D1::LayerParameters();
  206384. imageMaskLayerParams.opacityBrush = bitmapMaskBrush;
  206385. shouldClipBitmap = true;
  206386. pushClips();
  206387. }
  206388. void popClips()
  206389. {
  206390. if (clipsBitmap)
  206391. {
  206392. owner.renderingTarget->PopLayer();
  206393. clipsBitmap = false;
  206394. }
  206395. if (clipsComplex)
  206396. {
  206397. owner.renderingTarget->PopLayer();
  206398. clipsComplex = false;
  206399. }
  206400. if (clipsRectList)
  206401. {
  206402. owner.renderingTarget->PopLayer();
  206403. clipsRectList = false;
  206404. }
  206405. if (clipsRect)
  206406. {
  206407. owner.renderingTarget->PopAxisAlignedClip();
  206408. clipsRect = false;
  206409. }
  206410. }
  206411. void pushClips()
  206412. {
  206413. if (shouldClipRect && ! clipsRect)
  206414. {
  206415. owner.renderingTarget->PushAxisAlignedClip (rectangleToRectF (clipRect), D2D1_ANTIALIAS_MODE_PER_PRIMITIVE);
  206416. clipsRect = true;
  206417. }
  206418. if (shouldClipRectList && ! clipsRectList)
  206419. {
  206420. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206421. rectListGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206422. layerParams.geometricMask = rectListGeometry;
  206423. owner.renderingTarget->PushLayer (layerParams, rectListLayer);
  206424. clipsRectList = true;
  206425. }
  206426. if (shouldClipComplex && ! clipsComplex)
  206427. {
  206428. D2D1_LAYER_PARAMETERS layerParams = D2D1::LayerParameters();
  206429. complexClipGeometry->GetBounds (D2D1::IdentityMatrix(), &layerParams.contentBounds);
  206430. layerParams.geometricMask = complexClipGeometry;
  206431. owner.renderingTarget->PushLayer (layerParams, complexClipLayer);
  206432. clipsComplex = true;
  206433. }
  206434. if (shouldClipBitmap && ! clipsBitmap)
  206435. {
  206436. owner.renderingTarget->PushLayer (imageMaskLayerParams, bitmapMaskLayer);
  206437. clipsBitmap = true;
  206438. }
  206439. }
  206440. void setFill (const FillType& newFillType)
  206441. {
  206442. if (fillType != newFillType)
  206443. {
  206444. fillType = newFillType;
  206445. clearFill();
  206446. }
  206447. }
  206448. void clearFont()
  206449. {
  206450. currentFontFace = localFontFace = 0;
  206451. }
  206452. void setFont (const Font& newFont)
  206453. {
  206454. if (font != newFont)
  206455. {
  206456. font = newFont;
  206457. clearFont();
  206458. }
  206459. }
  206460. void createFont()
  206461. {
  206462. // xxx The font shouldn't be managed by the graphics context.
  206463. // The correct way to handle font lifetimes is to use a subclass of Typeface - see
  206464. // MacTypeface and WindowsTypeface classes. D2D support could probably just be added to the
  206465. // WindowsTypeface class.
  206466. if (currentFontFace == 0)
  206467. {
  206468. WindowsTypeface* systemType = dynamic_cast<WindowsTypeface*> (font.getTypeface());
  206469. fontScaling = systemType->getAscent();
  206470. BOOL fontFound;
  206471. uint32 fontIndex;
  206472. IDWriteFontCollection* fonts = SharedD2DFactory::getInstance()->systemFonts;
  206473. fonts->FindFamilyName (systemType->getName(), &fontIndex, &fontFound);
  206474. if (! fontFound)
  206475. fontIndex = 0;
  206476. ComSmartPtr <IDWriteFontFamily> fontFam;
  206477. fonts->GetFontFamily (fontIndex, &fontFam);
  206478. ComSmartPtr <IDWriteFont> font;
  206479. DWRITE_FONT_WEIGHT weight = this->font.isBold() ? DWRITE_FONT_WEIGHT_BOLD : DWRITE_FONT_WEIGHT_NORMAL;
  206480. DWRITE_FONT_STYLE style = this->font.isItalic() ? DWRITE_FONT_STYLE_ITALIC : DWRITE_FONT_STYLE_NORMAL;
  206481. fontFam->GetFirstMatchingFont (weight, DWRITE_FONT_STRETCH_NORMAL, style, &font);
  206482. font->CreateFontFace (&localFontFace);
  206483. currentFontFace = localFontFace;
  206484. }
  206485. }
  206486. void setOpacity (float newOpacity)
  206487. {
  206488. fillType.setOpacity (newOpacity);
  206489. if (currentBrush != 0)
  206490. currentBrush->SetOpacity (newOpacity);
  206491. }
  206492. void clearFill()
  206493. {
  206494. gradientStops = 0;
  206495. linearGradient = 0;
  206496. radialGradient = 0;
  206497. bitmap = 0;
  206498. bitmapBrush = 0;
  206499. currentBrush = 0;
  206500. }
  206501. void createBrush()
  206502. {
  206503. if (currentBrush == 0)
  206504. {
  206505. const int x = origin.getX();
  206506. const int y = origin.getY();
  206507. if (fillType.isColour())
  206508. {
  206509. D2D1_COLOR_F colour = colourToD2D (fillType.colour);
  206510. owner.colourBrush->SetColor (colour);
  206511. currentBrush = owner.colourBrush;
  206512. }
  206513. else if (fillType.isTiledImage())
  206514. {
  206515. D2D1_BRUSH_PROPERTIES brushProps;
  206516. brushProps.opacity = fillType.getOpacity();
  206517. brushProps.transform = transfromToMatrix (fillType.transform);
  206518. D2D1_BITMAP_BRUSH_PROPERTIES bmProps = D2D1::BitmapBrushProperties (D2D1_EXTEND_MODE_WRAP,D2D1_EXTEND_MODE_WRAP);
  206519. image = fillType.image;
  206520. D2D1_SIZE_U size;
  206521. size.width = image.getWidth();
  206522. size.height = image.getHeight();
  206523. D2D1_BITMAP_PROPERTIES bp = D2D1::BitmapProperties();
  206524. this->image = image.convertedToFormat (Image::ARGB);
  206525. Image::BitmapData bd (this->image, false);
  206526. bp.pixelFormat = owner.renderingTarget->GetPixelFormat();
  206527. bp.pixelFormat.alphaMode = D2D1_ALPHA_MODE_PREMULTIPLIED;
  206528. HRESULT hr = owner.renderingTarget->CreateBitmap (size, bd.data, bd.lineStride, bp, &bitmap);
  206529. hr = owner.renderingTarget->CreateBitmapBrush (bitmap, bmProps, brushProps, &bitmapBrush);
  206530. currentBrush = bitmapBrush;
  206531. }
  206532. else if (fillType.isGradient())
  206533. {
  206534. gradientStops = 0;
  206535. D2D1_BRUSH_PROPERTIES brushProps;
  206536. brushProps.opacity = fillType.getOpacity();
  206537. brushProps.transform = transfromToMatrix (fillType.transform);
  206538. const int numColors = fillType.gradient->getNumColours();
  206539. HeapBlock<D2D1_GRADIENT_STOP> stops (numColors);
  206540. for (int i = fillType.gradient->getNumColours(); --i >= 0;)
  206541. {
  206542. stops[i].color = colourToD2D (fillType.gradient->getColour(i));
  206543. stops[i].position = fillType.gradient->getColourPosition(i);
  206544. }
  206545. owner.renderingTarget->CreateGradientStopCollection (stops.getData(), numColors, &gradientStops);
  206546. if (fillType.gradient->isRadial)
  206547. {
  206548. radialGradient = 0;
  206549. const Point<float>& p1 = fillType.gradient->point1;
  206550. const Point<float>& p2 = fillType.gradient->point2;
  206551. float r = p1.getDistanceFrom (p2);
  206552. D2D1_RADIAL_GRADIENT_BRUSH_PROPERTIES props =
  206553. D2D1::RadialGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206554. D2D1::Point2F (0, 0),
  206555. r, r);
  206556. owner.renderingTarget->CreateRadialGradientBrush (props, brushProps, gradientStops, &radialGradient);
  206557. currentBrush = radialGradient;
  206558. }
  206559. else
  206560. {
  206561. linearGradient = 0;
  206562. const Point<float>& p1 = fillType.gradient->point1;
  206563. const Point<float>& p2 = fillType.gradient->point2;
  206564. D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES props =
  206565. D2D1::LinearGradientBrushProperties (D2D1::Point2F (p1.getX() + x, p1.getY() + y),
  206566. D2D1::Point2F (p2.getX() + x, p2.getY() + y));
  206567. owner.renderingTarget->CreateLinearGradientBrush (props, brushProps, gradientStops, &linearGradient);
  206568. currentBrush = linearGradient;
  206569. }
  206570. }
  206571. }
  206572. }
  206573. juce_UseDebuggingNewOperator
  206574. //xxx most of these members should probably be private...
  206575. Direct2DLowLevelGraphicsContext& owner;
  206576. Point<int> origin;
  206577. Font font;
  206578. float fontScaling;
  206579. IDWriteFontFace* currentFontFace;
  206580. ComSmartPtr <IDWriteFontFace> localFontFace;
  206581. FillType fillType;
  206582. Image image;
  206583. ComSmartPtr <ID2D1Bitmap> bitmap; // xxx needs a better name - what is this for??
  206584. Rectangle<int> clipRect;
  206585. bool clipsRect, shouldClipRect;
  206586. ComSmartPtr <ID2D1Geometry> complexClipGeometry;
  206587. D2D1_LAYER_PARAMETERS complexClipLayerParams;
  206588. ComSmartPtr <ID2D1Layer> complexClipLayer;
  206589. bool clipsComplex, shouldClipComplex;
  206590. ComSmartPtr <ID2D1Geometry> rectListGeometry;
  206591. D2D1_LAYER_PARAMETERS rectListLayerParams;
  206592. ComSmartPtr <ID2D1Layer> rectListLayer;
  206593. bool clipsRectList, shouldClipRectList;
  206594. Image maskImage;
  206595. D2D1_LAYER_PARAMETERS imageMaskLayerParams;
  206596. ComSmartPtr <ID2D1Layer> bitmapMaskLayer;
  206597. ComSmartPtr <ID2D1Bitmap> maskBitmap;
  206598. ComSmartPtr <ID2D1BitmapBrush> bitmapMaskBrush;
  206599. bool clipsBitmap, shouldClipBitmap;
  206600. ID2D1Brush* currentBrush;
  206601. ComSmartPtr <ID2D1BitmapBrush> bitmapBrush;
  206602. ComSmartPtr <ID2D1LinearGradientBrush> linearGradient;
  206603. ComSmartPtr <ID2D1RadialGradientBrush> radialGradient;
  206604. ComSmartPtr <ID2D1GradientStopCollection> gradientStops;
  206605. private:
  206606. SavedState (const SavedState&);
  206607. SavedState& operator= (const SavedState& other);
  206608. };
  206609. juce_UseDebuggingNewOperator
  206610. private:
  206611. HWND hwnd;
  206612. ComSmartPtr <ID2D1HwndRenderTarget> renderingTarget;
  206613. ComSmartPtr <ID2D1SolidColorBrush> colourBrush;
  206614. Rectangle<int> bounds;
  206615. SavedState* currentState;
  206616. OwnedArray<SavedState> states;
  206617. static D2D1_RECT_F rectangleToRectF (const Rectangle<int>& r)
  206618. {
  206619. return D2D1::RectF ((float) r.getX(), (float) r.getY(), (float) r.getRight(), (float) r.getBottom());
  206620. }
  206621. static const D2D1_COLOR_F colourToD2D (const Colour& c)
  206622. {
  206623. return D2D1::ColorF::ColorF (c.getFloatRed(), c.getFloatGreen(), c.getFloatBlue(), c.getFloatAlpha());
  206624. }
  206625. static const D2D1_POINT_2F pointTransformed (int x, int y, const AffineTransform& transform = AffineTransform::identity)
  206626. {
  206627. transform.transformPoint (x, y);
  206628. return D2D1::Point2F (x, y);
  206629. }
  206630. static void rectToGeometrySink (const Rectangle<int>& rect, ID2D1GeometrySink* sink)
  206631. {
  206632. sink->BeginFigure (pointTransformed (rect.getX(), rect.getY()), D2D1_FIGURE_BEGIN_FILLED);
  206633. sink->AddLine (pointTransformed (rect.getRight(), rect.getY()));
  206634. sink->AddLine (pointTransformed (rect.getRight(), rect.getBottom()));
  206635. sink->AddLine (pointTransformed (rect.getX(), rect.getBottom()));
  206636. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206637. }
  206638. static ID2D1PathGeometry* rectListToPathGeometry (const RectangleList& clipRegion)
  206639. {
  206640. ID2D1PathGeometry* p = 0;
  206641. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206642. ComSmartPtr <ID2D1GeometrySink> sink;
  206643. HRESULT hr = p->Open (&sink); // xxx handle error
  206644. sink->SetFillMode (D2D1_FILL_MODE_WINDING);
  206645. for (int i = clipRegion.getNumRectangles(); --i >= 0;)
  206646. rectToGeometrySink (clipRegion.getRectangle(i), sink);
  206647. hr = sink->Close();
  206648. return p;
  206649. }
  206650. static void pathToGeometrySink (const Path& path, ID2D1GeometrySink* sink, const AffineTransform& transform, int x, int y)
  206651. {
  206652. Path::Iterator it (path);
  206653. while (it.next())
  206654. {
  206655. switch (it.elementType)
  206656. {
  206657. case Path::Iterator::cubicTo:
  206658. {
  206659. D2D1_BEZIER_SEGMENT seg;
  206660. transform.transformPoint (it.x1, it.y1);
  206661. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206662. transform.transformPoint (it.x2, it.y2);
  206663. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206664. transform.transformPoint(it.x3, it.y3);
  206665. seg.point3 = D2D1::Point2F (it.x3 + x, it.y3 + y);
  206666. sink->AddBezier (seg);
  206667. break;
  206668. }
  206669. case Path::Iterator::lineTo:
  206670. {
  206671. transform.transformPoint (it.x1, it.y1);
  206672. sink->AddLine (D2D1::Point2F (it.x1 + x, it.y1 + y));
  206673. break;
  206674. }
  206675. case Path::Iterator::quadraticTo:
  206676. {
  206677. D2D1_QUADRATIC_BEZIER_SEGMENT seg;
  206678. transform.transformPoint (it.x1, it.y1);
  206679. seg.point1 = D2D1::Point2F (it.x1 + x, it.y1 + y);
  206680. transform.transformPoint (it.x2, it.y2);
  206681. seg.point2 = D2D1::Point2F (it.x2 + x, it.y2 + y);
  206682. sink->AddQuadraticBezier (seg);
  206683. break;
  206684. }
  206685. case Path::Iterator::closePath:
  206686. {
  206687. sink->EndFigure (D2D1_FIGURE_END_CLOSED);
  206688. break;
  206689. }
  206690. case Path::Iterator::startNewSubPath:
  206691. {
  206692. transform.transformPoint (it.x1, it.y1);
  206693. sink->BeginFigure (D2D1::Point2F (it.x1 + x, it.y1 + y), D2D1_FIGURE_BEGIN_FILLED);
  206694. break;
  206695. }
  206696. }
  206697. }
  206698. }
  206699. static ID2D1PathGeometry* pathToPathGeometry (const Path& path, const AffineTransform& transform, const Point<int>& point)
  206700. {
  206701. ID2D1PathGeometry* p = 0;
  206702. SharedD2DFactory::getInstance()->d2dFactory->CreatePathGeometry (&p);
  206703. ComSmartPtr <ID2D1GeometrySink> sink;
  206704. HRESULT hr = p->Open (&sink);
  206705. sink->SetFillMode (D2D1_FILL_MODE_WINDING); // xxx need to check Path::isUsingNonZeroWinding()
  206706. pathToGeometrySink (path, sink, transform, point.getX(), point.getY());
  206707. hr = sink->Close();
  206708. return p;
  206709. }
  206710. static const D2D1::Matrix3x2F transfromToMatrix (const AffineTransform& transform)
  206711. {
  206712. D2D1::Matrix3x2F matrix;
  206713. matrix._11 = transform.mat00;
  206714. matrix._12 = transform.mat10;
  206715. matrix._21 = transform.mat01;
  206716. matrix._22 = transform.mat11;
  206717. matrix._31 = transform.mat02;
  206718. matrix._32 = transform.mat12;
  206719. return matrix;
  206720. }
  206721. };
  206722. #endif
  206723. /*** End of inlined file: juce_win32_Direct2DGraphicsContext.cpp ***/
  206724. /*** Start of inlined file: juce_win32_Windowing.cpp ***/
  206725. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206726. // compiled on its own).
  206727. #if JUCE_INCLUDED_FILE
  206728. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206729. // these are in the windows SDK, but need to be repeated here for GCC..
  206730. #ifndef GET_APPCOMMAND_LPARAM
  206731. #define FAPPCOMMAND_MASK 0xF000
  206732. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206733. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206734. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206735. #define APPCOMMAND_MEDIA_STOP 13
  206736. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206737. #define WM_APPCOMMAND 0x0319
  206738. #endif
  206739. extern void juce_repeatLastProcessPriority(); // in juce_win32_Threads.cpp
  206740. extern void juce_CheckCurrentlyFocusedTopLevelWindow(); // in juce_TopLevelWindow.cpp
  206741. extern bool juce_IsRunningInWine();
  206742. #ifndef ULW_ALPHA
  206743. #define ULW_ALPHA 0x00000002
  206744. #endif
  206745. #ifndef AC_SRC_ALPHA
  206746. #define AC_SRC_ALPHA 0x01
  206747. #endif
  206748. static HPALETTE palette = 0;
  206749. static bool createPaletteIfNeeded = true;
  206750. static bool shouldDeactivateTitleBar = true;
  206751. #define WM_TRAYNOTIFY WM_USER + 100
  206752. using ::abs;
  206753. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206754. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206755. bool Desktop::canUseSemiTransparentWindows() throw()
  206756. {
  206757. if (updateLayeredWindow == 0)
  206758. {
  206759. if (! juce_IsRunningInWine())
  206760. {
  206761. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206762. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206763. }
  206764. }
  206765. return updateLayeredWindow != 0;
  206766. }
  206767. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  206768. {
  206769. return upright;
  206770. }
  206771. const int extendedKeyModifier = 0x10000;
  206772. const int KeyPress::spaceKey = VK_SPACE;
  206773. const int KeyPress::returnKey = VK_RETURN;
  206774. const int KeyPress::escapeKey = VK_ESCAPE;
  206775. const int KeyPress::backspaceKey = VK_BACK;
  206776. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206777. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206778. const int KeyPress::tabKey = VK_TAB;
  206779. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206780. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206781. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206782. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206783. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206784. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206785. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206786. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206787. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206788. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206789. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206790. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206791. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206792. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206793. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206794. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206795. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206796. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206797. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206798. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206799. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206800. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206801. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206802. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206803. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206804. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206805. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206806. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206807. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206808. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206809. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206810. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206811. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206812. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206813. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206814. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206815. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206816. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206817. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206818. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206819. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206820. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206821. const int KeyPress::playKey = 0x30000;
  206822. const int KeyPress::stopKey = 0x30001;
  206823. const int KeyPress::fastForwardKey = 0x30002;
  206824. const int KeyPress::rewindKey = 0x30003;
  206825. class WindowsBitmapImage : public Image::SharedImage
  206826. {
  206827. public:
  206828. HBITMAP hBitmap;
  206829. BITMAPV4HEADER bitmapInfo;
  206830. HDC hdc;
  206831. unsigned char* bitmapData;
  206832. WindowsBitmapImage (const Image::PixelFormat format_,
  206833. const int w, const int h, const bool clearImage)
  206834. : Image::SharedImage (format_, w, h)
  206835. {
  206836. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  206837. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  206838. zerostruct (bitmapInfo);
  206839. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206840. bitmapInfo.bV4Width = w;
  206841. bitmapInfo.bV4Height = h;
  206842. bitmapInfo.bV4Planes = 1;
  206843. bitmapInfo.bV4CSType = 1;
  206844. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206845. if (format_ == Image::ARGB)
  206846. {
  206847. bitmapInfo.bV4AlphaMask = 0xff000000;
  206848. bitmapInfo.bV4RedMask = 0xff0000;
  206849. bitmapInfo.bV4GreenMask = 0xff00;
  206850. bitmapInfo.bV4BlueMask = 0xff;
  206851. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206852. }
  206853. else
  206854. {
  206855. bitmapInfo.bV4V4Compression = BI_RGB;
  206856. }
  206857. lineStride = -((w * pixelStride + 3) & ~3);
  206858. HDC dc = GetDC (0);
  206859. hdc = CreateCompatibleDC (dc);
  206860. ReleaseDC (0, dc);
  206861. SetMapMode (hdc, MM_TEXT);
  206862. hBitmap = CreateDIBSection (hdc,
  206863. (BITMAPINFO*) &(bitmapInfo),
  206864. DIB_RGB_COLORS,
  206865. (void**) &bitmapData,
  206866. 0, 0);
  206867. SelectObject (hdc, hBitmap);
  206868. if (format_ == Image::ARGB && clearImage)
  206869. zeromem (bitmapData, abs (h * lineStride));
  206870. imageData = bitmapData - (lineStride * (h - 1));
  206871. }
  206872. ~WindowsBitmapImage()
  206873. {
  206874. DeleteDC (hdc);
  206875. DeleteObject (hBitmap);
  206876. }
  206877. Image::ImageType getType() const { return Image::NativeImage; }
  206878. LowLevelGraphicsContext* createLowLevelContext()
  206879. {
  206880. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  206881. }
  206882. SharedImage* clone()
  206883. {
  206884. WindowsBitmapImage* im = new WindowsBitmapImage (format, width, height, false);
  206885. for (int i = 0; i < height; ++i)
  206886. memcpy (im->imageData + i * lineStride, imageData + i * lineStride, lineStride);
  206887. return im;
  206888. }
  206889. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206890. const int x, const int y,
  206891. const RectangleList& maskedRegion,
  206892. const uint8 updateLayeredWindowAlpha) throw()
  206893. {
  206894. static HDRAWDIB hdd = 0;
  206895. static bool needToCreateDrawDib = true;
  206896. if (needToCreateDrawDib)
  206897. {
  206898. needToCreateDrawDib = false;
  206899. HDC dc = GetDC (0);
  206900. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206901. ReleaseDC (0, dc);
  206902. // only open if we're not palettised
  206903. if (n > 8)
  206904. hdd = DrawDibOpen();
  206905. }
  206906. if (createPaletteIfNeeded)
  206907. {
  206908. HDC dc = GetDC (0);
  206909. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206910. ReleaseDC (0, dc);
  206911. if (n <= 8)
  206912. palette = CreateHalftonePalette (dc);
  206913. createPaletteIfNeeded = false;
  206914. }
  206915. if (palette != 0)
  206916. {
  206917. SelectPalette (dc, palette, FALSE);
  206918. RealizePalette (dc);
  206919. SetStretchBltMode (dc, HALFTONE);
  206920. }
  206921. SetMapMode (dc, MM_TEXT);
  206922. if (transparent)
  206923. {
  206924. POINT p, pos;
  206925. SIZE size;
  206926. RECT windowBounds;
  206927. GetWindowRect (hwnd, &windowBounds);
  206928. p.x = -x;
  206929. p.y = -y;
  206930. pos.x = windowBounds.left;
  206931. pos.y = windowBounds.top;
  206932. size.cx = windowBounds.right - windowBounds.left;
  206933. size.cy = windowBounds.bottom - windowBounds.top;
  206934. BLENDFUNCTION bf;
  206935. bf.AlphaFormat = AC_SRC_ALPHA;
  206936. bf.BlendFlags = 0;
  206937. bf.BlendOp = AC_SRC_OVER;
  206938. bf.SourceConstantAlpha = updateLayeredWindowAlpha;
  206939. if (! maskedRegion.isEmpty())
  206940. {
  206941. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206942. {
  206943. const Rectangle<int>& r = *i.getRectangle();
  206944. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206945. }
  206946. }
  206947. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206948. }
  206949. else
  206950. {
  206951. int savedDC = 0;
  206952. if (! maskedRegion.isEmpty())
  206953. {
  206954. savedDC = SaveDC (dc);
  206955. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206956. {
  206957. const Rectangle<int>& r = *i.getRectangle();
  206958. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206959. }
  206960. }
  206961. if (hdd == 0)
  206962. {
  206963. StretchDIBits (dc,
  206964. x, y, width, height,
  206965. 0, 0, width, height,
  206966. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206967. DIB_RGB_COLORS, SRCCOPY);
  206968. }
  206969. else
  206970. {
  206971. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206972. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206973. 0, 0, width, height, 0);
  206974. }
  206975. if (! maskedRegion.isEmpty())
  206976. RestoreDC (dc, savedDC);
  206977. }
  206978. }
  206979. juce_UseDebuggingNewOperator
  206980. private:
  206981. WindowsBitmapImage (const WindowsBitmapImage&);
  206982. WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206983. };
  206984. namespace IconConverters
  206985. {
  206986. const Image createImageFromHBITMAP (HBITMAP bitmap)
  206987. {
  206988. Image im;
  206989. if (bitmap != 0)
  206990. {
  206991. BITMAP bm;
  206992. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  206993. && bm.bmWidth > 0 && bm.bmHeight > 0)
  206994. {
  206995. HDC tempDC = GetDC (0);
  206996. HDC dc = CreateCompatibleDC (tempDC);
  206997. ReleaseDC (0, tempDC);
  206998. SelectObject (dc, bitmap);
  206999. im = Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  207000. Image::BitmapData imageData (im, true);
  207001. for (int y = bm.bmHeight; --y >= 0;)
  207002. {
  207003. for (int x = bm.bmWidth; --x >= 0;)
  207004. {
  207005. COLORREF col = GetPixel (dc, x, y);
  207006. imageData.setPixelColour (x, y, Colour ((uint8) GetRValue (col),
  207007. (uint8) GetGValue (col),
  207008. (uint8) GetBValue (col)));
  207009. }
  207010. }
  207011. DeleteDC (dc);
  207012. }
  207013. }
  207014. return im;
  207015. }
  207016. const Image createImageFromHICON (HICON icon)
  207017. {
  207018. ICONINFO info;
  207019. if (GetIconInfo (icon, &info))
  207020. {
  207021. Image mask (createImageFromHBITMAP (info.hbmMask));
  207022. Image image (createImageFromHBITMAP (info.hbmColor));
  207023. if (mask.isValid() && image.isValid())
  207024. {
  207025. for (int y = image.getHeight(); --y >= 0;)
  207026. {
  207027. for (int x = image.getWidth(); --x >= 0;)
  207028. {
  207029. const float brightness = mask.getPixelAt (x, y).getBrightness();
  207030. if (brightness > 0.0f)
  207031. image.multiplyAlphaAt (x, y, 1.0f - brightness);
  207032. }
  207033. }
  207034. return image;
  207035. }
  207036. }
  207037. return Image::null;
  207038. }
  207039. HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY)
  207040. {
  207041. WindowsBitmapImage* nativeBitmap = new WindowsBitmapImage (Image::ARGB, image.getWidth(), image.getHeight(), true);
  207042. Image bitmap (nativeBitmap);
  207043. {
  207044. Graphics g (bitmap);
  207045. g.drawImageAt (image, 0, 0);
  207046. }
  207047. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  207048. ICONINFO info;
  207049. info.fIcon = isIcon;
  207050. info.xHotspot = hotspotX;
  207051. info.yHotspot = hotspotY;
  207052. info.hbmMask = mask;
  207053. info.hbmColor = nativeBitmap->hBitmap;
  207054. HICON hi = CreateIconIndirect (&info);
  207055. DeleteObject (mask);
  207056. return hi;
  207057. }
  207058. }
  207059. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  207060. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  207061. {
  207062. SHORT k = (SHORT) keyCode;
  207063. if ((keyCode & extendedKeyModifier) == 0
  207064. && (k >= (SHORT) 'a' && k <= (SHORT) 'z'))
  207065. k += (SHORT) 'A' - (SHORT) 'a';
  207066. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  207067. (SHORT) '+', VK_OEM_PLUS,
  207068. (SHORT) '-', VK_OEM_MINUS,
  207069. (SHORT) '.', VK_OEM_PERIOD,
  207070. (SHORT) ';', VK_OEM_1,
  207071. (SHORT) ':', VK_OEM_1,
  207072. (SHORT) '/', VK_OEM_2,
  207073. (SHORT) '?', VK_OEM_2,
  207074. (SHORT) '[', VK_OEM_4,
  207075. (SHORT) ']', VK_OEM_6 };
  207076. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  207077. if (k == translatedValues [i])
  207078. k = translatedValues [i + 1];
  207079. return (GetKeyState (k) & 0x8000) != 0;
  207080. }
  207081. class Win32ComponentPeer : public ComponentPeer
  207082. {
  207083. public:
  207084. enum RenderingEngineType
  207085. {
  207086. softwareRenderingEngine = 0,
  207087. direct2DRenderingEngine
  207088. };
  207089. Win32ComponentPeer (Component* const component,
  207090. const int windowStyleFlags,
  207091. HWND parentToAddTo_)
  207092. : ComponentPeer (component, windowStyleFlags),
  207093. dontRepaint (false),
  207094. #if JUCE_DIRECT2D
  207095. currentRenderingEngine (direct2DRenderingEngine),
  207096. #else
  207097. currentRenderingEngine (softwareRenderingEngine),
  207098. #endif
  207099. fullScreen (false),
  207100. isDragging (false),
  207101. isMouseOver (false),
  207102. hasCreatedCaret (false),
  207103. currentWindowIcon (0),
  207104. dropTarget (0),
  207105. updateLayeredWindowAlpha (255),
  207106. parentToAddTo (parentToAddTo_)
  207107. {
  207108. callFunctionIfNotLocked (&createWindowCallback, this);
  207109. setTitle (component->getName());
  207110. if ((windowStyleFlags & windowHasDropShadow) != 0
  207111. && Desktop::canUseSemiTransparentWindows())
  207112. {
  207113. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  207114. if (shadower != 0)
  207115. shadower->setOwner (component);
  207116. }
  207117. }
  207118. ~Win32ComponentPeer()
  207119. {
  207120. setTaskBarIcon (Image());
  207121. shadower = 0;
  207122. // do this before the next bit to avoid messages arriving for this window
  207123. // before it's destroyed
  207124. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  207125. callFunctionIfNotLocked (&destroyWindowCallback, (void*) hwnd);
  207126. if (currentWindowIcon != 0)
  207127. DestroyIcon (currentWindowIcon);
  207128. if (dropTarget != 0)
  207129. {
  207130. dropTarget->Release();
  207131. dropTarget = 0;
  207132. }
  207133. #if JUCE_DIRECT2D
  207134. direct2DContext = 0;
  207135. #endif
  207136. }
  207137. void* getNativeHandle() const
  207138. {
  207139. return hwnd;
  207140. }
  207141. void setVisible (bool shouldBeVisible)
  207142. {
  207143. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  207144. if (shouldBeVisible)
  207145. InvalidateRect (hwnd, 0, 0);
  207146. else
  207147. lastPaintTime = 0;
  207148. }
  207149. void setTitle (const String& title)
  207150. {
  207151. SetWindowText (hwnd, title);
  207152. }
  207153. void setPosition (int x, int y)
  207154. {
  207155. offsetWithinParent (x, y);
  207156. SetWindowPos (hwnd, 0,
  207157. x - windowBorder.getLeft(),
  207158. y - windowBorder.getTop(),
  207159. 0, 0,
  207160. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207161. }
  207162. void repaintNowIfTransparent()
  207163. {
  207164. if (isUsingUpdateLayeredWindow() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  207165. handlePaintMessage();
  207166. }
  207167. void updateBorderSize()
  207168. {
  207169. WINDOWINFO info;
  207170. info.cbSize = sizeof (info);
  207171. if (GetWindowInfo (hwnd, &info))
  207172. {
  207173. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  207174. info.rcClient.left - info.rcWindow.left,
  207175. info.rcWindow.bottom - info.rcClient.bottom,
  207176. info.rcWindow.right - info.rcClient.right);
  207177. }
  207178. #if JUCE_DIRECT2D
  207179. if (direct2DContext != 0)
  207180. direct2DContext->resized();
  207181. #endif
  207182. }
  207183. void setSize (int w, int h)
  207184. {
  207185. SetWindowPos (hwnd, 0, 0, 0,
  207186. w + windowBorder.getLeftAndRight(),
  207187. h + windowBorder.getTopAndBottom(),
  207188. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207189. updateBorderSize();
  207190. repaintNowIfTransparent();
  207191. }
  207192. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  207193. {
  207194. fullScreen = isNowFullScreen;
  207195. offsetWithinParent (x, y);
  207196. SetWindowPos (hwnd, 0,
  207197. x - windowBorder.getLeft(),
  207198. y - windowBorder.getTop(),
  207199. w + windowBorder.getLeftAndRight(),
  207200. h + windowBorder.getTopAndBottom(),
  207201. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  207202. updateBorderSize();
  207203. repaintNowIfTransparent();
  207204. }
  207205. const Rectangle<int> getBounds() const
  207206. {
  207207. RECT r;
  207208. GetWindowRect (hwnd, &r);
  207209. Rectangle<int> bounds (r.left, r.top, r.right - r.left, r.bottom - r.top);
  207210. HWND parentH = GetParent (hwnd);
  207211. if (parentH != 0)
  207212. {
  207213. GetWindowRect (parentH, &r);
  207214. bounds.translate (-r.left, -r.top);
  207215. }
  207216. return windowBorder.subtractedFrom (bounds);
  207217. }
  207218. const Point<int> getScreenPosition() const
  207219. {
  207220. RECT r;
  207221. GetWindowRect (hwnd, &r);
  207222. return Point<int> (r.left + windowBorder.getLeft(),
  207223. r.top + windowBorder.getTop());
  207224. }
  207225. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  207226. {
  207227. return relativePosition + getScreenPosition();
  207228. }
  207229. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  207230. {
  207231. return screenPosition - getScreenPosition();
  207232. }
  207233. void setAlpha (float newAlpha)
  207234. {
  207235. const uint8 intAlpha = (uint8) jlimit (0, 255, (int) (newAlpha * 255.0f));
  207236. if (component->isOpaque())
  207237. {
  207238. if (newAlpha < 1.0f)
  207239. {
  207240. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) | WS_EX_LAYERED);
  207241. SetLayeredWindowAttributes (hwnd, RGB (0, 0, 0), intAlpha, LWA_ALPHA);
  207242. }
  207243. else
  207244. {
  207245. SetWindowLong (hwnd, GWL_EXSTYLE, GetWindowLong (hwnd, GWL_EXSTYLE) & ~WS_EX_LAYERED);
  207246. RedrawWindow (hwnd, 0, 0, RDW_ERASE | RDW_INVALIDATE | RDW_FRAME | RDW_ALLCHILDREN);
  207247. }
  207248. }
  207249. else
  207250. {
  207251. updateLayeredWindowAlpha = intAlpha;
  207252. component->repaint();
  207253. }
  207254. }
  207255. void setMinimised (bool shouldBeMinimised)
  207256. {
  207257. if (shouldBeMinimised != isMinimised())
  207258. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  207259. }
  207260. bool isMinimised() const
  207261. {
  207262. WINDOWPLACEMENT wp;
  207263. wp.length = sizeof (WINDOWPLACEMENT);
  207264. GetWindowPlacement (hwnd, &wp);
  207265. return wp.showCmd == SW_SHOWMINIMIZED;
  207266. }
  207267. void setFullScreen (bool shouldBeFullScreen)
  207268. {
  207269. setMinimised (false);
  207270. if (fullScreen != shouldBeFullScreen)
  207271. {
  207272. fullScreen = shouldBeFullScreen;
  207273. const Component::SafePointer<Component> deletionChecker (component);
  207274. if (! fullScreen)
  207275. {
  207276. const Rectangle<int> boundsCopy (lastNonFullscreenBounds);
  207277. if (hasTitleBar())
  207278. ShowWindow (hwnd, SW_SHOWNORMAL);
  207279. if (! boundsCopy.isEmpty())
  207280. {
  207281. setBounds (boundsCopy.getX(),
  207282. boundsCopy.getY(),
  207283. boundsCopy.getWidth(),
  207284. boundsCopy.getHeight(),
  207285. false);
  207286. }
  207287. }
  207288. else
  207289. {
  207290. if (hasTitleBar())
  207291. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  207292. else
  207293. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  207294. }
  207295. if (deletionChecker != 0)
  207296. handleMovedOrResized();
  207297. }
  207298. }
  207299. bool isFullScreen() const
  207300. {
  207301. if (! hasTitleBar())
  207302. return fullScreen;
  207303. WINDOWPLACEMENT wp;
  207304. wp.length = sizeof (wp);
  207305. GetWindowPlacement (hwnd, &wp);
  207306. return wp.showCmd == SW_SHOWMAXIMIZED;
  207307. }
  207308. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  207309. {
  207310. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  207311. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  207312. return false;
  207313. RECT r;
  207314. GetWindowRect (hwnd, &r);
  207315. POINT p;
  207316. p.x = position.getX() + r.left + windowBorder.getLeft();
  207317. p.y = position.getY() + r.top + windowBorder.getTop();
  207318. HWND w = WindowFromPoint (p);
  207319. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  207320. }
  207321. const BorderSize getFrameSize() const
  207322. {
  207323. return windowBorder;
  207324. }
  207325. bool setAlwaysOnTop (bool alwaysOnTop)
  207326. {
  207327. const bool oldDeactivate = shouldDeactivateTitleBar;
  207328. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207329. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  207330. 0, 0, 0, 0,
  207331. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207332. shouldDeactivateTitleBar = oldDeactivate;
  207333. if (shadower != 0)
  207334. shadower->componentBroughtToFront (*component);
  207335. return true;
  207336. }
  207337. void toFront (bool makeActive)
  207338. {
  207339. setMinimised (false);
  207340. const bool oldDeactivate = shouldDeactivateTitleBar;
  207341. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207342. callFunctionIfNotLocked (makeActive ? &toFrontCallback1 : &toFrontCallback2, hwnd);
  207343. shouldDeactivateTitleBar = oldDeactivate;
  207344. if (! makeActive)
  207345. {
  207346. // in this case a broughttofront call won't have occured, so do it now..
  207347. handleBroughtToFront();
  207348. }
  207349. }
  207350. void toBehind (ComponentPeer* other)
  207351. {
  207352. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  207353. jassert (otherPeer != 0); // wrong type of window?
  207354. if (otherPeer != 0)
  207355. {
  207356. setMinimised (false);
  207357. // must be careful not to try to put a topmost window behind a normal one, or win32
  207358. // promotes the normal one to be topmost!
  207359. if (getComponent()->isAlwaysOnTop() == otherPeer->getComponent()->isAlwaysOnTop())
  207360. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  207361. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207362. else if (otherPeer->getComponent()->isAlwaysOnTop())
  207363. SetWindowPos (hwnd, HWND_TOP, 0, 0, 0, 0,
  207364. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207365. }
  207366. }
  207367. bool isFocused() const
  207368. {
  207369. return callFunctionIfNotLocked (&getFocusCallback, 0) == (void*) hwnd;
  207370. }
  207371. void grabFocus()
  207372. {
  207373. const bool oldDeactivate = shouldDeactivateTitleBar;
  207374. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  207375. callFunctionIfNotLocked (&setFocusCallback, hwnd);
  207376. shouldDeactivateTitleBar = oldDeactivate;
  207377. }
  207378. void textInputRequired (const Point<int>&)
  207379. {
  207380. if (! hasCreatedCaret)
  207381. {
  207382. hasCreatedCaret = true;
  207383. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  207384. }
  207385. ShowCaret (hwnd);
  207386. SetCaretPos (0, 0);
  207387. }
  207388. void repaint (const Rectangle<int>& area)
  207389. {
  207390. const RECT r = { area.getX(), area.getY(), area.getRight(), area.getBottom() };
  207391. InvalidateRect (hwnd, &r, FALSE);
  207392. }
  207393. void performAnyPendingRepaintsNow()
  207394. {
  207395. MSG m;
  207396. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  207397. DispatchMessage (&m);
  207398. }
  207399. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  207400. {
  207401. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  207402. return (Win32ComponentPeer*) (pointer_sized_int) GetWindowLongPtr (h, 8);
  207403. return 0;
  207404. }
  207405. void setTaskBarIcon (const Image& image)
  207406. {
  207407. if (image.isValid())
  207408. {
  207409. HICON hicon = IconConverters::createHICONFromImage (image, TRUE, 0, 0);
  207410. if (taskBarIcon == 0)
  207411. {
  207412. taskBarIcon = new NOTIFYICONDATA();
  207413. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  207414. taskBarIcon->hWnd = (HWND) hwnd;
  207415. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  207416. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  207417. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  207418. taskBarIcon->hIcon = hicon;
  207419. taskBarIcon->szTip[0] = 0;
  207420. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  207421. }
  207422. else
  207423. {
  207424. HICON oldIcon = taskBarIcon->hIcon;
  207425. taskBarIcon->hIcon = hicon;
  207426. taskBarIcon->uFlags = NIF_ICON;
  207427. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207428. DestroyIcon (oldIcon);
  207429. }
  207430. DestroyIcon (hicon);
  207431. }
  207432. else if (taskBarIcon != 0)
  207433. {
  207434. taskBarIcon->uFlags = 0;
  207435. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  207436. DestroyIcon (taskBarIcon->hIcon);
  207437. taskBarIcon = 0;
  207438. }
  207439. }
  207440. void setTaskBarIconToolTip (const String& toolTip) const
  207441. {
  207442. if (taskBarIcon != 0)
  207443. {
  207444. taskBarIcon->uFlags = NIF_TIP;
  207445. toolTip.copyToUnicode (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  207446. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  207447. }
  207448. }
  207449. bool isInside (HWND h) const
  207450. {
  207451. return GetAncestor (hwnd, GA_ROOT) == h;
  207452. }
  207453. static void updateKeyModifiers() throw()
  207454. {
  207455. int keyMods = 0;
  207456. if (GetKeyState (VK_SHIFT) & 0x8000) keyMods |= ModifierKeys::shiftModifier;
  207457. if (GetKeyState (VK_CONTROL) & 0x8000) keyMods |= ModifierKeys::ctrlModifier;
  207458. if (GetKeyState (VK_MENU) & 0x8000) keyMods |= ModifierKeys::altModifier;
  207459. if (GetKeyState (VK_RMENU) & 0x8000) keyMods &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  207460. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  207461. }
  207462. static void updateModifiersFromWParam (const WPARAM wParam)
  207463. {
  207464. int mouseMods = 0;
  207465. if (wParam & MK_LBUTTON) mouseMods |= ModifierKeys::leftButtonModifier;
  207466. if (wParam & MK_RBUTTON) mouseMods |= ModifierKeys::rightButtonModifier;
  207467. if (wParam & MK_MBUTTON) mouseMods |= ModifierKeys::middleButtonModifier;
  207468. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  207469. updateKeyModifiers();
  207470. }
  207471. static int64 getMouseEventTime()
  207472. {
  207473. static int64 eventTimeOffset = 0;
  207474. static DWORD lastMessageTime = 0;
  207475. const DWORD thisMessageTime = GetMessageTime();
  207476. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  207477. {
  207478. lastMessageTime = thisMessageTime;
  207479. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  207480. }
  207481. return eventTimeOffset + thisMessageTime;
  207482. }
  207483. juce_UseDebuggingNewOperator
  207484. bool dontRepaint;
  207485. static ModifierKeys currentModifiers;
  207486. static ModifierKeys modifiersAtLastCallback;
  207487. private:
  207488. HWND hwnd, parentToAddTo;
  207489. ScopedPointer<DropShadower> shadower;
  207490. RenderingEngineType currentRenderingEngine;
  207491. #if JUCE_DIRECT2D
  207492. ScopedPointer<Direct2DLowLevelGraphicsContext> direct2DContext;
  207493. #endif
  207494. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  207495. BorderSize windowBorder;
  207496. HICON currentWindowIcon;
  207497. ScopedPointer<NOTIFYICONDATA> taskBarIcon;
  207498. IDropTarget* dropTarget;
  207499. uint8 updateLayeredWindowAlpha;
  207500. class TemporaryImage : public Timer
  207501. {
  207502. public:
  207503. TemporaryImage() {}
  207504. ~TemporaryImage() {}
  207505. const Image& getImage (const bool transparent, const int w, const int h)
  207506. {
  207507. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  207508. if ((! image.isValid()) || image.getWidth() < w || image.getHeight() < h || image.getFormat() != format)
  207509. image = Image (new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false));
  207510. startTimer (3000);
  207511. return image;
  207512. }
  207513. void timerCallback()
  207514. {
  207515. stopTimer();
  207516. image = Image::null;
  207517. }
  207518. private:
  207519. Image image;
  207520. TemporaryImage (const TemporaryImage&);
  207521. TemporaryImage& operator= (const TemporaryImage&);
  207522. };
  207523. TemporaryImage offscreenImageGenerator;
  207524. class WindowClassHolder : public DeletedAtShutdown
  207525. {
  207526. public:
  207527. WindowClassHolder()
  207528. : windowClassName ("JUCE_")
  207529. {
  207530. // this name has to be different for each app/dll instance because otherwise
  207531. // poor old Win32 can get a bit confused (even despite it not being a process-global
  207532. // window class).
  207533. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  207534. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  207535. TCHAR moduleFile [1024];
  207536. moduleFile[0] = 0;
  207537. GetModuleFileName (moduleHandle, moduleFile, 1024);
  207538. WORD iconNum = 0;
  207539. WNDCLASSEX wcex;
  207540. wcex.cbSize = sizeof (wcex);
  207541. wcex.style = CS_OWNDC;
  207542. wcex.lpfnWndProc = (WNDPROC) windowProc;
  207543. wcex.lpszClassName = windowClassName;
  207544. wcex.cbClsExtra = 0;
  207545. wcex.cbWndExtra = 32;
  207546. wcex.hInstance = moduleHandle;
  207547. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207548. iconNum = 1;
  207549. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  207550. wcex.hCursor = 0;
  207551. wcex.hbrBackground = 0;
  207552. wcex.lpszMenuName = 0;
  207553. RegisterClassEx (&wcex);
  207554. }
  207555. ~WindowClassHolder()
  207556. {
  207557. if (ComponentPeer::getNumPeers() == 0)
  207558. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  207559. clearSingletonInstance();
  207560. }
  207561. String windowClassName;
  207562. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  207563. };
  207564. static void* createWindowCallback (void* userData)
  207565. {
  207566. static_cast <Win32ComponentPeer*> (userData)->createWindow();
  207567. return 0;
  207568. }
  207569. void createWindow()
  207570. {
  207571. DWORD exstyle = WS_EX_ACCEPTFILES;
  207572. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  207573. if (hasTitleBar())
  207574. {
  207575. type |= WS_OVERLAPPED;
  207576. if ((styleFlags & windowHasCloseButton) != 0)
  207577. {
  207578. type |= WS_SYSMENU;
  207579. }
  207580. else
  207581. {
  207582. // annoyingly, windows won't let you have a min/max button without a close button
  207583. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  207584. }
  207585. if ((styleFlags & windowIsResizable) != 0)
  207586. type |= WS_THICKFRAME;
  207587. }
  207588. else if (parentToAddTo != 0)
  207589. {
  207590. type |= WS_CHILD;
  207591. }
  207592. else
  207593. {
  207594. type |= WS_POPUP | WS_SYSMENU;
  207595. }
  207596. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  207597. exstyle |= WS_EX_TOOLWINDOW;
  207598. else
  207599. exstyle |= WS_EX_APPWINDOW;
  207600. if ((styleFlags & windowHasMinimiseButton) != 0)
  207601. type |= WS_MINIMIZEBOX;
  207602. if ((styleFlags & windowHasMaximiseButton) != 0)
  207603. type |= WS_MAXIMIZEBOX;
  207604. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  207605. exstyle |= WS_EX_TRANSPARENT;
  207606. if ((styleFlags & windowIsSemiTransparent) != 0
  207607. && Desktop::canUseSemiTransparentWindows())
  207608. exstyle |= WS_EX_LAYERED;
  207609. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0,
  207610. parentToAddTo, 0, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(), 0);
  207611. #if JUCE_DIRECT2D
  207612. updateDirect2DContext();
  207613. #endif
  207614. if (hwnd != 0)
  207615. {
  207616. SetWindowLongPtr (hwnd, 0, 0);
  207617. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  207618. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207619. if (dropTarget == 0)
  207620. dropTarget = new JuceDropTarget (this);
  207621. RegisterDragDrop (hwnd, dropTarget);
  207622. updateBorderSize();
  207623. // Calling this function here is (for some reason) necessary to make Windows
  207624. // correctly enable the menu items that we specify in the wm_initmenu message.
  207625. GetSystemMenu (hwnd, false);
  207626. const float alpha = component->getAlpha();
  207627. if (alpha < 1.0f)
  207628. setAlpha (alpha);
  207629. }
  207630. else
  207631. {
  207632. jassertfalse;
  207633. }
  207634. }
  207635. static void* destroyWindowCallback (void* handle)
  207636. {
  207637. RevokeDragDrop ((HWND) handle);
  207638. DestroyWindow ((HWND) handle);
  207639. return 0;
  207640. }
  207641. static void* toFrontCallback1 (void* h)
  207642. {
  207643. SetForegroundWindow ((HWND) h);
  207644. return 0;
  207645. }
  207646. static void* toFrontCallback2 (void* h)
  207647. {
  207648. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207649. return 0;
  207650. }
  207651. static void* setFocusCallback (void* h)
  207652. {
  207653. SetFocus ((HWND) h);
  207654. return 0;
  207655. }
  207656. static void* getFocusCallback (void*)
  207657. {
  207658. return GetFocus();
  207659. }
  207660. void offsetWithinParent (int& x, int& y) const
  207661. {
  207662. if (isUsingUpdateLayeredWindow())
  207663. {
  207664. HWND parentHwnd = GetParent (hwnd);
  207665. if (parentHwnd != 0)
  207666. {
  207667. RECT parentRect;
  207668. GetWindowRect (parentHwnd, &parentRect);
  207669. x += parentRect.left;
  207670. y += parentRect.top;
  207671. }
  207672. }
  207673. }
  207674. bool isUsingUpdateLayeredWindow() const
  207675. {
  207676. return ! component->isOpaque();
  207677. }
  207678. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207679. void setIcon (const Image& newIcon)
  207680. {
  207681. HICON hicon = IconConverters::createHICONFromImage (newIcon, TRUE, 0, 0);
  207682. if (hicon != 0)
  207683. {
  207684. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207685. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207686. if (currentWindowIcon != 0)
  207687. DestroyIcon (currentWindowIcon);
  207688. currentWindowIcon = hicon;
  207689. }
  207690. }
  207691. void handlePaintMessage()
  207692. {
  207693. #if JUCE_DIRECT2D
  207694. if (direct2DContext != 0)
  207695. {
  207696. RECT r;
  207697. if (GetUpdateRect (hwnd, &r, false))
  207698. {
  207699. direct2DContext->start();
  207700. direct2DContext->clipToRectangle (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  207701. handlePaint (*direct2DContext);
  207702. direct2DContext->end();
  207703. }
  207704. }
  207705. else
  207706. #endif
  207707. {
  207708. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207709. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207710. PAINTSTRUCT paintStruct;
  207711. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207712. // message and become re-entrant, but that's OK
  207713. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207714. // corrupt the image it's using to paint into, so do a check here.
  207715. static bool reentrant = false;
  207716. if (reentrant)
  207717. {
  207718. DeleteObject (rgn);
  207719. EndPaint (hwnd, &paintStruct);
  207720. return;
  207721. }
  207722. reentrant = true;
  207723. // this is the rectangle to update..
  207724. int x = paintStruct.rcPaint.left;
  207725. int y = paintStruct.rcPaint.top;
  207726. int w = paintStruct.rcPaint.right - x;
  207727. int h = paintStruct.rcPaint.bottom - y;
  207728. const bool transparent = isUsingUpdateLayeredWindow();
  207729. if (transparent)
  207730. {
  207731. // it's not possible to have a transparent window with a title bar at the moment!
  207732. jassert (! hasTitleBar());
  207733. RECT r;
  207734. GetWindowRect (hwnd, &r);
  207735. x = y = 0;
  207736. w = r.right - r.left;
  207737. h = r.bottom - r.top;
  207738. }
  207739. if (w > 0 && h > 0)
  207740. {
  207741. clearMaskedRegion();
  207742. Image offscreenImage (offscreenImageGenerator.getImage (transparent, w, h));
  207743. RectangleList contextClip;
  207744. const Rectangle<int> clipBounds (0, 0, w, h);
  207745. bool needToPaintAll = true;
  207746. if (regionType == COMPLEXREGION && ! transparent)
  207747. {
  207748. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207749. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207750. DeleteObject (clipRgn);
  207751. char rgnData [8192];
  207752. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207753. if (res > 0 && res <= sizeof (rgnData))
  207754. {
  207755. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207756. if (hdr->iType == RDH_RECTANGLES
  207757. && hdr->rcBound.right - hdr->rcBound.left >= w
  207758. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207759. {
  207760. needToPaintAll = false;
  207761. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207762. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207763. while (--num >= 0)
  207764. {
  207765. if (rects->right <= x + w && rects->bottom <= y + h)
  207766. {
  207767. const int cx = jmax (x, (int) rects->left);
  207768. contextClip.addWithoutMerging (Rectangle<int> (cx - x, rects->top - y, rects->right - cx, rects->bottom - rects->top)
  207769. .getIntersection (clipBounds));
  207770. }
  207771. else
  207772. {
  207773. needToPaintAll = true;
  207774. break;
  207775. }
  207776. ++rects;
  207777. }
  207778. }
  207779. }
  207780. }
  207781. if (needToPaintAll)
  207782. {
  207783. contextClip.clear();
  207784. contextClip.addWithoutMerging (Rectangle<int> (w, h));
  207785. }
  207786. if (transparent)
  207787. {
  207788. RectangleList::Iterator i (contextClip);
  207789. while (i.next())
  207790. offscreenImage.clear (*i.getRectangle());
  207791. }
  207792. // if the component's not opaque, this won't draw properly unless the platform can support this
  207793. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207794. updateCurrentModifiers();
  207795. LowLevelGraphicsSoftwareRenderer context (offscreenImage, -x, -y, contextClip);
  207796. handlePaint (context);
  207797. if (! dontRepaint)
  207798. static_cast <WindowsBitmapImage*> (offscreenImage.getSharedImage())
  207799. ->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion, updateLayeredWindowAlpha);
  207800. }
  207801. DeleteObject (rgn);
  207802. EndPaint (hwnd, &paintStruct);
  207803. reentrant = false;
  207804. }
  207805. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207806. _fpreset(); // because some graphics cards can unmask FP exceptions
  207807. #endif
  207808. lastPaintTime = Time::getMillisecondCounter();
  207809. }
  207810. void doMouseEvent (const Point<int>& position)
  207811. {
  207812. handleMouseEvent (0, position, currentModifiers, getMouseEventTime());
  207813. }
  207814. const StringArray getAvailableRenderingEngines()
  207815. {
  207816. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  207817. #if JUCE_DIRECT2D
  207818. // xxx is this correct? Seems to enable it on Vista too??
  207819. OSVERSIONINFO info;
  207820. zerostruct (info);
  207821. info.dwOSVersionInfoSize = sizeof (OSVERSIONINFO);
  207822. GetVersionEx (&info);
  207823. if (info.dwMajorVersion >= 6)
  207824. s.add ("Direct2D");
  207825. #endif
  207826. return s;
  207827. }
  207828. int getCurrentRenderingEngine() throw()
  207829. {
  207830. return currentRenderingEngine;
  207831. }
  207832. #if JUCE_DIRECT2D
  207833. void updateDirect2DContext()
  207834. {
  207835. if (currentRenderingEngine != direct2DRenderingEngine)
  207836. direct2DContext = 0;
  207837. else if (direct2DContext == 0)
  207838. direct2DContext = new Direct2DLowLevelGraphicsContext (hwnd);
  207839. }
  207840. #endif
  207841. void setCurrentRenderingEngine (int index)
  207842. {
  207843. (void) index;
  207844. #if JUCE_DIRECT2D
  207845. currentRenderingEngine = index == 1 ? direct2DRenderingEngine : softwareRenderingEngine;
  207846. updateDirect2DContext();
  207847. repaint (component->getLocalBounds());
  207848. #endif
  207849. }
  207850. void doMouseMove (const Point<int>& position)
  207851. {
  207852. if (! isMouseOver)
  207853. {
  207854. isMouseOver = true;
  207855. updateKeyModifiers();
  207856. TRACKMOUSEEVENT tme;
  207857. tme.cbSize = sizeof (tme);
  207858. tme.dwFlags = TME_LEAVE;
  207859. tme.hwndTrack = hwnd;
  207860. tme.dwHoverTime = 0;
  207861. if (! TrackMouseEvent (&tme))
  207862. jassertfalse;
  207863. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  207864. }
  207865. else if (! isDragging)
  207866. {
  207867. if (! contains (position, false))
  207868. return;
  207869. }
  207870. // (Throttling the incoming queue of mouse-events seems to still be required in XP..)
  207871. static uint32 lastMouseTime = 0;
  207872. const uint32 now = Time::getMillisecondCounter();
  207873. const int maxMouseMovesPerSecond = 60;
  207874. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207875. {
  207876. lastMouseTime = now;
  207877. doMouseEvent (position);
  207878. }
  207879. }
  207880. void doMouseDown (const Point<int>& position, const WPARAM wParam)
  207881. {
  207882. if (GetCapture() != hwnd)
  207883. SetCapture (hwnd);
  207884. doMouseMove (position);
  207885. updateModifiersFromWParam (wParam);
  207886. isDragging = true;
  207887. doMouseEvent (position);
  207888. }
  207889. void doMouseUp (const Point<int>& position, const WPARAM wParam)
  207890. {
  207891. updateModifiersFromWParam (wParam);
  207892. isDragging = false;
  207893. // release the mouse capture if the user has released all buttons
  207894. if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) == 0 && hwnd == GetCapture())
  207895. ReleaseCapture();
  207896. doMouseEvent (position);
  207897. }
  207898. void doCaptureChanged()
  207899. {
  207900. if (isDragging)
  207901. doMouseUp (getCurrentMousePos(), (WPARAM) 0);
  207902. }
  207903. void doMouseExit()
  207904. {
  207905. isMouseOver = false;
  207906. doMouseEvent (getCurrentMousePos());
  207907. }
  207908. void doMouseWheel (const Point<int>& position, const WPARAM wParam, const bool isVertical)
  207909. {
  207910. updateKeyModifiers();
  207911. const float amount = jlimit (-1000.0f, 1000.0f, 0.75f * (short) HIWORD (wParam));
  207912. handleMouseWheel (0, position, getMouseEventTime(),
  207913. isVertical ? 0.0f : amount,
  207914. isVertical ? amount : 0.0f);
  207915. }
  207916. void sendModifierKeyChangeIfNeeded()
  207917. {
  207918. if (modifiersAtLastCallback != currentModifiers)
  207919. {
  207920. modifiersAtLastCallback = currentModifiers;
  207921. handleModifierKeysChange();
  207922. }
  207923. }
  207924. bool doKeyUp (const WPARAM key)
  207925. {
  207926. updateKeyModifiers();
  207927. switch (key)
  207928. {
  207929. case VK_SHIFT:
  207930. case VK_CONTROL:
  207931. case VK_MENU:
  207932. case VK_CAPITAL:
  207933. case VK_LWIN:
  207934. case VK_RWIN:
  207935. case VK_APPS:
  207936. case VK_NUMLOCK:
  207937. case VK_SCROLL:
  207938. case VK_LSHIFT:
  207939. case VK_RSHIFT:
  207940. case VK_LCONTROL:
  207941. case VK_LMENU:
  207942. case VK_RCONTROL:
  207943. case VK_RMENU:
  207944. sendModifierKeyChangeIfNeeded();
  207945. }
  207946. return handleKeyUpOrDown (false)
  207947. || Component::getCurrentlyModalComponent() != 0;
  207948. }
  207949. bool doKeyDown (const WPARAM key)
  207950. {
  207951. updateKeyModifiers();
  207952. bool used = false;
  207953. switch (key)
  207954. {
  207955. case VK_SHIFT:
  207956. case VK_LSHIFT:
  207957. case VK_RSHIFT:
  207958. case VK_CONTROL:
  207959. case VK_LCONTROL:
  207960. case VK_RCONTROL:
  207961. case VK_MENU:
  207962. case VK_LMENU:
  207963. case VK_RMENU:
  207964. case VK_LWIN:
  207965. case VK_RWIN:
  207966. case VK_CAPITAL:
  207967. case VK_NUMLOCK:
  207968. case VK_SCROLL:
  207969. case VK_APPS:
  207970. sendModifierKeyChangeIfNeeded();
  207971. break;
  207972. case VK_LEFT:
  207973. case VK_RIGHT:
  207974. case VK_UP:
  207975. case VK_DOWN:
  207976. case VK_PRIOR:
  207977. case VK_NEXT:
  207978. case VK_HOME:
  207979. case VK_END:
  207980. case VK_DELETE:
  207981. case VK_INSERT:
  207982. case VK_F1:
  207983. case VK_F2:
  207984. case VK_F3:
  207985. case VK_F4:
  207986. case VK_F5:
  207987. case VK_F6:
  207988. case VK_F7:
  207989. case VK_F8:
  207990. case VK_F9:
  207991. case VK_F10:
  207992. case VK_F11:
  207993. case VK_F12:
  207994. case VK_F13:
  207995. case VK_F14:
  207996. case VK_F15:
  207997. case VK_F16:
  207998. used = handleKeyUpOrDown (true);
  207999. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  208000. break;
  208001. case VK_ADD:
  208002. case VK_SUBTRACT:
  208003. case VK_MULTIPLY:
  208004. case VK_DIVIDE:
  208005. case VK_SEPARATOR:
  208006. case VK_DECIMAL:
  208007. used = handleKeyUpOrDown (true);
  208008. break;
  208009. default:
  208010. used = handleKeyUpOrDown (true);
  208011. {
  208012. MSG msg;
  208013. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  208014. {
  208015. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  208016. // manually generate the key-press event that matches this key-down.
  208017. const UINT keyChar = MapVirtualKey (key, 2);
  208018. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  208019. }
  208020. }
  208021. break;
  208022. }
  208023. if (Component::getCurrentlyModalComponent() != 0)
  208024. used = true;
  208025. return used;
  208026. }
  208027. bool doKeyChar (int key, const LPARAM flags)
  208028. {
  208029. updateKeyModifiers();
  208030. juce_wchar textChar = (juce_wchar) key;
  208031. const int virtualScanCode = (flags >> 16) & 0xff;
  208032. if (key >= '0' && key <= '9')
  208033. {
  208034. switch (virtualScanCode) // check for a numeric keypad scan-code
  208035. {
  208036. case 0x52:
  208037. case 0x4f:
  208038. case 0x50:
  208039. case 0x51:
  208040. case 0x4b:
  208041. case 0x4c:
  208042. case 0x4d:
  208043. case 0x47:
  208044. case 0x48:
  208045. case 0x49:
  208046. key = (key - '0') + KeyPress::numberPad0;
  208047. break;
  208048. default:
  208049. break;
  208050. }
  208051. }
  208052. else
  208053. {
  208054. // convert the scan code to an unmodified character code..
  208055. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  208056. UINT keyChar = MapVirtualKey (virtualKey, 2);
  208057. keyChar = LOWORD (keyChar);
  208058. if (keyChar != 0)
  208059. key = (int) keyChar;
  208060. // avoid sending junk text characters for some control-key combinations
  208061. if (textChar < ' ' && currentModifiers.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::altModifier))
  208062. textChar = 0;
  208063. }
  208064. return handleKeyPress (key, textChar);
  208065. }
  208066. bool doAppCommand (const LPARAM lParam)
  208067. {
  208068. int key = 0;
  208069. switch (GET_APPCOMMAND_LPARAM (lParam))
  208070. {
  208071. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  208072. key = KeyPress::playKey;
  208073. break;
  208074. case APPCOMMAND_MEDIA_STOP:
  208075. key = KeyPress::stopKey;
  208076. break;
  208077. case APPCOMMAND_MEDIA_NEXTTRACK:
  208078. key = KeyPress::fastForwardKey;
  208079. break;
  208080. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  208081. key = KeyPress::rewindKey;
  208082. break;
  208083. }
  208084. if (key != 0)
  208085. {
  208086. updateKeyModifiers();
  208087. if (hwnd == GetActiveWindow())
  208088. {
  208089. handleKeyPress (key, 0);
  208090. return true;
  208091. }
  208092. }
  208093. return false;
  208094. }
  208095. class JuceDropTarget : public ComBaseClassHelper <IDropTarget>
  208096. {
  208097. public:
  208098. JuceDropTarget (Win32ComponentPeer* const owner_)
  208099. : owner (owner_)
  208100. {
  208101. }
  208102. ~JuceDropTarget() {}
  208103. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208104. {
  208105. updateFileList (pDataObject);
  208106. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  208107. *pdwEffect = DROPEFFECT_COPY;
  208108. return S_OK;
  208109. }
  208110. HRESULT __stdcall DragLeave()
  208111. {
  208112. owner->handleFileDragExit (files);
  208113. return S_OK;
  208114. }
  208115. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208116. {
  208117. owner->handleFileDragMove (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  208118. *pdwEffect = DROPEFFECT_COPY;
  208119. return S_OK;
  208120. }
  208121. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  208122. {
  208123. updateFileList (pDataObject);
  208124. owner->handleFileDragDrop (files, owner->globalPositionToRelative (Point<int> (mousePos.x, mousePos.y)));
  208125. *pdwEffect = DROPEFFECT_COPY;
  208126. return S_OK;
  208127. }
  208128. private:
  208129. Win32ComponentPeer* const owner;
  208130. StringArray files;
  208131. void updateFileList (IDataObject* const pDataObject)
  208132. {
  208133. files.clear();
  208134. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208135. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208136. if (pDataObject->GetData (&format, &medium) == S_OK)
  208137. {
  208138. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  208139. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  208140. unsigned int i = 0;
  208141. if (pDropFiles->fWide)
  208142. {
  208143. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  208144. for (;;)
  208145. {
  208146. unsigned int len = 0;
  208147. while (i + len < totalLen && fname [i + len] != 0)
  208148. ++len;
  208149. if (len == 0)
  208150. break;
  208151. files.add (String (fname + i, len));
  208152. i += len + 1;
  208153. }
  208154. }
  208155. else
  208156. {
  208157. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  208158. for (;;)
  208159. {
  208160. unsigned int len = 0;
  208161. while (i + len < totalLen && fname [i + len] != 0)
  208162. ++len;
  208163. if (len == 0)
  208164. break;
  208165. files.add (String (fname + i, len));
  208166. i += len + 1;
  208167. }
  208168. }
  208169. GlobalUnlock (medium.hGlobal);
  208170. }
  208171. }
  208172. JuceDropTarget (const JuceDropTarget&);
  208173. JuceDropTarget& operator= (const JuceDropTarget&);
  208174. };
  208175. void doSettingChange()
  208176. {
  208177. Desktop::getInstance().refreshMonitorSizes();
  208178. if (fullScreen && ! isMinimised())
  208179. {
  208180. const Rectangle<int> r (component->getParentMonitorArea());
  208181. SetWindowPos (hwnd, 0,
  208182. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  208183. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  208184. }
  208185. }
  208186. public:
  208187. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208188. {
  208189. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  208190. if (peer != 0)
  208191. return peer->peerWindowProc (h, message, wParam, lParam);
  208192. return DefWindowProcW (h, message, wParam, lParam);
  208193. }
  208194. private:
  208195. static void* callFunctionIfNotLocked (MessageCallbackFunction* callback, void* userData)
  208196. {
  208197. if (MessageManager::getInstance()->currentThreadHasLockedMessageManager())
  208198. return callback (userData);
  208199. else
  208200. return MessageManager::getInstance()->callFunctionOnMessageThread (callback, userData);
  208201. }
  208202. static const Point<int> getPointFromLParam (LPARAM lParam) throw()
  208203. {
  208204. return Point<int> (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  208205. }
  208206. const Point<int> getCurrentMousePos() throw()
  208207. {
  208208. RECT wr;
  208209. GetWindowRect (hwnd, &wr);
  208210. const DWORD mp = GetMessagePos();
  208211. return Point<int> (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  208212. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop());
  208213. }
  208214. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  208215. {
  208216. if (isValidPeer (this))
  208217. {
  208218. switch (message)
  208219. {
  208220. case WM_NCHITTEST:
  208221. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  208222. return HTTRANSPARENT;
  208223. if (hasTitleBar())
  208224. break;
  208225. return HTCLIENT;
  208226. case WM_PAINT:
  208227. handlePaintMessage();
  208228. return 0;
  208229. case WM_NCPAINT:
  208230. if (wParam != 1)
  208231. handlePaintMessage();
  208232. if (hasTitleBar())
  208233. break;
  208234. return 0;
  208235. case WM_ERASEBKGND:
  208236. case WM_NCCALCSIZE:
  208237. if (hasTitleBar())
  208238. break;
  208239. return 1;
  208240. case WM_MOUSEMOVE:
  208241. doMouseMove (getPointFromLParam (lParam));
  208242. return 0;
  208243. case WM_MOUSELEAVE:
  208244. doMouseExit();
  208245. return 0;
  208246. case WM_LBUTTONDOWN:
  208247. case WM_MBUTTONDOWN:
  208248. case WM_RBUTTONDOWN:
  208249. doMouseDown (getPointFromLParam (lParam), wParam);
  208250. return 0;
  208251. case WM_LBUTTONUP:
  208252. case WM_MBUTTONUP:
  208253. case WM_RBUTTONUP:
  208254. doMouseUp (getPointFromLParam (lParam), wParam);
  208255. return 0;
  208256. case WM_CAPTURECHANGED:
  208257. doCaptureChanged();
  208258. return 0;
  208259. case WM_NCMOUSEMOVE:
  208260. if (hasTitleBar())
  208261. break;
  208262. return 0;
  208263. case 0x020A: /* WM_MOUSEWHEEL */
  208264. doMouseWheel (getCurrentMousePos(), wParam, true);
  208265. return 0;
  208266. case 0x020E: /* WM_MOUSEHWHEEL */
  208267. doMouseWheel (getCurrentMousePos(), wParam, false);
  208268. return 0;
  208269. case WM_SIZING:
  208270. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208271. {
  208272. RECT* const r = (RECT*) lParam;
  208273. Rectangle<int> pos (r->left, r->top, r->right - r->left, r->bottom - r->top);
  208274. constrainer->checkBounds (pos, windowBorder.addedTo (component->getBounds()),
  208275. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208276. wParam == WMSZ_TOP || wParam == WMSZ_TOPLEFT || wParam == WMSZ_TOPRIGHT,
  208277. wParam == WMSZ_LEFT || wParam == WMSZ_TOPLEFT || wParam == WMSZ_BOTTOMLEFT,
  208278. wParam == WMSZ_BOTTOM || wParam == WMSZ_BOTTOMLEFT || wParam == WMSZ_BOTTOMRIGHT,
  208279. wParam == WMSZ_RIGHT || wParam == WMSZ_TOPRIGHT || wParam == WMSZ_BOTTOMRIGHT);
  208280. r->left = pos.getX();
  208281. r->top = pos.getY();
  208282. r->right = pos.getRight();
  208283. r->bottom = pos.getBottom();
  208284. }
  208285. return TRUE;
  208286. case WM_WINDOWPOSCHANGING:
  208287. if (constrainer != 0 && (styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  208288. {
  208289. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  208290. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE)
  208291. && ! Component::isMouseButtonDownAnywhere())
  208292. {
  208293. Rectangle<int> pos (wp->x, wp->y, wp->cx, wp->cy);
  208294. const Rectangle<int> current (windowBorder.addedTo (component->getBounds()));
  208295. constrainer->checkBounds (pos, current,
  208296. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  208297. pos.getY() != current.getY() && pos.getBottom() == current.getBottom(),
  208298. pos.getX() != current.getX() && pos.getRight() == current.getRight(),
  208299. pos.getY() == current.getY() && pos.getBottom() != current.getBottom(),
  208300. pos.getX() == current.getX() && pos.getRight() != current.getRight());
  208301. wp->x = pos.getX();
  208302. wp->y = pos.getY();
  208303. wp->cx = pos.getWidth();
  208304. wp->cy = pos.getHeight();
  208305. }
  208306. }
  208307. return 0;
  208308. case WM_WINDOWPOSCHANGED:
  208309. {
  208310. const Point<int> pos (getCurrentMousePos());
  208311. if (contains (pos, false))
  208312. doMouseEvent (pos);
  208313. }
  208314. handleMovedOrResized();
  208315. if (dontRepaint)
  208316. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  208317. return 0;
  208318. case WM_KEYDOWN:
  208319. case WM_SYSKEYDOWN:
  208320. if (doKeyDown (wParam))
  208321. return 0;
  208322. break;
  208323. case WM_KEYUP:
  208324. case WM_SYSKEYUP:
  208325. if (doKeyUp (wParam))
  208326. return 0;
  208327. break;
  208328. case WM_CHAR:
  208329. if (doKeyChar ((int) wParam, lParam))
  208330. return 0;
  208331. break;
  208332. case WM_APPCOMMAND:
  208333. if (doAppCommand (lParam))
  208334. return TRUE;
  208335. break;
  208336. case WM_SETFOCUS:
  208337. updateKeyModifiers();
  208338. handleFocusGain();
  208339. break;
  208340. case WM_KILLFOCUS:
  208341. if (hasCreatedCaret)
  208342. {
  208343. hasCreatedCaret = false;
  208344. DestroyCaret();
  208345. }
  208346. handleFocusLoss();
  208347. break;
  208348. case WM_ACTIVATEAPP:
  208349. // Windows does weird things to process priority when you swap apps,
  208350. // so this forces an update when the app is brought to the front
  208351. if (wParam != FALSE)
  208352. juce_repeatLastProcessPriority();
  208353. else
  208354. Desktop::getInstance().setKioskModeComponent (0); // turn kiosk mode off if we lose focus
  208355. juce_CheckCurrentlyFocusedTopLevelWindow();
  208356. modifiersAtLastCallback = -1;
  208357. return 0;
  208358. case WM_ACTIVATE:
  208359. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  208360. {
  208361. modifiersAtLastCallback = -1;
  208362. updateKeyModifiers();
  208363. if (isMinimised())
  208364. {
  208365. component->repaint();
  208366. handleMovedOrResized();
  208367. if (! ComponentPeer::isValidPeer (this))
  208368. return 0;
  208369. }
  208370. if (LOWORD (wParam) == WA_CLICKACTIVE
  208371. && component->isCurrentlyBlockedByAnotherModalComponent())
  208372. {
  208373. const Point<int> mousePos (component->getMouseXYRelative());
  208374. Component* const underMouse = component->getComponentAt (mousePos.getX(), mousePos.getY());
  208375. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  208376. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  208377. return 0;
  208378. }
  208379. handleBroughtToFront();
  208380. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208381. Component::getCurrentlyModalComponent()->toFront (true);
  208382. return 0;
  208383. }
  208384. break;
  208385. case WM_NCACTIVATE:
  208386. // while a temporary window is being shown, prevent Windows from deactivating the
  208387. // title bars of our main windows.
  208388. if (wParam == 0 && ! shouldDeactivateTitleBar)
  208389. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  208390. break;
  208391. case WM_MOUSEACTIVATE:
  208392. if (! component->getMouseClickGrabsKeyboardFocus())
  208393. return MA_NOACTIVATE;
  208394. break;
  208395. case WM_SHOWWINDOW:
  208396. if (wParam != 0)
  208397. handleBroughtToFront();
  208398. break;
  208399. case WM_CLOSE:
  208400. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  208401. handleUserClosingWindow();
  208402. return 0;
  208403. case WM_QUERYENDSESSION:
  208404. if (JUCEApplication::getInstance() != 0)
  208405. {
  208406. JUCEApplication::getInstance()->systemRequestedQuit();
  208407. return MessageManager::getInstance()->hasStopMessageBeenSent();
  208408. }
  208409. return TRUE;
  208410. case WM_TRAYNOTIFY:
  208411. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208412. {
  208413. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  208414. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208415. {
  208416. Component* const current = Component::getCurrentlyModalComponent();
  208417. if (current != 0)
  208418. current->inputAttemptWhenModal();
  208419. }
  208420. }
  208421. else
  208422. {
  208423. ModifierKeys eventMods (ModifierKeys::getCurrentModifiersRealtime());
  208424. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  208425. eventMods = eventMods.withFlags (ModifierKeys::leftButtonModifier);
  208426. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  208427. eventMods = eventMods.withFlags (ModifierKeys::rightButtonModifier);
  208428. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208429. eventMods = eventMods.withoutMouseButtons();
  208430. const MouseEvent e (Desktop::getInstance().getMainMouseSource(),
  208431. Point<int>(), eventMods, component, component, getMouseEventTime(),
  208432. Point<int>(), getMouseEventTime(), 1, false);
  208433. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  208434. {
  208435. SetFocus (hwnd);
  208436. SetForegroundWindow (hwnd);
  208437. component->mouseDown (e);
  208438. }
  208439. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  208440. {
  208441. component->mouseUp (e);
  208442. }
  208443. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  208444. {
  208445. component->mouseDoubleClick (e);
  208446. }
  208447. else if (lParam == WM_MOUSEMOVE)
  208448. {
  208449. component->mouseMove (e);
  208450. }
  208451. }
  208452. break;
  208453. case WM_SYNCPAINT:
  208454. return 0;
  208455. case WM_PALETTECHANGED:
  208456. InvalidateRect (h, 0, 0);
  208457. break;
  208458. case WM_DISPLAYCHANGE:
  208459. InvalidateRect (h, 0, 0);
  208460. createPaletteIfNeeded = true;
  208461. // intentional fall-through...
  208462. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  208463. doSettingChange();
  208464. break;
  208465. case WM_INITMENU:
  208466. if (! hasTitleBar())
  208467. {
  208468. if (isFullScreen())
  208469. {
  208470. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  208471. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  208472. }
  208473. else if (! isMinimised())
  208474. {
  208475. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  208476. }
  208477. }
  208478. break;
  208479. case WM_SYSCOMMAND:
  208480. switch (wParam & 0xfff0)
  208481. {
  208482. case SC_CLOSE:
  208483. if (sendInputAttemptWhenModalMessage())
  208484. return 0;
  208485. if (hasTitleBar())
  208486. {
  208487. PostMessage (h, WM_CLOSE, 0, 0);
  208488. return 0;
  208489. }
  208490. break;
  208491. case SC_KEYMENU:
  208492. // (NB mustn't call sendInputAttemptWhenModalMessage() here because of very
  208493. // obscure situations that can arise if a modal loop is started from an alt-key
  208494. // keypress).
  208495. if (hasTitleBar() && h == GetCapture())
  208496. ReleaseCapture();
  208497. break;
  208498. case SC_MAXIMIZE:
  208499. if (sendInputAttemptWhenModalMessage())
  208500. return 0;
  208501. setFullScreen (true);
  208502. return 0;
  208503. case SC_MINIMIZE:
  208504. if (sendInputAttemptWhenModalMessage())
  208505. return 0;
  208506. if (! hasTitleBar())
  208507. {
  208508. setMinimised (true);
  208509. return 0;
  208510. }
  208511. break;
  208512. case SC_RESTORE:
  208513. if (sendInputAttemptWhenModalMessage())
  208514. return 0;
  208515. if (hasTitleBar())
  208516. {
  208517. if (isFullScreen())
  208518. {
  208519. setFullScreen (false);
  208520. return 0;
  208521. }
  208522. }
  208523. else
  208524. {
  208525. if (isMinimised())
  208526. setMinimised (false);
  208527. else if (isFullScreen())
  208528. setFullScreen (false);
  208529. return 0;
  208530. }
  208531. break;
  208532. }
  208533. break;
  208534. case WM_NCLBUTTONDOWN:
  208535. case WM_NCRBUTTONDOWN:
  208536. case WM_NCMBUTTONDOWN:
  208537. sendInputAttemptWhenModalMessage();
  208538. break;
  208539. //case WM_IME_STARTCOMPOSITION;
  208540. // return 0;
  208541. case WM_GETDLGCODE:
  208542. return DLGC_WANTALLKEYS;
  208543. default:
  208544. break;
  208545. }
  208546. }
  208547. return DefWindowProcW (h, message, wParam, lParam);
  208548. }
  208549. bool sendInputAttemptWhenModalMessage()
  208550. {
  208551. if (component->isCurrentlyBlockedByAnotherModalComponent())
  208552. {
  208553. Component* const current = Component::getCurrentlyModalComponent();
  208554. if (current != 0)
  208555. current->inputAttemptWhenModal();
  208556. return true;
  208557. }
  208558. return false;
  208559. }
  208560. Win32ComponentPeer (const Win32ComponentPeer&);
  208561. Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  208562. };
  208563. ModifierKeys Win32ComponentPeer::currentModifiers;
  208564. ModifierKeys Win32ComponentPeer::modifiersAtLastCallback;
  208565. ComponentPeer* Component::createNewPeer (int styleFlags, void* nativeWindowToAttachTo)
  208566. {
  208567. return new Win32ComponentPeer (this, styleFlags, (HWND) nativeWindowToAttachTo);
  208568. }
  208569. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  208570. void ModifierKeys::updateCurrentModifiers() throw()
  208571. {
  208572. currentModifiers = Win32ComponentPeer::currentModifiers;
  208573. }
  208574. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  208575. {
  208576. Win32ComponentPeer::updateKeyModifiers();
  208577. int mouseMods = 0;
  208578. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  208579. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  208580. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  208581. Win32ComponentPeer::currentModifiers
  208582. = Win32ComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  208583. return Win32ComponentPeer::currentModifiers;
  208584. }
  208585. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  208586. {
  208587. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208588. if (wp != 0)
  208589. wp->setTaskBarIcon (newImage);
  208590. }
  208591. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  208592. {
  208593. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  208594. if (wp != 0)
  208595. wp->setTaskBarIconToolTip (tooltip);
  208596. }
  208597. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  208598. {
  208599. DWORD val = GetWindowLong (h, styleType);
  208600. if (bitIsSet)
  208601. val |= feature;
  208602. else
  208603. val &= ~feature;
  208604. SetWindowLongPtr (h, styleType, val);
  208605. SetWindowPos (h, 0, 0, 0, 0, 0,
  208606. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  208607. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  208608. }
  208609. bool Process::isForegroundProcess()
  208610. {
  208611. HWND fg = GetForegroundWindow();
  208612. if (fg == 0)
  208613. return true;
  208614. // when running as a plugin in IE8, the browser UI runs in a different process to the plugin, so
  208615. // process ID isn't a reliable way to check if the foreground window belongs to us - instead, we
  208616. // have to see if any of our windows are children of the foreground window
  208617. fg = GetAncestor (fg, GA_ROOT);
  208618. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  208619. {
  208620. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (ComponentPeer::getPeer (i));
  208621. if (wp != 0 && wp->isInside (fg))
  208622. return true;
  208623. }
  208624. return false;
  208625. }
  208626. bool AlertWindow::showNativeDialogBox (const String& title,
  208627. const String& bodyText,
  208628. bool isOkCancel)
  208629. {
  208630. return MessageBox (0, bodyText, title,
  208631. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  208632. : MB_OK)) == IDOK;
  208633. }
  208634. void Desktop::createMouseInputSources()
  208635. {
  208636. mouseSources.add (new MouseInputSource (0, true));
  208637. }
  208638. const Point<int> Desktop::getMousePosition()
  208639. {
  208640. POINT mousePos;
  208641. GetCursorPos (&mousePos);
  208642. return Point<int> (mousePos.x, mousePos.y);
  208643. }
  208644. void Desktop::setMousePosition (const Point<int>& newPosition)
  208645. {
  208646. SetCursorPos (newPosition.getX(), newPosition.getY());
  208647. }
  208648. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  208649. {
  208650. return createSoftwareImage (format, width, height, clearImage);
  208651. }
  208652. class ScreenSaverDefeater : public Timer,
  208653. public DeletedAtShutdown
  208654. {
  208655. public:
  208656. ScreenSaverDefeater()
  208657. {
  208658. startTimer (10000);
  208659. timerCallback();
  208660. }
  208661. ~ScreenSaverDefeater() {}
  208662. void timerCallback()
  208663. {
  208664. if (Process::isForegroundProcess())
  208665. {
  208666. // simulate a shift key getting pressed..
  208667. INPUT input[2];
  208668. input[0].type = INPUT_KEYBOARD;
  208669. input[0].ki.wVk = VK_SHIFT;
  208670. input[0].ki.dwFlags = 0;
  208671. input[0].ki.dwExtraInfo = 0;
  208672. input[1].type = INPUT_KEYBOARD;
  208673. input[1].ki.wVk = VK_SHIFT;
  208674. input[1].ki.dwFlags = KEYEVENTF_KEYUP;
  208675. input[1].ki.dwExtraInfo = 0;
  208676. SendInput (2, input, sizeof (INPUT));
  208677. }
  208678. }
  208679. };
  208680. static ScreenSaverDefeater* screenSaverDefeater = 0;
  208681. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  208682. {
  208683. if (isEnabled)
  208684. deleteAndZero (screenSaverDefeater);
  208685. else if (screenSaverDefeater == 0)
  208686. screenSaverDefeater = new ScreenSaverDefeater();
  208687. }
  208688. bool Desktop::isScreenSaverEnabled()
  208689. {
  208690. return screenSaverDefeater == 0;
  208691. }
  208692. /* (The code below is the "correct" way to disable the screen saver, but it
  208693. completely fails on winXP when the saver is password-protected...)
  208694. static bool juce_screenSaverEnabled = true;
  208695. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  208696. {
  208697. juce_screenSaverEnabled = isEnabled;
  208698. SetThreadExecutionState (isEnabled ? ES_CONTINUOUS
  208699. : (ES_DISPLAY_REQUIRED | ES_CONTINUOUS));
  208700. }
  208701. bool Desktop::isScreenSaverEnabled() throw()
  208702. {
  208703. return juce_screenSaverEnabled;
  208704. }
  208705. */
  208706. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool /*allowMenusAndBars*/)
  208707. {
  208708. if (enableOrDisable)
  208709. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  208710. }
  208711. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  208712. {
  208713. Array <Rectangle<int> >* const monitorCoords = (Array <Rectangle<int> >*) userInfo;
  208714. monitorCoords->add (Rectangle<int> (r->left, r->top, r->right - r->left, r->bottom - r->top));
  208715. return TRUE;
  208716. }
  208717. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  208718. {
  208719. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208720. // make sure the first in the list is the main monitor
  208721. for (int i = 1; i < monitorCoords.size(); ++i)
  208722. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208723. monitorCoords.swap (i, 0);
  208724. if (monitorCoords.size() == 0)
  208725. {
  208726. RECT r;
  208727. GetWindowRect (GetDesktopWindow(), &r);
  208728. monitorCoords.add (Rectangle<int> (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208729. }
  208730. if (clipToWorkArea)
  208731. {
  208732. // clip the main monitor to the active non-taskbar area
  208733. RECT r;
  208734. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208735. Rectangle<int>& screen = monitorCoords.getReference (0);
  208736. screen.setPosition (jmax (screen.getX(), (int) r.left),
  208737. jmax (screen.getY(), (int) r.top));
  208738. screen.setSize (jmin (screen.getRight(), (int) r.right) - screen.getX(),
  208739. jmin (screen.getBottom(), (int) r.bottom) - screen.getY());
  208740. }
  208741. }
  208742. const Image juce_createIconForFile (const File& file)
  208743. {
  208744. Image image;
  208745. WCHAR filename [1024];
  208746. file.getFullPathName().copyToUnicode (filename, 1023);
  208747. WORD iconNum = 0;
  208748. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208749. filename, &iconNum);
  208750. if (icon != 0)
  208751. {
  208752. image = IconConverters::createImageFromHICON (icon);
  208753. DestroyIcon (icon);
  208754. }
  208755. return image;
  208756. }
  208757. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  208758. {
  208759. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208760. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208761. Image im (image);
  208762. if (im.getWidth() > maxW || im.getHeight() > maxH)
  208763. {
  208764. im = im.rescaled (maxW, maxH);
  208765. hotspotX = (hotspotX * maxW) / image.getWidth();
  208766. hotspotY = (hotspotY * maxH) / image.getHeight();
  208767. }
  208768. return IconConverters::createHICONFromImage (im, FALSE, hotspotX, hotspotY);
  208769. }
  208770. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard)
  208771. {
  208772. if (cursorHandle != 0 && ! isStandard)
  208773. DestroyCursor ((HCURSOR) cursorHandle);
  208774. }
  208775. void* MouseCursor::createStandardMouseCursor (const MouseCursor::StandardCursorType type)
  208776. {
  208777. LPCTSTR cursorName = IDC_ARROW;
  208778. switch (type)
  208779. {
  208780. case NormalCursor: break;
  208781. case NoCursor: return 0;
  208782. case WaitCursor: cursorName = IDC_WAIT; break;
  208783. case IBeamCursor: cursorName = IDC_IBEAM; break;
  208784. case PointingHandCursor: cursorName = MAKEINTRESOURCE(32649); break;
  208785. case CrosshairCursor: cursorName = IDC_CROSS; break;
  208786. case CopyingCursor: break; // can't seem to find one of these in the win32 list..
  208787. case LeftRightResizeCursor:
  208788. case LeftEdgeResizeCursor:
  208789. case RightEdgeResizeCursor: cursorName = IDC_SIZEWE; break;
  208790. case UpDownResizeCursor:
  208791. case TopEdgeResizeCursor:
  208792. case BottomEdgeResizeCursor: cursorName = IDC_SIZENS; break;
  208793. case TopLeftCornerResizeCursor:
  208794. case BottomRightCornerResizeCursor: cursorName = IDC_SIZENWSE; break;
  208795. case TopRightCornerResizeCursor:
  208796. case BottomLeftCornerResizeCursor: cursorName = IDC_SIZENESW; break;
  208797. case UpDownLeftRightResizeCursor: cursorName = IDC_SIZEALL; break;
  208798. case DraggingHandCursor:
  208799. {
  208800. static void* dragHandCursor = 0;
  208801. if (dragHandCursor == 0)
  208802. {
  208803. static const unsigned char dragHandData[] =
  208804. { 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,
  208805. 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,
  208806. 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 };
  208807. dragHandCursor = createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, sizeof (dragHandData)), 8, 7);
  208808. }
  208809. return dragHandCursor;
  208810. }
  208811. default:
  208812. jassertfalse; break;
  208813. }
  208814. HCURSOR cursorH = LoadCursor (0, cursorName);
  208815. if (cursorH == 0)
  208816. cursorH = LoadCursor (0, IDC_ARROW);
  208817. return cursorH;
  208818. }
  208819. void MouseCursor::showInWindow (ComponentPeer*) const
  208820. {
  208821. SetCursor ((HCURSOR) getHandle());
  208822. }
  208823. void MouseCursor::showInAllWindows() const
  208824. {
  208825. showInWindow (0);
  208826. }
  208827. class JuceDropSource : public ComBaseClassHelper <IDropSource>
  208828. {
  208829. public:
  208830. JuceDropSource() {}
  208831. ~JuceDropSource() {}
  208832. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208833. {
  208834. if (escapePressed)
  208835. return DRAGDROP_S_CANCEL;
  208836. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208837. return DRAGDROP_S_DROP;
  208838. return S_OK;
  208839. }
  208840. HRESULT __stdcall GiveFeedback (DWORD)
  208841. {
  208842. return DRAGDROP_S_USEDEFAULTCURSORS;
  208843. }
  208844. };
  208845. class JuceEnumFormatEtc : public ComBaseClassHelper <IEnumFORMATETC>
  208846. {
  208847. public:
  208848. JuceEnumFormatEtc (const FORMATETC* const format_)
  208849. : format (format_),
  208850. index (0)
  208851. {
  208852. }
  208853. ~JuceEnumFormatEtc() {}
  208854. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208855. {
  208856. if (result == 0)
  208857. return E_POINTER;
  208858. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208859. newOne->index = index;
  208860. *result = newOne;
  208861. return S_OK;
  208862. }
  208863. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208864. {
  208865. if (pceltFetched != 0)
  208866. *pceltFetched = 0;
  208867. else if (celt != 1)
  208868. return S_FALSE;
  208869. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208870. {
  208871. copyFormatEtc (lpFormatEtc [0], *format);
  208872. ++index;
  208873. if (pceltFetched != 0)
  208874. *pceltFetched = 1;
  208875. return S_OK;
  208876. }
  208877. return S_FALSE;
  208878. }
  208879. HRESULT __stdcall Skip (ULONG celt)
  208880. {
  208881. if (index + (int) celt >= 1)
  208882. return S_FALSE;
  208883. index += celt;
  208884. return S_OK;
  208885. }
  208886. HRESULT __stdcall Reset()
  208887. {
  208888. index = 0;
  208889. return S_OK;
  208890. }
  208891. private:
  208892. const FORMATETC* const format;
  208893. int index;
  208894. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208895. {
  208896. dest = source;
  208897. if (source.ptd != 0)
  208898. {
  208899. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208900. *(dest.ptd) = *(source.ptd);
  208901. }
  208902. }
  208903. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208904. JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208905. };
  208906. class JuceDataObject : public ComBaseClassHelper <IDataObject>
  208907. {
  208908. public:
  208909. JuceDataObject (JuceDropSource* const dropSource_,
  208910. const FORMATETC* const format_,
  208911. const STGMEDIUM* const medium_)
  208912. : dropSource (dropSource_),
  208913. format (format_),
  208914. medium (medium_)
  208915. {
  208916. }
  208917. ~JuceDataObject()
  208918. {
  208919. jassert (refCount == 0);
  208920. }
  208921. HRESULT __stdcall GetData (FORMATETC* pFormatEtc, STGMEDIUM* pMedium)
  208922. {
  208923. if ((pFormatEtc->tymed & format->tymed) != 0
  208924. && pFormatEtc->cfFormat == format->cfFormat
  208925. && pFormatEtc->dwAspect == format->dwAspect)
  208926. {
  208927. pMedium->tymed = format->tymed;
  208928. pMedium->pUnkForRelease = 0;
  208929. if (format->tymed == TYMED_HGLOBAL)
  208930. {
  208931. const SIZE_T len = GlobalSize (medium->hGlobal);
  208932. void* const src = GlobalLock (medium->hGlobal);
  208933. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208934. memcpy (dst, src, len);
  208935. GlobalUnlock (medium->hGlobal);
  208936. pMedium->hGlobal = dst;
  208937. return S_OK;
  208938. }
  208939. }
  208940. return DV_E_FORMATETC;
  208941. }
  208942. HRESULT __stdcall QueryGetData (FORMATETC* f)
  208943. {
  208944. if (f == 0)
  208945. return E_INVALIDARG;
  208946. if (f->tymed == format->tymed
  208947. && f->cfFormat == format->cfFormat
  208948. && f->dwAspect == format->dwAspect)
  208949. return S_OK;
  208950. return DV_E_FORMATETC;
  208951. }
  208952. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC*, FORMATETC* pFormatEtcOut)
  208953. {
  208954. pFormatEtcOut->ptd = 0;
  208955. return E_NOTIMPL;
  208956. }
  208957. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC** result)
  208958. {
  208959. if (result == 0)
  208960. return E_POINTER;
  208961. if (direction == DATADIR_GET)
  208962. {
  208963. *result = new JuceEnumFormatEtc (format);
  208964. return S_OK;
  208965. }
  208966. *result = 0;
  208967. return E_NOTIMPL;
  208968. }
  208969. HRESULT __stdcall GetDataHere (FORMATETC*, STGMEDIUM*) { return DATA_E_FORMATETC; }
  208970. HRESULT __stdcall SetData (FORMATETC*, STGMEDIUM*, BOOL) { return E_NOTIMPL; }
  208971. HRESULT __stdcall DAdvise (FORMATETC*, DWORD, IAdviseSink*, DWORD*) { return OLE_E_ADVISENOTSUPPORTED; }
  208972. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208973. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA**) { return OLE_E_ADVISENOTSUPPORTED; }
  208974. private:
  208975. JuceDropSource* const dropSource;
  208976. const FORMATETC* const format;
  208977. const STGMEDIUM* const medium;
  208978. JuceDataObject (const JuceDataObject&);
  208979. JuceDataObject& operator= (const JuceDataObject&);
  208980. };
  208981. static HDROP createHDrop (const StringArray& fileNames)
  208982. {
  208983. int totalChars = 0;
  208984. for (int i = fileNames.size(); --i >= 0;)
  208985. totalChars += fileNames[i].length() + 1;
  208986. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208987. sizeof (DROPFILES) + sizeof (WCHAR) * (totalChars + 2));
  208988. if (hDrop != 0)
  208989. {
  208990. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208991. pDropFiles->pFiles = sizeof (DROPFILES);
  208992. pDropFiles->fWide = true;
  208993. WCHAR* fname = reinterpret_cast<WCHAR*> (addBytesToPointer (pDropFiles, sizeof (DROPFILES)));
  208994. for (int i = 0; i < fileNames.size(); ++i)
  208995. {
  208996. fileNames[i].copyToUnicode (fname, 2048);
  208997. fname += fileNames[i].length() + 1;
  208998. }
  208999. *fname = 0;
  209000. GlobalUnlock (hDrop);
  209001. }
  209002. return hDrop;
  209003. }
  209004. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo)
  209005. {
  209006. JuceDropSource* const source = new JuceDropSource();
  209007. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  209008. DWORD effect;
  209009. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  209010. data->Release();
  209011. source->Release();
  209012. return res == DRAGDROP_S_DROP;
  209013. }
  209014. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  209015. {
  209016. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209017. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209018. medium.hGlobal = createHDrop (files);
  209019. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  209020. : DROPEFFECT_COPY);
  209021. }
  209022. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  209023. {
  209024. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  209025. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  209026. const int numChars = text.length();
  209027. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  209028. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (medium.hGlobal));
  209029. text.copyToUnicode (data, numChars + 1);
  209030. format.cfFormat = CF_UNICODETEXT;
  209031. GlobalUnlock (medium.hGlobal);
  209032. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  209033. }
  209034. #endif
  209035. /*** End of inlined file: juce_win32_Windowing.cpp ***/
  209036. /*** Start of inlined file: juce_win32_FileChooser.cpp ***/
  209037. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209038. // compiled on its own).
  209039. #if JUCE_INCLUDED_FILE
  209040. namespace FileChooserHelpers
  209041. {
  209042. static bool areThereAnyAlwaysOnTopWindows()
  209043. {
  209044. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  209045. {
  209046. Component* c = Desktop::getInstance().getComponent (i);
  209047. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  209048. return true;
  209049. }
  209050. return false;
  209051. }
  209052. struct FileChooserCallbackInfo
  209053. {
  209054. String initialPath;
  209055. String returnedString; // need this to get non-existent pathnames from the directory chooser
  209056. ScopedPointer<Component> customComponent;
  209057. };
  209058. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM lpData)
  209059. {
  209060. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) lpData;
  209061. if (msg == BFFM_INITIALIZED)
  209062. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) static_cast <const WCHAR*> (info->initialPath));
  209063. else if (msg == BFFM_VALIDATEFAILEDW)
  209064. info->returnedString = (LPCWSTR) lParam;
  209065. else if (msg == BFFM_VALIDATEFAILEDA)
  209066. info->returnedString = (const char*) lParam;
  209067. return 0;
  209068. }
  209069. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  209070. {
  209071. if (uiMsg == WM_INITDIALOG)
  209072. {
  209073. Component* customComp = ((FileChooserCallbackInfo*) (((OPENFILENAMEW*) lParam)->lCustData))->customComponent;
  209074. HWND dialogH = GetParent (hdlg);
  209075. jassert (dialogH != 0);
  209076. if (dialogH == 0)
  209077. dialogH = hdlg;
  209078. RECT r, cr;
  209079. GetWindowRect (dialogH, &r);
  209080. GetClientRect (dialogH, &cr);
  209081. SetWindowPos (dialogH, 0,
  209082. r.left, r.top,
  209083. customComp->getWidth() + jmax (150, (int) (r.right - r.left)),
  209084. jmax (150, (int) (r.bottom - r.top)),
  209085. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  209086. customComp->setBounds (cr.right, cr.top, customComp->getWidth(), cr.bottom - cr.top);
  209087. customComp->addToDesktop (0, dialogH);
  209088. }
  209089. else if (uiMsg == WM_NOTIFY)
  209090. {
  209091. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  209092. if (ofn->hdr.code == CDN_SELCHANGE)
  209093. {
  209094. FileChooserCallbackInfo* info = (FileChooserCallbackInfo*) ofn->lpOFN->lCustData;
  209095. FilePreviewComponent* comp = static_cast<FilePreviewComponent*> (info->customComponent->getChildComponent(0));
  209096. if (comp != 0)
  209097. {
  209098. WCHAR path [MAX_PATH * 2];
  209099. zerostruct (path);
  209100. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  209101. comp->selectedFileChanged (File (path));
  209102. }
  209103. }
  209104. }
  209105. return 0;
  209106. }
  209107. class CustomComponentHolder : public Component
  209108. {
  209109. public:
  209110. CustomComponentHolder (Component* customComp)
  209111. {
  209112. setVisible (true);
  209113. setOpaque (true);
  209114. addAndMakeVisible (customComp);
  209115. setSize (jlimit (20, 800, customComp->getWidth()), customComp->getHeight());
  209116. }
  209117. void paint (Graphics& g)
  209118. {
  209119. g.fillAll (Colours::lightgrey);
  209120. }
  209121. void resized()
  209122. {
  209123. if (getNumChildComponents() > 0)
  209124. getChildComponent(0)->setBounds (getLocalBounds());
  209125. }
  209126. juce_UseDebuggingNewOperator
  209127. private:
  209128. CustomComponentHolder (const CustomComponentHolder&);
  209129. CustomComponentHolder& operator= (const CustomComponentHolder&);
  209130. };
  209131. }
  209132. void FileChooser::showPlatformDialog (Array<File>& results, const String& title, const File& currentFileOrDirectory,
  209133. const String& filter, bool selectsDirectory, bool /*selectsFiles*/,
  209134. bool isSaveDialogue, bool warnAboutOverwritingExistingFiles,
  209135. bool selectMultipleFiles, FilePreviewComponent* extraInfoComponent)
  209136. {
  209137. using namespace FileChooserHelpers;
  209138. HeapBlock<WCHAR> files;
  209139. const int charsAvailableForResult = 32768;
  209140. files.calloc (charsAvailableForResult + 1);
  209141. int filenameOffset = 0;
  209142. FileChooserCallbackInfo info;
  209143. // use a modal window as the parent for this dialog box
  209144. // to block input from other app windows
  209145. Component parentWindow (String::empty);
  209146. const Rectangle<int> mainMon (Desktop::getInstance().getMainMonitorArea());
  209147. parentWindow.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209148. mainMon.getY() + mainMon.getHeight() / 4,
  209149. 0, 0);
  209150. parentWindow.setOpaque (true);
  209151. parentWindow.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209152. parentWindow.addToDesktop (0);
  209153. if (extraInfoComponent == 0)
  209154. parentWindow.enterModalState();
  209155. if (currentFileOrDirectory.isDirectory())
  209156. {
  209157. info.initialPath = currentFileOrDirectory.getFullPathName();
  209158. }
  209159. else
  209160. {
  209161. currentFileOrDirectory.getFileName().copyToUnicode (files, charsAvailableForResult);
  209162. info.initialPath = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209163. }
  209164. if (selectsDirectory)
  209165. {
  209166. BROWSEINFO bi;
  209167. zerostruct (bi);
  209168. bi.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209169. bi.pszDisplayName = files;
  209170. bi.lpszTitle = title;
  209171. bi.lParam = (LPARAM) &info;
  209172. bi.lpfn = browseCallbackProc;
  209173. #ifdef BIF_USENEWUI
  209174. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209175. #else
  209176. bi.ulFlags = 0x50;
  209177. #endif
  209178. LPITEMIDLIST list = SHBrowseForFolder (&bi);
  209179. if (! SHGetPathFromIDListW (list, files))
  209180. {
  209181. files[0] = 0;
  209182. info.returnedString = String::empty;
  209183. }
  209184. LPMALLOC al;
  209185. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209186. al->Free (list);
  209187. if (info.returnedString.isNotEmpty())
  209188. {
  209189. results.add (File (String (files)).getSiblingFile (info.returnedString));
  209190. return;
  209191. }
  209192. }
  209193. else
  209194. {
  209195. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209196. if (warnAboutOverwritingExistingFiles)
  209197. flags |= OFN_OVERWRITEPROMPT;
  209198. if (selectMultipleFiles)
  209199. flags |= OFN_ALLOWMULTISELECT;
  209200. if (extraInfoComponent != 0)
  209201. {
  209202. flags |= OFN_ENABLEHOOK;
  209203. info.customComponent = new CustomComponentHolder (extraInfoComponent);
  209204. info.customComponent->enterModalState();
  209205. }
  209206. WCHAR filters [1024];
  209207. zerostruct (filters);
  209208. filter.copyToUnicode (filters, 1024);
  209209. filter.copyToUnicode (filters + filter.length() + 1, 1022 - filter.length());
  209210. OPENFILENAMEW of;
  209211. zerostruct (of);
  209212. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209213. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209214. #else
  209215. of.lStructSize = sizeof (of);
  209216. #endif
  209217. of.hwndOwner = (HWND) parentWindow.getWindowHandle();
  209218. of.lpstrFilter = filters;
  209219. of.nFilterIndex = 1;
  209220. of.lpstrFile = files;
  209221. of.nMaxFile = charsAvailableForResult;
  209222. of.lpstrInitialDir = info.initialPath;
  209223. of.lpstrTitle = title;
  209224. of.Flags = flags;
  209225. of.lCustData = (LPARAM) &info;
  209226. if (extraInfoComponent != 0)
  209227. of.lpfnHook = &openCallback;
  209228. if (! (isSaveDialogue ? GetSaveFileName (&of)
  209229. : GetOpenFileName (&of)))
  209230. return;
  209231. filenameOffset = of.nFileOffset;
  209232. }
  209233. if (selectMultipleFiles && filenameOffset > 0 && files [filenameOffset - 1] == 0)
  209234. {
  209235. const WCHAR* filename = files + filenameOffset;
  209236. while (*filename != 0)
  209237. {
  209238. results.add (File (String (files) + "\\" + String (filename)));
  209239. filename += CharacterFunctions::length (filename) + 1;
  209240. }
  209241. }
  209242. else if (files[0] != 0)
  209243. {
  209244. results.add (File (String (files)));
  209245. }
  209246. }
  209247. #endif
  209248. /*** End of inlined file: juce_win32_FileChooser.cpp ***/
  209249. /*** Start of inlined file: juce_win32_Misc.cpp ***/
  209250. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209251. // compiled on its own).
  209252. #if JUCE_INCLUDED_FILE
  209253. void SystemClipboard::copyTextToClipboard (const String& text)
  209254. {
  209255. if (OpenClipboard (0) != 0)
  209256. {
  209257. if (EmptyClipboard() != 0)
  209258. {
  209259. const int len = text.length();
  209260. if (len > 0)
  209261. {
  209262. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209263. (len + 1) * sizeof (wchar_t));
  209264. if (bufH != 0)
  209265. {
  209266. WCHAR* const data = static_cast <WCHAR*> (GlobalLock (bufH));
  209267. text.copyToUnicode (data, len);
  209268. GlobalUnlock (bufH);
  209269. SetClipboardData (CF_UNICODETEXT, bufH);
  209270. }
  209271. }
  209272. }
  209273. CloseClipboard();
  209274. }
  209275. }
  209276. const String SystemClipboard::getTextFromClipboard()
  209277. {
  209278. String result;
  209279. if (OpenClipboard (0) != 0)
  209280. {
  209281. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209282. if (bufH != 0)
  209283. {
  209284. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209285. if (data != 0)
  209286. {
  209287. result = String (data, (int) (GlobalSize (bufH) / sizeof (wchar_t)));
  209288. GlobalUnlock (bufH);
  209289. }
  209290. }
  209291. CloseClipboard();
  209292. }
  209293. return result;
  209294. }
  209295. #endif
  209296. /*** End of inlined file: juce_win32_Misc.cpp ***/
  209297. /*** Start of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209298. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209299. // compiled on its own).
  209300. #if JUCE_INCLUDED_FILE
  209301. namespace ActiveXHelpers
  209302. {
  209303. class JuceIStorage : public ComBaseClassHelper <IStorage>
  209304. {
  209305. public:
  209306. JuceIStorage() {}
  209307. ~JuceIStorage() {}
  209308. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209309. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209310. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209311. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209312. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209313. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209314. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209315. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209316. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209317. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209318. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209319. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209320. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209321. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209322. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209323. juce_UseDebuggingNewOperator
  209324. };
  209325. class JuceOleInPlaceFrame : public ComBaseClassHelper <IOleInPlaceFrame>
  209326. {
  209327. HWND window;
  209328. public:
  209329. JuceOleInPlaceFrame (HWND window_) : window (window_) {}
  209330. ~JuceOleInPlaceFrame() {}
  209331. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209332. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209333. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209334. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209335. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209336. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209337. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209338. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209339. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209340. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209341. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209342. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209343. juce_UseDebuggingNewOperator
  209344. };
  209345. class JuceIOleInPlaceSite : public ComBaseClassHelper <IOleInPlaceSite>
  209346. {
  209347. HWND window;
  209348. JuceOleInPlaceFrame* frame;
  209349. public:
  209350. JuceIOleInPlaceSite (HWND window_)
  209351. : window (window_),
  209352. frame (new JuceOleInPlaceFrame (window))
  209353. {}
  209354. ~JuceIOleInPlaceSite()
  209355. {
  209356. frame->Release();
  209357. }
  209358. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209359. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209360. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209361. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209362. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209363. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209364. {
  209365. /* Note: if you call AddRef on the frame here, then some types of object (e.g. web browser control) cause leaks..
  209366. If you don't call AddRef then others crash (e.g. QuickTime).. Bit of a catch-22, so letting it leak is probably preferable.
  209367. */
  209368. if (lplpFrame != 0) { frame->AddRef(); *lplpFrame = frame; }
  209369. if (lplpDoc != 0) *lplpDoc = 0;
  209370. lpFrameInfo->fMDIApp = FALSE;
  209371. lpFrameInfo->hwndFrame = window;
  209372. lpFrameInfo->haccel = 0;
  209373. lpFrameInfo->cAccelEntries = 0;
  209374. return S_OK;
  209375. }
  209376. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209377. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209378. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209379. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209380. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209381. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209382. juce_UseDebuggingNewOperator
  209383. };
  209384. class JuceIOleClientSite : public ComBaseClassHelper <IOleClientSite>
  209385. {
  209386. JuceIOleInPlaceSite* inplaceSite;
  209387. public:
  209388. JuceIOleClientSite (HWND window)
  209389. : inplaceSite (new JuceIOleInPlaceSite (window))
  209390. {}
  209391. ~JuceIOleClientSite()
  209392. {
  209393. inplaceSite->Release();
  209394. }
  209395. HRESULT __stdcall QueryInterface (REFIID type, void** result)
  209396. {
  209397. if (type == IID_IOleInPlaceSite)
  209398. {
  209399. inplaceSite->AddRef();
  209400. *result = static_cast <IOleInPlaceSite*> (inplaceSite);
  209401. return S_OK;
  209402. }
  209403. return ComBaseClassHelper <IOleClientSite>::QueryInterface (type, result);
  209404. }
  209405. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209406. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209407. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209408. HRESULT __stdcall ShowObject() { return S_OK; }
  209409. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209410. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209411. juce_UseDebuggingNewOperator
  209412. };
  209413. static Array<ActiveXControlComponent*> activeXComps;
  209414. static HWND getHWND (const ActiveXControlComponent* const component)
  209415. {
  209416. HWND hwnd = 0;
  209417. const IID iid = IID_IOleWindow;
  209418. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209419. if (window != 0)
  209420. {
  209421. window->GetWindow (&hwnd);
  209422. window->Release();
  209423. }
  209424. return hwnd;
  209425. }
  209426. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209427. {
  209428. RECT activeXRect, peerRect;
  209429. GetWindowRect (hwnd, &activeXRect);
  209430. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209431. const Point<int> mousePos (GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left,
  209432. GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top);
  209433. const int64 mouseEventTime = Win32ComponentPeer::getMouseEventTime();
  209434. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209435. switch (message)
  209436. {
  209437. case WM_MOUSEMOVE:
  209438. case WM_LBUTTONDOWN:
  209439. case WM_MBUTTONDOWN:
  209440. case WM_RBUTTONDOWN:
  209441. case WM_LBUTTONUP:
  209442. case WM_MBUTTONUP:
  209443. case WM_RBUTTONUP:
  209444. peer->handleMouseEvent (0, mousePos, Win32ComponentPeer::currentModifiers, mouseEventTime);
  209445. break;
  209446. default:
  209447. break;
  209448. }
  209449. }
  209450. }
  209451. class ActiveXControlComponent::Pimpl : public ComponentMovementWatcher
  209452. {
  209453. ActiveXControlComponent& owner;
  209454. bool wasShowing;
  209455. public:
  209456. HWND controlHWND;
  209457. IStorage* storage;
  209458. IOleClientSite* clientSite;
  209459. IOleObject* control;
  209460. Pimpl (HWND hwnd, ActiveXControlComponent& owner_)
  209461. : ComponentMovementWatcher (&owner_),
  209462. owner (owner_),
  209463. wasShowing (owner_.isShowing()),
  209464. controlHWND (0),
  209465. storage (new ActiveXHelpers::JuceIStorage()),
  209466. clientSite (new ActiveXHelpers::JuceIOleClientSite (hwnd)),
  209467. control (0)
  209468. {
  209469. }
  209470. ~Pimpl()
  209471. {
  209472. if (control != 0)
  209473. {
  209474. control->Close (OLECLOSE_NOSAVE);
  209475. control->Release();
  209476. }
  209477. clientSite->Release();
  209478. storage->Release();
  209479. }
  209480. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209481. {
  209482. Component* const topComp = owner.getTopLevelComponent();
  209483. if (topComp->getPeer() != 0)
  209484. {
  209485. const Point<int> pos (owner.relativePositionToOtherComponent (topComp, Point<int>()));
  209486. owner.setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), owner.getWidth(), owner.getHeight()));
  209487. }
  209488. }
  209489. void componentPeerChanged()
  209490. {
  209491. const bool isShowingNow = owner.isShowing();
  209492. if (wasShowing != isShowingNow)
  209493. {
  209494. wasShowing = isShowingNow;
  209495. owner.setControlVisible (isShowingNow);
  209496. }
  209497. componentMovedOrResized (true, true);
  209498. }
  209499. void componentVisibilityChanged (Component&)
  209500. {
  209501. componentPeerChanged();
  209502. }
  209503. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209504. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209505. {
  209506. for (int i = ActiveXHelpers::activeXComps.size(); --i >= 0;)
  209507. {
  209508. const ActiveXControlComponent* const ax = ActiveXHelpers::activeXComps.getUnchecked(i);
  209509. if (ax->control != 0 && ax->control->controlHWND == hwnd)
  209510. {
  209511. switch (message)
  209512. {
  209513. case WM_MOUSEMOVE:
  209514. case WM_LBUTTONDOWN:
  209515. case WM_MBUTTONDOWN:
  209516. case WM_RBUTTONDOWN:
  209517. case WM_LBUTTONUP:
  209518. case WM_MBUTTONUP:
  209519. case WM_RBUTTONUP:
  209520. case WM_LBUTTONDBLCLK:
  209521. case WM_MBUTTONDBLCLK:
  209522. case WM_RBUTTONDBLCLK:
  209523. if (ax->isShowing())
  209524. {
  209525. ComponentPeer* const peer = ax->getPeer();
  209526. if (peer != 0)
  209527. {
  209528. ActiveXHelpers::offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209529. if (! ax->areMouseEventsAllowed())
  209530. return 0;
  209531. }
  209532. }
  209533. break;
  209534. default:
  209535. break;
  209536. }
  209537. return CallWindowProc ((WNDPROC) ax->originalWndProc, hwnd, message, wParam, lParam);
  209538. }
  209539. }
  209540. return DefWindowProc (hwnd, message, wParam, lParam);
  209541. }
  209542. };
  209543. ActiveXControlComponent::ActiveXControlComponent()
  209544. : originalWndProc (0),
  209545. mouseEventsAllowed (true)
  209546. {
  209547. ActiveXHelpers::activeXComps.add (this);
  209548. }
  209549. ActiveXControlComponent::~ActiveXControlComponent()
  209550. {
  209551. deleteControl();
  209552. ActiveXHelpers::activeXComps.removeValue (this);
  209553. }
  209554. void ActiveXControlComponent::paint (Graphics& g)
  209555. {
  209556. if (control == 0)
  209557. g.fillAll (Colours::lightgrey);
  209558. }
  209559. bool ActiveXControlComponent::createControl (const void* controlIID)
  209560. {
  209561. deleteControl();
  209562. ComponentPeer* const peer = getPeer();
  209563. // the component must have already been added to a real window when you call this!
  209564. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209565. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209566. {
  209567. const Point<int> pos (relativePositionToOtherComponent (getTopLevelComponent(), Point<int>()));
  209568. HWND hwnd = (HWND) peer->getNativeHandle();
  209569. ScopedPointer<Pimpl> newControl (new Pimpl (hwnd, *this));
  209570. HRESULT hr;
  209571. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209572. newControl->clientSite, newControl->storage,
  209573. (void**) &(newControl->control))) == S_OK)
  209574. {
  209575. newControl->control->SetHostNames (L"Juce", 0);
  209576. if (OleSetContainedObject (newControl->control, TRUE) == S_OK)
  209577. {
  209578. RECT rect;
  209579. rect.left = pos.getX();
  209580. rect.top = pos.getY();
  209581. rect.right = pos.getX() + getWidth();
  209582. rect.bottom = pos.getY() + getHeight();
  209583. if (newControl->control->DoVerb (OLEIVERB_SHOW, 0, newControl->clientSite, 0, hwnd, &rect) == S_OK)
  209584. {
  209585. control = newControl;
  209586. setControlBounds (Rectangle<int> (pos.getX(), pos.getY(), getWidth(), getHeight()));
  209587. control->controlHWND = ActiveXHelpers::getHWND (this);
  209588. if (control->controlHWND != 0)
  209589. {
  209590. originalWndProc = (void*) (pointer_sized_int) GetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC);
  209591. SetWindowLongPtr ((HWND) control->controlHWND, GWLP_WNDPROC, (LONG_PTR) Pimpl::activeXHookWndProc);
  209592. }
  209593. return true;
  209594. }
  209595. }
  209596. }
  209597. }
  209598. return false;
  209599. }
  209600. void ActiveXControlComponent::deleteControl()
  209601. {
  209602. control = 0;
  209603. originalWndProc = 0;
  209604. }
  209605. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209606. {
  209607. void* result = 0;
  209608. if (control != 0 && control->control != 0
  209609. && SUCCEEDED (control->control->QueryInterface (*(const IID*) iid, &result)))
  209610. return result;
  209611. return 0;
  209612. }
  209613. void ActiveXControlComponent::setControlBounds (const Rectangle<int>& newBounds) const
  209614. {
  209615. if (control->controlHWND != 0)
  209616. MoveWindow (control->controlHWND, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209617. }
  209618. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209619. {
  209620. if (control->controlHWND != 0)
  209621. ShowWindow (control->controlHWND, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209622. }
  209623. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209624. {
  209625. mouseEventsAllowed = eventsCanReachControl;
  209626. }
  209627. #endif
  209628. /*** End of inlined file: juce_win32_ActiveXComponent.cpp ***/
  209629. /*** Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  209630. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209631. // compiled on its own).
  209632. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209633. using namespace QTOLibrary;
  209634. using namespace QTOControlLib;
  209635. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209636. static bool isQTAvailable = false;
  209637. class QuickTimeMovieComponent::Pimpl
  209638. {
  209639. public:
  209640. Pimpl() : dataHandle (0)
  209641. {
  209642. }
  209643. ~Pimpl()
  209644. {
  209645. clearHandle();
  209646. }
  209647. void clearHandle()
  209648. {
  209649. if (dataHandle != 0)
  209650. {
  209651. DisposeHandle (dataHandle);
  209652. dataHandle = 0;
  209653. }
  209654. }
  209655. IQTControlPtr qtControl;
  209656. IQTMoviePtr qtMovie;
  209657. Handle dataHandle;
  209658. };
  209659. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209660. : movieLoaded (false),
  209661. controllerVisible (true)
  209662. {
  209663. pimpl = new Pimpl();
  209664. setMouseEventsAllowed (false);
  209665. }
  209666. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209667. {
  209668. closeMovie();
  209669. pimpl->qtControl = 0;
  209670. deleteControl();
  209671. pimpl = 0;
  209672. }
  209673. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209674. {
  209675. if (! isQTAvailable)
  209676. isQTAvailable = (InitializeQTML (0) == noErr) && (EnterMovies() == noErr);
  209677. return isQTAvailable;
  209678. }
  209679. void QuickTimeMovieComponent::createControlIfNeeded()
  209680. {
  209681. if (isShowing() && ! isControlCreated())
  209682. {
  209683. const IID qtIID = __uuidof (QTControl);
  209684. if (createControl (&qtIID))
  209685. {
  209686. const IID qtInterfaceIID = __uuidof (IQTControl);
  209687. pimpl->qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209688. if (pimpl->qtControl != 0)
  209689. {
  209690. pimpl->qtControl->Release(); // it has one ref too many at this point
  209691. pimpl->qtControl->QuickTimeInitialize();
  209692. pimpl->qtControl->PutSizing (qtMovieFitsControl);
  209693. if (movieFile != File::nonexistent)
  209694. loadMovie (movieFile, controllerVisible);
  209695. }
  209696. }
  209697. }
  209698. }
  209699. bool QuickTimeMovieComponent::isControlCreated() const
  209700. {
  209701. return isControlOpen();
  209702. }
  209703. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209704. const bool isControllerVisible)
  209705. {
  209706. const ScopedPointer<InputStream> movieStreamDeleter (movieStream);
  209707. movieFile = File::nonexistent;
  209708. movieLoaded = false;
  209709. pimpl->qtMovie = 0;
  209710. controllerVisible = isControllerVisible;
  209711. createControlIfNeeded();
  209712. if (isControlCreated())
  209713. {
  209714. if (pimpl->qtControl != 0)
  209715. {
  209716. pimpl->qtControl->Put_MovieHandle (0);
  209717. pimpl->clearHandle();
  209718. Movie movie;
  209719. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, pimpl->dataHandle))
  209720. {
  209721. pimpl->qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209722. pimpl->qtMovie = pimpl->qtControl->GetMovie();
  209723. if (pimpl->qtMovie != 0)
  209724. pimpl->qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209725. : qtMovieControllerTypeNone);
  209726. }
  209727. if (movie == 0)
  209728. pimpl->clearHandle();
  209729. }
  209730. movieLoaded = (pimpl->qtMovie != 0);
  209731. }
  209732. else
  209733. {
  209734. // You're trying to open a movie when the control hasn't yet been created, probably because
  209735. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209736. jassertfalse;
  209737. }
  209738. return movieLoaded;
  209739. }
  209740. void QuickTimeMovieComponent::closeMovie()
  209741. {
  209742. stop();
  209743. movieFile = File::nonexistent;
  209744. movieLoaded = false;
  209745. pimpl->qtMovie = 0;
  209746. if (pimpl->qtControl != 0)
  209747. pimpl->qtControl->Put_MovieHandle (0);
  209748. pimpl->clearHandle();
  209749. }
  209750. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209751. {
  209752. return movieFile;
  209753. }
  209754. bool QuickTimeMovieComponent::isMovieOpen() const
  209755. {
  209756. return movieLoaded;
  209757. }
  209758. double QuickTimeMovieComponent::getMovieDuration() const
  209759. {
  209760. if (pimpl->qtMovie != 0)
  209761. return pimpl->qtMovie->GetDuration() / (double) pimpl->qtMovie->GetTimeScale();
  209762. return 0.0;
  209763. }
  209764. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209765. {
  209766. if (pimpl->qtMovie != 0)
  209767. {
  209768. struct QTRECT r = pimpl->qtMovie->GetNaturalRect();
  209769. width = r.right - r.left;
  209770. height = r.bottom - r.top;
  209771. }
  209772. else
  209773. {
  209774. width = height = 0;
  209775. }
  209776. }
  209777. void QuickTimeMovieComponent::play()
  209778. {
  209779. if (pimpl->qtMovie != 0)
  209780. pimpl->qtMovie->Play();
  209781. }
  209782. void QuickTimeMovieComponent::stop()
  209783. {
  209784. if (pimpl->qtMovie != 0)
  209785. pimpl->qtMovie->Stop();
  209786. }
  209787. bool QuickTimeMovieComponent::isPlaying() const
  209788. {
  209789. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetRate() != 0.0f;
  209790. }
  209791. void QuickTimeMovieComponent::setPosition (const double seconds)
  209792. {
  209793. if (pimpl->qtMovie != 0)
  209794. pimpl->qtMovie->PutTime ((long) (seconds * pimpl->qtMovie->GetTimeScale()));
  209795. }
  209796. double QuickTimeMovieComponent::getPosition() const
  209797. {
  209798. if (pimpl->qtMovie != 0)
  209799. return pimpl->qtMovie->GetTime() / (double) pimpl->qtMovie->GetTimeScale();
  209800. return 0.0;
  209801. }
  209802. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209803. {
  209804. if (pimpl->qtMovie != 0)
  209805. pimpl->qtMovie->PutRate (newSpeed);
  209806. }
  209807. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209808. {
  209809. if (pimpl->qtMovie != 0)
  209810. {
  209811. pimpl->qtMovie->PutAudioVolume (newVolume);
  209812. pimpl->qtMovie->PutAudioMute (newVolume <= 0);
  209813. }
  209814. }
  209815. float QuickTimeMovieComponent::getMovieVolume() const
  209816. {
  209817. if (pimpl->qtMovie != 0)
  209818. return pimpl->qtMovie->GetAudioVolume();
  209819. return 0.0f;
  209820. }
  209821. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209822. {
  209823. if (pimpl->qtMovie != 0)
  209824. pimpl->qtMovie->PutLoop (shouldLoop);
  209825. }
  209826. bool QuickTimeMovieComponent::isLooping() const
  209827. {
  209828. return pimpl->qtMovie != 0 && pimpl->qtMovie->GetLoop();
  209829. }
  209830. bool QuickTimeMovieComponent::isControllerVisible() const
  209831. {
  209832. return controllerVisible;
  209833. }
  209834. void QuickTimeMovieComponent::parentHierarchyChanged()
  209835. {
  209836. createControlIfNeeded();
  209837. QTCompBaseClass::parentHierarchyChanged();
  209838. }
  209839. void QuickTimeMovieComponent::visibilityChanged()
  209840. {
  209841. createControlIfNeeded();
  209842. QTCompBaseClass::visibilityChanged();
  209843. }
  209844. void QuickTimeMovieComponent::paint (Graphics& g)
  209845. {
  209846. if (! isControlCreated())
  209847. g.fillAll (Colours::black);
  209848. }
  209849. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209850. {
  209851. Handle dataRef = 0;
  209852. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209853. if (err == noErr)
  209854. {
  209855. Str255 suffix;
  209856. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209857. StringPtr name = suffix;
  209858. err = PtrAndHand (name, dataRef, name[0] + 1);
  209859. if (err == noErr)
  209860. {
  209861. long atoms[3];
  209862. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209863. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209864. atoms[2] = EndianU32_NtoB (MovieFileType);
  209865. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209866. if (err == noErr)
  209867. return dataRef;
  209868. }
  209869. DisposeHandle (dataRef);
  209870. }
  209871. return 0;
  209872. }
  209873. static CFStringRef juceStringToCFString (const String& s)
  209874. {
  209875. const int len = s.length();
  209876. const juce_wchar* const t = s;
  209877. HeapBlock <UniChar> temp (len + 2);
  209878. for (int i = 0; i <= len; ++i)
  209879. temp[i] = t[i];
  209880. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209881. }
  209882. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209883. {
  209884. Boolean trueBool = true;
  209885. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209886. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209887. props[prop].propValueSize = sizeof (trueBool);
  209888. props[prop].propValueAddress = &trueBool;
  209889. ++prop;
  209890. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209891. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209892. props[prop].propValueSize = sizeof (trueBool);
  209893. props[prop].propValueAddress = &trueBool;
  209894. ++prop;
  209895. Boolean isActive = true;
  209896. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209897. props[prop].propID = kQTNewMoviePropertyID_Active;
  209898. props[prop].propValueSize = sizeof (isActive);
  209899. props[prop].propValueAddress = &isActive;
  209900. ++prop;
  209901. MacSetPort (0);
  209902. jassert (prop <= 5);
  209903. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209904. return err == noErr;
  209905. }
  209906. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209907. {
  209908. if (input == 0)
  209909. return false;
  209910. dataHandle = 0;
  209911. bool ok = false;
  209912. QTNewMoviePropertyElement props[5];
  209913. zeromem (props, sizeof (props));
  209914. int prop = 0;
  209915. DataReferenceRecord dr;
  209916. props[prop].propClass = kQTPropertyClass_DataLocation;
  209917. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209918. props[prop].propValueSize = sizeof (dr);
  209919. props[prop].propValueAddress = &dr;
  209920. ++prop;
  209921. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209922. if (fin != 0)
  209923. {
  209924. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209925. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209926. &dr.dataRef, &dr.dataRefType);
  209927. ok = openMovie (props, prop, movie);
  209928. DisposeHandle (dr.dataRef);
  209929. CFRelease (filePath);
  209930. }
  209931. else
  209932. {
  209933. // sanity-check because this currently needs to load the whole stream into memory..
  209934. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209935. dataHandle = NewHandle ((Size) input->getTotalLength());
  209936. HLock (dataHandle);
  209937. // read the entire stream into memory - this is a pain, but can't get it to work
  209938. // properly using a custom callback to supply the data.
  209939. input->read (*dataHandle, (int) input->getTotalLength());
  209940. HUnlock (dataHandle);
  209941. // different types to get QT to try. (We should really be a bit smarter here by
  209942. // working out in advance which one the stream contains, rather than just trying
  209943. // each one)
  209944. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209945. "\04.avi", "\04.m4a" };
  209946. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209947. {
  209948. /* // this fails for some bizarre reason - it can be bodged to work with
  209949. // movies, but can't seem to do it for other file types..
  209950. QTNewMovieUserProcRecord procInfo;
  209951. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209952. procInfo.getMovieUserProcRefcon = this;
  209953. procInfo.defaultDataRef.dataRef = dataRef;
  209954. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209955. props[prop].propClass = kQTPropertyClass_DataLocation;
  209956. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209957. props[prop].propValueSize = sizeof (procInfo);
  209958. props[prop].propValueAddress = (void*) &procInfo;
  209959. ++prop; */
  209960. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209961. dr.dataRefType = HandleDataHandlerSubType;
  209962. ok = openMovie (props, prop, movie);
  209963. DisposeHandle (dr.dataRef);
  209964. }
  209965. }
  209966. return ok;
  209967. }
  209968. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209969. const bool isControllerVisible)
  209970. {
  209971. const bool ok = loadMovie (static_cast <InputStream*> (movieFile_.createInputStream()), isControllerVisible);
  209972. movieFile = movieFile_;
  209973. return ok;
  209974. }
  209975. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  209976. const bool isControllerVisible)
  209977. {
  209978. return loadMovie (static_cast <InputStream*> (movieURL.createInputStream (false)), isControllerVisible);
  209979. }
  209980. void QuickTimeMovieComponent::goToStart()
  209981. {
  209982. setPosition (0.0);
  209983. }
  209984. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  209985. const RectanglePlacement& placement)
  209986. {
  209987. int normalWidth, normalHeight;
  209988. getMovieNormalSize (normalWidth, normalHeight);
  209989. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209990. {
  209991. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209992. placement.applyTo (x, y, w, h,
  209993. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209994. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209995. if (w > 0 && h > 0)
  209996. {
  209997. setBounds (roundToInt (x), roundToInt (y),
  209998. roundToInt (w), roundToInt (h));
  209999. }
  210000. }
  210001. else
  210002. {
  210003. setBounds (spaceToFitWithin);
  210004. }
  210005. }
  210006. #endif
  210007. /*** End of inlined file: juce_win32_QuickTimeMovieComponent.cpp ***/
  210008. /*** Start of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210009. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210010. // compiled on its own).
  210011. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  210012. class WebBrowserComponentInternal : public ActiveXControlComponent
  210013. {
  210014. public:
  210015. WebBrowserComponentInternal()
  210016. : browser (0),
  210017. connectionPoint (0),
  210018. adviseCookie (0)
  210019. {
  210020. }
  210021. ~WebBrowserComponentInternal()
  210022. {
  210023. if (connectionPoint != 0)
  210024. connectionPoint->Unadvise (adviseCookie);
  210025. if (browser != 0)
  210026. browser->Release();
  210027. }
  210028. void createBrowser()
  210029. {
  210030. createControl (&CLSID_WebBrowser);
  210031. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  210032. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  210033. if (connectionPointContainer != 0)
  210034. {
  210035. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  210036. &connectionPoint);
  210037. if (connectionPoint != 0)
  210038. {
  210039. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  210040. jassert (owner != 0);
  210041. EventHandler* handler = new EventHandler (owner);
  210042. connectionPoint->Advise (handler, &adviseCookie);
  210043. handler->Release();
  210044. }
  210045. }
  210046. }
  210047. void goToURL (const String& url,
  210048. const StringArray* headers,
  210049. const MemoryBlock* postData)
  210050. {
  210051. if (browser != 0)
  210052. {
  210053. LPSAFEARRAY sa = 0;
  210054. VARIANT flags, frame, postDataVar, headersVar; // (_variant_t isn't available in all compilers)
  210055. VariantInit (&flags);
  210056. VariantInit (&frame);
  210057. VariantInit (&postDataVar);
  210058. VariantInit (&headersVar);
  210059. if (headers != 0)
  210060. {
  210061. V_VT (&headersVar) = VT_BSTR;
  210062. V_BSTR (&headersVar) = SysAllocString ((const OLECHAR*) headers->joinIntoString ("\r\n"));
  210063. }
  210064. if (postData != 0 && postData->getSize() > 0)
  210065. {
  210066. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210067. if (sa != 0)
  210068. {
  210069. void* data = 0;
  210070. SafeArrayAccessData (sa, &data);
  210071. jassert (data != 0);
  210072. if (data != 0)
  210073. {
  210074. postData->copyTo (data, 0, postData->getSize());
  210075. SafeArrayUnaccessData (sa);
  210076. VARIANT postDataVar2;
  210077. VariantInit (&postDataVar2);
  210078. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210079. V_ARRAY (&postDataVar2) = sa;
  210080. postDataVar = postDataVar2;
  210081. }
  210082. }
  210083. }
  210084. browser->Navigate ((BSTR) (const OLECHAR*) url,
  210085. &flags, &frame,
  210086. &postDataVar, &headersVar);
  210087. if (sa != 0)
  210088. SafeArrayDestroy (sa);
  210089. VariantClear (&flags);
  210090. VariantClear (&frame);
  210091. VariantClear (&postDataVar);
  210092. VariantClear (&headersVar);
  210093. }
  210094. }
  210095. IWebBrowser2* browser;
  210096. juce_UseDebuggingNewOperator
  210097. private:
  210098. IConnectionPoint* connectionPoint;
  210099. DWORD adviseCookie;
  210100. class EventHandler : public ComBaseClassHelper <IDispatch>,
  210101. public ComponentMovementWatcher
  210102. {
  210103. public:
  210104. EventHandler (WebBrowserComponent* owner_)
  210105. : ComponentMovementWatcher (owner_),
  210106. owner (owner_)
  210107. {
  210108. }
  210109. ~EventHandler()
  210110. {
  210111. }
  210112. HRESULT __stdcall GetTypeInfoCount (UINT*) { return E_NOTIMPL; }
  210113. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo**) { return E_NOTIMPL; }
  210114. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR*, UINT, LCID, DISPID*) { return E_NOTIMPL; }
  210115. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  210116. WORD /*wFlags*/, DISPPARAMS* pDispParams,
  210117. VARIANT* /*pVarResult*/, EXCEPINFO* /*pExcepInfo*/,
  210118. UINT* /*puArgErr*/)
  210119. {
  210120. switch (dispIdMember)
  210121. {
  210122. case DISPID_BEFORENAVIGATE2:
  210123. {
  210124. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210125. String url;
  210126. if ((vurl->vt & VT_BYREF) != 0)
  210127. url = *vurl->pbstrVal;
  210128. else
  210129. url = vurl->bstrVal;
  210130. *pDispParams->rgvarg->pboolVal
  210131. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  210132. : VARIANT_TRUE;
  210133. return S_OK;
  210134. }
  210135. default:
  210136. break;
  210137. }
  210138. return E_NOTIMPL;
  210139. }
  210140. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) {}
  210141. void componentPeerChanged() {}
  210142. void componentVisibilityChanged (Component&)
  210143. {
  210144. owner->visibilityChanged();
  210145. }
  210146. juce_UseDebuggingNewOperator
  210147. private:
  210148. WebBrowserComponent* const owner;
  210149. EventHandler (const EventHandler&);
  210150. EventHandler& operator= (const EventHandler&);
  210151. };
  210152. };
  210153. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  210154. : browser (0),
  210155. blankPageShown (false),
  210156. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  210157. {
  210158. setOpaque (true);
  210159. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210160. }
  210161. WebBrowserComponent::~WebBrowserComponent()
  210162. {
  210163. delete browser;
  210164. }
  210165. void WebBrowserComponent::goToURL (const String& url,
  210166. const StringArray* headers,
  210167. const MemoryBlock* postData)
  210168. {
  210169. lastURL = url;
  210170. lastHeaders.clear();
  210171. if (headers != 0)
  210172. lastHeaders = *headers;
  210173. lastPostData.setSize (0);
  210174. if (postData != 0)
  210175. lastPostData = *postData;
  210176. blankPageShown = false;
  210177. browser->goToURL (url, headers, postData);
  210178. }
  210179. void WebBrowserComponent::stop()
  210180. {
  210181. if (browser->browser != 0)
  210182. browser->browser->Stop();
  210183. }
  210184. void WebBrowserComponent::goBack()
  210185. {
  210186. lastURL = String::empty;
  210187. blankPageShown = false;
  210188. if (browser->browser != 0)
  210189. browser->browser->GoBack();
  210190. }
  210191. void WebBrowserComponent::goForward()
  210192. {
  210193. lastURL = String::empty;
  210194. if (browser->browser != 0)
  210195. browser->browser->GoForward();
  210196. }
  210197. void WebBrowserComponent::refresh()
  210198. {
  210199. if (browser->browser != 0)
  210200. browser->browser->Refresh();
  210201. }
  210202. void WebBrowserComponent::paint (Graphics& g)
  210203. {
  210204. if (browser->browser == 0)
  210205. g.fillAll (Colours::white);
  210206. }
  210207. void WebBrowserComponent::checkWindowAssociation()
  210208. {
  210209. if (isShowing())
  210210. {
  210211. if (browser->browser == 0 && getPeer() != 0)
  210212. {
  210213. browser->createBrowser();
  210214. reloadLastURL();
  210215. }
  210216. else
  210217. {
  210218. if (blankPageShown)
  210219. goBack();
  210220. }
  210221. }
  210222. else
  210223. {
  210224. if (browser != 0 && unloadPageWhenBrowserIsHidden && ! blankPageShown)
  210225. {
  210226. // when the component becomes invisible, some stuff like flash
  210227. // carries on playing audio, so we need to force it onto a blank
  210228. // page to avoid this..
  210229. blankPageShown = true;
  210230. browser->goToURL ("about:blank", 0, 0);
  210231. }
  210232. }
  210233. }
  210234. void WebBrowserComponent::reloadLastURL()
  210235. {
  210236. if (lastURL.isNotEmpty())
  210237. {
  210238. goToURL (lastURL, &lastHeaders, &lastPostData);
  210239. lastURL = String::empty;
  210240. }
  210241. }
  210242. void WebBrowserComponent::parentHierarchyChanged()
  210243. {
  210244. checkWindowAssociation();
  210245. }
  210246. void WebBrowserComponent::resized()
  210247. {
  210248. browser->setSize (getWidth(), getHeight());
  210249. }
  210250. void WebBrowserComponent::visibilityChanged()
  210251. {
  210252. checkWindowAssociation();
  210253. }
  210254. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210255. {
  210256. return true;
  210257. }
  210258. #endif
  210259. /*** End of inlined file: juce_win32_WebBrowserComponent.cpp ***/
  210260. /*** Start of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210261. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210262. // compiled on its own).
  210263. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210264. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210265. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210266. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210267. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210268. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210269. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210270. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210271. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210272. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210273. #define WGL_ACCELERATION_ARB 0x2003
  210274. #define WGL_SWAP_METHOD_ARB 0x2007
  210275. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210276. #define WGL_PIXEL_TYPE_ARB 0x2013
  210277. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210278. #define WGL_COLOR_BITS_ARB 0x2014
  210279. #define WGL_RED_BITS_ARB 0x2015
  210280. #define WGL_GREEN_BITS_ARB 0x2017
  210281. #define WGL_BLUE_BITS_ARB 0x2019
  210282. #define WGL_ALPHA_BITS_ARB 0x201B
  210283. #define WGL_DEPTH_BITS_ARB 0x2022
  210284. #define WGL_STENCIL_BITS_ARB 0x2023
  210285. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210286. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210287. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210288. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210289. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210290. #define WGL_STEREO_ARB 0x2012
  210291. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210292. #define WGL_SAMPLES_ARB 0x2042
  210293. #define WGL_TYPE_RGBA_ARB 0x202B
  210294. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210295. {
  210296. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210297. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210298. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210299. else
  210300. jassertfalse; // If this fails, it may be because you didn't activate the openGL context
  210301. }
  210302. class WindowedGLContext : public OpenGLContext
  210303. {
  210304. public:
  210305. WindowedGLContext (Component* const component_,
  210306. HGLRC contextToShareWith,
  210307. const OpenGLPixelFormat& pixelFormat)
  210308. : renderContext (0),
  210309. dc (0),
  210310. component (component_)
  210311. {
  210312. jassert (component != 0);
  210313. createNativeWindow();
  210314. // Use a default pixel format that should be supported everywhere
  210315. PIXELFORMATDESCRIPTOR pfd;
  210316. zerostruct (pfd);
  210317. pfd.nSize = sizeof (pfd);
  210318. pfd.nVersion = 1;
  210319. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210320. pfd.iPixelType = PFD_TYPE_RGBA;
  210321. pfd.cColorBits = 24;
  210322. pfd.cDepthBits = 16;
  210323. const int format = ChoosePixelFormat (dc, &pfd);
  210324. if (format != 0)
  210325. SetPixelFormat (dc, format, &pfd);
  210326. renderContext = wglCreateContext (dc);
  210327. makeActive();
  210328. setPixelFormat (pixelFormat);
  210329. if (contextToShareWith != 0 && renderContext != 0)
  210330. wglShareLists (contextToShareWith, renderContext);
  210331. }
  210332. ~WindowedGLContext()
  210333. {
  210334. deleteContext();
  210335. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210336. nativeWindow = 0;
  210337. }
  210338. void deleteContext()
  210339. {
  210340. makeInactive();
  210341. if (renderContext != 0)
  210342. {
  210343. wglDeleteContext (renderContext);
  210344. renderContext = 0;
  210345. }
  210346. }
  210347. bool makeActive() const throw()
  210348. {
  210349. jassert (renderContext != 0);
  210350. return wglMakeCurrent (dc, renderContext) != 0;
  210351. }
  210352. bool makeInactive() const throw()
  210353. {
  210354. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210355. }
  210356. bool isActive() const throw()
  210357. {
  210358. return wglGetCurrentContext() == renderContext;
  210359. }
  210360. const OpenGLPixelFormat getPixelFormat() const
  210361. {
  210362. OpenGLPixelFormat pf;
  210363. makeActive();
  210364. StringArray availableExtensions;
  210365. getWglExtensions (dc, availableExtensions);
  210366. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210367. return pf;
  210368. }
  210369. void* getRawContext() const throw()
  210370. {
  210371. return renderContext;
  210372. }
  210373. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210374. {
  210375. makeActive();
  210376. PIXELFORMATDESCRIPTOR pfd;
  210377. zerostruct (pfd);
  210378. pfd.nSize = sizeof (pfd);
  210379. pfd.nVersion = 1;
  210380. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210381. pfd.iPixelType = PFD_TYPE_RGBA;
  210382. pfd.iLayerType = PFD_MAIN_PLANE;
  210383. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210384. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210385. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210386. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210387. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210388. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210389. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210390. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210391. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210392. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210393. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210394. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210395. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210396. int format = 0;
  210397. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210398. StringArray availableExtensions;
  210399. getWglExtensions (dc, availableExtensions);
  210400. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210401. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210402. {
  210403. int attributes[64];
  210404. int n = 0;
  210405. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210406. attributes[n++] = GL_TRUE;
  210407. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210408. attributes[n++] = GL_TRUE;
  210409. attributes[n++] = WGL_ACCELERATION_ARB;
  210410. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210411. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210412. attributes[n++] = GL_TRUE;
  210413. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210414. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210415. attributes[n++] = WGL_COLOR_BITS_ARB;
  210416. attributes[n++] = pfd.cColorBits;
  210417. attributes[n++] = WGL_RED_BITS_ARB;
  210418. attributes[n++] = pixelFormat.redBits;
  210419. attributes[n++] = WGL_GREEN_BITS_ARB;
  210420. attributes[n++] = pixelFormat.greenBits;
  210421. attributes[n++] = WGL_BLUE_BITS_ARB;
  210422. attributes[n++] = pixelFormat.blueBits;
  210423. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210424. attributes[n++] = pixelFormat.alphaBits;
  210425. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210426. attributes[n++] = pixelFormat.depthBufferBits;
  210427. if (pixelFormat.stencilBufferBits > 0)
  210428. {
  210429. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210430. attributes[n++] = pixelFormat.stencilBufferBits;
  210431. }
  210432. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210433. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210434. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210435. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210436. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210437. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210438. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210439. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210440. if (availableExtensions.contains ("WGL_ARB_multisample")
  210441. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210442. {
  210443. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210444. attributes[n++] = 1;
  210445. attributes[n++] = WGL_SAMPLES_ARB;
  210446. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210447. }
  210448. attributes[n++] = 0;
  210449. UINT formatsCount;
  210450. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210451. (void) ok;
  210452. jassert (ok);
  210453. }
  210454. else
  210455. {
  210456. format = ChoosePixelFormat (dc, &pfd);
  210457. }
  210458. if (format != 0)
  210459. {
  210460. makeInactive();
  210461. // win32 can't change the pixel format of a window, so need to delete the
  210462. // old one and create a new one..
  210463. jassert (nativeWindow != 0);
  210464. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210465. nativeWindow = 0;
  210466. createNativeWindow();
  210467. if (SetPixelFormat (dc, format, &pfd))
  210468. {
  210469. wglDeleteContext (renderContext);
  210470. renderContext = wglCreateContext (dc);
  210471. jassert (renderContext != 0);
  210472. return renderContext != 0;
  210473. }
  210474. }
  210475. return false;
  210476. }
  210477. void updateWindowPosition (int x, int y, int w, int h, int)
  210478. {
  210479. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210480. x, y, w, h,
  210481. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210482. }
  210483. void repaint()
  210484. {
  210485. nativeWindow->repaint (nativeWindow->getBounds().withPosition (Point<int>()));
  210486. }
  210487. void swapBuffers()
  210488. {
  210489. SwapBuffers (dc);
  210490. }
  210491. bool setSwapInterval (int numFramesPerSwap)
  210492. {
  210493. makeActive();
  210494. StringArray availableExtensions;
  210495. getWglExtensions (dc, availableExtensions);
  210496. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210497. return availableExtensions.contains ("WGL_EXT_swap_control")
  210498. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210499. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210500. }
  210501. int getSwapInterval() const
  210502. {
  210503. makeActive();
  210504. StringArray availableExtensions;
  210505. getWglExtensions (dc, availableExtensions);
  210506. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210507. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210508. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210509. return wglGetSwapIntervalEXT();
  210510. return 0;
  210511. }
  210512. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210513. {
  210514. jassert (isActive());
  210515. StringArray availableExtensions;
  210516. getWglExtensions (dc, availableExtensions);
  210517. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210518. int numTypes = 0;
  210519. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210520. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210521. {
  210522. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210523. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210524. jassertfalse;
  210525. }
  210526. else
  210527. {
  210528. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210529. }
  210530. OpenGLPixelFormat pf;
  210531. for (int i = 0; i < numTypes; ++i)
  210532. {
  210533. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210534. {
  210535. bool alreadyListed = false;
  210536. for (int j = results.size(); --j >= 0;)
  210537. if (pf == *results.getUnchecked(j))
  210538. alreadyListed = true;
  210539. if (! alreadyListed)
  210540. results.add (new OpenGLPixelFormat (pf));
  210541. }
  210542. }
  210543. }
  210544. void* getNativeWindowHandle() const
  210545. {
  210546. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210547. }
  210548. juce_UseDebuggingNewOperator
  210549. HGLRC renderContext;
  210550. private:
  210551. ScopedPointer<Win32ComponentPeer> nativeWindow;
  210552. Component* const component;
  210553. HDC dc;
  210554. void createNativeWindow()
  210555. {
  210556. Win32ComponentPeer* topLevelPeer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210557. nativeWindow = new Win32ComponentPeer (component, ComponentPeer::windowIgnoresMouseClicks,
  210558. topLevelPeer == 0 ? 0 : (HWND) topLevelPeer->getNativeHandle());
  210559. nativeWindow->dontRepaint = true;
  210560. nativeWindow->setVisible (true);
  210561. dc = GetDC ((HWND) nativeWindow->getNativeHandle());
  210562. }
  210563. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210564. OpenGLPixelFormat& result,
  210565. const StringArray& availableExtensions) const throw()
  210566. {
  210567. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210568. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210569. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210570. {
  210571. int attributes[32];
  210572. int numAttributes = 0;
  210573. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210574. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210575. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210576. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210577. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210578. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210579. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210580. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210581. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210582. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210583. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210584. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210585. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210586. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210587. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210588. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210589. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210590. int values[32];
  210591. zeromem (values, sizeof (values));
  210592. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210593. {
  210594. int n = 0;
  210595. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210596. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210597. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210598. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210599. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210600. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210601. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210602. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210603. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210604. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210605. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210606. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210607. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210608. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210609. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210610. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210611. return isValidFormat;
  210612. }
  210613. else
  210614. {
  210615. jassertfalse;
  210616. }
  210617. }
  210618. else
  210619. {
  210620. PIXELFORMATDESCRIPTOR pfd;
  210621. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210622. {
  210623. result.redBits = pfd.cRedBits;
  210624. result.greenBits = pfd.cGreenBits;
  210625. result.blueBits = pfd.cBlueBits;
  210626. result.alphaBits = pfd.cAlphaBits;
  210627. result.depthBufferBits = pfd.cDepthBits;
  210628. result.stencilBufferBits = pfd.cStencilBits;
  210629. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210630. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210631. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210632. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210633. result.fullSceneAntiAliasingNumSamples = 0;
  210634. return true;
  210635. }
  210636. else
  210637. {
  210638. jassertfalse;
  210639. }
  210640. }
  210641. return false;
  210642. }
  210643. WindowedGLContext (const WindowedGLContext&);
  210644. WindowedGLContext& operator= (const WindowedGLContext&);
  210645. };
  210646. OpenGLContext* OpenGLComponent::createContext()
  210647. {
  210648. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this,
  210649. contextToShareListsWith != 0 ? (HGLRC) contextToShareListsWith->getRawContext() : 0,
  210650. preferredPixelFormat));
  210651. return (c->renderContext != 0) ? c.release() : 0;
  210652. }
  210653. void* OpenGLComponent::getNativeWindowHandle() const
  210654. {
  210655. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle() : 0;
  210656. }
  210657. void juce_glViewport (const int w, const int h)
  210658. {
  210659. glViewport (0, 0, w, h);
  210660. }
  210661. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210662. OwnedArray <OpenGLPixelFormat>& results)
  210663. {
  210664. Component tempComp;
  210665. {
  210666. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210667. wc.makeActive();
  210668. wc.findAlternativeOpenGLPixelFormats (results);
  210669. }
  210670. }
  210671. #endif
  210672. /*** End of inlined file: juce_win32_OpenGLComponent.cpp ***/
  210673. /*** Start of inlined file: juce_win32_AudioCDReader.cpp ***/
  210674. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210675. // compiled on its own).
  210676. #if JUCE_INCLUDED_FILE
  210677. #if JUCE_USE_CDREADER
  210678. namespace CDReaderHelpers
  210679. {
  210680. //***************************************************************************
  210681. // %%% TARGET STATUS VALUES %%%
  210682. //***************************************************************************
  210683. #define STATUS_GOOD 0x00 // Status Good
  210684. #define STATUS_CHKCOND 0x02 // Check Condition
  210685. #define STATUS_CONDMET 0x04 // Condition Met
  210686. #define STATUS_BUSY 0x08 // Busy
  210687. #define STATUS_INTERM 0x10 // Intermediate
  210688. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210689. #define STATUS_RESCONF 0x18 // Reservation conflict
  210690. #define STATUS_COMTERM 0x22 // Command Terminated
  210691. #define STATUS_QFULL 0x28 // Queue full
  210692. //***************************************************************************
  210693. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210694. //***************************************************************************
  210695. #define MAXLUN 7 // Maximum Logical Unit Id
  210696. #define MAXTARG 7 // Maximum Target Id
  210697. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210698. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210699. //***************************************************************************
  210700. // %%% Commands for all Device Types %%%
  210701. //***************************************************************************
  210702. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210703. #define SCSI_COMPARE 0x39 // Compare (O)
  210704. #define SCSI_COPY 0x18 // Copy (O)
  210705. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210706. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210707. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210708. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210709. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210710. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210711. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210712. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210713. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210714. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210715. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210716. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210717. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210718. //***************************************************************************
  210719. // %%% Commands Unique to Direct Access Devices %%%
  210720. //***************************************************************************
  210721. #define SCSI_COMPARE 0x39 // Compare (O)
  210722. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210723. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210724. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210725. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210726. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210727. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210728. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210729. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210730. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210731. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210732. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210733. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210734. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210735. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210736. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210737. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210738. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210739. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210740. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210741. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210742. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210743. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210744. #define SCSI_VERIFY 0x2F // Verify (O)
  210745. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210746. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210747. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210748. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210749. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210750. //***************************************************************************
  210751. // %%% Commands Unique to Sequential Access Devices %%%
  210752. //***************************************************************************
  210753. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210754. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210755. #define SCSI_LOCATE 0x2B // Locate (O)
  210756. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210757. #define SCSI_READ_POS 0x34 // Read Position (O)
  210758. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210759. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210760. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210761. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210762. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210763. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210764. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210765. //***************************************************************************
  210766. // %%% Commands Unique to Printer Devices %%%
  210767. //***************************************************************************
  210768. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210769. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210770. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210771. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210772. //***************************************************************************
  210773. // %%% Commands Unique to Processor Devices %%%
  210774. //***************************************************************************
  210775. #define SCSI_RECEIVE 0x08 // Receive (O)
  210776. #define SCSI_SEND 0x0A // Send (O)
  210777. //***************************************************************************
  210778. // %%% Commands Unique to Write-Once Devices %%%
  210779. //***************************************************************************
  210780. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210781. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210782. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210783. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210784. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210785. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210786. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210787. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210788. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210789. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210790. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210791. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210792. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210793. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210794. //***************************************************************************
  210795. // %%% Commands Unique to CD-ROM Devices %%%
  210796. //***************************************************************************
  210797. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210798. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210799. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210800. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210801. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210802. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210803. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210804. #define SCSI_READHEADER 0x44 // Read Header (O)
  210805. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210806. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210807. //***************************************************************************
  210808. // %%% Commands Unique to Scanner Devices %%%
  210809. //***************************************************************************
  210810. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210811. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210812. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210813. #define SCSI_SCAN 0x1B // Scan (O)
  210814. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210815. //***************************************************************************
  210816. // %%% Commands Unique to Optical Memory Devices %%%
  210817. //***************************************************************************
  210818. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210819. //***************************************************************************
  210820. // %%% Commands Unique to Medium Changer Devices %%%
  210821. //***************************************************************************
  210822. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210823. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210824. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210825. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210826. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210827. //***************************************************************************
  210828. // %%% Commands Unique to Communication Devices %%%
  210829. //***************************************************************************
  210830. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210831. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210832. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210833. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210834. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210835. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210836. //***************************************************************************
  210837. // %%% Request Sense Data Format %%%
  210838. //***************************************************************************
  210839. typedef struct {
  210840. BYTE ErrorCode; // Error Code (70H or 71H)
  210841. BYTE SegmentNum; // Number of current segment descriptor
  210842. BYTE SenseKey; // Sense Key(See bit definitions too)
  210843. BYTE InfoByte0; // Information MSB
  210844. BYTE InfoByte1; // Information MID
  210845. BYTE InfoByte2; // Information MID
  210846. BYTE InfoByte3; // Information LSB
  210847. BYTE AddSenLen; // Additional Sense Length
  210848. BYTE ComSpecInf0; // Command Specific Information MSB
  210849. BYTE ComSpecInf1; // Command Specific Information MID
  210850. BYTE ComSpecInf2; // Command Specific Information MID
  210851. BYTE ComSpecInf3; // Command Specific Information LSB
  210852. BYTE AddSenseCode; // Additional Sense Code
  210853. BYTE AddSenQual; // Additional Sense Code Qualifier
  210854. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210855. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210856. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210857. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210858. BYTE AddSenseBytes; // Additional Sense Bytes
  210859. } SENSE_DATA_FMT;
  210860. //***************************************************************************
  210861. // %%% REQUEST SENSE ERROR CODE %%%
  210862. //***************************************************************************
  210863. #define SERROR_CURRENT 0x70 // Current Errors
  210864. #define SERROR_DEFERED 0x71 // Deferred Errors
  210865. //***************************************************************************
  210866. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210867. //***************************************************************************
  210868. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210869. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210870. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210871. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210872. //***************************************************************************
  210873. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210874. //***************************************************************************
  210875. #define KEY_NOSENSE 0x00 // No Sense
  210876. #define KEY_RECERROR 0x01 // Recovered Error
  210877. #define KEY_NOTREADY 0x02 // Not Ready
  210878. #define KEY_MEDIUMERR 0x03 // Medium Error
  210879. #define KEY_HARDERROR 0x04 // Hardware Error
  210880. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210881. #define KEY_UNITATT 0x06 // Unit Attention
  210882. #define KEY_DATAPROT 0x07 // Data Protect
  210883. #define KEY_BLANKCHK 0x08 // Blank Check
  210884. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210885. #define KEY_COPYABORT 0x0A // Copy Abort
  210886. #define KEY_EQUAL 0x0C // Equal (Search)
  210887. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210888. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210889. #define KEY_RESERVED 0x0F // Reserved
  210890. //***************************************************************************
  210891. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210892. //***************************************************************************
  210893. #define DTYPE_DASD 0x00 // Disk Device
  210894. #define DTYPE_SEQD 0x01 // Tape Device
  210895. #define DTYPE_PRNT 0x02 // Printer
  210896. #define DTYPE_PROC 0x03 // Processor
  210897. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210898. #define DTYPE_CROM 0x05 // CD-ROM device
  210899. #define DTYPE_SCAN 0x06 // Scanner device
  210900. #define DTYPE_OPTI 0x07 // Optical memory device
  210901. #define DTYPE_JUKE 0x08 // Medium Changer device
  210902. #define DTYPE_COMM 0x09 // Communications device
  210903. #define DTYPE_RESL 0x0A // Reserved (low)
  210904. #define DTYPE_RESH 0x1E // Reserved (high)
  210905. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210906. //***************************************************************************
  210907. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210908. //***************************************************************************
  210909. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210910. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210911. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210912. #define ANSI_RESLO 0x3 // Reserved (low)
  210913. #define ANSI_RESHI 0x7 // Reserved (high)
  210914. typedef struct
  210915. {
  210916. USHORT Length;
  210917. UCHAR ScsiStatus;
  210918. UCHAR PathId;
  210919. UCHAR TargetId;
  210920. UCHAR Lun;
  210921. UCHAR CdbLength;
  210922. UCHAR SenseInfoLength;
  210923. UCHAR DataIn;
  210924. ULONG DataTransferLength;
  210925. ULONG TimeOutValue;
  210926. ULONG DataBufferOffset;
  210927. ULONG SenseInfoOffset;
  210928. UCHAR Cdb[16];
  210929. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210930. typedef struct
  210931. {
  210932. USHORT Length;
  210933. UCHAR ScsiStatus;
  210934. UCHAR PathId;
  210935. UCHAR TargetId;
  210936. UCHAR Lun;
  210937. UCHAR CdbLength;
  210938. UCHAR SenseInfoLength;
  210939. UCHAR DataIn;
  210940. ULONG DataTransferLength;
  210941. ULONG TimeOutValue;
  210942. PVOID DataBuffer;
  210943. ULONG SenseInfoOffset;
  210944. UCHAR Cdb[16];
  210945. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210946. typedef struct
  210947. {
  210948. SCSI_PASS_THROUGH_DIRECT spt;
  210949. ULONG Filler;
  210950. UCHAR ucSenseBuf[32];
  210951. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210952. typedef struct
  210953. {
  210954. ULONG Length;
  210955. UCHAR PortNumber;
  210956. UCHAR PathId;
  210957. UCHAR TargetId;
  210958. UCHAR Lun;
  210959. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210960. #define METHOD_BUFFERED 0
  210961. #define METHOD_IN_DIRECT 1
  210962. #define METHOD_OUT_DIRECT 2
  210963. #define METHOD_NEITHER 3
  210964. #define FILE_ANY_ACCESS 0
  210965. #ifndef FILE_READ_ACCESS
  210966. #define FILE_READ_ACCESS (0x0001)
  210967. #endif
  210968. #ifndef FILE_WRITE_ACCESS
  210969. #define FILE_WRITE_ACCESS (0x0002)
  210970. #endif
  210971. #define IOCTL_SCSI_BASE 0x00000004
  210972. #define SCSI_IOCTL_DATA_OUT 0
  210973. #define SCSI_IOCTL_DATA_IN 1
  210974. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210975. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210976. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210977. )
  210978. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210979. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210980. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210981. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210982. #define SENSE_LEN 14
  210983. #define SRB_DIR_SCSI 0x00
  210984. #define SRB_POSTING 0x01
  210985. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210986. #define SRB_DIR_IN 0x08
  210987. #define SRB_DIR_OUT 0x10
  210988. #define SRB_EVENT_NOTIFY 0x40
  210989. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210990. #define MAX_SRB_TIMEOUT 1080001u
  210991. #define DEFAULT_SRB_TIMEOUT 1080001u
  210992. #define SC_HA_INQUIRY 0x00
  210993. #define SC_GET_DEV_TYPE 0x01
  210994. #define SC_EXEC_SCSI_CMD 0x02
  210995. #define SC_ABORT_SRB 0x03
  210996. #define SC_RESET_DEV 0x04
  210997. #define SC_SET_HA_PARMS 0x05
  210998. #define SC_GET_DISK_INFO 0x06
  210999. #define SC_RESCAN_SCSI_BUS 0x07
  211000. #define SC_GETSET_TIMEOUTS 0x08
  211001. #define SS_PENDING 0x00
  211002. #define SS_COMP 0x01
  211003. #define SS_ABORTED 0x02
  211004. #define SS_ABORT_FAIL 0x03
  211005. #define SS_ERR 0x04
  211006. #define SS_INVALID_CMD 0x80
  211007. #define SS_INVALID_HA 0x81
  211008. #define SS_NO_DEVICE 0x82
  211009. #define SS_INVALID_SRB 0xE0
  211010. #define SS_OLD_MANAGER 0xE1
  211011. #define SS_BUFFER_ALIGN 0xE1
  211012. #define SS_ILLEGAL_MODE 0xE2
  211013. #define SS_NO_ASPI 0xE3
  211014. #define SS_FAILED_INIT 0xE4
  211015. #define SS_ASPI_IS_BUSY 0xE5
  211016. #define SS_BUFFER_TO_BIG 0xE6
  211017. #define SS_BUFFER_TOO_BIG 0xE6
  211018. #define SS_MISMATCHED_COMPONENTS 0xE7
  211019. #define SS_NO_ADAPTERS 0xE8
  211020. #define SS_INSUFFICIENT_RESOURCES 0xE9
  211021. #define SS_ASPI_IS_SHUTDOWN 0xEA
  211022. #define SS_BAD_INSTALL 0xEB
  211023. #define HASTAT_OK 0x00
  211024. #define HASTAT_SEL_TO 0x11
  211025. #define HASTAT_DO_DU 0x12
  211026. #define HASTAT_BUS_FREE 0x13
  211027. #define HASTAT_PHASE_ERR 0x14
  211028. #define HASTAT_TIMEOUT 0x09
  211029. #define HASTAT_COMMAND_TIMEOUT 0x0B
  211030. #define HASTAT_MESSAGE_REJECT 0x0D
  211031. #define HASTAT_BUS_RESET 0x0E
  211032. #define HASTAT_PARITY_ERROR 0x0F
  211033. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  211034. #define PACKED
  211035. #pragma pack(1)
  211036. typedef struct
  211037. {
  211038. BYTE SRB_Cmd;
  211039. BYTE SRB_Status;
  211040. BYTE SRB_HaID;
  211041. BYTE SRB_Flags;
  211042. DWORD SRB_Hdr_Rsvd;
  211043. BYTE HA_Count;
  211044. BYTE HA_SCSI_ID;
  211045. BYTE HA_ManagerId[16];
  211046. BYTE HA_Identifier[16];
  211047. BYTE HA_Unique[16];
  211048. WORD HA_Rsvd1;
  211049. BYTE pad[20];
  211050. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  211051. typedef struct
  211052. {
  211053. BYTE SRB_Cmd;
  211054. BYTE SRB_Status;
  211055. BYTE SRB_HaID;
  211056. BYTE SRB_Flags;
  211057. DWORD SRB_Hdr_Rsvd;
  211058. BYTE SRB_Target;
  211059. BYTE SRB_Lun;
  211060. BYTE SRB_DeviceType;
  211061. BYTE SRB_Rsvd1;
  211062. BYTE pad[68];
  211063. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  211064. typedef struct
  211065. {
  211066. BYTE SRB_Cmd;
  211067. BYTE SRB_Status;
  211068. BYTE SRB_HaID;
  211069. BYTE SRB_Flags;
  211070. DWORD SRB_Hdr_Rsvd;
  211071. BYTE SRB_Target;
  211072. BYTE SRB_Lun;
  211073. WORD SRB_Rsvd1;
  211074. DWORD SRB_BufLen;
  211075. BYTE FAR *SRB_BufPointer;
  211076. BYTE SRB_SenseLen;
  211077. BYTE SRB_CDBLen;
  211078. BYTE SRB_HaStat;
  211079. BYTE SRB_TargStat;
  211080. VOID FAR *SRB_PostProc;
  211081. BYTE SRB_Rsvd2[20];
  211082. BYTE CDBByte[16];
  211083. BYTE SenseArea[SENSE_LEN+2];
  211084. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  211085. typedef struct
  211086. {
  211087. BYTE SRB_Cmd;
  211088. BYTE SRB_Status;
  211089. BYTE SRB_HaId;
  211090. BYTE SRB_Flags;
  211091. DWORD SRB_Hdr_Rsvd;
  211092. } PACKED SRB, *PSRB, FAR *LPSRB;
  211093. #pragma pack()
  211094. struct CDDeviceInfo
  211095. {
  211096. char vendor[9];
  211097. char productId[17];
  211098. char rev[5];
  211099. char vendorSpec[21];
  211100. BYTE ha;
  211101. BYTE tgt;
  211102. BYTE lun;
  211103. char scsiDriveLetter; // will be 0 if not using scsi
  211104. };
  211105. class CDReadBuffer
  211106. {
  211107. public:
  211108. int startFrame;
  211109. int numFrames;
  211110. int dataStartOffset;
  211111. int dataLength;
  211112. int bufferSize;
  211113. HeapBlock<BYTE> buffer;
  211114. int index;
  211115. bool wantsIndex;
  211116. CDReadBuffer (const int numberOfFrames)
  211117. : startFrame (0),
  211118. numFrames (0),
  211119. dataStartOffset (0),
  211120. dataLength (0),
  211121. bufferSize (2352 * numberOfFrames),
  211122. buffer (bufferSize),
  211123. index (0),
  211124. wantsIndex (false)
  211125. {
  211126. }
  211127. bool isZero() const throw()
  211128. {
  211129. BYTE* p = buffer + dataStartOffset;
  211130. for (int i = dataLength; --i >= 0;)
  211131. if (*p++ != 0)
  211132. return false;
  211133. return true;
  211134. }
  211135. };
  211136. class CDDeviceHandle;
  211137. class CDController
  211138. {
  211139. public:
  211140. CDController();
  211141. virtual ~CDController();
  211142. virtual bool read (CDReadBuffer* t) = 0;
  211143. virtual void shutDown();
  211144. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  211145. int getLastIndex();
  211146. public:
  211147. bool initialised;
  211148. CDDeviceHandle* deviceInfo;
  211149. int framesToCheck, framesOverlap;
  211150. void prepare (SRB_ExecSCSICmd& s);
  211151. void perform (SRB_ExecSCSICmd& s);
  211152. void setPaused (bool paused);
  211153. };
  211154. #pragma pack(1)
  211155. struct TOCTRACK
  211156. {
  211157. BYTE rsvd;
  211158. BYTE ADR;
  211159. BYTE trackNumber;
  211160. BYTE rsvd2;
  211161. BYTE addr[4];
  211162. };
  211163. struct TOC
  211164. {
  211165. WORD tocLen;
  211166. BYTE firstTrack;
  211167. BYTE lastTrack;
  211168. TOCTRACK tracks[100];
  211169. };
  211170. #pragma pack()
  211171. enum
  211172. {
  211173. READTYPE_ANY = 0,
  211174. READTYPE_ATAPI1 = 1,
  211175. READTYPE_ATAPI2 = 2,
  211176. READTYPE_READ6 = 3,
  211177. READTYPE_READ10 = 4,
  211178. READTYPE_READ_D8 = 5,
  211179. READTYPE_READ_D4 = 6,
  211180. READTYPE_READ_D4_1 = 7,
  211181. READTYPE_READ10_2 = 8
  211182. };
  211183. class CDDeviceHandle
  211184. {
  211185. public:
  211186. CDDeviceHandle (const CDDeviceInfo* const device)
  211187. : scsiHandle (0),
  211188. readType (READTYPE_ANY),
  211189. controller (0)
  211190. {
  211191. memcpy (&info, device, sizeof (info));
  211192. }
  211193. ~CDDeviceHandle()
  211194. {
  211195. if (controller != 0)
  211196. {
  211197. controller->shutDown();
  211198. controller = 0;
  211199. }
  211200. if (scsiHandle != 0)
  211201. CloseHandle (scsiHandle);
  211202. }
  211203. bool readTOC (TOC* lpToc);
  211204. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211205. void openDrawer (bool shouldBeOpen);
  211206. CDDeviceInfo info;
  211207. HANDLE scsiHandle;
  211208. BYTE readType;
  211209. private:
  211210. ScopedPointer<CDController> controller;
  211211. bool testController (const int readType,
  211212. CDController* const newController,
  211213. CDReadBuffer* const bufferToUse);
  211214. };
  211215. DWORD (*fGetASPI32SupportInfo)(void);
  211216. DWORD (*fSendASPI32Command)(LPSRB);
  211217. static HINSTANCE winAspiLib = 0;
  211218. static bool usingScsi = false;
  211219. static bool initialised = false;
  211220. bool InitialiseCDRipper()
  211221. {
  211222. if (! initialised)
  211223. {
  211224. initialised = true;
  211225. OSVERSIONINFO info;
  211226. info.dwOSVersionInfoSize = sizeof (info);
  211227. GetVersionEx (&info);
  211228. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211229. if (! usingScsi)
  211230. {
  211231. fGetASPI32SupportInfo = 0;
  211232. fSendASPI32Command = 0;
  211233. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211234. if (winAspiLib != 0)
  211235. {
  211236. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211237. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211238. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211239. return false;
  211240. }
  211241. else
  211242. {
  211243. usingScsi = true;
  211244. }
  211245. }
  211246. }
  211247. return true;
  211248. }
  211249. void DeinitialiseCDRipper()
  211250. {
  211251. if (winAspiLib != 0)
  211252. {
  211253. fGetASPI32SupportInfo = 0;
  211254. fSendASPI32Command = 0;
  211255. FreeLibrary (winAspiLib);
  211256. winAspiLib = 0;
  211257. }
  211258. initialised = false;
  211259. }
  211260. HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211261. {
  211262. TCHAR devicePath[] = { '\\', '\\', '.', '\\', driveLetter, ':', 0, 0 };
  211263. OSVERSIONINFO info;
  211264. info.dwOSVersionInfoSize = sizeof (info);
  211265. GetVersionEx (&info);
  211266. DWORD flags = GENERIC_READ;
  211267. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211268. flags = GENERIC_READ | GENERIC_WRITE;
  211269. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211270. if (h == INVALID_HANDLE_VALUE)
  211271. {
  211272. flags ^= GENERIC_WRITE;
  211273. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211274. }
  211275. return h;
  211276. }
  211277. DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb, const char driveLetter,
  211278. HANDLE& deviceHandle, const bool retryOnFailure = true)
  211279. {
  211280. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211281. zerostruct (s);
  211282. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211283. s.spt.CdbLength = srb->SRB_CDBLen;
  211284. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211285. ? SCSI_IOCTL_DATA_IN
  211286. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211287. ? SCSI_IOCTL_DATA_OUT
  211288. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211289. s.spt.DataTransferLength = srb->SRB_BufLen;
  211290. s.spt.TimeOutValue = 5;
  211291. s.spt.DataBuffer = srb->SRB_BufPointer;
  211292. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211293. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211294. srb->SRB_Status = SS_ERR;
  211295. srb->SRB_TargStat = 0x0004;
  211296. DWORD bytesReturned = 0;
  211297. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211298. &s, sizeof (s),
  211299. &s, sizeof (s),
  211300. &bytesReturned, 0) != 0)
  211301. {
  211302. srb->SRB_Status = SS_COMP;
  211303. }
  211304. else if (retryOnFailure)
  211305. {
  211306. const DWORD error = GetLastError();
  211307. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211308. {
  211309. if (error != ERROR_INVALID_HANDLE)
  211310. CloseHandle (deviceHandle);
  211311. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211312. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211313. }
  211314. }
  211315. return srb->SRB_Status;
  211316. }
  211317. // Controller types..
  211318. class ControllerType1 : public CDController
  211319. {
  211320. public:
  211321. ControllerType1() {}
  211322. ~ControllerType1() {}
  211323. bool read (CDReadBuffer* rb)
  211324. {
  211325. if (rb->numFrames * 2352 > rb->bufferSize)
  211326. return false;
  211327. SRB_ExecSCSICmd s;
  211328. prepare (s);
  211329. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211330. s.SRB_BufLen = rb->bufferSize;
  211331. s.SRB_BufPointer = rb->buffer;
  211332. s.SRB_CDBLen = 12;
  211333. s.CDBByte[0] = 0xBE;
  211334. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211335. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211336. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211337. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211338. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211339. perform (s);
  211340. if (s.SRB_Status != SS_COMP)
  211341. return false;
  211342. rb->dataLength = rb->numFrames * 2352;
  211343. rb->dataStartOffset = 0;
  211344. return true;
  211345. }
  211346. };
  211347. class ControllerType2 : public CDController
  211348. {
  211349. public:
  211350. ControllerType2() {}
  211351. ~ControllerType2() {}
  211352. void shutDown()
  211353. {
  211354. if (initialised)
  211355. {
  211356. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211357. SRB_ExecSCSICmd s;
  211358. prepare (s);
  211359. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211360. s.SRB_BufLen = 0x0C;
  211361. s.SRB_BufPointer = bufPointer;
  211362. s.SRB_CDBLen = 6;
  211363. s.CDBByte[0] = 0x15;
  211364. s.CDBByte[4] = 0x0C;
  211365. perform (s);
  211366. }
  211367. }
  211368. bool init()
  211369. {
  211370. SRB_ExecSCSICmd s;
  211371. s.SRB_Status = SS_ERR;
  211372. if (deviceInfo->readType == READTYPE_READ10_2)
  211373. {
  211374. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211375. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211376. for (int i = 0; i < 2; ++i)
  211377. {
  211378. prepare (s);
  211379. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211380. s.SRB_BufLen = 0x14;
  211381. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211382. s.SRB_CDBLen = 6;
  211383. s.CDBByte[0] = 0x15;
  211384. s.CDBByte[1] = 0x10;
  211385. s.CDBByte[4] = 0x14;
  211386. perform (s);
  211387. if (s.SRB_Status != SS_COMP)
  211388. return false;
  211389. }
  211390. }
  211391. else
  211392. {
  211393. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211394. prepare (s);
  211395. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211396. s.SRB_BufLen = 0x0C;
  211397. s.SRB_BufPointer = bufPointer;
  211398. s.SRB_CDBLen = 6;
  211399. s.CDBByte[0] = 0x15;
  211400. s.CDBByte[4] = 0x0C;
  211401. perform (s);
  211402. }
  211403. return s.SRB_Status == SS_COMP;
  211404. }
  211405. bool read (CDReadBuffer* rb)
  211406. {
  211407. if (rb->numFrames * 2352 > rb->bufferSize)
  211408. return false;
  211409. if (!initialised)
  211410. {
  211411. initialised = init();
  211412. if (!initialised)
  211413. return false;
  211414. }
  211415. SRB_ExecSCSICmd s;
  211416. prepare (s);
  211417. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211418. s.SRB_BufLen = rb->bufferSize;
  211419. s.SRB_BufPointer = rb->buffer;
  211420. s.SRB_CDBLen = 10;
  211421. s.CDBByte[0] = 0x28;
  211422. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211423. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211424. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211425. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211426. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211427. perform (s);
  211428. if (s.SRB_Status != SS_COMP)
  211429. return false;
  211430. rb->dataLength = rb->numFrames * 2352;
  211431. rb->dataStartOffset = 0;
  211432. return true;
  211433. }
  211434. };
  211435. class ControllerType3 : public CDController
  211436. {
  211437. public:
  211438. ControllerType3() {}
  211439. ~ControllerType3() {}
  211440. bool read (CDReadBuffer* rb)
  211441. {
  211442. if (rb->numFrames * 2352 > rb->bufferSize)
  211443. return false;
  211444. if (!initialised)
  211445. {
  211446. setPaused (false);
  211447. initialised = true;
  211448. }
  211449. SRB_ExecSCSICmd s;
  211450. prepare (s);
  211451. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211452. s.SRB_BufLen = rb->numFrames * 2352;
  211453. s.SRB_BufPointer = rb->buffer;
  211454. s.SRB_CDBLen = 12;
  211455. s.CDBByte[0] = 0xD8;
  211456. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211457. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211458. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211459. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211460. perform (s);
  211461. if (s.SRB_Status != SS_COMP)
  211462. return false;
  211463. rb->dataLength = rb->numFrames * 2352;
  211464. rb->dataStartOffset = 0;
  211465. return true;
  211466. }
  211467. };
  211468. class ControllerType4 : public CDController
  211469. {
  211470. public:
  211471. ControllerType4() {}
  211472. ~ControllerType4() {}
  211473. bool selectD4Mode()
  211474. {
  211475. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211476. SRB_ExecSCSICmd s;
  211477. prepare (s);
  211478. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211479. s.SRB_CDBLen = 6;
  211480. s.SRB_BufLen = 12;
  211481. s.SRB_BufPointer = bufPointer;
  211482. s.CDBByte[0] = 0x15;
  211483. s.CDBByte[1] = 0x10;
  211484. s.CDBByte[4] = 0x08;
  211485. perform (s);
  211486. return s.SRB_Status == SS_COMP;
  211487. }
  211488. bool read (CDReadBuffer* rb)
  211489. {
  211490. if (rb->numFrames * 2352 > rb->bufferSize)
  211491. return false;
  211492. if (!initialised)
  211493. {
  211494. setPaused (true);
  211495. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211496. selectD4Mode();
  211497. initialised = true;
  211498. }
  211499. SRB_ExecSCSICmd s;
  211500. prepare (s);
  211501. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211502. s.SRB_BufLen = rb->bufferSize;
  211503. s.SRB_BufPointer = rb->buffer;
  211504. s.SRB_CDBLen = 10;
  211505. s.CDBByte[0] = 0xD4;
  211506. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211507. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211508. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211509. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211510. perform (s);
  211511. if (s.SRB_Status != SS_COMP)
  211512. return false;
  211513. rb->dataLength = rb->numFrames * 2352;
  211514. rb->dataStartOffset = 0;
  211515. return true;
  211516. }
  211517. };
  211518. CDController::CDController() : initialised (false)
  211519. {
  211520. }
  211521. CDController::~CDController()
  211522. {
  211523. }
  211524. void CDController::prepare (SRB_ExecSCSICmd& s)
  211525. {
  211526. zerostruct (s);
  211527. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211528. s.SRB_HaID = deviceInfo->info.ha;
  211529. s.SRB_Target = deviceInfo->info.tgt;
  211530. s.SRB_Lun = deviceInfo->info.lun;
  211531. s.SRB_SenseLen = SENSE_LEN;
  211532. }
  211533. void CDController::perform (SRB_ExecSCSICmd& s)
  211534. {
  211535. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211536. s.SRB_PostProc = event;
  211537. ResetEvent (event);
  211538. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211539. deviceInfo->info.scsiDriveLetter,
  211540. deviceInfo->scsiHandle)
  211541. : fSendASPI32Command ((LPSRB)&s);
  211542. if (status == SS_PENDING)
  211543. WaitForSingleObject (event, 4000);
  211544. CloseHandle (event);
  211545. }
  211546. void CDController::setPaused (bool paused)
  211547. {
  211548. SRB_ExecSCSICmd s;
  211549. prepare (s);
  211550. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211551. s.SRB_CDBLen = 10;
  211552. s.CDBByte[0] = 0x4B;
  211553. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211554. perform (s);
  211555. }
  211556. void CDController::shutDown()
  211557. {
  211558. }
  211559. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211560. {
  211561. if (overlapBuffer != 0)
  211562. {
  211563. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211564. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211565. if (doJitter
  211566. && overlapBuffer->startFrame > 0
  211567. && overlapBuffer->numFrames > 0
  211568. && overlapBuffer->dataLength > 0)
  211569. {
  211570. const int numFrames = rb->numFrames;
  211571. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211572. {
  211573. rb->startFrame -= framesOverlap;
  211574. if (framesToCheck < framesOverlap
  211575. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211576. rb->numFrames += framesOverlap;
  211577. }
  211578. else
  211579. {
  211580. overlapBuffer->dataLength = 0;
  211581. overlapBuffer->startFrame = 0;
  211582. overlapBuffer->numFrames = 0;
  211583. }
  211584. }
  211585. if (! read (rb))
  211586. return false;
  211587. if (doJitter)
  211588. {
  211589. const int checkLen = framesToCheck * 2352;
  211590. const int maxToCheck = rb->dataLength - checkLen;
  211591. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211592. return true;
  211593. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211594. bool found = false;
  211595. for (int i = 0; i < maxToCheck; ++i)
  211596. {
  211597. if (memcmp (p, rb->buffer + i, checkLen) == 0)
  211598. {
  211599. i += checkLen;
  211600. rb->dataStartOffset = i;
  211601. rb->dataLength -= i;
  211602. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211603. found = true;
  211604. break;
  211605. }
  211606. }
  211607. rb->numFrames = rb->dataLength / 2352;
  211608. rb->dataLength = 2352 * rb->numFrames;
  211609. if (!found)
  211610. return false;
  211611. }
  211612. if (canDoJitter)
  211613. {
  211614. memcpy (overlapBuffer->buffer,
  211615. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211616. 2352 * framesToCheck);
  211617. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211618. overlapBuffer->numFrames = framesToCheck;
  211619. overlapBuffer->dataLength = 2352 * framesToCheck;
  211620. overlapBuffer->dataStartOffset = 0;
  211621. }
  211622. else
  211623. {
  211624. overlapBuffer->startFrame = 0;
  211625. overlapBuffer->numFrames = 0;
  211626. overlapBuffer->dataLength = 0;
  211627. }
  211628. return true;
  211629. }
  211630. else
  211631. {
  211632. return read (rb);
  211633. }
  211634. }
  211635. int CDController::getLastIndex()
  211636. {
  211637. char qdata[100];
  211638. SRB_ExecSCSICmd s;
  211639. prepare (s);
  211640. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211641. s.SRB_BufLen = sizeof (qdata);
  211642. s.SRB_BufPointer = (BYTE*)qdata;
  211643. s.SRB_CDBLen = 12;
  211644. s.CDBByte[0] = 0x42;
  211645. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211646. s.CDBByte[2] = 64;
  211647. s.CDBByte[3] = 1; // get current position
  211648. s.CDBByte[7] = 0;
  211649. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211650. perform (s);
  211651. if (s.SRB_Status == SS_COMP)
  211652. return qdata[7];
  211653. return 0;
  211654. }
  211655. bool CDDeviceHandle::readTOC (TOC* lpToc)
  211656. {
  211657. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211658. SRB_ExecSCSICmd s;
  211659. zerostruct (s);
  211660. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211661. s.SRB_HaID = info.ha;
  211662. s.SRB_Target = info.tgt;
  211663. s.SRB_Lun = info.lun;
  211664. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211665. s.SRB_BufLen = 0x324;
  211666. s.SRB_BufPointer = (BYTE*)lpToc;
  211667. s.SRB_SenseLen = 0x0E;
  211668. s.SRB_CDBLen = 0x0A;
  211669. s.SRB_PostProc = event;
  211670. s.CDBByte[0] = 0x43;
  211671. s.CDBByte[1] = 0x00;
  211672. s.CDBByte[7] = 0x03;
  211673. s.CDBByte[8] = 0x24;
  211674. ResetEvent (event);
  211675. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211676. : fSendASPI32Command ((LPSRB)&s);
  211677. if (status == SS_PENDING)
  211678. WaitForSingleObject (event, 4000);
  211679. CloseHandle (event);
  211680. return (s.SRB_Status == SS_COMP);
  211681. }
  211682. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211683. CDReadBuffer* const overlapBuffer)
  211684. {
  211685. if (controller == 0)
  211686. {
  211687. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211688. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211689. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211690. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211691. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211692. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211693. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211694. }
  211695. buffer->index = 0;
  211696. if ((controller != 0)
  211697. && controller->readAudio (buffer, overlapBuffer))
  211698. {
  211699. if (buffer->wantsIndex)
  211700. buffer->index = controller->getLastIndex();
  211701. return true;
  211702. }
  211703. return false;
  211704. }
  211705. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211706. {
  211707. if (shouldBeOpen)
  211708. {
  211709. if (controller != 0)
  211710. {
  211711. controller->shutDown();
  211712. controller = 0;
  211713. }
  211714. if (scsiHandle != 0)
  211715. {
  211716. CloseHandle (scsiHandle);
  211717. scsiHandle = 0;
  211718. }
  211719. }
  211720. SRB_ExecSCSICmd s;
  211721. zerostruct (s);
  211722. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211723. s.SRB_HaID = info.ha;
  211724. s.SRB_Target = info.tgt;
  211725. s.SRB_Lun = info.lun;
  211726. s.SRB_SenseLen = SENSE_LEN;
  211727. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211728. s.SRB_BufLen = 0;
  211729. s.SRB_BufPointer = 0;
  211730. s.SRB_CDBLen = 12;
  211731. s.CDBByte[0] = 0x1b;
  211732. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211733. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211734. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211735. s.SRB_PostProc = event;
  211736. ResetEvent (event);
  211737. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211738. : fSendASPI32Command ((LPSRB)&s);
  211739. if (status == SS_PENDING)
  211740. WaitForSingleObject (event, 4000);
  211741. CloseHandle (event);
  211742. }
  211743. bool CDDeviceHandle::testController (const int type,
  211744. CDController* const newController,
  211745. CDReadBuffer* const rb)
  211746. {
  211747. controller = newController;
  211748. readType = (BYTE)type;
  211749. controller->deviceInfo = this;
  211750. controller->framesToCheck = 1;
  211751. controller->framesOverlap = 3;
  211752. bool passed = false;
  211753. memset (rb->buffer, 0xcd, rb->bufferSize);
  211754. if (controller->read (rb))
  211755. {
  211756. passed = true;
  211757. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211758. int wrong = 0;
  211759. for (int i = rb->dataLength / 4; --i >= 0;)
  211760. {
  211761. if (*p++ == (int) 0xcdcdcdcd)
  211762. {
  211763. if (++wrong == 4)
  211764. {
  211765. passed = false;
  211766. break;
  211767. }
  211768. }
  211769. else
  211770. {
  211771. wrong = 0;
  211772. }
  211773. }
  211774. }
  211775. if (! passed)
  211776. {
  211777. controller->shutDown();
  211778. controller = 0;
  211779. }
  211780. return passed;
  211781. }
  211782. void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211783. {
  211784. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211785. const int bufSize = 128;
  211786. BYTE buffer[bufSize];
  211787. zeromem (buffer, bufSize);
  211788. SRB_ExecSCSICmd s;
  211789. zerostruct (s);
  211790. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211791. s.SRB_HaID = ha;
  211792. s.SRB_Target = tgt;
  211793. s.SRB_Lun = lun;
  211794. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211795. s.SRB_BufLen = bufSize;
  211796. s.SRB_BufPointer = buffer;
  211797. s.SRB_SenseLen = SENSE_LEN;
  211798. s.SRB_CDBLen = 6;
  211799. s.SRB_PostProc = event;
  211800. s.CDBByte[0] = SCSI_INQUIRY;
  211801. s.CDBByte[4] = 100;
  211802. ResetEvent (event);
  211803. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211804. WaitForSingleObject (event, 4000);
  211805. CloseHandle (event);
  211806. if (s.SRB_Status == SS_COMP)
  211807. {
  211808. memcpy (dev->vendor, &buffer[8], 8);
  211809. memcpy (dev->productId, &buffer[16], 16);
  211810. memcpy (dev->rev, &buffer[32], 4);
  211811. memcpy (dev->vendorSpec, &buffer[36], 20);
  211812. }
  211813. }
  211814. int FindCDDevices (CDDeviceInfo* const list, int maxItems)
  211815. {
  211816. int count = 0;
  211817. if (usingScsi)
  211818. {
  211819. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211820. {
  211821. TCHAR drivePath[8];
  211822. drivePath[0] = driveLetter;
  211823. drivePath[1] = ':';
  211824. drivePath[2] = '\\';
  211825. drivePath[3] = 0;
  211826. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211827. {
  211828. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211829. if (h != INVALID_HANDLE_VALUE)
  211830. {
  211831. BYTE buffer[100], passThroughStruct[1024];
  211832. zeromem (buffer, sizeof (buffer));
  211833. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211834. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211835. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211836. p->spt.CdbLength = 6;
  211837. p->spt.SenseInfoLength = 24;
  211838. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211839. p->spt.DataTransferLength = 100;
  211840. p->spt.TimeOutValue = 2;
  211841. p->spt.DataBuffer = buffer;
  211842. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211843. p->spt.Cdb[0] = 0x12;
  211844. p->spt.Cdb[4] = 100;
  211845. DWORD bytesReturned = 0;
  211846. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211847. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211848. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211849. &bytesReturned, 0) != 0)
  211850. {
  211851. zeromem (&list[count], sizeof (CDDeviceInfo));
  211852. list[count].scsiDriveLetter = driveLetter;
  211853. memcpy (list[count].vendor, &buffer[8], 8);
  211854. memcpy (list[count].productId, &buffer[16], 16);
  211855. memcpy (list[count].rev, &buffer[32], 4);
  211856. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211857. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211858. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211859. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211860. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211861. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211862. &bytesReturned, 0) != 0)
  211863. {
  211864. list[count].ha = scsiAddr->PortNumber;
  211865. list[count].tgt = scsiAddr->TargetId;
  211866. list[count].lun = scsiAddr->Lun;
  211867. ++count;
  211868. }
  211869. }
  211870. CloseHandle (h);
  211871. }
  211872. }
  211873. }
  211874. }
  211875. else
  211876. {
  211877. const DWORD d = fGetASPI32SupportInfo();
  211878. BYTE status = HIBYTE (LOWORD (d));
  211879. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211880. return 0;
  211881. const int numAdapters = LOBYTE (LOWORD (d));
  211882. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211883. {
  211884. SRB_HAInquiry s;
  211885. zerostruct (s);
  211886. s.SRB_Cmd = SC_HA_INQUIRY;
  211887. s.SRB_HaID = ha;
  211888. fSendASPI32Command ((LPSRB)&s);
  211889. if (s.SRB_Status == SS_COMP)
  211890. {
  211891. maxItems = (int)s.HA_Unique[3];
  211892. if (maxItems == 0)
  211893. maxItems = 8;
  211894. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211895. {
  211896. for (BYTE lun = 0; lun < 8; ++lun)
  211897. {
  211898. SRB_GDEVBlock sb;
  211899. zerostruct (sb);
  211900. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211901. sb.SRB_HaID = ha;
  211902. sb.SRB_Target = tgt;
  211903. sb.SRB_Lun = lun;
  211904. fSendASPI32Command ((LPSRB) &sb);
  211905. if (sb.SRB_Status == SS_COMP
  211906. && sb.SRB_DeviceType == DTYPE_CROM)
  211907. {
  211908. zeromem (&list[count], sizeof (CDDeviceInfo));
  211909. list[count].ha = ha;
  211910. list[count].tgt = tgt;
  211911. list[count].lun = lun;
  211912. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211913. ++count;
  211914. }
  211915. }
  211916. }
  211917. }
  211918. }
  211919. }
  211920. return count;
  211921. }
  211922. static int ripperUsers = 0;
  211923. static bool initialisedOk = false;
  211924. class DeinitialiseTimer : private Timer,
  211925. private DeletedAtShutdown
  211926. {
  211927. DeinitialiseTimer (const DeinitialiseTimer&);
  211928. DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211929. public:
  211930. DeinitialiseTimer()
  211931. {
  211932. startTimer (4000);
  211933. }
  211934. ~DeinitialiseTimer()
  211935. {
  211936. if (--ripperUsers == 0)
  211937. DeinitialiseCDRipper();
  211938. }
  211939. void timerCallback()
  211940. {
  211941. delete this;
  211942. }
  211943. juce_UseDebuggingNewOperator
  211944. };
  211945. static void incUserCount()
  211946. {
  211947. if (ripperUsers++ == 0)
  211948. initialisedOk = InitialiseCDRipper();
  211949. }
  211950. static void decUserCount()
  211951. {
  211952. new DeinitialiseTimer();
  211953. }
  211954. struct CDDeviceWrapper
  211955. {
  211956. ScopedPointer<CDDeviceHandle> cdH;
  211957. ScopedPointer<CDReadBuffer> overlapBuffer;
  211958. bool jitter;
  211959. };
  211960. int getAddressOf (const TOCTRACK* const t)
  211961. {
  211962. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211963. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211964. }
  211965. static const int samplesPerFrame = 44100 / 75;
  211966. static const int bytesPerFrame = samplesPerFrame * 4;
  211967. CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211968. {
  211969. SRB_GDEVBlock s;
  211970. zerostruct (s);
  211971. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211972. s.SRB_HaID = device->ha;
  211973. s.SRB_Target = device->tgt;
  211974. s.SRB_Lun = device->lun;
  211975. if (usingScsi)
  211976. {
  211977. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  211978. if (h != INVALID_HANDLE_VALUE)
  211979. {
  211980. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  211981. cdh->scsiHandle = h;
  211982. return cdh;
  211983. }
  211984. }
  211985. else
  211986. {
  211987. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  211988. && s.SRB_DeviceType == DTYPE_CROM)
  211989. {
  211990. return new CDDeviceHandle (device);
  211991. }
  211992. }
  211993. return 0;
  211994. }
  211995. }
  211996. const StringArray AudioCDReader::getAvailableCDNames()
  211997. {
  211998. using namespace CDReaderHelpers;
  211999. StringArray results;
  212000. incUserCount();
  212001. if (initialisedOk)
  212002. {
  212003. CDDeviceInfo list[8];
  212004. const int num = FindCDDevices (list, 8);
  212005. decUserCount();
  212006. for (int i = 0; i < num; ++i)
  212007. {
  212008. String s;
  212009. if (list[i].scsiDriveLetter > 0)
  212010. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << ": ";
  212011. s << String (list[i].vendor).trim()
  212012. << ' ' << String (list[i].productId).trim()
  212013. << ' ' << String (list[i].rev).trim();
  212014. results.add (s);
  212015. }
  212016. }
  212017. return results;
  212018. }
  212019. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  212020. {
  212021. using namespace CDReaderHelpers;
  212022. incUserCount();
  212023. if (initialisedOk)
  212024. {
  212025. CDDeviceInfo list[8];
  212026. const int num = FindCDDevices (list, 8);
  212027. if (((unsigned int) deviceIndex) < (unsigned int) num)
  212028. {
  212029. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  212030. if (handle != 0)
  212031. {
  212032. CDDeviceWrapper* const d = new CDDeviceWrapper();
  212033. d->cdH = handle;
  212034. d->overlapBuffer = new CDReadBuffer(3);
  212035. return new AudioCDReader (d);
  212036. }
  212037. }
  212038. }
  212039. decUserCount();
  212040. return 0;
  212041. }
  212042. AudioCDReader::AudioCDReader (void* handle_)
  212043. : AudioFormatReader (0, "CD Audio"),
  212044. handle (handle_),
  212045. indexingEnabled (false),
  212046. lastIndex (0),
  212047. firstFrameInBuffer (0),
  212048. samplesInBuffer (0)
  212049. {
  212050. using namespace CDReaderHelpers;
  212051. jassert (handle_ != 0);
  212052. refreshTrackLengths();
  212053. sampleRate = 44100.0;
  212054. bitsPerSample = 16;
  212055. numChannels = 2;
  212056. usesFloatingPointData = false;
  212057. buffer.setSize (4 * bytesPerFrame, true);
  212058. }
  212059. AudioCDReader::~AudioCDReader()
  212060. {
  212061. using namespace CDReaderHelpers;
  212062. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212063. delete device;
  212064. decUserCount();
  212065. }
  212066. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  212067. int64 startSampleInFile, int numSamples)
  212068. {
  212069. using namespace CDReaderHelpers;
  212070. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212071. bool ok = true;
  212072. while (numSamples > 0)
  212073. {
  212074. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  212075. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  212076. if (startSampleInFile >= bufferStartSample
  212077. && startSampleInFile < bufferEndSample)
  212078. {
  212079. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  212080. int* const l = destSamples[0] + startOffsetInDestBuffer;
  212081. int* const r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  212082. const short* src = (const short*) buffer.getData();
  212083. src += 2 * (startSampleInFile - bufferStartSample);
  212084. for (int i = 0; i < toDo; ++i)
  212085. {
  212086. l[i] = src [i << 1] << 16;
  212087. if (r != 0)
  212088. r[i] = src [(i << 1) + 1] << 16;
  212089. }
  212090. startOffsetInDestBuffer += toDo;
  212091. startSampleInFile += toDo;
  212092. numSamples -= toDo;
  212093. }
  212094. else
  212095. {
  212096. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  212097. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  212098. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  212099. {
  212100. device->overlapBuffer->dataLength = 0;
  212101. device->overlapBuffer->startFrame = 0;
  212102. device->overlapBuffer->numFrames = 0;
  212103. device->jitter = false;
  212104. }
  212105. firstFrameInBuffer = frameNeeded;
  212106. lastIndex = 0;
  212107. CDReadBuffer readBuffer (framesInBuffer + 4);
  212108. readBuffer.wantsIndex = indexingEnabled;
  212109. int i;
  212110. for (i = 5; --i >= 0;)
  212111. {
  212112. readBuffer.startFrame = frameNeeded;
  212113. readBuffer.numFrames = framesInBuffer;
  212114. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  212115. break;
  212116. else
  212117. device->overlapBuffer->dataLength = 0;
  212118. }
  212119. if (i >= 0)
  212120. {
  212121. memcpy ((char*) buffer.getData(),
  212122. readBuffer.buffer + readBuffer.dataStartOffset,
  212123. readBuffer.dataLength);
  212124. samplesInBuffer = readBuffer.dataLength >> 2;
  212125. lastIndex = readBuffer.index;
  212126. }
  212127. else
  212128. {
  212129. int* l = destSamples[0] + startOffsetInDestBuffer;
  212130. int* r = numDestChannels > 1 ? (destSamples[1] + startOffsetInDestBuffer) : 0;
  212131. while (--numSamples >= 0)
  212132. {
  212133. *l++ = 0;
  212134. if (r != 0)
  212135. *r++ = 0;
  212136. }
  212137. // sometimes the read fails for just the very last couple of blocks, so
  212138. // we'll ignore and errors in the last half-second of the disk..
  212139. ok = startSampleInFile > (trackStartSamples [getNumTracks()] - 20000);
  212140. break;
  212141. }
  212142. }
  212143. }
  212144. return ok;
  212145. }
  212146. bool AudioCDReader::isCDStillPresent() const
  212147. {
  212148. using namespace CDReaderHelpers;
  212149. TOC toc;
  212150. zerostruct (toc);
  212151. return ((CDDeviceWrapper*) handle)->cdH->readTOC (&toc);
  212152. }
  212153. void AudioCDReader::refreshTrackLengths()
  212154. {
  212155. using namespace CDReaderHelpers;
  212156. trackStartSamples.clear();
  212157. zeromem (audioTracks, sizeof (audioTracks));
  212158. TOC toc;
  212159. zerostruct (toc);
  212160. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc))
  212161. {
  212162. int numTracks = 1 + toc.lastTrack - toc.firstTrack;
  212163. for (int i = 0; i <= numTracks; ++i)
  212164. {
  212165. trackStartSamples.add (samplesPerFrame * getAddressOf (&toc.tracks [i]));
  212166. audioTracks [i] = ((toc.tracks[i].ADR & 4) == 0);
  212167. }
  212168. }
  212169. lengthInSamples = getPositionOfTrackStart (getNumTracks());
  212170. }
  212171. bool AudioCDReader::isTrackAudio (int trackNum) const
  212172. {
  212173. return trackNum >= 0 && trackNum < getNumTracks() && audioTracks [trackNum];
  212174. }
  212175. void AudioCDReader::enableIndexScanning (bool b)
  212176. {
  212177. indexingEnabled = b;
  212178. }
  212179. int AudioCDReader::getLastIndex() const
  212180. {
  212181. return lastIndex;
  212182. }
  212183. const int framesPerIndexRead = 4;
  212184. int AudioCDReader::getIndexAt (int samplePos)
  212185. {
  212186. using namespace CDReaderHelpers;
  212187. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212188. const int frameNeeded = samplePos / samplesPerFrame;
  212189. device->overlapBuffer->dataLength = 0;
  212190. device->overlapBuffer->startFrame = 0;
  212191. device->overlapBuffer->numFrames = 0;
  212192. device->jitter = false;
  212193. firstFrameInBuffer = 0;
  212194. lastIndex = 0;
  212195. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  212196. readBuffer.wantsIndex = true;
  212197. int i;
  212198. for (i = 5; --i >= 0;)
  212199. {
  212200. readBuffer.startFrame = frameNeeded;
  212201. readBuffer.numFrames = framesPerIndexRead;
  212202. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212203. break;
  212204. }
  212205. if (i >= 0)
  212206. return readBuffer.index;
  212207. return -1;
  212208. }
  212209. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212210. {
  212211. using namespace CDReaderHelpers;
  212212. Array <int> indexes;
  212213. const int trackStart = getPositionOfTrackStart (trackNumber);
  212214. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212215. bool needToScan = true;
  212216. if (trackEnd - trackStart > 20 * 44100)
  212217. {
  212218. // check the end of the track for indexes before scanning the whole thing
  212219. needToScan = false;
  212220. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212221. bool seenAnIndex = false;
  212222. while (pos <= trackEnd - samplesPerFrame)
  212223. {
  212224. const int index = getIndexAt (pos);
  212225. if (index == 0)
  212226. {
  212227. // lead-out, so skip back a bit if we've not found any indexes yet..
  212228. if (seenAnIndex)
  212229. break;
  212230. pos -= 44100 * 5;
  212231. if (pos < trackStart)
  212232. break;
  212233. }
  212234. else
  212235. {
  212236. if (index > 0)
  212237. seenAnIndex = true;
  212238. if (index > 1)
  212239. {
  212240. needToScan = true;
  212241. break;
  212242. }
  212243. pos += samplesPerFrame * framesPerIndexRead;
  212244. }
  212245. }
  212246. }
  212247. if (needToScan)
  212248. {
  212249. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212250. int pos = trackStart;
  212251. int last = -1;
  212252. while (pos < trackEnd - samplesPerFrame * 10)
  212253. {
  212254. const int frameNeeded = pos / samplesPerFrame;
  212255. device->overlapBuffer->dataLength = 0;
  212256. device->overlapBuffer->startFrame = 0;
  212257. device->overlapBuffer->numFrames = 0;
  212258. device->jitter = false;
  212259. firstFrameInBuffer = 0;
  212260. CDReadBuffer readBuffer (4);
  212261. readBuffer.wantsIndex = true;
  212262. int i;
  212263. for (i = 5; --i >= 0;)
  212264. {
  212265. readBuffer.startFrame = frameNeeded;
  212266. readBuffer.numFrames = framesPerIndexRead;
  212267. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212268. break;
  212269. }
  212270. if (i < 0)
  212271. break;
  212272. if (readBuffer.index > last && readBuffer.index > 1)
  212273. {
  212274. last = readBuffer.index;
  212275. indexes.add (pos);
  212276. }
  212277. pos += samplesPerFrame * framesPerIndexRead;
  212278. }
  212279. indexes.removeValue (trackStart);
  212280. }
  212281. return indexes;
  212282. }
  212283. void AudioCDReader::ejectDisk()
  212284. {
  212285. using namespace CDReaderHelpers;
  212286. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212287. }
  212288. #endif
  212289. #if JUCE_USE_CDBURNER
  212290. namespace CDBurnerHelpers
  212291. {
  212292. IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212293. {
  212294. CoInitialize (0);
  212295. IDiscMaster* dm;
  212296. IDiscRecorder* result = 0;
  212297. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212298. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212299. IID_IDiscMaster,
  212300. (void**) &dm)))
  212301. {
  212302. if (SUCCEEDED (dm->Open()))
  212303. {
  212304. IEnumDiscRecorders* drEnum = 0;
  212305. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212306. {
  212307. IDiscRecorder* dr = 0;
  212308. DWORD dummy;
  212309. int index = 0;
  212310. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212311. {
  212312. if (indexToOpen == index)
  212313. {
  212314. result = dr;
  212315. break;
  212316. }
  212317. else if (list != 0)
  212318. {
  212319. BSTR path;
  212320. if (SUCCEEDED (dr->GetPath (&path)))
  212321. list->add ((const WCHAR*) path);
  212322. }
  212323. ++index;
  212324. dr->Release();
  212325. }
  212326. drEnum->Release();
  212327. }
  212328. if (master == 0)
  212329. dm->Close();
  212330. }
  212331. if (master != 0)
  212332. *master = dm;
  212333. else
  212334. dm->Release();
  212335. }
  212336. return result;
  212337. }
  212338. }
  212339. class AudioCDBurner::Pimpl : public ComBaseClassHelper <IDiscMasterProgressEvents>,
  212340. public Timer
  212341. {
  212342. public:
  212343. Pimpl (AudioCDBurner& owner_, IDiscMaster* discMaster_, IDiscRecorder* discRecorder_)
  212344. : owner (owner_), discMaster (discMaster_), discRecorder (discRecorder_), redbook (0),
  212345. listener (0), progress (0), shouldCancel (false)
  212346. {
  212347. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212348. jassert (SUCCEEDED (hr));
  212349. hr = discMaster->SetActiveDiscRecorder (discRecorder);
  212350. //jassert (SUCCEEDED (hr));
  212351. lastState = getDiskState();
  212352. startTimer (2000);
  212353. }
  212354. ~Pimpl() {}
  212355. void releaseObjects()
  212356. {
  212357. discRecorder->Close();
  212358. if (redbook != 0)
  212359. redbook->Release();
  212360. discRecorder->Release();
  212361. discMaster->Release();
  212362. Release();
  212363. }
  212364. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212365. {
  212366. if (listener != 0 && ! shouldCancel)
  212367. shouldCancel = listener->audioCDBurnProgress (progress);
  212368. *pbCancel = shouldCancel;
  212369. return S_OK;
  212370. }
  212371. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212372. {
  212373. progress = nCompleted / (float) nTotal;
  212374. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212375. return E_NOTIMPL;
  212376. }
  212377. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212378. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212379. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212380. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212381. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212382. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212383. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212384. class ScopedDiscOpener
  212385. {
  212386. public:
  212387. ScopedDiscOpener (Pimpl& p) : pimpl (p) { pimpl.discRecorder->OpenExclusive(); }
  212388. ~ScopedDiscOpener() { pimpl.discRecorder->Close(); }
  212389. private:
  212390. Pimpl& pimpl;
  212391. ScopedDiscOpener (const ScopedDiscOpener&);
  212392. ScopedDiscOpener& operator= (const ScopedDiscOpener&);
  212393. };
  212394. DiskState getDiskState()
  212395. {
  212396. const ScopedDiscOpener opener (*this);
  212397. long type, flags;
  212398. HRESULT hr = discRecorder->QueryMediaType (&type, &flags);
  212399. if (FAILED (hr))
  212400. return unknown;
  212401. if (type != 0 && (flags & MEDIA_WRITABLE) != 0)
  212402. return writableDiskPresent;
  212403. if (type == 0)
  212404. return noDisc;
  212405. else
  212406. return readOnlyDiskPresent;
  212407. }
  212408. int getIntProperty (const LPOLESTR name, const int defaultReturn) const
  212409. {
  212410. ComSmartPtr<IPropertyStorage> prop;
  212411. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212412. return defaultReturn;
  212413. PROPSPEC iPropSpec;
  212414. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212415. iPropSpec.lpwstr = name;
  212416. PROPVARIANT iPropVariant;
  212417. return FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant))
  212418. ? defaultReturn : (int) iPropVariant.lVal;
  212419. }
  212420. bool setIntProperty (const LPOLESTR name, const int value) const
  212421. {
  212422. ComSmartPtr<IPropertyStorage> prop;
  212423. if (FAILED (discRecorder->GetRecorderProperties (prop.resetAndGetPointerAddress())))
  212424. return false;
  212425. PROPSPEC iPropSpec;
  212426. iPropSpec.ulKind = PRSPEC_LPWSTR;
  212427. iPropSpec.lpwstr = name;
  212428. PROPVARIANT iPropVariant;
  212429. if (FAILED (prop->ReadMultiple (1, &iPropSpec, &iPropVariant)))
  212430. return false;
  212431. iPropVariant.lVal = (long) value;
  212432. return SUCCEEDED (prop->WriteMultiple (1, &iPropSpec, &iPropVariant, iPropVariant.vt))
  212433. && SUCCEEDED (discRecorder->SetRecorderProperties (prop));
  212434. }
  212435. void timerCallback()
  212436. {
  212437. const DiskState state = getDiskState();
  212438. if (state != lastState)
  212439. {
  212440. lastState = state;
  212441. owner.sendChangeMessage (&owner);
  212442. }
  212443. }
  212444. AudioCDBurner& owner;
  212445. DiskState lastState;
  212446. IDiscMaster* discMaster;
  212447. IDiscRecorder* discRecorder;
  212448. IRedbookDiscMaster* redbook;
  212449. AudioCDBurner::BurnProgressListener* listener;
  212450. float progress;
  212451. bool shouldCancel;
  212452. };
  212453. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212454. {
  212455. IDiscMaster* discMaster = 0;
  212456. IDiscRecorder* discRecorder = CDBurnerHelpers::enumCDBurners (0, deviceIndex, &discMaster);
  212457. if (discRecorder != 0)
  212458. pimpl = new Pimpl (*this, discMaster, discRecorder);
  212459. }
  212460. AudioCDBurner::~AudioCDBurner()
  212461. {
  212462. if (pimpl != 0)
  212463. pimpl.release()->releaseObjects();
  212464. }
  212465. const StringArray AudioCDBurner::findAvailableDevices()
  212466. {
  212467. StringArray devs;
  212468. CDBurnerHelpers::enumCDBurners (&devs, -1, 0);
  212469. return devs;
  212470. }
  212471. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212472. {
  212473. ScopedPointer<AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  212474. if (b->pimpl == 0)
  212475. b = 0;
  212476. return b.release();
  212477. }
  212478. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  212479. {
  212480. return pimpl->getDiskState();
  212481. }
  212482. bool AudioCDBurner::isDiskPresent() const
  212483. {
  212484. return getDiskState() == writableDiskPresent;
  212485. }
  212486. bool AudioCDBurner::openTray()
  212487. {
  212488. const Pimpl::ScopedDiscOpener opener (*pimpl);
  212489. return SUCCEEDED (pimpl->discRecorder->Eject());
  212490. }
  212491. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  212492. {
  212493. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  212494. DiskState oldState = getDiskState();
  212495. DiskState newState = oldState;
  212496. while (newState == oldState && Time::currentTimeMillis() < timeout)
  212497. {
  212498. newState = getDiskState();
  212499. Thread::sleep (jmin (250, (int) (timeout - Time::currentTimeMillis())));
  212500. }
  212501. return newState;
  212502. }
  212503. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  212504. {
  212505. Array<int> results;
  212506. const int maxSpeed = pimpl->getIntProperty (L"MaxWriteSpeed", 1);
  212507. const int speeds[] = { 1, 2, 4, 8, 12, 16, 20, 24, 32, 40, 64, 80 };
  212508. for (int i = 0; i < numElementsInArray (speeds); ++i)
  212509. if (speeds[i] <= maxSpeed)
  212510. results.add (speeds[i]);
  212511. results.addIfNotAlreadyThere (maxSpeed);
  212512. return results;
  212513. }
  212514. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  212515. {
  212516. if (pimpl->getIntProperty (L"BufferUnderrunFreeCapable", 0) == 0)
  212517. return false;
  212518. pimpl->setIntProperty (L"EnableBufferUnderrunFree", shouldBeEnabled ? -1 : 0);
  212519. return pimpl->getIntProperty (L"EnableBufferUnderrunFree", 0) != 0;
  212520. }
  212521. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212522. {
  212523. long blocksFree = 0;
  212524. pimpl->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212525. return blocksFree;
  212526. }
  212527. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener, bool ejectDiscAfterwards,
  212528. bool performFakeBurnForTesting, int writeSpeed)
  212529. {
  212530. pimpl->setIntProperty (L"WriteSpeed", writeSpeed > 0 ? writeSpeed : -1);
  212531. pimpl->listener = listener;
  212532. pimpl->progress = 0;
  212533. pimpl->shouldCancel = false;
  212534. UINT_PTR cookie;
  212535. HRESULT hr = pimpl->discMaster->ProgressAdvise ((AudioCDBurner::Pimpl*) pimpl, &cookie);
  212536. hr = pimpl->discMaster->RecordDisc (performFakeBurnForTesting,
  212537. ejectDiscAfterwards);
  212538. String error;
  212539. if (hr != S_OK)
  212540. {
  212541. const char* e = "Couldn't open or write to the CD device";
  212542. if (hr == IMAPI_E_USERABORT)
  212543. e = "User cancelled the write operation";
  212544. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212545. e = "No Disk present";
  212546. error = e;
  212547. }
  212548. pimpl->discMaster->ProgressUnadvise (cookie);
  212549. pimpl->listener = 0;
  212550. return error;
  212551. }
  212552. bool AudioCDBurner::addAudioTrack (AudioSource* audioSource, int numSamples)
  212553. {
  212554. if (audioSource == 0)
  212555. return false;
  212556. ScopedPointer<AudioSource> source (audioSource);
  212557. long bytesPerBlock;
  212558. HRESULT hr = pimpl->redbook->GetAudioBlockSize (&bytesPerBlock);
  212559. const int samplesPerBlock = bytesPerBlock / 4;
  212560. bool ok = true;
  212561. hr = pimpl->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212562. HeapBlock <byte> buffer (bytesPerBlock);
  212563. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212564. int samplesDone = 0;
  212565. source->prepareToPlay (samplesPerBlock, 44100.0);
  212566. while (ok)
  212567. {
  212568. {
  212569. AudioSourceChannelInfo info;
  212570. info.buffer = &sourceBuffer;
  212571. info.numSamples = samplesPerBlock;
  212572. info.startSample = 0;
  212573. sourceBuffer.clear();
  212574. source->getNextAudioBlock (info);
  212575. }
  212576. zeromem (buffer, bytesPerBlock);
  212577. typedef AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian,
  212578. AudioData::Interleaved, AudioData::NonConst> CDSampleFormat;
  212579. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian,
  212580. AudioData::NonInterleaved, AudioData::Const> SourceSampleFormat;
  212581. CDSampleFormat left (buffer, 2);
  212582. left.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (0)), samplesPerBlock);
  212583. CDSampleFormat right (buffer + 2, 2);
  212584. right.convertSamples (SourceSampleFormat (sourceBuffer.getSampleData (1)), samplesPerBlock);
  212585. hr = pimpl->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212586. if (FAILED (hr))
  212587. ok = false;
  212588. samplesDone += samplesPerBlock;
  212589. if (samplesDone >= numSamples)
  212590. break;
  212591. }
  212592. hr = pimpl->redbook->CloseAudioTrack();
  212593. return ok && hr == S_OK;
  212594. }
  212595. #endif
  212596. #endif
  212597. /*** End of inlined file: juce_win32_AudioCDReader.cpp ***/
  212598. /*** Start of inlined file: juce_win32_Midi.cpp ***/
  212599. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212600. // compiled on its own).
  212601. #if JUCE_INCLUDED_FILE
  212602. class MidiInCollector
  212603. {
  212604. public:
  212605. MidiInCollector (MidiInput* const input_,
  212606. MidiInputCallback& callback_)
  212607. : deviceHandle (0),
  212608. input (input_),
  212609. callback (callback_),
  212610. concatenator (4096),
  212611. isStarted (false),
  212612. startTime (0)
  212613. {
  212614. }
  212615. ~MidiInCollector()
  212616. {
  212617. stop();
  212618. if (deviceHandle != 0)
  212619. {
  212620. int count = 5;
  212621. while (--count >= 0)
  212622. {
  212623. if (midiInClose (deviceHandle) == MMSYSERR_NOERROR)
  212624. break;
  212625. Sleep (20);
  212626. }
  212627. }
  212628. }
  212629. void handleMessage (const uint32 message, const uint32 timeStamp)
  212630. {
  212631. if ((message & 0xff) >= 0x80 && isStarted)
  212632. {
  212633. concatenator.pushMidiData (&message, 3, convertTimeStamp (timeStamp), input, callback);
  212634. writeFinishedBlocks();
  212635. }
  212636. }
  212637. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp)
  212638. {
  212639. if (isStarted)
  212640. {
  212641. concatenator.pushMidiData (hdr->lpData, hdr->dwBytesRecorded, convertTimeStamp (timeStamp), input, callback);
  212642. writeFinishedBlocks();
  212643. }
  212644. }
  212645. void start()
  212646. {
  212647. jassert (deviceHandle != 0);
  212648. if (deviceHandle != 0 && ! isStarted)
  212649. {
  212650. activeMidiCollectors.addIfNotAlreadyThere (this);
  212651. for (int i = 0; i < (int) numHeaders; ++i)
  212652. headers[i].write (deviceHandle);
  212653. startTime = Time::getMillisecondCounter();
  212654. MMRESULT res = midiInStart (deviceHandle);
  212655. if (res == MMSYSERR_NOERROR)
  212656. {
  212657. concatenator.reset();
  212658. isStarted = true;
  212659. }
  212660. else
  212661. {
  212662. unprepareAllHeaders();
  212663. }
  212664. }
  212665. }
  212666. void stop()
  212667. {
  212668. if (isStarted)
  212669. {
  212670. isStarted = false;
  212671. midiInReset (deviceHandle);
  212672. midiInStop (deviceHandle);
  212673. activeMidiCollectors.removeValue (this);
  212674. unprepareAllHeaders();
  212675. concatenator.reset();
  212676. }
  212677. }
  212678. static void CALLBACK midiInCallback (HMIDIIN, UINT uMsg, DWORD_PTR dwInstance, DWORD_PTR midiMessage, DWORD_PTR timeStamp)
  212679. {
  212680. MidiInCollector* const collector = reinterpret_cast <MidiInCollector*> (dwInstance);
  212681. if (activeMidiCollectors.contains (collector))
  212682. {
  212683. if (uMsg == MIM_DATA)
  212684. collector->handleMessage ((uint32) midiMessage, (uint32) timeStamp);
  212685. else if (uMsg == MIM_LONGDATA)
  212686. collector->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212687. }
  212688. }
  212689. juce_UseDebuggingNewOperator
  212690. HMIDIIN deviceHandle;
  212691. private:
  212692. static Array <MidiInCollector*, CriticalSection> activeMidiCollectors;
  212693. MidiInput* input;
  212694. MidiInputCallback& callback;
  212695. MidiDataConcatenator concatenator;
  212696. bool volatile isStarted;
  212697. uint32 startTime;
  212698. class MidiHeader
  212699. {
  212700. public:
  212701. MidiHeader()
  212702. {
  212703. zerostruct (hdr);
  212704. hdr.lpData = data;
  212705. hdr.dwBufferLength = numElementsInArray (data);
  212706. }
  212707. void write (HMIDIIN deviceHandle)
  212708. {
  212709. hdr.dwBytesRecorded = 0;
  212710. MMRESULT res = midiInPrepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212711. res = midiInAddBuffer (deviceHandle, &hdr, sizeof (hdr));
  212712. }
  212713. void writeIfFinished (HMIDIIN deviceHandle)
  212714. {
  212715. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212716. {
  212717. MMRESULT res = midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr));
  212718. (void) res;
  212719. write (deviceHandle);
  212720. }
  212721. }
  212722. void unprepare (HMIDIIN deviceHandle)
  212723. {
  212724. if ((hdr.dwFlags & WHDR_DONE) != 0)
  212725. {
  212726. int c = 10;
  212727. while (--c >= 0 && midiInUnprepareHeader (deviceHandle, &hdr, sizeof (hdr)) == MIDIERR_STILLPLAYING)
  212728. Thread::sleep (20);
  212729. jassert (c >= 0);
  212730. }
  212731. }
  212732. private:
  212733. MIDIHDR hdr;
  212734. char data [256];
  212735. MidiHeader (const MidiHeader&);
  212736. MidiHeader& operator= (const MidiHeader&);
  212737. };
  212738. enum { numHeaders = 32 };
  212739. MidiHeader headers [numHeaders];
  212740. void writeFinishedBlocks()
  212741. {
  212742. for (int i = 0; i < (int) numHeaders; ++i)
  212743. headers[i].writeIfFinished (deviceHandle);
  212744. }
  212745. void unprepareAllHeaders()
  212746. {
  212747. for (int i = 0; i < (int) numHeaders; ++i)
  212748. headers[i].unprepare (deviceHandle);
  212749. }
  212750. double convertTimeStamp (uint32 timeStamp)
  212751. {
  212752. timeStamp += startTime;
  212753. const uint32 now = Time::getMillisecondCounter();
  212754. if (timeStamp > now)
  212755. {
  212756. if (timeStamp > now + 2)
  212757. --startTime;
  212758. timeStamp = now;
  212759. }
  212760. return timeStamp * 0.001;
  212761. }
  212762. MidiInCollector (const MidiInCollector&);
  212763. MidiInCollector& operator= (const MidiInCollector&);
  212764. };
  212765. Array <MidiInCollector*, CriticalSection> MidiInCollector::activeMidiCollectors;
  212766. const StringArray MidiInput::getDevices()
  212767. {
  212768. StringArray s;
  212769. const int num = midiInGetNumDevs();
  212770. for (int i = 0; i < num; ++i)
  212771. {
  212772. MIDIINCAPS mc;
  212773. zerostruct (mc);
  212774. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212775. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212776. }
  212777. return s;
  212778. }
  212779. int MidiInput::getDefaultDeviceIndex()
  212780. {
  212781. return 0;
  212782. }
  212783. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212784. {
  212785. if (callback == 0)
  212786. return 0;
  212787. UINT deviceId = MIDI_MAPPER;
  212788. int n = 0;
  212789. String name;
  212790. const int num = midiInGetNumDevs();
  212791. for (int i = 0; i < num; ++i)
  212792. {
  212793. MIDIINCAPS mc;
  212794. zerostruct (mc);
  212795. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212796. {
  212797. if (index == n)
  212798. {
  212799. deviceId = i;
  212800. name = String (mc.szPname, numElementsInArray (mc.szPname));
  212801. break;
  212802. }
  212803. ++n;
  212804. }
  212805. }
  212806. ScopedPointer <MidiInput> in (new MidiInput (name));
  212807. ScopedPointer <MidiInCollector> collector (new MidiInCollector (in, *callback));
  212808. HMIDIIN h;
  212809. HRESULT err = midiInOpen (&h, deviceId,
  212810. (DWORD_PTR) &MidiInCollector::midiInCallback,
  212811. (DWORD_PTR) (MidiInCollector*) collector,
  212812. CALLBACK_FUNCTION);
  212813. if (err == MMSYSERR_NOERROR)
  212814. {
  212815. collector->deviceHandle = h;
  212816. in->internal = collector.release();
  212817. return in.release();
  212818. }
  212819. return 0;
  212820. }
  212821. MidiInput::MidiInput (const String& name_)
  212822. : name (name_),
  212823. internal (0)
  212824. {
  212825. }
  212826. MidiInput::~MidiInput()
  212827. {
  212828. delete static_cast <MidiInCollector*> (internal);
  212829. }
  212830. void MidiInput::start()
  212831. {
  212832. static_cast <MidiInCollector*> (internal)->start();
  212833. }
  212834. void MidiInput::stop()
  212835. {
  212836. static_cast <MidiInCollector*> (internal)->stop();
  212837. }
  212838. struct MidiOutHandle
  212839. {
  212840. int refCount;
  212841. UINT deviceId;
  212842. HMIDIOUT handle;
  212843. static Array<MidiOutHandle*> activeHandles;
  212844. juce_UseDebuggingNewOperator
  212845. };
  212846. Array<MidiOutHandle*> MidiOutHandle::activeHandles;
  212847. const StringArray MidiOutput::getDevices()
  212848. {
  212849. StringArray s;
  212850. const int num = midiOutGetNumDevs();
  212851. for (int i = 0; i < num; ++i)
  212852. {
  212853. MIDIOUTCAPS mc;
  212854. zerostruct (mc);
  212855. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212856. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212857. }
  212858. return s;
  212859. }
  212860. int MidiOutput::getDefaultDeviceIndex()
  212861. {
  212862. const int num = midiOutGetNumDevs();
  212863. int n = 0;
  212864. for (int i = 0; i < num; ++i)
  212865. {
  212866. MIDIOUTCAPS mc;
  212867. zerostruct (mc);
  212868. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212869. {
  212870. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212871. return n;
  212872. ++n;
  212873. }
  212874. }
  212875. return 0;
  212876. }
  212877. MidiOutput* MidiOutput::openDevice (int index)
  212878. {
  212879. UINT deviceId = MIDI_MAPPER;
  212880. const int num = midiOutGetNumDevs();
  212881. int i, n = 0;
  212882. for (i = 0; i < num; ++i)
  212883. {
  212884. MIDIOUTCAPS mc;
  212885. zerostruct (mc);
  212886. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212887. {
  212888. // use the microsoft sw synth as a default - best not to allow deviceId
  212889. // to be MIDI_MAPPER, or else device sharing breaks
  212890. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase ("microsoft"))
  212891. deviceId = i;
  212892. if (index == n)
  212893. {
  212894. deviceId = i;
  212895. break;
  212896. }
  212897. ++n;
  212898. }
  212899. }
  212900. for (i = MidiOutHandle::activeHandles.size(); --i >= 0;)
  212901. {
  212902. MidiOutHandle* const han = MidiOutHandle::activeHandles.getUnchecked(i);
  212903. if (han != 0 && han->deviceId == deviceId)
  212904. {
  212905. han->refCount++;
  212906. MidiOutput* const out = new MidiOutput();
  212907. out->internal = han;
  212908. return out;
  212909. }
  212910. }
  212911. for (i = 4; --i >= 0;)
  212912. {
  212913. HMIDIOUT h = 0;
  212914. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212915. if (res == MMSYSERR_NOERROR)
  212916. {
  212917. MidiOutHandle* const han = new MidiOutHandle();
  212918. han->deviceId = deviceId;
  212919. han->refCount = 1;
  212920. han->handle = h;
  212921. MidiOutHandle::activeHandles.add (han);
  212922. MidiOutput* const out = new MidiOutput();
  212923. out->internal = han;
  212924. return out;
  212925. }
  212926. else if (res == MMSYSERR_ALLOCATED)
  212927. {
  212928. Sleep (100);
  212929. }
  212930. else
  212931. {
  212932. break;
  212933. }
  212934. }
  212935. return 0;
  212936. }
  212937. MidiOutput::~MidiOutput()
  212938. {
  212939. MidiOutHandle* const h = static_cast <MidiOutHandle*> (internal);
  212940. if (MidiOutHandle::activeHandles.contains (h) && --(h->refCount) == 0)
  212941. {
  212942. midiOutClose (h->handle);
  212943. MidiOutHandle::activeHandles.removeValue (h);
  212944. delete h;
  212945. }
  212946. }
  212947. void MidiOutput::reset()
  212948. {
  212949. const MidiOutHandle* const h = static_cast <const MidiOutHandle*> (internal);
  212950. midiOutReset (h->handle);
  212951. }
  212952. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  212953. {
  212954. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212955. DWORD n;
  212956. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  212957. {
  212958. const unsigned short* const nn = reinterpret_cast<const unsigned short*> (&n);
  212959. rightVol = nn[0] / (float) 0xffff;
  212960. leftVol = nn[1] / (float) 0xffff;
  212961. return true;
  212962. }
  212963. else
  212964. {
  212965. rightVol = leftVol = 1.0f;
  212966. return false;
  212967. }
  212968. }
  212969. void MidiOutput::setVolume (float leftVol, float rightVol)
  212970. {
  212971. const MidiOutHandle* const handle = static_cast <MidiOutHandle*> (internal);
  212972. DWORD n;
  212973. unsigned short* const nn = reinterpret_cast<unsigned short*> (&n);
  212974. nn[0] = (unsigned short) jlimit (0, 0xffff, (int) (rightVol * 0xffff));
  212975. nn[1] = (unsigned short) jlimit (0, 0xffff, (int) (leftVol * 0xffff));
  212976. midiOutSetVolume (handle->handle, n);
  212977. }
  212978. void MidiOutput::sendMessageNow (const MidiMessage& message)
  212979. {
  212980. const MidiOutHandle* const handle = static_cast <const MidiOutHandle*> (internal);
  212981. if (message.getRawDataSize() > 3
  212982. || message.isSysEx())
  212983. {
  212984. MIDIHDR h;
  212985. zerostruct (h);
  212986. h.lpData = (char*) message.getRawData();
  212987. h.dwBufferLength = message.getRawDataSize();
  212988. h.dwBytesRecorded = message.getRawDataSize();
  212989. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  212990. {
  212991. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  212992. if (res == MMSYSERR_NOERROR)
  212993. {
  212994. while ((h.dwFlags & MHDR_DONE) == 0)
  212995. Sleep (1);
  212996. int count = 500; // 1 sec timeout
  212997. while (--count >= 0)
  212998. {
  212999. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  213000. if (res == MIDIERR_STILLPLAYING)
  213001. Sleep (2);
  213002. else
  213003. break;
  213004. }
  213005. }
  213006. }
  213007. }
  213008. else
  213009. {
  213010. midiOutShortMsg (handle->handle,
  213011. *(unsigned int*) message.getRawData());
  213012. }
  213013. }
  213014. #endif
  213015. /*** End of inlined file: juce_win32_Midi.cpp ***/
  213016. /*** Start of inlined file: juce_win32_ASIO.cpp ***/
  213017. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213018. // compiled on its own).
  213019. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  213020. #undef WINDOWS
  213021. // #define ASIO_DEBUGGING 1
  213022. #undef log
  213023. #if ASIO_DEBUGGING
  213024. #define log(a) { Logger::writeToLog (a); DBG (a) }
  213025. #else
  213026. #define log(a) {}
  213027. #endif
  213028. /* The ASIO SDK *should* declare its callback functions as being __cdecl, but different versions seem
  213029. to be pretty random about whether or not they do this. If you hit an error using these functions
  213030. it'll be because you're trying to build using __stdcall, in which case you'd need to either get hold of
  213031. an ASIO SDK which correctly specifies __cdecl, or add the __cdecl keyword to its functions yourself.
  213032. */
  213033. #define JUCE_ASIOCALLBACK __cdecl
  213034. namespace ASIODebugging
  213035. {
  213036. #if ASIO_DEBUGGING
  213037. static void log (const String& context, long error)
  213038. {
  213039. String err ("unknown error");
  213040. if (error == ASE_NotPresent) err = "Not Present";
  213041. else if (error == ASE_HWMalfunction) err = "Hardware Malfunction";
  213042. else if (error == ASE_InvalidParameter) err = "Invalid Parameter";
  213043. else if (error == ASE_InvalidMode) err = "Invalid Mode";
  213044. else if (error == ASE_SPNotAdvancing) err = "Sample position not advancing";
  213045. else if (error == ASE_NoClock) err = "No Clock";
  213046. else if (error == ASE_NoMemory) err = "Out of memory";
  213047. log ("!!error: " + context + " - " + err);
  213048. }
  213049. #define logError(a, b) ASIODebugging::log ((a), (b))
  213050. #else
  213051. #define logError(a, b) {}
  213052. #endif
  213053. }
  213054. class ASIOAudioIODevice;
  213055. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  213056. static const int maxASIOChannels = 160;
  213057. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  213058. private Timer
  213059. {
  213060. public:
  213061. Component ourWindow;
  213062. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber,
  213063. const String& optionalDllForDirectLoading_)
  213064. : AudioIODevice (name_, "ASIO"),
  213065. asioObject (0),
  213066. classId (classId_),
  213067. optionalDllForDirectLoading (optionalDllForDirectLoading_),
  213068. currentBitDepth (16),
  213069. currentSampleRate (0),
  213070. isOpen_ (false),
  213071. isStarted (false),
  213072. postOutput (true),
  213073. insideControlPanelModalLoop (false),
  213074. shouldUsePreferredSize (false)
  213075. {
  213076. name = name_;
  213077. ourWindow.addToDesktop (0);
  213078. windowHandle = ourWindow.getWindowHandle();
  213079. jassert (currentASIODev [slotNumber] == 0);
  213080. currentASIODev [slotNumber] = this;
  213081. openDevice();
  213082. }
  213083. ~ASIOAudioIODevice()
  213084. {
  213085. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213086. if (currentASIODev[i] == this)
  213087. currentASIODev[i] = 0;
  213088. close();
  213089. log ("ASIO - exiting");
  213090. removeCurrentDriver();
  213091. }
  213092. void updateSampleRates()
  213093. {
  213094. // find a list of sample rates..
  213095. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  213096. sampleRates.clear();
  213097. if (asioObject != 0)
  213098. {
  213099. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  213100. {
  213101. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  213102. if (err == 0)
  213103. {
  213104. sampleRates.add ((int) possibleSampleRates[index]);
  213105. log ("rate: " + String ((int) possibleSampleRates[index]));
  213106. }
  213107. else if (err != ASE_NoClock)
  213108. {
  213109. logError ("CanSampleRate", err);
  213110. }
  213111. }
  213112. if (sampleRates.size() == 0)
  213113. {
  213114. double cr = 0;
  213115. const long err = asioObject->getSampleRate (&cr);
  213116. log ("No sample rates supported - current rate: " + String ((int) cr));
  213117. if (err == 0)
  213118. sampleRates.add ((int) cr);
  213119. }
  213120. }
  213121. }
  213122. const StringArray getOutputChannelNames() { return outputChannelNames; }
  213123. const StringArray getInputChannelNames() { return inputChannelNames; }
  213124. int getNumSampleRates() { return sampleRates.size(); }
  213125. double getSampleRate (int index) { return sampleRates [index]; }
  213126. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  213127. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  213128. int getDefaultBufferSize() { return preferredSize; }
  213129. const String open (const BigInteger& inputChannels,
  213130. const BigInteger& outputChannels,
  213131. double sr,
  213132. int bufferSizeSamples)
  213133. {
  213134. close();
  213135. currentCallback = 0;
  213136. if (bufferSizeSamples <= 0)
  213137. shouldUsePreferredSize = true;
  213138. if (asioObject == 0 || ! isASIOOpen)
  213139. {
  213140. log ("Warning: device not open");
  213141. const String err (openDevice());
  213142. if (asioObject == 0 || ! isASIOOpen)
  213143. return err;
  213144. }
  213145. isStarted = false;
  213146. bufferIndex = -1;
  213147. long err = 0;
  213148. long newPreferredSize = 0;
  213149. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  213150. minSize = 0;
  213151. maxSize = 0;
  213152. newPreferredSize = 0;
  213153. granularity = 0;
  213154. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  213155. {
  213156. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  213157. shouldUsePreferredSize = true;
  213158. preferredSize = newPreferredSize;
  213159. }
  213160. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  213161. // dynamic changes to the buffer size...
  213162. shouldUsePreferredSize = shouldUsePreferredSize
  213163. || getName().containsIgnoreCase ("Digidesign");
  213164. if (shouldUsePreferredSize)
  213165. {
  213166. log ("Using preferred size for buffer..");
  213167. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213168. {
  213169. bufferSizeSamples = preferredSize;
  213170. }
  213171. else
  213172. {
  213173. bufferSizeSamples = 1024;
  213174. logError ("GetBufferSize1", err);
  213175. }
  213176. shouldUsePreferredSize = false;
  213177. }
  213178. int sampleRate = roundDoubleToInt (sr);
  213179. currentSampleRate = sampleRate;
  213180. currentBlockSizeSamples = bufferSizeSamples;
  213181. currentChansOut.clear();
  213182. currentChansIn.clear();
  213183. zeromem (inBuffers, sizeof (inBuffers));
  213184. zeromem (outBuffers, sizeof (outBuffers));
  213185. updateSampleRates();
  213186. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  213187. sampleRate = sampleRates[0];
  213188. jassert (sampleRate != 0);
  213189. if (sampleRate == 0)
  213190. sampleRate = 44100;
  213191. long numSources = 32;
  213192. ASIOClockSource clocks[32];
  213193. zeromem (clocks, sizeof (clocks));
  213194. asioObject->getClockSources (clocks, &numSources);
  213195. bool isSourceSet = false;
  213196. // careful not to remove this loop because it does more than just logging!
  213197. int i;
  213198. for (i = 0; i < numSources; ++i)
  213199. {
  213200. String s ("clock: ");
  213201. s += clocks[i].name;
  213202. if (clocks[i].isCurrentSource)
  213203. {
  213204. isSourceSet = true;
  213205. s << " (cur)";
  213206. }
  213207. log (s);
  213208. }
  213209. if (numSources > 1 && ! isSourceSet)
  213210. {
  213211. log ("setting clock source");
  213212. asioObject->setClockSource (clocks[0].index);
  213213. Thread::sleep (20);
  213214. }
  213215. else
  213216. {
  213217. if (numSources == 0)
  213218. {
  213219. log ("ASIO - no clock sources!");
  213220. }
  213221. }
  213222. double cr = 0;
  213223. err = asioObject->getSampleRate (&cr);
  213224. if (err == 0)
  213225. {
  213226. currentSampleRate = cr;
  213227. }
  213228. else
  213229. {
  213230. logError ("GetSampleRate", err);
  213231. currentSampleRate = 0;
  213232. }
  213233. error = String::empty;
  213234. needToReset = false;
  213235. isReSync = false;
  213236. err = 0;
  213237. bool buffersCreated = false;
  213238. if (currentSampleRate != sampleRate)
  213239. {
  213240. log ("ASIO samplerate: " + String (currentSampleRate) + " to " + String (sampleRate));
  213241. err = asioObject->setSampleRate (sampleRate);
  213242. if (err == ASE_NoClock && numSources > 0)
  213243. {
  213244. log ("trying to set a clock source..");
  213245. Thread::sleep (10);
  213246. err = asioObject->setClockSource (clocks[0].index);
  213247. if (err != 0)
  213248. {
  213249. logError ("SetClock", err);
  213250. }
  213251. Thread::sleep (10);
  213252. err = asioObject->setSampleRate (sampleRate);
  213253. }
  213254. }
  213255. if (err == 0)
  213256. {
  213257. currentSampleRate = sampleRate;
  213258. if (needToReset)
  213259. {
  213260. if (isReSync)
  213261. {
  213262. log ("Resync request");
  213263. }
  213264. log ("! Resetting ASIO after sample rate change");
  213265. removeCurrentDriver();
  213266. loadDriver();
  213267. const String error (initDriver());
  213268. if (error.isNotEmpty())
  213269. {
  213270. log ("ASIOInit: " + error);
  213271. }
  213272. needToReset = false;
  213273. isReSync = false;
  213274. }
  213275. numActiveInputChans = 0;
  213276. numActiveOutputChans = 0;
  213277. ASIOBufferInfo* info = bufferInfos;
  213278. int i;
  213279. for (i = 0; i < totalNumInputChans; ++i)
  213280. {
  213281. if (inputChannels[i])
  213282. {
  213283. currentChansIn.setBit (i);
  213284. info->isInput = 1;
  213285. info->channelNum = i;
  213286. info->buffers[0] = info->buffers[1] = 0;
  213287. ++info;
  213288. ++numActiveInputChans;
  213289. }
  213290. }
  213291. for (i = 0; i < totalNumOutputChans; ++i)
  213292. {
  213293. if (outputChannels[i])
  213294. {
  213295. currentChansOut.setBit (i);
  213296. info->isInput = 0;
  213297. info->channelNum = i;
  213298. info->buffers[0] = info->buffers[1] = 0;
  213299. ++info;
  213300. ++numActiveOutputChans;
  213301. }
  213302. }
  213303. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213304. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213305. if (currentASIODev[0] == this)
  213306. {
  213307. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213308. callbacks.asioMessage = &asioMessagesCallback0;
  213309. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213310. }
  213311. else if (currentASIODev[1] == this)
  213312. {
  213313. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213314. callbacks.asioMessage = &asioMessagesCallback1;
  213315. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213316. }
  213317. else if (currentASIODev[2] == this)
  213318. {
  213319. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213320. callbacks.asioMessage = &asioMessagesCallback2;
  213321. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213322. }
  213323. else
  213324. {
  213325. jassertfalse;
  213326. }
  213327. log ("disposing buffers");
  213328. err = asioObject->disposeBuffers();
  213329. log ("creating buffers: " + String (totalBuffers) + ", " + String (currentBlockSizeSamples));
  213330. err = asioObject->createBuffers (bufferInfos,
  213331. totalBuffers,
  213332. currentBlockSizeSamples,
  213333. &callbacks);
  213334. if (err != 0)
  213335. {
  213336. currentBlockSizeSamples = preferredSize;
  213337. logError ("create buffers 2", err);
  213338. asioObject->disposeBuffers();
  213339. err = asioObject->createBuffers (bufferInfos,
  213340. totalBuffers,
  213341. currentBlockSizeSamples,
  213342. &callbacks);
  213343. }
  213344. if (err == 0)
  213345. {
  213346. buffersCreated = true;
  213347. tempBuffer.calloc (totalBuffers * currentBlockSizeSamples + 32);
  213348. int n = 0;
  213349. Array <int> types;
  213350. currentBitDepth = 16;
  213351. for (i = 0; i < jmin ((int) totalNumInputChans, maxASIOChannels); ++i)
  213352. {
  213353. if (inputChannels[i])
  213354. {
  213355. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213356. ASIOChannelInfo channelInfo;
  213357. zerostruct (channelInfo);
  213358. channelInfo.channel = i;
  213359. channelInfo.isInput = 1;
  213360. asioObject->getChannelInfo (&channelInfo);
  213361. types.addIfNotAlreadyThere (channelInfo.type);
  213362. typeToFormatParameters (channelInfo.type,
  213363. inputChannelBitDepths[n],
  213364. inputChannelBytesPerSample[n],
  213365. inputChannelIsFloat[n],
  213366. inputChannelLittleEndian[n]);
  213367. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213368. ++n;
  213369. }
  213370. }
  213371. jassert (numActiveInputChans == n);
  213372. n = 0;
  213373. for (i = 0; i < jmin ((int) totalNumOutputChans, maxASIOChannels); ++i)
  213374. {
  213375. if (outputChannels[i])
  213376. {
  213377. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213378. ASIOChannelInfo channelInfo;
  213379. zerostruct (channelInfo);
  213380. channelInfo.channel = i;
  213381. channelInfo.isInput = 0;
  213382. asioObject->getChannelInfo (&channelInfo);
  213383. types.addIfNotAlreadyThere (channelInfo.type);
  213384. typeToFormatParameters (channelInfo.type,
  213385. outputChannelBitDepths[n],
  213386. outputChannelBytesPerSample[n],
  213387. outputChannelIsFloat[n],
  213388. outputChannelLittleEndian[n]);
  213389. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213390. ++n;
  213391. }
  213392. }
  213393. jassert (numActiveOutputChans == n);
  213394. for (i = types.size(); --i >= 0;)
  213395. {
  213396. log ("channel format: " + String (types[i]));
  213397. }
  213398. jassert (n <= totalBuffers);
  213399. for (i = 0; i < numActiveOutputChans; ++i)
  213400. {
  213401. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213402. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213403. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213404. {
  213405. log ("!! Null buffers");
  213406. }
  213407. else
  213408. {
  213409. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213410. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213411. }
  213412. }
  213413. inputLatency = outputLatency = 0;
  213414. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213415. {
  213416. log ("ASIO - no latencies");
  213417. }
  213418. else
  213419. {
  213420. log ("ASIO latencies: " + String ((int) outputLatency) + ", " + String ((int) inputLatency));
  213421. }
  213422. isOpen_ = true;
  213423. log ("starting ASIO");
  213424. calledback = false;
  213425. err = asioObject->start();
  213426. if (err != 0)
  213427. {
  213428. isOpen_ = false;
  213429. log ("ASIO - stop on failure");
  213430. Thread::sleep (10);
  213431. asioObject->stop();
  213432. error = "Can't start device";
  213433. Thread::sleep (10);
  213434. }
  213435. else
  213436. {
  213437. int count = 300;
  213438. while (--count > 0 && ! calledback)
  213439. Thread::sleep (10);
  213440. isStarted = true;
  213441. if (! calledback)
  213442. {
  213443. error = "Device didn't start correctly";
  213444. log ("ASIO didn't callback - stopping..");
  213445. asioObject->stop();
  213446. }
  213447. }
  213448. }
  213449. else
  213450. {
  213451. error = "Can't create i/o buffers";
  213452. }
  213453. }
  213454. else
  213455. {
  213456. error = "Can't set sample rate: ";
  213457. error << sampleRate;
  213458. }
  213459. if (error.isNotEmpty())
  213460. {
  213461. logError (error, err);
  213462. if (asioObject != 0 && buffersCreated)
  213463. asioObject->disposeBuffers();
  213464. Thread::sleep (20);
  213465. isStarted = false;
  213466. isOpen_ = false;
  213467. const String errorCopy (error);
  213468. close(); // (this resets the error string)
  213469. error = errorCopy;
  213470. }
  213471. needToReset = false;
  213472. isReSync = false;
  213473. return error;
  213474. }
  213475. void close()
  213476. {
  213477. error = String::empty;
  213478. stopTimer();
  213479. stop();
  213480. if (isASIOOpen && isOpen_)
  213481. {
  213482. const ScopedLock sl (callbackLock);
  213483. isOpen_ = false;
  213484. isStarted = false;
  213485. needToReset = false;
  213486. isReSync = false;
  213487. log ("ASIO - stopping");
  213488. if (asioObject != 0)
  213489. {
  213490. Thread::sleep (20);
  213491. asioObject->stop();
  213492. Thread::sleep (10);
  213493. asioObject->disposeBuffers();
  213494. }
  213495. Thread::sleep (10);
  213496. }
  213497. }
  213498. bool isOpen() { return isOpen_ || insideControlPanelModalLoop; }
  213499. bool isPlaying() { return isASIOOpen && (currentCallback != 0); }
  213500. int getCurrentBufferSizeSamples() { return currentBlockSizeSamples; }
  213501. double getCurrentSampleRate() { return currentSampleRate; }
  213502. int getCurrentBitDepth() { return currentBitDepth; }
  213503. const BigInteger getActiveOutputChannels() const { return currentChansOut; }
  213504. const BigInteger getActiveInputChannels() const { return currentChansIn; }
  213505. int getOutputLatencyInSamples() { return outputLatency + currentBlockSizeSamples / 4; }
  213506. int getInputLatencyInSamples() { return inputLatency + currentBlockSizeSamples / 4; }
  213507. void start (AudioIODeviceCallback* callback)
  213508. {
  213509. if (callback != 0)
  213510. {
  213511. callback->audioDeviceAboutToStart (this);
  213512. const ScopedLock sl (callbackLock);
  213513. currentCallback = callback;
  213514. }
  213515. }
  213516. void stop()
  213517. {
  213518. AudioIODeviceCallback* const lastCallback = currentCallback;
  213519. {
  213520. const ScopedLock sl (callbackLock);
  213521. currentCallback = 0;
  213522. }
  213523. if (lastCallback != 0)
  213524. lastCallback->audioDeviceStopped();
  213525. }
  213526. const String getLastError() { return error; }
  213527. bool hasControlPanel() const { return true; }
  213528. bool showControlPanel()
  213529. {
  213530. log ("ASIO - showing control panel");
  213531. Component modalWindow (String::empty);
  213532. modalWindow.setOpaque (true);
  213533. modalWindow.addToDesktop (0);
  213534. modalWindow.enterModalState();
  213535. bool done = false;
  213536. JUCE_TRY
  213537. {
  213538. // are there are devices that need to be closed before showing their control panel?
  213539. // close();
  213540. insideControlPanelModalLoop = true;
  213541. const uint32 started = Time::getMillisecondCounter();
  213542. if (asioObject != 0)
  213543. {
  213544. asioObject->controlPanel();
  213545. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213546. log ("spent: " + String (spent));
  213547. if (spent > 300)
  213548. {
  213549. shouldUsePreferredSize = true;
  213550. done = true;
  213551. }
  213552. }
  213553. }
  213554. JUCE_CATCH_ALL
  213555. insideControlPanelModalLoop = false;
  213556. return done;
  213557. }
  213558. void resetRequest() throw()
  213559. {
  213560. needToReset = true;
  213561. }
  213562. void resyncRequest() throw()
  213563. {
  213564. needToReset = true;
  213565. isReSync = true;
  213566. }
  213567. void timerCallback()
  213568. {
  213569. if (! insideControlPanelModalLoop)
  213570. {
  213571. stopTimer();
  213572. // used to cause a reset
  213573. log ("! ASIO restart request!");
  213574. if (isOpen_)
  213575. {
  213576. AudioIODeviceCallback* const oldCallback = currentCallback;
  213577. close();
  213578. open (BigInteger (currentChansIn), BigInteger (currentChansOut),
  213579. currentSampleRate, currentBlockSizeSamples);
  213580. if (oldCallback != 0)
  213581. start (oldCallback);
  213582. }
  213583. }
  213584. else
  213585. {
  213586. startTimer (100);
  213587. }
  213588. }
  213589. juce_UseDebuggingNewOperator
  213590. private:
  213591. IASIO* volatile asioObject;
  213592. ASIOCallbacks callbacks;
  213593. void* windowHandle;
  213594. CLSID classId;
  213595. const String optionalDllForDirectLoading;
  213596. String error;
  213597. long totalNumInputChans, totalNumOutputChans;
  213598. StringArray inputChannelNames, outputChannelNames;
  213599. Array<int> sampleRates, bufferSizes;
  213600. long inputLatency, outputLatency;
  213601. long minSize, maxSize, preferredSize, granularity;
  213602. int volatile currentBlockSizeSamples;
  213603. int volatile currentBitDepth;
  213604. double volatile currentSampleRate;
  213605. BigInteger currentChansOut, currentChansIn;
  213606. AudioIODeviceCallback* volatile currentCallback;
  213607. CriticalSection callbackLock;
  213608. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213609. float* inBuffers [maxASIOChannels];
  213610. float* outBuffers [maxASIOChannels];
  213611. int inputChannelBitDepths [maxASIOChannels];
  213612. int outputChannelBitDepths [maxASIOChannels];
  213613. int inputChannelBytesPerSample [maxASIOChannels];
  213614. int outputChannelBytesPerSample [maxASIOChannels];
  213615. bool inputChannelIsFloat [maxASIOChannels];
  213616. bool outputChannelIsFloat [maxASIOChannels];
  213617. bool inputChannelLittleEndian [maxASIOChannels];
  213618. bool outputChannelLittleEndian [maxASIOChannels];
  213619. WaitableEvent event1;
  213620. HeapBlock <float> tempBuffer;
  213621. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213622. bool isOpen_, isStarted;
  213623. bool volatile isASIOOpen;
  213624. bool volatile calledback;
  213625. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213626. bool volatile insideControlPanelModalLoop;
  213627. bool volatile shouldUsePreferredSize;
  213628. void removeCurrentDriver()
  213629. {
  213630. if (asioObject != 0)
  213631. {
  213632. asioObject->Release();
  213633. asioObject = 0;
  213634. }
  213635. }
  213636. bool loadDriver()
  213637. {
  213638. removeCurrentDriver();
  213639. JUCE_TRY
  213640. {
  213641. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213642. classId, (void**) &asioObject) == S_OK)
  213643. {
  213644. return true;
  213645. }
  213646. // If a class isn't registered but we have a path for it, we can fallback to
  213647. // doing a direct load of the COM object (only available via the juce_createASIOAudioIODeviceForGUID function).
  213648. if (optionalDllForDirectLoading.isNotEmpty())
  213649. {
  213650. HMODULE h = LoadLibrary (optionalDllForDirectLoading);
  213651. if (h != 0)
  213652. {
  213653. typedef HRESULT (CALLBACK* DllGetClassObjectFunc) (REFCLSID clsid, REFIID iid, LPVOID* ppv);
  213654. DllGetClassObjectFunc dllGetClassObject = (DllGetClassObjectFunc) GetProcAddress (h, "DllGetClassObject");
  213655. if (dllGetClassObject != 0)
  213656. {
  213657. IClassFactory* classFactory = 0;
  213658. HRESULT hr = dllGetClassObject (classId, IID_IClassFactory, (void**) &classFactory);
  213659. if (classFactory != 0)
  213660. {
  213661. hr = classFactory->CreateInstance (0, classId, (void**) &asioObject);
  213662. classFactory->Release();
  213663. }
  213664. return asioObject != 0;
  213665. }
  213666. }
  213667. }
  213668. }
  213669. JUCE_CATCH_ALL
  213670. asioObject = 0;
  213671. return false;
  213672. }
  213673. const String initDriver()
  213674. {
  213675. if (asioObject != 0)
  213676. {
  213677. char buffer [256];
  213678. zeromem (buffer, sizeof (buffer));
  213679. if (! asioObject->init (windowHandle))
  213680. {
  213681. asioObject->getErrorMessage (buffer);
  213682. return String (buffer, sizeof (buffer) - 1);
  213683. }
  213684. // just in case any daft drivers expect this to be called..
  213685. asioObject->getDriverName (buffer);
  213686. return String::empty;
  213687. }
  213688. return "No Driver";
  213689. }
  213690. const String openDevice()
  213691. {
  213692. // use this in case the driver starts opening dialog boxes..
  213693. Component modalWindow (String::empty);
  213694. modalWindow.setOpaque (true);
  213695. modalWindow.addToDesktop (0);
  213696. modalWindow.enterModalState();
  213697. // open the device and get its info..
  213698. log ("opening ASIO device: " + getName());
  213699. needToReset = false;
  213700. isReSync = false;
  213701. outputChannelNames.clear();
  213702. inputChannelNames.clear();
  213703. bufferSizes.clear();
  213704. sampleRates.clear();
  213705. isASIOOpen = false;
  213706. isOpen_ = false;
  213707. totalNumInputChans = 0;
  213708. totalNumOutputChans = 0;
  213709. numActiveInputChans = 0;
  213710. numActiveOutputChans = 0;
  213711. currentCallback = 0;
  213712. error = String::empty;
  213713. if (getName().isEmpty())
  213714. return error;
  213715. long err = 0;
  213716. if (loadDriver())
  213717. {
  213718. if ((error = initDriver()).isEmpty())
  213719. {
  213720. numActiveInputChans = 0;
  213721. numActiveOutputChans = 0;
  213722. totalNumInputChans = 0;
  213723. totalNumOutputChans = 0;
  213724. if (asioObject != 0
  213725. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213726. {
  213727. log (String ((int) totalNumInputChans) + " in, " + String ((int) totalNumOutputChans) + " out");
  213728. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213729. {
  213730. // find a list of buffer sizes..
  213731. log (String ((int) minSize) + " " + String ((int) maxSize) + " " + String ((int) preferredSize) + " " + String ((int) granularity));
  213732. if (granularity >= 0)
  213733. {
  213734. granularity = jmax (1, (int) granularity);
  213735. for (int i = jmax ((int) minSize, (int) granularity); i < jmin (6400, (int) maxSize); i += granularity)
  213736. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213737. }
  213738. else if (granularity < 0)
  213739. {
  213740. for (int i = 0; i < 18; ++i)
  213741. {
  213742. const int s = (1 << i);
  213743. if (s >= minSize && s <= maxSize)
  213744. bufferSizes.add (s);
  213745. }
  213746. }
  213747. if (! bufferSizes.contains (preferredSize))
  213748. bufferSizes.insert (0, preferredSize);
  213749. double currentRate = 0;
  213750. asioObject->getSampleRate (&currentRate);
  213751. if (currentRate <= 0.0 || currentRate > 192001.0)
  213752. {
  213753. log ("setting sample rate");
  213754. err = asioObject->setSampleRate (44100.0);
  213755. if (err != 0)
  213756. {
  213757. logError ("setting sample rate", err);
  213758. }
  213759. asioObject->getSampleRate (&currentRate);
  213760. }
  213761. currentSampleRate = currentRate;
  213762. postOutput = (asioObject->outputReady() == 0);
  213763. if (postOutput)
  213764. {
  213765. log ("ASIO outputReady = ok");
  213766. }
  213767. updateSampleRates();
  213768. // ..because cubase does it at this point
  213769. inputLatency = outputLatency = 0;
  213770. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213771. {
  213772. log ("ASIO - no latencies");
  213773. }
  213774. log ("latencies: " + String ((int) inputLatency) + ", " + String ((int) outputLatency));
  213775. // create some dummy buffers now.. because cubase does..
  213776. numActiveInputChans = 0;
  213777. numActiveOutputChans = 0;
  213778. ASIOBufferInfo* info = bufferInfos;
  213779. int i, numChans = 0;
  213780. for (i = 0; i < jmin (2, (int) totalNumInputChans); ++i)
  213781. {
  213782. info->isInput = 1;
  213783. info->channelNum = i;
  213784. info->buffers[0] = info->buffers[1] = 0;
  213785. ++info;
  213786. ++numChans;
  213787. }
  213788. const int outputBufferIndex = numChans;
  213789. for (i = 0; i < jmin (2, (int) totalNumOutputChans); ++i)
  213790. {
  213791. info->isInput = 0;
  213792. info->channelNum = i;
  213793. info->buffers[0] = info->buffers[1] = 0;
  213794. ++info;
  213795. ++numChans;
  213796. }
  213797. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213798. if (currentASIODev[0] == this)
  213799. {
  213800. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213801. callbacks.asioMessage = &asioMessagesCallback0;
  213802. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213803. }
  213804. else if (currentASIODev[1] == this)
  213805. {
  213806. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213807. callbacks.asioMessage = &asioMessagesCallback1;
  213808. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213809. }
  213810. else if (currentASIODev[2] == this)
  213811. {
  213812. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213813. callbacks.asioMessage = &asioMessagesCallback2;
  213814. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213815. }
  213816. else
  213817. {
  213818. jassertfalse;
  213819. }
  213820. log ("creating buffers (dummy): " + String (numChans) + ", " + String ((int) preferredSize));
  213821. if (preferredSize > 0)
  213822. {
  213823. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213824. if (err != 0)
  213825. {
  213826. logError ("dummy buffers", err);
  213827. }
  213828. }
  213829. long newInps = 0, newOuts = 0;
  213830. asioObject->getChannels (&newInps, &newOuts);
  213831. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213832. {
  213833. totalNumInputChans = newInps;
  213834. totalNumOutputChans = newOuts;
  213835. log (String ((int) totalNumInputChans) + " in; " + String ((int) totalNumOutputChans) + " out");
  213836. }
  213837. updateSampleRates();
  213838. ASIOChannelInfo channelInfo;
  213839. channelInfo.type = 0;
  213840. for (i = 0; i < totalNumInputChans; ++i)
  213841. {
  213842. zerostruct (channelInfo);
  213843. channelInfo.channel = i;
  213844. channelInfo.isInput = 1;
  213845. asioObject->getChannelInfo (&channelInfo);
  213846. inputChannelNames.add (String (channelInfo.name));
  213847. }
  213848. for (i = 0; i < totalNumOutputChans; ++i)
  213849. {
  213850. zerostruct (channelInfo);
  213851. channelInfo.channel = i;
  213852. channelInfo.isInput = 0;
  213853. asioObject->getChannelInfo (&channelInfo);
  213854. outputChannelNames.add (String (channelInfo.name));
  213855. typeToFormatParameters (channelInfo.type,
  213856. outputChannelBitDepths[i],
  213857. outputChannelBytesPerSample[i],
  213858. outputChannelIsFloat[i],
  213859. outputChannelLittleEndian[i]);
  213860. if (i < 2)
  213861. {
  213862. // clear the channels that are used with the dummy stuff
  213863. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213864. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213865. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213866. }
  213867. }
  213868. outputChannelNames.trim();
  213869. inputChannelNames.trim();
  213870. outputChannelNames.appendNumbersToDuplicates (false, true);
  213871. inputChannelNames.appendNumbersToDuplicates (false, true);
  213872. // start and stop because cubase does it..
  213873. asioObject->getLatencies (&inputLatency, &outputLatency);
  213874. if ((err = asioObject->start()) != 0)
  213875. {
  213876. // ignore an error here, as it might start later after setting other stuff up
  213877. logError ("ASIO start", err);
  213878. }
  213879. Thread::sleep (100);
  213880. asioObject->stop();
  213881. }
  213882. else
  213883. {
  213884. error = "Can't detect buffer sizes";
  213885. }
  213886. }
  213887. else
  213888. {
  213889. error = "Can't detect asio channels";
  213890. }
  213891. }
  213892. }
  213893. else
  213894. {
  213895. error = "No such device";
  213896. }
  213897. if (error.isNotEmpty())
  213898. {
  213899. logError (error, err);
  213900. if (asioObject != 0)
  213901. asioObject->disposeBuffers();
  213902. removeCurrentDriver();
  213903. isASIOOpen = false;
  213904. }
  213905. else
  213906. {
  213907. isASIOOpen = true;
  213908. log ("ASIO device open");
  213909. }
  213910. isOpen_ = false;
  213911. needToReset = false;
  213912. isReSync = false;
  213913. return error;
  213914. }
  213915. void JUCE_ASIOCALLBACK callback (const long index)
  213916. {
  213917. if (isStarted)
  213918. {
  213919. bufferIndex = index;
  213920. processBuffer();
  213921. }
  213922. else
  213923. {
  213924. if (postOutput && (asioObject != 0))
  213925. asioObject->outputReady();
  213926. }
  213927. calledback = true;
  213928. }
  213929. void processBuffer()
  213930. {
  213931. const ASIOBufferInfo* const infos = bufferInfos;
  213932. const int bi = bufferIndex;
  213933. const ScopedLock sl (callbackLock);
  213934. if (needToReset)
  213935. {
  213936. needToReset = false;
  213937. if (isReSync)
  213938. {
  213939. log ("! ASIO resync");
  213940. isReSync = false;
  213941. }
  213942. else
  213943. {
  213944. startTimer (20);
  213945. }
  213946. }
  213947. if (bi >= 0)
  213948. {
  213949. const int samps = currentBlockSizeSamples;
  213950. if (currentCallback != 0)
  213951. {
  213952. int i;
  213953. for (i = 0; i < numActiveInputChans; ++i)
  213954. {
  213955. float* const dst = inBuffers[i];
  213956. jassert (dst != 0);
  213957. const char* const src = (const char*) (infos[i].buffers[bi]);
  213958. if (inputChannelIsFloat[i])
  213959. {
  213960. memcpy (dst, src, samps * sizeof (float));
  213961. }
  213962. else
  213963. {
  213964. jassert (dst == tempBuffer + (samps * i));
  213965. switch (inputChannelBitDepths[i])
  213966. {
  213967. case 16:
  213968. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  213969. samps, inputChannelLittleEndian[i]);
  213970. break;
  213971. case 24:
  213972. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  213973. samps, inputChannelLittleEndian[i]);
  213974. break;
  213975. case 32:
  213976. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  213977. samps, inputChannelLittleEndian[i]);
  213978. break;
  213979. case 64:
  213980. jassertfalse;
  213981. break;
  213982. }
  213983. }
  213984. }
  213985. currentCallback->audioDeviceIOCallback ((const float**) inBuffers, numActiveInputChans,
  213986. outBuffers, numActiveOutputChans, samps);
  213987. for (i = 0; i < numActiveOutputChans; ++i)
  213988. {
  213989. float* const src = outBuffers[i];
  213990. jassert (src != 0);
  213991. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  213992. if (outputChannelIsFloat[i])
  213993. {
  213994. memcpy (dst, src, samps * sizeof (float));
  213995. }
  213996. else
  213997. {
  213998. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  213999. switch (outputChannelBitDepths[i])
  214000. {
  214001. case 16:
  214002. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  214003. samps, outputChannelLittleEndian[i]);
  214004. break;
  214005. case 24:
  214006. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  214007. samps, outputChannelLittleEndian[i]);
  214008. break;
  214009. case 32:
  214010. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  214011. samps, outputChannelLittleEndian[i]);
  214012. break;
  214013. case 64:
  214014. jassertfalse;
  214015. break;
  214016. }
  214017. }
  214018. }
  214019. }
  214020. else
  214021. {
  214022. for (int i = 0; i < numActiveOutputChans; ++i)
  214023. {
  214024. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  214025. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  214026. }
  214027. }
  214028. }
  214029. if (postOutput)
  214030. asioObject->outputReady();
  214031. }
  214032. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long)
  214033. {
  214034. if (currentASIODev[0] != 0)
  214035. currentASIODev[0]->callback (index);
  214036. return 0;
  214037. }
  214038. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long)
  214039. {
  214040. if (currentASIODev[1] != 0)
  214041. currentASIODev[1]->callback (index);
  214042. return 0;
  214043. }
  214044. static ASIOTime* JUCE_ASIOCALLBACK bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long)
  214045. {
  214046. if (currentASIODev[2] != 0)
  214047. currentASIODev[2]->callback (index);
  214048. return 0;
  214049. }
  214050. static void JUCE_ASIOCALLBACK bufferSwitchCallback0 (long index, long)
  214051. {
  214052. if (currentASIODev[0] != 0)
  214053. currentASIODev[0]->callback (index);
  214054. }
  214055. static void JUCE_ASIOCALLBACK bufferSwitchCallback1 (long index, long)
  214056. {
  214057. if (currentASIODev[1] != 0)
  214058. currentASIODev[1]->callback (index);
  214059. }
  214060. static void JUCE_ASIOCALLBACK bufferSwitchCallback2 (long index, long)
  214061. {
  214062. if (currentASIODev[2] != 0)
  214063. currentASIODev[2]->callback (index);
  214064. }
  214065. static long JUCE_ASIOCALLBACK asioMessagesCallback0 (long selector, long value, void*, double*)
  214066. {
  214067. return asioMessagesCallback (selector, value, 0);
  214068. }
  214069. static long JUCE_ASIOCALLBACK asioMessagesCallback1 (long selector, long value, void*, double*)
  214070. {
  214071. return asioMessagesCallback (selector, value, 1);
  214072. }
  214073. static long JUCE_ASIOCALLBACK asioMessagesCallback2 (long selector, long value, void*, double*)
  214074. {
  214075. return asioMessagesCallback (selector, value, 2);
  214076. }
  214077. static long JUCE_ASIOCALLBACK asioMessagesCallback (long selector, long value, const int deviceIndex)
  214078. {
  214079. switch (selector)
  214080. {
  214081. case kAsioSelectorSupported:
  214082. if (value == kAsioResetRequest
  214083. || value == kAsioEngineVersion
  214084. || value == kAsioResyncRequest
  214085. || value == kAsioLatenciesChanged
  214086. || value == kAsioSupportsInputMonitor)
  214087. return 1;
  214088. break;
  214089. case kAsioBufferSizeChange:
  214090. break;
  214091. case kAsioResetRequest:
  214092. if (currentASIODev[deviceIndex] != 0)
  214093. currentASIODev[deviceIndex]->resetRequest();
  214094. return 1;
  214095. case kAsioResyncRequest:
  214096. if (currentASIODev[deviceIndex] != 0)
  214097. currentASIODev[deviceIndex]->resyncRequest();
  214098. return 1;
  214099. case kAsioLatenciesChanged:
  214100. return 1;
  214101. case kAsioEngineVersion:
  214102. return 2;
  214103. case kAsioSupportsTimeInfo:
  214104. case kAsioSupportsTimeCode:
  214105. return 0;
  214106. }
  214107. return 0;
  214108. }
  214109. static void JUCE_ASIOCALLBACK sampleRateChangedCallback (ASIOSampleRate)
  214110. {
  214111. }
  214112. static void convertInt16ToFloat (const char* src,
  214113. float* dest,
  214114. const int srcStrideBytes,
  214115. int numSamples,
  214116. const bool littleEndian) throw()
  214117. {
  214118. const double g = 1.0 / 32768.0;
  214119. if (littleEndian)
  214120. {
  214121. while (--numSamples >= 0)
  214122. {
  214123. *dest++ = (float) (g * (short) ByteOrder::littleEndianShort (src));
  214124. src += srcStrideBytes;
  214125. }
  214126. }
  214127. else
  214128. {
  214129. while (--numSamples >= 0)
  214130. {
  214131. *dest++ = (float) (g * (short) ByteOrder::bigEndianShort (src));
  214132. src += srcStrideBytes;
  214133. }
  214134. }
  214135. }
  214136. static void convertFloatToInt16 (const float* src,
  214137. char* dest,
  214138. const int dstStrideBytes,
  214139. int numSamples,
  214140. const bool littleEndian) throw()
  214141. {
  214142. const double maxVal = (double) 0x7fff;
  214143. if (littleEndian)
  214144. {
  214145. while (--numSamples >= 0)
  214146. {
  214147. *(uint16*) dest = ByteOrder::swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214148. dest += dstStrideBytes;
  214149. }
  214150. }
  214151. else
  214152. {
  214153. while (--numSamples >= 0)
  214154. {
  214155. *(uint16*) dest = ByteOrder::swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214156. dest += dstStrideBytes;
  214157. }
  214158. }
  214159. }
  214160. static void convertInt24ToFloat (const char* src,
  214161. float* dest,
  214162. const int srcStrideBytes,
  214163. int numSamples,
  214164. const bool littleEndian) throw()
  214165. {
  214166. const double g = 1.0 / 0x7fffff;
  214167. if (littleEndian)
  214168. {
  214169. while (--numSamples >= 0)
  214170. {
  214171. *dest++ = (float) (g * ByteOrder::littleEndian24Bit (src));
  214172. src += srcStrideBytes;
  214173. }
  214174. }
  214175. else
  214176. {
  214177. while (--numSamples >= 0)
  214178. {
  214179. *dest++ = (float) (g * ByteOrder::bigEndian24Bit (src));
  214180. src += srcStrideBytes;
  214181. }
  214182. }
  214183. }
  214184. static void convertFloatToInt24 (const float* src,
  214185. char* dest,
  214186. const int dstStrideBytes,
  214187. int numSamples,
  214188. const bool littleEndian) throw()
  214189. {
  214190. const double maxVal = (double) 0x7fffff;
  214191. if (littleEndian)
  214192. {
  214193. while (--numSamples >= 0)
  214194. {
  214195. ByteOrder::littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214196. dest += dstStrideBytes;
  214197. }
  214198. }
  214199. else
  214200. {
  214201. while (--numSamples >= 0)
  214202. {
  214203. ByteOrder::bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214204. dest += dstStrideBytes;
  214205. }
  214206. }
  214207. }
  214208. static void convertInt32ToFloat (const char* src,
  214209. float* dest,
  214210. const int srcStrideBytes,
  214211. int numSamples,
  214212. const bool littleEndian) throw()
  214213. {
  214214. const double g = 1.0 / 0x7fffffff;
  214215. if (littleEndian)
  214216. {
  214217. while (--numSamples >= 0)
  214218. {
  214219. *dest++ = (float) (g * (int) ByteOrder::littleEndianInt (src));
  214220. src += srcStrideBytes;
  214221. }
  214222. }
  214223. else
  214224. {
  214225. while (--numSamples >= 0)
  214226. {
  214227. *dest++ = (float) (g * (int) ByteOrder::bigEndianInt (src));
  214228. src += srcStrideBytes;
  214229. }
  214230. }
  214231. }
  214232. static void convertFloatToInt32 (const float* src,
  214233. char* dest,
  214234. const int dstStrideBytes,
  214235. int numSamples,
  214236. const bool littleEndian) throw()
  214237. {
  214238. const double maxVal = (double) 0x7fffffff;
  214239. if (littleEndian)
  214240. {
  214241. while (--numSamples >= 0)
  214242. {
  214243. *(uint32*) dest = ByteOrder::swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214244. dest += dstStrideBytes;
  214245. }
  214246. }
  214247. else
  214248. {
  214249. while (--numSamples >= 0)
  214250. {
  214251. *(uint32*) dest = ByteOrder::swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214252. dest += dstStrideBytes;
  214253. }
  214254. }
  214255. }
  214256. static void typeToFormatParameters (const long type,
  214257. int& bitDepth,
  214258. int& byteStride,
  214259. bool& formatIsFloat,
  214260. bool& littleEndian) throw()
  214261. {
  214262. bitDepth = 0;
  214263. littleEndian = false;
  214264. formatIsFloat = false;
  214265. switch (type)
  214266. {
  214267. case ASIOSTInt16MSB:
  214268. case ASIOSTInt16LSB:
  214269. case ASIOSTInt32MSB16:
  214270. case ASIOSTInt32LSB16:
  214271. bitDepth = 16; break;
  214272. case ASIOSTFloat32MSB:
  214273. case ASIOSTFloat32LSB:
  214274. formatIsFloat = true;
  214275. bitDepth = 32; break;
  214276. case ASIOSTInt32MSB:
  214277. case ASIOSTInt32LSB:
  214278. bitDepth = 32; break;
  214279. case ASIOSTInt24MSB:
  214280. case ASIOSTInt24LSB:
  214281. case ASIOSTInt32MSB24:
  214282. case ASIOSTInt32LSB24:
  214283. case ASIOSTInt32MSB18:
  214284. case ASIOSTInt32MSB20:
  214285. case ASIOSTInt32LSB18:
  214286. case ASIOSTInt32LSB20:
  214287. bitDepth = 24; break;
  214288. case ASIOSTFloat64MSB:
  214289. case ASIOSTFloat64LSB:
  214290. default:
  214291. bitDepth = 64;
  214292. break;
  214293. }
  214294. switch (type)
  214295. {
  214296. case ASIOSTInt16MSB:
  214297. case ASIOSTInt32MSB16:
  214298. case ASIOSTFloat32MSB:
  214299. case ASIOSTFloat64MSB:
  214300. case ASIOSTInt32MSB:
  214301. case ASIOSTInt32MSB18:
  214302. case ASIOSTInt32MSB20:
  214303. case ASIOSTInt32MSB24:
  214304. case ASIOSTInt24MSB:
  214305. littleEndian = false; break;
  214306. case ASIOSTInt16LSB:
  214307. case ASIOSTInt32LSB16:
  214308. case ASIOSTFloat32LSB:
  214309. case ASIOSTFloat64LSB:
  214310. case ASIOSTInt32LSB:
  214311. case ASIOSTInt32LSB18:
  214312. case ASIOSTInt32LSB20:
  214313. case ASIOSTInt32LSB24:
  214314. case ASIOSTInt24LSB:
  214315. littleEndian = true; break;
  214316. default:
  214317. break;
  214318. }
  214319. switch (type)
  214320. {
  214321. case ASIOSTInt16LSB:
  214322. case ASIOSTInt16MSB:
  214323. byteStride = 2; break;
  214324. case ASIOSTInt24LSB:
  214325. case ASIOSTInt24MSB:
  214326. byteStride = 3; break;
  214327. case ASIOSTInt32MSB16:
  214328. case ASIOSTInt32LSB16:
  214329. case ASIOSTInt32MSB:
  214330. case ASIOSTInt32MSB18:
  214331. case ASIOSTInt32MSB20:
  214332. case ASIOSTInt32MSB24:
  214333. case ASIOSTInt32LSB:
  214334. case ASIOSTInt32LSB18:
  214335. case ASIOSTInt32LSB20:
  214336. case ASIOSTInt32LSB24:
  214337. case ASIOSTFloat32LSB:
  214338. case ASIOSTFloat32MSB:
  214339. byteStride = 4; break;
  214340. case ASIOSTFloat64MSB:
  214341. case ASIOSTFloat64LSB:
  214342. byteStride = 8; break;
  214343. default:
  214344. break;
  214345. }
  214346. }
  214347. };
  214348. class ASIOAudioIODeviceType : public AudioIODeviceType
  214349. {
  214350. public:
  214351. ASIOAudioIODeviceType()
  214352. : AudioIODeviceType ("ASIO"),
  214353. hasScanned (false)
  214354. {
  214355. CoInitialize (0);
  214356. }
  214357. ~ASIOAudioIODeviceType()
  214358. {
  214359. }
  214360. void scanForDevices()
  214361. {
  214362. hasScanned = true;
  214363. deviceNames.clear();
  214364. classIds.clear();
  214365. HKEY hk = 0;
  214366. int index = 0;
  214367. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214368. {
  214369. for (;;)
  214370. {
  214371. char name [256];
  214372. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214373. {
  214374. addDriverInfo (name, hk);
  214375. }
  214376. else
  214377. {
  214378. break;
  214379. }
  214380. }
  214381. RegCloseKey (hk);
  214382. }
  214383. }
  214384. const StringArray getDeviceNames (bool /*wantInputNames*/) const
  214385. {
  214386. jassert (hasScanned); // need to call scanForDevices() before doing this
  214387. return deviceNames;
  214388. }
  214389. int getDefaultDeviceIndex (bool) const
  214390. {
  214391. jassert (hasScanned); // need to call scanForDevices() before doing this
  214392. for (int i = deviceNames.size(); --i >= 0;)
  214393. if (deviceNames[i].containsIgnoreCase ("asio4all"))
  214394. return i; // asio4all is a safe choice for a default..
  214395. #if JUCE_DEBUG
  214396. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase ("digidesign"))
  214397. return 1; // (the digi m-box driver crashes the app when you run
  214398. // it in the debugger, which can be a bit annoying)
  214399. #endif
  214400. return 0;
  214401. }
  214402. static int findFreeSlot()
  214403. {
  214404. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214405. if (currentASIODev[i] == 0)
  214406. return i;
  214407. jassertfalse; // unfortunately you can only have a finite number
  214408. // of ASIO devices open at the same time..
  214409. return -1;
  214410. }
  214411. int getIndexOfDevice (AudioIODevice* d, bool /*asInput*/) const
  214412. {
  214413. jassert (hasScanned); // need to call scanForDevices() before doing this
  214414. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214415. }
  214416. bool hasSeparateInputsAndOutputs() const { return false; }
  214417. AudioIODevice* createDevice (const String& outputDeviceName,
  214418. const String& inputDeviceName)
  214419. {
  214420. // ASIO can't open two different devices for input and output - they must be the same one.
  214421. jassert (inputDeviceName == outputDeviceName || outputDeviceName.isEmpty() || inputDeviceName.isEmpty());
  214422. jassert (hasScanned); // need to call scanForDevices() before doing this
  214423. const int index = deviceNames.indexOf (outputDeviceName.isNotEmpty() ? outputDeviceName
  214424. : inputDeviceName);
  214425. if (index >= 0)
  214426. {
  214427. const int freeSlot = findFreeSlot();
  214428. if (freeSlot >= 0)
  214429. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot, String::empty);
  214430. }
  214431. return 0;
  214432. }
  214433. juce_UseDebuggingNewOperator
  214434. private:
  214435. StringArray deviceNames;
  214436. OwnedArray <CLSID> classIds;
  214437. bool hasScanned;
  214438. static bool checkClassIsOk (const String& classId)
  214439. {
  214440. HKEY hk = 0;
  214441. bool ok = false;
  214442. if (RegOpenKey (HKEY_CLASSES_ROOT, _T("clsid"), &hk) == ERROR_SUCCESS)
  214443. {
  214444. int index = 0;
  214445. for (;;)
  214446. {
  214447. WCHAR buf [512];
  214448. if (RegEnumKey (hk, index++, buf, 512) == ERROR_SUCCESS)
  214449. {
  214450. if (classId.equalsIgnoreCase (buf))
  214451. {
  214452. HKEY subKey, pathKey;
  214453. if (RegOpenKeyEx (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214454. {
  214455. if (RegOpenKeyEx (subKey, _T("InprocServer32"), 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214456. {
  214457. WCHAR pathName [1024];
  214458. DWORD dtype = REG_SZ;
  214459. DWORD dsize = sizeof (pathName);
  214460. if (RegQueryValueEx (pathKey, 0, 0, &dtype, (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214461. ok = File (pathName).exists();
  214462. RegCloseKey (pathKey);
  214463. }
  214464. RegCloseKey (subKey);
  214465. }
  214466. break;
  214467. }
  214468. }
  214469. else
  214470. {
  214471. break;
  214472. }
  214473. }
  214474. RegCloseKey (hk);
  214475. }
  214476. return ok;
  214477. }
  214478. void addDriverInfo (const String& keyName, HKEY hk)
  214479. {
  214480. HKEY subKey;
  214481. if (RegOpenKeyEx (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214482. {
  214483. WCHAR buf [256];
  214484. zerostruct (buf);
  214485. DWORD dtype = REG_SZ;
  214486. DWORD dsize = sizeof (buf);
  214487. if (RegQueryValueEx (subKey, _T("clsid"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214488. {
  214489. if (dsize > 0 && checkClassIsOk (buf))
  214490. {
  214491. CLSID classId;
  214492. if (CLSIDFromString ((LPOLESTR) buf, &classId) == S_OK)
  214493. {
  214494. dtype = REG_SZ;
  214495. dsize = sizeof (buf);
  214496. String deviceName;
  214497. if (RegQueryValueEx (subKey, _T("description"), 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214498. deviceName = buf;
  214499. else
  214500. deviceName = keyName;
  214501. log ("found " + deviceName);
  214502. deviceNames.add (deviceName);
  214503. classIds.add (new CLSID (classId));
  214504. }
  214505. }
  214506. RegCloseKey (subKey);
  214507. }
  214508. }
  214509. }
  214510. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214511. ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214512. };
  214513. AudioIODeviceType* juce_createAudioIODeviceType_ASIO()
  214514. {
  214515. return new ASIOAudioIODeviceType();
  214516. }
  214517. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214518. void* guid,
  214519. const String& optionalDllForDirectLoading)
  214520. {
  214521. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214522. if (freeSlot < 0)
  214523. return 0;
  214524. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot, optionalDllForDirectLoading);
  214525. }
  214526. #undef logError
  214527. #undef log
  214528. #endif
  214529. /*** End of inlined file: juce_win32_ASIO.cpp ***/
  214530. /*** Start of inlined file: juce_win32_DirectSound.cpp ***/
  214531. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214532. // compiled on its own).
  214533. #if JUCE_INCLUDED_FILE && JUCE_DIRECTSOUND
  214534. END_JUCE_NAMESPACE
  214535. extern "C"
  214536. {
  214537. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214538. typedef struct typeDSBUFFERDESC
  214539. {
  214540. DWORD dwSize;
  214541. DWORD dwFlags;
  214542. DWORD dwBufferBytes;
  214543. DWORD dwReserved;
  214544. LPWAVEFORMATEX lpwfxFormat;
  214545. GUID guid3DAlgorithm;
  214546. } DSBUFFERDESC;
  214547. struct IDirectSoundBuffer;
  214548. #undef INTERFACE
  214549. #define INTERFACE IDirectSound
  214550. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214551. {
  214552. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214553. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214554. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214555. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214556. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214557. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214558. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214559. STDMETHOD(Compact) (THIS) PURE;
  214560. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214561. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214562. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214563. };
  214564. #undef INTERFACE
  214565. #define INTERFACE IDirectSoundBuffer
  214566. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214567. {
  214568. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214569. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214570. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214571. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214572. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214573. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214574. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214575. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214576. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214577. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214578. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214579. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214580. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214581. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214582. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214583. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214584. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214585. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214586. STDMETHOD(Stop) (THIS) PURE;
  214587. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214588. STDMETHOD(Restore) (THIS) PURE;
  214589. };
  214590. typedef struct typeDSCBUFFERDESC
  214591. {
  214592. DWORD dwSize;
  214593. DWORD dwFlags;
  214594. DWORD dwBufferBytes;
  214595. DWORD dwReserved;
  214596. LPWAVEFORMATEX lpwfxFormat;
  214597. } DSCBUFFERDESC;
  214598. struct IDirectSoundCaptureBuffer;
  214599. #undef INTERFACE
  214600. #define INTERFACE IDirectSoundCapture
  214601. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214602. {
  214603. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214604. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214605. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214606. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214607. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214608. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214609. };
  214610. #undef INTERFACE
  214611. #define INTERFACE IDirectSoundCaptureBuffer
  214612. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214613. {
  214614. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214615. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214616. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214617. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214618. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214619. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214620. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214621. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214622. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214623. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214624. STDMETHOD(Stop) (THIS) PURE;
  214625. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214626. };
  214627. };
  214628. BEGIN_JUCE_NAMESPACE
  214629. namespace
  214630. {
  214631. const String getDSErrorMessage (HRESULT hr)
  214632. {
  214633. const char* result = 0;
  214634. switch (hr)
  214635. {
  214636. case MAKE_HRESULT(1, 0x878, 10): result = "Device already allocated"; break;
  214637. case MAKE_HRESULT(1, 0x878, 30): result = "Control unavailable"; break;
  214638. case E_INVALIDARG: result = "Invalid parameter"; break;
  214639. case MAKE_HRESULT(1, 0x878, 50): result = "Invalid call"; break;
  214640. case E_FAIL: result = "Generic error"; break;
  214641. case MAKE_HRESULT(1, 0x878, 70): result = "Priority level error"; break;
  214642. case E_OUTOFMEMORY: result = "Out of memory"; break;
  214643. case MAKE_HRESULT(1, 0x878, 100): result = "Bad format"; break;
  214644. case E_NOTIMPL: result = "Unsupported function"; break;
  214645. case MAKE_HRESULT(1, 0x878, 120): result = "No driver"; break;
  214646. case MAKE_HRESULT(1, 0x878, 130): result = "Already initialised"; break;
  214647. case CLASS_E_NOAGGREGATION: result = "No aggregation"; break;
  214648. case MAKE_HRESULT(1, 0x878, 150): result = "Buffer lost"; break;
  214649. case MAKE_HRESULT(1, 0x878, 160): result = "Another app has priority"; break;
  214650. case MAKE_HRESULT(1, 0x878, 170): result = "Uninitialised"; break;
  214651. case E_NOINTERFACE: result = "No interface"; break;
  214652. case S_OK: result = "No error"; break;
  214653. default: return "Unknown error: " + String ((int) hr);
  214654. }
  214655. return result;
  214656. }
  214657. #define DS_DEBUGGING 1
  214658. #ifdef DS_DEBUGGING
  214659. #define CATCH JUCE_CATCH_EXCEPTION
  214660. #undef log
  214661. #define log(a) Logger::writeToLog(a);
  214662. #undef logError
  214663. #define logError(a) logDSError(a, __LINE__);
  214664. static void logDSError (HRESULT hr, int lineNum)
  214665. {
  214666. if (hr != S_OK)
  214667. {
  214668. String error ("DS error at line ");
  214669. error << lineNum << " - " << getDSErrorMessage (hr);
  214670. log (error);
  214671. }
  214672. }
  214673. #else
  214674. #define CATCH JUCE_CATCH_ALL
  214675. #define log(a)
  214676. #define logError(a)
  214677. #endif
  214678. #define DSOUND_FUNCTION(functionName, params) \
  214679. typedef HRESULT (WINAPI *type##functionName) params; \
  214680. static type##functionName ds##functionName = 0;
  214681. #define DSOUND_FUNCTION_LOAD(functionName) \
  214682. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214683. jassert (ds##functionName != 0);
  214684. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214685. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214686. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214687. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214688. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214689. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214690. void initialiseDSoundFunctions()
  214691. {
  214692. if (dsDirectSoundCreate == 0)
  214693. {
  214694. HMODULE h = LoadLibraryA ("dsound.dll");
  214695. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214696. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214697. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214698. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214699. }
  214700. }
  214701. }
  214702. class DSoundInternalOutChannel
  214703. {
  214704. String name;
  214705. LPGUID guid;
  214706. int sampleRate, bufferSizeSamples;
  214707. float* leftBuffer;
  214708. float* rightBuffer;
  214709. IDirectSound* pDirectSound;
  214710. IDirectSoundBuffer* pOutputBuffer;
  214711. DWORD writeOffset;
  214712. int totalBytesPerBuffer;
  214713. int bytesPerBuffer;
  214714. unsigned int lastPlayCursor;
  214715. public:
  214716. int bitDepth;
  214717. bool doneFlag;
  214718. DSoundInternalOutChannel (const String& name_,
  214719. LPGUID guid_,
  214720. int rate,
  214721. int bufferSize,
  214722. float* left,
  214723. float* right)
  214724. : name (name_),
  214725. guid (guid_),
  214726. sampleRate (rate),
  214727. bufferSizeSamples (bufferSize),
  214728. leftBuffer (left),
  214729. rightBuffer (right),
  214730. pDirectSound (0),
  214731. pOutputBuffer (0),
  214732. bitDepth (16)
  214733. {
  214734. }
  214735. ~DSoundInternalOutChannel()
  214736. {
  214737. close();
  214738. }
  214739. void close()
  214740. {
  214741. HRESULT hr;
  214742. if (pOutputBuffer != 0)
  214743. {
  214744. JUCE_TRY
  214745. {
  214746. log ("closing dsound out: " + name);
  214747. hr = pOutputBuffer->Stop();
  214748. logError (hr);
  214749. }
  214750. CATCH
  214751. JUCE_TRY
  214752. {
  214753. hr = pOutputBuffer->Release();
  214754. logError (hr);
  214755. }
  214756. CATCH
  214757. pOutputBuffer = 0;
  214758. }
  214759. if (pDirectSound != 0)
  214760. {
  214761. JUCE_TRY
  214762. {
  214763. hr = pDirectSound->Release();
  214764. logError (hr);
  214765. }
  214766. CATCH
  214767. pDirectSound = 0;
  214768. }
  214769. }
  214770. const String open()
  214771. {
  214772. log ("opening dsound out device: " + name + " rate=" + String (sampleRate)
  214773. + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  214774. pDirectSound = 0;
  214775. pOutputBuffer = 0;
  214776. writeOffset = 0;
  214777. String error;
  214778. HRESULT hr = E_NOINTERFACE;
  214779. if (dsDirectSoundCreate != 0)
  214780. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214781. if (hr == S_OK)
  214782. {
  214783. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214784. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214785. const int numChannels = 2;
  214786. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214787. logError (hr);
  214788. if (hr == S_OK)
  214789. {
  214790. IDirectSoundBuffer* pPrimaryBuffer;
  214791. DSBUFFERDESC primaryDesc;
  214792. zerostruct (primaryDesc);
  214793. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214794. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214795. primaryDesc.dwBufferBytes = 0;
  214796. primaryDesc.lpwfxFormat = 0;
  214797. log ("opening dsound out step 2");
  214798. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214799. logError (hr);
  214800. if (hr == S_OK)
  214801. {
  214802. WAVEFORMATEX wfFormat;
  214803. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214804. wfFormat.nChannels = (unsigned short) numChannels;
  214805. wfFormat.nSamplesPerSec = sampleRate;
  214806. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214807. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214808. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214809. wfFormat.cbSize = 0;
  214810. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214811. logError (hr);
  214812. if (hr == S_OK)
  214813. {
  214814. DSBUFFERDESC secondaryDesc;
  214815. zerostruct (secondaryDesc);
  214816. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214817. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214818. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214819. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214820. secondaryDesc.lpwfxFormat = &wfFormat;
  214821. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214822. logError (hr);
  214823. if (hr == S_OK)
  214824. {
  214825. log ("opening dsound out step 3");
  214826. DWORD dwDataLen;
  214827. unsigned char* pDSBuffData;
  214828. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214829. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214830. logError (hr);
  214831. if (hr == S_OK)
  214832. {
  214833. zeromem (pDSBuffData, dwDataLen);
  214834. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214835. if (hr == S_OK)
  214836. {
  214837. hr = pOutputBuffer->SetCurrentPosition (0);
  214838. if (hr == S_OK)
  214839. {
  214840. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214841. if (hr == S_OK)
  214842. return String::empty;
  214843. }
  214844. }
  214845. }
  214846. }
  214847. }
  214848. }
  214849. }
  214850. }
  214851. error = getDSErrorMessage (hr);
  214852. close();
  214853. return error;
  214854. }
  214855. void synchronisePosition()
  214856. {
  214857. if (pOutputBuffer != 0)
  214858. {
  214859. DWORD playCursor;
  214860. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214861. }
  214862. }
  214863. bool service()
  214864. {
  214865. if (pOutputBuffer == 0)
  214866. return true;
  214867. DWORD playCursor, writeCursor;
  214868. for (;;)
  214869. {
  214870. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  214871. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214872. {
  214873. pOutputBuffer->Restore();
  214874. continue;
  214875. }
  214876. if (hr == S_OK)
  214877. break;
  214878. logError (hr);
  214879. jassertfalse;
  214880. return true;
  214881. }
  214882. int playWriteGap = writeCursor - playCursor;
  214883. if (playWriteGap < 0)
  214884. playWriteGap += totalBytesPerBuffer;
  214885. int bytesEmpty = playCursor - writeOffset;
  214886. if (bytesEmpty < 0)
  214887. bytesEmpty += totalBytesPerBuffer;
  214888. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  214889. {
  214890. writeOffset = writeCursor;
  214891. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  214892. }
  214893. if (bytesEmpty >= bytesPerBuffer)
  214894. {
  214895. void* lpbuf1 = 0;
  214896. void* lpbuf2 = 0;
  214897. DWORD dwSize1 = 0;
  214898. DWORD dwSize2 = 0;
  214899. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  214900. bytesPerBuffer,
  214901. &lpbuf1, &dwSize1,
  214902. &lpbuf2, &dwSize2, 0);
  214903. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  214904. {
  214905. pOutputBuffer->Restore();
  214906. hr = pOutputBuffer->Lock (writeOffset,
  214907. bytesPerBuffer,
  214908. &lpbuf1, &dwSize1,
  214909. &lpbuf2, &dwSize2, 0);
  214910. }
  214911. if (hr == S_OK)
  214912. {
  214913. if (bitDepth == 16)
  214914. {
  214915. const float gainL = 32767.0f;
  214916. const float gainR = 32767.0f;
  214917. int* dest = static_cast<int*> (lpbuf1);
  214918. const float* left = leftBuffer;
  214919. const float* right = rightBuffer;
  214920. int samples1 = dwSize1 >> 2;
  214921. int samples2 = dwSize2 >> 2;
  214922. if (left == 0)
  214923. {
  214924. while (--samples1 >= 0)
  214925. {
  214926. int r = roundToInt (gainR * *right++);
  214927. if (r < -32768)
  214928. r = -32768;
  214929. else if (r > 32767)
  214930. r = 32767;
  214931. *dest++ = (r << 16);
  214932. }
  214933. dest = static_cast<int*> (lpbuf2);
  214934. while (--samples2 >= 0)
  214935. {
  214936. int r = roundToInt (gainR * *right++);
  214937. if (r < -32768)
  214938. r = -32768;
  214939. else if (r > 32767)
  214940. r = 32767;
  214941. *dest++ = (r << 16);
  214942. }
  214943. }
  214944. else if (right == 0)
  214945. {
  214946. while (--samples1 >= 0)
  214947. {
  214948. int l = roundToInt (gainL * *left++);
  214949. if (l < -32768)
  214950. l = -32768;
  214951. else if (l > 32767)
  214952. l = 32767;
  214953. l &= 0xffff;
  214954. *dest++ = l;
  214955. }
  214956. dest = static_cast<int*> (lpbuf2);
  214957. while (--samples2 >= 0)
  214958. {
  214959. int l = roundToInt (gainL * *left++);
  214960. if (l < -32768)
  214961. l = -32768;
  214962. else if (l > 32767)
  214963. l = 32767;
  214964. l &= 0xffff;
  214965. *dest++ = l;
  214966. }
  214967. }
  214968. else
  214969. {
  214970. while (--samples1 >= 0)
  214971. {
  214972. int l = roundToInt (gainL * *left++);
  214973. if (l < -32768)
  214974. l = -32768;
  214975. else if (l > 32767)
  214976. l = 32767;
  214977. l &= 0xffff;
  214978. int r = roundToInt (gainR * *right++);
  214979. if (r < -32768)
  214980. r = -32768;
  214981. else if (r > 32767)
  214982. r = 32767;
  214983. *dest++ = (r << 16) | l;
  214984. }
  214985. dest = static_cast<int*> (lpbuf2);
  214986. while (--samples2 >= 0)
  214987. {
  214988. int l = roundToInt (gainL * *left++);
  214989. if (l < -32768)
  214990. l = -32768;
  214991. else if (l > 32767)
  214992. l = 32767;
  214993. l &= 0xffff;
  214994. int r = roundToInt (gainR * *right++);
  214995. if (r < -32768)
  214996. r = -32768;
  214997. else if (r > 32767)
  214998. r = 32767;
  214999. *dest++ = (r << 16) | l;
  215000. }
  215001. }
  215002. }
  215003. else
  215004. {
  215005. jassertfalse;
  215006. }
  215007. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  215008. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  215009. }
  215010. else
  215011. {
  215012. jassertfalse;
  215013. logError (hr);
  215014. }
  215015. bytesEmpty -= bytesPerBuffer;
  215016. return true;
  215017. }
  215018. else
  215019. {
  215020. return false;
  215021. }
  215022. }
  215023. };
  215024. struct DSoundInternalInChannel
  215025. {
  215026. String name;
  215027. LPGUID guid;
  215028. int sampleRate, bufferSizeSamples;
  215029. float* leftBuffer;
  215030. float* rightBuffer;
  215031. IDirectSound* pDirectSound;
  215032. IDirectSoundCapture* pDirectSoundCapture;
  215033. IDirectSoundCaptureBuffer* pInputBuffer;
  215034. public:
  215035. unsigned int readOffset;
  215036. int bytesPerBuffer, totalBytesPerBuffer;
  215037. int bitDepth;
  215038. bool doneFlag;
  215039. DSoundInternalInChannel (const String& name_,
  215040. LPGUID guid_,
  215041. int rate,
  215042. int bufferSize,
  215043. float* left,
  215044. float* right)
  215045. : name (name_),
  215046. guid (guid_),
  215047. sampleRate (rate),
  215048. bufferSizeSamples (bufferSize),
  215049. leftBuffer (left),
  215050. rightBuffer (right),
  215051. pDirectSound (0),
  215052. pDirectSoundCapture (0),
  215053. pInputBuffer (0),
  215054. bitDepth (16)
  215055. {
  215056. }
  215057. ~DSoundInternalInChannel()
  215058. {
  215059. close();
  215060. }
  215061. void close()
  215062. {
  215063. HRESULT hr;
  215064. if (pInputBuffer != 0)
  215065. {
  215066. JUCE_TRY
  215067. {
  215068. log ("closing dsound in: " + name);
  215069. hr = pInputBuffer->Stop();
  215070. logError (hr);
  215071. }
  215072. CATCH
  215073. JUCE_TRY
  215074. {
  215075. hr = pInputBuffer->Release();
  215076. logError (hr);
  215077. }
  215078. CATCH
  215079. pInputBuffer = 0;
  215080. }
  215081. if (pDirectSoundCapture != 0)
  215082. {
  215083. JUCE_TRY
  215084. {
  215085. hr = pDirectSoundCapture->Release();
  215086. logError (hr);
  215087. }
  215088. CATCH
  215089. pDirectSoundCapture = 0;
  215090. }
  215091. if (pDirectSound != 0)
  215092. {
  215093. JUCE_TRY
  215094. {
  215095. hr = pDirectSound->Release();
  215096. logError (hr);
  215097. }
  215098. CATCH
  215099. pDirectSound = 0;
  215100. }
  215101. }
  215102. const String open()
  215103. {
  215104. log ("opening dsound in device: " + name
  215105. + " rate=" + String (sampleRate) + " bits=" + String (bitDepth) + " buf=" + String (bufferSizeSamples));
  215106. pDirectSound = 0;
  215107. pDirectSoundCapture = 0;
  215108. pInputBuffer = 0;
  215109. readOffset = 0;
  215110. totalBytesPerBuffer = 0;
  215111. String error;
  215112. HRESULT hr = E_NOINTERFACE;
  215113. if (dsDirectSoundCaptureCreate != 0)
  215114. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  215115. logError (hr);
  215116. if (hr == S_OK)
  215117. {
  215118. const int numChannels = 2;
  215119. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  215120. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  215121. WAVEFORMATEX wfFormat;
  215122. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  215123. wfFormat.nChannels = (unsigned short)numChannels;
  215124. wfFormat.nSamplesPerSec = sampleRate;
  215125. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  215126. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  215127. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  215128. wfFormat.cbSize = 0;
  215129. DSCBUFFERDESC captureDesc;
  215130. zerostruct (captureDesc);
  215131. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  215132. captureDesc.dwFlags = 0;
  215133. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  215134. captureDesc.lpwfxFormat = &wfFormat;
  215135. log ("opening dsound in step 2");
  215136. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  215137. logError (hr);
  215138. if (hr == S_OK)
  215139. {
  215140. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  215141. logError (hr);
  215142. if (hr == S_OK)
  215143. return String::empty;
  215144. }
  215145. }
  215146. error = getDSErrorMessage (hr);
  215147. close();
  215148. return error;
  215149. }
  215150. void synchronisePosition()
  215151. {
  215152. if (pInputBuffer != 0)
  215153. {
  215154. DWORD capturePos;
  215155. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  215156. }
  215157. }
  215158. bool service()
  215159. {
  215160. if (pInputBuffer == 0)
  215161. return true;
  215162. DWORD capturePos, readPos;
  215163. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  215164. logError (hr);
  215165. if (hr != S_OK)
  215166. return true;
  215167. int bytesFilled = readPos - readOffset;
  215168. if (bytesFilled < 0)
  215169. bytesFilled += totalBytesPerBuffer;
  215170. if (bytesFilled >= bytesPerBuffer)
  215171. {
  215172. LPBYTE lpbuf1 = 0;
  215173. LPBYTE lpbuf2 = 0;
  215174. DWORD dwsize1 = 0;
  215175. DWORD dwsize2 = 0;
  215176. HRESULT hr = pInputBuffer->Lock (readOffset,
  215177. bytesPerBuffer,
  215178. (void**) &lpbuf1, &dwsize1,
  215179. (void**) &lpbuf2, &dwsize2, 0);
  215180. if (hr == S_OK)
  215181. {
  215182. if (bitDepth == 16)
  215183. {
  215184. const float g = 1.0f / 32768.0f;
  215185. float* destL = leftBuffer;
  215186. float* destR = rightBuffer;
  215187. int samples1 = dwsize1 >> 2;
  215188. int samples2 = dwsize2 >> 2;
  215189. const short* src = (const short*)lpbuf1;
  215190. if (destL == 0)
  215191. {
  215192. while (--samples1 >= 0)
  215193. {
  215194. ++src;
  215195. *destR++ = *src++ * g;
  215196. }
  215197. src = (const short*)lpbuf2;
  215198. while (--samples2 >= 0)
  215199. {
  215200. ++src;
  215201. *destR++ = *src++ * g;
  215202. }
  215203. }
  215204. else if (destR == 0)
  215205. {
  215206. while (--samples1 >= 0)
  215207. {
  215208. *destL++ = *src++ * g;
  215209. ++src;
  215210. }
  215211. src = (const short*)lpbuf2;
  215212. while (--samples2 >= 0)
  215213. {
  215214. *destL++ = *src++ * g;
  215215. ++src;
  215216. }
  215217. }
  215218. else
  215219. {
  215220. while (--samples1 >= 0)
  215221. {
  215222. *destL++ = *src++ * g;
  215223. *destR++ = *src++ * g;
  215224. }
  215225. src = (const short*)lpbuf2;
  215226. while (--samples2 >= 0)
  215227. {
  215228. *destL++ = *src++ * g;
  215229. *destR++ = *src++ * g;
  215230. }
  215231. }
  215232. }
  215233. else
  215234. {
  215235. jassertfalse;
  215236. }
  215237. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215238. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215239. }
  215240. else
  215241. {
  215242. logError (hr);
  215243. jassertfalse;
  215244. }
  215245. bytesFilled -= bytesPerBuffer;
  215246. return true;
  215247. }
  215248. else
  215249. {
  215250. return false;
  215251. }
  215252. }
  215253. };
  215254. class DSoundAudioIODevice : public AudioIODevice,
  215255. public Thread
  215256. {
  215257. public:
  215258. DSoundAudioIODevice (const String& deviceName,
  215259. const int outputDeviceIndex_,
  215260. const int inputDeviceIndex_)
  215261. : AudioIODevice (deviceName, "DirectSound"),
  215262. Thread ("Juce DSound"),
  215263. isOpen_ (false),
  215264. isStarted (false),
  215265. outputDeviceIndex (outputDeviceIndex_),
  215266. inputDeviceIndex (inputDeviceIndex_),
  215267. totalSamplesOut (0),
  215268. sampleRate (0.0),
  215269. inputBuffers (1, 1),
  215270. outputBuffers (1, 1),
  215271. callback (0),
  215272. bufferSizeSamples (0)
  215273. {
  215274. if (outputDeviceIndex_ >= 0)
  215275. {
  215276. outChannels.add (TRANS("Left"));
  215277. outChannels.add (TRANS("Right"));
  215278. }
  215279. if (inputDeviceIndex_ >= 0)
  215280. {
  215281. inChannels.add (TRANS("Left"));
  215282. inChannels.add (TRANS("Right"));
  215283. }
  215284. }
  215285. ~DSoundAudioIODevice()
  215286. {
  215287. close();
  215288. }
  215289. const StringArray getOutputChannelNames()
  215290. {
  215291. return outChannels;
  215292. }
  215293. const StringArray getInputChannelNames()
  215294. {
  215295. return inChannels;
  215296. }
  215297. int getNumSampleRates()
  215298. {
  215299. return 4;
  215300. }
  215301. double getSampleRate (int index)
  215302. {
  215303. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215304. return samps [jlimit (0, 3, index)];
  215305. }
  215306. int getNumBufferSizesAvailable()
  215307. {
  215308. return 50;
  215309. }
  215310. int getBufferSizeSamples (int index)
  215311. {
  215312. int n = 64;
  215313. for (int i = 0; i < index; ++i)
  215314. n += (n < 512) ? 32
  215315. : ((n < 1024) ? 64
  215316. : ((n < 2048) ? 128 : 256));
  215317. return n;
  215318. }
  215319. int getDefaultBufferSize()
  215320. {
  215321. return 2560;
  215322. }
  215323. const String open (const BigInteger& inputChannels,
  215324. const BigInteger& outputChannels,
  215325. double sampleRate,
  215326. int bufferSizeSamples)
  215327. {
  215328. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215329. isOpen_ = lastError.isEmpty();
  215330. return lastError;
  215331. }
  215332. void close()
  215333. {
  215334. stop();
  215335. if (isOpen_)
  215336. {
  215337. closeDevice();
  215338. isOpen_ = false;
  215339. }
  215340. }
  215341. bool isOpen()
  215342. {
  215343. return isOpen_ && isThreadRunning();
  215344. }
  215345. int getCurrentBufferSizeSamples()
  215346. {
  215347. return bufferSizeSamples;
  215348. }
  215349. double getCurrentSampleRate()
  215350. {
  215351. return sampleRate;
  215352. }
  215353. int getCurrentBitDepth()
  215354. {
  215355. int i, bits = 256;
  215356. for (i = inChans.size(); --i >= 0;)
  215357. bits = jmin (bits, inChans[i]->bitDepth);
  215358. for (i = outChans.size(); --i >= 0;)
  215359. bits = jmin (bits, outChans[i]->bitDepth);
  215360. if (bits > 32)
  215361. bits = 16;
  215362. return bits;
  215363. }
  215364. const BigInteger getActiveOutputChannels() const
  215365. {
  215366. return enabledOutputs;
  215367. }
  215368. const BigInteger getActiveInputChannels() const
  215369. {
  215370. return enabledInputs;
  215371. }
  215372. int getOutputLatencyInSamples()
  215373. {
  215374. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215375. }
  215376. int getInputLatencyInSamples()
  215377. {
  215378. return getOutputLatencyInSamples();
  215379. }
  215380. void start (AudioIODeviceCallback* call)
  215381. {
  215382. if (isOpen_ && call != 0 && ! isStarted)
  215383. {
  215384. if (! isThreadRunning())
  215385. {
  215386. // something gone wrong and the thread's stopped..
  215387. isOpen_ = false;
  215388. return;
  215389. }
  215390. call->audioDeviceAboutToStart (this);
  215391. const ScopedLock sl (startStopLock);
  215392. callback = call;
  215393. isStarted = true;
  215394. }
  215395. }
  215396. void stop()
  215397. {
  215398. if (isStarted)
  215399. {
  215400. AudioIODeviceCallback* const callbackLocal = callback;
  215401. {
  215402. const ScopedLock sl (startStopLock);
  215403. isStarted = false;
  215404. }
  215405. if (callbackLocal != 0)
  215406. callbackLocal->audioDeviceStopped();
  215407. }
  215408. }
  215409. bool isPlaying()
  215410. {
  215411. return isStarted && isOpen_ && isThreadRunning();
  215412. }
  215413. const String getLastError()
  215414. {
  215415. return lastError;
  215416. }
  215417. juce_UseDebuggingNewOperator
  215418. StringArray inChannels, outChannels;
  215419. int outputDeviceIndex, inputDeviceIndex;
  215420. private:
  215421. bool isOpen_;
  215422. bool isStarted;
  215423. String lastError;
  215424. OwnedArray <DSoundInternalInChannel> inChans;
  215425. OwnedArray <DSoundInternalOutChannel> outChans;
  215426. WaitableEvent startEvent;
  215427. int bufferSizeSamples;
  215428. int volatile totalSamplesOut;
  215429. int64 volatile lastBlockTime;
  215430. double sampleRate;
  215431. BigInteger enabledInputs, enabledOutputs;
  215432. AudioSampleBuffer inputBuffers, outputBuffers;
  215433. AudioIODeviceCallback* callback;
  215434. CriticalSection startStopLock;
  215435. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215436. DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215437. const String openDevice (const BigInteger& inputChannels,
  215438. const BigInteger& outputChannels,
  215439. double sampleRate_,
  215440. int bufferSizeSamples_);
  215441. void closeDevice()
  215442. {
  215443. isStarted = false;
  215444. stopThread (5000);
  215445. inChans.clear();
  215446. outChans.clear();
  215447. inputBuffers.setSize (1, 1);
  215448. outputBuffers.setSize (1, 1);
  215449. }
  215450. void resync()
  215451. {
  215452. if (! threadShouldExit())
  215453. {
  215454. sleep (5);
  215455. int i;
  215456. for (i = 0; i < outChans.size(); ++i)
  215457. outChans.getUnchecked(i)->synchronisePosition();
  215458. for (i = 0; i < inChans.size(); ++i)
  215459. inChans.getUnchecked(i)->synchronisePosition();
  215460. }
  215461. }
  215462. public:
  215463. void run()
  215464. {
  215465. while (! threadShouldExit())
  215466. {
  215467. if (wait (100))
  215468. break;
  215469. }
  215470. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215471. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215472. while (! threadShouldExit())
  215473. {
  215474. int numToDo = 0;
  215475. uint32 startTime = Time::getMillisecondCounter();
  215476. int i;
  215477. for (i = inChans.size(); --i >= 0;)
  215478. {
  215479. inChans.getUnchecked(i)->doneFlag = false;
  215480. ++numToDo;
  215481. }
  215482. for (i = outChans.size(); --i >= 0;)
  215483. {
  215484. outChans.getUnchecked(i)->doneFlag = false;
  215485. ++numToDo;
  215486. }
  215487. if (numToDo > 0)
  215488. {
  215489. const int maxCount = 3;
  215490. int count = maxCount;
  215491. for (;;)
  215492. {
  215493. for (i = inChans.size(); --i >= 0;)
  215494. {
  215495. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215496. if ((! in->doneFlag) && in->service())
  215497. {
  215498. in->doneFlag = true;
  215499. --numToDo;
  215500. }
  215501. }
  215502. for (i = outChans.size(); --i >= 0;)
  215503. {
  215504. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215505. if ((! out->doneFlag) && out->service())
  215506. {
  215507. out->doneFlag = true;
  215508. --numToDo;
  215509. }
  215510. }
  215511. if (numToDo <= 0)
  215512. break;
  215513. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215514. {
  215515. resync();
  215516. break;
  215517. }
  215518. if (--count <= 0)
  215519. {
  215520. Sleep (1);
  215521. count = maxCount;
  215522. }
  215523. if (threadShouldExit())
  215524. return;
  215525. }
  215526. }
  215527. else
  215528. {
  215529. sleep (1);
  215530. }
  215531. const ScopedLock sl (startStopLock);
  215532. if (isStarted)
  215533. {
  215534. JUCE_TRY
  215535. {
  215536. callback->audioDeviceIOCallback (const_cast <const float**> (inputBuffers.getArrayOfChannels()),
  215537. inputBuffers.getNumChannels(),
  215538. outputBuffers.getArrayOfChannels(),
  215539. outputBuffers.getNumChannels(),
  215540. bufferSizeSamples);
  215541. }
  215542. JUCE_CATCH_EXCEPTION
  215543. totalSamplesOut += bufferSizeSamples;
  215544. }
  215545. else
  215546. {
  215547. outputBuffers.clear();
  215548. totalSamplesOut = 0;
  215549. sleep (1);
  215550. }
  215551. }
  215552. }
  215553. };
  215554. class DSoundAudioIODeviceType : public AudioIODeviceType
  215555. {
  215556. public:
  215557. DSoundAudioIODeviceType()
  215558. : AudioIODeviceType ("DirectSound"),
  215559. hasScanned (false)
  215560. {
  215561. initialiseDSoundFunctions();
  215562. }
  215563. ~DSoundAudioIODeviceType()
  215564. {
  215565. }
  215566. void scanForDevices()
  215567. {
  215568. hasScanned = true;
  215569. outputDeviceNames.clear();
  215570. outputGuids.clear();
  215571. inputDeviceNames.clear();
  215572. inputGuids.clear();
  215573. if (dsDirectSoundEnumerateW != 0)
  215574. {
  215575. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215576. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215577. }
  215578. }
  215579. const StringArray getDeviceNames (bool wantInputNames) const
  215580. {
  215581. jassert (hasScanned); // need to call scanForDevices() before doing this
  215582. return wantInputNames ? inputDeviceNames
  215583. : outputDeviceNames;
  215584. }
  215585. int getDefaultDeviceIndex (bool /*forInput*/) const
  215586. {
  215587. jassert (hasScanned); // need to call scanForDevices() before doing this
  215588. return 0;
  215589. }
  215590. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  215591. {
  215592. jassert (hasScanned); // need to call scanForDevices() before doing this
  215593. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215594. if (d == 0)
  215595. return -1;
  215596. return asInput ? d->inputDeviceIndex
  215597. : d->outputDeviceIndex;
  215598. }
  215599. bool hasSeparateInputsAndOutputs() const { return true; }
  215600. AudioIODevice* createDevice (const String& outputDeviceName,
  215601. const String& inputDeviceName)
  215602. {
  215603. jassert (hasScanned); // need to call scanForDevices() before doing this
  215604. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215605. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215606. if (outputIndex >= 0 || inputIndex >= 0)
  215607. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215608. : inputDeviceName,
  215609. outputIndex, inputIndex);
  215610. return 0;
  215611. }
  215612. juce_UseDebuggingNewOperator
  215613. StringArray outputDeviceNames;
  215614. OwnedArray <GUID> outputGuids;
  215615. StringArray inputDeviceNames;
  215616. OwnedArray <GUID> inputGuids;
  215617. private:
  215618. bool hasScanned;
  215619. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215620. {
  215621. desc = desc.trim();
  215622. if (desc.isNotEmpty())
  215623. {
  215624. const String origDesc (desc);
  215625. int n = 2;
  215626. while (outputDeviceNames.contains (desc))
  215627. desc = origDesc + " (" + String (n++) + ")";
  215628. outputDeviceNames.add (desc);
  215629. if (lpGUID != 0)
  215630. outputGuids.add (new GUID (*lpGUID));
  215631. else
  215632. outputGuids.add (0);
  215633. }
  215634. return TRUE;
  215635. }
  215636. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215637. {
  215638. return ((DSoundAudioIODeviceType*) object)
  215639. ->outputEnumProc (lpGUID, String (description));
  215640. }
  215641. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215642. {
  215643. return ((DSoundAudioIODeviceType*) object)
  215644. ->outputEnumProc (lpGUID, String (description));
  215645. }
  215646. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215647. {
  215648. desc = desc.trim();
  215649. if (desc.isNotEmpty())
  215650. {
  215651. const String origDesc (desc);
  215652. int n = 2;
  215653. while (inputDeviceNames.contains (desc))
  215654. desc = origDesc + " (" + String (n++) + ")";
  215655. inputDeviceNames.add (desc);
  215656. if (lpGUID != 0)
  215657. inputGuids.add (new GUID (*lpGUID));
  215658. else
  215659. inputGuids.add (0);
  215660. }
  215661. return TRUE;
  215662. }
  215663. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215664. {
  215665. return ((DSoundAudioIODeviceType*) object)
  215666. ->inputEnumProc (lpGUID, String (description));
  215667. }
  215668. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215669. {
  215670. return ((DSoundAudioIODeviceType*) object)
  215671. ->inputEnumProc (lpGUID, String (description));
  215672. }
  215673. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215674. DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215675. };
  215676. const String DSoundAudioIODevice::openDevice (const BigInteger& inputChannels,
  215677. const BigInteger& outputChannels,
  215678. double sampleRate_,
  215679. int bufferSizeSamples_)
  215680. {
  215681. closeDevice();
  215682. totalSamplesOut = 0;
  215683. sampleRate = sampleRate_;
  215684. if (bufferSizeSamples_ <= 0)
  215685. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215686. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215687. DSoundAudioIODeviceType dlh;
  215688. dlh.scanForDevices();
  215689. enabledInputs = inputChannels;
  215690. enabledInputs.setRange (inChannels.size(),
  215691. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215692. false);
  215693. inputBuffers.setSize (jmax (1, enabledInputs.countNumberOfSetBits()), bufferSizeSamples);
  215694. inputBuffers.clear();
  215695. int i, numIns = 0;
  215696. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215697. {
  215698. float* left = 0;
  215699. if (enabledInputs[i])
  215700. left = inputBuffers.getSampleData (numIns++);
  215701. float* right = 0;
  215702. if (enabledInputs[i + 1])
  215703. right = inputBuffers.getSampleData (numIns++);
  215704. if (left != 0 || right != 0)
  215705. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215706. dlh.inputGuids [inputDeviceIndex],
  215707. (int) sampleRate, bufferSizeSamples,
  215708. left, right));
  215709. }
  215710. enabledOutputs = outputChannels;
  215711. enabledOutputs.setRange (outChannels.size(),
  215712. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215713. false);
  215714. outputBuffers.setSize (jmax (1, enabledOutputs.countNumberOfSetBits()), bufferSizeSamples);
  215715. outputBuffers.clear();
  215716. int numOuts = 0;
  215717. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215718. {
  215719. float* left = 0;
  215720. if (enabledOutputs[i])
  215721. left = outputBuffers.getSampleData (numOuts++);
  215722. float* right = 0;
  215723. if (enabledOutputs[i + 1])
  215724. right = outputBuffers.getSampleData (numOuts++);
  215725. if (left != 0 || right != 0)
  215726. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215727. dlh.outputGuids [outputDeviceIndex],
  215728. (int) sampleRate, bufferSizeSamples,
  215729. left, right));
  215730. }
  215731. String error;
  215732. // boost our priority while opening the devices to try to get better sync between them
  215733. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215734. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215735. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215736. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215737. for (i = 0; i < outChans.size(); ++i)
  215738. {
  215739. error = outChans[i]->open();
  215740. if (error.isNotEmpty())
  215741. {
  215742. error = "Error opening " + dlh.outputDeviceNames[i] + ": \"" + error + "\"";
  215743. break;
  215744. }
  215745. }
  215746. if (error.isEmpty())
  215747. {
  215748. for (i = 0; i < inChans.size(); ++i)
  215749. {
  215750. error = inChans[i]->open();
  215751. if (error.isNotEmpty())
  215752. {
  215753. error = "Error opening " + dlh.inputDeviceNames[i] + ": \"" + error + "\"";
  215754. break;
  215755. }
  215756. }
  215757. }
  215758. if (error.isEmpty())
  215759. {
  215760. totalSamplesOut = 0;
  215761. for (i = 0; i < outChans.size(); ++i)
  215762. outChans.getUnchecked(i)->synchronisePosition();
  215763. for (i = 0; i < inChans.size(); ++i)
  215764. inChans.getUnchecked(i)->synchronisePosition();
  215765. startThread (9);
  215766. sleep (10);
  215767. notify();
  215768. }
  215769. else
  215770. {
  215771. log (error);
  215772. }
  215773. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215774. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215775. return error;
  215776. }
  215777. AudioIODeviceType* juce_createAudioIODeviceType_DirectSound()
  215778. {
  215779. return new DSoundAudioIODeviceType();
  215780. }
  215781. #undef log
  215782. #endif
  215783. /*** End of inlined file: juce_win32_DirectSound.cpp ***/
  215784. /*** Start of inlined file: juce_win32_WASAPI.cpp ***/
  215785. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  215786. // compiled on its own).
  215787. #if JUCE_INCLUDED_FILE && JUCE_WASAPI
  215788. #ifndef WASAPI_ENABLE_LOGGING
  215789. #define WASAPI_ENABLE_LOGGING 1
  215790. #endif
  215791. namespace WasapiClasses
  215792. {
  215793. void logFailure (HRESULT hr)
  215794. {
  215795. (void) hr;
  215796. #if WASAPI_ENABLE_LOGGING
  215797. if (FAILED (hr))
  215798. {
  215799. String e;
  215800. e << Time::getCurrentTime().toString (true, true, true, true)
  215801. << " -- WASAPI error: ";
  215802. switch (hr)
  215803. {
  215804. case E_POINTER: e << "E_POINTER"; break;
  215805. case E_INVALIDARG: e << "E_INVALIDARG"; break;
  215806. case AUDCLNT_E_NOT_INITIALIZED: e << "AUDCLNT_E_NOT_INITIALIZED"; break;
  215807. case AUDCLNT_E_ALREADY_INITIALIZED: e << "AUDCLNT_E_ALREADY_INITIALIZED"; break;
  215808. case AUDCLNT_E_WRONG_ENDPOINT_TYPE: e << "AUDCLNT_E_WRONG_ENDPOINT_TYPE"; break;
  215809. case AUDCLNT_E_DEVICE_INVALIDATED: e << "AUDCLNT_E_DEVICE_INVALIDATED"; break;
  215810. case AUDCLNT_E_NOT_STOPPED: e << "AUDCLNT_E_NOT_STOPPED"; break;
  215811. case AUDCLNT_E_BUFFER_TOO_LARGE: e << "AUDCLNT_E_BUFFER_TOO_LARGE"; break;
  215812. case AUDCLNT_E_OUT_OF_ORDER: e << "AUDCLNT_E_OUT_OF_ORDER"; break;
  215813. case AUDCLNT_E_UNSUPPORTED_FORMAT: e << "AUDCLNT_E_UNSUPPORTED_FORMAT"; break;
  215814. case AUDCLNT_E_INVALID_SIZE: e << "AUDCLNT_E_INVALID_SIZE"; break;
  215815. case AUDCLNT_E_DEVICE_IN_USE: e << "AUDCLNT_E_DEVICE_IN_USE"; break;
  215816. case AUDCLNT_E_BUFFER_OPERATION_PENDING: e << "AUDCLNT_E_BUFFER_OPERATION_PENDING"; break;
  215817. case AUDCLNT_E_THREAD_NOT_REGISTERED: e << "AUDCLNT_E_THREAD_NOT_REGISTERED"; break;
  215818. case AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED: e << "AUDCLNT_E_EXCLUSIVE_MODE_NOT_ALLOWED"; break;
  215819. case AUDCLNT_E_ENDPOINT_CREATE_FAILED: e << "AUDCLNT_E_ENDPOINT_CREATE_FAILED"; break;
  215820. case AUDCLNT_E_SERVICE_NOT_RUNNING: e << "AUDCLNT_E_SERVICE_NOT_RUNNING"; break;
  215821. case AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED: e << "AUDCLNT_E_EVENTHANDLE_NOT_EXPECTED"; break;
  215822. case AUDCLNT_E_EXCLUSIVE_MODE_ONLY: e << "AUDCLNT_E_EXCLUSIVE_MODE_ONLY"; break;
  215823. case AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL: e << "AUDCLNT_E_BUFDURATION_PERIOD_NOT_EQUAL"; break;
  215824. case AUDCLNT_E_EVENTHANDLE_NOT_SET: e << "AUDCLNT_E_EVENTHANDLE_NOT_SET"; break;
  215825. case AUDCLNT_E_INCORRECT_BUFFER_SIZE: e << "AUDCLNT_E_INCORRECT_BUFFER_SIZE"; break;
  215826. case AUDCLNT_E_BUFFER_SIZE_ERROR: e << "AUDCLNT_E_BUFFER_SIZE_ERROR"; break;
  215827. case AUDCLNT_S_BUFFER_EMPTY: e << "AUDCLNT_S_BUFFER_EMPTY"; break;
  215828. case AUDCLNT_S_THREAD_ALREADY_REGISTERED: e << "AUDCLNT_S_THREAD_ALREADY_REGISTERED"; break;
  215829. default: e << String::toHexString ((int) hr); break;
  215830. }
  215831. DBG (e);
  215832. jassertfalse;
  215833. }
  215834. #endif
  215835. }
  215836. #undef check
  215837. bool check (HRESULT hr)
  215838. {
  215839. logFailure (hr);
  215840. return SUCCEEDED (hr);
  215841. }
  215842. const String getDeviceID (IMMDevice* const device)
  215843. {
  215844. String s;
  215845. WCHAR* deviceId = 0;
  215846. if (check (device->GetId (&deviceId)))
  215847. {
  215848. s = String (deviceId);
  215849. CoTaskMemFree (deviceId);
  215850. }
  215851. return s;
  215852. }
  215853. EDataFlow getDataFlow (const ComSmartPtr<IMMDevice>& device)
  215854. {
  215855. EDataFlow flow = eRender;
  215856. ComSmartPtr <IMMEndpoint> endPoint;
  215857. if (check (device.QueryInterface (__uuidof (IMMEndpoint), endPoint)))
  215858. (void) check (endPoint->GetDataFlow (&flow));
  215859. return flow;
  215860. }
  215861. int refTimeToSamples (const REFERENCE_TIME& t, const double sampleRate) throw()
  215862. {
  215863. return roundDoubleToInt (sampleRate * ((double) t) * 0.0000001);
  215864. }
  215865. void copyWavFormat (WAVEFORMATEXTENSIBLE& dest, const WAVEFORMATEX* const src) throw()
  215866. {
  215867. memcpy (&dest, src, src->wFormatTag == WAVE_FORMAT_EXTENSIBLE ? sizeof (WAVEFORMATEXTENSIBLE)
  215868. : sizeof (WAVEFORMATEX));
  215869. }
  215870. class WASAPIDeviceBase
  215871. {
  215872. public:
  215873. WASAPIDeviceBase (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  215874. : device (device_),
  215875. sampleRate (0),
  215876. numChannels (0),
  215877. actualNumChannels (0),
  215878. defaultSampleRate (0),
  215879. minBufferSize (0),
  215880. defaultBufferSize (0),
  215881. latencySamples (0),
  215882. useExclusiveMode (useExclusiveMode_)
  215883. {
  215884. clientEvent = CreateEvent (0, false, false, _T("JuceWASAPI"));
  215885. ComSmartPtr <IAudioClient> tempClient (createClient());
  215886. if (tempClient == 0)
  215887. return;
  215888. REFERENCE_TIME defaultPeriod, minPeriod;
  215889. if (! check (tempClient->GetDevicePeriod (&defaultPeriod, &minPeriod)))
  215890. return;
  215891. WAVEFORMATEX* mixFormat = 0;
  215892. if (! check (tempClient->GetMixFormat (&mixFormat)))
  215893. return;
  215894. WAVEFORMATEXTENSIBLE format;
  215895. copyWavFormat (format, mixFormat);
  215896. CoTaskMemFree (mixFormat);
  215897. actualNumChannels = numChannels = format.Format.nChannels;
  215898. defaultSampleRate = format.Format.nSamplesPerSec;
  215899. minBufferSize = refTimeToSamples (minPeriod, defaultSampleRate);
  215900. defaultBufferSize = refTimeToSamples (defaultPeriod, defaultSampleRate);
  215901. rates.addUsingDefaultSort (defaultSampleRate);
  215902. static const double ratesToTest[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215903. for (int i = 0; i < numElementsInArray (ratesToTest); ++i)
  215904. {
  215905. if (ratesToTest[i] == defaultSampleRate)
  215906. continue;
  215907. format.Format.nSamplesPerSec = roundDoubleToInt (ratesToTest[i]);
  215908. if (SUCCEEDED (tempClient->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  215909. (WAVEFORMATEX*) &format, 0)))
  215910. if (! rates.contains (ratesToTest[i]))
  215911. rates.addUsingDefaultSort (ratesToTest[i]);
  215912. }
  215913. }
  215914. ~WASAPIDeviceBase()
  215915. {
  215916. device = 0;
  215917. CloseHandle (clientEvent);
  215918. }
  215919. bool isOk() const throw() { return defaultBufferSize > 0 && defaultSampleRate > 0; }
  215920. bool openClient (const double newSampleRate, const BigInteger& newChannels)
  215921. {
  215922. sampleRate = newSampleRate;
  215923. channels = newChannels;
  215924. channels.setRange (actualNumChannels, channels.getHighestBit() + 1 - actualNumChannels, false);
  215925. numChannels = channels.getHighestBit() + 1;
  215926. if (numChannels == 0)
  215927. return true;
  215928. client = createClient();
  215929. if (client != 0
  215930. && (tryInitialisingWithFormat (true, 4) || tryInitialisingWithFormat (false, 4)
  215931. || tryInitialisingWithFormat (false, 3) || tryInitialisingWithFormat (false, 2)))
  215932. {
  215933. channelMaps.clear();
  215934. for (int i = 0; i <= channels.getHighestBit(); ++i)
  215935. if (channels[i])
  215936. channelMaps.add (i);
  215937. REFERENCE_TIME latency;
  215938. if (check (client->GetStreamLatency (&latency)))
  215939. latencySamples = refTimeToSamples (latency, sampleRate);
  215940. (void) check (client->GetBufferSize (&actualBufferSize));
  215941. return check (client->SetEventHandle (clientEvent));
  215942. }
  215943. return false;
  215944. }
  215945. void closeClient()
  215946. {
  215947. if (client != 0)
  215948. client->Stop();
  215949. client = 0;
  215950. ResetEvent (clientEvent);
  215951. }
  215952. ComSmartPtr <IMMDevice> device;
  215953. ComSmartPtr <IAudioClient> client;
  215954. double sampleRate, defaultSampleRate;
  215955. int numChannels, actualNumChannels;
  215956. int minBufferSize, defaultBufferSize, latencySamples;
  215957. const bool useExclusiveMode;
  215958. Array <double> rates;
  215959. HANDLE clientEvent;
  215960. BigInteger channels;
  215961. Array <int> channelMaps;
  215962. UINT32 actualBufferSize;
  215963. int bytesPerSample;
  215964. virtual void updateFormat (bool isFloat) = 0;
  215965. private:
  215966. const ComSmartPtr <IAudioClient> createClient()
  215967. {
  215968. ComSmartPtr <IAudioClient> client;
  215969. if (device != 0)
  215970. {
  215971. HRESULT hr = device->Activate (__uuidof (IAudioClient), CLSCTX_INPROC_SERVER, 0, (void**) client.resetAndGetPointerAddress());
  215972. logFailure (hr);
  215973. }
  215974. return client;
  215975. }
  215976. bool tryInitialisingWithFormat (const bool useFloat, const int bytesPerSampleToTry)
  215977. {
  215978. WAVEFORMATEXTENSIBLE format;
  215979. zerostruct (format);
  215980. if (numChannels <= 2 && bytesPerSampleToTry <= 2)
  215981. {
  215982. format.Format.wFormatTag = WAVE_FORMAT_PCM;
  215983. }
  215984. else
  215985. {
  215986. format.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
  215987. format.Format.cbSize = sizeof (WAVEFORMATEXTENSIBLE) - sizeof (WAVEFORMATEX);
  215988. }
  215989. format.Format.nSamplesPerSec = roundDoubleToInt (sampleRate);
  215990. format.Format.nChannels = (WORD) numChannels;
  215991. format.Format.wBitsPerSample = (WORD) (8 * bytesPerSampleToTry);
  215992. format.Format.nAvgBytesPerSec = (DWORD) (format.Format.nSamplesPerSec * numChannels * bytesPerSampleToTry);
  215993. format.Format.nBlockAlign = (WORD) (numChannels * bytesPerSampleToTry);
  215994. format.SubFormat = useFloat ? KSDATAFORMAT_SUBTYPE_IEEE_FLOAT : KSDATAFORMAT_SUBTYPE_PCM;
  215995. format.Samples.wValidBitsPerSample = format.Format.wBitsPerSample;
  215996. switch (numChannels)
  215997. {
  215998. case 1: format.dwChannelMask = SPEAKER_FRONT_CENTER; break;
  215999. case 2: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT; break;
  216000. case 4: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  216001. case 6: format.dwChannelMask = SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT | SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY | SPEAKER_BACK_LEFT | SPEAKER_BACK_RIGHT; break;
  216002. 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;
  216003. default: break;
  216004. }
  216005. WAVEFORMATEXTENSIBLE* nearestFormat = 0;
  216006. HRESULT hr = client->IsFormatSupported (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  216007. (WAVEFORMATEX*) &format, useExclusiveMode ? 0 : (WAVEFORMATEX**) &nearestFormat);
  216008. logFailure (hr);
  216009. if (hr == S_FALSE && format.Format.nSamplesPerSec == nearestFormat->Format.nSamplesPerSec)
  216010. {
  216011. copyWavFormat (format, (WAVEFORMATEX*) nearestFormat);
  216012. hr = S_OK;
  216013. }
  216014. CoTaskMemFree (nearestFormat);
  216015. REFERENCE_TIME defaultPeriod = 0, minPeriod = 0;
  216016. if (useExclusiveMode)
  216017. check (client->GetDevicePeriod (&defaultPeriod, &minPeriod));
  216018. GUID session;
  216019. if (hr == S_OK
  216020. && check (client->Initialize (useExclusiveMode ? AUDCLNT_SHAREMODE_EXCLUSIVE : AUDCLNT_SHAREMODE_SHARED,
  216021. AUDCLNT_STREAMFLAGS_EVENTCALLBACK,
  216022. defaultPeriod, defaultPeriod, (WAVEFORMATEX*) &format, &session)))
  216023. {
  216024. actualNumChannels = format.Format.nChannels;
  216025. const bool isFloat = format.Format.wFormatTag == WAVE_FORMAT_EXTENSIBLE && format.SubFormat == KSDATAFORMAT_SUBTYPE_IEEE_FLOAT;
  216026. bytesPerSample = format.Format.wBitsPerSample / 8;
  216027. updateFormat (isFloat);
  216028. return true;
  216029. }
  216030. return false;
  216031. }
  216032. WASAPIDeviceBase (const WASAPIDeviceBase&);
  216033. WASAPIDeviceBase& operator= (const WASAPIDeviceBase&);
  216034. };
  216035. class WASAPIInputDevice : public WASAPIDeviceBase
  216036. {
  216037. public:
  216038. WASAPIInputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  216039. : WASAPIDeviceBase (device_, useExclusiveMode_),
  216040. reservoir (1, 1)
  216041. {
  216042. }
  216043. ~WASAPIInputDevice()
  216044. {
  216045. close();
  216046. }
  216047. bool open (const double newSampleRate, const BigInteger& newChannels)
  216048. {
  216049. reservoirSize = 0;
  216050. reservoirCapacity = 16384;
  216051. reservoir.setSize (actualNumChannels * reservoirCapacity * sizeof (float));
  216052. return openClient (newSampleRate, newChannels)
  216053. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioCaptureClient), (void**) captureClient.resetAndGetPointerAddress())));
  216054. }
  216055. void close()
  216056. {
  216057. closeClient();
  216058. captureClient = 0;
  216059. reservoir.setSize (0);
  216060. }
  216061. void updateFormat (bool isFloat)
  216062. {
  216063. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> NativeType;
  216064. if (isFloat)
  216065. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216066. else if (bytesPerSample == 4)
  216067. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216068. else if (bytesPerSample == 3)
  216069. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216070. else
  216071. converter = new AudioData::ConverterInstance <AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, NativeType> (actualNumChannels, 1);
  216072. }
  216073. void copyBuffers (float** destBuffers, int numDestBuffers, int bufferSize, Thread& thread)
  216074. {
  216075. if (numChannels <= 0)
  216076. return;
  216077. int offset = 0;
  216078. while (bufferSize > 0)
  216079. {
  216080. if (reservoirSize > 0) // There's stuff in the reservoir, so use that...
  216081. {
  216082. const int samplesToDo = jmin (bufferSize, (int) reservoirSize);
  216083. for (int i = 0; i < numDestBuffers; ++i)
  216084. converter->convertSamples (destBuffers[i] + offset, 0, reservoir.getData(), channelMaps.getUnchecked(i), samplesToDo);
  216085. bufferSize -= samplesToDo;
  216086. offset += samplesToDo;
  216087. reservoirSize -= samplesToDo;
  216088. }
  216089. else
  216090. {
  216091. UINT32 packetLength = 0;
  216092. if (! check (captureClient->GetNextPacketSize (&packetLength)))
  216093. break;
  216094. if (packetLength == 0)
  216095. {
  216096. if (thread.threadShouldExit())
  216097. break;
  216098. Thread::sleep (1);
  216099. continue;
  216100. }
  216101. uint8* inputData = 0;
  216102. UINT32 numSamplesAvailable;
  216103. DWORD flags;
  216104. if (check (captureClient->GetBuffer (&inputData, &numSamplesAvailable, &flags, 0, 0)))
  216105. {
  216106. const int samplesToDo = jmin (bufferSize, (int) numSamplesAvailable);
  216107. for (int i = 0; i < numDestBuffers; ++i)
  216108. converter->convertSamples (destBuffers[i] + offset, 0, inputData, channelMaps.getUnchecked(i), samplesToDo);
  216109. bufferSize -= samplesToDo;
  216110. offset += samplesToDo;
  216111. if (samplesToDo < (int) numSamplesAvailable)
  216112. {
  216113. reservoirSize = jmin ((int) (numSamplesAvailable - samplesToDo), reservoirCapacity);
  216114. memcpy ((uint8*) reservoir.getData(), inputData + bytesPerSample * actualNumChannels * samplesToDo,
  216115. bytesPerSample * actualNumChannels * reservoirSize);
  216116. }
  216117. captureClient->ReleaseBuffer (numSamplesAvailable);
  216118. }
  216119. }
  216120. }
  216121. }
  216122. ComSmartPtr <IAudioCaptureClient> captureClient;
  216123. MemoryBlock reservoir;
  216124. int reservoirSize, reservoirCapacity;
  216125. ScopedPointer <AudioData::Converter> converter;
  216126. private:
  216127. WASAPIInputDevice (const WASAPIInputDevice&);
  216128. WASAPIInputDevice& operator= (const WASAPIInputDevice&);
  216129. };
  216130. class WASAPIOutputDevice : public WASAPIDeviceBase
  216131. {
  216132. public:
  216133. WASAPIOutputDevice (const ComSmartPtr <IMMDevice>& device_, const bool useExclusiveMode_)
  216134. : WASAPIDeviceBase (device_, useExclusiveMode_)
  216135. {
  216136. }
  216137. ~WASAPIOutputDevice()
  216138. {
  216139. close();
  216140. }
  216141. bool open (const double newSampleRate, const BigInteger& newChannels)
  216142. {
  216143. return openClient (newSampleRate, newChannels)
  216144. && (numChannels == 0 || check (client->GetService (__uuidof (IAudioRenderClient), (void**) renderClient.resetAndGetPointerAddress())));
  216145. }
  216146. void close()
  216147. {
  216148. closeClient();
  216149. renderClient = 0;
  216150. }
  216151. void updateFormat (bool isFloat)
  216152. {
  216153. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> NativeType;
  216154. if (isFloat)
  216155. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Float32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216156. else if (bytesPerSample == 4)
  216157. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int32, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216158. else if (bytesPerSample == 3)
  216159. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int24, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216160. else
  216161. converter = new AudioData::ConverterInstance <NativeType, AudioData::Pointer <AudioData::Int16, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, actualNumChannels);
  216162. }
  216163. void copyBuffers (const float** const srcBuffers, const int numSrcBuffers, int bufferSize, Thread& thread)
  216164. {
  216165. if (numChannels <= 0)
  216166. return;
  216167. int offset = 0;
  216168. while (bufferSize > 0)
  216169. {
  216170. UINT32 padding = 0;
  216171. if (! check (client->GetCurrentPadding (&padding)))
  216172. return;
  216173. int samplesToDo = useExclusiveMode ? bufferSize
  216174. : jmin ((int) (actualBufferSize - padding), bufferSize);
  216175. if (samplesToDo <= 0)
  216176. {
  216177. if (thread.threadShouldExit())
  216178. break;
  216179. Thread::sleep (0);
  216180. continue;
  216181. }
  216182. uint8* outputData = 0;
  216183. if (check (renderClient->GetBuffer (samplesToDo, &outputData)))
  216184. {
  216185. for (int i = 0; i < numSrcBuffers; ++i)
  216186. converter->convertSamples (outputData, channelMaps.getUnchecked(i), srcBuffers[i] + offset, 0, samplesToDo);
  216187. renderClient->ReleaseBuffer (samplesToDo, 0);
  216188. offset += samplesToDo;
  216189. bufferSize -= samplesToDo;
  216190. }
  216191. }
  216192. }
  216193. ComSmartPtr <IAudioRenderClient> renderClient;
  216194. ScopedPointer <AudioData::Converter> converter;
  216195. private:
  216196. WASAPIOutputDevice (const WASAPIOutputDevice&);
  216197. WASAPIOutputDevice& operator= (const WASAPIOutputDevice&);
  216198. };
  216199. class WASAPIAudioIODevice : public AudioIODevice,
  216200. public Thread
  216201. {
  216202. public:
  216203. WASAPIAudioIODevice (const String& deviceName,
  216204. const String& outputDeviceId_,
  216205. const String& inputDeviceId_,
  216206. const bool useExclusiveMode_)
  216207. : AudioIODevice (deviceName, "Windows Audio"),
  216208. Thread ("Juce WASAPI"),
  216209. isOpen_ (false),
  216210. isStarted (false),
  216211. outputDeviceId (outputDeviceId_),
  216212. inputDeviceId (inputDeviceId_),
  216213. useExclusiveMode (useExclusiveMode_),
  216214. currentBufferSizeSamples (0),
  216215. currentSampleRate (0),
  216216. callback (0)
  216217. {
  216218. }
  216219. ~WASAPIAudioIODevice()
  216220. {
  216221. close();
  216222. }
  216223. bool initialise()
  216224. {
  216225. double defaultSampleRateIn = 0, defaultSampleRateOut = 0;
  216226. int minBufferSizeIn = 0, defaultBufferSizeIn = 0, minBufferSizeOut = 0, defaultBufferSizeOut = 0;
  216227. latencyIn = latencyOut = 0;
  216228. Array <double> ratesIn, ratesOut;
  216229. if (createDevices())
  216230. {
  216231. jassert (inputDevice != 0 || outputDevice != 0);
  216232. if (inputDevice != 0 && outputDevice != 0)
  216233. {
  216234. defaultSampleRate = jmin (inputDevice->defaultSampleRate, outputDevice->defaultSampleRate);
  216235. minBufferSize = jmin (inputDevice->minBufferSize, outputDevice->minBufferSize);
  216236. defaultBufferSize = jmax (inputDevice->defaultBufferSize, outputDevice->defaultBufferSize);
  216237. sampleRates = inputDevice->rates;
  216238. sampleRates.removeValuesNotIn (outputDevice->rates);
  216239. }
  216240. else
  216241. {
  216242. WASAPIDeviceBase* d = inputDevice != 0 ? static_cast<WASAPIDeviceBase*> (inputDevice)
  216243. : static_cast<WASAPIDeviceBase*> (outputDevice);
  216244. defaultSampleRate = d->defaultSampleRate;
  216245. minBufferSize = d->minBufferSize;
  216246. defaultBufferSize = d->defaultBufferSize;
  216247. sampleRates = d->rates;
  216248. }
  216249. bufferSizes.addUsingDefaultSort (defaultBufferSize);
  216250. if (minBufferSize != defaultBufferSize)
  216251. bufferSizes.addUsingDefaultSort (minBufferSize);
  216252. int n = 64;
  216253. for (int i = 0; i < 40; ++i)
  216254. {
  216255. if (n >= minBufferSize && n <= 2048 && ! bufferSizes.contains (n))
  216256. bufferSizes.addUsingDefaultSort (n);
  216257. n += (n < 512) ? 32 : (n < 1024 ? 64 : 128);
  216258. }
  216259. return true;
  216260. }
  216261. return false;
  216262. }
  216263. const StringArray getOutputChannelNames()
  216264. {
  216265. StringArray outChannels;
  216266. if (outputDevice != 0)
  216267. for (int i = 1; i <= outputDevice->actualNumChannels; ++i)
  216268. outChannels.add ("Output channel " + String (i));
  216269. return outChannels;
  216270. }
  216271. const StringArray getInputChannelNames()
  216272. {
  216273. StringArray inChannels;
  216274. if (inputDevice != 0)
  216275. for (int i = 1; i <= inputDevice->actualNumChannels; ++i)
  216276. inChannels.add ("Input channel " + String (i));
  216277. return inChannels;
  216278. }
  216279. int getNumSampleRates() { return sampleRates.size(); }
  216280. double getSampleRate (int index) { return sampleRates [index]; }
  216281. int getNumBufferSizesAvailable() { return bufferSizes.size(); }
  216282. int getBufferSizeSamples (int index) { return bufferSizes [index]; }
  216283. int getDefaultBufferSize() { return defaultBufferSize; }
  216284. int getCurrentBufferSizeSamples() { return currentBufferSizeSamples; }
  216285. double getCurrentSampleRate() { return currentSampleRate; }
  216286. int getCurrentBitDepth() { return 32; }
  216287. int getOutputLatencyInSamples() { return latencyOut; }
  216288. int getInputLatencyInSamples() { return latencyIn; }
  216289. const BigInteger getActiveOutputChannels() const { return outputDevice != 0 ? outputDevice->channels : BigInteger(); }
  216290. const BigInteger getActiveInputChannels() const { return inputDevice != 0 ? inputDevice->channels : BigInteger(); }
  216291. const String getLastError() { return lastError; }
  216292. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  216293. double sampleRate, int bufferSizeSamples)
  216294. {
  216295. close();
  216296. lastError = String::empty;
  216297. if (sampleRates.size() == 0 && inputDevice != 0 && outputDevice != 0)
  216298. {
  216299. lastError = "The input and output devices don't share a common sample rate!";
  216300. return lastError;
  216301. }
  216302. currentBufferSizeSamples = bufferSizeSamples <= 0 ? defaultBufferSize : jmax (bufferSizeSamples, minBufferSize);
  216303. currentSampleRate = sampleRate > 0 ? sampleRate : defaultSampleRate;
  216304. if (inputDevice != 0 && ! inputDevice->open (currentSampleRate, inputChannels))
  216305. {
  216306. lastError = "Couldn't open the input device!";
  216307. return lastError;
  216308. }
  216309. if (outputDevice != 0 && ! outputDevice->open (currentSampleRate, outputChannels))
  216310. {
  216311. close();
  216312. lastError = "Couldn't open the output device!";
  216313. return lastError;
  216314. }
  216315. if (inputDevice != 0)
  216316. ResetEvent (inputDevice->clientEvent);
  216317. if (outputDevice != 0)
  216318. ResetEvent (outputDevice->clientEvent);
  216319. startThread (8);
  216320. Thread::sleep (5);
  216321. if (inputDevice != 0 && inputDevice->client != 0)
  216322. {
  216323. latencyIn = inputDevice->latencySamples + inputDevice->actualBufferSize + inputDevice->minBufferSize;
  216324. HRESULT hr = inputDevice->client->Start();
  216325. logFailure (hr); //xxx handle this
  216326. }
  216327. if (outputDevice != 0 && outputDevice->client != 0)
  216328. {
  216329. latencyOut = outputDevice->latencySamples + outputDevice->actualBufferSize + outputDevice->minBufferSize;
  216330. HRESULT hr = outputDevice->client->Start();
  216331. logFailure (hr); //xxx handle this
  216332. }
  216333. isOpen_ = true;
  216334. return lastError;
  216335. }
  216336. void close()
  216337. {
  216338. stop();
  216339. if (inputDevice != 0)
  216340. SetEvent (inputDevice->clientEvent);
  216341. if (outputDevice != 0)
  216342. SetEvent (outputDevice->clientEvent);
  216343. stopThread (5000);
  216344. if (inputDevice != 0)
  216345. inputDevice->close();
  216346. if (outputDevice != 0)
  216347. outputDevice->close();
  216348. isOpen_ = false;
  216349. }
  216350. bool isOpen() { return isOpen_ && isThreadRunning(); }
  216351. bool isPlaying() { return isStarted && isOpen_ && isThreadRunning(); }
  216352. void start (AudioIODeviceCallback* call)
  216353. {
  216354. if (isOpen_ && call != 0 && ! isStarted)
  216355. {
  216356. if (! isThreadRunning())
  216357. {
  216358. // something's gone wrong and the thread's stopped..
  216359. isOpen_ = false;
  216360. return;
  216361. }
  216362. call->audioDeviceAboutToStart (this);
  216363. const ScopedLock sl (startStopLock);
  216364. callback = call;
  216365. isStarted = true;
  216366. }
  216367. }
  216368. void stop()
  216369. {
  216370. if (isStarted)
  216371. {
  216372. AudioIODeviceCallback* const callbackLocal = callback;
  216373. {
  216374. const ScopedLock sl (startStopLock);
  216375. isStarted = false;
  216376. }
  216377. if (callbackLocal != 0)
  216378. callbackLocal->audioDeviceStopped();
  216379. }
  216380. }
  216381. void setMMThreadPriority()
  216382. {
  216383. DynamicLibraryLoader dll ("avrt.dll");
  216384. DynamicLibraryImport (AvSetMmThreadCharacteristics, avSetMmThreadCharacteristics, HANDLE, dll, (LPCTSTR, LPDWORD))
  216385. DynamicLibraryImport (AvSetMmThreadPriority, avSetMmThreadPriority, HANDLE, dll, (HANDLE, AVRT_PRIORITY))
  216386. if (avSetMmThreadCharacteristics != 0 && avSetMmThreadPriority != 0)
  216387. {
  216388. DWORD dummy = 0;
  216389. HANDLE h = avSetMmThreadCharacteristics (_T("Pro Audio"), &dummy);
  216390. if (h != 0)
  216391. avSetMmThreadPriority (h, AVRT_PRIORITY_NORMAL);
  216392. }
  216393. }
  216394. void run()
  216395. {
  216396. setMMThreadPriority();
  216397. const int bufferSize = currentBufferSizeSamples;
  216398. HANDLE events[2];
  216399. int numEvents = 0;
  216400. if (inputDevice != 0)
  216401. events [numEvents++] = inputDevice->clientEvent;
  216402. if (outputDevice != 0)
  216403. events [numEvents++] = outputDevice->clientEvent;
  216404. const int numInputBuffers = getActiveInputChannels().countNumberOfSetBits();
  216405. const int numOutputBuffers = getActiveOutputChannels().countNumberOfSetBits();
  216406. AudioSampleBuffer ins (jmax (1, numInputBuffers), bufferSize + 32);
  216407. AudioSampleBuffer outs (jmax (1, numOutputBuffers), bufferSize + 32);
  216408. float** const inputBuffers = ins.getArrayOfChannels();
  216409. float** const outputBuffers = outs.getArrayOfChannels();
  216410. ins.clear();
  216411. while (! threadShouldExit())
  216412. {
  216413. const DWORD result = useExclusiveMode ? (inputDevice != 0 ? WaitForSingleObject (inputDevice->clientEvent, 1000) : S_OK)
  216414. : WaitForMultipleObjects (numEvents, events, true, 1000);
  216415. if (result == WAIT_TIMEOUT)
  216416. continue;
  216417. if (threadShouldExit())
  216418. break;
  216419. if (inputDevice != 0)
  216420. inputDevice->copyBuffers (inputBuffers, numInputBuffers, bufferSize, *this);
  216421. // Make the callback..
  216422. {
  216423. const ScopedLock sl (startStopLock);
  216424. if (isStarted)
  216425. {
  216426. JUCE_TRY
  216427. {
  216428. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  216429. numInputBuffers,
  216430. outputBuffers,
  216431. numOutputBuffers,
  216432. bufferSize);
  216433. }
  216434. JUCE_CATCH_EXCEPTION
  216435. }
  216436. else
  216437. {
  216438. outs.clear();
  216439. }
  216440. }
  216441. if (useExclusiveMode && WaitForSingleObject (outputDevice->clientEvent, 1000) == WAIT_TIMEOUT)
  216442. continue;
  216443. if (outputDevice != 0)
  216444. outputDevice->copyBuffers ((const float**) outputBuffers, numOutputBuffers, bufferSize, *this);
  216445. }
  216446. }
  216447. juce_UseDebuggingNewOperator
  216448. String outputDeviceId, inputDeviceId;
  216449. String lastError;
  216450. private:
  216451. // Device stats...
  216452. ScopedPointer<WASAPIInputDevice> inputDevice;
  216453. ScopedPointer<WASAPIOutputDevice> outputDevice;
  216454. const bool useExclusiveMode;
  216455. double defaultSampleRate;
  216456. int minBufferSize, defaultBufferSize;
  216457. int latencyIn, latencyOut;
  216458. Array <double> sampleRates;
  216459. Array <int> bufferSizes;
  216460. // Active state...
  216461. bool isOpen_, isStarted;
  216462. int currentBufferSizeSamples;
  216463. double currentSampleRate;
  216464. AudioIODeviceCallback* callback;
  216465. CriticalSection startStopLock;
  216466. bool createDevices()
  216467. {
  216468. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216469. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216470. return false;
  216471. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216472. if (! check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress())))
  216473. return false;
  216474. UINT32 numDevices = 0;
  216475. if (! check (deviceCollection->GetCount (&numDevices)))
  216476. return false;
  216477. for (UINT32 i = 0; i < numDevices; ++i)
  216478. {
  216479. ComSmartPtr <IMMDevice> device;
  216480. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216481. continue;
  216482. const String deviceId (getDeviceID (device));
  216483. if (deviceId.isEmpty())
  216484. continue;
  216485. const EDataFlow flow = getDataFlow (device);
  216486. if (deviceId == inputDeviceId && flow == eCapture)
  216487. inputDevice = new WASAPIInputDevice (device, useExclusiveMode);
  216488. else if (deviceId == outputDeviceId && flow == eRender)
  216489. outputDevice = new WASAPIOutputDevice (device, useExclusiveMode);
  216490. }
  216491. return (outputDeviceId.isEmpty() || (outputDevice != 0 && outputDevice->isOk()))
  216492. && (inputDeviceId.isEmpty() || (inputDevice != 0 && inputDevice->isOk()));
  216493. }
  216494. WASAPIAudioIODevice (const WASAPIAudioIODevice&);
  216495. WASAPIAudioIODevice& operator= (const WASAPIAudioIODevice&);
  216496. };
  216497. class WASAPIAudioIODeviceType : public AudioIODeviceType
  216498. {
  216499. public:
  216500. WASAPIAudioIODeviceType()
  216501. : AudioIODeviceType ("Windows Audio"),
  216502. hasScanned (false)
  216503. {
  216504. }
  216505. ~WASAPIAudioIODeviceType()
  216506. {
  216507. }
  216508. void scanForDevices()
  216509. {
  216510. hasScanned = true;
  216511. outputDeviceNames.clear();
  216512. inputDeviceNames.clear();
  216513. outputDeviceIds.clear();
  216514. inputDeviceIds.clear();
  216515. ComSmartPtr <IMMDeviceEnumerator> enumerator;
  216516. if (! check (enumerator.CoCreateInstance (__uuidof (MMDeviceEnumerator))))
  216517. return;
  216518. const String defaultRenderer = getDefaultEndpoint (enumerator, false);
  216519. const String defaultCapture = getDefaultEndpoint (enumerator, true);
  216520. ComSmartPtr <IMMDeviceCollection> deviceCollection;
  216521. UINT32 numDevices = 0;
  216522. if (! (check (enumerator->EnumAudioEndpoints (eAll, DEVICE_STATE_ACTIVE, deviceCollection.resetAndGetPointerAddress()))
  216523. && check (deviceCollection->GetCount (&numDevices))))
  216524. return;
  216525. for (UINT32 i = 0; i < numDevices; ++i)
  216526. {
  216527. ComSmartPtr <IMMDevice> device;
  216528. if (! check (deviceCollection->Item (i, device.resetAndGetPointerAddress())))
  216529. continue;
  216530. const String deviceId (getDeviceID (device));
  216531. DWORD state = 0;
  216532. if (! check (device->GetState (&state)))
  216533. continue;
  216534. if (state != DEVICE_STATE_ACTIVE)
  216535. continue;
  216536. String name;
  216537. {
  216538. ComSmartPtr <IPropertyStore> properties;
  216539. if (! check (device->OpenPropertyStore (STGM_READ, properties.resetAndGetPointerAddress())))
  216540. continue;
  216541. PROPVARIANT value;
  216542. PropVariantInit (&value);
  216543. if (check (properties->GetValue (PKEY_Device_FriendlyName, &value)))
  216544. name = value.pwszVal;
  216545. PropVariantClear (&value);
  216546. }
  216547. const EDataFlow flow = getDataFlow (device);
  216548. if (flow == eRender)
  216549. {
  216550. const int index = (deviceId == defaultRenderer) ? 0 : -1;
  216551. outputDeviceIds.insert (index, deviceId);
  216552. outputDeviceNames.insert (index, name);
  216553. }
  216554. else if (flow == eCapture)
  216555. {
  216556. const int index = (deviceId == defaultCapture) ? 0 : -1;
  216557. inputDeviceIds.insert (index, deviceId);
  216558. inputDeviceNames.insert (index, name);
  216559. }
  216560. }
  216561. inputDeviceNames.appendNumbersToDuplicates (false, false);
  216562. outputDeviceNames.appendNumbersToDuplicates (false, false);
  216563. }
  216564. const StringArray getDeviceNames (bool wantInputNames) const
  216565. {
  216566. jassert (hasScanned); // need to call scanForDevices() before doing this
  216567. return wantInputNames ? inputDeviceNames
  216568. : outputDeviceNames;
  216569. }
  216570. int getDefaultDeviceIndex (bool /*forInput*/) const
  216571. {
  216572. jassert (hasScanned); // need to call scanForDevices() before doing this
  216573. return 0;
  216574. }
  216575. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  216576. {
  216577. jassert (hasScanned); // need to call scanForDevices() before doing this
  216578. WASAPIAudioIODevice* const d = dynamic_cast <WASAPIAudioIODevice*> (device);
  216579. return d == 0 ? -1 : (asInput ? inputDeviceIds.indexOf (d->inputDeviceId)
  216580. : outputDeviceIds.indexOf (d->outputDeviceId));
  216581. }
  216582. bool hasSeparateInputsAndOutputs() const { return true; }
  216583. AudioIODevice* createDevice (const String& outputDeviceName,
  216584. const String& inputDeviceName)
  216585. {
  216586. jassert (hasScanned); // need to call scanForDevices() before doing this
  216587. const bool useExclusiveMode = false;
  216588. ScopedPointer<WASAPIAudioIODevice> device;
  216589. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  216590. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  216591. if (outputIndex >= 0 || inputIndex >= 0)
  216592. {
  216593. device = new WASAPIAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  216594. : inputDeviceName,
  216595. outputDeviceIds [outputIndex],
  216596. inputDeviceIds [inputIndex],
  216597. useExclusiveMode);
  216598. if (! device->initialise())
  216599. device = 0;
  216600. }
  216601. return device.release();
  216602. }
  216603. juce_UseDebuggingNewOperator
  216604. StringArray outputDeviceNames, outputDeviceIds;
  216605. StringArray inputDeviceNames, inputDeviceIds;
  216606. private:
  216607. bool hasScanned;
  216608. static const String getDefaultEndpoint (IMMDeviceEnumerator* const enumerator, const bool forCapture)
  216609. {
  216610. String s;
  216611. IMMDevice* dev = 0;
  216612. if (check (enumerator->GetDefaultAudioEndpoint (forCapture ? eCapture : eRender,
  216613. eMultimedia, &dev)))
  216614. {
  216615. WCHAR* deviceId = 0;
  216616. if (check (dev->GetId (&deviceId)))
  216617. {
  216618. s = String (deviceId);
  216619. CoTaskMemFree (deviceId);
  216620. }
  216621. dev->Release();
  216622. }
  216623. return s;
  216624. }
  216625. WASAPIAudioIODeviceType (const WASAPIAudioIODeviceType&);
  216626. WASAPIAudioIODeviceType& operator= (const WASAPIAudioIODeviceType&);
  216627. };
  216628. }
  216629. AudioIODeviceType* juce_createAudioIODeviceType_WASAPI()
  216630. {
  216631. return new WasapiClasses::WASAPIAudioIODeviceType();
  216632. }
  216633. #endif
  216634. /*** End of inlined file: juce_win32_WASAPI.cpp ***/
  216635. /*** Start of inlined file: juce_win32_CameraDevice.cpp ***/
  216636. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  216637. // compiled on its own).
  216638. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  216639. class DShowCameraDeviceInteral : public ChangeBroadcaster
  216640. {
  216641. public:
  216642. DShowCameraDeviceInteral (CameraDevice* const owner_,
  216643. const ComSmartPtr <ICaptureGraphBuilder2>& captureGraphBuilder_,
  216644. const ComSmartPtr <IBaseFilter>& filter_,
  216645. int minWidth, int minHeight,
  216646. int maxWidth, int maxHeight)
  216647. : owner (owner_),
  216648. captureGraphBuilder (captureGraphBuilder_),
  216649. filter (filter_),
  216650. ok (false),
  216651. imageNeedsFlipping (false),
  216652. width (0),
  216653. height (0),
  216654. activeUsers (0),
  216655. recordNextFrameTime (false),
  216656. previewMaxFPS (60)
  216657. {
  216658. HRESULT hr = graphBuilder.CoCreateInstance (CLSID_FilterGraph);
  216659. if (FAILED (hr))
  216660. return;
  216661. hr = captureGraphBuilder->SetFiltergraph (graphBuilder);
  216662. if (FAILED (hr))
  216663. return;
  216664. hr = graphBuilder.QueryInterface (IID_IMediaControl, mediaControl);
  216665. if (FAILED (hr))
  216666. return;
  216667. {
  216668. ComSmartPtr <IAMStreamConfig> streamConfig;
  216669. hr = captureGraphBuilder->FindInterface (&PIN_CATEGORY_CAPTURE, 0, filter,
  216670. IID_IAMStreamConfig, (void**) streamConfig.resetAndGetPointerAddress());
  216671. if (streamConfig != 0)
  216672. {
  216673. getVideoSizes (streamConfig);
  216674. if (! selectVideoSize (streamConfig, minWidth, minHeight, maxWidth, maxHeight))
  216675. return;
  216676. }
  216677. }
  216678. hr = graphBuilder->AddFilter (filter, _T("Video Capture"));
  216679. if (FAILED (hr))
  216680. return;
  216681. hr = smartTee.CoCreateInstance (CLSID_SmartTee);
  216682. if (FAILED (hr))
  216683. return;
  216684. hr = graphBuilder->AddFilter (smartTee, _T("Smart Tee"));
  216685. if (FAILED (hr))
  216686. return;
  216687. if (! connectFilters (filter, smartTee))
  216688. return;
  216689. ComSmartPtr <IBaseFilter> sampleGrabberBase;
  216690. hr = sampleGrabberBase.CoCreateInstance (CLSID_SampleGrabber);
  216691. if (FAILED (hr))
  216692. return;
  216693. hr = sampleGrabberBase.QueryInterface (IID_ISampleGrabber, sampleGrabber);
  216694. if (FAILED (hr))
  216695. return;
  216696. AM_MEDIA_TYPE mt;
  216697. zerostruct (mt);
  216698. mt.majortype = MEDIATYPE_Video;
  216699. mt.subtype = MEDIASUBTYPE_RGB24;
  216700. mt.formattype = FORMAT_VideoInfo;
  216701. sampleGrabber->SetMediaType (&mt);
  216702. callback = new GrabberCallback (*this);
  216703. hr = sampleGrabber->SetCallback (callback, 1);
  216704. hr = graphBuilder->AddFilter (sampleGrabberBase, _T("Sample Grabber"));
  216705. if (FAILED (hr))
  216706. return;
  216707. ComSmartPtr <IPin> grabberInputPin;
  216708. if (! (getPin (smartTee, PINDIR_OUTPUT, smartTeeCaptureOutputPin, "capture")
  216709. && getPin (smartTee, PINDIR_OUTPUT, smartTeePreviewOutputPin, "preview")
  216710. && getPin (sampleGrabberBase, PINDIR_INPUT, grabberInputPin)))
  216711. return;
  216712. hr = graphBuilder->Connect (smartTeePreviewOutputPin, grabberInputPin);
  216713. if (FAILED (hr))
  216714. return;
  216715. zerostruct (mt);
  216716. hr = sampleGrabber->GetConnectedMediaType (&mt);
  216717. VIDEOINFOHEADER* pVih = (VIDEOINFOHEADER*) (mt.pbFormat);
  216718. width = pVih->bmiHeader.biWidth;
  216719. height = pVih->bmiHeader.biHeight;
  216720. ComSmartPtr <IBaseFilter> nullFilter;
  216721. hr = nullFilter.CoCreateInstance (CLSID_NullRenderer);
  216722. hr = graphBuilder->AddFilter (nullFilter, _T("Null Renderer"));
  216723. if (connectFilters (sampleGrabberBase, nullFilter)
  216724. && addGraphToRot())
  216725. {
  216726. activeImage = Image (Image::RGB, width, height, true);
  216727. loadingImage = Image (Image::RGB, width, height, true);
  216728. ok = true;
  216729. }
  216730. }
  216731. ~DShowCameraDeviceInteral()
  216732. {
  216733. if (mediaControl != 0)
  216734. mediaControl->Stop();
  216735. removeGraphFromRot();
  216736. for (int i = viewerComps.size(); --i >= 0;)
  216737. viewerComps.getUnchecked(i)->ownerDeleted();
  216738. callback = 0;
  216739. graphBuilder = 0;
  216740. sampleGrabber = 0;
  216741. mediaControl = 0;
  216742. filter = 0;
  216743. captureGraphBuilder = 0;
  216744. smartTee = 0;
  216745. smartTeePreviewOutputPin = 0;
  216746. smartTeeCaptureOutputPin = 0;
  216747. asfWriter = 0;
  216748. }
  216749. void addUser()
  216750. {
  216751. if (ok && activeUsers++ == 0)
  216752. mediaControl->Run();
  216753. }
  216754. void removeUser()
  216755. {
  216756. if (ok && --activeUsers == 0)
  216757. mediaControl->Stop();
  216758. }
  216759. int getPreviewMaxFPS() const
  216760. {
  216761. return previewMaxFPS;
  216762. }
  216763. void handleFrame (double /*time*/, BYTE* buffer, long /*bufferSize*/)
  216764. {
  216765. if (recordNextFrameTime)
  216766. {
  216767. const double defaultCameraLatency = 0.1;
  216768. firstRecordedTime = Time::getCurrentTime() - RelativeTime (defaultCameraLatency);
  216769. recordNextFrameTime = false;
  216770. ComSmartPtr <IPin> pin;
  216771. if (getPin (filter, PINDIR_OUTPUT, pin))
  216772. {
  216773. ComSmartPtr <IAMPushSource> pushSource;
  216774. HRESULT hr = pin.QueryInterface (IID_IAMPushSource, pushSource);
  216775. if (pushSource != 0)
  216776. {
  216777. REFERENCE_TIME latency = 0;
  216778. hr = pushSource->GetLatency (&latency);
  216779. firstRecordedTime = firstRecordedTime - RelativeTime ((double) latency);
  216780. }
  216781. }
  216782. }
  216783. {
  216784. const int lineStride = width * 3;
  216785. const ScopedLock sl (imageSwapLock);
  216786. {
  216787. const Image::BitmapData destData (loadingImage, 0, 0, width, height, true);
  216788. for (int i = 0; i < height; ++i)
  216789. memcpy (destData.getLinePointer ((height - 1) - i),
  216790. buffer + lineStride * i,
  216791. lineStride);
  216792. }
  216793. imageNeedsFlipping = true;
  216794. }
  216795. if (listeners.size() > 0)
  216796. callListeners (loadingImage);
  216797. sendChangeMessage (this);
  216798. }
  216799. void drawCurrentImage (Graphics& g, int x, int y, int w, int h)
  216800. {
  216801. if (imageNeedsFlipping)
  216802. {
  216803. const ScopedLock sl (imageSwapLock);
  216804. swapVariables (loadingImage, activeImage);
  216805. imageNeedsFlipping = false;
  216806. }
  216807. RectanglePlacement rp (RectanglePlacement::centred);
  216808. double dx = 0, dy = 0, dw = width, dh = height;
  216809. rp.applyTo (dx, dy, dw, dh, x, y, w, h);
  216810. const int rx = roundToInt (dx), ry = roundToInt (dy);
  216811. const int rw = roundToInt (dw), rh = roundToInt (dh);
  216812. g.saveState();
  216813. g.excludeClipRegion (Rectangle<int> (rx, ry, rw, rh));
  216814. g.fillAll (Colours::black);
  216815. g.restoreState();
  216816. g.drawImage (activeImage, rx, ry, rw, rh, 0, 0, width, height);
  216817. }
  216818. bool createFileCaptureFilter (const File& file, int quality)
  216819. {
  216820. removeFileCaptureFilter();
  216821. file.deleteFile();
  216822. mediaControl->Stop();
  216823. firstRecordedTime = Time();
  216824. recordNextFrameTime = true;
  216825. previewMaxFPS = 60;
  216826. HRESULT hr = asfWriter.CoCreateInstance (CLSID_WMAsfWriter);
  216827. if (SUCCEEDED (hr))
  216828. {
  216829. ComSmartPtr <IFileSinkFilter> fileSink;
  216830. hr = asfWriter.QueryInterface (IID_IFileSinkFilter, fileSink);
  216831. if (SUCCEEDED (hr))
  216832. {
  216833. hr = fileSink->SetFileName (file.getFullPathName(), 0);
  216834. if (SUCCEEDED (hr))
  216835. {
  216836. hr = graphBuilder->AddFilter (asfWriter, _T("AsfWriter"));
  216837. if (SUCCEEDED (hr))
  216838. {
  216839. ComSmartPtr <IConfigAsfWriter> asfConfig;
  216840. hr = asfWriter.QueryInterface (IID_IConfigAsfWriter, asfConfig);
  216841. asfConfig->SetIndexMode (true);
  216842. ComSmartPtr <IWMProfileManager> profileManager;
  216843. hr = WMCreateProfileManager (profileManager.resetAndGetPointerAddress());
  216844. // This gibberish is the DirectShow profile for a video-only wmv file.
  216845. String prof ("<profile version=\"589824\" storageformat=\"1\" name=\"Quality\" description=\"Quality type for output.\">"
  216846. " <streamconfig majortype=\"{73646976-0000-0010-8000-00AA00389B71}\" streamnumber=\"1\""
  216847. " streamname=\"Video Stream\" inputname=\"Video409\" bitrate=\"894960\""
  216848. " bufferwindow=\"0\" reliabletransport=\"1\" decodercomplexity=\"AU\" rfc1766langid=\"en-us\">"
  216849. " <videomediaprops maxkeyframespacing=\"50000000\" quality=\"90\"/>"
  216850. " <wmmediatype subtype=\"{33564D57-0000-0010-8000-00AA00389B71}\" bfixedsizesamples=\"0\""
  216851. " btemporalcompression=\"1\" lsamplesize=\"0\">"
  216852. " <videoinfoheader dwbitrate=\"894960\" dwbiterrorrate=\"0\" avgtimeperframe=\"$AVGTIMEPERFRAME\">"
  216853. " <rcsource left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216854. " <rctarget left=\"0\" top=\"0\" right=\"$WIDTH\" bottom=\"$HEIGHT\"/>"
  216855. " <bitmapinfoheader biwidth=\"$WIDTH\" biheight=\"$HEIGHT\" biplanes=\"1\" bibitcount=\"24\""
  216856. " bicompression=\"WMV3\" bisizeimage=\"0\" bixpelspermeter=\"0\" biypelspermeter=\"0\""
  216857. " biclrused=\"0\" biclrimportant=\"0\"/>"
  216858. " </videoinfoheader>"
  216859. " </wmmediatype>"
  216860. " </streamconfig>"
  216861. "</profile>");
  216862. const int fps[] = { 10, 15, 30 };
  216863. const int maxFramesPerSecond = fps [quality % numElementsInArray (fps)];
  216864. prof = prof.replace ("$WIDTH", String (width))
  216865. .replace ("$HEIGHT", String (height))
  216866. .replace ("$AVGTIMEPERFRAME", String (10000000 / maxFramesPerSecond));
  216867. ComSmartPtr <IWMProfile> currentProfile;
  216868. hr = profileManager->LoadProfileByData ((const WCHAR*) prof, currentProfile.resetAndGetPointerAddress());
  216869. hr = asfConfig->ConfigureFilterUsingProfile (currentProfile);
  216870. if (SUCCEEDED (hr))
  216871. {
  216872. ComSmartPtr <IPin> asfWriterInputPin;
  216873. if (getPin (asfWriter, PINDIR_INPUT, asfWriterInputPin, "Video Input 01"))
  216874. {
  216875. hr = graphBuilder->Connect (smartTeeCaptureOutputPin, asfWriterInputPin);
  216876. if (SUCCEEDED (hr)
  216877. && ok && activeUsers > 0
  216878. && SUCCEEDED (mediaControl->Run()))
  216879. {
  216880. previewMaxFPS = (quality < 2) ? 15 : 25; // throttle back the preview comps to try to leave the cpu free for encoding
  216881. return true;
  216882. }
  216883. }
  216884. }
  216885. }
  216886. }
  216887. }
  216888. }
  216889. removeFileCaptureFilter();
  216890. if (ok && activeUsers > 0)
  216891. mediaControl->Run();
  216892. return false;
  216893. }
  216894. void removeFileCaptureFilter()
  216895. {
  216896. mediaControl->Stop();
  216897. if (asfWriter != 0)
  216898. {
  216899. graphBuilder->RemoveFilter (asfWriter);
  216900. asfWriter = 0;
  216901. }
  216902. if (ok && activeUsers > 0)
  216903. mediaControl->Run();
  216904. previewMaxFPS = 60;
  216905. }
  216906. void addListener (CameraDevice::Listener* listenerToAdd)
  216907. {
  216908. const ScopedLock sl (listenerLock);
  216909. if (listeners.size() == 0)
  216910. addUser();
  216911. listeners.addIfNotAlreadyThere (listenerToAdd);
  216912. }
  216913. void removeListener (CameraDevice::Listener* listenerToRemove)
  216914. {
  216915. const ScopedLock sl (listenerLock);
  216916. listeners.removeValue (listenerToRemove);
  216917. if (listeners.size() == 0)
  216918. removeUser();
  216919. }
  216920. void callListeners (const Image& image)
  216921. {
  216922. const ScopedLock sl (listenerLock);
  216923. for (int i = listeners.size(); --i >= 0;)
  216924. {
  216925. CameraDevice::Listener* const l = listeners[i];
  216926. if (l != 0)
  216927. l->imageReceived (image);
  216928. }
  216929. }
  216930. class DShowCaptureViewerComp : public Component,
  216931. public ChangeListener
  216932. {
  216933. public:
  216934. DShowCaptureViewerComp (DShowCameraDeviceInteral* const owner_)
  216935. : owner (owner_), maxFPS (15), lastRepaintTime (0)
  216936. {
  216937. setOpaque (true);
  216938. owner->addChangeListener (this);
  216939. owner->addUser();
  216940. owner->viewerComps.add (this);
  216941. setSize (owner->width, owner->height);
  216942. }
  216943. ~DShowCaptureViewerComp()
  216944. {
  216945. if (owner != 0)
  216946. {
  216947. owner->viewerComps.removeValue (this);
  216948. owner->removeUser();
  216949. owner->removeChangeListener (this);
  216950. }
  216951. }
  216952. void ownerDeleted()
  216953. {
  216954. owner = 0;
  216955. }
  216956. void paint (Graphics& g)
  216957. {
  216958. g.setColour (Colours::black);
  216959. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  216960. if (owner != 0)
  216961. owner->drawCurrentImage (g, 0, 0, getWidth(), getHeight());
  216962. else
  216963. g.fillAll (Colours::black);
  216964. }
  216965. void changeListenerCallback (void*)
  216966. {
  216967. const int64 now = Time::currentTimeMillis();
  216968. if (now >= lastRepaintTime + (1000 / maxFPS))
  216969. {
  216970. lastRepaintTime = now;
  216971. repaint();
  216972. if (owner != 0)
  216973. maxFPS = owner->getPreviewMaxFPS();
  216974. }
  216975. }
  216976. private:
  216977. DShowCameraDeviceInteral* owner;
  216978. int maxFPS;
  216979. int64 lastRepaintTime;
  216980. };
  216981. bool ok;
  216982. int width, height;
  216983. Time firstRecordedTime;
  216984. Array <DShowCaptureViewerComp*> viewerComps;
  216985. private:
  216986. CameraDevice* const owner;
  216987. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  216988. ComSmartPtr <IBaseFilter> filter;
  216989. ComSmartPtr <IBaseFilter> smartTee;
  216990. ComSmartPtr <IGraphBuilder> graphBuilder;
  216991. ComSmartPtr <ISampleGrabber> sampleGrabber;
  216992. ComSmartPtr <IMediaControl> mediaControl;
  216993. ComSmartPtr <IPin> smartTeePreviewOutputPin;
  216994. ComSmartPtr <IPin> smartTeeCaptureOutputPin;
  216995. ComSmartPtr <IBaseFilter> asfWriter;
  216996. int activeUsers;
  216997. Array <int> widths, heights;
  216998. DWORD graphRegistrationID;
  216999. CriticalSection imageSwapLock;
  217000. bool imageNeedsFlipping;
  217001. Image loadingImage;
  217002. Image activeImage;
  217003. bool recordNextFrameTime;
  217004. int previewMaxFPS;
  217005. void getVideoSizes (IAMStreamConfig* const streamConfig)
  217006. {
  217007. widths.clear();
  217008. heights.clear();
  217009. int count = 0, size = 0;
  217010. streamConfig->GetNumberOfCapabilities (&count, &size);
  217011. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  217012. {
  217013. for (int i = 0; i < count; ++i)
  217014. {
  217015. VIDEO_STREAM_CONFIG_CAPS scc;
  217016. AM_MEDIA_TYPE* config;
  217017. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  217018. if (SUCCEEDED (hr))
  217019. {
  217020. const int w = scc.InputSize.cx;
  217021. const int h = scc.InputSize.cy;
  217022. bool duplicate = false;
  217023. for (int j = widths.size(); --j >= 0;)
  217024. {
  217025. if (w == widths.getUnchecked (j) && h == heights.getUnchecked (j))
  217026. {
  217027. duplicate = true;
  217028. break;
  217029. }
  217030. }
  217031. if (! duplicate)
  217032. {
  217033. DBG ("Camera capture size: " + String (w) + ", " + String (h));
  217034. widths.add (w);
  217035. heights.add (h);
  217036. }
  217037. deleteMediaType (config);
  217038. }
  217039. }
  217040. }
  217041. }
  217042. bool selectVideoSize (IAMStreamConfig* const streamConfig,
  217043. const int minWidth, const int minHeight,
  217044. const int maxWidth, const int maxHeight)
  217045. {
  217046. int count = 0, size = 0, bestArea = 0, bestIndex = -1;
  217047. streamConfig->GetNumberOfCapabilities (&count, &size);
  217048. if (size == sizeof (VIDEO_STREAM_CONFIG_CAPS))
  217049. {
  217050. AM_MEDIA_TYPE* config;
  217051. VIDEO_STREAM_CONFIG_CAPS scc;
  217052. for (int i = 0; i < count; ++i)
  217053. {
  217054. HRESULT hr = streamConfig->GetStreamCaps (i, &config, (BYTE*) &scc);
  217055. if (SUCCEEDED (hr))
  217056. {
  217057. if (scc.InputSize.cx >= minWidth
  217058. && scc.InputSize.cy >= minHeight
  217059. && scc.InputSize.cx <= maxWidth
  217060. && scc.InputSize.cy <= maxHeight)
  217061. {
  217062. int area = scc.InputSize.cx * scc.InputSize.cy;
  217063. if (area > bestArea)
  217064. {
  217065. bestIndex = i;
  217066. bestArea = area;
  217067. }
  217068. }
  217069. deleteMediaType (config);
  217070. }
  217071. }
  217072. if (bestIndex >= 0)
  217073. {
  217074. HRESULT hr = streamConfig->GetStreamCaps (bestIndex, &config, (BYTE*) &scc);
  217075. hr = streamConfig->SetFormat (config);
  217076. deleteMediaType (config);
  217077. return SUCCEEDED (hr);
  217078. }
  217079. }
  217080. return false;
  217081. }
  217082. static bool getPin (IBaseFilter* filter, const PIN_DIRECTION wantedDirection, ComSmartPtr<IPin>& result, const char* pinName = 0)
  217083. {
  217084. ComSmartPtr <IEnumPins> enumerator;
  217085. ComSmartPtr <IPin> pin;
  217086. filter->EnumPins (enumerator.resetAndGetPointerAddress());
  217087. while (enumerator->Next (1, pin.resetAndGetPointerAddress(), 0) == S_OK)
  217088. {
  217089. PIN_DIRECTION dir;
  217090. pin->QueryDirection (&dir);
  217091. if (wantedDirection == dir)
  217092. {
  217093. PIN_INFO info;
  217094. zerostruct (info);
  217095. pin->QueryPinInfo (&info);
  217096. if (pinName == 0 || String (pinName).equalsIgnoreCase (String (info.achName)))
  217097. {
  217098. result = pin;
  217099. return true;
  217100. }
  217101. }
  217102. }
  217103. return false;
  217104. }
  217105. bool connectFilters (IBaseFilter* const first, IBaseFilter* const second) const
  217106. {
  217107. ComSmartPtr <IPin> in, out;
  217108. return getPin (first, PINDIR_OUTPUT, out)
  217109. && getPin (second, PINDIR_INPUT, in)
  217110. && SUCCEEDED (graphBuilder->Connect (out, in));
  217111. }
  217112. bool addGraphToRot()
  217113. {
  217114. ComSmartPtr <IRunningObjectTable> rot;
  217115. if (FAILED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  217116. return false;
  217117. ComSmartPtr <IMoniker> moniker;
  217118. WCHAR buffer[128];
  217119. HRESULT hr = CreateItemMoniker (_T("!"), buffer, moniker.resetAndGetPointerAddress());
  217120. if (FAILED (hr))
  217121. return false;
  217122. graphRegistrationID = 0;
  217123. return SUCCEEDED (rot->Register (0, graphBuilder, moniker, &graphRegistrationID));
  217124. }
  217125. void removeGraphFromRot()
  217126. {
  217127. ComSmartPtr <IRunningObjectTable> rot;
  217128. if (SUCCEEDED (GetRunningObjectTable (0, rot.resetAndGetPointerAddress())))
  217129. rot->Revoke (graphRegistrationID);
  217130. }
  217131. static void deleteMediaType (AM_MEDIA_TYPE* const pmt)
  217132. {
  217133. if (pmt->cbFormat != 0)
  217134. CoTaskMemFree ((PVOID) pmt->pbFormat);
  217135. if (pmt->pUnk != 0)
  217136. pmt->pUnk->Release();
  217137. CoTaskMemFree (pmt);
  217138. }
  217139. class GrabberCallback : public ComBaseClassHelper <ISampleGrabberCB>
  217140. {
  217141. public:
  217142. GrabberCallback (DShowCameraDeviceInteral& owner_)
  217143. : owner (owner_)
  217144. {
  217145. }
  217146. STDMETHODIMP SampleCB (double /*SampleTime*/, IMediaSample* /*pSample*/)
  217147. {
  217148. return E_FAIL;
  217149. }
  217150. STDMETHODIMP BufferCB (double time, BYTE* buffer, long bufferSize)
  217151. {
  217152. owner.handleFrame (time, buffer, bufferSize);
  217153. return S_OK;
  217154. }
  217155. private:
  217156. DShowCameraDeviceInteral& owner;
  217157. GrabberCallback (const GrabberCallback&);
  217158. GrabberCallback& operator= (const GrabberCallback&);
  217159. };
  217160. ComSmartPtr <GrabberCallback> callback;
  217161. Array <CameraDevice::Listener*> listeners;
  217162. CriticalSection listenerLock;
  217163. DShowCameraDeviceInteral (const DShowCameraDeviceInteral&);
  217164. DShowCameraDeviceInteral& operator= (const DShowCameraDeviceInteral&);
  217165. };
  217166. CameraDevice::CameraDevice (const String& name_, int /*index*/)
  217167. : name (name_)
  217168. {
  217169. isRecording = false;
  217170. }
  217171. CameraDevice::~CameraDevice()
  217172. {
  217173. stopRecording();
  217174. delete static_cast <DShowCameraDeviceInteral*> (internal);
  217175. internal = 0;
  217176. }
  217177. Component* CameraDevice::createViewerComponent()
  217178. {
  217179. return new DShowCameraDeviceInteral::DShowCaptureViewerComp (static_cast <DShowCameraDeviceInteral*> (internal));
  217180. }
  217181. const String CameraDevice::getFileExtension()
  217182. {
  217183. return ".wmv";
  217184. }
  217185. void CameraDevice::startRecordingToFile (const File& file, int quality)
  217186. {
  217187. jassert (quality >= 0 && quality <= 2);
  217188. stopRecording();
  217189. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217190. d->addUser();
  217191. isRecording = d->createFileCaptureFilter (file, quality);
  217192. }
  217193. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  217194. {
  217195. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217196. return d->firstRecordedTime;
  217197. }
  217198. void CameraDevice::stopRecording()
  217199. {
  217200. if (isRecording)
  217201. {
  217202. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217203. d->removeFileCaptureFilter();
  217204. d->removeUser();
  217205. isRecording = false;
  217206. }
  217207. }
  217208. void CameraDevice::addListener (Listener* listenerToAdd)
  217209. {
  217210. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217211. if (listenerToAdd != 0)
  217212. d->addListener (listenerToAdd);
  217213. }
  217214. void CameraDevice::removeListener (Listener* listenerToRemove)
  217215. {
  217216. DShowCameraDeviceInteral* const d = (DShowCameraDeviceInteral*) internal;
  217217. if (listenerToRemove != 0)
  217218. d->removeListener (listenerToRemove);
  217219. }
  217220. namespace
  217221. {
  217222. ComSmartPtr <IBaseFilter> enumerateCameras (StringArray* const names,
  217223. const int deviceIndexToOpen,
  217224. String& name)
  217225. {
  217226. int index = 0;
  217227. ComSmartPtr <IBaseFilter> result;
  217228. ComSmartPtr <ICreateDevEnum> pDevEnum;
  217229. HRESULT hr = pDevEnum.CoCreateInstance (CLSID_SystemDeviceEnum);
  217230. if (SUCCEEDED (hr))
  217231. {
  217232. ComSmartPtr <IEnumMoniker> enumerator;
  217233. hr = pDevEnum->CreateClassEnumerator (CLSID_VideoInputDeviceCategory, enumerator.resetAndGetPointerAddress(), 0);
  217234. if (SUCCEEDED (hr) && enumerator != 0)
  217235. {
  217236. ComSmartPtr <IMoniker> moniker;
  217237. ULONG fetched;
  217238. while (enumerator->Next (1, moniker.resetAndGetPointerAddress(), &fetched) == S_OK)
  217239. {
  217240. ComSmartPtr <IBaseFilter> captureFilter;
  217241. hr = moniker->BindToObject (0, 0, IID_IBaseFilter, (void**) captureFilter.resetAndGetPointerAddress());
  217242. if (SUCCEEDED (hr))
  217243. {
  217244. ComSmartPtr <IPropertyBag> propertyBag;
  217245. hr = moniker->BindToStorage (0, 0, IID_IPropertyBag, (void**) propertyBag.resetAndGetPointerAddress());
  217246. if (SUCCEEDED (hr))
  217247. {
  217248. VARIANT var;
  217249. var.vt = VT_BSTR;
  217250. hr = propertyBag->Read (_T("FriendlyName"), &var, 0);
  217251. propertyBag = 0;
  217252. if (SUCCEEDED (hr))
  217253. {
  217254. if (names != 0)
  217255. names->add (var.bstrVal);
  217256. if (index == deviceIndexToOpen)
  217257. {
  217258. name = var.bstrVal;
  217259. result = captureFilter;
  217260. break;
  217261. }
  217262. ++index;
  217263. }
  217264. }
  217265. }
  217266. }
  217267. }
  217268. }
  217269. return result;
  217270. }
  217271. }
  217272. const StringArray CameraDevice::getAvailableDevices()
  217273. {
  217274. StringArray devs;
  217275. String dummy;
  217276. enumerateCameras (&devs, -1, dummy);
  217277. return devs;
  217278. }
  217279. CameraDevice* CameraDevice::openDevice (int index,
  217280. int minWidth, int minHeight,
  217281. int maxWidth, int maxHeight)
  217282. {
  217283. ComSmartPtr <ICaptureGraphBuilder2> captureGraphBuilder;
  217284. HRESULT hr = captureGraphBuilder.CoCreateInstance (CLSID_CaptureGraphBuilder2);
  217285. if (SUCCEEDED (hr))
  217286. {
  217287. String name;
  217288. const ComSmartPtr <IBaseFilter> filter (enumerateCameras (0, index, name));
  217289. if (filter != 0)
  217290. {
  217291. ScopedPointer <CameraDevice> cam (new CameraDevice (name, index));
  217292. DShowCameraDeviceInteral* const intern
  217293. = new DShowCameraDeviceInteral (cam, captureGraphBuilder, filter,
  217294. minWidth, minHeight, maxWidth, maxHeight);
  217295. cam->internal = intern;
  217296. if (intern->ok)
  217297. return cam.release();
  217298. }
  217299. }
  217300. return 0;
  217301. }
  217302. #endif
  217303. /*** End of inlined file: juce_win32_CameraDevice.cpp ***/
  217304. #endif
  217305. // Auto-link the other win32 libs that are needed by library calls..
  217306. #if (JUCE_AMALGAMATED_TEMPLATE || defined (JUCE_DLL_BUILD)) && JUCE_MSVC && ! DONT_AUTOLINK_TO_WIN32_LIBRARIES
  217307. /*** Start of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217308. // Auto-links to various win32 libs that are needed by library calls..
  217309. #pragma comment(lib, "kernel32.lib")
  217310. #pragma comment(lib, "user32.lib")
  217311. #pragma comment(lib, "shell32.lib")
  217312. #pragma comment(lib, "gdi32.lib")
  217313. #pragma comment(lib, "vfw32.lib")
  217314. #pragma comment(lib, "comdlg32.lib")
  217315. #pragma comment(lib, "winmm.lib")
  217316. #pragma comment(lib, "wininet.lib")
  217317. #pragma comment(lib, "ole32.lib")
  217318. #pragma comment(lib, "oleaut32.lib")
  217319. #pragma comment(lib, "advapi32.lib")
  217320. #pragma comment(lib, "ws2_32.lib")
  217321. #pragma comment(lib, "version.lib")
  217322. #ifdef _NATIVE_WCHAR_T_DEFINED
  217323. #ifdef _DEBUG
  217324. #pragma comment(lib, "comsuppwd.lib")
  217325. #else
  217326. #pragma comment(lib, "comsuppw.lib")
  217327. #endif
  217328. #else
  217329. #ifdef _DEBUG
  217330. #pragma comment(lib, "comsuppd.lib")
  217331. #else
  217332. #pragma comment(lib, "comsupp.lib")
  217333. #endif
  217334. #endif
  217335. #if JUCE_OPENGL
  217336. #pragma comment(lib, "OpenGL32.Lib")
  217337. #pragma comment(lib, "GlU32.Lib")
  217338. #endif
  217339. #if JUCE_QUICKTIME
  217340. #pragma comment (lib, "QTMLClient.lib")
  217341. #endif
  217342. #if JUCE_USE_CAMERA
  217343. #pragma comment (lib, "Strmiids.lib")
  217344. #pragma comment (lib, "wmvcore.lib")
  217345. #endif
  217346. #if JUCE_DIRECT2D
  217347. #pragma comment (lib, "Dwrite.lib")
  217348. #pragma comment (lib, "D2d1.lib")
  217349. #endif
  217350. /*** End of inlined file: juce_win32_AutoLinkLibraries.h ***/
  217351. #endif
  217352. END_JUCE_NAMESPACE
  217353. #endif
  217354. /*** End of inlined file: juce_win32_NativeCode.cpp ***/
  217355. #endif
  217356. #if JUCE_LINUX
  217357. /*** Start of inlined file: juce_linux_NativeCode.cpp ***/
  217358. /*
  217359. This file wraps together all the mac-specific code, so that
  217360. we can include all the native headers just once, and compile all our
  217361. platform-specific stuff in one big lump, keeping it out of the way of
  217362. the rest of the codebase.
  217363. */
  217364. #if JUCE_LINUX
  217365. BEGIN_JUCE_NAMESPACE
  217366. #define JUCE_INCLUDED_FILE 1
  217367. // Now include the actual code files..
  217368. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  217369. /*
  217370. This file contains posix routines that are common to both the Linux and Mac builds.
  217371. It gets included directly in the cpp files for these platforms.
  217372. */
  217373. CriticalSection::CriticalSection() throw()
  217374. {
  217375. pthread_mutexattr_t atts;
  217376. pthread_mutexattr_init (&atts);
  217377. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  217378. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217379. pthread_mutex_init (&internal, &atts);
  217380. }
  217381. CriticalSection::~CriticalSection() throw()
  217382. {
  217383. pthread_mutex_destroy (&internal);
  217384. }
  217385. void CriticalSection::enter() const throw()
  217386. {
  217387. pthread_mutex_lock (&internal);
  217388. }
  217389. bool CriticalSection::tryEnter() const throw()
  217390. {
  217391. return pthread_mutex_trylock (&internal) == 0;
  217392. }
  217393. void CriticalSection::exit() const throw()
  217394. {
  217395. pthread_mutex_unlock (&internal);
  217396. }
  217397. class WaitableEventImpl
  217398. {
  217399. public:
  217400. WaitableEventImpl (const bool manualReset_)
  217401. : triggered (false),
  217402. manualReset (manualReset_)
  217403. {
  217404. pthread_cond_init (&condition, 0);
  217405. pthread_mutexattr_t atts;
  217406. pthread_mutexattr_init (&atts);
  217407. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  217408. pthread_mutex_init (&mutex, &atts);
  217409. }
  217410. ~WaitableEventImpl()
  217411. {
  217412. pthread_cond_destroy (&condition);
  217413. pthread_mutex_destroy (&mutex);
  217414. }
  217415. bool wait (const int timeOutMillisecs) throw()
  217416. {
  217417. pthread_mutex_lock (&mutex);
  217418. if (! triggered)
  217419. {
  217420. if (timeOutMillisecs < 0)
  217421. {
  217422. do
  217423. {
  217424. pthread_cond_wait (&condition, &mutex);
  217425. }
  217426. while (! triggered);
  217427. }
  217428. else
  217429. {
  217430. struct timeval now;
  217431. gettimeofday (&now, 0);
  217432. struct timespec time;
  217433. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  217434. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  217435. if (time.tv_nsec >= 1000000000)
  217436. {
  217437. time.tv_nsec -= 1000000000;
  217438. time.tv_sec++;
  217439. }
  217440. do
  217441. {
  217442. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  217443. {
  217444. pthread_mutex_unlock (&mutex);
  217445. return false;
  217446. }
  217447. }
  217448. while (! triggered);
  217449. }
  217450. }
  217451. if (! manualReset)
  217452. triggered = false;
  217453. pthread_mutex_unlock (&mutex);
  217454. return true;
  217455. }
  217456. void signal() throw()
  217457. {
  217458. pthread_mutex_lock (&mutex);
  217459. triggered = true;
  217460. pthread_cond_broadcast (&condition);
  217461. pthread_mutex_unlock (&mutex);
  217462. }
  217463. void reset() throw()
  217464. {
  217465. pthread_mutex_lock (&mutex);
  217466. triggered = false;
  217467. pthread_mutex_unlock (&mutex);
  217468. }
  217469. private:
  217470. pthread_cond_t condition;
  217471. pthread_mutex_t mutex;
  217472. bool triggered;
  217473. const bool manualReset;
  217474. WaitableEventImpl (const WaitableEventImpl&);
  217475. WaitableEventImpl& operator= (const WaitableEventImpl&);
  217476. };
  217477. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  217478. : internal (new WaitableEventImpl (manualReset))
  217479. {
  217480. }
  217481. WaitableEvent::~WaitableEvent() throw()
  217482. {
  217483. delete static_cast <WaitableEventImpl*> (internal);
  217484. }
  217485. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  217486. {
  217487. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  217488. }
  217489. void WaitableEvent::signal() const throw()
  217490. {
  217491. static_cast <WaitableEventImpl*> (internal)->signal();
  217492. }
  217493. void WaitableEvent::reset() const throw()
  217494. {
  217495. static_cast <WaitableEventImpl*> (internal)->reset();
  217496. }
  217497. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  217498. {
  217499. struct timespec time;
  217500. time.tv_sec = millisecs / 1000;
  217501. time.tv_nsec = (millisecs % 1000) * 1000000;
  217502. nanosleep (&time, 0);
  217503. }
  217504. const juce_wchar File::separator = '/';
  217505. const String File::separatorString ("/");
  217506. const File File::getCurrentWorkingDirectory()
  217507. {
  217508. HeapBlock<char> heapBuffer;
  217509. char localBuffer [1024];
  217510. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  217511. int bufferSize = 4096;
  217512. while (cwd == 0 && errno == ERANGE)
  217513. {
  217514. heapBuffer.malloc (bufferSize);
  217515. cwd = getcwd (heapBuffer, bufferSize - 1);
  217516. bufferSize += 1024;
  217517. }
  217518. return File (String::fromUTF8 (cwd));
  217519. }
  217520. bool File::setAsCurrentWorkingDirectory() const
  217521. {
  217522. return chdir (getFullPathName().toUTF8()) == 0;
  217523. }
  217524. namespace
  217525. {
  217526. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217527. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  217528. #else
  217529. typedef struct stat juce_statStruct;
  217530. #endif
  217531. bool juce_stat (const String& fileName, juce_statStruct& info)
  217532. {
  217533. return fileName.isNotEmpty()
  217534. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217535. && (stat64 (fileName.toUTF8(), &info) == 0);
  217536. #else
  217537. && (stat (fileName.toUTF8(), &info) == 0);
  217538. #endif
  217539. }
  217540. // if this file doesn't exist, find a parent of it that does..
  217541. bool juce_doStatFS (File f, struct statfs& result)
  217542. {
  217543. for (int i = 5; --i >= 0;)
  217544. {
  217545. if (f.exists())
  217546. break;
  217547. f = f.getParentDirectory();
  217548. }
  217549. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  217550. }
  217551. }
  217552. bool File::isDirectory() const
  217553. {
  217554. juce_statStruct info;
  217555. return fullPath.isEmpty()
  217556. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  217557. }
  217558. bool File::exists() const
  217559. {
  217560. juce_statStruct info;
  217561. return fullPath.isNotEmpty()
  217562. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  217563. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  217564. #else
  217565. && (lstat (fullPath.toUTF8(), &info) == 0);
  217566. #endif
  217567. }
  217568. bool File::existsAsFile() const
  217569. {
  217570. return exists() && ! isDirectory();
  217571. }
  217572. int64 File::getSize() const
  217573. {
  217574. juce_statStruct info;
  217575. return juce_stat (fullPath, info) ? info.st_size : 0;
  217576. }
  217577. bool File::hasWriteAccess() const
  217578. {
  217579. if (exists())
  217580. return access (fullPath.toUTF8(), W_OK) == 0;
  217581. if ((! isDirectory()) && fullPath.containsChar (separator))
  217582. return getParentDirectory().hasWriteAccess();
  217583. return false;
  217584. }
  217585. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  217586. {
  217587. juce_statStruct info;
  217588. if (! juce_stat (fullPath, info))
  217589. return false;
  217590. info.st_mode &= 0777; // Just permissions
  217591. if (shouldBeReadOnly)
  217592. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  217593. else
  217594. // Give everybody write permission?
  217595. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  217596. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  217597. }
  217598. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  217599. {
  217600. modificationTime = 0;
  217601. accessTime = 0;
  217602. creationTime = 0;
  217603. juce_statStruct info;
  217604. if (juce_stat (fullPath, info))
  217605. {
  217606. modificationTime = (int64) info.st_mtime * 1000;
  217607. accessTime = (int64) info.st_atime * 1000;
  217608. creationTime = (int64) info.st_ctime * 1000;
  217609. }
  217610. }
  217611. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  217612. {
  217613. struct utimbuf times;
  217614. times.actime = (time_t) (accessTime / 1000);
  217615. times.modtime = (time_t) (modificationTime / 1000);
  217616. return utime (fullPath.toUTF8(), &times) == 0;
  217617. }
  217618. bool File::deleteFile() const
  217619. {
  217620. if (! exists())
  217621. return true;
  217622. else if (isDirectory())
  217623. return rmdir (fullPath.toUTF8()) == 0;
  217624. else
  217625. return remove (fullPath.toUTF8()) == 0;
  217626. }
  217627. bool File::moveInternal (const File& dest) const
  217628. {
  217629. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  217630. return true;
  217631. if (hasWriteAccess() && copyInternal (dest))
  217632. {
  217633. if (deleteFile())
  217634. return true;
  217635. dest.deleteFile();
  217636. }
  217637. return false;
  217638. }
  217639. void File::createDirectoryInternal (const String& fileName) const
  217640. {
  217641. mkdir (fileName.toUTF8(), 0777);
  217642. }
  217643. int64 juce_fileSetPosition (void* handle, int64 pos)
  217644. {
  217645. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  217646. return pos;
  217647. return -1;
  217648. }
  217649. void FileInputStream::openHandle()
  217650. {
  217651. totalSize = file.getSize();
  217652. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  217653. if (f != -1)
  217654. fileHandle = (void*) f;
  217655. }
  217656. void FileInputStream::closeHandle()
  217657. {
  217658. if (fileHandle != 0)
  217659. {
  217660. close ((int) (pointer_sized_int) fileHandle);
  217661. fileHandle = 0;
  217662. }
  217663. }
  217664. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  217665. {
  217666. if (fileHandle != 0)
  217667. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  217668. return 0;
  217669. }
  217670. void FileOutputStream::openHandle()
  217671. {
  217672. if (file.exists())
  217673. {
  217674. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  217675. if (f != -1)
  217676. {
  217677. currentPosition = lseek (f, 0, SEEK_END);
  217678. if (currentPosition >= 0)
  217679. fileHandle = (void*) f;
  217680. else
  217681. close (f);
  217682. }
  217683. }
  217684. else
  217685. {
  217686. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  217687. if (f != -1)
  217688. fileHandle = (void*) f;
  217689. }
  217690. }
  217691. void FileOutputStream::closeHandle()
  217692. {
  217693. if (fileHandle != 0)
  217694. {
  217695. close ((int) (pointer_sized_int) fileHandle);
  217696. fileHandle = 0;
  217697. }
  217698. }
  217699. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  217700. {
  217701. if (fileHandle != 0)
  217702. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  217703. return 0;
  217704. }
  217705. void FileOutputStream::flushInternal()
  217706. {
  217707. if (fileHandle != 0)
  217708. fsync ((int) (pointer_sized_int) fileHandle);
  217709. }
  217710. const File juce_getExecutableFile()
  217711. {
  217712. Dl_info exeInfo;
  217713. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  217714. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  217715. }
  217716. int64 File::getBytesFreeOnVolume() const
  217717. {
  217718. struct statfs buf;
  217719. if (juce_doStatFS (*this, buf))
  217720. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  217721. return 0;
  217722. }
  217723. int64 File::getVolumeTotalSize() const
  217724. {
  217725. struct statfs buf;
  217726. if (juce_doStatFS (*this, buf))
  217727. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  217728. return 0;
  217729. }
  217730. const String File::getVolumeLabel() const
  217731. {
  217732. #if JUCE_MAC
  217733. struct VolAttrBuf
  217734. {
  217735. u_int32_t length;
  217736. attrreference_t mountPointRef;
  217737. char mountPointSpace [MAXPATHLEN];
  217738. } attrBuf;
  217739. struct attrlist attrList;
  217740. zerostruct (attrList);
  217741. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  217742. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  217743. File f (*this);
  217744. for (;;)
  217745. {
  217746. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  217747. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  217748. (int) attrBuf.mountPointRef.attr_length);
  217749. const File parent (f.getParentDirectory());
  217750. if (f == parent)
  217751. break;
  217752. f = parent;
  217753. }
  217754. #endif
  217755. return String::empty;
  217756. }
  217757. int File::getVolumeSerialNumber() const
  217758. {
  217759. return 0; // xxx
  217760. }
  217761. void juce_runSystemCommand (const String& command)
  217762. {
  217763. int result = system (command.toUTF8());
  217764. (void) result;
  217765. }
  217766. const String juce_getOutputFromCommand (const String& command)
  217767. {
  217768. // slight bodge here, as we just pipe the output into a temp file and read it...
  217769. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  217770. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  217771. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  217772. String result (tempFile.loadFileAsString());
  217773. tempFile.deleteFile();
  217774. return result;
  217775. }
  217776. class InterProcessLock::Pimpl
  217777. {
  217778. public:
  217779. Pimpl (const String& name, const int timeOutMillisecs)
  217780. : handle (0), refCount (1)
  217781. {
  217782. #if JUCE_MAC
  217783. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  217784. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  217785. #else
  217786. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  217787. #endif
  217788. temp.create();
  217789. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  217790. if (handle != 0)
  217791. {
  217792. struct flock fl;
  217793. zerostruct (fl);
  217794. fl.l_whence = SEEK_SET;
  217795. fl.l_type = F_WRLCK;
  217796. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  217797. for (;;)
  217798. {
  217799. const int result = fcntl (handle, F_SETLK, &fl);
  217800. if (result >= 0)
  217801. return;
  217802. if (errno != EINTR)
  217803. {
  217804. if (timeOutMillisecs == 0
  217805. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  217806. break;
  217807. Thread::sleep (10);
  217808. }
  217809. }
  217810. }
  217811. closeFile();
  217812. }
  217813. ~Pimpl()
  217814. {
  217815. closeFile();
  217816. }
  217817. void closeFile()
  217818. {
  217819. if (handle != 0)
  217820. {
  217821. struct flock fl;
  217822. zerostruct (fl);
  217823. fl.l_whence = SEEK_SET;
  217824. fl.l_type = F_UNLCK;
  217825. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  217826. {}
  217827. close (handle);
  217828. handle = 0;
  217829. }
  217830. }
  217831. int handle, refCount;
  217832. };
  217833. InterProcessLock::InterProcessLock (const String& name_)
  217834. : name (name_)
  217835. {
  217836. }
  217837. InterProcessLock::~InterProcessLock()
  217838. {
  217839. }
  217840. bool InterProcessLock::enter (const int timeOutMillisecs)
  217841. {
  217842. const ScopedLock sl (lock);
  217843. if (pimpl == 0)
  217844. {
  217845. pimpl = new Pimpl (name, timeOutMillisecs);
  217846. if (pimpl->handle == 0)
  217847. pimpl = 0;
  217848. }
  217849. else
  217850. {
  217851. pimpl->refCount++;
  217852. }
  217853. return pimpl != 0;
  217854. }
  217855. void InterProcessLock::exit()
  217856. {
  217857. const ScopedLock sl (lock);
  217858. // Trying to release the lock too many times!
  217859. jassert (pimpl != 0);
  217860. if (pimpl != 0 && --(pimpl->refCount) == 0)
  217861. pimpl = 0;
  217862. }
  217863. void JUCE_API juce_threadEntryPoint (void*);
  217864. void* threadEntryProc (void* userData)
  217865. {
  217866. JUCE_AUTORELEASEPOOL
  217867. juce_threadEntryPoint (userData);
  217868. return 0;
  217869. }
  217870. void* juce_createThread (void* userData)
  217871. {
  217872. pthread_t handle = 0;
  217873. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217874. {
  217875. pthread_detach (handle);
  217876. return (void*) handle;
  217877. }
  217878. return 0;
  217879. }
  217880. void juce_killThread (void* handle)
  217881. {
  217882. if (handle != 0)
  217883. pthread_cancel ((pthread_t) handle);
  217884. }
  217885. void juce_setCurrentThreadName (const String& /*name*/)
  217886. {
  217887. }
  217888. bool juce_setThreadPriority (void* handle, int priority)
  217889. {
  217890. struct sched_param param;
  217891. int policy;
  217892. priority = jlimit (0, 10, priority);
  217893. if (handle == 0)
  217894. handle = (void*) pthread_self();
  217895. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  217896. return false;
  217897. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  217898. const int minPriority = sched_get_priority_min (policy);
  217899. const int maxPriority = sched_get_priority_max (policy);
  217900. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  217901. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  217902. }
  217903. Thread::ThreadID Thread::getCurrentThreadId()
  217904. {
  217905. return (ThreadID) pthread_self();
  217906. }
  217907. void Thread::yield()
  217908. {
  217909. sched_yield();
  217910. }
  217911. /* Remove this macro if you're having problems compiling the cpu affinity
  217912. calls (the API for these has changed about quite a bit in various Linux
  217913. versions, and a lot of distros seem to ship with obsolete versions)
  217914. */
  217915. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  217916. #define SUPPORT_AFFINITIES 1
  217917. #endif
  217918. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  217919. {
  217920. #if SUPPORT_AFFINITIES
  217921. cpu_set_t affinity;
  217922. CPU_ZERO (&affinity);
  217923. for (int i = 0; i < 32; ++i)
  217924. if ((affinityMask & (1 << i)) != 0)
  217925. CPU_SET (i, &affinity);
  217926. /*
  217927. N.B. If this line causes a compile error, then you've probably not got the latest
  217928. version of glibc installed.
  217929. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217930. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  217931. */
  217932. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217933. sched_yield();
  217934. #else
  217935. /* affinities aren't supported because either the appropriate header files weren't found,
  217936. or the SUPPORT_AFFINITIES macro was turned off
  217937. */
  217938. jassertfalse;
  217939. #endif
  217940. }
  217941. /*** End of inlined file: juce_posix_SharedCode.h ***/
  217942. /*** Start of inlined file: juce_linux_Files.cpp ***/
  217943. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  217944. // compiled on its own).
  217945. #if JUCE_INCLUDED_FILE
  217946. enum
  217947. {
  217948. U_ISOFS_SUPER_MAGIC = 0x9660, // linux/iso_fs.h
  217949. U_MSDOS_SUPER_MAGIC = 0x4d44, // linux/msdos_fs.h
  217950. U_NFS_SUPER_MAGIC = 0x6969, // linux/nfs_fs.h
  217951. U_SMB_SUPER_MAGIC = 0x517B // linux/smb_fs.h
  217952. };
  217953. bool File::copyInternal (const File& dest) const
  217954. {
  217955. FileInputStream in (*this);
  217956. if (dest.deleteFile())
  217957. {
  217958. {
  217959. FileOutputStream out (dest);
  217960. if (out.failedToOpen())
  217961. return false;
  217962. if (out.writeFromInputStream (in, -1) == getSize())
  217963. return true;
  217964. }
  217965. dest.deleteFile();
  217966. }
  217967. return false;
  217968. }
  217969. void File::findFileSystemRoots (Array<File>& destArray)
  217970. {
  217971. destArray.add (File ("/"));
  217972. }
  217973. bool File::isOnCDRomDrive() const
  217974. {
  217975. struct statfs buf;
  217976. return statfs (getFullPathName().toUTF8(), &buf) == 0
  217977. && buf.f_type == (short) U_ISOFS_SUPER_MAGIC;
  217978. }
  217979. bool File::isOnHardDisk() const
  217980. {
  217981. struct statfs buf;
  217982. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  217983. {
  217984. switch (buf.f_type)
  217985. {
  217986. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  217987. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  217988. case U_NFS_SUPER_MAGIC: // Network NFS
  217989. case U_SMB_SUPER_MAGIC: // Network Samba
  217990. return false;
  217991. default:
  217992. // Assume anything else is a hard-disk (but note it could
  217993. // be a RAM disk. There isn't a good way of determining
  217994. // this for sure)
  217995. return true;
  217996. }
  217997. }
  217998. // Assume so if this fails for some reason
  217999. return true;
  218000. }
  218001. bool File::isOnRemovableDrive() const
  218002. {
  218003. jassertfalse; // xxx not implemented for linux!
  218004. return false;
  218005. }
  218006. bool File::isHidden() const
  218007. {
  218008. return getFileName().startsWithChar ('.');
  218009. }
  218010. namespace
  218011. {
  218012. const File juce_readlink (const String& file, const File& defaultFile)
  218013. {
  218014. const int size = 8192;
  218015. HeapBlock<char> buffer;
  218016. buffer.malloc (size + 4);
  218017. const size_t numBytes = readlink (file.toUTF8(), buffer, size);
  218018. if (numBytes > 0 && numBytes <= size)
  218019. return File (file).getSiblingFile (String::fromUTF8 (buffer, (int) numBytes));
  218020. return defaultFile;
  218021. }
  218022. }
  218023. const File File::getLinkedTarget() const
  218024. {
  218025. return juce_readlink (getFullPathName().toUTF8(), *this);
  218026. }
  218027. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  218028. const File File::getSpecialLocation (const SpecialLocationType type)
  218029. {
  218030. switch (type)
  218031. {
  218032. case userHomeDirectory:
  218033. {
  218034. const char* homeDir = getenv ("HOME");
  218035. if (homeDir == 0)
  218036. {
  218037. struct passwd* const pw = getpwuid (getuid());
  218038. if (pw != 0)
  218039. homeDir = pw->pw_dir;
  218040. }
  218041. return File (String::fromUTF8 (homeDir));
  218042. }
  218043. case userDocumentsDirectory:
  218044. case userMusicDirectory:
  218045. case userMoviesDirectory:
  218046. case userApplicationDataDirectory:
  218047. return File ("~");
  218048. case userDesktopDirectory:
  218049. return File ("~/Desktop");
  218050. case commonApplicationDataDirectory:
  218051. return File ("/var");
  218052. case globalApplicationsDirectory:
  218053. return File ("/usr");
  218054. case tempDirectory:
  218055. {
  218056. File tmp ("/var/tmp");
  218057. if (! tmp.isDirectory())
  218058. {
  218059. tmp = "/tmp";
  218060. if (! tmp.isDirectory())
  218061. tmp = File::getCurrentWorkingDirectory();
  218062. }
  218063. return tmp;
  218064. }
  218065. case invokedExecutableFile:
  218066. if (juce_Argv0 != 0)
  218067. return File (String::fromUTF8 (juce_Argv0));
  218068. // deliberate fall-through...
  218069. case currentExecutableFile:
  218070. case currentApplicationFile:
  218071. return juce_getExecutableFile();
  218072. case hostApplicationPath:
  218073. return juce_readlink ("/proc/self/exe", juce_getExecutableFile());
  218074. default:
  218075. jassertfalse; // unknown type?
  218076. break;
  218077. }
  218078. return File::nonexistent;
  218079. }
  218080. const String File::getVersion() const
  218081. {
  218082. return String::empty; // xxx not yet implemented
  218083. }
  218084. bool File::moveToTrash() const
  218085. {
  218086. if (! exists())
  218087. return true;
  218088. File trashCan ("~/.Trash");
  218089. if (! trashCan.isDirectory())
  218090. trashCan = "~/.local/share/Trash/files";
  218091. if (! trashCan.isDirectory())
  218092. return false;
  218093. return moveFileTo (trashCan.getNonexistentChildFile (getFileNameWithoutExtension(),
  218094. getFileExtension()));
  218095. }
  218096. class DirectoryIterator::NativeIterator::Pimpl
  218097. {
  218098. public:
  218099. Pimpl (const File& directory, const String& wildCard_)
  218100. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  218101. wildCard (wildCard_),
  218102. dir (opendir (directory.getFullPathName().toUTF8()))
  218103. {
  218104. if (wildCard == "*.*")
  218105. wildCard = "*";
  218106. wildcardUTF8 = wildCard.toUTF8();
  218107. }
  218108. ~Pimpl()
  218109. {
  218110. if (dir != 0)
  218111. closedir (dir);
  218112. }
  218113. bool next (String& filenameFound,
  218114. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218115. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218116. {
  218117. if (dir == 0)
  218118. return false;
  218119. for (;;)
  218120. {
  218121. struct dirent* const de = readdir (dir);
  218122. if (de == 0)
  218123. return false;
  218124. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  218125. {
  218126. filenameFound = String::fromUTF8 (de->d_name);
  218127. const String path (parentDir + filenameFound);
  218128. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  218129. {
  218130. struct stat info;
  218131. const bool statOk = juce_stat (path, info);
  218132. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  218133. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  218134. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  218135. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  218136. }
  218137. if (isHidden != 0)
  218138. *isHidden = filenameFound.startsWithChar ('.');
  218139. if (isReadOnly != 0)
  218140. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  218141. return true;
  218142. }
  218143. }
  218144. }
  218145. private:
  218146. String parentDir, wildCard;
  218147. const char* wildcardUTF8;
  218148. DIR* dir;
  218149. Pimpl (const Pimpl&);
  218150. Pimpl& operator= (const Pimpl&);
  218151. };
  218152. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  218153. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  218154. {
  218155. }
  218156. DirectoryIterator::NativeIterator::~NativeIterator()
  218157. {
  218158. }
  218159. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  218160. bool* const isDir, bool* const isHidden, int64* const fileSize,
  218161. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  218162. {
  218163. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  218164. }
  218165. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  218166. {
  218167. String cmdString (fileName.replace (" ", "\\ ",false));
  218168. cmdString << " " << parameters;
  218169. if (URL::isProbablyAWebsiteURL (fileName)
  218170. || cmdString.startsWithIgnoreCase ("file:")
  218171. || URL::isProbablyAnEmailAddress (fileName))
  218172. {
  218173. // create a command that tries to launch a bunch of likely browsers
  218174. const char* const browserNames[] = { "xdg-open", "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  218175. StringArray cmdLines;
  218176. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  218177. cmdLines.add (String (browserNames[i]) + " " + cmdString.trim().quoted());
  218178. cmdString = cmdLines.joinIntoString (" || ");
  218179. }
  218180. const char* const argv[4] = { "/bin/sh", "-c", cmdString.toUTF8(), 0 };
  218181. const int cpid = fork();
  218182. if (cpid == 0)
  218183. {
  218184. setsid();
  218185. // Child process
  218186. execve (argv[0], (char**) argv, environ);
  218187. exit (0);
  218188. }
  218189. return cpid >= 0;
  218190. }
  218191. void File::revealToUser() const
  218192. {
  218193. if (isDirectory())
  218194. startAsProcess();
  218195. else if (getParentDirectory().exists())
  218196. getParentDirectory().startAsProcess();
  218197. }
  218198. #endif
  218199. /*** End of inlined file: juce_linux_Files.cpp ***/
  218200. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  218201. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  218202. // compiled on its own).
  218203. #if JUCE_INCLUDED_FILE
  218204. struct NamedPipeInternal
  218205. {
  218206. String pipeInName, pipeOutName;
  218207. int pipeIn, pipeOut;
  218208. bool volatile createdPipe, blocked, stopReadOperation;
  218209. static void signalHandler (int) {}
  218210. };
  218211. void NamedPipe::cancelPendingReads()
  218212. {
  218213. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  218214. {
  218215. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218216. intern->stopReadOperation = true;
  218217. char buffer [1] = { 0 };
  218218. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  218219. (void) bytesWritten;
  218220. int timeout = 2000;
  218221. while (intern->blocked && --timeout >= 0)
  218222. Thread::sleep (2);
  218223. intern->stopReadOperation = false;
  218224. }
  218225. }
  218226. void NamedPipe::close()
  218227. {
  218228. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218229. if (intern != 0)
  218230. {
  218231. internal = 0;
  218232. if (intern->pipeIn != -1)
  218233. ::close (intern->pipeIn);
  218234. if (intern->pipeOut != -1)
  218235. ::close (intern->pipeOut);
  218236. if (intern->createdPipe)
  218237. {
  218238. unlink (intern->pipeInName.toUTF8());
  218239. unlink (intern->pipeOutName.toUTF8());
  218240. }
  218241. delete intern;
  218242. }
  218243. }
  218244. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  218245. {
  218246. close();
  218247. NamedPipeInternal* const intern = new NamedPipeInternal();
  218248. internal = intern;
  218249. intern->createdPipe = createPipe;
  218250. intern->blocked = false;
  218251. intern->stopReadOperation = false;
  218252. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  218253. siginterrupt (SIGPIPE, 1);
  218254. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  218255. intern->pipeInName = pipePath + "_in";
  218256. intern->pipeOutName = pipePath + "_out";
  218257. intern->pipeIn = -1;
  218258. intern->pipeOut = -1;
  218259. if (createPipe)
  218260. {
  218261. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  218262. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  218263. {
  218264. delete intern;
  218265. internal = 0;
  218266. return false;
  218267. }
  218268. }
  218269. return true;
  218270. }
  218271. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  218272. {
  218273. int bytesRead = -1;
  218274. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218275. if (intern != 0)
  218276. {
  218277. intern->blocked = true;
  218278. if (intern->pipeIn == -1)
  218279. {
  218280. if (intern->createdPipe)
  218281. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  218282. else
  218283. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  218284. if (intern->pipeIn == -1)
  218285. {
  218286. intern->blocked = false;
  218287. return -1;
  218288. }
  218289. }
  218290. bytesRead = 0;
  218291. char* p = static_cast<char*> (destBuffer);
  218292. while (bytesRead < maxBytesToRead)
  218293. {
  218294. const int bytesThisTime = maxBytesToRead - bytesRead;
  218295. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  218296. if (numRead <= 0 || intern->stopReadOperation)
  218297. {
  218298. bytesRead = -1;
  218299. break;
  218300. }
  218301. bytesRead += numRead;
  218302. p += bytesRead;
  218303. }
  218304. intern->blocked = false;
  218305. }
  218306. return bytesRead;
  218307. }
  218308. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  218309. {
  218310. int bytesWritten = -1;
  218311. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  218312. if (intern != 0)
  218313. {
  218314. if (intern->pipeOut == -1)
  218315. {
  218316. if (intern->createdPipe)
  218317. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  218318. else
  218319. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  218320. if (intern->pipeOut == -1)
  218321. {
  218322. return -1;
  218323. }
  218324. }
  218325. const char* p = static_cast<const char*> (sourceBuffer);
  218326. bytesWritten = 0;
  218327. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  218328. while (bytesWritten < numBytesToWrite
  218329. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  218330. {
  218331. const int bytesThisTime = numBytesToWrite - bytesWritten;
  218332. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  218333. if (numWritten <= 0)
  218334. {
  218335. bytesWritten = -1;
  218336. break;
  218337. }
  218338. bytesWritten += numWritten;
  218339. p += bytesWritten;
  218340. }
  218341. }
  218342. return bytesWritten;
  218343. }
  218344. #endif
  218345. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  218346. /*** Start of inlined file: juce_linux_Network.cpp ***/
  218347. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218348. // compiled on its own).
  218349. #if JUCE_INCLUDED_FILE
  218350. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  218351. {
  218352. int numResults = 0;
  218353. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  218354. if (s != -1)
  218355. {
  218356. char buf [1024];
  218357. struct ifconf ifc;
  218358. ifc.ifc_len = sizeof (buf);
  218359. ifc.ifc_buf = buf;
  218360. ioctl (s, SIOCGIFCONF, &ifc);
  218361. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  218362. {
  218363. struct ifreq ifr;
  218364. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  218365. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  218366. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  218367. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  218368. && numResults < maxNum)
  218369. {
  218370. int64 a = 0;
  218371. for (int j = 6; --j >= 0;)
  218372. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data [littleEndian ? j : (5 - j)];
  218373. *addresses++ = a;
  218374. ++numResults;
  218375. }
  218376. }
  218377. close (s);
  218378. }
  218379. return numResults;
  218380. }
  218381. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  218382. const String& emailSubject,
  218383. const String& bodyText,
  218384. const StringArray& filesToAttach)
  218385. {
  218386. jassertfalse; // xxx todo
  218387. return false;
  218388. }
  218389. /** A HTTP input stream that uses sockets.
  218390. */
  218391. class JUCE_HTTPSocketStream
  218392. {
  218393. public:
  218394. JUCE_HTTPSocketStream()
  218395. : readPosition (0),
  218396. socketHandle (-1),
  218397. levelsOfRedirection (0),
  218398. timeoutSeconds (15)
  218399. {
  218400. }
  218401. ~JUCE_HTTPSocketStream()
  218402. {
  218403. closeSocket();
  218404. }
  218405. bool open (const String& url,
  218406. const String& headers,
  218407. const MemoryBlock& postData,
  218408. const bool isPost,
  218409. URL::OpenStreamProgressCallback* callback,
  218410. void* callbackContext,
  218411. int timeOutMs)
  218412. {
  218413. closeSocket();
  218414. uint32 timeOutTime = Time::getMillisecondCounter();
  218415. if (timeOutMs == 0)
  218416. timeOutTime += 60000;
  218417. else if (timeOutMs < 0)
  218418. timeOutTime = 0xffffffff;
  218419. else
  218420. timeOutTime += timeOutMs;
  218421. String hostName, hostPath;
  218422. int hostPort;
  218423. if (! decomposeURL (url, hostName, hostPath, hostPort))
  218424. return false;
  218425. const struct hostent* host = 0;
  218426. int port = 0;
  218427. String proxyName, proxyPath;
  218428. int proxyPort = 0;
  218429. String proxyURL (getenv ("http_proxy"));
  218430. if (proxyURL.startsWithIgnoreCase ("http://"))
  218431. {
  218432. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  218433. return false;
  218434. host = gethostbyname (proxyName.toUTF8());
  218435. port = proxyPort;
  218436. }
  218437. else
  218438. {
  218439. host = gethostbyname (hostName.toUTF8());
  218440. port = hostPort;
  218441. }
  218442. if (host == 0)
  218443. return false;
  218444. struct sockaddr_in address;
  218445. zerostruct (address);
  218446. memcpy (&address.sin_addr, host->h_addr, host->h_length);
  218447. address.sin_family = host->h_addrtype;
  218448. address.sin_port = htons (port);
  218449. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  218450. if (socketHandle == -1)
  218451. return false;
  218452. int receiveBufferSize = 16384;
  218453. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  218454. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  218455. #if JUCE_MAC
  218456. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  218457. #endif
  218458. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  218459. {
  218460. closeSocket();
  218461. return false;
  218462. }
  218463. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  218464. proxyName, proxyPort,
  218465. hostPath, url,
  218466. headers, postData,
  218467. isPost));
  218468. size_t totalHeaderSent = 0;
  218469. while (totalHeaderSent < requestHeader.getSize())
  218470. {
  218471. if (Time::getMillisecondCounter() > timeOutTime)
  218472. {
  218473. closeSocket();
  218474. return false;
  218475. }
  218476. const int numToSend = jmin (1024, (int) (requestHeader.getSize() - totalHeaderSent));
  218477. if (send (socketHandle,
  218478. ((const char*) requestHeader.getData()) + totalHeaderSent,
  218479. numToSend, 0)
  218480. != numToSend)
  218481. {
  218482. closeSocket();
  218483. return false;
  218484. }
  218485. totalHeaderSent += numToSend;
  218486. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  218487. {
  218488. closeSocket();
  218489. return false;
  218490. }
  218491. }
  218492. const String responseHeader (readResponse (timeOutTime));
  218493. if (responseHeader.isNotEmpty())
  218494. {
  218495. //DBG (responseHeader);
  218496. headerLines.clear();
  218497. headerLines.addLines (responseHeader);
  218498. const int statusCode = responseHeader.fromFirstOccurrenceOf (" ", false, false)
  218499. .substring (0, 3).getIntValue();
  218500. //int contentLength = findHeaderItem (lines, "Content-Length:").getIntValue();
  218501. //bool isChunked = findHeaderItem (lines, "Transfer-Encoding:").equalsIgnoreCase ("chunked");
  218502. String location (findHeaderItem (headerLines, "Location:"));
  218503. if (statusCode >= 300 && statusCode < 400
  218504. && location.isNotEmpty())
  218505. {
  218506. if (! location.startsWithIgnoreCase ("http://"))
  218507. location = "http://" + location;
  218508. if (levelsOfRedirection++ < 3)
  218509. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  218510. }
  218511. else
  218512. {
  218513. levelsOfRedirection = 0;
  218514. return true;
  218515. }
  218516. }
  218517. closeSocket();
  218518. return false;
  218519. }
  218520. int read (void* buffer, int bytesToRead)
  218521. {
  218522. fd_set readbits;
  218523. FD_ZERO (&readbits);
  218524. FD_SET (socketHandle, &readbits);
  218525. struct timeval tv;
  218526. tv.tv_sec = timeoutSeconds;
  218527. tv.tv_usec = 0;
  218528. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218529. return 0; // (timeout)
  218530. const int bytesRead = jmax (0, (int) recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  218531. readPosition += bytesRead;
  218532. return bytesRead;
  218533. }
  218534. int readPosition;
  218535. StringArray headerLines;
  218536. juce_UseDebuggingNewOperator
  218537. private:
  218538. int socketHandle, levelsOfRedirection;
  218539. const int timeoutSeconds;
  218540. void closeSocket()
  218541. {
  218542. if (socketHandle >= 0)
  218543. close (socketHandle);
  218544. socketHandle = -1;
  218545. }
  218546. const MemoryBlock createRequestHeader (const String& hostName,
  218547. const int hostPort,
  218548. const String& proxyName,
  218549. const int proxyPort,
  218550. const String& hostPath,
  218551. const String& originalURL,
  218552. const String& headers,
  218553. const MemoryBlock& postData,
  218554. const bool isPost)
  218555. {
  218556. String header (isPost ? "POST " : "GET ");
  218557. if (proxyName.isEmpty())
  218558. {
  218559. header << hostPath << " HTTP/1.0\r\nHost: "
  218560. << hostName << ':' << hostPort;
  218561. }
  218562. else
  218563. {
  218564. header << originalURL << " HTTP/1.0\r\nHost: "
  218565. << proxyName << ':' << proxyPort;
  218566. }
  218567. header << "\r\nUser-Agent: JUCE/"
  218568. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  218569. << "\r\nConnection: Close\r\nContent-Length: "
  218570. << postData.getSize() << "\r\n"
  218571. << headers << "\r\n";
  218572. MemoryBlock mb;
  218573. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  218574. mb.append (postData.getData(), postData.getSize());
  218575. return mb;
  218576. }
  218577. const String readResponse (const uint32 timeOutTime)
  218578. {
  218579. int bytesRead = 0, numConsecutiveLFs = 0;
  218580. MemoryBlock buffer (1024, true);
  218581. while (numConsecutiveLFs < 2 && bytesRead < 32768
  218582. && Time::getMillisecondCounter() <= timeOutTime)
  218583. {
  218584. fd_set readbits;
  218585. FD_ZERO (&readbits);
  218586. FD_SET (socketHandle, &readbits);
  218587. struct timeval tv;
  218588. tv.tv_sec = timeoutSeconds;
  218589. tv.tv_usec = 0;
  218590. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  218591. return String::empty; // (timeout)
  218592. buffer.ensureSize (bytesRead + 8, true);
  218593. char* const dest = (char*) buffer.getData() + bytesRead;
  218594. if (recv (socketHandle, dest, 1, 0) == -1)
  218595. return String::empty;
  218596. const char lastByte = *dest;
  218597. ++bytesRead;
  218598. if (lastByte == '\n')
  218599. ++numConsecutiveLFs;
  218600. else if (lastByte != '\r')
  218601. numConsecutiveLFs = 0;
  218602. }
  218603. const String header (String::fromUTF8 ((const char*) buffer.getData()));
  218604. if (header.startsWithIgnoreCase ("HTTP/"))
  218605. return header.trimEnd();
  218606. return String::empty;
  218607. }
  218608. static bool decomposeURL (const String& url,
  218609. String& host, String& path, int& port)
  218610. {
  218611. if (! url.startsWithIgnoreCase ("http://"))
  218612. return false;
  218613. const int nextSlash = url.indexOfChar (7, '/');
  218614. int nextColon = url.indexOfChar (7, ':');
  218615. if (nextColon > nextSlash && nextSlash > 0)
  218616. nextColon = -1;
  218617. if (nextColon >= 0)
  218618. {
  218619. host = url.substring (7, nextColon);
  218620. if (nextSlash >= 0)
  218621. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  218622. else
  218623. port = url.substring (nextColon + 1).getIntValue();
  218624. }
  218625. else
  218626. {
  218627. port = 80;
  218628. if (nextSlash >= 0)
  218629. host = url.substring (7, nextSlash);
  218630. else
  218631. host = url.substring (7);
  218632. }
  218633. if (nextSlash >= 0)
  218634. path = url.substring (nextSlash);
  218635. else
  218636. path = "/";
  218637. return true;
  218638. }
  218639. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  218640. {
  218641. for (int i = 0; i < lines.size(); ++i)
  218642. if (lines[i].startsWithIgnoreCase (itemName))
  218643. return lines[i].substring (itemName.length()).trim();
  218644. return String::empty;
  218645. }
  218646. };
  218647. void* juce_openInternetFile (const String& url,
  218648. const String& headers,
  218649. const MemoryBlock& postData,
  218650. const bool isPost,
  218651. URL::OpenStreamProgressCallback* callback,
  218652. void* callbackContext,
  218653. int timeOutMs)
  218654. {
  218655. ScopedPointer<JUCE_HTTPSocketStream> s (new JUCE_HTTPSocketStream());
  218656. if (s->open (url, headers, postData, isPost, callback, callbackContext, timeOutMs))
  218657. return s.release();
  218658. return 0;
  218659. }
  218660. void juce_closeInternetFile (void* handle)
  218661. {
  218662. delete static_cast <JUCE_HTTPSocketStream*> (handle);
  218663. }
  218664. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  218665. {
  218666. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218667. return s != 0 ? s->read (buffer, bytesToRead) : 0;
  218668. }
  218669. int64 juce_getInternetFileContentLength (void* handle)
  218670. {
  218671. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218672. if (s != 0)
  218673. {
  218674. //xxx todo
  218675. jassertfalse
  218676. }
  218677. return -1;
  218678. }
  218679. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  218680. {
  218681. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218682. if (s != 0)
  218683. {
  218684. for (int i = 0; i < s->headerLines.size(); ++i)
  218685. {
  218686. const String& headersEntry = s->headerLines[i];
  218687. const String key (headersEntry.upToFirstOccurrenceOf (": ", false, false));
  218688. const String value (headersEntry.fromFirstOccurrenceOf (": ", false, false));
  218689. const String previousValue (headers [key]);
  218690. headers.set (key, previousValue.isEmpty() ? value : (previousValue + "," + value));
  218691. }
  218692. }
  218693. }
  218694. int juce_seekInInternetFile (void* handle, int newPosition)
  218695. {
  218696. JUCE_HTTPSocketStream* const s = static_cast <JUCE_HTTPSocketStream*> (handle);
  218697. return s != 0 ? s->readPosition : 0;
  218698. }
  218699. #endif
  218700. /*** End of inlined file: juce_linux_Network.cpp ***/
  218701. /*** Start of inlined file: juce_linux_SystemStats.cpp ***/
  218702. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218703. // compiled on its own).
  218704. #if JUCE_INCLUDED_FILE
  218705. void Logger::outputDebugString (const String& text)
  218706. {
  218707. std::cerr << text << std::endl;
  218708. }
  218709. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  218710. {
  218711. return Linux;
  218712. }
  218713. const String SystemStats::getOperatingSystemName()
  218714. {
  218715. return "Linux";
  218716. }
  218717. bool SystemStats::isOperatingSystem64Bit()
  218718. {
  218719. #if JUCE_64BIT
  218720. return true;
  218721. #else
  218722. //xxx not sure how to find this out?..
  218723. return false;
  218724. #endif
  218725. }
  218726. namespace LinuxStatsHelpers
  218727. {
  218728. const String getCpuInfo (const char* const key)
  218729. {
  218730. StringArray lines;
  218731. lines.addLines (File ("/proc/cpuinfo").loadFileAsString());
  218732. for (int i = lines.size(); --i >= 0;) // (NB - it's important that this runs in reverse order)
  218733. if (lines[i].startsWithIgnoreCase (key))
  218734. return lines[i].fromFirstOccurrenceOf (":", false, false).trim();
  218735. return String::empty;
  218736. }
  218737. bool getTimeSinceStartup (timeval* const t) throw()
  218738. {
  218739. if (gettimeofday (t, 0) != 0)
  218740. return false;
  218741. static unsigned int calibrate = 0;
  218742. static bool calibrated = false;
  218743. if (! calibrated)
  218744. {
  218745. calibrated = true;
  218746. struct sysinfo sysi;
  218747. if (sysinfo (&sysi) == 0)
  218748. calibrate = t->tv_sec - sysi.uptime; // Safe to assume system was not brought up earlier than 1970!
  218749. }
  218750. t->tv_sec -= calibrate;
  218751. return true;
  218752. }
  218753. }
  218754. const String SystemStats::getCpuVendor()
  218755. {
  218756. return LinuxStatsHelpers::getCpuInfo ("vendor_id");
  218757. }
  218758. int SystemStats::getCpuSpeedInMegaherz()
  218759. {
  218760. return roundToInt (LinuxStatsHelpers::getCpuInfo ("cpu MHz").getFloatValue());
  218761. }
  218762. int SystemStats::getMemorySizeInMegabytes()
  218763. {
  218764. struct sysinfo sysi;
  218765. if (sysinfo (&sysi) == 0)
  218766. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  218767. return 0;
  218768. }
  218769. int SystemStats::getPageSize()
  218770. {
  218771. return sysconf (_SC_PAGESIZE);
  218772. }
  218773. const String SystemStats::getLogonName()
  218774. {
  218775. const char* user = getenv ("USER");
  218776. if (user == 0)
  218777. {
  218778. struct passwd* const pw = getpwuid (getuid());
  218779. if (pw != 0)
  218780. user = pw->pw_name;
  218781. }
  218782. return String::fromUTF8 (user);
  218783. }
  218784. const String SystemStats::getFullUserName()
  218785. {
  218786. return getLogonName();
  218787. }
  218788. void SystemStats::initialiseStats()
  218789. {
  218790. const String flags (LinuxStatsHelpers::getCpuInfo ("flags"));
  218791. cpuFlags.hasMMX = flags.contains ("mmx");
  218792. cpuFlags.hasSSE = flags.contains ("sse");
  218793. cpuFlags.hasSSE2 = flags.contains ("sse2");
  218794. cpuFlags.has3DNow = flags.contains ("3dnow");
  218795. cpuFlags.numCpus = LinuxStatsHelpers::getCpuInfo ("processor").getIntValue() + 1;
  218796. }
  218797. void PlatformUtilities::fpuReset()
  218798. {
  218799. }
  218800. uint32 juce_millisecondsSinceStartup() throw()
  218801. {
  218802. timeval t;
  218803. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218804. return (uint32) (t.tv_sec * 1000 + (t.tv_usec / 1000));
  218805. return 0;
  218806. }
  218807. int64 Time::getHighResolutionTicks() throw()
  218808. {
  218809. timeval t;
  218810. if (LinuxStatsHelpers::getTimeSinceStartup (&t))
  218811. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  218812. return 0;
  218813. }
  218814. int64 Time::getHighResolutionTicksPerSecond() throw()
  218815. {
  218816. return 1000000; // (microseconds)
  218817. }
  218818. double Time::getMillisecondCounterHiRes() throw()
  218819. {
  218820. return getHighResolutionTicks() * 0.001;
  218821. }
  218822. bool Time::setSystemTimeToThisTime() const
  218823. {
  218824. timeval t;
  218825. t.tv_sec = millisSinceEpoch % 1000000;
  218826. t.tv_usec = millisSinceEpoch - t.tv_sec;
  218827. return settimeofday (&t, 0) ? false : true;
  218828. }
  218829. #endif
  218830. /*** End of inlined file: juce_linux_SystemStats.cpp ***/
  218831. /*** Start of inlined file: juce_linux_Threads.cpp ***/
  218832. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218833. // compiled on its own).
  218834. #if JUCE_INCLUDED_FILE
  218835. /*
  218836. Note that a lot of methods that you'd expect to find in this file actually
  218837. live in juce_posix_SharedCode.h!
  218838. */
  218839. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  218840. void Process::setPriority (ProcessPriority prior)
  218841. {
  218842. struct sched_param param;
  218843. int policy, maxp, minp;
  218844. const int p = (int) prior;
  218845. if (p <= 1)
  218846. policy = SCHED_OTHER;
  218847. else
  218848. policy = SCHED_RR;
  218849. minp = sched_get_priority_min (policy);
  218850. maxp = sched_get_priority_max (policy);
  218851. if (p < 2)
  218852. param.sched_priority = 0;
  218853. else if (p == 2 )
  218854. // Set to middle of lower realtime priority range
  218855. param.sched_priority = minp + (maxp - minp) / 4;
  218856. else
  218857. // Set to middle of higher realtime priority range
  218858. param.sched_priority = minp + (3 * (maxp - minp) / 4);
  218859. pthread_setschedparam (pthread_self(), policy, &param);
  218860. }
  218861. void Process::terminate()
  218862. {
  218863. exit (0);
  218864. }
  218865. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  218866. {
  218867. static char testResult = 0;
  218868. if (testResult == 0)
  218869. {
  218870. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  218871. if (testResult >= 0)
  218872. {
  218873. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  218874. testResult = 1;
  218875. }
  218876. }
  218877. return testResult < 0;
  218878. }
  218879. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  218880. {
  218881. return juce_isRunningUnderDebugger();
  218882. }
  218883. void Process::raisePrivilege()
  218884. {
  218885. // If running suid root, change effective user
  218886. // to root
  218887. if (geteuid() != 0 && getuid() == 0)
  218888. {
  218889. setreuid (geteuid(), getuid());
  218890. setregid (getegid(), getgid());
  218891. }
  218892. }
  218893. void Process::lowerPrivilege()
  218894. {
  218895. // If runing suid root, change effective user
  218896. // back to real user
  218897. if (geteuid() == 0 && getuid() != 0)
  218898. {
  218899. setreuid (geteuid(), getuid());
  218900. setregid (getegid(), getgid());
  218901. }
  218902. }
  218903. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218904. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  218905. {
  218906. return dlopen (name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  218907. }
  218908. void PlatformUtilities::freeDynamicLibrary (void* handle)
  218909. {
  218910. dlclose(handle);
  218911. }
  218912. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  218913. {
  218914. return dlsym (libraryHandle, procedureName.toCString());
  218915. }
  218916. #endif
  218917. #endif
  218918. /*** End of inlined file: juce_linux_Threads.cpp ***/
  218919. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  218920. /*** Start of inlined file: juce_linux_Clipboard.cpp ***/
  218921. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  218922. // compiled on its own).
  218923. #if JUCE_INCLUDED_FILE
  218924. extern Display* display;
  218925. extern Window juce_messageWindowHandle;
  218926. namespace ClipboardHelpers
  218927. {
  218928. static String localClipboardContent;
  218929. static Atom atom_UTF8_STRING;
  218930. static Atom atom_CLIPBOARD;
  218931. static Atom atom_TARGETS;
  218932. static void initSelectionAtoms()
  218933. {
  218934. static bool isInitialised = false;
  218935. if (! isInitialised)
  218936. {
  218937. atom_UTF8_STRING = XInternAtom (display, "UTF8_STRING", False);
  218938. atom_CLIPBOARD = XInternAtom (display, "CLIPBOARD", False);
  218939. atom_TARGETS = XInternAtom (display, "TARGETS", False);
  218940. }
  218941. }
  218942. // Read the content of a window property as either a locale-dependent string or an utf8 string
  218943. // works only for strings shorter than 1000000 bytes
  218944. static String readWindowProperty (Window window, Atom prop, Atom fmt)
  218945. {
  218946. String returnData;
  218947. char* clipData;
  218948. Atom actualType;
  218949. int actualFormat;
  218950. unsigned long numItems, bytesLeft;
  218951. if (XGetWindowProperty (display, window, prop,
  218952. 0L /* offset */, 1000000 /* length (max) */, False,
  218953. AnyPropertyType /* format */,
  218954. &actualType, &actualFormat, &numItems, &bytesLeft,
  218955. (unsigned char**) &clipData) == Success)
  218956. {
  218957. if (actualType == atom_UTF8_STRING && actualFormat == 8)
  218958. returnData = String::fromUTF8 (clipData, numItems);
  218959. else if (actualType == XA_STRING && actualFormat == 8)
  218960. returnData = String (clipData, numItems);
  218961. if (clipData != 0)
  218962. XFree (clipData);
  218963. jassert (bytesLeft == 0 || numItems == 1000000);
  218964. }
  218965. XDeleteProperty (display, window, prop);
  218966. return returnData;
  218967. }
  218968. // Send a SelectionRequest to the window owning the selection and waits for its answer (with a timeout) */
  218969. static bool requestSelectionContent (String& selectionContent, Atom selection, Atom requestedFormat)
  218970. {
  218971. Atom property_name = XInternAtom (display, "JUCE_SEL", false);
  218972. // The selection owner will be asked to set the JUCE_SEL property on the
  218973. // juce_messageWindowHandle with the selection content
  218974. XConvertSelection (display, selection, requestedFormat, property_name,
  218975. juce_messageWindowHandle, CurrentTime);
  218976. int count = 50; // will wait at most for 200 ms
  218977. while (--count >= 0)
  218978. {
  218979. XEvent event;
  218980. if (XCheckTypedWindowEvent (display, juce_messageWindowHandle, SelectionNotify, &event))
  218981. {
  218982. if (event.xselection.property == property_name)
  218983. {
  218984. jassert (event.xselection.requestor == juce_messageWindowHandle);
  218985. selectionContent = readWindowProperty (event.xselection.requestor,
  218986. event.xselection.property,
  218987. requestedFormat);
  218988. return true;
  218989. }
  218990. else
  218991. {
  218992. return false; // the format we asked for was denied.. (event.xselection.property == None)
  218993. }
  218994. }
  218995. // not very elegant.. we could do a select() or something like that...
  218996. // however clipboard content requesting is inherently slow on x11, it
  218997. // often takes 50ms or more so...
  218998. Thread::sleep (4);
  218999. }
  219000. return false;
  219001. }
  219002. }
  219003. // Called from the event loop in juce_linux_Messaging in response to SelectionRequest events
  219004. void juce_handleSelectionRequest (XSelectionRequestEvent &evt)
  219005. {
  219006. ClipboardHelpers::initSelectionAtoms();
  219007. // the selection content is sent to the target window as a window property
  219008. XSelectionEvent reply;
  219009. reply.type = SelectionNotify;
  219010. reply.display = evt.display;
  219011. reply.requestor = evt.requestor;
  219012. reply.selection = evt.selection;
  219013. reply.target = evt.target;
  219014. reply.property = None; // == "fail"
  219015. reply.time = evt.time;
  219016. HeapBlock <char> data;
  219017. int propertyFormat = 0, numDataItems = 0;
  219018. if (evt.selection == XA_PRIMARY || evt.selection == ClipboardHelpers::atom_CLIPBOARD)
  219019. {
  219020. if (evt.target == XA_STRING)
  219021. {
  219022. // format data according to system locale
  219023. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsCString() + 1;
  219024. data.calloc (numDataItems + 1);
  219025. ClipboardHelpers::localClipboardContent.copyToCString (data, numDataItems);
  219026. propertyFormat = 8; // bits/item
  219027. }
  219028. else if (evt.target == ClipboardHelpers::atom_UTF8_STRING)
  219029. {
  219030. // translate to utf8
  219031. numDataItems = ClipboardHelpers::localClipboardContent.getNumBytesAsUTF8() + 1;
  219032. data.calloc (numDataItems + 1);
  219033. ClipboardHelpers::localClipboardContent.copyToUTF8 (data, numDataItems);
  219034. propertyFormat = 8; // bits/item
  219035. }
  219036. else if (evt.target == ClipboardHelpers::atom_TARGETS)
  219037. {
  219038. // another application wants to know what we are able to send
  219039. numDataItems = 2;
  219040. propertyFormat = 32; // atoms are 32-bit
  219041. data.calloc (numDataItems * 4);
  219042. Atom* atoms = reinterpret_cast<Atom*> (data.getData());
  219043. atoms[0] = ClipboardHelpers::atom_UTF8_STRING;
  219044. atoms[1] = XA_STRING;
  219045. }
  219046. }
  219047. else
  219048. {
  219049. DBG ("requested unsupported clipboard");
  219050. }
  219051. if (data != 0)
  219052. {
  219053. const int maxReasonableSelectionSize = 1000000;
  219054. // for very big chunks of data, we should use the "INCR" protocol , which is a pain in the *ss
  219055. if (evt.property != None && numDataItems < maxReasonableSelectionSize)
  219056. {
  219057. XChangeProperty (evt.display, evt.requestor,
  219058. evt.property, evt.target,
  219059. propertyFormat /* 8 or 32 */, PropModeReplace,
  219060. reinterpret_cast<const unsigned char*> (data.getData()), numDataItems);
  219061. reply.property = evt.property; // " == success"
  219062. }
  219063. }
  219064. XSendEvent (evt.display, evt.requestor, 0, NoEventMask, (XEvent*) &reply);
  219065. }
  219066. void SystemClipboard::copyTextToClipboard (const String& clipText)
  219067. {
  219068. ClipboardHelpers::initSelectionAtoms();
  219069. ClipboardHelpers::localClipboardContent = clipText;
  219070. XSetSelectionOwner (display, XA_PRIMARY, juce_messageWindowHandle, CurrentTime);
  219071. XSetSelectionOwner (display, ClipboardHelpers::atom_CLIPBOARD, juce_messageWindowHandle, CurrentTime);
  219072. }
  219073. const String SystemClipboard::getTextFromClipboard()
  219074. {
  219075. ClipboardHelpers::initSelectionAtoms();
  219076. /* 1) try to read from the "CLIPBOARD" selection first (the "high
  219077. level" clipboard that is supposed to be filled by ctrl-C
  219078. etc). When a clipboard manager is running, the content of this
  219079. selection is preserved even when the original selection owner
  219080. exits.
  219081. 2) and then try to read from "PRIMARY" selection (the "legacy" selection
  219082. filled by good old x11 apps such as xterm)
  219083. */
  219084. String content;
  219085. Atom selection = XA_PRIMARY;
  219086. Window selectionOwner = None;
  219087. if ((selectionOwner = XGetSelectionOwner (display, selection)) == None)
  219088. {
  219089. selection = ClipboardHelpers::atom_CLIPBOARD;
  219090. selectionOwner = XGetSelectionOwner (display, selection);
  219091. }
  219092. if (selectionOwner != None)
  219093. {
  219094. if (selectionOwner == juce_messageWindowHandle)
  219095. {
  219096. content = ClipboardHelpers::localClipboardContent;
  219097. }
  219098. else
  219099. {
  219100. // first try: we want an utf8 string
  219101. bool ok = ClipboardHelpers::requestSelectionContent (content, selection, ClipboardHelpers::atom_UTF8_STRING);
  219102. if (! ok)
  219103. {
  219104. // second chance, ask for a good old locale-dependent string ..
  219105. ok = ClipboardHelpers::requestSelectionContent (content, selection, XA_STRING);
  219106. }
  219107. }
  219108. }
  219109. return content;
  219110. }
  219111. #endif
  219112. /*** End of inlined file: juce_linux_Clipboard.cpp ***/
  219113. /*** Start of inlined file: juce_linux_Messaging.cpp ***/
  219114. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219115. // compiled on its own).
  219116. #if JUCE_INCLUDED_FILE
  219117. #if JUCE_DEBUG && ! defined (JUCE_DEBUG_XERRORS)
  219118. #define JUCE_DEBUG_XERRORS 1
  219119. #endif
  219120. Display* display = 0;
  219121. Window juce_messageWindowHandle = None;
  219122. XContext windowHandleXContext; // This is referenced from Windowing.cpp
  219123. extern void juce_windowMessageReceive (XEvent* event); // Defined in Windowing.cpp
  219124. extern void juce_handleSelectionRequest (XSelectionRequestEvent &evt); // Defined in Clipboard.cpp
  219125. ScopedXLock::ScopedXLock() { XLockDisplay (display); }
  219126. ScopedXLock::~ScopedXLock() { XUnlockDisplay (display); }
  219127. class InternalMessageQueue
  219128. {
  219129. public:
  219130. InternalMessageQueue()
  219131. : bytesInSocket (0),
  219132. totalEventCount (0)
  219133. {
  219134. int ret = ::socketpair (AF_LOCAL, SOCK_STREAM, 0, fd);
  219135. (void) ret; jassert (ret == 0);
  219136. //setNonBlocking (fd[0]);
  219137. //setNonBlocking (fd[1]);
  219138. }
  219139. ~InternalMessageQueue()
  219140. {
  219141. close (fd[0]);
  219142. close (fd[1]);
  219143. clearSingletonInstance();
  219144. }
  219145. void postMessage (Message* msg)
  219146. {
  219147. const int maxBytesInSocketQueue = 128;
  219148. ScopedLock sl (lock);
  219149. queue.add (msg);
  219150. if (bytesInSocket < maxBytesInSocketQueue)
  219151. {
  219152. ++bytesInSocket;
  219153. ScopedUnlock ul (lock);
  219154. const unsigned char x = 0xff;
  219155. size_t bytesWritten = write (fd[0], &x, 1);
  219156. (void) bytesWritten;
  219157. }
  219158. }
  219159. bool isEmpty() const
  219160. {
  219161. ScopedLock sl (lock);
  219162. return queue.size() == 0;
  219163. }
  219164. bool dispatchNextEvent()
  219165. {
  219166. // This alternates between giving priority to XEvents or internal messages,
  219167. // to keep everything running smoothly..
  219168. if ((++totalEventCount & 1) != 0)
  219169. return dispatchNextXEvent() || dispatchNextInternalMessage();
  219170. else
  219171. return dispatchNextInternalMessage() || dispatchNextXEvent();
  219172. }
  219173. // Wait for an event (either XEvent, or an internal Message)
  219174. bool sleepUntilEvent (const int timeoutMs)
  219175. {
  219176. if (! isEmpty())
  219177. return true;
  219178. if (display != 0)
  219179. {
  219180. ScopedXLock xlock;
  219181. if (XPending (display))
  219182. return true;
  219183. }
  219184. struct timeval tv;
  219185. tv.tv_sec = 0;
  219186. tv.tv_usec = timeoutMs * 1000;
  219187. int fd0 = getWaitHandle();
  219188. int fdmax = fd0;
  219189. fd_set readset;
  219190. FD_ZERO (&readset);
  219191. FD_SET (fd0, &readset);
  219192. if (display != 0)
  219193. {
  219194. ScopedXLock xlock;
  219195. int fd1 = XConnectionNumber (display);
  219196. FD_SET (fd1, &readset);
  219197. fdmax = jmax (fd0, fd1);
  219198. }
  219199. const int ret = select (fdmax + 1, &readset, 0, 0, &tv);
  219200. return (ret > 0); // ret <= 0 if error or timeout
  219201. }
  219202. struct MessageThreadFuncCall
  219203. {
  219204. enum { uniqueID = 0x73774623 };
  219205. MessageCallbackFunction* func;
  219206. void* parameter;
  219207. void* result;
  219208. CriticalSection lock;
  219209. WaitableEvent event;
  219210. };
  219211. juce_DeclareSingleton_SingleThreaded_Minimal (InternalMessageQueue);
  219212. private:
  219213. CriticalSection lock;
  219214. OwnedArray <Message> queue;
  219215. int fd[2];
  219216. int bytesInSocket;
  219217. int totalEventCount;
  219218. int getWaitHandle() const throw() { return fd[1]; }
  219219. static bool setNonBlocking (int handle)
  219220. {
  219221. int socketFlags = fcntl (handle, F_GETFL, 0);
  219222. if (socketFlags == -1)
  219223. return false;
  219224. socketFlags |= O_NONBLOCK;
  219225. return fcntl (handle, F_SETFL, socketFlags) == 0;
  219226. }
  219227. static bool dispatchNextXEvent()
  219228. {
  219229. if (display == 0)
  219230. return false;
  219231. XEvent evt;
  219232. {
  219233. ScopedXLock xlock;
  219234. if (! XPending (display))
  219235. return false;
  219236. XNextEvent (display, &evt);
  219237. }
  219238. if (evt.type == SelectionRequest && evt.xany.window == juce_messageWindowHandle)
  219239. juce_handleSelectionRequest (evt.xselectionrequest);
  219240. else if (evt.xany.window != juce_messageWindowHandle)
  219241. juce_windowMessageReceive (&evt);
  219242. return true;
  219243. }
  219244. Message* popNextMessage()
  219245. {
  219246. ScopedLock sl (lock);
  219247. if (bytesInSocket > 0)
  219248. {
  219249. --bytesInSocket;
  219250. ScopedUnlock ul (lock);
  219251. unsigned char x;
  219252. size_t numBytes = read (fd[1], &x, 1);
  219253. (void) numBytes;
  219254. }
  219255. return queue.removeAndReturn (0);
  219256. }
  219257. bool dispatchNextInternalMessage()
  219258. {
  219259. ScopedPointer <Message> msg (popNextMessage());
  219260. if (msg == 0)
  219261. return false;
  219262. if (msg->intParameter1 == MessageThreadFuncCall::uniqueID)
  219263. {
  219264. // Handle callback message
  219265. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) msg->pointerParameter;
  219266. call->result = (*(call->func)) (call->parameter);
  219267. call->event.signal();
  219268. }
  219269. else
  219270. {
  219271. // Handle "normal" messages
  219272. MessageManager::getInstance()->deliverMessage (msg.release());
  219273. }
  219274. return true;
  219275. }
  219276. };
  219277. juce_ImplementSingleton_SingleThreaded (InternalMessageQueue);
  219278. namespace LinuxErrorHandling
  219279. {
  219280. static bool errorOccurred = false;
  219281. static bool keyboardBreakOccurred = false;
  219282. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219283. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219284. // Usually happens when client-server connection is broken
  219285. static int ioErrorHandler (Display* display)
  219286. {
  219287. DBG ("ERROR: connection to X server broken.. terminating.");
  219288. if (JUCEApplication::isStandaloneApp())
  219289. MessageManager::getInstance()->stopDispatchLoop();
  219290. errorOccurred = true;
  219291. return 0;
  219292. }
  219293. // A protocol error has occurred
  219294. static int juce_XErrorHandler (Display* display, XErrorEvent* event)
  219295. {
  219296. #if JUCE_DEBUG_XERRORS
  219297. char errorStr[64] = { 0 };
  219298. char requestStr[64] = { 0 };
  219299. XGetErrorText (display, event->error_code, errorStr, 64);
  219300. XGetErrorDatabaseText (display, "XRequest", String (event->request_code).toCString(), "Unknown", requestStr, 64);
  219301. DBG ("ERROR: X returned " + String (errorStr) + " for operation " + String (requestStr));
  219302. #endif
  219303. return 0;
  219304. }
  219305. static void installXErrorHandlers()
  219306. {
  219307. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219308. oldErrorHandler = XSetErrorHandler (juce_XErrorHandler);
  219309. }
  219310. static void removeXErrorHandlers()
  219311. {
  219312. XSetIOErrorHandler (oldIOErrorHandler);
  219313. oldIOErrorHandler = 0;
  219314. XSetErrorHandler (oldErrorHandler);
  219315. oldErrorHandler = 0;
  219316. }
  219317. static void keyboardBreakSignalHandler (int sig)
  219318. {
  219319. if (sig == SIGINT)
  219320. keyboardBreakOccurred = true;
  219321. }
  219322. static void installKeyboardBreakHandler()
  219323. {
  219324. struct sigaction saction;
  219325. sigset_t maskSet;
  219326. sigemptyset (&maskSet);
  219327. saction.sa_handler = keyboardBreakSignalHandler;
  219328. saction.sa_mask = maskSet;
  219329. saction.sa_flags = 0;
  219330. sigaction (SIGINT, &saction, 0);
  219331. }
  219332. }
  219333. void MessageManager::doPlatformSpecificInitialisation()
  219334. {
  219335. // Initialise xlib for multiple thread support
  219336. static bool initThreadCalled = false;
  219337. if (! initThreadCalled)
  219338. {
  219339. if (! XInitThreads())
  219340. {
  219341. // This is fatal! Print error and closedown
  219342. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219343. if (JUCEApplication::isStandaloneApp())
  219344. Process::terminate();
  219345. return;
  219346. }
  219347. initThreadCalled = true;
  219348. }
  219349. LinuxErrorHandling::installXErrorHandlers();
  219350. LinuxErrorHandling::installKeyboardBreakHandler();
  219351. // Create the internal message queue
  219352. InternalMessageQueue::getInstance();
  219353. // Try to connect to a display
  219354. String displayName (getenv ("DISPLAY"));
  219355. if (displayName.isEmpty())
  219356. displayName = ":0.0";
  219357. display = XOpenDisplay (displayName.toCString());
  219358. if (display != 0) // This is not fatal! we can run headless.
  219359. {
  219360. // Create a context to store user data associated with Windows we create in WindowDriver
  219361. windowHandleXContext = XUniqueContext();
  219362. // We're only interested in client messages for this window, which are always sent
  219363. XSetWindowAttributes swa;
  219364. swa.event_mask = NoEventMask;
  219365. // Create our message window (this will never be mapped)
  219366. const int screen = DefaultScreen (display);
  219367. juce_messageWindowHandle = XCreateWindow (display, RootWindow (display, screen),
  219368. 0, 0, 1, 1, 0, 0, InputOnly,
  219369. DefaultVisual (display, screen),
  219370. CWEventMask, &swa);
  219371. }
  219372. }
  219373. void MessageManager::doPlatformSpecificShutdown()
  219374. {
  219375. InternalMessageQueue::deleteInstance();
  219376. if (display != 0 && ! LinuxErrorHandling::errorOccurred)
  219377. {
  219378. XDestroyWindow (display, juce_messageWindowHandle);
  219379. XCloseDisplay (display);
  219380. juce_messageWindowHandle = 0;
  219381. display = 0;
  219382. LinuxErrorHandling::removeXErrorHandlers();
  219383. }
  219384. }
  219385. bool juce_postMessageToSystemQueue (Message* message)
  219386. {
  219387. if (LinuxErrorHandling::errorOccurred)
  219388. return false;
  219389. InternalMessageQueue::getInstanceWithoutCreating()->postMessage (message);
  219390. return true;
  219391. }
  219392. void MessageManager::broadcastMessage (const String& value)
  219393. {
  219394. /* TODO */
  219395. }
  219396. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func, void* parameter)
  219397. {
  219398. if (LinuxErrorHandling::errorOccurred)
  219399. return 0;
  219400. if (isThisTheMessageThread())
  219401. return func (parameter);
  219402. InternalMessageQueue::MessageThreadFuncCall messageCallContext;
  219403. messageCallContext.func = func;
  219404. messageCallContext.parameter = parameter;
  219405. InternalMessageQueue::getInstanceWithoutCreating()
  219406. ->postMessage (new Message (InternalMessageQueue::MessageThreadFuncCall::uniqueID,
  219407. 0, 0, &messageCallContext));
  219408. // Wait for it to complete before continuing
  219409. messageCallContext.event.wait();
  219410. return messageCallContext.result;
  219411. }
  219412. // this function expects that it will NEVER be called simultaneously for two concurrent threads
  219413. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219414. {
  219415. while (! LinuxErrorHandling::errorOccurred)
  219416. {
  219417. if (LinuxErrorHandling::keyboardBreakOccurred)
  219418. {
  219419. LinuxErrorHandling::errorOccurred = true;
  219420. if (JUCEApplication::isStandaloneApp())
  219421. Process::terminate();
  219422. break;
  219423. }
  219424. if (InternalMessageQueue::getInstanceWithoutCreating()->dispatchNextEvent())
  219425. return true;
  219426. if (returnIfNoPendingMessages)
  219427. break;
  219428. InternalMessageQueue::getInstanceWithoutCreating()->sleepUntilEvent (2000);
  219429. }
  219430. return false;
  219431. }
  219432. #endif
  219433. /*** End of inlined file: juce_linux_Messaging.cpp ***/
  219434. /*** Start of inlined file: juce_linux_Fonts.cpp ***/
  219435. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219436. // compiled on its own).
  219437. #if JUCE_INCLUDED_FILE
  219438. class FreeTypeFontFace
  219439. {
  219440. public:
  219441. enum FontStyle
  219442. {
  219443. Plain = 0,
  219444. Bold = 1,
  219445. Italic = 2
  219446. };
  219447. FreeTypeFontFace (const String& familyName)
  219448. : hasSerif (false),
  219449. monospaced (false)
  219450. {
  219451. family = familyName;
  219452. }
  219453. void setFileName (const String& name, const int faceIndex, FontStyle style)
  219454. {
  219455. if (names [(int) style].fileName.isEmpty())
  219456. {
  219457. names [(int) style].fileName = name;
  219458. names [(int) style].faceIndex = faceIndex;
  219459. }
  219460. }
  219461. const String& getFamilyName() const throw() { return family; }
  219462. const String& getFileName (const int style, int& faceIndex) const throw()
  219463. {
  219464. faceIndex = names[style].faceIndex;
  219465. return names[style].fileName;
  219466. }
  219467. void setMonospaced (bool mono) throw() { monospaced = mono; }
  219468. bool getMonospaced() const throw() { return monospaced; }
  219469. void setSerif (const bool serif) throw() { hasSerif = serif; }
  219470. bool getSerif() const throw() { return hasSerif; }
  219471. private:
  219472. String family;
  219473. struct FontNameIndex
  219474. {
  219475. String fileName;
  219476. int faceIndex;
  219477. };
  219478. FontNameIndex names[4];
  219479. bool hasSerif, monospaced;
  219480. };
  219481. class FreeTypeInterface : public DeletedAtShutdown
  219482. {
  219483. public:
  219484. FreeTypeInterface()
  219485. : ftLib (0),
  219486. lastFace (0),
  219487. lastBold (false),
  219488. lastItalic (false)
  219489. {
  219490. if (FT_Init_FreeType (&ftLib) != 0)
  219491. {
  219492. ftLib = 0;
  219493. DBG ("Failed to initialize FreeType");
  219494. }
  219495. StringArray fontDirs;
  219496. fontDirs.addTokens (String::fromUTF8 (getenv ("JUCE_FONT_PATH")), ";,", String::empty);
  219497. fontDirs.removeEmptyStrings (true);
  219498. if (fontDirs.size() == 0)
  219499. {
  219500. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219501. const ScopedPointer<XmlElement> fontsInfo (fontsConfig.getDocumentElement());
  219502. if (fontsInfo != 0)
  219503. {
  219504. forEachXmlChildElementWithTagName (*fontsInfo, e, "dir")
  219505. {
  219506. fontDirs.add (e->getAllSubText().trim());
  219507. }
  219508. }
  219509. }
  219510. if (fontDirs.size() == 0)
  219511. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219512. for (int i = 0; i < fontDirs.size(); ++i)
  219513. enumerateFaces (fontDirs[i]);
  219514. }
  219515. ~FreeTypeInterface()
  219516. {
  219517. if (lastFace != 0)
  219518. FT_Done_Face (lastFace);
  219519. if (ftLib != 0)
  219520. FT_Done_FreeType (ftLib);
  219521. clearSingletonInstance();
  219522. }
  219523. FreeTypeFontFace* findOrCreate (const String& familyName, const bool create = false)
  219524. {
  219525. for (int i = 0; i < faces.size(); i++)
  219526. if (faces[i]->getFamilyName() == familyName)
  219527. return faces[i];
  219528. if (! create)
  219529. return 0;
  219530. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219531. faces.add (newFace);
  219532. return newFace;
  219533. }
  219534. // Enumerate all font faces available in a given directory
  219535. void enumerateFaces (const String& path)
  219536. {
  219537. File dirPath (path);
  219538. if (path.isEmpty() || ! dirPath.isDirectory())
  219539. return;
  219540. DirectoryIterator di (dirPath, true);
  219541. while (di.next())
  219542. {
  219543. File possible (di.getFile());
  219544. if (possible.hasFileExtension ("ttf")
  219545. || possible.hasFileExtension ("pfb")
  219546. || possible.hasFileExtension ("pcf"))
  219547. {
  219548. FT_Face face;
  219549. int faceIndex = 0;
  219550. int numFaces = 0;
  219551. do
  219552. {
  219553. if (FT_New_Face (ftLib, possible.getFullPathName().toUTF8(),
  219554. faceIndex, &face) == 0)
  219555. {
  219556. if (faceIndex == 0)
  219557. numFaces = face->num_faces;
  219558. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219559. {
  219560. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219561. int style = (int) FreeTypeFontFace::Plain;
  219562. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219563. style |= (int) FreeTypeFontFace::Bold;
  219564. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219565. style |= (int) FreeTypeFontFace::Italic;
  219566. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219567. newFace->setMonospaced ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0);
  219568. // Surely there must be a better way to do this?
  219569. const String name (face->family_name);
  219570. newFace->setSerif (! (name.containsIgnoreCase ("Sans")
  219571. || name.containsIgnoreCase ("Verdana")
  219572. || name.containsIgnoreCase ("Arial")));
  219573. }
  219574. FT_Done_Face (face);
  219575. }
  219576. ++faceIndex;
  219577. }
  219578. while (faceIndex < numFaces);
  219579. }
  219580. }
  219581. }
  219582. // Create a FreeType face object for a given font
  219583. FT_Face createFT_Face (const String& fontName, const bool bold, const bool italic)
  219584. {
  219585. FT_Face face = 0;
  219586. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219587. {
  219588. face = lastFace;
  219589. }
  219590. else
  219591. {
  219592. if (lastFace != 0)
  219593. {
  219594. FT_Done_Face (lastFace);
  219595. lastFace = 0;
  219596. }
  219597. lastFontName = fontName;
  219598. lastBold = bold;
  219599. lastItalic = italic;
  219600. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219601. if (ftFace != 0)
  219602. {
  219603. int style = (int) FreeTypeFontFace::Plain;
  219604. if (bold)
  219605. style |= (int) FreeTypeFontFace::Bold;
  219606. if (italic)
  219607. style |= (int) FreeTypeFontFace::Italic;
  219608. int faceIndex;
  219609. String fileName (ftFace->getFileName (style, faceIndex));
  219610. if (fileName.isEmpty())
  219611. {
  219612. style ^= (int) FreeTypeFontFace::Bold;
  219613. fileName = ftFace->getFileName (style, faceIndex);
  219614. if (fileName.isEmpty())
  219615. {
  219616. style ^= (int) FreeTypeFontFace::Bold;
  219617. style ^= (int) FreeTypeFontFace::Italic;
  219618. fileName = ftFace->getFileName (style, faceIndex);
  219619. if (! fileName.length())
  219620. {
  219621. style ^= (int) FreeTypeFontFace::Bold;
  219622. fileName = ftFace->getFileName (style, faceIndex);
  219623. }
  219624. }
  219625. }
  219626. if (! FT_New_Face (ftLib, fileName.toUTF8(), faceIndex, &lastFace))
  219627. {
  219628. face = lastFace;
  219629. // If there isn't a unicode charmap then select the first one.
  219630. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219631. FT_Set_Charmap (face, face->charmaps[0]);
  219632. }
  219633. }
  219634. }
  219635. return face;
  219636. }
  219637. bool addGlyph (FT_Face face, CustomTypeface& dest, uint32 character)
  219638. {
  219639. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219640. const float height = (float) (face->ascender - face->descender);
  219641. const float scaleX = 1.0f / height;
  219642. const float scaleY = -1.0f / height;
  219643. Path destShape;
  219644. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE | FT_LOAD_NO_BITMAP | FT_LOAD_IGNORE_TRANSFORM) != 0
  219645. || face->glyph->format != ft_glyph_format_outline)
  219646. {
  219647. return false;
  219648. }
  219649. const FT_Outline* const outline = &face->glyph->outline;
  219650. const short* const contours = outline->contours;
  219651. const char* const tags = outline->tags;
  219652. FT_Vector* const points = outline->points;
  219653. for (int c = 0; c < outline->n_contours; c++)
  219654. {
  219655. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219656. const int endPoint = contours[c];
  219657. for (int p = startPoint; p <= endPoint; p++)
  219658. {
  219659. const float x = scaleX * points[p].x;
  219660. const float y = scaleY * points[p].y;
  219661. if (p == startPoint)
  219662. {
  219663. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219664. {
  219665. float x2 = scaleX * points [endPoint].x;
  219666. float y2 = scaleY * points [endPoint].y;
  219667. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219668. {
  219669. x2 = (x + x2) * 0.5f;
  219670. y2 = (y + y2) * 0.5f;
  219671. }
  219672. destShape.startNewSubPath (x2, y2);
  219673. }
  219674. else
  219675. {
  219676. destShape.startNewSubPath (x, y);
  219677. }
  219678. }
  219679. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219680. {
  219681. if (p != startPoint)
  219682. destShape.lineTo (x, y);
  219683. }
  219684. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219685. {
  219686. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219687. float x2 = scaleX * points [nextIndex].x;
  219688. float y2 = scaleY * points [nextIndex].y;
  219689. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219690. {
  219691. x2 = (x + x2) * 0.5f;
  219692. y2 = (y + y2) * 0.5f;
  219693. }
  219694. else
  219695. {
  219696. ++p;
  219697. }
  219698. destShape.quadraticTo (x, y, x2, y2);
  219699. }
  219700. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219701. {
  219702. if (p >= endPoint)
  219703. return false;
  219704. const int next1 = p + 1;
  219705. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219706. const float x2 = scaleX * points [next1].x;
  219707. const float y2 = scaleY * points [next1].y;
  219708. const float x3 = scaleX * points [next2].x;
  219709. const float y3 = scaleY * points [next2].y;
  219710. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219711. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219712. return false;
  219713. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219714. p += 2;
  219715. }
  219716. }
  219717. destShape.closeSubPath();
  219718. }
  219719. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance / height);
  219720. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219721. addKerning (face, dest, character, glyphIndex);
  219722. return true;
  219723. }
  219724. void addKerning (FT_Face face, CustomTypeface& dest, const uint32 character, const uint32 glyphIndex)
  219725. {
  219726. const float height = (float) (face->ascender - face->descender);
  219727. uint32 rightGlyphIndex;
  219728. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219729. while (rightGlyphIndex != 0)
  219730. {
  219731. FT_Vector kerning;
  219732. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219733. {
  219734. if (kerning.x != 0)
  219735. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219736. }
  219737. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219738. }
  219739. }
  219740. // Add a glyph to a font
  219741. bool addGlyphToFont (const uint32 character, const String& fontName,
  219742. bool bold, bool italic, CustomTypeface& dest)
  219743. {
  219744. FT_Face face = createFT_Face (fontName, bold, italic);
  219745. return face != 0 && addGlyph (face, dest, character);
  219746. }
  219747. void getFamilyNames (StringArray& familyNames) const
  219748. {
  219749. for (int i = 0; i < faces.size(); i++)
  219750. familyNames.add (faces[i]->getFamilyName());
  219751. }
  219752. void getMonospacedNames (StringArray& monoSpaced) const
  219753. {
  219754. for (int i = 0; i < faces.size(); i++)
  219755. if (faces[i]->getMonospaced())
  219756. monoSpaced.add (faces[i]->getFamilyName());
  219757. }
  219758. void getSerifNames (StringArray& serif) const
  219759. {
  219760. for (int i = 0; i < faces.size(); i++)
  219761. if (faces[i]->getSerif())
  219762. serif.add (faces[i]->getFamilyName());
  219763. }
  219764. void getSansSerifNames (StringArray& sansSerif) const
  219765. {
  219766. for (int i = 0; i < faces.size(); i++)
  219767. if (! faces[i]->getSerif())
  219768. sansSerif.add (faces[i]->getFamilyName());
  219769. }
  219770. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219771. private:
  219772. FT_Library ftLib;
  219773. FT_Face lastFace;
  219774. String lastFontName;
  219775. bool lastBold, lastItalic;
  219776. OwnedArray<FreeTypeFontFace> faces;
  219777. };
  219778. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219779. class FreetypeTypeface : public CustomTypeface
  219780. {
  219781. public:
  219782. FreetypeTypeface (const Font& font)
  219783. {
  219784. FT_Face face = FreeTypeInterface::getInstance()
  219785. ->createFT_Face (font.getTypefaceName(), font.isBold(), font.isItalic());
  219786. if (face == 0)
  219787. {
  219788. #if JUCE_DEBUG
  219789. String msg ("Failed to create typeface: ");
  219790. msg << font.getTypefaceName() << " " << (font.isBold() ? 'B' : ' ') << (font.isItalic() ? 'I' : ' ');
  219791. DBG (msg);
  219792. #endif
  219793. }
  219794. else
  219795. {
  219796. setCharacteristics (font.getTypefaceName(),
  219797. face->ascender / (float) (face->ascender - face->descender),
  219798. font.isBold(), font.isItalic(),
  219799. L' ');
  219800. }
  219801. }
  219802. bool loadGlyphIfPossible (juce_wchar character)
  219803. {
  219804. return FreeTypeInterface::getInstance()
  219805. ->addGlyphToFont (character, name, isBold, isItalic, *this);
  219806. }
  219807. };
  219808. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  219809. {
  219810. return new FreetypeTypeface (font);
  219811. }
  219812. const StringArray Font::findAllTypefaceNames()
  219813. {
  219814. StringArray s;
  219815. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219816. s.sort (true);
  219817. return s;
  219818. }
  219819. namespace
  219820. {
  219821. const String pickBestFont (const StringArray& names,
  219822. const char* const choicesString)
  219823. {
  219824. StringArray choices;
  219825. choices.addTokens (String (choicesString), ",", String::empty);
  219826. choices.trim();
  219827. choices.removeEmptyStrings();
  219828. int i, j;
  219829. for (j = 0; j < choices.size(); ++j)
  219830. if (names.contains (choices[j], true))
  219831. return choices[j];
  219832. for (j = 0; j < choices.size(); ++j)
  219833. for (i = 0; i < names.size(); i++)
  219834. if (names[i].startsWithIgnoreCase (choices[j]))
  219835. return names[i];
  219836. for (j = 0; j < choices.size(); ++j)
  219837. for (i = 0; i < names.size(); i++)
  219838. if (names[i].containsIgnoreCase (choices[j]))
  219839. return names[i];
  219840. return names[0];
  219841. }
  219842. const String linux_getDefaultSansSerifFontName()
  219843. {
  219844. StringArray allFonts;
  219845. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219846. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219847. }
  219848. const String linux_getDefaultSerifFontName()
  219849. {
  219850. StringArray allFonts;
  219851. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219852. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219853. }
  219854. const String linux_getDefaultMonospacedFontName()
  219855. {
  219856. StringArray allFonts;
  219857. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219858. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219859. }
  219860. }
  219861. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  219862. {
  219863. defaultSans = linux_getDefaultSansSerifFontName();
  219864. defaultSerif = linux_getDefaultSerifFontName();
  219865. defaultFixed = linux_getDefaultMonospacedFontName();
  219866. }
  219867. #endif
  219868. /*** End of inlined file: juce_linux_Fonts.cpp ***/
  219869. /*** Start of inlined file: juce_linux_Windowing.cpp ***/
  219870. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  219871. // compiled on its own).
  219872. #if JUCE_INCLUDED_FILE
  219873. // These are defined in juce_linux_Messaging.cpp
  219874. extern Display* display;
  219875. extern XContext windowHandleXContext;
  219876. namespace Atoms
  219877. {
  219878. enum ProtocolItems
  219879. {
  219880. TAKE_FOCUS = 0,
  219881. DELETE_WINDOW = 1,
  219882. PING = 2
  219883. };
  219884. static Atom Protocols, ProtocolList[3], ChangeState, State,
  219885. ActiveWin, Pid, WindowType, WindowState,
  219886. XdndAware, XdndEnter, XdndLeave, XdndPosition, XdndStatus,
  219887. XdndDrop, XdndFinished, XdndSelection, XdndTypeList, XdndActionList,
  219888. XdndActionDescription, XdndActionCopy,
  219889. allowedActions[5],
  219890. allowedMimeTypes[2];
  219891. const unsigned long DndVersion = 3;
  219892. static void initialiseAtoms()
  219893. {
  219894. static bool atomsInitialised = false;
  219895. if (! atomsInitialised)
  219896. {
  219897. atomsInitialised = true;
  219898. Protocols = XInternAtom (display, "WM_PROTOCOLS", True);
  219899. ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", True);
  219900. ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", True);
  219901. ProtocolList [PING] = XInternAtom (display, "_NET_WM_PING", True);
  219902. ChangeState = XInternAtom (display, "WM_CHANGE_STATE", True);
  219903. State = XInternAtom (display, "WM_STATE", True);
  219904. ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  219905. Pid = XInternAtom (display, "_NET_WM_PID", False);
  219906. WindowType = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  219907. WindowState = XInternAtom (display, "_NET_WM_STATE", True);
  219908. XdndAware = XInternAtom (display, "XdndAware", False);
  219909. XdndEnter = XInternAtom (display, "XdndEnter", False);
  219910. XdndLeave = XInternAtom (display, "XdndLeave", False);
  219911. XdndPosition = XInternAtom (display, "XdndPosition", False);
  219912. XdndStatus = XInternAtom (display, "XdndStatus", False);
  219913. XdndDrop = XInternAtom (display, "XdndDrop", False);
  219914. XdndFinished = XInternAtom (display, "XdndFinished", False);
  219915. XdndSelection = XInternAtom (display, "XdndSelection", False);
  219916. XdndTypeList = XInternAtom (display, "XdndTypeList", False);
  219917. XdndActionList = XInternAtom (display, "XdndActionList", False);
  219918. XdndActionCopy = XInternAtom (display, "XdndActionCopy", False);
  219919. XdndActionDescription = XInternAtom (display, "XdndActionDescription", False);
  219920. allowedMimeTypes[0] = XInternAtom (display, "text/plain", False);
  219921. allowedMimeTypes[1] = XInternAtom (display, "text/uri-list", False);
  219922. allowedActions[0] = XInternAtom (display, "XdndActionMove", False);
  219923. allowedActions[1] = XdndActionCopy;
  219924. allowedActions[2] = XInternAtom (display, "XdndActionLink", False);
  219925. allowedActions[3] = XInternAtom (display, "XdndActionAsk", False);
  219926. allowedActions[4] = XInternAtom (display, "XdndActionPrivate", False);
  219927. }
  219928. }
  219929. }
  219930. namespace Keys
  219931. {
  219932. enum MouseButtons
  219933. {
  219934. NoButton = 0,
  219935. LeftButton = 1,
  219936. MiddleButton = 2,
  219937. RightButton = 3,
  219938. WheelUp = 4,
  219939. WheelDown = 5
  219940. };
  219941. static int AltMask = 0;
  219942. static int NumLockMask = 0;
  219943. static bool numLock = false;
  219944. static bool capsLock = false;
  219945. static char keyStates [32];
  219946. static const int extendedKeyModifier = 0x10000000;
  219947. }
  219948. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  219949. {
  219950. int keysym;
  219951. if (keyCode & Keys::extendedKeyModifier)
  219952. {
  219953. keysym = 0xff00 | (keyCode & 0xff);
  219954. }
  219955. else
  219956. {
  219957. keysym = keyCode;
  219958. if (keysym == (XK_Tab & 0xff)
  219959. || keysym == (XK_Return & 0xff)
  219960. || keysym == (XK_Escape & 0xff)
  219961. || keysym == (XK_BackSpace & 0xff))
  219962. {
  219963. keysym |= 0xff00;
  219964. }
  219965. }
  219966. ScopedXLock xlock;
  219967. const int keycode = XKeysymToKeycode (display, keysym);
  219968. const int keybyte = keycode >> 3;
  219969. const int keybit = (1 << (keycode & 7));
  219970. return (Keys::keyStates [keybyte] & keybit) != 0;
  219971. }
  219972. #if JUCE_USE_XSHM
  219973. namespace XSHMHelpers
  219974. {
  219975. static int trappedErrorCode = 0;
  219976. extern "C" int errorTrapHandler (Display*, XErrorEvent* err)
  219977. {
  219978. trappedErrorCode = err->error_code;
  219979. return 0;
  219980. }
  219981. static bool isShmAvailable() throw()
  219982. {
  219983. static bool isChecked = false;
  219984. static bool isAvailable = false;
  219985. if (! isChecked)
  219986. {
  219987. isChecked = true;
  219988. int major, minor;
  219989. Bool pixmaps;
  219990. ScopedXLock xlock;
  219991. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  219992. {
  219993. trappedErrorCode = 0;
  219994. XErrorHandler oldHandler = XSetErrorHandler (errorTrapHandler);
  219995. XShmSegmentInfo segmentInfo;
  219996. zerostruct (segmentInfo);
  219997. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  219998. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  219999. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220000. xImage->bytes_per_line * xImage->height,
  220001. IPC_CREAT | 0777)) >= 0)
  220002. {
  220003. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220004. if (segmentInfo.shmaddr != (void*) -1)
  220005. {
  220006. segmentInfo.readOnly = False;
  220007. xImage->data = segmentInfo.shmaddr;
  220008. XSync (display, False);
  220009. if (XShmAttach (display, &segmentInfo) != 0)
  220010. {
  220011. XSync (display, False);
  220012. XShmDetach (display, &segmentInfo);
  220013. isAvailable = true;
  220014. }
  220015. }
  220016. XFlush (display);
  220017. XDestroyImage (xImage);
  220018. shmdt (segmentInfo.shmaddr);
  220019. }
  220020. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220021. XSetErrorHandler (oldHandler);
  220022. if (trappedErrorCode != 0)
  220023. isAvailable = false;
  220024. }
  220025. }
  220026. return isAvailable;
  220027. }
  220028. }
  220029. #endif
  220030. #if JUCE_USE_XRENDER
  220031. namespace XRender
  220032. {
  220033. typedef Status (*tXRenderQueryVersion) (Display*, int*, int*);
  220034. typedef XRenderPictFormat* (*tXrenderFindStandardFormat) (Display*, int);
  220035. typedef XRenderPictFormat* (*tXRenderFindFormat) (Display*, unsigned long, XRenderPictFormat*, int);
  220036. typedef XRenderPictFormat* (*tXRenderFindVisualFormat) (Display*, Visual*);
  220037. static tXRenderQueryVersion xRenderQueryVersion = 0;
  220038. static tXrenderFindStandardFormat xRenderFindStandardFormat = 0;
  220039. static tXRenderFindFormat xRenderFindFormat = 0;
  220040. static tXRenderFindVisualFormat xRenderFindVisualFormat = 0;
  220041. static bool isAvailable()
  220042. {
  220043. static bool hasLoaded = false;
  220044. if (! hasLoaded)
  220045. {
  220046. ScopedXLock xlock;
  220047. hasLoaded = true;
  220048. void* h = dlopen ("libXrender.so", RTLD_GLOBAL | RTLD_NOW);
  220049. if (h != 0)
  220050. {
  220051. xRenderQueryVersion = (tXRenderQueryVersion) dlsym (h, "XRenderQueryVersion");
  220052. xRenderFindStandardFormat = (tXrenderFindStandardFormat) dlsym (h, "XrenderFindStandardFormat");
  220053. xRenderFindFormat = (tXRenderFindFormat) dlsym (h, "XRenderFindFormat");
  220054. xRenderFindVisualFormat = (tXRenderFindVisualFormat) dlsym (h, "XRenderFindVisualFormat");
  220055. }
  220056. if (xRenderQueryVersion != 0
  220057. && xRenderFindStandardFormat != 0
  220058. && xRenderFindFormat != 0
  220059. && xRenderFindVisualFormat != 0)
  220060. {
  220061. int major, minor;
  220062. if (xRenderQueryVersion (display, &major, &minor))
  220063. return true;
  220064. }
  220065. xRenderQueryVersion = 0;
  220066. }
  220067. return xRenderQueryVersion != 0;
  220068. }
  220069. static XRenderPictFormat* findPictureFormat()
  220070. {
  220071. ScopedXLock xlock;
  220072. XRenderPictFormat* pictFormat = 0;
  220073. if (isAvailable())
  220074. {
  220075. pictFormat = xRenderFindStandardFormat (display, PictStandardARGB32);
  220076. if (pictFormat == 0)
  220077. {
  220078. XRenderPictFormat desiredFormat;
  220079. desiredFormat.type = PictTypeDirect;
  220080. desiredFormat.depth = 32;
  220081. desiredFormat.direct.alphaMask = 0xff;
  220082. desiredFormat.direct.redMask = 0xff;
  220083. desiredFormat.direct.greenMask = 0xff;
  220084. desiredFormat.direct.blueMask = 0xff;
  220085. desiredFormat.direct.alpha = 24;
  220086. desiredFormat.direct.red = 16;
  220087. desiredFormat.direct.green = 8;
  220088. desiredFormat.direct.blue = 0;
  220089. pictFormat = xRenderFindFormat (display,
  220090. PictFormatType | PictFormatDepth
  220091. | PictFormatRedMask | PictFormatRed
  220092. | PictFormatGreenMask | PictFormatGreen
  220093. | PictFormatBlueMask | PictFormatBlue
  220094. | PictFormatAlphaMask | PictFormatAlpha,
  220095. &desiredFormat,
  220096. 0);
  220097. }
  220098. }
  220099. return pictFormat;
  220100. }
  220101. }
  220102. #endif
  220103. namespace Visuals
  220104. {
  220105. static Visual* findVisualWithDepth (const int desiredDepth) throw()
  220106. {
  220107. ScopedXLock xlock;
  220108. Visual* visual = 0;
  220109. int numVisuals = 0;
  220110. long desiredMask = VisualNoMask;
  220111. XVisualInfo desiredVisual;
  220112. desiredVisual.screen = DefaultScreen (display);
  220113. desiredVisual.depth = desiredDepth;
  220114. desiredMask = VisualScreenMask | VisualDepthMask;
  220115. if (desiredDepth == 32)
  220116. {
  220117. desiredVisual.c_class = TrueColor;
  220118. desiredVisual.red_mask = 0x00FF0000;
  220119. desiredVisual.green_mask = 0x0000FF00;
  220120. desiredVisual.blue_mask = 0x000000FF;
  220121. desiredVisual.bits_per_rgb = 8;
  220122. desiredMask |= VisualClassMask;
  220123. desiredMask |= VisualRedMaskMask;
  220124. desiredMask |= VisualGreenMaskMask;
  220125. desiredMask |= VisualBlueMaskMask;
  220126. desiredMask |= VisualBitsPerRGBMask;
  220127. }
  220128. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220129. desiredMask,
  220130. &desiredVisual,
  220131. &numVisuals);
  220132. if (xvinfos != 0)
  220133. {
  220134. for (int i = 0; i < numVisuals; i++)
  220135. {
  220136. if (xvinfos[i].depth == desiredDepth)
  220137. {
  220138. visual = xvinfos[i].visual;
  220139. break;
  220140. }
  220141. }
  220142. XFree (xvinfos);
  220143. }
  220144. return visual;
  220145. }
  220146. static Visual* findVisualFormat (const int desiredDepth, int& matchedDepth) throw()
  220147. {
  220148. Visual* visual = 0;
  220149. if (desiredDepth == 32)
  220150. {
  220151. #if JUCE_USE_XSHM
  220152. if (XSHMHelpers::isShmAvailable())
  220153. {
  220154. #if JUCE_USE_XRENDER
  220155. if (XRender::isAvailable())
  220156. {
  220157. XRenderPictFormat* pictFormat = XRender::findPictureFormat();
  220158. if (pictFormat != 0)
  220159. {
  220160. int numVisuals = 0;
  220161. XVisualInfo desiredVisual;
  220162. desiredVisual.screen = DefaultScreen (display);
  220163. desiredVisual.depth = 32;
  220164. desiredVisual.bits_per_rgb = 8;
  220165. XVisualInfo* xvinfos = XGetVisualInfo (display,
  220166. VisualScreenMask | VisualDepthMask | VisualBitsPerRGBMask,
  220167. &desiredVisual, &numVisuals);
  220168. if (xvinfos != 0)
  220169. {
  220170. for (int i = 0; i < numVisuals; ++i)
  220171. {
  220172. XRenderPictFormat* pictVisualFormat = XRender::xRenderFindVisualFormat (display, xvinfos[i].visual);
  220173. if (pictVisualFormat != 0
  220174. && pictVisualFormat->type == PictTypeDirect
  220175. && pictVisualFormat->direct.alphaMask)
  220176. {
  220177. visual = xvinfos[i].visual;
  220178. matchedDepth = 32;
  220179. break;
  220180. }
  220181. }
  220182. XFree (xvinfos);
  220183. }
  220184. }
  220185. }
  220186. #endif
  220187. if (visual == 0)
  220188. {
  220189. visual = findVisualWithDepth (32);
  220190. if (visual != 0)
  220191. matchedDepth = 32;
  220192. }
  220193. }
  220194. #endif
  220195. }
  220196. if (visual == 0 && desiredDepth >= 24)
  220197. {
  220198. visual = findVisualWithDepth (24);
  220199. if (visual != 0)
  220200. matchedDepth = 24;
  220201. }
  220202. if (visual == 0 && desiredDepth >= 16)
  220203. {
  220204. visual = findVisualWithDepth (16);
  220205. if (visual != 0)
  220206. matchedDepth = 16;
  220207. }
  220208. return visual;
  220209. }
  220210. }
  220211. class XBitmapImage : public Image::SharedImage
  220212. {
  220213. public:
  220214. XBitmapImage (const Image::PixelFormat format_, const int w, const int h,
  220215. const bool clearImage, const int imageDepth_, Visual* visual)
  220216. : Image::SharedImage (format_, w, h),
  220217. imageDepth (imageDepth_),
  220218. gc (None)
  220219. {
  220220. jassert (format_ == Image::RGB || format_ == Image::ARGB);
  220221. pixelStride = (format_ == Image::RGB) ? 3 : 4;
  220222. lineStride = ((w * pixelStride + 3) & ~3);
  220223. ScopedXLock xlock;
  220224. #if JUCE_USE_XSHM
  220225. usingXShm = false;
  220226. if ((imageDepth > 16) && XSHMHelpers::isShmAvailable())
  220227. {
  220228. zerostruct (segmentInfo);
  220229. segmentInfo.shmid = -1;
  220230. segmentInfo.shmaddr = (char *) -1;
  220231. segmentInfo.readOnly = False;
  220232. xImage = XShmCreateImage (display, visual, imageDepth, ZPixmap, 0, &segmentInfo, w, h);
  220233. if (xImage != 0)
  220234. {
  220235. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220236. xImage->bytes_per_line * xImage->height,
  220237. IPC_CREAT | 0777)) >= 0)
  220238. {
  220239. if (segmentInfo.shmid != -1)
  220240. {
  220241. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220242. if (segmentInfo.shmaddr != (void*) -1)
  220243. {
  220244. segmentInfo.readOnly = False;
  220245. xImage->data = segmentInfo.shmaddr;
  220246. imageData = (uint8*) segmentInfo.shmaddr;
  220247. if (XShmAttach (display, &segmentInfo) != 0)
  220248. usingXShm = true;
  220249. else
  220250. jassertfalse;
  220251. }
  220252. else
  220253. {
  220254. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220255. }
  220256. }
  220257. }
  220258. }
  220259. }
  220260. if (! usingXShm)
  220261. #endif
  220262. {
  220263. imageDataAllocated.malloc (lineStride * h);
  220264. imageData = imageDataAllocated;
  220265. if (format_ == Image::ARGB && clearImage)
  220266. zeromem (imageData, h * lineStride);
  220267. xImage = (XImage*) juce_calloc (sizeof (XImage));
  220268. xImage->width = w;
  220269. xImage->height = h;
  220270. xImage->xoffset = 0;
  220271. xImage->format = ZPixmap;
  220272. xImage->data = (char*) imageData;
  220273. xImage->byte_order = ImageByteOrder (display);
  220274. xImage->bitmap_unit = BitmapUnit (display);
  220275. xImage->bitmap_bit_order = BitmapBitOrder (display);
  220276. xImage->bitmap_pad = 32;
  220277. xImage->depth = pixelStride * 8;
  220278. xImage->bytes_per_line = lineStride;
  220279. xImage->bits_per_pixel = pixelStride * 8;
  220280. xImage->red_mask = 0x00FF0000;
  220281. xImage->green_mask = 0x0000FF00;
  220282. xImage->blue_mask = 0x000000FF;
  220283. if (imageDepth == 16)
  220284. {
  220285. const int pixelStride = 2;
  220286. const int lineStride = ((w * pixelStride + 3) & ~3);
  220287. imageData16Bit.malloc (lineStride * h);
  220288. xImage->data = imageData16Bit;
  220289. xImage->bitmap_pad = 16;
  220290. xImage->depth = pixelStride * 8;
  220291. xImage->bytes_per_line = lineStride;
  220292. xImage->bits_per_pixel = pixelStride * 8;
  220293. xImage->red_mask = visual->red_mask;
  220294. xImage->green_mask = visual->green_mask;
  220295. xImage->blue_mask = visual->blue_mask;
  220296. }
  220297. if (! XInitImage (xImage))
  220298. jassertfalse;
  220299. }
  220300. }
  220301. ~XBitmapImage()
  220302. {
  220303. ScopedXLock xlock;
  220304. if (gc != None)
  220305. XFreeGC (display, gc);
  220306. #if JUCE_USE_XSHM
  220307. if (usingXShm)
  220308. {
  220309. XShmDetach (display, &segmentInfo);
  220310. XFlush (display);
  220311. XDestroyImage (xImage);
  220312. shmdt (segmentInfo.shmaddr);
  220313. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220314. }
  220315. else
  220316. #endif
  220317. {
  220318. xImage->data = 0;
  220319. XDestroyImage (xImage);
  220320. }
  220321. }
  220322. Image::ImageType getType() const { return Image::NativeImage; }
  220323. LowLevelGraphicsContext* createLowLevelContext()
  220324. {
  220325. return new LowLevelGraphicsSoftwareRenderer (Image (this));
  220326. }
  220327. SharedImage* clone()
  220328. {
  220329. jassertfalse;
  220330. return 0;
  220331. }
  220332. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  220333. {
  220334. ScopedXLock xlock;
  220335. if (gc == None)
  220336. {
  220337. XGCValues gcvalues;
  220338. gcvalues.foreground = None;
  220339. gcvalues.background = None;
  220340. gcvalues.function = GXcopy;
  220341. gcvalues.plane_mask = AllPlanes;
  220342. gcvalues.clip_mask = None;
  220343. gcvalues.graphics_exposures = False;
  220344. gc = XCreateGC (display, window,
  220345. GCBackground | GCForeground | GCFunction | GCPlaneMask | GCClipMask | GCGraphicsExposures,
  220346. &gcvalues);
  220347. }
  220348. if (imageDepth == 16)
  220349. {
  220350. const uint32 rMask = xImage->red_mask;
  220351. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  220352. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  220353. const uint32 gMask = xImage->green_mask;
  220354. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  220355. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  220356. const uint32 bMask = xImage->blue_mask;
  220357. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  220358. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  220359. const Image::BitmapData srcData (Image (this), false);
  220360. for (int y = sy; y < sy + dh; ++y)
  220361. {
  220362. const uint8* p = srcData.getPixelPointer (sx, y);
  220363. for (int x = sx; x < sx + dw; ++x)
  220364. {
  220365. const PixelRGB* const pixel = (const PixelRGB*) p;
  220366. p += srcData.pixelStride;
  220367. XPutPixel (xImage, x, y,
  220368. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  220369. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  220370. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  220371. }
  220372. }
  220373. }
  220374. // blit results to screen.
  220375. #if JUCE_USE_XSHM
  220376. if (usingXShm)
  220377. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, True);
  220378. else
  220379. #endif
  220380. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  220381. }
  220382. juce_UseDebuggingNewOperator
  220383. private:
  220384. XImage* xImage;
  220385. const int imageDepth;
  220386. HeapBlock <uint8> imageDataAllocated;
  220387. HeapBlock <char> imageData16Bit;
  220388. GC gc;
  220389. #if JUCE_USE_XSHM
  220390. XShmSegmentInfo segmentInfo;
  220391. bool usingXShm;
  220392. #endif
  220393. static int getShiftNeeded (const uint32 mask) throw()
  220394. {
  220395. for (int i = 32; --i >= 0;)
  220396. if (((mask >> i) & 1) != 0)
  220397. return i - 7;
  220398. jassertfalse;
  220399. return 0;
  220400. }
  220401. };
  220402. class LinuxComponentPeer : public ComponentPeer
  220403. {
  220404. public:
  220405. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  220406. : ComponentPeer (component, windowStyleFlags),
  220407. windowH (0),
  220408. parentWindow (0),
  220409. wx (0),
  220410. wy (0),
  220411. ww (0),
  220412. wh (0),
  220413. fullScreen (false),
  220414. mapped (false),
  220415. visual (0),
  220416. depth (0)
  220417. {
  220418. // it's dangerous to create a window on a thread other than the message thread..
  220419. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220420. repainter = new LinuxRepaintManager (this);
  220421. createWindow();
  220422. setTitle (component->getName());
  220423. }
  220424. ~LinuxComponentPeer()
  220425. {
  220426. // it's dangerous to delete a window on a thread other than the message thread..
  220427. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  220428. deleteIconPixmaps();
  220429. destroyWindow();
  220430. windowH = 0;
  220431. }
  220432. void* getNativeHandle() const
  220433. {
  220434. return (void*) windowH;
  220435. }
  220436. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  220437. {
  220438. XPointer peer = 0;
  220439. ScopedXLock xlock;
  220440. if (! XFindContext (display, (XID) windowHandle, windowHandleXContext, &peer))
  220441. {
  220442. if (peer != 0 && ! ComponentPeer::isValidPeer ((LinuxComponentPeer*) peer))
  220443. peer = 0;
  220444. }
  220445. return (LinuxComponentPeer*) peer;
  220446. }
  220447. void setVisible (bool shouldBeVisible)
  220448. {
  220449. ScopedXLock xlock;
  220450. if (shouldBeVisible)
  220451. XMapWindow (display, windowH);
  220452. else
  220453. XUnmapWindow (display, windowH);
  220454. }
  220455. void setTitle (const String& title)
  220456. {
  220457. setWindowTitle (windowH, title);
  220458. }
  220459. void setPosition (int x, int y)
  220460. {
  220461. setBounds (x, y, ww, wh, false);
  220462. }
  220463. void setSize (int w, int h)
  220464. {
  220465. setBounds (wx, wy, w, h, false);
  220466. }
  220467. void setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  220468. {
  220469. fullScreen = isNowFullScreen;
  220470. if (windowH != 0)
  220471. {
  220472. Component::SafePointer<Component> deletionChecker (component);
  220473. wx = x;
  220474. wy = y;
  220475. ww = jmax (1, w);
  220476. wh = jmax (1, h);
  220477. ScopedXLock xlock;
  220478. // Make sure the Window manager does what we want
  220479. XSizeHints* hints = XAllocSizeHints();
  220480. hints->flags = USSize | USPosition;
  220481. hints->width = ww;
  220482. hints->height = wh;
  220483. hints->x = wx;
  220484. hints->y = wy;
  220485. if ((getStyleFlags() & (windowHasTitleBar | windowIsResizable)) == windowHasTitleBar)
  220486. {
  220487. hints->min_width = hints->max_width = hints->width;
  220488. hints->min_height = hints->max_height = hints->height;
  220489. hints->flags |= PMinSize | PMaxSize;
  220490. }
  220491. XSetWMNormalHints (display, windowH, hints);
  220492. XFree (hints);
  220493. XMoveResizeWindow (display, windowH,
  220494. wx - windowBorder.getLeft(),
  220495. wy - windowBorder.getTop(), ww, wh);
  220496. if (deletionChecker != 0)
  220497. {
  220498. updateBorderSize();
  220499. handleMovedOrResized();
  220500. }
  220501. }
  220502. }
  220503. const Rectangle<int> getBounds() const { return Rectangle<int> (wx, wy, ww, wh); }
  220504. const Point<int> getScreenPosition() const { return Point<int> (wx, wy); }
  220505. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition)
  220506. {
  220507. return relativePosition + getScreenPosition();
  220508. }
  220509. const Point<int> globalPositionToRelative (const Point<int>& screenPosition)
  220510. {
  220511. return screenPosition - getScreenPosition();
  220512. }
  220513. void setAlpha (float newAlpha)
  220514. {
  220515. //xxx todo!
  220516. }
  220517. void setMinimised (bool shouldBeMinimised)
  220518. {
  220519. if (shouldBeMinimised)
  220520. {
  220521. Window root = RootWindow (display, DefaultScreen (display));
  220522. XClientMessageEvent clientMsg;
  220523. clientMsg.display = display;
  220524. clientMsg.window = windowH;
  220525. clientMsg.type = ClientMessage;
  220526. clientMsg.format = 32;
  220527. clientMsg.message_type = Atoms::ChangeState;
  220528. clientMsg.data.l[0] = IconicState;
  220529. ScopedXLock xlock;
  220530. XSendEvent (display, root, false, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*) &clientMsg);
  220531. }
  220532. else
  220533. {
  220534. setVisible (true);
  220535. }
  220536. }
  220537. bool isMinimised() const
  220538. {
  220539. bool minimised = false;
  220540. unsigned char* stateProp;
  220541. unsigned long nitems, bytesLeft;
  220542. Atom actualType;
  220543. int actualFormat;
  220544. ScopedXLock xlock;
  220545. if (XGetWindowProperty (display, windowH, Atoms::State, 0, 64, False,
  220546. Atoms::State, &actualType, &actualFormat, &nitems, &bytesLeft,
  220547. &stateProp) == Success
  220548. && actualType == Atoms::State
  220549. && actualFormat == 32
  220550. && nitems > 0)
  220551. {
  220552. if (((unsigned long*) stateProp)[0] == IconicState)
  220553. minimised = true;
  220554. XFree (stateProp);
  220555. }
  220556. return minimised;
  220557. }
  220558. void setFullScreen (const bool shouldBeFullScreen)
  220559. {
  220560. Rectangle<int> r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  220561. setMinimised (false);
  220562. if (fullScreen != shouldBeFullScreen)
  220563. {
  220564. if (shouldBeFullScreen)
  220565. r = Desktop::getInstance().getMainMonitorArea();
  220566. if (! r.isEmpty())
  220567. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  220568. getComponent()->repaint();
  220569. }
  220570. }
  220571. bool isFullScreen() const
  220572. {
  220573. return fullScreen;
  220574. }
  220575. bool isChildWindowOf (Window possibleParent) const
  220576. {
  220577. Window* windowList = 0;
  220578. uint32 windowListSize = 0;
  220579. Window parent, root;
  220580. ScopedXLock xlock;
  220581. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  220582. {
  220583. if (windowList != 0)
  220584. XFree (windowList);
  220585. return parent == possibleParent;
  220586. }
  220587. return false;
  220588. }
  220589. bool isFrontWindow() const
  220590. {
  220591. Window* windowList = 0;
  220592. uint32 windowListSize = 0;
  220593. bool result = false;
  220594. ScopedXLock xlock;
  220595. Window parent, root = RootWindow (display, DefaultScreen (display));
  220596. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  220597. {
  220598. for (int i = windowListSize; --i >= 0;)
  220599. {
  220600. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  220601. if (peer != 0)
  220602. {
  220603. result = (peer == this);
  220604. break;
  220605. }
  220606. }
  220607. }
  220608. if (windowList != 0)
  220609. XFree (windowList);
  220610. return result;
  220611. }
  220612. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const
  220613. {
  220614. int x = position.getX();
  220615. int y = position.getY();
  220616. if (((unsigned int) x) >= (unsigned int) ww
  220617. || ((unsigned int) y) >= (unsigned int) wh)
  220618. return false;
  220619. bool inFront = false;
  220620. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  220621. {
  220622. Component* const c = Desktop::getInstance().getComponent (i);
  220623. if (inFront)
  220624. {
  220625. if (c->contains (x + wx - c->getScreenX(),
  220626. y + wy - c->getScreenY()))
  220627. {
  220628. return false;
  220629. }
  220630. }
  220631. else if (c == getComponent())
  220632. {
  220633. inFront = true;
  220634. }
  220635. }
  220636. if (trueIfInAChildWindow)
  220637. return true;
  220638. ::Window root, child;
  220639. unsigned int bw, depth;
  220640. int wx, wy, w, h;
  220641. ScopedXLock xlock;
  220642. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  220643. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  220644. &bw, &depth))
  220645. {
  220646. return false;
  220647. }
  220648. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  220649. return false;
  220650. return child == None;
  220651. }
  220652. const BorderSize getFrameSize() const
  220653. {
  220654. return BorderSize();
  220655. }
  220656. bool setAlwaysOnTop (bool alwaysOnTop)
  220657. {
  220658. return false;
  220659. }
  220660. void toFront (bool makeActive)
  220661. {
  220662. if (makeActive)
  220663. {
  220664. setVisible (true);
  220665. grabFocus();
  220666. }
  220667. XEvent ev;
  220668. ev.xclient.type = ClientMessage;
  220669. ev.xclient.serial = 0;
  220670. ev.xclient.send_event = True;
  220671. ev.xclient.message_type = Atoms::ActiveWin;
  220672. ev.xclient.window = windowH;
  220673. ev.xclient.format = 32;
  220674. ev.xclient.data.l[0] = 2;
  220675. ev.xclient.data.l[1] = CurrentTime;
  220676. ev.xclient.data.l[2] = 0;
  220677. ev.xclient.data.l[3] = 0;
  220678. ev.xclient.data.l[4] = 0;
  220679. {
  220680. ScopedXLock xlock;
  220681. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  220682. False, SubstructureRedirectMask | SubstructureNotifyMask, &ev);
  220683. XWindowAttributes attr;
  220684. XGetWindowAttributes (display, windowH, &attr);
  220685. if (component->isAlwaysOnTop())
  220686. XRaiseWindow (display, windowH);
  220687. XSync (display, False);
  220688. }
  220689. handleBroughtToFront();
  220690. }
  220691. void toBehind (ComponentPeer* other)
  220692. {
  220693. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  220694. jassert (otherPeer != 0); // wrong type of window?
  220695. if (otherPeer != 0)
  220696. {
  220697. setMinimised (false);
  220698. Window newStack[] = { otherPeer->windowH, windowH };
  220699. ScopedXLock xlock;
  220700. XRestackWindows (display, newStack, 2);
  220701. }
  220702. }
  220703. bool isFocused() const
  220704. {
  220705. int revert = 0;
  220706. Window focusedWindow = 0;
  220707. ScopedXLock xlock;
  220708. XGetInputFocus (display, &focusedWindow, &revert);
  220709. return focusedWindow == windowH;
  220710. }
  220711. void grabFocus()
  220712. {
  220713. XWindowAttributes atts;
  220714. ScopedXLock xlock;
  220715. if (windowH != 0
  220716. && XGetWindowAttributes (display, windowH, &atts)
  220717. && atts.map_state == IsViewable
  220718. && ! isFocused())
  220719. {
  220720. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  220721. isActiveApplication = true;
  220722. }
  220723. }
  220724. void textInputRequired (const Point<int>&)
  220725. {
  220726. }
  220727. void repaint (const Rectangle<int>& area)
  220728. {
  220729. repainter->repaint (area.getIntersection (getComponent()->getLocalBounds()));
  220730. }
  220731. void performAnyPendingRepaintsNow()
  220732. {
  220733. repainter->performAnyPendingRepaintsNow();
  220734. }
  220735. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220736. {
  220737. ScopedXLock xlock;
  220738. const int width = image.getWidth();
  220739. const int height = image.getHeight();
  220740. HeapBlock <uint32> colour (width * height);
  220741. int index = 0;
  220742. for (int y = 0; y < height; ++y)
  220743. for (int x = 0; x < width; ++x)
  220744. colour[index++] = image.getPixelAt (x, y).getARGB();
  220745. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220746. 0, reinterpret_cast<char*> (colour.getData()),
  220747. width, height, 32, 0);
  220748. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220749. width, height, 24);
  220750. GC gc = XCreateGC (display, pixmap, 0, 0);
  220751. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  220752. XFreeGC (display, gc);
  220753. return pixmap;
  220754. }
  220755. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  220756. {
  220757. ScopedXLock xlock;
  220758. const int width = image.getWidth();
  220759. const int height = image.getHeight();
  220760. const int stride = (width + 7) >> 3;
  220761. HeapBlock <char> mask;
  220762. mask.calloc (stride * height);
  220763. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  220764. for (int y = 0; y < height; ++y)
  220765. {
  220766. for (int x = 0; x < width; ++x)
  220767. {
  220768. const char bit = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  220769. const int offset = y * stride + (x >> 3);
  220770. if (image.getPixelAt (x, y).getAlpha() >= 128)
  220771. mask[offset] |= bit;
  220772. }
  220773. }
  220774. return XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  220775. mask.getData(), width, height, 1, 0, 1);
  220776. }
  220777. void setIcon (const Image& newIcon)
  220778. {
  220779. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  220780. HeapBlock <unsigned long> data (dataSize);
  220781. int index = 0;
  220782. data[index++] = newIcon.getWidth();
  220783. data[index++] = newIcon.getHeight();
  220784. for (int y = 0; y < newIcon.getHeight(); ++y)
  220785. for (int x = 0; x < newIcon.getWidth(); ++x)
  220786. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  220787. ScopedXLock xlock;
  220788. XChangeProperty (display, windowH,
  220789. XInternAtom (display, "_NET_WM_ICON", False),
  220790. XA_CARDINAL, 32, PropModeReplace,
  220791. reinterpret_cast<unsigned char*> (data.getData()), dataSize);
  220792. deleteIconPixmaps();
  220793. XWMHints* wmHints = XGetWMHints (display, windowH);
  220794. if (wmHints == 0)
  220795. wmHints = XAllocWMHints();
  220796. wmHints->flags |= IconPixmapHint | IconMaskHint;
  220797. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  220798. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  220799. XSetWMHints (display, windowH, wmHints);
  220800. XFree (wmHints);
  220801. XSync (display, False);
  220802. }
  220803. void deleteIconPixmaps()
  220804. {
  220805. ScopedXLock xlock;
  220806. XWMHints* wmHints = XGetWMHints (display, windowH);
  220807. if (wmHints != 0)
  220808. {
  220809. if ((wmHints->flags & IconPixmapHint) != 0)
  220810. {
  220811. wmHints->flags &= ~IconPixmapHint;
  220812. XFreePixmap (display, wmHints->icon_pixmap);
  220813. }
  220814. if ((wmHints->flags & IconMaskHint) != 0)
  220815. {
  220816. wmHints->flags &= ~IconMaskHint;
  220817. XFreePixmap (display, wmHints->icon_mask);
  220818. }
  220819. XSetWMHints (display, windowH, wmHints);
  220820. XFree (wmHints);
  220821. }
  220822. }
  220823. void handleWindowMessage (XEvent* event)
  220824. {
  220825. switch (event->xany.type)
  220826. {
  220827. case 2: // 'KeyPress'
  220828. {
  220829. ScopedXLock xlock;
  220830. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  220831. updateKeyStates (keyEvent->keycode, true);
  220832. char utf8 [64];
  220833. zeromem (utf8, sizeof (utf8));
  220834. KeySym sym;
  220835. {
  220836. const char* oldLocale = ::setlocale (LC_ALL, 0);
  220837. ::setlocale (LC_ALL, "");
  220838. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  220839. ::setlocale (LC_ALL, oldLocale);
  220840. }
  220841. const juce_wchar unicodeChar = String::fromUTF8 (utf8, sizeof (utf8) - 1) [0];
  220842. int keyCode = (int) unicodeChar;
  220843. if (keyCode < 0x20)
  220844. keyCode = XKeycodeToKeysym (display, keyEvent->keycode, currentModifiers.isShiftDown() ? 1 : 0);
  220845. const ModifierKeys oldMods (currentModifiers);
  220846. bool keyPressed = false;
  220847. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  220848. if ((sym & 0xff00) == 0xff00)
  220849. {
  220850. // Translate keypad
  220851. if (sym == XK_KP_Divide)
  220852. keyCode = XK_slash;
  220853. else if (sym == XK_KP_Multiply)
  220854. keyCode = XK_asterisk;
  220855. else if (sym == XK_KP_Subtract)
  220856. keyCode = XK_hyphen;
  220857. else if (sym == XK_KP_Add)
  220858. keyCode = XK_plus;
  220859. else if (sym == XK_KP_Enter)
  220860. keyCode = XK_Return;
  220861. else if (sym == XK_KP_Decimal)
  220862. keyCode = Keys::numLock ? XK_period : XK_Delete;
  220863. else if (sym == XK_KP_0)
  220864. keyCode = Keys::numLock ? XK_0 : XK_Insert;
  220865. else if (sym == XK_KP_1)
  220866. keyCode = Keys::numLock ? XK_1 : XK_End;
  220867. else if (sym == XK_KP_2)
  220868. keyCode = Keys::numLock ? XK_2 : XK_Down;
  220869. else if (sym == XK_KP_3)
  220870. keyCode = Keys::numLock ? XK_3 : XK_Page_Down;
  220871. else if (sym == XK_KP_4)
  220872. keyCode = Keys::numLock ? XK_4 : XK_Left;
  220873. else if (sym == XK_KP_5)
  220874. keyCode = XK_5;
  220875. else if (sym == XK_KP_6)
  220876. keyCode = Keys::numLock ? XK_6 : XK_Right;
  220877. else if (sym == XK_KP_7)
  220878. keyCode = Keys::numLock ? XK_7 : XK_Home;
  220879. else if (sym == XK_KP_8)
  220880. keyCode = Keys::numLock ? XK_8 : XK_Up;
  220881. else if (sym == XK_KP_9)
  220882. keyCode = Keys::numLock ? XK_9 : XK_Page_Up;
  220883. switch (sym)
  220884. {
  220885. case XK_Left:
  220886. case XK_Right:
  220887. case XK_Up:
  220888. case XK_Down:
  220889. case XK_Page_Up:
  220890. case XK_Page_Down:
  220891. case XK_End:
  220892. case XK_Home:
  220893. case XK_Delete:
  220894. case XK_Insert:
  220895. keyPressed = true;
  220896. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220897. break;
  220898. case XK_Tab:
  220899. case XK_Return:
  220900. case XK_Escape:
  220901. case XK_BackSpace:
  220902. keyPressed = true;
  220903. keyCode &= 0xff;
  220904. break;
  220905. default:
  220906. {
  220907. if (sym >= XK_F1 && sym <= XK_F16)
  220908. {
  220909. keyPressed = true;
  220910. keyCode = (sym & 0xff) | Keys::extendedKeyModifier;
  220911. }
  220912. break;
  220913. }
  220914. }
  220915. }
  220916. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  220917. keyPressed = true;
  220918. if (oldMods != currentModifiers)
  220919. handleModifierKeysChange();
  220920. if (keyDownChange)
  220921. handleKeyUpOrDown (true);
  220922. if (keyPressed)
  220923. handleKeyPress (keyCode, unicodeChar);
  220924. break;
  220925. }
  220926. case KeyRelease:
  220927. {
  220928. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  220929. updateKeyStates (keyEvent->keycode, false);
  220930. KeySym sym;
  220931. {
  220932. ScopedXLock xlock;
  220933. sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  220934. }
  220935. const ModifierKeys oldMods (currentModifiers);
  220936. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  220937. if (oldMods != currentModifiers)
  220938. handleModifierKeysChange();
  220939. if (keyDownChange)
  220940. handleKeyUpOrDown (false);
  220941. break;
  220942. }
  220943. case ButtonPress:
  220944. {
  220945. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  220946. updateKeyModifiers (buttonPressEvent->state);
  220947. bool buttonMsg = false;
  220948. const int map = pointerMap [buttonPressEvent->button - Button1];
  220949. if (map == Keys::WheelUp || map == Keys::WheelDown)
  220950. {
  220951. handleMouseWheel (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y),
  220952. getEventTime (buttonPressEvent->time), 0, map == Keys::WheelDown ? -84.0f : 84.0f);
  220953. }
  220954. if (map == Keys::LeftButton)
  220955. {
  220956. currentModifiers = currentModifiers.withFlags (ModifierKeys::leftButtonModifier);
  220957. buttonMsg = true;
  220958. }
  220959. else if (map == Keys::RightButton)
  220960. {
  220961. currentModifiers = currentModifiers.withFlags (ModifierKeys::rightButtonModifier);
  220962. buttonMsg = true;
  220963. }
  220964. else if (map == Keys::MiddleButton)
  220965. {
  220966. currentModifiers = currentModifiers.withFlags (ModifierKeys::middleButtonModifier);
  220967. buttonMsg = true;
  220968. }
  220969. if (buttonMsg)
  220970. {
  220971. toFront (true);
  220972. handleMouseEvent (0, Point<int> (buttonPressEvent->x, buttonPressEvent->y), currentModifiers,
  220973. getEventTime (buttonPressEvent->time));
  220974. }
  220975. clearLastMousePos();
  220976. break;
  220977. }
  220978. case ButtonRelease:
  220979. {
  220980. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  220981. updateKeyModifiers (buttonRelEvent->state);
  220982. const int map = pointerMap [buttonRelEvent->button - Button1];
  220983. if (map == Keys::LeftButton)
  220984. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::leftButtonModifier);
  220985. else if (map == Keys::RightButton)
  220986. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::rightButtonModifier);
  220987. else if (map == Keys::MiddleButton)
  220988. currentModifiers = currentModifiers.withoutFlags (ModifierKeys::middleButtonModifier);
  220989. handleMouseEvent (0, Point<int> (buttonRelEvent->x, buttonRelEvent->y), currentModifiers,
  220990. getEventTime (buttonRelEvent->time));
  220991. clearLastMousePos();
  220992. break;
  220993. }
  220994. case MotionNotify:
  220995. {
  220996. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  220997. updateKeyModifiers (movedEvent->state);
  220998. const Point<int> mousePos (Desktop::getMousePosition());
  220999. if (lastMousePos != mousePos)
  221000. {
  221001. lastMousePos = mousePos;
  221002. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  221003. {
  221004. Window wRoot = 0, wParent = 0;
  221005. {
  221006. ScopedXLock xlock;
  221007. unsigned int numChildren;
  221008. Window* wChild = 0;
  221009. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  221010. }
  221011. if (wParent != 0
  221012. && wParent != windowH
  221013. && wParent != wRoot)
  221014. {
  221015. parentWindow = wParent;
  221016. updateBounds();
  221017. }
  221018. else
  221019. {
  221020. parentWindow = 0;
  221021. }
  221022. }
  221023. handleMouseEvent (0, mousePos - getScreenPosition(), currentModifiers, getEventTime (movedEvent->time));
  221024. }
  221025. break;
  221026. }
  221027. case EnterNotify:
  221028. {
  221029. clearLastMousePos();
  221030. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  221031. if (! currentModifiers.isAnyMouseButtonDown())
  221032. {
  221033. updateKeyModifiers (enterEvent->state);
  221034. handleMouseEvent (0, Point<int> (enterEvent->x, enterEvent->y), currentModifiers, getEventTime (enterEvent->time));
  221035. }
  221036. break;
  221037. }
  221038. case LeaveNotify:
  221039. {
  221040. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  221041. // Suppress the normal leave if we've got a pointer grab, or if
  221042. // it's a bogus one caused by clicking a mouse button when running
  221043. // in a Window manager
  221044. if (((! currentModifiers.isAnyMouseButtonDown()) && leaveEvent->mode == NotifyNormal)
  221045. || leaveEvent->mode == NotifyUngrab)
  221046. {
  221047. updateKeyModifiers (leaveEvent->state);
  221048. handleMouseEvent (0, Point<int> (leaveEvent->x, leaveEvent->y), currentModifiers, getEventTime (leaveEvent->time));
  221049. }
  221050. break;
  221051. }
  221052. case FocusIn:
  221053. {
  221054. isActiveApplication = true;
  221055. if (isFocused())
  221056. handleFocusGain();
  221057. break;
  221058. }
  221059. case FocusOut:
  221060. {
  221061. isActiveApplication = false;
  221062. if (! isFocused())
  221063. handleFocusLoss();
  221064. break;
  221065. }
  221066. case Expose:
  221067. {
  221068. // Batch together all pending expose events
  221069. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  221070. XEvent nextEvent;
  221071. ScopedXLock xlock;
  221072. if (exposeEvent->window != windowH)
  221073. {
  221074. Window child;
  221075. XTranslateCoordinates (display, exposeEvent->window, windowH,
  221076. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  221077. &child);
  221078. }
  221079. repaint (Rectangle<int> (exposeEvent->x, exposeEvent->y,
  221080. exposeEvent->width, exposeEvent->height));
  221081. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  221082. {
  221083. XPeekEvent (display, (XEvent*) &nextEvent);
  221084. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  221085. break;
  221086. XNextEvent (display, (XEvent*) &nextEvent);
  221087. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  221088. repaint (Rectangle<int> (nextExposeEvent->x, nextExposeEvent->y,
  221089. nextExposeEvent->width, nextExposeEvent->height));
  221090. }
  221091. break;
  221092. }
  221093. case CirculateNotify:
  221094. case CreateNotify:
  221095. case DestroyNotify:
  221096. // Think we can ignore these
  221097. break;
  221098. case ConfigureNotify:
  221099. {
  221100. updateBounds();
  221101. updateBorderSize();
  221102. handleMovedOrResized();
  221103. // if the native title bar is dragged, need to tell any active menus, etc.
  221104. if ((styleFlags & windowHasTitleBar) != 0
  221105. && component->isCurrentlyBlockedByAnotherModalComponent())
  221106. {
  221107. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  221108. if (currentModalComp != 0)
  221109. currentModalComp->inputAttemptWhenModal();
  221110. }
  221111. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  221112. if (confEvent->window == windowH
  221113. && confEvent->above != 0
  221114. && isFrontWindow())
  221115. {
  221116. handleBroughtToFront();
  221117. }
  221118. break;
  221119. }
  221120. case ReparentNotify:
  221121. {
  221122. parentWindow = 0;
  221123. Window wRoot = 0;
  221124. Window* wChild = 0;
  221125. unsigned int numChildren;
  221126. {
  221127. ScopedXLock xlock;
  221128. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  221129. }
  221130. if (parentWindow == windowH || parentWindow == wRoot)
  221131. parentWindow = 0;
  221132. updateBounds();
  221133. updateBorderSize();
  221134. handleMovedOrResized();
  221135. break;
  221136. }
  221137. case GravityNotify:
  221138. {
  221139. updateBounds();
  221140. updateBorderSize();
  221141. handleMovedOrResized();
  221142. break;
  221143. }
  221144. case MapNotify:
  221145. mapped = true;
  221146. handleBroughtToFront();
  221147. break;
  221148. case UnmapNotify:
  221149. mapped = false;
  221150. break;
  221151. case MappingNotify:
  221152. {
  221153. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  221154. if (mappingEvent->request != MappingPointer)
  221155. {
  221156. // Deal with modifier/keyboard mapping
  221157. ScopedXLock xlock;
  221158. XRefreshKeyboardMapping (mappingEvent);
  221159. updateModifierMappings();
  221160. }
  221161. break;
  221162. }
  221163. case ClientMessage:
  221164. {
  221165. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  221166. if (clientMsg->message_type == Atoms::Protocols && clientMsg->format == 32)
  221167. {
  221168. const Atom atom = (Atom) clientMsg->data.l[0];
  221169. if (atom == Atoms::ProtocolList [Atoms::PING])
  221170. {
  221171. Window root = RootWindow (display, DefaultScreen (display));
  221172. event->xclient.window = root;
  221173. XSendEvent (display, root, False, NoEventMask, event);
  221174. XFlush (display);
  221175. }
  221176. else if (atom == Atoms::ProtocolList [Atoms::TAKE_FOCUS])
  221177. {
  221178. XWindowAttributes atts;
  221179. ScopedXLock xlock;
  221180. if (clientMsg->window != 0
  221181. && XGetWindowAttributes (display, clientMsg->window, &atts))
  221182. {
  221183. if (atts.map_state == IsViewable)
  221184. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  221185. }
  221186. }
  221187. else if (atom == Atoms::ProtocolList [Atoms::DELETE_WINDOW])
  221188. {
  221189. handleUserClosingWindow();
  221190. }
  221191. }
  221192. else if (clientMsg->message_type == Atoms::XdndEnter)
  221193. {
  221194. handleDragAndDropEnter (clientMsg);
  221195. }
  221196. else if (clientMsg->message_type == Atoms::XdndLeave)
  221197. {
  221198. resetDragAndDrop();
  221199. }
  221200. else if (clientMsg->message_type == Atoms::XdndPosition)
  221201. {
  221202. handleDragAndDropPosition (clientMsg);
  221203. }
  221204. else if (clientMsg->message_type == Atoms::XdndDrop)
  221205. {
  221206. handleDragAndDropDrop (clientMsg);
  221207. }
  221208. else if (clientMsg->message_type == Atoms::XdndStatus)
  221209. {
  221210. handleDragAndDropStatus (clientMsg);
  221211. }
  221212. else if (clientMsg->message_type == Atoms::XdndFinished)
  221213. {
  221214. resetDragAndDrop();
  221215. }
  221216. break;
  221217. }
  221218. case SelectionNotify:
  221219. handleDragAndDropSelection (event);
  221220. break;
  221221. case SelectionClear:
  221222. case SelectionRequest:
  221223. break;
  221224. default:
  221225. #if JUCE_USE_XSHM
  221226. {
  221227. ScopedXLock xlock;
  221228. if (event->xany.type == XShmGetEventBase (display))
  221229. repainter->notifyPaintCompleted();
  221230. }
  221231. #endif
  221232. break;
  221233. }
  221234. }
  221235. void showMouseCursor (Cursor cursor) throw()
  221236. {
  221237. ScopedXLock xlock;
  221238. XDefineCursor (display, windowH, cursor);
  221239. }
  221240. void setTaskBarIcon (const Image& image)
  221241. {
  221242. ScopedXLock xlock;
  221243. taskbarImage = image;
  221244. Screen* const screen = XDefaultScreenOfDisplay (display);
  221245. const int screenNumber = XScreenNumberOfScreen (screen);
  221246. String screenAtom ("_NET_SYSTEM_TRAY_S");
  221247. screenAtom << screenNumber;
  221248. Atom selectionAtom = XInternAtom (display, screenAtom.toUTF8(), false);
  221249. XGrabServer (display);
  221250. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  221251. if (managerWin != None)
  221252. XSelectInput (display, managerWin, StructureNotifyMask);
  221253. XUngrabServer (display);
  221254. XFlush (display);
  221255. if (managerWin != None)
  221256. {
  221257. XEvent ev;
  221258. zerostruct (ev);
  221259. ev.xclient.type = ClientMessage;
  221260. ev.xclient.window = managerWin;
  221261. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  221262. ev.xclient.format = 32;
  221263. ev.xclient.data.l[0] = CurrentTime;
  221264. ev.xclient.data.l[1] = 0 /*SYSTEM_TRAY_REQUEST_DOCK*/;
  221265. ev.xclient.data.l[2] = windowH;
  221266. ev.xclient.data.l[3] = 0;
  221267. ev.xclient.data.l[4] = 0;
  221268. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  221269. XSync (display, False);
  221270. }
  221271. // For older KDE's ...
  221272. long atomData = 1;
  221273. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  221274. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  221275. // For more recent KDE's...
  221276. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  221277. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  221278. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  221279. XSizeHints* hints = XAllocSizeHints();
  221280. hints->flags = PMinSize;
  221281. hints->min_width = 22;
  221282. hints->min_height = 22;
  221283. XSetWMNormalHints (display, windowH, hints);
  221284. XFree (hints);
  221285. }
  221286. const Image& getTaskbarIcon() const throw() { return taskbarImage; }
  221287. juce_UseDebuggingNewOperator
  221288. bool dontRepaint;
  221289. static ModifierKeys currentModifiers;
  221290. static bool isActiveApplication;
  221291. private:
  221292. class LinuxRepaintManager : public Timer
  221293. {
  221294. public:
  221295. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  221296. : peer (peer_),
  221297. lastTimeImageUsed (0)
  221298. {
  221299. #if JUCE_USE_XSHM
  221300. shmCompletedDrawing = true;
  221301. useARGBImagesForRendering = XSHMHelpers::isShmAvailable();
  221302. if (useARGBImagesForRendering)
  221303. {
  221304. ScopedXLock xlock;
  221305. XShmSegmentInfo segmentinfo;
  221306. XImage* const testImage
  221307. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  221308. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  221309. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  221310. XDestroyImage (testImage);
  221311. }
  221312. #endif
  221313. }
  221314. ~LinuxRepaintManager()
  221315. {
  221316. }
  221317. void timerCallback()
  221318. {
  221319. #if JUCE_USE_XSHM
  221320. if (! shmCompletedDrawing)
  221321. return;
  221322. #endif
  221323. if (! regionsNeedingRepaint.isEmpty())
  221324. {
  221325. stopTimer();
  221326. performAnyPendingRepaintsNow();
  221327. }
  221328. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  221329. {
  221330. stopTimer();
  221331. image = Image::null;
  221332. }
  221333. }
  221334. void repaint (const Rectangle<int>& area)
  221335. {
  221336. if (! isTimerRunning())
  221337. startTimer (repaintTimerPeriod);
  221338. regionsNeedingRepaint.add (area);
  221339. }
  221340. void performAnyPendingRepaintsNow()
  221341. {
  221342. #if JUCE_USE_XSHM
  221343. if (! shmCompletedDrawing)
  221344. {
  221345. startTimer (repaintTimerPeriod);
  221346. return;
  221347. }
  221348. #endif
  221349. peer->clearMaskedRegion();
  221350. RectangleList originalRepaintRegion (regionsNeedingRepaint);
  221351. regionsNeedingRepaint.clear();
  221352. const Rectangle<int> totalArea (originalRepaintRegion.getBounds());
  221353. if (! totalArea.isEmpty())
  221354. {
  221355. if (image.isNull() || image.getWidth() < totalArea.getWidth()
  221356. || image.getHeight() < totalArea.getHeight())
  221357. {
  221358. #if JUCE_USE_XSHM
  221359. image = Image (new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  221360. : Image::RGB,
  221361. #else
  221362. image = Image (new XBitmapImage (Image::RGB,
  221363. #endif
  221364. (totalArea.getWidth() + 31) & ~31,
  221365. (totalArea.getHeight() + 31) & ~31,
  221366. false, peer->depth, peer->visual));
  221367. }
  221368. startTimer (repaintTimerPeriod);
  221369. RectangleList adjustedList (originalRepaintRegion);
  221370. adjustedList.offsetAll (-totalArea.getX(), -totalArea.getY());
  221371. LowLevelGraphicsSoftwareRenderer context (image, -totalArea.getX(), -totalArea.getY(), adjustedList);
  221372. if (peer->depth == 32)
  221373. {
  221374. RectangleList::Iterator i (originalRepaintRegion);
  221375. while (i.next())
  221376. image.clear (*i.getRectangle() - totalArea.getPosition());
  221377. }
  221378. peer->handlePaint (context);
  221379. if (! peer->maskedRegion.isEmpty())
  221380. originalRepaintRegion.subtract (peer->maskedRegion);
  221381. for (RectangleList::Iterator i (originalRepaintRegion); i.next();)
  221382. {
  221383. #if JUCE_USE_XSHM
  221384. shmCompletedDrawing = false;
  221385. #endif
  221386. const Rectangle<int>& r = *i.getRectangle();
  221387. static_cast<XBitmapImage*> (image.getSharedImage())
  221388. ->blitToWindow (peer->windowH,
  221389. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  221390. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  221391. }
  221392. }
  221393. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  221394. startTimer (repaintTimerPeriod);
  221395. }
  221396. #if JUCE_USE_XSHM
  221397. void notifyPaintCompleted() { shmCompletedDrawing = true; }
  221398. #endif
  221399. private:
  221400. enum { repaintTimerPeriod = 1000 / 100 };
  221401. LinuxComponentPeer* const peer;
  221402. Image image;
  221403. uint32 lastTimeImageUsed;
  221404. RectangleList regionsNeedingRepaint;
  221405. #if JUCE_USE_XSHM
  221406. bool useARGBImagesForRendering, shmCompletedDrawing;
  221407. #endif
  221408. LinuxRepaintManager (const LinuxRepaintManager&);
  221409. LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  221410. };
  221411. ScopedPointer <LinuxRepaintManager> repainter;
  221412. friend class LinuxRepaintManager;
  221413. Window windowH, parentWindow;
  221414. int wx, wy, ww, wh;
  221415. Image taskbarImage;
  221416. bool fullScreen, mapped;
  221417. Visual* visual;
  221418. int depth;
  221419. BorderSize windowBorder;
  221420. struct MotifWmHints
  221421. {
  221422. unsigned long flags;
  221423. unsigned long functions;
  221424. unsigned long decorations;
  221425. long input_mode;
  221426. unsigned long status;
  221427. };
  221428. static void updateKeyStates (const int keycode, const bool press) throw()
  221429. {
  221430. const int keybyte = keycode >> 3;
  221431. const int keybit = (1 << (keycode & 7));
  221432. if (press)
  221433. Keys::keyStates [keybyte] |= keybit;
  221434. else
  221435. Keys::keyStates [keybyte] &= ~keybit;
  221436. }
  221437. static void updateKeyModifiers (const int status) throw()
  221438. {
  221439. int keyMods = 0;
  221440. if (status & ShiftMask) keyMods |= ModifierKeys::shiftModifier;
  221441. if (status & ControlMask) keyMods |= ModifierKeys::ctrlModifier;
  221442. if (status & Keys::AltMask) keyMods |= ModifierKeys::altModifier;
  221443. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (keyMods);
  221444. Keys::numLock = ((status & Keys::NumLockMask) != 0);
  221445. Keys::capsLock = ((status & LockMask) != 0);
  221446. }
  221447. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  221448. {
  221449. int modifier = 0;
  221450. bool isModifier = true;
  221451. switch (sym)
  221452. {
  221453. case XK_Shift_L:
  221454. case XK_Shift_R:
  221455. modifier = ModifierKeys::shiftModifier;
  221456. break;
  221457. case XK_Control_L:
  221458. case XK_Control_R:
  221459. modifier = ModifierKeys::ctrlModifier;
  221460. break;
  221461. case XK_Alt_L:
  221462. case XK_Alt_R:
  221463. modifier = ModifierKeys::altModifier;
  221464. break;
  221465. case XK_Num_Lock:
  221466. if (press)
  221467. Keys::numLock = ! Keys::numLock;
  221468. break;
  221469. case XK_Caps_Lock:
  221470. if (press)
  221471. Keys::capsLock = ! Keys::capsLock;
  221472. break;
  221473. case XK_Scroll_Lock:
  221474. break;
  221475. default:
  221476. isModifier = false;
  221477. break;
  221478. }
  221479. if (modifier != 0)
  221480. {
  221481. if (press)
  221482. currentModifiers = currentModifiers.withFlags (modifier);
  221483. else
  221484. currentModifiers = currentModifiers.withoutFlags (modifier);
  221485. }
  221486. return isModifier;
  221487. }
  221488. // Alt and Num lock are not defined by standard X
  221489. // modifier constants: check what they're mapped to
  221490. static void updateModifierMappings() throw()
  221491. {
  221492. ScopedXLock xlock;
  221493. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  221494. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  221495. Keys::AltMask = 0;
  221496. Keys::NumLockMask = 0;
  221497. XModifierKeymap* mapping = XGetModifierMapping (display);
  221498. if (mapping)
  221499. {
  221500. for (int i = 0; i < 8; i++)
  221501. {
  221502. if (mapping->modifiermap [i << 1] == altLeftCode)
  221503. Keys::AltMask = 1 << i;
  221504. else if (mapping->modifiermap [i << 1] == numLockCode)
  221505. Keys::NumLockMask = 1 << i;
  221506. }
  221507. XFreeModifiermap (mapping);
  221508. }
  221509. }
  221510. void removeWindowDecorations (Window wndH)
  221511. {
  221512. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221513. if (hints != None)
  221514. {
  221515. MotifWmHints motifHints;
  221516. zerostruct (motifHints);
  221517. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  221518. motifHints.decorations = 0;
  221519. ScopedXLock xlock;
  221520. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221521. (unsigned char*) &motifHints, 4);
  221522. }
  221523. hints = XInternAtom (display, "_WIN_HINTS", True);
  221524. if (hints != None)
  221525. {
  221526. long gnomeHints = 0;
  221527. ScopedXLock xlock;
  221528. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221529. (unsigned char*) &gnomeHints, 1);
  221530. }
  221531. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  221532. if (hints != None)
  221533. {
  221534. long kwmHints = 2; /*KDE_tinyDecoration*/
  221535. ScopedXLock xlock;
  221536. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  221537. (unsigned char*) &kwmHints, 1);
  221538. }
  221539. }
  221540. void addWindowButtons (Window wndH)
  221541. {
  221542. ScopedXLock xlock;
  221543. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  221544. if (hints != None)
  221545. {
  221546. MotifWmHints motifHints;
  221547. zerostruct (motifHints);
  221548. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  221549. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  221550. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  221551. if ((styleFlags & windowHasCloseButton) != 0)
  221552. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  221553. if ((styleFlags & windowHasMinimiseButton) != 0)
  221554. {
  221555. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  221556. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  221557. }
  221558. if ((styleFlags & windowHasMaximiseButton) != 0)
  221559. {
  221560. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  221561. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  221562. }
  221563. if ((styleFlags & windowIsResizable) != 0)
  221564. {
  221565. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  221566. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  221567. }
  221568. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  221569. }
  221570. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  221571. if (hints != None)
  221572. {
  221573. int netHints [6];
  221574. int num = 0;
  221575. if ((styleFlags & windowIsResizable) != 0)
  221576. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", True);
  221577. if ((styleFlags & windowHasMaximiseButton) != 0)
  221578. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", True);
  221579. if ((styleFlags & windowHasMinimiseButton) != 0)
  221580. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", True);
  221581. if ((styleFlags & windowHasCloseButton) != 0)
  221582. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", True);
  221583. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace, (unsigned char*) &netHints, num);
  221584. }
  221585. }
  221586. void setWindowType()
  221587. {
  221588. int netHints [2];
  221589. int numHints = 0;
  221590. if ((styleFlags & windowIsTemporary) != 0
  221591. || ((styleFlags & windowHasDropShadow) == 0 && Desktop::canUseSemiTransparentWindows()))
  221592. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_COMBO", True);
  221593. else
  221594. netHints [numHints++] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  221595. netHints[numHints++] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  221596. XChangeProperty (display, windowH, Atoms::WindowType, XA_ATOM, 32, PropModeReplace,
  221597. (unsigned char*) &netHints, numHints);
  221598. numHints = 0;
  221599. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  221600. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_SKIP_TASKBAR", True);
  221601. if (component->isAlwaysOnTop())
  221602. netHints [numHints++] = XInternAtom (display, "_NET_WM_STATE_ABOVE", True);
  221603. if (numHints > 0)
  221604. XChangeProperty (display, windowH, Atoms::WindowState, XA_ATOM, 32, PropModeReplace,
  221605. (unsigned char*) &netHints, numHints);
  221606. }
  221607. void createWindow()
  221608. {
  221609. ScopedXLock xlock;
  221610. Atoms::initialiseAtoms();
  221611. resetDragAndDrop();
  221612. // Get defaults for various properties
  221613. const int screen = DefaultScreen (display);
  221614. Window root = RootWindow (display, screen);
  221615. // Try to obtain a 32-bit visual or fallback to 24 or 16
  221616. visual = Visuals::findVisualFormat ((styleFlags & windowIsSemiTransparent) ? 32 : 24, depth);
  221617. if (visual == 0)
  221618. {
  221619. Logger::outputDebugString ("ERROR: System doesn't support 32, 24 or 16 bit RGB display.\n");
  221620. Process::terminate();
  221621. }
  221622. // Create and install a colormap suitable fr our visual
  221623. Colormap colormap = XCreateColormap (display, root, visual, AllocNone);
  221624. XInstallColormap (display, colormap);
  221625. // Set up the window attributes
  221626. XSetWindowAttributes swa;
  221627. swa.border_pixel = 0;
  221628. swa.background_pixmap = None;
  221629. swa.colormap = colormap;
  221630. swa.event_mask = getAllEventsMask();
  221631. windowH = XCreateWindow (display, root,
  221632. 0, 0, 1, 1,
  221633. 0, depth, InputOutput, visual,
  221634. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask,
  221635. &swa);
  221636. XGrabButton (display, AnyButton, AnyModifier, windowH, False,
  221637. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  221638. GrabModeAsync, GrabModeAsync, None, None);
  221639. // Set the window context to identify the window handle object
  221640. if (XSaveContext (display, (XID) windowH, windowHandleXContext, (XPointer) this))
  221641. {
  221642. // Failed
  221643. jassertfalse;
  221644. Logger::outputDebugString ("Failed to create context information for window.\n");
  221645. XDestroyWindow (display, windowH);
  221646. windowH = 0;
  221647. return;
  221648. }
  221649. // Set window manager hints
  221650. XWMHints* wmHints = XAllocWMHints();
  221651. wmHints->flags = InputHint | StateHint;
  221652. wmHints->input = True; // Locally active input model
  221653. wmHints->initial_state = NormalState;
  221654. XSetWMHints (display, windowH, wmHints);
  221655. XFree (wmHints);
  221656. // Set the window type
  221657. setWindowType();
  221658. // Define decoration
  221659. if ((styleFlags & windowHasTitleBar) == 0)
  221660. removeWindowDecorations (windowH);
  221661. else
  221662. addWindowButtons (windowH);
  221663. // Set window name
  221664. setWindowTitle (windowH, getComponent()->getName());
  221665. // Associate the PID, allowing to be shut down when something goes wrong
  221666. unsigned long pid = getpid();
  221667. XChangeProperty (display, windowH, Atoms::Pid, XA_CARDINAL, 32, PropModeReplace,
  221668. (unsigned char*) &pid, 1);
  221669. // Set window manager protocols
  221670. XChangeProperty (display, windowH, Atoms::Protocols, XA_ATOM, 32, PropModeReplace,
  221671. (unsigned char*) Atoms::ProtocolList, 2);
  221672. // Set drag and drop flags
  221673. XChangeProperty (display, windowH, Atoms::XdndTypeList, XA_ATOM, 32, PropModeReplace,
  221674. (const unsigned char*) Atoms::allowedMimeTypes, numElementsInArray (Atoms::allowedMimeTypes));
  221675. XChangeProperty (display, windowH, Atoms::XdndActionList, XA_ATOM, 32, PropModeReplace,
  221676. (const unsigned char*) Atoms::allowedActions, numElementsInArray (Atoms::allowedActions));
  221677. XChangeProperty (display, windowH, Atoms::XdndActionDescription, XA_STRING, 8, PropModeReplace,
  221678. (const unsigned char*) "", 0);
  221679. unsigned long dndVersion = Atoms::DndVersion;
  221680. XChangeProperty (display, windowH, Atoms::XdndAware, XA_ATOM, 32, PropModeReplace,
  221681. (const unsigned char*) &dndVersion, 1);
  221682. // Initialise the pointer and keyboard mapping
  221683. // This is not the same as the logical pointer mapping the X server uses:
  221684. // we don't mess with this.
  221685. static bool mappingInitialised = false;
  221686. if (! mappingInitialised)
  221687. {
  221688. mappingInitialised = true;
  221689. const int numButtons = XGetPointerMapping (display, 0, 0);
  221690. if (numButtons == 2)
  221691. {
  221692. pointerMap[0] = Keys::LeftButton;
  221693. pointerMap[1] = Keys::RightButton;
  221694. pointerMap[2] = pointerMap[3] = pointerMap[4] = Keys::NoButton;
  221695. }
  221696. else if (numButtons >= 3)
  221697. {
  221698. pointerMap[0] = Keys::LeftButton;
  221699. pointerMap[1] = Keys::MiddleButton;
  221700. pointerMap[2] = Keys::RightButton;
  221701. if (numButtons >= 5)
  221702. {
  221703. pointerMap[3] = Keys::WheelUp;
  221704. pointerMap[4] = Keys::WheelDown;
  221705. }
  221706. }
  221707. updateModifierMappings();
  221708. }
  221709. }
  221710. void destroyWindow()
  221711. {
  221712. ScopedXLock xlock;
  221713. XPointer handlePointer;
  221714. if (! XFindContext (display, (XID) windowH, windowHandleXContext, &handlePointer))
  221715. XDeleteContext (display, (XID) windowH, windowHandleXContext);
  221716. XDestroyWindow (display, windowH);
  221717. // Wait for it to complete and then remove any events for this
  221718. // window from the event queue.
  221719. XSync (display, false);
  221720. XEvent event;
  221721. while (XCheckWindowEvent (display, windowH, getAllEventsMask(), &event) == True)
  221722. {}
  221723. }
  221724. static int getAllEventsMask() throw()
  221725. {
  221726. return NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  221727. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  221728. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  221729. }
  221730. static int64 getEventTime (::Time t)
  221731. {
  221732. static int64 eventTimeOffset = 0x12345678;
  221733. const int64 thisMessageTime = t;
  221734. if (eventTimeOffset == 0x12345678)
  221735. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  221736. return eventTimeOffset + thisMessageTime;
  221737. }
  221738. static void setWindowTitle (Window xwin, const String& title)
  221739. {
  221740. XTextProperty nameProperty;
  221741. char* strings[] = { const_cast <char*> (title.toUTF8()) };
  221742. ScopedXLock xlock;
  221743. if (XStringListToTextProperty (strings, 1, &nameProperty))
  221744. {
  221745. XSetWMName (display, xwin, &nameProperty);
  221746. XSetWMIconName (display, xwin, &nameProperty);
  221747. XFree (nameProperty.value);
  221748. }
  221749. }
  221750. void updateBorderSize()
  221751. {
  221752. if ((styleFlags & windowHasTitleBar) == 0)
  221753. {
  221754. windowBorder = BorderSize (0);
  221755. }
  221756. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  221757. {
  221758. ScopedXLock xlock;
  221759. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  221760. if (hints != None)
  221761. {
  221762. unsigned char* data = 0;
  221763. unsigned long nitems, bytesLeft;
  221764. Atom actualType;
  221765. int actualFormat;
  221766. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  221767. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  221768. &data) == Success)
  221769. {
  221770. const unsigned long* const sizes = (const unsigned long*) data;
  221771. if (actualFormat == 32)
  221772. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  221773. (int) sizes[3], (int) sizes[1]);
  221774. XFree (data);
  221775. }
  221776. }
  221777. }
  221778. }
  221779. void updateBounds()
  221780. {
  221781. jassert (windowH != 0);
  221782. if (windowH != 0)
  221783. {
  221784. Window root, child;
  221785. unsigned int bw, depth;
  221786. ScopedXLock xlock;
  221787. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221788. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  221789. &bw, &depth))
  221790. {
  221791. wx = wy = ww = wh = 0;
  221792. }
  221793. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  221794. {
  221795. wx = wy = 0;
  221796. }
  221797. }
  221798. }
  221799. void resetDragAndDrop()
  221800. {
  221801. dragAndDropFiles.clear();
  221802. lastDropPos = Point<int> (-1, -1);
  221803. dragAndDropCurrentMimeType = 0;
  221804. dragAndDropSourceWindow = 0;
  221805. srcMimeTypeAtomList.clear();
  221806. }
  221807. void sendDragAndDropMessage (XClientMessageEvent& msg)
  221808. {
  221809. msg.type = ClientMessage;
  221810. msg.display = display;
  221811. msg.window = dragAndDropSourceWindow;
  221812. msg.format = 32;
  221813. msg.data.l[0] = windowH;
  221814. ScopedXLock xlock;
  221815. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  221816. }
  221817. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  221818. {
  221819. XClientMessageEvent msg;
  221820. zerostruct (msg);
  221821. msg.message_type = Atoms::XdndStatus;
  221822. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  221823. msg.data.l[4] = dropAction;
  221824. sendDragAndDropMessage (msg);
  221825. }
  221826. void sendDragAndDropLeave()
  221827. {
  221828. XClientMessageEvent msg;
  221829. zerostruct (msg);
  221830. msg.message_type = Atoms::XdndLeave;
  221831. sendDragAndDropMessage (msg);
  221832. }
  221833. void sendDragAndDropFinish()
  221834. {
  221835. XClientMessageEvent msg;
  221836. zerostruct (msg);
  221837. msg.message_type = Atoms::XdndFinished;
  221838. sendDragAndDropMessage (msg);
  221839. }
  221840. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  221841. {
  221842. if ((clientMsg->data.l[1] & 1) == 0)
  221843. {
  221844. sendDragAndDropLeave();
  221845. if (dragAndDropFiles.size() > 0)
  221846. handleFileDragExit (dragAndDropFiles);
  221847. dragAndDropFiles.clear();
  221848. }
  221849. }
  221850. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  221851. {
  221852. if (dragAndDropSourceWindow == 0)
  221853. return;
  221854. dragAndDropSourceWindow = clientMsg->data.l[0];
  221855. Point<int> dropPos ((int) clientMsg->data.l[2] >> 16,
  221856. (int) clientMsg->data.l[2] & 0xffff);
  221857. dropPos -= getScreenPosition();
  221858. if (lastDropPos != dropPos)
  221859. {
  221860. lastDropPos = dropPos;
  221861. dragAndDropTimestamp = clientMsg->data.l[3];
  221862. Atom targetAction = Atoms::XdndActionCopy;
  221863. for (int i = numElementsInArray (Atoms::allowedActions); --i >= 0;)
  221864. {
  221865. if ((Atom) clientMsg->data.l[4] == Atoms::allowedActions[i])
  221866. {
  221867. targetAction = Atoms::allowedActions[i];
  221868. break;
  221869. }
  221870. }
  221871. sendDragAndDropStatus (true, targetAction);
  221872. if (dragAndDropFiles.size() == 0)
  221873. updateDraggedFileList (clientMsg);
  221874. if (dragAndDropFiles.size() > 0)
  221875. handleFileDragMove (dragAndDropFiles, dropPos);
  221876. }
  221877. }
  221878. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  221879. {
  221880. if (dragAndDropFiles.size() == 0)
  221881. updateDraggedFileList (clientMsg);
  221882. const StringArray files (dragAndDropFiles);
  221883. const Point<int> lastPos (lastDropPos);
  221884. sendDragAndDropFinish();
  221885. resetDragAndDrop();
  221886. if (files.size() > 0)
  221887. handleFileDragDrop (files, lastPos);
  221888. }
  221889. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  221890. {
  221891. dragAndDropFiles.clear();
  221892. srcMimeTypeAtomList.clear();
  221893. dragAndDropCurrentMimeType = 0;
  221894. const unsigned long dndCurrentVersion = static_cast <unsigned long> (clientMsg->data.l[1] & 0xff000000) >> 24;
  221895. if (dndCurrentVersion < 3 || dndCurrentVersion > Atoms::DndVersion)
  221896. {
  221897. dragAndDropSourceWindow = 0;
  221898. return;
  221899. }
  221900. dragAndDropSourceWindow = clientMsg->data.l[0];
  221901. if ((clientMsg->data.l[1] & 1) != 0)
  221902. {
  221903. Atom actual;
  221904. int format;
  221905. unsigned long count = 0, remaining = 0;
  221906. unsigned char* data = 0;
  221907. ScopedXLock xlock;
  221908. XGetWindowProperty (display, dragAndDropSourceWindow, Atoms::XdndTypeList,
  221909. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  221910. &count, &remaining, &data);
  221911. if (data != 0)
  221912. {
  221913. if (actual == XA_ATOM && format == 32 && count != 0)
  221914. {
  221915. const unsigned long* const types = (const unsigned long*) data;
  221916. for (unsigned int i = 0; i < count; ++i)
  221917. if (types[i] != None)
  221918. srcMimeTypeAtomList.add (types[i]);
  221919. }
  221920. XFree (data);
  221921. }
  221922. }
  221923. if (srcMimeTypeAtomList.size() == 0)
  221924. {
  221925. for (int i = 2; i < 5; ++i)
  221926. if (clientMsg->data.l[i] != None)
  221927. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  221928. if (srcMimeTypeAtomList.size() == 0)
  221929. {
  221930. dragAndDropSourceWindow = 0;
  221931. return;
  221932. }
  221933. }
  221934. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  221935. for (int j = 0; j < numElementsInArray (Atoms::allowedMimeTypes); ++j)
  221936. if (srcMimeTypeAtomList[i] == Atoms::allowedMimeTypes[j])
  221937. dragAndDropCurrentMimeType = Atoms::allowedMimeTypes[j];
  221938. handleDragAndDropPosition (clientMsg);
  221939. }
  221940. void handleDragAndDropSelection (const XEvent* const evt)
  221941. {
  221942. dragAndDropFiles.clear();
  221943. if (evt->xselection.property != 0)
  221944. {
  221945. StringArray lines;
  221946. {
  221947. MemoryBlock dropData;
  221948. for (;;)
  221949. {
  221950. Atom actual;
  221951. uint8* data = 0;
  221952. unsigned long count = 0, remaining = 0;
  221953. int format = 0;
  221954. ScopedXLock xlock;
  221955. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  221956. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  221957. &format, &count, &remaining, &data) == Success)
  221958. {
  221959. dropData.append (data, count * format / 8);
  221960. XFree (data);
  221961. if (remaining == 0)
  221962. break;
  221963. }
  221964. else
  221965. {
  221966. XFree (data);
  221967. break;
  221968. }
  221969. }
  221970. lines.addLines (dropData.toString());
  221971. }
  221972. for (int i = 0; i < lines.size(); ++i)
  221973. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf ("file://", false, true)));
  221974. dragAndDropFiles.trim();
  221975. dragAndDropFiles.removeEmptyStrings();
  221976. }
  221977. }
  221978. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  221979. {
  221980. dragAndDropFiles.clear();
  221981. if (dragAndDropSourceWindow != None
  221982. && dragAndDropCurrentMimeType != 0)
  221983. {
  221984. dragAndDropTimestamp = clientMsg->data.l[2];
  221985. ScopedXLock xlock;
  221986. XConvertSelection (display,
  221987. Atoms::XdndSelection,
  221988. dragAndDropCurrentMimeType,
  221989. XInternAtom (display, "JXSelectionWindowProperty", 0),
  221990. windowH,
  221991. dragAndDropTimestamp);
  221992. }
  221993. }
  221994. StringArray dragAndDropFiles;
  221995. int dragAndDropTimestamp;
  221996. Point<int> lastDropPos;
  221997. Atom dragAndDropCurrentMimeType;
  221998. Window dragAndDropSourceWindow;
  221999. Array <Atom> srcMimeTypeAtomList;
  222000. static int pointerMap[5];
  222001. static Point<int> lastMousePos;
  222002. static void clearLastMousePos() throw()
  222003. {
  222004. lastMousePos = Point<int> (0x100000, 0x100000);
  222005. }
  222006. };
  222007. ModifierKeys LinuxComponentPeer::currentModifiers;
  222008. bool LinuxComponentPeer::isActiveApplication = false;
  222009. int LinuxComponentPeer::pointerMap[5];
  222010. Point<int> LinuxComponentPeer::lastMousePos;
  222011. bool Process::isForegroundProcess()
  222012. {
  222013. return LinuxComponentPeer::isActiveApplication;
  222014. }
  222015. void ModifierKeys::updateCurrentModifiers() throw()
  222016. {
  222017. currentModifiers = LinuxComponentPeer::currentModifiers;
  222018. }
  222019. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  222020. {
  222021. Window root, child;
  222022. int x, y, winx, winy;
  222023. unsigned int mask;
  222024. int mouseMods = 0;
  222025. ScopedXLock xlock;
  222026. if (XQueryPointer (display, RootWindow (display, DefaultScreen (display)),
  222027. &root, &child, &x, &y, &winx, &winy, &mask) != False)
  222028. {
  222029. if ((mask & Button1Mask) != 0) mouseMods |= ModifierKeys::leftButtonModifier;
  222030. if ((mask & Button2Mask) != 0) mouseMods |= ModifierKeys::middleButtonModifier;
  222031. if ((mask & Button3Mask) != 0) mouseMods |= ModifierKeys::rightButtonModifier;
  222032. }
  222033. LinuxComponentPeer::currentModifiers = LinuxComponentPeer::currentModifiers.withoutMouseButtons().withFlags (mouseMods);
  222034. return LinuxComponentPeer::currentModifiers;
  222035. }
  222036. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  222037. {
  222038. if (enableOrDisable)
  222039. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  222040. }
  222041. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  222042. {
  222043. return new LinuxComponentPeer (this, styleFlags);
  222044. }
  222045. // (this callback is hooked up in the messaging code)
  222046. void juce_windowMessageReceive (XEvent* event)
  222047. {
  222048. if (event->xany.window != None)
  222049. {
  222050. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  222051. if (ComponentPeer::isValidPeer (peer))
  222052. peer->handleWindowMessage (event);
  222053. }
  222054. else
  222055. {
  222056. switch (event->xany.type)
  222057. {
  222058. case KeymapNotify:
  222059. {
  222060. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  222061. memcpy (Keys::keyStates, keymapEvent->key_vector, 32);
  222062. break;
  222063. }
  222064. default:
  222065. break;
  222066. }
  222067. }
  222068. }
  222069. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool /*clipToWorkArea*/)
  222070. {
  222071. if (display == 0)
  222072. return;
  222073. #if JUCE_USE_XINERAMA
  222074. int major_opcode, first_event, first_error;
  222075. ScopedXLock xlock;
  222076. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error))
  222077. {
  222078. typedef Bool (*tXineramaIsActive) (Display*);
  222079. typedef XineramaScreenInfo* (*tXineramaQueryScreens) (Display*, int*);
  222080. static tXineramaIsActive xXineramaIsActive = 0;
  222081. static tXineramaQueryScreens xXineramaQueryScreens = 0;
  222082. if (xXineramaIsActive == 0 || xXineramaQueryScreens == 0)
  222083. {
  222084. void* h = dlopen ("libXinerama.so", RTLD_GLOBAL | RTLD_NOW);
  222085. if (h == 0)
  222086. h = dlopen ("libXinerama.so.1", RTLD_GLOBAL | RTLD_NOW);
  222087. if (h != 0)
  222088. {
  222089. xXineramaIsActive = (tXineramaIsActive) dlsym (h, "XineramaIsActive");
  222090. xXineramaQueryScreens = (tXineramaQueryScreens) dlsym (h, "XineramaQueryScreens");
  222091. }
  222092. }
  222093. if (xXineramaIsActive != 0
  222094. && xXineramaQueryScreens != 0
  222095. && xXineramaIsActive (display))
  222096. {
  222097. int numMonitors = 0;
  222098. XineramaScreenInfo* const screens = xXineramaQueryScreens (display, &numMonitors);
  222099. if (screens != 0)
  222100. {
  222101. for (int i = numMonitors; --i >= 0;)
  222102. {
  222103. int index = screens[i].screen_number;
  222104. if (index >= 0)
  222105. {
  222106. while (monitorCoords.size() < index)
  222107. monitorCoords.add (Rectangle<int>());
  222108. monitorCoords.set (index, Rectangle<int> (screens[i].x_org,
  222109. screens[i].y_org,
  222110. screens[i].width,
  222111. screens[i].height));
  222112. }
  222113. }
  222114. XFree (screens);
  222115. }
  222116. }
  222117. }
  222118. if (monitorCoords.size() == 0)
  222119. #endif
  222120. {
  222121. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  222122. if (hints != None)
  222123. {
  222124. const int numMonitors = ScreenCount (display);
  222125. for (int i = 0; i < numMonitors; ++i)
  222126. {
  222127. Window root = RootWindow (display, i);
  222128. unsigned long nitems, bytesLeft;
  222129. Atom actualType;
  222130. int actualFormat;
  222131. unsigned char* data = 0;
  222132. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  222133. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  222134. &data) == Success)
  222135. {
  222136. const long* const position = (const long*) data;
  222137. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  222138. monitorCoords.add (Rectangle<int> (position[0], position[1],
  222139. position[2], position[3]));
  222140. XFree (data);
  222141. }
  222142. }
  222143. }
  222144. if (monitorCoords.size() == 0)
  222145. {
  222146. monitorCoords.add (Rectangle<int> (DisplayWidth (display, DefaultScreen (display)),
  222147. DisplayHeight (display, DefaultScreen (display))));
  222148. }
  222149. }
  222150. }
  222151. void Desktop::createMouseInputSources()
  222152. {
  222153. mouseSources.add (new MouseInputSource (0, true));
  222154. }
  222155. bool Desktop::canUseSemiTransparentWindows() throw()
  222156. {
  222157. int matchedDepth = 0;
  222158. const int desiredDepth = 32;
  222159. return Visuals::findVisualFormat (desiredDepth, matchedDepth) != 0
  222160. && (matchedDepth == desiredDepth);
  222161. }
  222162. const Point<int> Desktop::getMousePosition()
  222163. {
  222164. Window root, child;
  222165. int x, y, winx, winy;
  222166. unsigned int mask;
  222167. ScopedXLock xlock;
  222168. if (XQueryPointer (display,
  222169. RootWindow (display, DefaultScreen (display)),
  222170. &root, &child,
  222171. &x, &y, &winx, &winy, &mask) == False)
  222172. {
  222173. // Pointer not on the default screen
  222174. x = y = -1;
  222175. }
  222176. return Point<int> (x, y);
  222177. }
  222178. void Desktop::setMousePosition (const Point<int>& newPosition)
  222179. {
  222180. ScopedXLock xlock;
  222181. Window root = RootWindow (display, DefaultScreen (display));
  222182. XWarpPointer (display, None, root, 0, 0, 0, 0, newPosition.getX(), newPosition.getY());
  222183. }
  222184. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  222185. {
  222186. return upright;
  222187. }
  222188. static bool screenSaverAllowed = true;
  222189. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  222190. {
  222191. if (screenSaverAllowed != isEnabled)
  222192. {
  222193. screenSaverAllowed = isEnabled;
  222194. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  222195. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  222196. if (xScreenSaverSuspend == 0)
  222197. {
  222198. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  222199. if (h != 0)
  222200. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  222201. }
  222202. ScopedXLock xlock;
  222203. if (xScreenSaverSuspend != 0)
  222204. xScreenSaverSuspend (display, ! isEnabled);
  222205. }
  222206. }
  222207. bool Desktop::isScreenSaverEnabled()
  222208. {
  222209. return screenSaverAllowed;
  222210. }
  222211. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  222212. {
  222213. ScopedXLock xlock;
  222214. const unsigned int imageW = image.getWidth();
  222215. const unsigned int imageH = image.getHeight();
  222216. #if JUCE_USE_XCURSOR
  222217. {
  222218. typedef XcursorBool (*tXcursorSupportsARGB) (Display*);
  222219. typedef XcursorImage* (*tXcursorImageCreate) (int, int);
  222220. typedef void (*tXcursorImageDestroy) (XcursorImage*);
  222221. typedef Cursor (*tXcursorImageLoadCursor) (Display*, const XcursorImage*);
  222222. static tXcursorSupportsARGB xXcursorSupportsARGB = 0;
  222223. static tXcursorImageCreate xXcursorImageCreate = 0;
  222224. static tXcursorImageDestroy xXcursorImageDestroy = 0;
  222225. static tXcursorImageLoadCursor xXcursorImageLoadCursor = 0;
  222226. static bool hasBeenLoaded = false;
  222227. if (! hasBeenLoaded)
  222228. {
  222229. hasBeenLoaded = true;
  222230. void* h = dlopen ("libXcursor.so", RTLD_GLOBAL | RTLD_NOW);
  222231. if (h != 0)
  222232. {
  222233. xXcursorSupportsARGB = (tXcursorSupportsARGB) dlsym (h, "XcursorSupportsARGB");
  222234. xXcursorImageCreate = (tXcursorImageCreate) dlsym (h, "XcursorImageCreate");
  222235. xXcursorImageLoadCursor = (tXcursorImageLoadCursor) dlsym (h, "XcursorImageLoadCursor");
  222236. xXcursorImageDestroy = (tXcursorImageDestroy) dlsym (h, "XcursorImageDestroy");
  222237. if (xXcursorSupportsARGB == 0 || xXcursorImageCreate == 0
  222238. || xXcursorImageLoadCursor == 0 || xXcursorImageDestroy == 0
  222239. || ! xXcursorSupportsARGB (display))
  222240. xXcursorSupportsARGB = 0;
  222241. }
  222242. }
  222243. if (xXcursorSupportsARGB != 0)
  222244. {
  222245. XcursorImage* xcImage = xXcursorImageCreate (imageW, imageH);
  222246. if (xcImage != 0)
  222247. {
  222248. xcImage->xhot = hotspotX;
  222249. xcImage->yhot = hotspotY;
  222250. XcursorPixel* dest = xcImage->pixels;
  222251. for (int y = 0; y < (int) imageH; ++y)
  222252. for (int x = 0; x < (int) imageW; ++x)
  222253. *dest++ = image.getPixelAt (x, y).getARGB();
  222254. void* result = (void*) xXcursorImageLoadCursor (display, xcImage);
  222255. xXcursorImageDestroy (xcImage);
  222256. if (result != 0)
  222257. return result;
  222258. }
  222259. }
  222260. }
  222261. #endif
  222262. Window root = RootWindow (display, DefaultScreen (display));
  222263. unsigned int cursorW, cursorH;
  222264. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222265. return 0;
  222266. Image im (Image::ARGB, cursorW, cursorH, true);
  222267. {
  222268. Graphics g (im);
  222269. if (imageW > cursorW || imageH > cursorH)
  222270. {
  222271. hotspotX = (hotspotX * cursorW) / imageW;
  222272. hotspotY = (hotspotY * cursorH) / imageH;
  222273. g.drawImageWithin (image, 0, 0, imageW, imageH,
  222274. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222275. false);
  222276. }
  222277. else
  222278. {
  222279. g.drawImageAt (image, 0, 0);
  222280. }
  222281. }
  222282. const int stride = (cursorW + 7) >> 3;
  222283. HeapBlock <char> maskPlane, sourcePlane;
  222284. maskPlane.calloc (stride * cursorH);
  222285. sourcePlane.calloc (stride * cursorH);
  222286. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222287. for (int y = cursorH; --y >= 0;)
  222288. {
  222289. for (int x = cursorW; --x >= 0;)
  222290. {
  222291. const char mask = (char) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222292. const int offset = y * stride + (x >> 3);
  222293. const Colour c (im.getPixelAt (x, y));
  222294. if (c.getAlpha() >= 128)
  222295. maskPlane[offset] |= mask;
  222296. if (c.getBrightness() >= 0.5f)
  222297. sourcePlane[offset] |= mask;
  222298. }
  222299. }
  222300. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, sourcePlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222301. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, maskPlane.getData(), cursorW, cursorH, 0xffff, 0, 1);
  222302. XColor white, black;
  222303. black.red = black.green = black.blue = 0;
  222304. white.red = white.green = white.blue = 0xffff;
  222305. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222306. XFreePixmap (display, sourcePixmap);
  222307. XFreePixmap (display, maskPixmap);
  222308. return result;
  222309. }
  222310. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool)
  222311. {
  222312. ScopedXLock xlock;
  222313. if (cursorHandle != 0)
  222314. XFreeCursor (display, (Cursor) cursorHandle);
  222315. }
  222316. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  222317. {
  222318. unsigned int shape;
  222319. switch (type)
  222320. {
  222321. case NormalCursor: return None; // Use parent cursor
  222322. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 16, 16, true), 0, 0);
  222323. case WaitCursor: shape = XC_watch; break;
  222324. case IBeamCursor: shape = XC_xterm; break;
  222325. case PointingHandCursor: shape = XC_hand2; break;
  222326. case LeftRightResizeCursor: shape = XC_sb_h_double_arrow; break;
  222327. case UpDownResizeCursor: shape = XC_sb_v_double_arrow; break;
  222328. case UpDownLeftRightResizeCursor: shape = XC_fleur; break;
  222329. case TopEdgeResizeCursor: shape = XC_top_side; break;
  222330. case BottomEdgeResizeCursor: shape = XC_bottom_side; break;
  222331. case LeftEdgeResizeCursor: shape = XC_left_side; break;
  222332. case RightEdgeResizeCursor: shape = XC_right_side; break;
  222333. case TopLeftCornerResizeCursor: shape = XC_top_left_corner; break;
  222334. case TopRightCornerResizeCursor: shape = XC_top_right_corner; break;
  222335. case BottomLeftCornerResizeCursor: shape = XC_bottom_left_corner; break;
  222336. case BottomRightCornerResizeCursor: shape = XC_bottom_right_corner; break;
  222337. case CrosshairCursor: shape = XC_crosshair; break;
  222338. case DraggingHandCursor:
  222339. {
  222340. static unsigned char dragHandData[] = { 71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222341. 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,
  222342. 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 };
  222343. const int dragHandDataSize = 99;
  222344. return createMouseCursorFromImage (ImageFileFormat::loadFrom (dragHandData, dragHandDataSize), 8, 7);
  222345. }
  222346. case CopyingCursor:
  222347. {
  222348. static unsigned char copyCursorData[] = { 71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222349. 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,
  222350. 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,
  222351. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222352. const int copyCursorSize = 119;
  222353. return createMouseCursorFromImage (ImageFileFormat::loadFrom (copyCursorData, copyCursorSize), 1, 3);
  222354. }
  222355. default:
  222356. jassertfalse;
  222357. return None;
  222358. }
  222359. ScopedXLock xlock;
  222360. return (void*) XCreateFontCursor (display, shape);
  222361. }
  222362. void MouseCursor::showInWindow (ComponentPeer* peer) const
  222363. {
  222364. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222365. if (lp != 0)
  222366. lp->showMouseCursor ((Cursor) getHandle());
  222367. }
  222368. void MouseCursor::showInAllWindows() const
  222369. {
  222370. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222371. showInWindow (ComponentPeer::getPeer (i));
  222372. }
  222373. const Image juce_createIconForFile (const File& file)
  222374. {
  222375. return Image::null;
  222376. }
  222377. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  222378. {
  222379. return createSoftwareImage (format, width, height, clearImage);
  222380. }
  222381. #if JUCE_OPENGL
  222382. class WindowedGLContext : public OpenGLContext
  222383. {
  222384. public:
  222385. WindowedGLContext (Component* const component,
  222386. const OpenGLPixelFormat& pixelFormat_,
  222387. GLXContext sharedContext)
  222388. : renderContext (0),
  222389. embeddedWindow (0),
  222390. pixelFormat (pixelFormat_),
  222391. swapInterval (0)
  222392. {
  222393. jassert (component != 0);
  222394. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222395. if (peer == 0)
  222396. return;
  222397. ScopedXLock xlock;
  222398. XSync (display, False);
  222399. GLint attribs [64];
  222400. int n = 0;
  222401. attribs[n++] = GLX_RGBA;
  222402. attribs[n++] = GLX_DOUBLEBUFFER;
  222403. attribs[n++] = GLX_RED_SIZE;
  222404. attribs[n++] = pixelFormat.redBits;
  222405. attribs[n++] = GLX_GREEN_SIZE;
  222406. attribs[n++] = pixelFormat.greenBits;
  222407. attribs[n++] = GLX_BLUE_SIZE;
  222408. attribs[n++] = pixelFormat.blueBits;
  222409. attribs[n++] = GLX_ALPHA_SIZE;
  222410. attribs[n++] = pixelFormat.alphaBits;
  222411. attribs[n++] = GLX_DEPTH_SIZE;
  222412. attribs[n++] = pixelFormat.depthBufferBits;
  222413. attribs[n++] = GLX_STENCIL_SIZE;
  222414. attribs[n++] = pixelFormat.stencilBufferBits;
  222415. attribs[n++] = GLX_ACCUM_RED_SIZE;
  222416. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  222417. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  222418. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  222419. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  222420. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  222421. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  222422. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  222423. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  222424. attribs[n++] = None;
  222425. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  222426. if (bestVisual == 0)
  222427. return;
  222428. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  222429. Window windowH = (Window) peer->getNativeHandle();
  222430. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  222431. XSetWindowAttributes swa;
  222432. swa.colormap = colourMap;
  222433. swa.border_pixel = 0;
  222434. swa.event_mask = ExposureMask | StructureNotifyMask;
  222435. embeddedWindow = XCreateWindow (display, windowH,
  222436. 0, 0, 1, 1, 0,
  222437. bestVisual->depth,
  222438. InputOutput,
  222439. bestVisual->visual,
  222440. CWBorderPixel | CWColormap | CWEventMask,
  222441. &swa);
  222442. XSaveContext (display, (XID) embeddedWindow, windowHandleXContext, (XPointer) peer);
  222443. XMapWindow (display, embeddedWindow);
  222444. XFreeColormap (display, colourMap);
  222445. XFree (bestVisual);
  222446. XSync (display, False);
  222447. }
  222448. ~WindowedGLContext()
  222449. {
  222450. ScopedXLock xlock;
  222451. deleteContext();
  222452. XUnmapWindow (display, embeddedWindow);
  222453. XDestroyWindow (display, embeddedWindow);
  222454. }
  222455. void deleteContext()
  222456. {
  222457. makeInactive();
  222458. if (renderContext != 0)
  222459. {
  222460. ScopedXLock xlock;
  222461. glXDestroyContext (display, renderContext);
  222462. renderContext = 0;
  222463. }
  222464. }
  222465. bool makeActive() const throw()
  222466. {
  222467. jassert (renderContext != 0);
  222468. ScopedXLock xlock;
  222469. return glXMakeCurrent (display, embeddedWindow, renderContext)
  222470. && XSync (display, False);
  222471. }
  222472. bool makeInactive() const throw()
  222473. {
  222474. ScopedXLock xlock;
  222475. return (! isActive()) || glXMakeCurrent (display, None, 0);
  222476. }
  222477. bool isActive() const throw()
  222478. {
  222479. ScopedXLock xlock;
  222480. return glXGetCurrentContext() == renderContext;
  222481. }
  222482. const OpenGLPixelFormat getPixelFormat() const
  222483. {
  222484. return pixelFormat;
  222485. }
  222486. void* getRawContext() const throw()
  222487. {
  222488. return renderContext;
  222489. }
  222490. void updateWindowPosition (int x, int y, int w, int h, int)
  222491. {
  222492. ScopedXLock xlock;
  222493. XMoveResizeWindow (display, embeddedWindow,
  222494. x, y, jmax (1, w), jmax (1, h));
  222495. }
  222496. void swapBuffers()
  222497. {
  222498. ScopedXLock xlock;
  222499. glXSwapBuffers (display, embeddedWindow);
  222500. }
  222501. bool setSwapInterval (const int numFramesPerSwap)
  222502. {
  222503. static PFNGLXSWAPINTERVALSGIPROC GLXSwapIntervalSGI = (PFNGLXSWAPINTERVALSGIPROC) glXGetProcAddress ((const GLubyte*) "glXSwapIntervalSGI");
  222504. if (GLXSwapIntervalSGI != 0)
  222505. {
  222506. swapInterval = numFramesPerSwap;
  222507. GLXSwapIntervalSGI (numFramesPerSwap);
  222508. return true;
  222509. }
  222510. return false;
  222511. }
  222512. int getSwapInterval() const
  222513. {
  222514. return swapInterval;
  222515. }
  222516. void repaint()
  222517. {
  222518. }
  222519. juce_UseDebuggingNewOperator
  222520. GLXContext renderContext;
  222521. private:
  222522. Window embeddedWindow;
  222523. OpenGLPixelFormat pixelFormat;
  222524. int swapInterval;
  222525. WindowedGLContext (const WindowedGLContext&);
  222526. WindowedGLContext& operator= (const WindowedGLContext&);
  222527. };
  222528. OpenGLContext* OpenGLComponent::createContext()
  222529. {
  222530. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  222531. contextToShareListsWith != 0 ? (GLXContext) contextToShareListsWith->getRawContext() : 0));
  222532. return (c->renderContext != 0) ? c.release() : 0;
  222533. }
  222534. void juce_glViewport (const int w, const int h)
  222535. {
  222536. glViewport (0, 0, w, h);
  222537. }
  222538. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  222539. OwnedArray <OpenGLPixelFormat>& results)
  222540. {
  222541. results.add (new OpenGLPixelFormat()); // xxx
  222542. }
  222543. #endif
  222544. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  222545. {
  222546. jassertfalse; // not implemented!
  222547. return false;
  222548. }
  222549. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  222550. {
  222551. jassertfalse; // not implemented!
  222552. return false;
  222553. }
  222554. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  222555. {
  222556. if (! isOnDesktop ())
  222557. addToDesktop (0);
  222558. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222559. if (wp != 0)
  222560. {
  222561. wp->setTaskBarIcon (newImage);
  222562. setVisible (true);
  222563. toFront (false);
  222564. repaint();
  222565. }
  222566. }
  222567. void SystemTrayIconComponent::paint (Graphics& g)
  222568. {
  222569. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  222570. if (wp != 0)
  222571. {
  222572. g.drawImageWithin (wp->getTaskbarIcon(), 0, 0, getWidth(), getHeight(),
  222573. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222574. false);
  222575. }
  222576. }
  222577. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  222578. {
  222579. // xxx not yet implemented!
  222580. }
  222581. void PlatformUtilities::beep()
  222582. {
  222583. std::cout << "\a" << std::flush;
  222584. }
  222585. bool AlertWindow::showNativeDialogBox (const String& title,
  222586. const String& bodyText,
  222587. bool isOkCancel)
  222588. {
  222589. // use a non-native one for the time being..
  222590. if (isOkCancel)
  222591. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  222592. else
  222593. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  222594. return true;
  222595. }
  222596. const int KeyPress::spaceKey = XK_space & 0xff;
  222597. const int KeyPress::returnKey = XK_Return & 0xff;
  222598. const int KeyPress::escapeKey = XK_Escape & 0xff;
  222599. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  222600. const int KeyPress::leftKey = (XK_Left & 0xff) | Keys::extendedKeyModifier;
  222601. const int KeyPress::rightKey = (XK_Right & 0xff) | Keys::extendedKeyModifier;
  222602. const int KeyPress::upKey = (XK_Up & 0xff) | Keys::extendedKeyModifier;
  222603. const int KeyPress::downKey = (XK_Down & 0xff) | Keys::extendedKeyModifier;
  222604. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | Keys::extendedKeyModifier;
  222605. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | Keys::extendedKeyModifier;
  222606. const int KeyPress::endKey = (XK_End & 0xff) | Keys::extendedKeyModifier;
  222607. const int KeyPress::homeKey = (XK_Home & 0xff) | Keys::extendedKeyModifier;
  222608. const int KeyPress::insertKey = (XK_Insert & 0xff) | Keys::extendedKeyModifier;
  222609. const int KeyPress::deleteKey = (XK_Delete & 0xff) | Keys::extendedKeyModifier;
  222610. const int KeyPress::tabKey = XK_Tab & 0xff;
  222611. const int KeyPress::F1Key = (XK_F1 & 0xff) | Keys::extendedKeyModifier;
  222612. const int KeyPress::F2Key = (XK_F2 & 0xff) | Keys::extendedKeyModifier;
  222613. const int KeyPress::F3Key = (XK_F3 & 0xff) | Keys::extendedKeyModifier;
  222614. const int KeyPress::F4Key = (XK_F4 & 0xff) | Keys::extendedKeyModifier;
  222615. const int KeyPress::F5Key = (XK_F5 & 0xff) | Keys::extendedKeyModifier;
  222616. const int KeyPress::F6Key = (XK_F6 & 0xff) | Keys::extendedKeyModifier;
  222617. const int KeyPress::F7Key = (XK_F7 & 0xff) | Keys::extendedKeyModifier;
  222618. const int KeyPress::F8Key = (XK_F8 & 0xff) | Keys::extendedKeyModifier;
  222619. const int KeyPress::F9Key = (XK_F9 & 0xff) | Keys::extendedKeyModifier;
  222620. const int KeyPress::F10Key = (XK_F10 & 0xff) | Keys::extendedKeyModifier;
  222621. const int KeyPress::F11Key = (XK_F11 & 0xff) | Keys::extendedKeyModifier;
  222622. const int KeyPress::F12Key = (XK_F12 & 0xff) | Keys::extendedKeyModifier;
  222623. const int KeyPress::F13Key = (XK_F13 & 0xff) | Keys::extendedKeyModifier;
  222624. const int KeyPress::F14Key = (XK_F14 & 0xff) | Keys::extendedKeyModifier;
  222625. const int KeyPress::F15Key = (XK_F15 & 0xff) | Keys::extendedKeyModifier;
  222626. const int KeyPress::F16Key = (XK_F16 & 0xff) | Keys::extendedKeyModifier;
  222627. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | Keys::extendedKeyModifier;
  222628. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | Keys::extendedKeyModifier;
  222629. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | Keys::extendedKeyModifier;
  222630. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | Keys::extendedKeyModifier;
  222631. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | Keys::extendedKeyModifier;
  222632. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | Keys::extendedKeyModifier;
  222633. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | Keys::extendedKeyModifier;
  222634. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| Keys::extendedKeyModifier;
  222635. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| Keys::extendedKeyModifier;
  222636. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| Keys::extendedKeyModifier;
  222637. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| Keys::extendedKeyModifier;
  222638. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| Keys::extendedKeyModifier;
  222639. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| Keys::extendedKeyModifier;
  222640. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| Keys::extendedKeyModifier;
  222641. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| Keys::extendedKeyModifier;
  222642. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| Keys::extendedKeyModifier;
  222643. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| Keys::extendedKeyModifier;
  222644. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| Keys::extendedKeyModifier;
  222645. const int KeyPress::playKey = (0xffeeff00) | Keys::extendedKeyModifier;
  222646. const int KeyPress::stopKey = (0xffeeff01) | Keys::extendedKeyModifier;
  222647. const int KeyPress::fastForwardKey = (0xffeeff02) | Keys::extendedKeyModifier;
  222648. const int KeyPress::rewindKey = (0xffeeff03) | Keys::extendedKeyModifier;
  222649. #endif
  222650. /*** End of inlined file: juce_linux_Windowing.cpp ***/
  222651. /*** Start of inlined file: juce_linux_Audio.cpp ***/
  222652. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  222653. // compiled on its own).
  222654. #if JUCE_INCLUDED_FILE && JUCE_ALSA
  222655. namespace
  222656. {
  222657. void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  222658. {
  222659. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  222660. snd_pcm_hw_params_t* hwParams;
  222661. snd_pcm_hw_params_alloca (&hwParams);
  222662. for (int i = 0; ratesToTry[i] != 0; ++i)
  222663. {
  222664. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  222665. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  222666. {
  222667. rates.addIfNotAlreadyThere (ratesToTry[i]);
  222668. }
  222669. }
  222670. }
  222671. void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  222672. {
  222673. snd_pcm_hw_params_t *params;
  222674. snd_pcm_hw_params_alloca (&params);
  222675. if (snd_pcm_hw_params_any (handle, params) >= 0)
  222676. {
  222677. snd_pcm_hw_params_get_channels_min (params, minChans);
  222678. snd_pcm_hw_params_get_channels_max (params, maxChans);
  222679. }
  222680. }
  222681. void getDeviceProperties (const String& deviceID,
  222682. unsigned int& minChansOut,
  222683. unsigned int& maxChansOut,
  222684. unsigned int& minChansIn,
  222685. unsigned int& maxChansIn,
  222686. Array <int>& rates)
  222687. {
  222688. if (deviceID.isEmpty())
  222689. return;
  222690. snd_ctl_t* handle;
  222691. if (snd_ctl_open (&handle, deviceID.upToLastOccurrenceOf (",", false, false).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  222692. {
  222693. snd_pcm_info_t* info;
  222694. snd_pcm_info_alloca (&info);
  222695. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  222696. snd_pcm_info_set_device (info, deviceID.fromLastOccurrenceOf (",", false, false).getIntValue());
  222697. snd_pcm_info_set_subdevice (info, 0);
  222698. if (snd_ctl_pcm_info (handle, info) >= 0)
  222699. {
  222700. snd_pcm_t* pcmHandle;
  222701. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222702. {
  222703. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  222704. getDeviceSampleRates (pcmHandle, rates);
  222705. snd_pcm_close (pcmHandle);
  222706. }
  222707. }
  222708. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  222709. if (snd_ctl_pcm_info (handle, info) >= 0)
  222710. {
  222711. snd_pcm_t* pcmHandle;
  222712. if (snd_pcm_open (&pcmHandle, deviceID.toUTF8(), SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK) >= 0)
  222713. {
  222714. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  222715. if (rates.size() == 0)
  222716. getDeviceSampleRates (pcmHandle, rates);
  222717. snd_pcm_close (pcmHandle);
  222718. }
  222719. }
  222720. snd_ctl_close (handle);
  222721. }
  222722. }
  222723. }
  222724. class ALSADevice
  222725. {
  222726. public:
  222727. ALSADevice (const String& deviceID, bool forInput)
  222728. : handle (0),
  222729. bitDepth (16),
  222730. numChannelsRunning (0),
  222731. latency (0),
  222732. isInput (forInput)
  222733. {
  222734. failed (snd_pcm_open (&handle, deviceID.toUTF8(),
  222735. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  222736. SND_PCM_ASYNC));
  222737. }
  222738. ~ALSADevice()
  222739. {
  222740. if (handle != 0)
  222741. snd_pcm_close (handle);
  222742. }
  222743. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  222744. {
  222745. if (handle == 0)
  222746. return false;
  222747. snd_pcm_hw_params_t* hwParams;
  222748. snd_pcm_hw_params_alloca (&hwParams);
  222749. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  222750. return false;
  222751. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  222752. isInterleaved = false;
  222753. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  222754. isInterleaved = true;
  222755. else
  222756. {
  222757. jassertfalse;
  222758. return false;
  222759. }
  222760. enum { isFloatBit = 1 << 16, isLittleEndianBit = 1 << 17 };
  222761. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32 | isFloatBit | isLittleEndianBit,
  222762. SND_PCM_FORMAT_FLOAT_BE, 32 | isFloatBit,
  222763. SND_PCM_FORMAT_S32_LE, 32 | isLittleEndianBit,
  222764. SND_PCM_FORMAT_S32_BE, 32,
  222765. SND_PCM_FORMAT_S24_3LE, 24 | isLittleEndianBit,
  222766. SND_PCM_FORMAT_S24_3BE, 24,
  222767. SND_PCM_FORMAT_S16_LE, 16 | isLittleEndianBit,
  222768. SND_PCM_FORMAT_S16_BE, 16 };
  222769. bitDepth = 0;
  222770. for (int i = 0; i < numElementsInArray (formatsToTry); i += 2)
  222771. {
  222772. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  222773. {
  222774. bitDepth = formatsToTry [i + 1] & 255;
  222775. const bool isFloat = (formatsToTry [i + 1] & isFloatBit) != 0;
  222776. const bool isLittleEndian = (formatsToTry [i + 1] & isLittleEndianBit) != 0;
  222777. converter = createConverter (isInput, bitDepth, isFloat, isLittleEndian, numChannels);
  222778. break;
  222779. }
  222780. }
  222781. if (bitDepth == 0)
  222782. {
  222783. error = "device doesn't support a compatible PCM format";
  222784. DBG ("ALSA error: " + error + "\n");
  222785. return false;
  222786. }
  222787. int dir = 0;
  222788. unsigned int periods = 4;
  222789. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  222790. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  222791. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  222792. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  222793. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  222794. || failed (snd_pcm_hw_params (handle, hwParams)))
  222795. {
  222796. return false;
  222797. }
  222798. snd_pcm_uframes_t frames = 0;
  222799. if (failed (snd_pcm_hw_params_get_period_size (hwParams, &frames, &dir))
  222800. || failed (snd_pcm_hw_params_get_periods (hwParams, &periods, &dir)))
  222801. latency = 0;
  222802. else
  222803. latency = frames * (periods - 1); // (this is the method JACK uses to guess the latency..)
  222804. snd_pcm_sw_params_t* swParams;
  222805. snd_pcm_sw_params_alloca (&swParams);
  222806. snd_pcm_uframes_t boundary;
  222807. if (failed (snd_pcm_sw_params_current (handle, swParams))
  222808. || failed (snd_pcm_sw_params_get_boundary (swParams, &boundary))
  222809. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  222810. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, boundary))
  222811. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  222812. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, boundary))
  222813. || failed (snd_pcm_sw_params (handle, swParams)))
  222814. {
  222815. return false;
  222816. }
  222817. /*
  222818. #if JUCE_DEBUG
  222819. // enable this to dump the config of the devices that get opened
  222820. snd_output_t* out;
  222821. snd_output_stdio_attach (&out, stderr, 0);
  222822. snd_pcm_hw_params_dump (hwParams, out);
  222823. snd_pcm_sw_params_dump (swParams, out);
  222824. #endif
  222825. */
  222826. numChannelsRunning = numChannels;
  222827. return true;
  222828. }
  222829. bool writeToOutputDevice (AudioSampleBuffer& outputChannelBuffer, const int numSamples)
  222830. {
  222831. jassert (numChannelsRunning <= outputChannelBuffer.getNumChannels());
  222832. float** const data = outputChannelBuffer.getArrayOfChannels();
  222833. snd_pcm_sframes_t numDone = 0;
  222834. if (isInterleaved)
  222835. {
  222836. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222837. for (int i = 0; i < numChannelsRunning; ++i)
  222838. converter->convertSamples (scratch.getData(), i, data[i], 0, numSamples);
  222839. numDone = snd_pcm_writei (handle, scratch.getData(), numSamples);
  222840. }
  222841. else
  222842. {
  222843. for (int i = 0; i < numChannelsRunning; ++i)
  222844. converter->convertSamples (data[i], data[i], numSamples);
  222845. numDone = snd_pcm_writen (handle, (void**) data, numSamples);
  222846. }
  222847. if (failed (numDone))
  222848. {
  222849. if (numDone == -EPIPE)
  222850. {
  222851. if (failed (snd_pcm_prepare (handle)))
  222852. return false;
  222853. }
  222854. else if (numDone != -ESTRPIPE)
  222855. return false;
  222856. }
  222857. return true;
  222858. }
  222859. bool readFromInputDevice (AudioSampleBuffer& inputChannelBuffer, const int numSamples)
  222860. {
  222861. jassert (numChannelsRunning <= inputChannelBuffer.getNumChannels());
  222862. float** const data = inputChannelBuffer.getArrayOfChannels();
  222863. if (isInterleaved)
  222864. {
  222865. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  222866. snd_pcm_sframes_t num = snd_pcm_readi (handle, scratch.getData(), numSamples);
  222867. if (failed (num))
  222868. {
  222869. if (num == -EPIPE)
  222870. {
  222871. if (failed (snd_pcm_prepare (handle)))
  222872. return false;
  222873. }
  222874. else if (num != -ESTRPIPE)
  222875. return false;
  222876. }
  222877. for (int i = 0; i < numChannelsRunning; ++i)
  222878. converter->convertSamples (data[i], 0, scratch.getData(), i, numSamples);
  222879. }
  222880. else
  222881. {
  222882. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  222883. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  222884. return false;
  222885. for (int i = 0; i < numChannelsRunning; ++i)
  222886. converter->convertSamples (data[i], data[i], numSamples);
  222887. }
  222888. return true;
  222889. }
  222890. juce_UseDebuggingNewOperator
  222891. snd_pcm_t* handle;
  222892. String error;
  222893. int bitDepth, numChannelsRunning, latency;
  222894. private:
  222895. const bool isInput;
  222896. bool isInterleaved;
  222897. MemoryBlock scratch;
  222898. ScopedPointer<AudioData::Converter> converter;
  222899. template <class SampleType>
  222900. struct ConverterHelper
  222901. {
  222902. static AudioData::Converter* createConverter (const bool forInput, const bool isLittleEndian, const int numInterleavedChannels)
  222903. {
  222904. if (forInput)
  222905. {
  222906. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::NonConst> DestType;
  222907. if (isLittleEndian)
  222908. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222909. else
  222910. return new AudioData::ConverterInstance <AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::Const>, DestType> (numInterleavedChannels, 1);
  222911. }
  222912. else
  222913. {
  222914. typedef AudioData::Pointer <AudioData::Float32, AudioData::NativeEndian, AudioData::NonInterleaved, AudioData::Const> SourceType;
  222915. if (isLittleEndian)
  222916. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::LittleEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222917. else
  222918. return new AudioData::ConverterInstance <SourceType, AudioData::Pointer <SampleType, AudioData::BigEndian, AudioData::Interleaved, AudioData::NonConst> > (1, numInterleavedChannels);
  222919. }
  222920. }
  222921. };
  222922. static AudioData::Converter* createConverter (const bool forInput, const int bitDepth, const bool isFloat, const bool isLittleEndian, const int numInterleavedChannels)
  222923. {
  222924. switch (bitDepth)
  222925. {
  222926. case 16: return ConverterHelper <AudioData::Int16>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222927. case 24: return ConverterHelper <AudioData::Int24>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222928. case 32: return isFloat ? ConverterHelper <AudioData::Float32>::createConverter (forInput, isLittleEndian, numInterleavedChannels)
  222929. : ConverterHelper <AudioData::Int32>::createConverter (forInput, isLittleEndian, numInterleavedChannels);
  222930. default: jassertfalse; break; // unsupported format!
  222931. }
  222932. return 0;
  222933. }
  222934. bool failed (const int errorNum)
  222935. {
  222936. if (errorNum >= 0)
  222937. return false;
  222938. error = snd_strerror (errorNum);
  222939. DBG ("ALSA error: " + error + "\n");
  222940. return true;
  222941. }
  222942. };
  222943. class ALSAThread : public Thread
  222944. {
  222945. public:
  222946. ALSAThread (const String& inputId_,
  222947. const String& outputId_)
  222948. : Thread ("Juce ALSA"),
  222949. sampleRate (0),
  222950. bufferSize (0),
  222951. outputLatency (0),
  222952. inputLatency (0),
  222953. callback (0),
  222954. inputId (inputId_),
  222955. outputId (outputId_),
  222956. numCallbacks (0),
  222957. inputChannelBuffer (1, 1),
  222958. outputChannelBuffer (1, 1)
  222959. {
  222960. initialiseRatesAndChannels();
  222961. }
  222962. ~ALSAThread()
  222963. {
  222964. close();
  222965. }
  222966. void open (BigInteger inputChannels,
  222967. BigInteger outputChannels,
  222968. const double sampleRate_,
  222969. const int bufferSize_)
  222970. {
  222971. close();
  222972. error = String::empty;
  222973. sampleRate = sampleRate_;
  222974. bufferSize = bufferSize_;
  222975. inputChannelBuffer.setSize (jmax ((int) minChansIn, inputChannels.getHighestBit()) + 1, bufferSize);
  222976. inputChannelBuffer.clear();
  222977. inputChannelDataForCallback.clear();
  222978. currentInputChans.clear();
  222979. if (inputChannels.getHighestBit() >= 0)
  222980. {
  222981. for (int i = 0; i <= jmax (inputChannels.getHighestBit(), (int) minChansIn); ++i)
  222982. {
  222983. if (inputChannels[i])
  222984. {
  222985. inputChannelDataForCallback.add (inputChannelBuffer.getSampleData (i));
  222986. currentInputChans.setBit (i);
  222987. }
  222988. }
  222989. }
  222990. outputChannelBuffer.setSize (jmax ((int) minChansOut, outputChannels.getHighestBit()) + 1, bufferSize);
  222991. outputChannelBuffer.clear();
  222992. outputChannelDataForCallback.clear();
  222993. currentOutputChans.clear();
  222994. if (outputChannels.getHighestBit() >= 0)
  222995. {
  222996. for (int i = 0; i <= jmax (outputChannels.getHighestBit(), (int) minChansOut); ++i)
  222997. {
  222998. if (outputChannels[i])
  222999. {
  223000. outputChannelDataForCallback.add (outputChannelBuffer.getSampleData (i));
  223001. currentOutputChans.setBit (i);
  223002. }
  223003. }
  223004. }
  223005. if (outputChannelDataForCallback.size() > 0 && outputId.isNotEmpty())
  223006. {
  223007. outputDevice = new ALSADevice (outputId, false);
  223008. if (outputDevice->error.isNotEmpty())
  223009. {
  223010. error = outputDevice->error;
  223011. outputDevice = 0;
  223012. return;
  223013. }
  223014. currentOutputChans.setRange (0, minChansOut, true);
  223015. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  223016. jlimit ((int) minChansOut, (int) maxChansOut, currentOutputChans.getHighestBit() + 1),
  223017. bufferSize))
  223018. {
  223019. error = outputDevice->error;
  223020. outputDevice = 0;
  223021. return;
  223022. }
  223023. outputLatency = outputDevice->latency;
  223024. }
  223025. if (inputChannelDataForCallback.size() > 0 && inputId.isNotEmpty())
  223026. {
  223027. inputDevice = new ALSADevice (inputId, true);
  223028. if (inputDevice->error.isNotEmpty())
  223029. {
  223030. error = inputDevice->error;
  223031. inputDevice = 0;
  223032. return;
  223033. }
  223034. currentInputChans.setRange (0, minChansIn, true);
  223035. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  223036. jlimit ((int) minChansIn, (int) maxChansIn, currentInputChans.getHighestBit() + 1),
  223037. bufferSize))
  223038. {
  223039. error = inputDevice->error;
  223040. inputDevice = 0;
  223041. return;
  223042. }
  223043. inputLatency = inputDevice->latency;
  223044. }
  223045. if (outputDevice == 0 && inputDevice == 0)
  223046. {
  223047. error = "no channels";
  223048. return;
  223049. }
  223050. if (outputDevice != 0 && inputDevice != 0)
  223051. {
  223052. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  223053. }
  223054. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  223055. return;
  223056. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  223057. return;
  223058. startThread (9);
  223059. int count = 1000;
  223060. while (numCallbacks == 0)
  223061. {
  223062. sleep (5);
  223063. if (--count < 0 || ! isThreadRunning())
  223064. {
  223065. error = "device didn't start";
  223066. break;
  223067. }
  223068. }
  223069. }
  223070. void close()
  223071. {
  223072. stopThread (6000);
  223073. inputDevice = 0;
  223074. outputDevice = 0;
  223075. inputChannelBuffer.setSize (1, 1);
  223076. outputChannelBuffer.setSize (1, 1);
  223077. numCallbacks = 0;
  223078. }
  223079. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  223080. {
  223081. const ScopedLock sl (callbackLock);
  223082. callback = newCallback;
  223083. }
  223084. void run()
  223085. {
  223086. while (! threadShouldExit())
  223087. {
  223088. if (inputDevice != 0)
  223089. {
  223090. if (! inputDevice->readFromInputDevice (inputChannelBuffer, bufferSize))
  223091. {
  223092. DBG ("ALSA: read failure");
  223093. break;
  223094. }
  223095. }
  223096. if (threadShouldExit())
  223097. break;
  223098. {
  223099. const ScopedLock sl (callbackLock);
  223100. ++numCallbacks;
  223101. if (callback != 0)
  223102. {
  223103. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback.getRawDataPointer(),
  223104. inputChannelDataForCallback.size(),
  223105. outputChannelDataForCallback.getRawDataPointer(),
  223106. outputChannelDataForCallback.size(),
  223107. bufferSize);
  223108. }
  223109. else
  223110. {
  223111. for (int i = 0; i < outputChannelDataForCallback.size(); ++i)
  223112. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  223113. }
  223114. }
  223115. if (outputDevice != 0)
  223116. {
  223117. failed (snd_pcm_wait (outputDevice->handle, 2000));
  223118. if (threadShouldExit())
  223119. break;
  223120. failed (snd_pcm_avail_update (outputDevice->handle));
  223121. if (! outputDevice->writeToOutputDevice (outputChannelBuffer, bufferSize))
  223122. {
  223123. DBG ("ALSA: write failure");
  223124. break;
  223125. }
  223126. }
  223127. }
  223128. }
  223129. int getBitDepth() const throw()
  223130. {
  223131. if (outputDevice != 0)
  223132. return outputDevice->bitDepth;
  223133. if (inputDevice != 0)
  223134. return inputDevice->bitDepth;
  223135. return 16;
  223136. }
  223137. juce_UseDebuggingNewOperator
  223138. String error;
  223139. double sampleRate;
  223140. int bufferSize, outputLatency, inputLatency;
  223141. BigInteger currentInputChans, currentOutputChans;
  223142. Array <int> sampleRates;
  223143. StringArray channelNamesOut, channelNamesIn;
  223144. AudioIODeviceCallback* callback;
  223145. private:
  223146. const String inputId, outputId;
  223147. ScopedPointer<ALSADevice> outputDevice, inputDevice;
  223148. int numCallbacks;
  223149. CriticalSection callbackLock;
  223150. AudioSampleBuffer inputChannelBuffer, outputChannelBuffer;
  223151. Array<float*> inputChannelDataForCallback, outputChannelDataForCallback;
  223152. unsigned int minChansOut, maxChansOut;
  223153. unsigned int minChansIn, maxChansIn;
  223154. bool failed (const int errorNum)
  223155. {
  223156. if (errorNum >= 0)
  223157. return false;
  223158. error = snd_strerror (errorNum);
  223159. DBG ("ALSA error: " + error + "\n");
  223160. return true;
  223161. }
  223162. void initialiseRatesAndChannels()
  223163. {
  223164. sampleRates.clear();
  223165. channelNamesOut.clear();
  223166. channelNamesIn.clear();
  223167. minChansOut = 0;
  223168. maxChansOut = 0;
  223169. minChansIn = 0;
  223170. maxChansIn = 0;
  223171. unsigned int dummy = 0;
  223172. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  223173. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  223174. unsigned int i;
  223175. for (i = 0; i < maxChansOut; ++i)
  223176. channelNamesOut.add ("channel " + String ((int) i + 1));
  223177. for (i = 0; i < maxChansIn; ++i)
  223178. channelNamesIn.add ("channel " + String ((int) i + 1));
  223179. }
  223180. };
  223181. class ALSAAudioIODevice : public AudioIODevice
  223182. {
  223183. public:
  223184. ALSAAudioIODevice (const String& deviceName,
  223185. const String& inputId_,
  223186. const String& outputId_)
  223187. : AudioIODevice (deviceName, "ALSA"),
  223188. inputId (inputId_),
  223189. outputId (outputId_),
  223190. isOpen_ (false),
  223191. isStarted (false),
  223192. internal (inputId_, outputId_)
  223193. {
  223194. }
  223195. ~ALSAAudioIODevice()
  223196. {
  223197. }
  223198. const StringArray getOutputChannelNames() { return internal.channelNamesOut; }
  223199. const StringArray getInputChannelNames() { return internal.channelNamesIn; }
  223200. int getNumSampleRates() { return internal.sampleRates.size(); }
  223201. double getSampleRate (int index) { return internal.sampleRates [index]; }
  223202. int getDefaultBufferSize() { return 512; }
  223203. int getNumBufferSizesAvailable() { return 50; }
  223204. int getBufferSizeSamples (int index)
  223205. {
  223206. int n = 16;
  223207. for (int i = 0; i < index; ++i)
  223208. n += n < 64 ? 16
  223209. : (n < 512 ? 32
  223210. : (n < 1024 ? 64
  223211. : (n < 2048 ? 128 : 256)));
  223212. return n;
  223213. }
  223214. const String open (const BigInteger& inputChannels,
  223215. const BigInteger& outputChannels,
  223216. double sampleRate,
  223217. int bufferSizeSamples)
  223218. {
  223219. close();
  223220. if (bufferSizeSamples <= 0)
  223221. bufferSizeSamples = getDefaultBufferSize();
  223222. if (sampleRate <= 0)
  223223. {
  223224. for (int i = 0; i < getNumSampleRates(); ++i)
  223225. {
  223226. if (getSampleRate (i) >= 44100)
  223227. {
  223228. sampleRate = getSampleRate (i);
  223229. break;
  223230. }
  223231. }
  223232. }
  223233. internal.open (inputChannels, outputChannels,
  223234. sampleRate, bufferSizeSamples);
  223235. isOpen_ = internal.error.isEmpty();
  223236. return internal.error;
  223237. }
  223238. void close()
  223239. {
  223240. stop();
  223241. internal.close();
  223242. isOpen_ = false;
  223243. }
  223244. bool isOpen() { return isOpen_; }
  223245. bool isPlaying() { return isStarted && internal.error.isEmpty(); }
  223246. const String getLastError() { return internal.error; }
  223247. int getCurrentBufferSizeSamples() { return internal.bufferSize; }
  223248. double getCurrentSampleRate() { return internal.sampleRate; }
  223249. int getCurrentBitDepth() { return internal.getBitDepth(); }
  223250. const BigInteger getActiveOutputChannels() const { return internal.currentOutputChans; }
  223251. const BigInteger getActiveInputChannels() const { return internal.currentInputChans; }
  223252. int getOutputLatencyInSamples() { return internal.outputLatency; }
  223253. int getInputLatencyInSamples() { return internal.inputLatency; }
  223254. void start (AudioIODeviceCallback* callback)
  223255. {
  223256. if (! isOpen_)
  223257. callback = 0;
  223258. if (callback != 0)
  223259. callback->audioDeviceAboutToStart (this);
  223260. internal.setCallback (callback);
  223261. isStarted = (callback != 0);
  223262. }
  223263. void stop()
  223264. {
  223265. AudioIODeviceCallback* const oldCallback = internal.callback;
  223266. start (0);
  223267. if (oldCallback != 0)
  223268. oldCallback->audioDeviceStopped();
  223269. }
  223270. String inputId, outputId;
  223271. private:
  223272. bool isOpen_, isStarted;
  223273. ALSAThread internal;
  223274. };
  223275. class ALSAAudioIODeviceType : public AudioIODeviceType
  223276. {
  223277. public:
  223278. ALSAAudioIODeviceType()
  223279. : AudioIODeviceType ("ALSA"),
  223280. hasScanned (false)
  223281. {
  223282. }
  223283. ~ALSAAudioIODeviceType()
  223284. {
  223285. }
  223286. void scanForDevices()
  223287. {
  223288. if (hasScanned)
  223289. return;
  223290. hasScanned = true;
  223291. inputNames.clear();
  223292. inputIds.clear();
  223293. outputNames.clear();
  223294. outputIds.clear();
  223295. /* void** hints = 0;
  223296. if (snd_device_name_hint (-1, "pcm", &hints) >= 0)
  223297. {
  223298. for (void** hint = hints; *hint != 0; ++hint)
  223299. {
  223300. const String name (getHint (*hint, "NAME"));
  223301. if (name.isNotEmpty())
  223302. {
  223303. const String ioid (getHint (*hint, "IOID"));
  223304. String desc (getHint (*hint, "DESC"));
  223305. if (desc.isEmpty())
  223306. desc = name;
  223307. desc = desc.replaceCharacters ("\n\r", " ");
  223308. DBG ("name: " << name << "\ndesc: " << desc << "\nIO: " << ioid);
  223309. if (ioid.isEmpty() || ioid == "Input")
  223310. {
  223311. inputNames.add (desc);
  223312. inputIds.add (name);
  223313. }
  223314. if (ioid.isEmpty() || ioid == "Output")
  223315. {
  223316. outputNames.add (desc);
  223317. outputIds.add (name);
  223318. }
  223319. }
  223320. }
  223321. snd_device_name_free_hint (hints);
  223322. }
  223323. */
  223324. snd_ctl_t* handle = 0;
  223325. snd_ctl_card_info_t* info = 0;
  223326. snd_ctl_card_info_alloca (&info);
  223327. int cardNum = -1;
  223328. while (outputIds.size() + inputIds.size() <= 32)
  223329. {
  223330. snd_card_next (&cardNum);
  223331. if (cardNum < 0)
  223332. break;
  223333. if (snd_ctl_open (&handle, ("hw:" + String (cardNum)).toUTF8(), SND_CTL_NONBLOCK) >= 0)
  223334. {
  223335. if (snd_ctl_card_info (handle, info) >= 0)
  223336. {
  223337. String cardId (snd_ctl_card_info_get_id (info));
  223338. if (cardId.removeCharacters ("0123456789").isEmpty())
  223339. cardId = String (cardNum);
  223340. int device = -1;
  223341. for (;;)
  223342. {
  223343. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  223344. break;
  223345. String id, name;
  223346. id << "hw:" << cardId << ',' << device;
  223347. bool isInput, isOutput;
  223348. if (testDevice (id, isInput, isOutput))
  223349. {
  223350. name << snd_ctl_card_info_get_name (info);
  223351. if (name.isEmpty())
  223352. name = id;
  223353. if (isInput)
  223354. {
  223355. inputNames.add (name);
  223356. inputIds.add (id);
  223357. }
  223358. if (isOutput)
  223359. {
  223360. outputNames.add (name);
  223361. outputIds.add (id);
  223362. }
  223363. }
  223364. }
  223365. }
  223366. snd_ctl_close (handle);
  223367. }
  223368. }
  223369. inputNames.appendNumbersToDuplicates (false, true);
  223370. outputNames.appendNumbersToDuplicates (false, true);
  223371. }
  223372. const StringArray getDeviceNames (bool wantInputNames) const
  223373. {
  223374. jassert (hasScanned); // need to call scanForDevices() before doing this
  223375. return wantInputNames ? inputNames : outputNames;
  223376. }
  223377. int getDefaultDeviceIndex (bool forInput) const
  223378. {
  223379. jassert (hasScanned); // need to call scanForDevices() before doing this
  223380. return 0;
  223381. }
  223382. bool hasSeparateInputsAndOutputs() const { return true; }
  223383. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223384. {
  223385. jassert (hasScanned); // need to call scanForDevices() before doing this
  223386. ALSAAudioIODevice* d = dynamic_cast <ALSAAudioIODevice*> (device);
  223387. if (d == 0)
  223388. return -1;
  223389. return asInput ? inputIds.indexOf (d->inputId)
  223390. : outputIds.indexOf (d->outputId);
  223391. }
  223392. AudioIODevice* createDevice (const String& outputDeviceName,
  223393. const String& inputDeviceName)
  223394. {
  223395. jassert (hasScanned); // need to call scanForDevices() before doing this
  223396. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223397. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223398. String deviceName (outputIndex >= 0 ? outputDeviceName
  223399. : inputDeviceName);
  223400. if (inputIndex >= 0 || outputIndex >= 0)
  223401. return new ALSAAudioIODevice (deviceName,
  223402. inputIds [inputIndex],
  223403. outputIds [outputIndex]);
  223404. return 0;
  223405. }
  223406. juce_UseDebuggingNewOperator
  223407. private:
  223408. StringArray inputNames, outputNames, inputIds, outputIds;
  223409. bool hasScanned;
  223410. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  223411. {
  223412. unsigned int minChansOut = 0, maxChansOut = 0;
  223413. unsigned int minChansIn = 0, maxChansIn = 0;
  223414. Array <int> rates;
  223415. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  223416. DBG ("ALSA device: " + id
  223417. + " outs=" + String ((int) minChansOut) + "-" + String ((int) maxChansOut)
  223418. + " ins=" + String ((int) minChansIn) + "-" + String ((int) maxChansIn)
  223419. + " rates=" + String (rates.size()));
  223420. isInput = maxChansIn > 0;
  223421. isOutput = maxChansOut > 0;
  223422. return (isInput || isOutput) && rates.size() > 0;
  223423. }
  223424. /*static const String getHint (void* hint, const char* type)
  223425. {
  223426. char* const n = snd_device_name_get_hint (hint, type);
  223427. const String s ((const char*) n);
  223428. free (n);
  223429. return s;
  223430. }*/
  223431. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  223432. ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  223433. };
  223434. AudioIODeviceType* juce_createAudioIODeviceType_ALSA()
  223435. {
  223436. return new ALSAAudioIODeviceType();
  223437. }
  223438. #endif
  223439. /*** End of inlined file: juce_linux_Audio.cpp ***/
  223440. /*** Start of inlined file: juce_linux_JackAudio.cpp ***/
  223441. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223442. // compiled on its own).
  223443. #ifdef JUCE_INCLUDED_FILE
  223444. #if JUCE_JACK
  223445. static void* juce_libjack_handle = 0;
  223446. void* juce_load_jack_function (const char* const name)
  223447. {
  223448. if (juce_libjack_handle == 0)
  223449. return 0;
  223450. return dlsym (juce_libjack_handle, name);
  223451. }
  223452. #define JUCE_DECL_JACK_FUNCTION(return_type, fn_name, argument_types, arguments) \
  223453. typedef return_type (*fn_name##_ptr_t)argument_types; \
  223454. return_type fn_name argument_types { \
  223455. static fn_name##_ptr_t fn = 0; \
  223456. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223457. if (fn) return (*fn)arguments; \
  223458. else return 0; \
  223459. }
  223460. #define JUCE_DECL_VOID_JACK_FUNCTION(fn_name, argument_types, arguments) \
  223461. typedef void (*fn_name##_ptr_t)argument_types; \
  223462. void fn_name argument_types { \
  223463. static fn_name##_ptr_t fn = 0; \
  223464. if (fn == 0) { fn = (fn_name##_ptr_t)juce_load_jack_function(#fn_name); } \
  223465. if (fn) (*fn)arguments; \
  223466. }
  223467. 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));
  223468. JUCE_DECL_JACK_FUNCTION (int, jack_client_close, (jack_client_t *client), (client));
  223469. JUCE_DECL_JACK_FUNCTION (int, jack_activate, (jack_client_t* client), (client));
  223470. JUCE_DECL_JACK_FUNCTION (int, jack_deactivate, (jack_client_t* client), (client));
  223471. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_buffer_size, (jack_client_t* client), (client));
  223472. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_get_sample_rate, (jack_client_t* client), (client));
  223473. JUCE_DECL_VOID_JACK_FUNCTION (jack_on_shutdown, (jack_client_t* client, void (*function)(void* arg), void* arg), (client, function, arg));
  223474. JUCE_DECL_JACK_FUNCTION (void* , jack_port_get_buffer, (jack_port_t* port, jack_nframes_t nframes), (port, nframes));
  223475. JUCE_DECL_JACK_FUNCTION (jack_nframes_t, jack_port_get_total_latency, (jack_client_t* client, jack_port_t* port), (client, port));
  223476. 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));
  223477. JUCE_DECL_VOID_JACK_FUNCTION (jack_set_error_function, (void (*func)(const char*)), (func));
  223478. JUCE_DECL_JACK_FUNCTION (int, jack_set_process_callback, (jack_client_t* client, JackProcessCallback process_callback, void* arg), (client, process_callback, arg));
  223479. 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));
  223480. JUCE_DECL_JACK_FUNCTION (int, jack_connect, (jack_client_t* client, const char* source_port, const char* destination_port), (client, source_port, destination_port));
  223481. JUCE_DECL_JACK_FUNCTION (const char*, jack_port_name, (const jack_port_t* port), (port));
  223482. JUCE_DECL_JACK_FUNCTION (int, jack_set_port_connect_callback, (jack_client_t* client, JackPortConnectCallback connect_callback, void* arg), (client, connect_callback, arg));
  223483. JUCE_DECL_JACK_FUNCTION (jack_port_t* , jack_port_by_id, (jack_client_t* client, jack_port_id_t port_id), (client, port_id));
  223484. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected, (const jack_port_t* port), (port));
  223485. JUCE_DECL_JACK_FUNCTION (int, jack_port_connected_to, (const jack_port_t* port, const char* port_name), (port, port_name));
  223486. #if JUCE_DEBUG
  223487. #define JACK_LOGGING_ENABLED 1
  223488. #endif
  223489. #if JACK_LOGGING_ENABLED
  223490. namespace
  223491. {
  223492. void jack_Log (const String& s)
  223493. {
  223494. std::cerr << s << std::endl;
  223495. }
  223496. void dumpJackErrorMessage (const jack_status_t status)
  223497. {
  223498. if (status & JackServerFailed || status & JackServerError) jack_Log ("Unable to connect to JACK server");
  223499. if (status & JackVersionError) jack_Log ("Client's protocol version does not match");
  223500. if (status & JackInvalidOption) jack_Log ("The operation contained an invalid or unsupported option");
  223501. if (status & JackNameNotUnique) jack_Log ("The desired client name was not unique");
  223502. if (status & JackNoSuchClient) jack_Log ("Requested client does not exist");
  223503. if (status & JackInitFailure) jack_Log ("Unable to initialize client");
  223504. }
  223505. }
  223506. #else
  223507. #define dumpJackErrorMessage(a) {}
  223508. #define jack_Log(...) {}
  223509. #endif
  223510. #ifndef JUCE_JACK_CLIENT_NAME
  223511. #define JUCE_JACK_CLIENT_NAME "JuceJack"
  223512. #endif
  223513. class JackAudioIODevice : public AudioIODevice
  223514. {
  223515. public:
  223516. JackAudioIODevice (const String& deviceName,
  223517. const String& inputId_,
  223518. const String& outputId_)
  223519. : AudioIODevice (deviceName, "JACK"),
  223520. inputId (inputId_),
  223521. outputId (outputId_),
  223522. isOpen_ (false),
  223523. callback (0),
  223524. totalNumberOfInputChannels (0),
  223525. totalNumberOfOutputChannels (0)
  223526. {
  223527. jassert (deviceName.isNotEmpty());
  223528. jack_status_t status;
  223529. client = JUCE_NAMESPACE::jack_client_open (JUCE_JACK_CLIENT_NAME, JackNoStartServer, &status);
  223530. if (client == 0)
  223531. {
  223532. dumpJackErrorMessage (status);
  223533. }
  223534. else
  223535. {
  223536. JUCE_NAMESPACE::jack_set_error_function (errorCallback);
  223537. // open input ports
  223538. const StringArray inputChannels (getInputChannelNames());
  223539. for (int i = 0; i < inputChannels.size(); i++)
  223540. {
  223541. String inputName;
  223542. inputName << "in_" << ++totalNumberOfInputChannels;
  223543. inputPorts.add (JUCE_NAMESPACE::jack_port_register (client, inputName.toUTF8(),
  223544. JACK_DEFAULT_AUDIO_TYPE, JackPortIsInput, 0));
  223545. }
  223546. // open output ports
  223547. const StringArray outputChannels (getOutputChannelNames());
  223548. for (int i = 0; i < outputChannels.size (); i++)
  223549. {
  223550. String outputName;
  223551. outputName << "out_" << ++totalNumberOfOutputChannels;
  223552. outputPorts.add (JUCE_NAMESPACE::jack_port_register (client, outputName.toUTF8(),
  223553. JACK_DEFAULT_AUDIO_TYPE, JackPortIsOutput, 0));
  223554. }
  223555. inChans.calloc (totalNumberOfInputChannels + 2);
  223556. outChans.calloc (totalNumberOfOutputChannels + 2);
  223557. }
  223558. }
  223559. ~JackAudioIODevice()
  223560. {
  223561. close();
  223562. if (client != 0)
  223563. {
  223564. JUCE_NAMESPACE::jack_client_close (client);
  223565. client = 0;
  223566. }
  223567. }
  223568. const StringArray getChannelNames (bool forInput) const
  223569. {
  223570. StringArray names;
  223571. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */
  223572. forInput ? JackPortIsInput : JackPortIsOutput);
  223573. if (ports != 0)
  223574. {
  223575. int j = 0;
  223576. while (ports[j] != 0)
  223577. {
  223578. const String portName (ports [j++]);
  223579. if (portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223580. names.add (portName.fromFirstOccurrenceOf (":", false, false));
  223581. }
  223582. free (ports);
  223583. }
  223584. return names;
  223585. }
  223586. const StringArray getOutputChannelNames() { return getChannelNames (false); }
  223587. const StringArray getInputChannelNames() { return getChannelNames (true); }
  223588. int getNumSampleRates() { return client != 0 ? 1 : 0; }
  223589. double getSampleRate (int index) { return client != 0 ? JUCE_NAMESPACE::jack_get_sample_rate (client) : 0; }
  223590. int getNumBufferSizesAvailable() { return client != 0 ? 1 : 0; }
  223591. int getBufferSizeSamples (int index) { return getDefaultBufferSize(); }
  223592. int getDefaultBufferSize() { return client != 0 ? JUCE_NAMESPACE::jack_get_buffer_size (client) : 0; }
  223593. const String open (const BigInteger& inputChannels, const BigInteger& outputChannels,
  223594. double sampleRate, int bufferSizeSamples)
  223595. {
  223596. if (client == 0)
  223597. {
  223598. lastError = "No JACK client running";
  223599. return lastError;
  223600. }
  223601. lastError = String::empty;
  223602. close();
  223603. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, this);
  223604. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, this);
  223605. JUCE_NAMESPACE::jack_activate (client);
  223606. isOpen_ = true;
  223607. if (! inputChannels.isZero())
  223608. {
  223609. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223610. if (ports != 0)
  223611. {
  223612. const int numInputChannels = inputChannels.getHighestBit() + 1;
  223613. for (int i = 0; i < numInputChannels; ++i)
  223614. {
  223615. const String portName (ports[i]);
  223616. if (inputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223617. {
  223618. int error = JUCE_NAMESPACE::jack_connect (client, ports[i], JUCE_NAMESPACE::jack_port_name ((jack_port_t*) inputPorts[i]));
  223619. if (error != 0)
  223620. jack_Log ("Cannot connect input port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223621. }
  223622. }
  223623. free (ports);
  223624. }
  223625. }
  223626. if (! outputChannels.isZero())
  223627. {
  223628. const char** const ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223629. if (ports != 0)
  223630. {
  223631. const int numOutputChannels = outputChannels.getHighestBit() + 1;
  223632. for (int i = 0; i < numOutputChannels; ++i)
  223633. {
  223634. const String portName (ports[i]);
  223635. if (outputChannels[i] && portName.upToFirstOccurrenceOf (":", false, false) == getName())
  223636. {
  223637. int error = JUCE_NAMESPACE::jack_connect (client, JUCE_NAMESPACE::jack_port_name ((jack_port_t*) outputPorts[i]), ports[i]);
  223638. if (error != 0)
  223639. jack_Log ("Cannot connect output port " + String (i) + " (" + String (ports[i]) + "), error " + String (error));
  223640. }
  223641. }
  223642. free (ports);
  223643. }
  223644. }
  223645. return lastError;
  223646. }
  223647. void close()
  223648. {
  223649. stop();
  223650. if (client != 0)
  223651. {
  223652. JUCE_NAMESPACE::jack_deactivate (client);
  223653. JUCE_NAMESPACE::jack_set_process_callback (client, processCallback, 0);
  223654. JUCE_NAMESPACE::jack_on_shutdown (client, shutdownCallback, 0);
  223655. }
  223656. isOpen_ = false;
  223657. }
  223658. void start (AudioIODeviceCallback* newCallback)
  223659. {
  223660. if (isOpen_ && newCallback != callback)
  223661. {
  223662. if (newCallback != 0)
  223663. newCallback->audioDeviceAboutToStart (this);
  223664. AudioIODeviceCallback* const oldCallback = callback;
  223665. {
  223666. const ScopedLock sl (callbackLock);
  223667. callback = newCallback;
  223668. }
  223669. if (oldCallback != 0)
  223670. oldCallback->audioDeviceStopped();
  223671. }
  223672. }
  223673. void stop()
  223674. {
  223675. start (0);
  223676. }
  223677. bool isOpen() { return isOpen_; }
  223678. bool isPlaying() { return callback != 0; }
  223679. int getCurrentBufferSizeSamples() { return getBufferSizeSamples (0); }
  223680. double getCurrentSampleRate() { return getSampleRate (0); }
  223681. int getCurrentBitDepth() { return 32; }
  223682. const String getLastError() { return lastError; }
  223683. const BigInteger getActiveOutputChannels() const
  223684. {
  223685. BigInteger outputBits;
  223686. for (int i = 0; i < outputPorts.size(); i++)
  223687. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) outputPorts [i]))
  223688. outputBits.setBit (i);
  223689. return outputBits;
  223690. }
  223691. const BigInteger getActiveInputChannels() const
  223692. {
  223693. BigInteger inputBits;
  223694. for (int i = 0; i < inputPorts.size(); i++)
  223695. if (JUCE_NAMESPACE::jack_port_connected ((jack_port_t*) inputPorts [i]))
  223696. inputBits.setBit (i);
  223697. return inputBits;
  223698. }
  223699. int getOutputLatencyInSamples()
  223700. {
  223701. int latency = 0;
  223702. for (int i = 0; i < outputPorts.size(); i++)
  223703. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) outputPorts [i]));
  223704. return latency;
  223705. }
  223706. int getInputLatencyInSamples()
  223707. {
  223708. int latency = 0;
  223709. for (int i = 0; i < inputPorts.size(); i++)
  223710. latency = jmax (latency, (int) JUCE_NAMESPACE::jack_port_get_total_latency (client, (jack_port_t*) inputPorts [i]));
  223711. return latency;
  223712. }
  223713. String inputId, outputId;
  223714. private:
  223715. void process (const int numSamples)
  223716. {
  223717. int i, numActiveInChans = 0, numActiveOutChans = 0;
  223718. for (i = 0; i < totalNumberOfInputChannels; ++i)
  223719. {
  223720. jack_default_audio_sample_t* in
  223721. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) inputPorts.getUnchecked(i), numSamples);
  223722. if (in != 0)
  223723. inChans [numActiveInChans++] = (float*) in;
  223724. }
  223725. for (i = 0; i < totalNumberOfOutputChannels; ++i)
  223726. {
  223727. jack_default_audio_sample_t* out
  223728. = (jack_default_audio_sample_t*) JUCE_NAMESPACE::jack_port_get_buffer ((jack_port_t*) outputPorts.getUnchecked(i), numSamples);
  223729. if (out != 0)
  223730. outChans [numActiveOutChans++] = (float*) out;
  223731. }
  223732. const ScopedLock sl (callbackLock);
  223733. if (callback != 0)
  223734. {
  223735. callback->audioDeviceIOCallback (const_cast<const float**> (inChans.getData()), numActiveInChans,
  223736. outChans, numActiveOutChans, numSamples);
  223737. }
  223738. else
  223739. {
  223740. for (i = 0; i < numActiveOutChans; ++i)
  223741. zeromem (outChans[i], sizeof (float) * numSamples);
  223742. }
  223743. }
  223744. static int processCallback (jack_nframes_t nframes, void* callbackArgument)
  223745. {
  223746. if (callbackArgument != 0)
  223747. ((JackAudioIODevice*) callbackArgument)->process (nframes);
  223748. return 0;
  223749. }
  223750. static void threadInitCallback (void* callbackArgument)
  223751. {
  223752. jack_Log ("JackAudioIODevice::initialise");
  223753. }
  223754. static void shutdownCallback (void* callbackArgument)
  223755. {
  223756. jack_Log ("JackAudioIODevice::shutdown");
  223757. JackAudioIODevice* device = (JackAudioIODevice*) callbackArgument;
  223758. if (device != 0)
  223759. {
  223760. device->client = 0;
  223761. device->close();
  223762. }
  223763. }
  223764. static void errorCallback (const char* msg)
  223765. {
  223766. jack_Log ("JackAudioIODevice::errorCallback " + String (msg));
  223767. }
  223768. bool isOpen_;
  223769. jack_client_t* client;
  223770. String lastError;
  223771. AudioIODeviceCallback* callback;
  223772. CriticalSection callbackLock;
  223773. HeapBlock <float*> inChans, outChans;
  223774. int totalNumberOfInputChannels;
  223775. int totalNumberOfOutputChannels;
  223776. Array<void*> inputPorts, outputPorts;
  223777. };
  223778. class JackAudioIODeviceType : public AudioIODeviceType
  223779. {
  223780. public:
  223781. JackAudioIODeviceType()
  223782. : AudioIODeviceType ("JACK"),
  223783. hasScanned (false)
  223784. {
  223785. }
  223786. ~JackAudioIODeviceType()
  223787. {
  223788. }
  223789. void scanForDevices()
  223790. {
  223791. hasScanned = true;
  223792. inputNames.clear();
  223793. inputIds.clear();
  223794. outputNames.clear();
  223795. outputIds.clear();
  223796. if (juce_libjack_handle == 0)
  223797. {
  223798. juce_libjack_handle = dlopen ("libjack.so", RTLD_LAZY);
  223799. if (juce_libjack_handle == 0)
  223800. return;
  223801. }
  223802. // open a dummy client
  223803. jack_status_t status;
  223804. jack_client_t* client = JUCE_NAMESPACE::jack_client_open ("JuceJackDummy", JackNoStartServer, &status);
  223805. if (client == 0)
  223806. {
  223807. dumpJackErrorMessage (status);
  223808. }
  223809. else
  223810. {
  223811. // scan for output devices
  223812. const char** ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsOutput);
  223813. if (ports != 0)
  223814. {
  223815. int j = 0;
  223816. while (ports[j] != 0)
  223817. {
  223818. String clientName (ports[j]);
  223819. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223820. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223821. && ! inputNames.contains (clientName))
  223822. {
  223823. inputNames.add (clientName);
  223824. inputIds.add (ports [j]);
  223825. }
  223826. ++j;
  223827. }
  223828. free (ports);
  223829. }
  223830. // scan for input devices
  223831. ports = JUCE_NAMESPACE::jack_get_ports (client, 0, 0, /* JackPortIsPhysical | */ JackPortIsInput);
  223832. if (ports != 0)
  223833. {
  223834. int j = 0;
  223835. while (ports[j] != 0)
  223836. {
  223837. String clientName (ports[j]);
  223838. clientName = clientName.upToFirstOccurrenceOf (":", false, false);
  223839. if (clientName != String (JUCE_JACK_CLIENT_NAME)
  223840. && ! outputNames.contains (clientName))
  223841. {
  223842. outputNames.add (clientName);
  223843. outputIds.add (ports [j]);
  223844. }
  223845. ++j;
  223846. }
  223847. free (ports);
  223848. }
  223849. JUCE_NAMESPACE::jack_client_close (client);
  223850. }
  223851. }
  223852. const StringArray getDeviceNames (bool wantInputNames) const
  223853. {
  223854. jassert (hasScanned); // need to call scanForDevices() before doing this
  223855. return wantInputNames ? inputNames : outputNames;
  223856. }
  223857. int getDefaultDeviceIndex (bool forInput) const
  223858. {
  223859. jassert (hasScanned); // need to call scanForDevices() before doing this
  223860. return 0;
  223861. }
  223862. bool hasSeparateInputsAndOutputs() const { return true; }
  223863. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  223864. {
  223865. jassert (hasScanned); // need to call scanForDevices() before doing this
  223866. JackAudioIODevice* d = dynamic_cast <JackAudioIODevice*> (device);
  223867. if (d == 0)
  223868. return -1;
  223869. return asInput ? inputIds.indexOf (d->inputId)
  223870. : outputIds.indexOf (d->outputId);
  223871. }
  223872. AudioIODevice* createDevice (const String& outputDeviceName,
  223873. const String& inputDeviceName)
  223874. {
  223875. jassert (hasScanned); // need to call scanForDevices() before doing this
  223876. const int inputIndex = inputNames.indexOf (inputDeviceName);
  223877. const int outputIndex = outputNames.indexOf (outputDeviceName);
  223878. if (inputIndex >= 0 || outputIndex >= 0)
  223879. return new JackAudioIODevice (outputIndex >= 0 ? outputDeviceName
  223880. : inputDeviceName,
  223881. inputIds [inputIndex],
  223882. outputIds [outputIndex]);
  223883. return 0;
  223884. }
  223885. juce_UseDebuggingNewOperator
  223886. private:
  223887. StringArray inputNames, outputNames, inputIds, outputIds;
  223888. bool hasScanned;
  223889. JackAudioIODeviceType (const JackAudioIODeviceType&);
  223890. JackAudioIODeviceType& operator= (const JackAudioIODeviceType&);
  223891. };
  223892. AudioIODeviceType* juce_createAudioIODeviceType_JACK()
  223893. {
  223894. return new JackAudioIODeviceType();
  223895. }
  223896. #else // if JACK is turned off..
  223897. AudioIODeviceType* juce_createAudioIODeviceType_JACK() { return 0; }
  223898. #endif
  223899. #endif
  223900. /*** End of inlined file: juce_linux_JackAudio.cpp ***/
  223901. /*** Start of inlined file: juce_linux_Midi.cpp ***/
  223902. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  223903. // compiled on its own).
  223904. #if JUCE_INCLUDED_FILE
  223905. #if JUCE_ALSA
  223906. namespace
  223907. {
  223908. snd_seq_t* iterateMidiDevices (const bool forInput,
  223909. StringArray& deviceNamesFound,
  223910. const int deviceIndexToOpen)
  223911. {
  223912. snd_seq_t* returnedHandle = 0;
  223913. snd_seq_t* seqHandle;
  223914. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223915. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223916. {
  223917. snd_seq_system_info_t* systemInfo;
  223918. snd_seq_client_info_t* clientInfo;
  223919. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  223920. {
  223921. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  223922. && snd_seq_client_info_malloc (&clientInfo) == 0)
  223923. {
  223924. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  223925. while (--numClients >= 0 && returnedHandle == 0)
  223926. {
  223927. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  223928. {
  223929. snd_seq_port_info_t* portInfo;
  223930. if (snd_seq_port_info_malloc (&portInfo) == 0)
  223931. {
  223932. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  223933. const int client = snd_seq_client_info_get_client (clientInfo);
  223934. snd_seq_port_info_set_client (portInfo, client);
  223935. snd_seq_port_info_set_port (portInfo, -1);
  223936. while (--numPorts >= 0)
  223937. {
  223938. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  223939. && (snd_seq_port_info_get_capability (portInfo)
  223940. & (forInput ? SND_SEQ_PORT_CAP_READ
  223941. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  223942. {
  223943. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  223944. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  223945. {
  223946. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  223947. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  223948. if (sourcePort != -1)
  223949. {
  223950. snd_seq_set_client_name (seqHandle,
  223951. forInput ? "Juce Midi Input"
  223952. : "Juce Midi Output");
  223953. const int portId
  223954. = snd_seq_create_simple_port (seqHandle,
  223955. forInput ? "Juce Midi In Port"
  223956. : "Juce Midi Out Port",
  223957. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223958. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223959. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223960. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  223961. returnedHandle = seqHandle;
  223962. }
  223963. }
  223964. }
  223965. }
  223966. snd_seq_port_info_free (portInfo);
  223967. }
  223968. }
  223969. }
  223970. snd_seq_client_info_free (clientInfo);
  223971. }
  223972. snd_seq_system_info_free (systemInfo);
  223973. }
  223974. if (returnedHandle == 0)
  223975. snd_seq_close (seqHandle);
  223976. }
  223977. deviceNamesFound.appendNumbersToDuplicates (true, true);
  223978. return returnedHandle;
  223979. }
  223980. snd_seq_t* createMidiDevice (const bool forInput, const String& deviceNameToOpen)
  223981. {
  223982. snd_seq_t* seqHandle = 0;
  223983. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  223984. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  223985. {
  223986. snd_seq_set_client_name (seqHandle,
  223987. (deviceNameToOpen + (forInput ? " Input" : " Output")).toCString());
  223988. const int portId
  223989. = snd_seq_create_simple_port (seqHandle,
  223990. forInput ? "in"
  223991. : "out",
  223992. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  223993. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  223994. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  223995. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  223996. if (portId < 0)
  223997. {
  223998. snd_seq_close (seqHandle);
  223999. seqHandle = 0;
  224000. }
  224001. }
  224002. return seqHandle;
  224003. }
  224004. }
  224005. class MidiOutputDevice
  224006. {
  224007. public:
  224008. MidiOutputDevice (MidiOutput* const midiOutput_,
  224009. snd_seq_t* const seqHandle_)
  224010. :
  224011. midiOutput (midiOutput_),
  224012. seqHandle (seqHandle_),
  224013. maxEventSize (16 * 1024)
  224014. {
  224015. jassert (seqHandle != 0 && midiOutput != 0);
  224016. snd_midi_event_new (maxEventSize, &midiParser);
  224017. }
  224018. ~MidiOutputDevice()
  224019. {
  224020. snd_midi_event_free (midiParser);
  224021. snd_seq_close (seqHandle);
  224022. }
  224023. void sendMessageNow (const MidiMessage& message)
  224024. {
  224025. if (message.getRawDataSize() > maxEventSize)
  224026. {
  224027. maxEventSize = message.getRawDataSize();
  224028. snd_midi_event_free (midiParser);
  224029. snd_midi_event_new (maxEventSize, &midiParser);
  224030. }
  224031. snd_seq_event_t event;
  224032. snd_seq_ev_clear (&event);
  224033. snd_midi_event_encode (midiParser,
  224034. message.getRawData(),
  224035. message.getRawDataSize(),
  224036. &event);
  224037. snd_midi_event_reset_encode (midiParser);
  224038. snd_seq_ev_set_source (&event, 0);
  224039. snd_seq_ev_set_subs (&event);
  224040. snd_seq_ev_set_direct (&event);
  224041. snd_seq_event_output (seqHandle, &event);
  224042. snd_seq_drain_output (seqHandle);
  224043. }
  224044. juce_UseDebuggingNewOperator
  224045. private:
  224046. MidiOutput* const midiOutput;
  224047. snd_seq_t* const seqHandle;
  224048. snd_midi_event_t* midiParser;
  224049. int maxEventSize;
  224050. };
  224051. const StringArray MidiOutput::getDevices()
  224052. {
  224053. StringArray devices;
  224054. iterateMidiDevices (false, devices, -1);
  224055. return devices;
  224056. }
  224057. int MidiOutput::getDefaultDeviceIndex()
  224058. {
  224059. return 0;
  224060. }
  224061. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  224062. {
  224063. MidiOutput* newDevice = 0;
  224064. StringArray devices;
  224065. snd_seq_t* const handle = iterateMidiDevices (false, devices, deviceIndex);
  224066. if (handle != 0)
  224067. {
  224068. newDevice = new MidiOutput();
  224069. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  224070. }
  224071. return newDevice;
  224072. }
  224073. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  224074. {
  224075. MidiOutput* newDevice = 0;
  224076. snd_seq_t* const handle = createMidiDevice (false, deviceName);
  224077. if (handle != 0)
  224078. {
  224079. newDevice = new MidiOutput();
  224080. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  224081. }
  224082. return newDevice;
  224083. }
  224084. MidiOutput::~MidiOutput()
  224085. {
  224086. delete static_cast <MidiOutputDevice*> (internal);
  224087. }
  224088. void MidiOutput::reset()
  224089. {
  224090. }
  224091. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  224092. {
  224093. return false;
  224094. }
  224095. void MidiOutput::setVolume (float leftVol, float rightVol)
  224096. {
  224097. }
  224098. void MidiOutput::sendMessageNow (const MidiMessage& message)
  224099. {
  224100. static_cast <MidiOutputDevice*> (internal)->sendMessageNow (message);
  224101. }
  224102. class MidiInputThread : public Thread
  224103. {
  224104. public:
  224105. MidiInputThread (MidiInput* const midiInput_,
  224106. snd_seq_t* const seqHandle_,
  224107. MidiInputCallback* const callback_)
  224108. : Thread ("Juce MIDI Input"),
  224109. midiInput (midiInput_),
  224110. seqHandle (seqHandle_),
  224111. callback (callback_)
  224112. {
  224113. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  224114. }
  224115. ~MidiInputThread()
  224116. {
  224117. snd_seq_close (seqHandle);
  224118. }
  224119. void run()
  224120. {
  224121. const int maxEventSize = 16 * 1024;
  224122. snd_midi_event_t* midiParser;
  224123. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  224124. {
  224125. HeapBlock <uint8> buffer (maxEventSize);
  224126. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  224127. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  224128. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  224129. while (! threadShouldExit())
  224130. {
  224131. if (poll (pfd, numPfds, 500) > 0)
  224132. {
  224133. snd_seq_event_t* inputEvent = 0;
  224134. snd_seq_nonblock (seqHandle, 1);
  224135. do
  224136. {
  224137. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  224138. {
  224139. // xxx what about SYSEXes that are too big for the buffer?
  224140. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  224141. snd_midi_event_reset_decode (midiParser);
  224142. if (numBytes > 0)
  224143. {
  224144. const MidiMessage message ((const uint8*) buffer,
  224145. numBytes,
  224146. Time::getMillisecondCounter() * 0.001);
  224147. callback->handleIncomingMidiMessage (midiInput, message);
  224148. }
  224149. snd_seq_free_event (inputEvent);
  224150. }
  224151. }
  224152. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  224153. snd_seq_free_event (inputEvent);
  224154. }
  224155. }
  224156. snd_midi_event_free (midiParser);
  224157. }
  224158. };
  224159. juce_UseDebuggingNewOperator
  224160. private:
  224161. MidiInput* const midiInput;
  224162. snd_seq_t* const seqHandle;
  224163. MidiInputCallback* const callback;
  224164. };
  224165. MidiInput::MidiInput (const String& name_)
  224166. : name (name_),
  224167. internal (0)
  224168. {
  224169. }
  224170. MidiInput::~MidiInput()
  224171. {
  224172. stop();
  224173. delete static_cast <MidiInputThread*> (internal);
  224174. }
  224175. void MidiInput::start()
  224176. {
  224177. static_cast <MidiInputThread*> (internal)->startThread();
  224178. }
  224179. void MidiInput::stop()
  224180. {
  224181. static_cast <MidiInputThread*> (internal)->stopThread (3000);
  224182. }
  224183. int MidiInput::getDefaultDeviceIndex()
  224184. {
  224185. return 0;
  224186. }
  224187. const StringArray MidiInput::getDevices()
  224188. {
  224189. StringArray devices;
  224190. iterateMidiDevices (true, devices, -1);
  224191. return devices;
  224192. }
  224193. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  224194. {
  224195. MidiInput* newDevice = 0;
  224196. StringArray devices;
  224197. snd_seq_t* const handle = iterateMidiDevices (true, devices, deviceIndex);
  224198. if (handle != 0)
  224199. {
  224200. newDevice = new MidiInput (devices [deviceIndex]);
  224201. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224202. }
  224203. return newDevice;
  224204. }
  224205. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  224206. {
  224207. MidiInput* newDevice = 0;
  224208. snd_seq_t* const handle = createMidiDevice (true, deviceName);
  224209. if (handle != 0)
  224210. {
  224211. newDevice = new MidiInput (deviceName);
  224212. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  224213. }
  224214. return newDevice;
  224215. }
  224216. #else
  224217. // (These are just stub functions if ALSA is unavailable...)
  224218. const StringArray MidiOutput::getDevices() { return StringArray(); }
  224219. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  224220. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  224221. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  224222. MidiOutput::~MidiOutput() {}
  224223. void MidiOutput::reset() {}
  224224. bool MidiOutput::getVolume (float&, float&) { return false; }
  224225. void MidiOutput::setVolume (float, float) {}
  224226. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  224227. MidiInput::MidiInput (const String& name_) : name (name_), internal (0) {}
  224228. MidiInput::~MidiInput() {}
  224229. void MidiInput::start() {}
  224230. void MidiInput::stop() {}
  224231. int MidiInput::getDefaultDeviceIndex() { return 0; }
  224232. const StringArray MidiInput::getDevices() { return StringArray(); }
  224233. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  224234. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  224235. #endif
  224236. #endif
  224237. /*** End of inlined file: juce_linux_Midi.cpp ***/
  224238. /*** Start of inlined file: juce_linux_AudioCDReader.cpp ***/
  224239. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224240. // compiled on its own).
  224241. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  224242. AudioCDReader::AudioCDReader()
  224243. : AudioFormatReader (0, "CD Audio")
  224244. {
  224245. }
  224246. const StringArray AudioCDReader::getAvailableCDNames()
  224247. {
  224248. StringArray names;
  224249. return names;
  224250. }
  224251. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  224252. {
  224253. return 0;
  224254. }
  224255. AudioCDReader::~AudioCDReader()
  224256. {
  224257. }
  224258. void AudioCDReader::refreshTrackLengths()
  224259. {
  224260. }
  224261. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  224262. int64 startSampleInFile, int numSamples)
  224263. {
  224264. return false;
  224265. }
  224266. bool AudioCDReader::isCDStillPresent() const
  224267. {
  224268. return false;
  224269. }
  224270. bool AudioCDReader::isTrackAudio (int trackNum) const
  224271. {
  224272. return false;
  224273. }
  224274. void AudioCDReader::enableIndexScanning (bool b)
  224275. {
  224276. }
  224277. int AudioCDReader::getLastIndex() const
  224278. {
  224279. return 0;
  224280. }
  224281. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  224282. {
  224283. return Array<int>();
  224284. }
  224285. #endif
  224286. /*** End of inlined file: juce_linux_AudioCDReader.cpp ***/
  224287. /*** Start of inlined file: juce_linux_FileChooser.cpp ***/
  224288. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224289. // compiled on its own).
  224290. #if JUCE_INCLUDED_FILE
  224291. void FileChooser::showPlatformDialog (Array<File>& results,
  224292. const String& title,
  224293. const File& file,
  224294. const String& filters,
  224295. bool isDirectory,
  224296. bool selectsFiles,
  224297. bool isSave,
  224298. bool warnAboutOverwritingExistingFiles,
  224299. bool selectMultipleFiles,
  224300. FilePreviewComponent* previewComponent)
  224301. {
  224302. const String separator (":");
  224303. String command ("zenity --file-selection");
  224304. if (title.isNotEmpty())
  224305. command << " --title=\"" << title << "\"";
  224306. if (file != File::nonexistent)
  224307. command << " --filename=\"" << file.getFullPathName () << "\"";
  224308. if (isDirectory)
  224309. command << " --directory";
  224310. if (isSave)
  224311. command << " --save";
  224312. if (selectMultipleFiles)
  224313. command << " --multiple --separator=\"" << separator << "\"";
  224314. command << " 2>&1";
  224315. MemoryOutputStream result;
  224316. int status = -1;
  224317. FILE* stream = popen (command.toUTF8(), "r");
  224318. if (stream != 0)
  224319. {
  224320. for (;;)
  224321. {
  224322. char buffer [1024];
  224323. const int bytesRead = fread (buffer, 1, sizeof (buffer), stream);
  224324. if (bytesRead <= 0)
  224325. break;
  224326. result.write (buffer, bytesRead);
  224327. }
  224328. status = pclose (stream);
  224329. }
  224330. if (status == 0)
  224331. {
  224332. StringArray tokens;
  224333. if (selectMultipleFiles)
  224334. tokens.addTokens (result.toUTF8(), separator, String::empty);
  224335. else
  224336. tokens.add (result.toUTF8());
  224337. for (int i = 0; i < tokens.size(); i++)
  224338. results.add (File (tokens[i]));
  224339. return;
  224340. }
  224341. //xxx ain't got one!
  224342. jassertfalse;
  224343. }
  224344. #endif
  224345. /*** End of inlined file: juce_linux_FileChooser.cpp ***/
  224346. /*** Start of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224347. // (This file gets included by juce_linux_NativeCode.cpp, rather than being
  224348. // compiled on its own).
  224349. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  224350. /*
  224351. Sorry.. This class isn't implemented on Linux!
  224352. */
  224353. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  224354. : browser (0),
  224355. blankPageShown (false),
  224356. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  224357. {
  224358. setOpaque (true);
  224359. }
  224360. WebBrowserComponent::~WebBrowserComponent()
  224361. {
  224362. }
  224363. void WebBrowserComponent::goToURL (const String& url,
  224364. const StringArray* headers,
  224365. const MemoryBlock* postData)
  224366. {
  224367. lastURL = url;
  224368. lastHeaders.clear();
  224369. if (headers != 0)
  224370. lastHeaders = *headers;
  224371. lastPostData.setSize (0);
  224372. if (postData != 0)
  224373. lastPostData = *postData;
  224374. blankPageShown = false;
  224375. }
  224376. void WebBrowserComponent::stop()
  224377. {
  224378. }
  224379. void WebBrowserComponent::goBack()
  224380. {
  224381. lastURL = String::empty;
  224382. blankPageShown = false;
  224383. }
  224384. void WebBrowserComponent::goForward()
  224385. {
  224386. lastURL = String::empty;
  224387. }
  224388. void WebBrowserComponent::refresh()
  224389. {
  224390. }
  224391. void WebBrowserComponent::paint (Graphics& g)
  224392. {
  224393. g.fillAll (Colours::white);
  224394. }
  224395. void WebBrowserComponent::checkWindowAssociation()
  224396. {
  224397. }
  224398. void WebBrowserComponent::reloadLastURL()
  224399. {
  224400. if (lastURL.isNotEmpty())
  224401. {
  224402. goToURL (lastURL, &lastHeaders, &lastPostData);
  224403. lastURL = String::empty;
  224404. }
  224405. }
  224406. void WebBrowserComponent::parentHierarchyChanged()
  224407. {
  224408. checkWindowAssociation();
  224409. }
  224410. void WebBrowserComponent::resized()
  224411. {
  224412. }
  224413. void WebBrowserComponent::visibilityChanged()
  224414. {
  224415. checkWindowAssociation();
  224416. }
  224417. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  224418. {
  224419. return true;
  224420. }
  224421. #endif
  224422. /*** End of inlined file: juce_linux_WebBrowserComponent.cpp ***/
  224423. #endif
  224424. END_JUCE_NAMESPACE
  224425. #endif
  224426. /*** End of inlined file: juce_linux_NativeCode.cpp ***/
  224427. #endif
  224428. #if JUCE_MAC || JUCE_IPHONE
  224429. /*** Start of inlined file: juce_mac_NativeCode.mm ***/
  224430. /*
  224431. This file wraps together all the mac-specific code, so that
  224432. we can include all the native headers just once, and compile all our
  224433. platform-specific stuff in one big lump, keeping it out of the way of
  224434. the rest of the codebase.
  224435. */
  224436. #if JUCE_MAC || JUCE_IOS
  224437. BEGIN_JUCE_NAMESPACE
  224438. #undef Point
  224439. namespace
  224440. {
  224441. template <class RectType>
  224442. const Rectangle<int> convertToRectInt (const RectType& r)
  224443. {
  224444. return Rectangle<int> ((int) r.origin.x, (int) r.origin.y, (int) r.size.width, (int) r.size.height);
  224445. }
  224446. template <class RectType>
  224447. const Rectangle<float> convertToRectFloat (const RectType& r)
  224448. {
  224449. return Rectangle<float> (r.origin.x, r.origin.y, r.size.width, r.size.height);
  224450. }
  224451. template <class RectType>
  224452. CGRect convertToCGRect (const RectType& r)
  224453. {
  224454. return CGRectMake ((CGFloat) r.getX(), (CGFloat) r.getY(), (CGFloat) r.getWidth(), (CGFloat) r.getHeight());
  224455. }
  224456. }
  224457. #define JUCE_INCLUDED_FILE 1
  224458. // Now include the actual code files..
  224459. /*** Start of inlined file: juce_mac_ObjCSuffix.h ***/
  224460. /** This suffix is used for naming all Obj-C classes that are used inside juce.
  224461. Because of the flat naming structure used by Obj-C, you can get horrible situations where
  224462. two DLLs are loaded into a host, each of which uses classes with the same names, and these get
  224463. cross-linked so that when you make a call to a class that you thought was private, it ends up
  224464. actually calling into a similarly named class in the other module's address space.
  224465. By changing this macro to a unique value, you ensure that all the obj-C classes in your app
  224466. have unique names, and should avoid this problem.
  224467. If you're using the amalgamated version, you can just set this macro to something unique before
  224468. you include juce_amalgamated.cpp.
  224469. */
  224470. #ifndef JUCE_ObjCExtraSuffix
  224471. #define JUCE_ObjCExtraSuffix 3
  224472. #endif
  224473. #define appendMacro1(a, b, c, d, e) a ## _ ## b ## _ ## c ## _ ## d ## _ ## e
  224474. #define appendMacro2(a, b, c, d, e) appendMacro1(a, b, c, d, e)
  224475. #define MakeObjCClassName(rootName) appendMacro2 (rootName, JUCE_MAJOR_VERSION, JUCE_MINOR_VERSION, JUCE_BUILDNUMBER, JUCE_ObjCExtraSuffix)
  224476. /*** End of inlined file: juce_mac_ObjCSuffix.h ***/
  224477. /*** Start of inlined file: juce_mac_Strings.mm ***/
  224478. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224479. // compiled on its own).
  224480. #if JUCE_INCLUDED_FILE
  224481. namespace
  224482. {
  224483. const String nsStringToJuce (NSString* s)
  224484. {
  224485. return String::fromUTF8 ([s UTF8String]);
  224486. }
  224487. NSString* juceStringToNS (const String& s)
  224488. {
  224489. return [NSString stringWithUTF8String: s.toUTF8()];
  224490. }
  224491. const String convertUTF16ToString (const UniChar* utf16)
  224492. {
  224493. String s;
  224494. while (*utf16 != 0)
  224495. s += (juce_wchar) *utf16++;
  224496. return s;
  224497. }
  224498. }
  224499. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  224500. {
  224501. String result;
  224502. if (cfString != 0)
  224503. {
  224504. CFRange range = { 0, CFStringGetLength (cfString) };
  224505. HeapBlock <UniChar> u (range.length + 1);
  224506. CFStringGetCharacters (cfString, range, u);
  224507. u[range.length] = 0;
  224508. result = convertUTF16ToString (u);
  224509. }
  224510. return result;
  224511. }
  224512. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  224513. {
  224514. const int len = s.length();
  224515. HeapBlock <UniChar> temp (len + 2);
  224516. for (int i = 0; i <= len; ++i)
  224517. temp[i] = s[i];
  224518. return CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  224519. }
  224520. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  224521. {
  224522. #if JUCE_IOS
  224523. const ScopedAutoReleasePool pool;
  224524. return nsStringToJuce ([juceStringToNS (s) precomposedStringWithCanonicalMapping]);
  224525. #else
  224526. UnicodeMapping map;
  224527. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224528. kUnicodeNoSubset,
  224529. kTextEncodingDefaultFormat);
  224530. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  224531. kUnicodeCanonicalCompVariant,
  224532. kTextEncodingDefaultFormat);
  224533. map.mappingVersion = kUnicodeUseLatestMapping;
  224534. UnicodeToTextInfo conversionInfo = 0;
  224535. String result;
  224536. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  224537. {
  224538. const int len = s.length();
  224539. HeapBlock <UniChar> tempIn, tempOut;
  224540. tempIn.calloc (len + 2);
  224541. tempOut.calloc (len + 2);
  224542. for (int i = 0; i <= len; ++i)
  224543. tempIn[i] = s[i];
  224544. ByteCount bytesRead = 0;
  224545. ByteCount outputBufferSize = 0;
  224546. if (ConvertFromUnicodeToText (conversionInfo,
  224547. len * sizeof (UniChar), tempIn,
  224548. kUnicodeDefaultDirectionMask,
  224549. 0, 0, 0, 0,
  224550. len * sizeof (UniChar), &bytesRead,
  224551. &outputBufferSize, tempOut) == noErr)
  224552. {
  224553. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  224554. juce_wchar* t = result;
  224555. unsigned int i;
  224556. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  224557. t[i] = (juce_wchar) tempOut[i];
  224558. t[i] = 0;
  224559. }
  224560. DisposeUnicodeToTextInfo (&conversionInfo);
  224561. }
  224562. return result;
  224563. #endif
  224564. }
  224565. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224566. void SystemClipboard::copyTextToClipboard (const String& text)
  224567. {
  224568. #if JUCE_IOS
  224569. [[UIPasteboard generalPasteboard] setValue: juceStringToNS (text)
  224570. forPasteboardType: @"public.text"];
  224571. #else
  224572. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  224573. owner: nil];
  224574. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  224575. forType: NSStringPboardType];
  224576. #endif
  224577. }
  224578. const String SystemClipboard::getTextFromClipboard()
  224579. {
  224580. #if JUCE_IOS
  224581. NSString* text = [[UIPasteboard generalPasteboard] valueForPasteboardType: @"public.text"];
  224582. #else
  224583. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  224584. #endif
  224585. return text == 0 ? String::empty
  224586. : nsStringToJuce (text);
  224587. }
  224588. #endif
  224589. #endif
  224590. /*** End of inlined file: juce_mac_Strings.mm ***/
  224591. /*** Start of inlined file: juce_mac_SystemStats.mm ***/
  224592. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224593. // compiled on its own).
  224594. #if JUCE_INCLUDED_FILE
  224595. namespace SystemStatsHelpers
  224596. {
  224597. static int64 highResTimerFrequency = 0;
  224598. static double highResTimerToMillisecRatio = 0;
  224599. #if JUCE_INTEL
  224600. static void juce_getCpuVendor (char* const v) throw()
  224601. {
  224602. int vendor[4];
  224603. zerostruct (vendor);
  224604. int dummy = 0;
  224605. asm ("mov %%ebx, %%esi \n\t"
  224606. "cpuid \n\t"
  224607. "xchg %%esi, %%ebx"
  224608. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  224609. memcpy (v, vendor, 16);
  224610. }
  224611. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures)
  224612. {
  224613. unsigned int cpu = 0;
  224614. unsigned int ext = 0;
  224615. unsigned int family = 0;
  224616. unsigned int dummy = 0;
  224617. asm ("mov %%ebx, %%esi \n\t"
  224618. "cpuid \n\t"
  224619. "xchg %%esi, %%ebx"
  224620. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  224621. familyModel = family;
  224622. extFeatures = ext;
  224623. return cpu;
  224624. }
  224625. #endif
  224626. }
  224627. void SystemStats::initialiseStats()
  224628. {
  224629. using namespace SystemStatsHelpers;
  224630. static bool initialised = false;
  224631. if (! initialised)
  224632. {
  224633. initialised = true;
  224634. #if JUCE_MAC
  224635. [NSApplication sharedApplication];
  224636. #endif
  224637. #if JUCE_INTEL
  224638. unsigned int familyModel, extFeatures;
  224639. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  224640. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  224641. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  224642. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  224643. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  224644. #else
  224645. cpuFlags.hasMMX = false;
  224646. cpuFlags.hasSSE = false;
  224647. cpuFlags.hasSSE2 = false;
  224648. cpuFlags.has3DNow = false;
  224649. #endif
  224650. #if JUCE_IOS || (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5)
  224651. cpuFlags.numCpus = (int) [[NSProcessInfo processInfo] activeProcessorCount];
  224652. #else
  224653. cpuFlags.numCpus = (int) MPProcessors();
  224654. #endif
  224655. mach_timebase_info_data_t timebase;
  224656. (void) mach_timebase_info (&timebase);
  224657. highResTimerFrequency = (int64) (1.0e9 * timebase.denom / timebase.numer);
  224658. highResTimerToMillisecRatio = timebase.numer / (1.0e6 * timebase.denom);
  224659. String s (SystemStats::getJUCEVersion());
  224660. rlimit lim;
  224661. getrlimit (RLIMIT_NOFILE, &lim);
  224662. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  224663. setrlimit (RLIMIT_NOFILE, &lim);
  224664. }
  224665. }
  224666. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType()
  224667. {
  224668. return MacOSX;
  224669. }
  224670. const String SystemStats::getOperatingSystemName()
  224671. {
  224672. return "Mac OS X";
  224673. }
  224674. #if ! JUCE_IOS
  224675. int PlatformUtilities::getOSXMinorVersionNumber()
  224676. {
  224677. SInt32 versionMinor = 0;
  224678. OSErr err = Gestalt (gestaltSystemVersionMinor, &versionMinor);
  224679. (void) err;
  224680. jassert (err == noErr);
  224681. return (int) versionMinor;
  224682. }
  224683. #endif
  224684. bool SystemStats::isOperatingSystem64Bit()
  224685. {
  224686. #if JUCE_IOS
  224687. return false;
  224688. #elif JUCE_64BIT
  224689. return true;
  224690. #else
  224691. return PlatformUtilities::getOSXMinorVersionNumber() >= 6;
  224692. #endif
  224693. }
  224694. int SystemStats::getMemorySizeInMegabytes()
  224695. {
  224696. uint64 mem = 0;
  224697. size_t memSize = sizeof (mem);
  224698. int mib[] = { CTL_HW, HW_MEMSIZE };
  224699. sysctl (mib, 2, &mem, &memSize, 0, 0);
  224700. return (int) (mem / (1024 * 1024));
  224701. }
  224702. const String SystemStats::getCpuVendor()
  224703. {
  224704. #if JUCE_INTEL
  224705. char v [16];
  224706. SystemStatsHelpers::juce_getCpuVendor (v);
  224707. return String (v, 16);
  224708. #else
  224709. return String::empty;
  224710. #endif
  224711. }
  224712. int SystemStats::getCpuSpeedInMegaherz()
  224713. {
  224714. uint64 speedHz = 0;
  224715. size_t speedSize = sizeof (speedHz);
  224716. int mib[] = { CTL_HW, HW_CPU_FREQ };
  224717. sysctl (mib, 2, &speedHz, &speedSize, 0, 0);
  224718. #if JUCE_BIG_ENDIAN
  224719. if (speedSize == 4)
  224720. speedHz >>= 32;
  224721. #endif
  224722. return (int) (speedHz / 1000000);
  224723. }
  224724. const String SystemStats::getLogonName()
  224725. {
  224726. return nsStringToJuce (NSUserName());
  224727. }
  224728. const String SystemStats::getFullUserName()
  224729. {
  224730. return nsStringToJuce (NSFullUserName());
  224731. }
  224732. uint32 juce_millisecondsSinceStartup() throw()
  224733. {
  224734. return (uint32) (mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio);
  224735. }
  224736. double Time::getMillisecondCounterHiRes() throw()
  224737. {
  224738. return mach_absolute_time() * SystemStatsHelpers::highResTimerToMillisecRatio;
  224739. }
  224740. int64 Time::getHighResolutionTicks() throw()
  224741. {
  224742. return (int64) mach_absolute_time();
  224743. }
  224744. int64 Time::getHighResolutionTicksPerSecond() throw()
  224745. {
  224746. return SystemStatsHelpers::highResTimerFrequency;
  224747. }
  224748. bool Time::setSystemTimeToThisTime() const
  224749. {
  224750. jassertfalse;
  224751. return false;
  224752. }
  224753. int SystemStats::getPageSize()
  224754. {
  224755. return (int) NSPageSize();
  224756. }
  224757. void PlatformUtilities::fpuReset()
  224758. {
  224759. }
  224760. #endif
  224761. /*** End of inlined file: juce_mac_SystemStats.mm ***/
  224762. /*** Start of inlined file: juce_mac_Network.mm ***/
  224763. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224764. // compiled on its own).
  224765. #if JUCE_INCLUDED_FILE
  224766. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian)
  224767. {
  224768. #ifndef IFT_ETHER
  224769. #define IFT_ETHER 6
  224770. #endif
  224771. ifaddrs* addrs = 0;
  224772. int numResults = 0;
  224773. if (getifaddrs (&addrs) == 0)
  224774. {
  224775. const ifaddrs* cursor = addrs;
  224776. while (cursor != 0 && numResults < maxNum)
  224777. {
  224778. sockaddr_storage* sto = (sockaddr_storage*) cursor->ifa_addr;
  224779. if (sto->ss_family == AF_LINK)
  224780. {
  224781. const sockaddr_dl* const sadd = (const sockaddr_dl*) cursor->ifa_addr;
  224782. if (sadd->sdl_type == IFT_ETHER)
  224783. {
  224784. const uint8* const addr = ((const uint8*) sadd->sdl_data) + sadd->sdl_nlen;
  224785. uint64 a = 0;
  224786. for (int i = 6; --i >= 0;)
  224787. a = (a << 8) | addr [littleEndian ? i : (5 - i)];
  224788. *addresses++ = (int64) a;
  224789. ++numResults;
  224790. }
  224791. }
  224792. cursor = cursor->ifa_next;
  224793. }
  224794. freeifaddrs (addrs);
  224795. }
  224796. return numResults;
  224797. }
  224798. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  224799. const String& emailSubject,
  224800. const String& bodyText,
  224801. const StringArray& filesToAttach)
  224802. {
  224803. #if JUCE_IOS
  224804. //xxx probably need to use MFMailComposeViewController
  224805. jassertfalse;
  224806. return false;
  224807. #else
  224808. const ScopedAutoReleasePool pool;
  224809. String script;
  224810. script << "tell application \"Mail\"\r\n"
  224811. "set newMessage to make new outgoing message with properties {subject:\""
  224812. << emailSubject.replace ("\"", "\\\"")
  224813. << "\", content:\""
  224814. << bodyText.replace ("\"", "\\\"")
  224815. << "\" & return & return}\r\n"
  224816. "tell newMessage\r\n"
  224817. "set visible to true\r\n"
  224818. "set sender to \"sdfsdfsdfewf\"\r\n"
  224819. "make new to recipient at end of to recipients with properties {address:\""
  224820. << targetEmailAddress
  224821. << "\"}\r\n";
  224822. for (int i = 0; i < filesToAttach.size(); ++i)
  224823. {
  224824. script << "tell content\r\n"
  224825. "make new attachment with properties {file name:\""
  224826. << filesToAttach[i].replace ("\"", "\\\"")
  224827. << "\"} at after the last paragraph\r\n"
  224828. "end tell\r\n";
  224829. }
  224830. script << "end tell\r\n"
  224831. "end tell\r\n";
  224832. NSAppleScript* s = [[NSAppleScript alloc]
  224833. initWithSource: juceStringToNS (script)];
  224834. NSDictionary* error = 0;
  224835. const bool ok = [s executeAndReturnError: &error] != nil;
  224836. [s release];
  224837. return ok;
  224838. #endif
  224839. }
  224840. END_JUCE_NAMESPACE
  224841. using namespace JUCE_NAMESPACE;
  224842. #define JuceURLConnection MakeObjCClassName(JuceURLConnection)
  224843. @interface JuceURLConnection : NSObject
  224844. {
  224845. @public
  224846. NSURLRequest* request;
  224847. NSURLConnection* connection;
  224848. NSMutableData* data;
  224849. Thread* runLoopThread;
  224850. bool initialised, hasFailed, hasFinished;
  224851. int position;
  224852. int64 contentLength;
  224853. NSDictionary* headers;
  224854. NSLock* dataLock;
  224855. }
  224856. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  224857. - (void) dealloc;
  224858. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  224859. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  224860. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  224861. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  224862. - (BOOL) isOpen;
  224863. - (int) read: (char*) dest numBytes: (int) num;
  224864. - (int) readPosition;
  224865. - (void) stop;
  224866. - (void) createConnection;
  224867. @end
  224868. class JuceURLConnectionMessageThread : public Thread
  224869. {
  224870. JuceURLConnection* owner;
  224871. public:
  224872. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  224873. : Thread ("http connection"),
  224874. owner (owner_)
  224875. {
  224876. }
  224877. ~JuceURLConnectionMessageThread()
  224878. {
  224879. stopThread (10000);
  224880. }
  224881. void run()
  224882. {
  224883. [owner createConnection];
  224884. while (! threadShouldExit())
  224885. {
  224886. const ScopedAutoReleasePool pool;
  224887. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  224888. }
  224889. }
  224890. };
  224891. @implementation JuceURLConnection
  224892. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  224893. withCallback: (URL::OpenStreamProgressCallback*) callback
  224894. withContext: (void*) context;
  224895. {
  224896. [super init];
  224897. request = req;
  224898. [request retain];
  224899. data = [[NSMutableData data] retain];
  224900. dataLock = [[NSLock alloc] init];
  224901. connection = 0;
  224902. initialised = false;
  224903. hasFailed = false;
  224904. hasFinished = false;
  224905. contentLength = -1;
  224906. headers = 0;
  224907. runLoopThread = new JuceURLConnectionMessageThread (self);
  224908. runLoopThread->startThread();
  224909. while (runLoopThread->isThreadRunning() && ! initialised)
  224910. {
  224911. if (callback != 0)
  224912. callback (context, -1, (int) [[request HTTPBody] length]);
  224913. Thread::sleep (1);
  224914. }
  224915. return self;
  224916. }
  224917. - (void) dealloc
  224918. {
  224919. [self stop];
  224920. deleteAndZero (runLoopThread);
  224921. [connection release];
  224922. [data release];
  224923. [dataLock release];
  224924. [request release];
  224925. [headers release];
  224926. [super dealloc];
  224927. }
  224928. - (void) createConnection
  224929. {
  224930. NSUInteger oldRetainCount = [self retainCount];
  224931. connection = [[NSURLConnection alloc] initWithRequest: request
  224932. delegate: self];
  224933. if (oldRetainCount == [self retainCount])
  224934. [self retain]; // newer SDK should already retain this, but there were problems in older versions..
  224935. if (connection == nil)
  224936. runLoopThread->signalThreadShouldExit();
  224937. }
  224938. - (void) connection: (NSURLConnection*) conn didReceiveResponse: (NSURLResponse*) response
  224939. {
  224940. (void) conn;
  224941. [dataLock lock];
  224942. [data setLength: 0];
  224943. [dataLock unlock];
  224944. initialised = true;
  224945. contentLength = [response expectedContentLength];
  224946. [headers release];
  224947. headers = 0;
  224948. if ([response isKindOfClass: [NSHTTPURLResponse class]])
  224949. headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
  224950. }
  224951. - (void) connection: (NSURLConnection*) conn didFailWithError: (NSError*) error
  224952. {
  224953. (void) conn;
  224954. DBG (nsStringToJuce ([error description]));
  224955. hasFailed = true;
  224956. initialised = true;
  224957. if (runLoopThread != 0)
  224958. runLoopThread->signalThreadShouldExit();
  224959. }
  224960. - (void) connection: (NSURLConnection*) conn didReceiveData: (NSData*) newData
  224961. {
  224962. (void) conn;
  224963. [dataLock lock];
  224964. [data appendData: newData];
  224965. [dataLock unlock];
  224966. initialised = true;
  224967. }
  224968. - (void) connectionDidFinishLoading: (NSURLConnection*) conn
  224969. {
  224970. (void) conn;
  224971. hasFinished = true;
  224972. initialised = true;
  224973. if (runLoopThread != 0)
  224974. runLoopThread->signalThreadShouldExit();
  224975. }
  224976. - (BOOL) isOpen
  224977. {
  224978. return connection != 0 && ! hasFailed;
  224979. }
  224980. - (int) readPosition
  224981. {
  224982. return position;
  224983. }
  224984. - (int) read: (char*) dest numBytes: (int) numNeeded
  224985. {
  224986. int numDone = 0;
  224987. while (numNeeded > 0)
  224988. {
  224989. int available = jmin (numNeeded, (int) [data length]);
  224990. if (available > 0)
  224991. {
  224992. [dataLock lock];
  224993. [data getBytes: dest length: available];
  224994. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  224995. [dataLock unlock];
  224996. numDone += available;
  224997. numNeeded -= available;
  224998. dest += available;
  224999. }
  225000. else
  225001. {
  225002. if (hasFailed || hasFinished)
  225003. break;
  225004. Thread::sleep (1);
  225005. }
  225006. }
  225007. position += numDone;
  225008. return numDone;
  225009. }
  225010. - (void) stop
  225011. {
  225012. [connection cancel];
  225013. if (runLoopThread != 0)
  225014. runLoopThread->stopThread (10000);
  225015. }
  225016. @end
  225017. BEGIN_JUCE_NAMESPACE
  225018. void* juce_openInternetFile (const String& url,
  225019. const String& headers,
  225020. const MemoryBlock& postData,
  225021. const bool isPost,
  225022. URL::OpenStreamProgressCallback* callback,
  225023. void* callbackContext,
  225024. int timeOutMs)
  225025. {
  225026. const ScopedAutoReleasePool pool;
  225027. NSMutableURLRequest* req = [NSMutableURLRequest
  225028. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  225029. cachePolicy: NSURLRequestUseProtocolCachePolicy
  225030. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  225031. if (req == nil)
  225032. return 0;
  225033. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  225034. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  225035. StringArray headerLines;
  225036. headerLines.addLines (headers);
  225037. headerLines.removeEmptyStrings (true);
  225038. for (int i = 0; i < headerLines.size(); ++i)
  225039. {
  225040. const String key (headerLines[i].upToFirstOccurrenceOf (":", false, false).trim());
  225041. const String value (headerLines[i].fromFirstOccurrenceOf (":", false, false).trim());
  225042. if (key.isNotEmpty() && value.isNotEmpty())
  225043. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  225044. }
  225045. if (isPost && postData.getSize() > 0)
  225046. {
  225047. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  225048. length: postData.getSize()]];
  225049. }
  225050. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  225051. withCallback: callback
  225052. withContext: callbackContext];
  225053. if ([s isOpen])
  225054. return s;
  225055. [s release];
  225056. return 0;
  225057. }
  225058. void juce_closeInternetFile (void* handle)
  225059. {
  225060. JuceURLConnection* const s = (JuceURLConnection*) handle;
  225061. if (s != 0)
  225062. {
  225063. const ScopedAutoReleasePool pool;
  225064. [s stop];
  225065. [s release];
  225066. }
  225067. }
  225068. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  225069. {
  225070. JuceURLConnection* const s = (JuceURLConnection*) handle;
  225071. if (s != 0)
  225072. {
  225073. const ScopedAutoReleasePool pool;
  225074. return [s read: (char*) buffer numBytes: bytesToRead];
  225075. }
  225076. return 0;
  225077. }
  225078. int64 juce_getInternetFileContentLength (void* handle)
  225079. {
  225080. JuceURLConnection* const s = (JuceURLConnection*) handle;
  225081. if (s != 0)
  225082. return s->contentLength;
  225083. return -1;
  225084. }
  225085. void juce_getInternetFileHeaders (void* handle, StringPairArray& headers)
  225086. {
  225087. JuceURLConnection* const s = (JuceURLConnection*) handle;
  225088. if (s != 0 && s->headers != 0)
  225089. {
  225090. NSEnumerator* enumerator = [s->headers keyEnumerator];
  225091. NSString* key;
  225092. while ((key = [enumerator nextObject]) != nil)
  225093. headers.set (nsStringToJuce (key),
  225094. nsStringToJuce ((NSString*) [s->headers objectForKey: key]));
  225095. }
  225096. }
  225097. int juce_seekInInternetFile (void* handle, int /*newPosition*/)
  225098. {
  225099. JuceURLConnection* const s = (JuceURLConnection*) handle;
  225100. if (s != 0)
  225101. return [s readPosition];
  225102. return 0;
  225103. }
  225104. #endif
  225105. /*** End of inlined file: juce_mac_Network.mm ***/
  225106. /*** Start of inlined file: juce_posix_NamedPipe.cpp ***/
  225107. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225108. // compiled on its own).
  225109. #if JUCE_INCLUDED_FILE
  225110. struct NamedPipeInternal
  225111. {
  225112. String pipeInName, pipeOutName;
  225113. int pipeIn, pipeOut;
  225114. bool volatile createdPipe, blocked, stopReadOperation;
  225115. static void signalHandler (int) {}
  225116. };
  225117. void NamedPipe::cancelPendingReads()
  225118. {
  225119. while (internal != 0 && static_cast <NamedPipeInternal*> (internal)->blocked)
  225120. {
  225121. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225122. intern->stopReadOperation = true;
  225123. char buffer [1] = { 0 };
  225124. int bytesWritten = (int) ::write (intern->pipeIn, buffer, 1);
  225125. (void) bytesWritten;
  225126. int timeout = 2000;
  225127. while (intern->blocked && --timeout >= 0)
  225128. Thread::sleep (2);
  225129. intern->stopReadOperation = false;
  225130. }
  225131. }
  225132. void NamedPipe::close()
  225133. {
  225134. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225135. if (intern != 0)
  225136. {
  225137. internal = 0;
  225138. if (intern->pipeIn != -1)
  225139. ::close (intern->pipeIn);
  225140. if (intern->pipeOut != -1)
  225141. ::close (intern->pipeOut);
  225142. if (intern->createdPipe)
  225143. {
  225144. unlink (intern->pipeInName.toUTF8());
  225145. unlink (intern->pipeOutName.toUTF8());
  225146. }
  225147. delete intern;
  225148. }
  225149. }
  225150. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  225151. {
  225152. close();
  225153. NamedPipeInternal* const intern = new NamedPipeInternal();
  225154. internal = intern;
  225155. intern->createdPipe = createPipe;
  225156. intern->blocked = false;
  225157. intern->stopReadOperation = false;
  225158. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  225159. siginterrupt (SIGPIPE, 1);
  225160. const String pipePath ("/tmp/" + File::createLegalFileName (pipeName));
  225161. intern->pipeInName = pipePath + "_in";
  225162. intern->pipeOutName = pipePath + "_out";
  225163. intern->pipeIn = -1;
  225164. intern->pipeOut = -1;
  225165. if (createPipe)
  225166. {
  225167. if ((mkfifo (intern->pipeInName.toUTF8(), 0666) && errno != EEXIST)
  225168. || (mkfifo (intern->pipeOutName.toUTF8(), 0666) && errno != EEXIST))
  225169. {
  225170. delete intern;
  225171. internal = 0;
  225172. return false;
  225173. }
  225174. }
  225175. return true;
  225176. }
  225177. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  225178. {
  225179. int bytesRead = -1;
  225180. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225181. if (intern != 0)
  225182. {
  225183. intern->blocked = true;
  225184. if (intern->pipeIn == -1)
  225185. {
  225186. if (intern->createdPipe)
  225187. intern->pipeIn = ::open (intern->pipeInName.toUTF8(), O_RDWR);
  225188. else
  225189. intern->pipeIn = ::open (intern->pipeOutName.toUTF8(), O_RDWR);
  225190. if (intern->pipeIn == -1)
  225191. {
  225192. intern->blocked = false;
  225193. return -1;
  225194. }
  225195. }
  225196. bytesRead = 0;
  225197. char* p = static_cast<char*> (destBuffer);
  225198. while (bytesRead < maxBytesToRead)
  225199. {
  225200. const int bytesThisTime = maxBytesToRead - bytesRead;
  225201. const int numRead = (int) ::read (intern->pipeIn, p, bytesThisTime);
  225202. if (numRead <= 0 || intern->stopReadOperation)
  225203. {
  225204. bytesRead = -1;
  225205. break;
  225206. }
  225207. bytesRead += numRead;
  225208. p += bytesRead;
  225209. }
  225210. intern->blocked = false;
  225211. }
  225212. return bytesRead;
  225213. }
  225214. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  225215. {
  225216. int bytesWritten = -1;
  225217. NamedPipeInternal* const intern = static_cast <NamedPipeInternal*> (internal);
  225218. if (intern != 0)
  225219. {
  225220. if (intern->pipeOut == -1)
  225221. {
  225222. if (intern->createdPipe)
  225223. intern->pipeOut = ::open (intern->pipeOutName.toUTF8(), O_WRONLY);
  225224. else
  225225. intern->pipeOut = ::open (intern->pipeInName.toUTF8(), O_WRONLY);
  225226. if (intern->pipeOut == -1)
  225227. {
  225228. return -1;
  225229. }
  225230. }
  225231. const char* p = static_cast<const char*> (sourceBuffer);
  225232. bytesWritten = 0;
  225233. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  225234. while (bytesWritten < numBytesToWrite
  225235. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  225236. {
  225237. const int bytesThisTime = numBytesToWrite - bytesWritten;
  225238. const int numWritten = (int) ::write (intern->pipeOut, p, bytesThisTime);
  225239. if (numWritten <= 0)
  225240. {
  225241. bytesWritten = -1;
  225242. break;
  225243. }
  225244. bytesWritten += numWritten;
  225245. p += bytesWritten;
  225246. }
  225247. }
  225248. return bytesWritten;
  225249. }
  225250. #endif
  225251. /*** End of inlined file: juce_posix_NamedPipe.cpp ***/
  225252. /*** Start of inlined file: juce_mac_Threads.mm ***/
  225253. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225254. // compiled on its own).
  225255. #if JUCE_INCLUDED_FILE
  225256. /*
  225257. Note that a lot of methods that you'd expect to find in this file actually
  225258. live in juce_posix_SharedCode.h!
  225259. */
  225260. bool Process::isForegroundProcess()
  225261. {
  225262. #if JUCE_MAC
  225263. return [NSApp isActive];
  225264. #else
  225265. return true; // xxx change this if more than one app is ever possible on the iPhone!
  225266. #endif
  225267. }
  225268. void Process::raisePrivilege()
  225269. {
  225270. jassertfalse;
  225271. }
  225272. void Process::lowerPrivilege()
  225273. {
  225274. jassertfalse;
  225275. }
  225276. void Process::terminate()
  225277. {
  225278. exit (0);
  225279. }
  225280. void Process::setPriority (ProcessPriority)
  225281. {
  225282. // xxx
  225283. }
  225284. #endif
  225285. /*** End of inlined file: juce_mac_Threads.mm ***/
  225286. /*** Start of inlined file: juce_posix_SharedCode.h ***/
  225287. /*
  225288. This file contains posix routines that are common to both the Linux and Mac builds.
  225289. It gets included directly in the cpp files for these platforms.
  225290. */
  225291. CriticalSection::CriticalSection() throw()
  225292. {
  225293. pthread_mutexattr_t atts;
  225294. pthread_mutexattr_init (&atts);
  225295. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  225296. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225297. pthread_mutex_init (&internal, &atts);
  225298. }
  225299. CriticalSection::~CriticalSection() throw()
  225300. {
  225301. pthread_mutex_destroy (&internal);
  225302. }
  225303. void CriticalSection::enter() const throw()
  225304. {
  225305. pthread_mutex_lock (&internal);
  225306. }
  225307. bool CriticalSection::tryEnter() const throw()
  225308. {
  225309. return pthread_mutex_trylock (&internal) == 0;
  225310. }
  225311. void CriticalSection::exit() const throw()
  225312. {
  225313. pthread_mutex_unlock (&internal);
  225314. }
  225315. class WaitableEventImpl
  225316. {
  225317. public:
  225318. WaitableEventImpl (const bool manualReset_)
  225319. : triggered (false),
  225320. manualReset (manualReset_)
  225321. {
  225322. pthread_cond_init (&condition, 0);
  225323. pthread_mutexattr_t atts;
  225324. pthread_mutexattr_init (&atts);
  225325. pthread_mutexattr_setprotocol (&atts, PTHREAD_PRIO_INHERIT);
  225326. pthread_mutex_init (&mutex, &atts);
  225327. }
  225328. ~WaitableEventImpl()
  225329. {
  225330. pthread_cond_destroy (&condition);
  225331. pthread_mutex_destroy (&mutex);
  225332. }
  225333. bool wait (const int timeOutMillisecs) throw()
  225334. {
  225335. pthread_mutex_lock (&mutex);
  225336. if (! triggered)
  225337. {
  225338. if (timeOutMillisecs < 0)
  225339. {
  225340. do
  225341. {
  225342. pthread_cond_wait (&condition, &mutex);
  225343. }
  225344. while (! triggered);
  225345. }
  225346. else
  225347. {
  225348. struct timeval now;
  225349. gettimeofday (&now, 0);
  225350. struct timespec time;
  225351. time.tv_sec = now.tv_sec + (timeOutMillisecs / 1000);
  225352. time.tv_nsec = (now.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  225353. if (time.tv_nsec >= 1000000000)
  225354. {
  225355. time.tv_nsec -= 1000000000;
  225356. time.tv_sec++;
  225357. }
  225358. do
  225359. {
  225360. if (pthread_cond_timedwait (&condition, &mutex, &time) == ETIMEDOUT)
  225361. {
  225362. pthread_mutex_unlock (&mutex);
  225363. return false;
  225364. }
  225365. }
  225366. while (! triggered);
  225367. }
  225368. }
  225369. if (! manualReset)
  225370. triggered = false;
  225371. pthread_mutex_unlock (&mutex);
  225372. return true;
  225373. }
  225374. void signal() throw()
  225375. {
  225376. pthread_mutex_lock (&mutex);
  225377. triggered = true;
  225378. pthread_cond_broadcast (&condition);
  225379. pthread_mutex_unlock (&mutex);
  225380. }
  225381. void reset() throw()
  225382. {
  225383. pthread_mutex_lock (&mutex);
  225384. triggered = false;
  225385. pthread_mutex_unlock (&mutex);
  225386. }
  225387. private:
  225388. pthread_cond_t condition;
  225389. pthread_mutex_t mutex;
  225390. bool triggered;
  225391. const bool manualReset;
  225392. WaitableEventImpl (const WaitableEventImpl&);
  225393. WaitableEventImpl& operator= (const WaitableEventImpl&);
  225394. };
  225395. WaitableEvent::WaitableEvent (const bool manualReset) throw()
  225396. : internal (new WaitableEventImpl (manualReset))
  225397. {
  225398. }
  225399. WaitableEvent::~WaitableEvent() throw()
  225400. {
  225401. delete static_cast <WaitableEventImpl*> (internal);
  225402. }
  225403. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  225404. {
  225405. return static_cast <WaitableEventImpl*> (internal)->wait (timeOutMillisecs);
  225406. }
  225407. void WaitableEvent::signal() const throw()
  225408. {
  225409. static_cast <WaitableEventImpl*> (internal)->signal();
  225410. }
  225411. void WaitableEvent::reset() const throw()
  225412. {
  225413. static_cast <WaitableEventImpl*> (internal)->reset();
  225414. }
  225415. void JUCE_CALLTYPE Thread::sleep (int millisecs)
  225416. {
  225417. struct timespec time;
  225418. time.tv_sec = millisecs / 1000;
  225419. time.tv_nsec = (millisecs % 1000) * 1000000;
  225420. nanosleep (&time, 0);
  225421. }
  225422. const juce_wchar File::separator = '/';
  225423. const String File::separatorString ("/");
  225424. const File File::getCurrentWorkingDirectory()
  225425. {
  225426. HeapBlock<char> heapBuffer;
  225427. char localBuffer [1024];
  225428. char* cwd = getcwd (localBuffer, sizeof (localBuffer) - 1);
  225429. int bufferSize = 4096;
  225430. while (cwd == 0 && errno == ERANGE)
  225431. {
  225432. heapBuffer.malloc (bufferSize);
  225433. cwd = getcwd (heapBuffer, bufferSize - 1);
  225434. bufferSize += 1024;
  225435. }
  225436. return File (String::fromUTF8 (cwd));
  225437. }
  225438. bool File::setAsCurrentWorkingDirectory() const
  225439. {
  225440. return chdir (getFullPathName().toUTF8()) == 0;
  225441. }
  225442. namespace
  225443. {
  225444. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225445. typedef struct stat64 juce_statStruct; // (need to use the 64-bit version to work around a simulator bug)
  225446. #else
  225447. typedef struct stat juce_statStruct;
  225448. #endif
  225449. bool juce_stat (const String& fileName, juce_statStruct& info)
  225450. {
  225451. return fileName.isNotEmpty()
  225452. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225453. && (stat64 (fileName.toUTF8(), &info) == 0);
  225454. #else
  225455. && (stat (fileName.toUTF8(), &info) == 0);
  225456. #endif
  225457. }
  225458. // if this file doesn't exist, find a parent of it that does..
  225459. bool juce_doStatFS (File f, struct statfs& result)
  225460. {
  225461. for (int i = 5; --i >= 0;)
  225462. {
  225463. if (f.exists())
  225464. break;
  225465. f = f.getParentDirectory();
  225466. }
  225467. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  225468. }
  225469. }
  225470. bool File::isDirectory() const
  225471. {
  225472. juce_statStruct info;
  225473. return fullPath.isEmpty()
  225474. || (juce_stat (fullPath, info) && ((info.st_mode & S_IFDIR) != 0));
  225475. }
  225476. bool File::exists() const
  225477. {
  225478. juce_statStruct info;
  225479. return fullPath.isNotEmpty()
  225480. #if JUCE_IOS && ! __DARWIN_ONLY_64_BIT_INO_T
  225481. && (lstat64 (fullPath.toUTF8(), &info) == 0);
  225482. #else
  225483. && (lstat (fullPath.toUTF8(), &info) == 0);
  225484. #endif
  225485. }
  225486. bool File::existsAsFile() const
  225487. {
  225488. return exists() && ! isDirectory();
  225489. }
  225490. int64 File::getSize() const
  225491. {
  225492. juce_statStruct info;
  225493. return juce_stat (fullPath, info) ? info.st_size : 0;
  225494. }
  225495. bool File::hasWriteAccess() const
  225496. {
  225497. if (exists())
  225498. return access (fullPath.toUTF8(), W_OK) == 0;
  225499. if ((! isDirectory()) && fullPath.containsChar (separator))
  225500. return getParentDirectory().hasWriteAccess();
  225501. return false;
  225502. }
  225503. bool File::setFileReadOnlyInternal (const bool shouldBeReadOnly) const
  225504. {
  225505. juce_statStruct info;
  225506. if (! juce_stat (fullPath, info))
  225507. return false;
  225508. info.st_mode &= 0777; // Just permissions
  225509. if (shouldBeReadOnly)
  225510. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  225511. else
  225512. // Give everybody write permission?
  225513. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  225514. return chmod (fullPath.toUTF8(), info.st_mode) == 0;
  225515. }
  225516. void File::getFileTimesInternal (int64& modificationTime, int64& accessTime, int64& creationTime) const
  225517. {
  225518. modificationTime = 0;
  225519. accessTime = 0;
  225520. creationTime = 0;
  225521. juce_statStruct info;
  225522. if (juce_stat (fullPath, info))
  225523. {
  225524. modificationTime = (int64) info.st_mtime * 1000;
  225525. accessTime = (int64) info.st_atime * 1000;
  225526. creationTime = (int64) info.st_ctime * 1000;
  225527. }
  225528. }
  225529. bool File::setFileTimesInternal (int64 modificationTime, int64 accessTime, int64 /*creationTime*/) const
  225530. {
  225531. struct utimbuf times;
  225532. times.actime = (time_t) (accessTime / 1000);
  225533. times.modtime = (time_t) (modificationTime / 1000);
  225534. return utime (fullPath.toUTF8(), &times) == 0;
  225535. }
  225536. bool File::deleteFile() const
  225537. {
  225538. if (! exists())
  225539. return true;
  225540. else if (isDirectory())
  225541. return rmdir (fullPath.toUTF8()) == 0;
  225542. else
  225543. return remove (fullPath.toUTF8()) == 0;
  225544. }
  225545. bool File::moveInternal (const File& dest) const
  225546. {
  225547. if (rename (fullPath.toUTF8(), dest.getFullPathName().toUTF8()) == 0)
  225548. return true;
  225549. if (hasWriteAccess() && copyInternal (dest))
  225550. {
  225551. if (deleteFile())
  225552. return true;
  225553. dest.deleteFile();
  225554. }
  225555. return false;
  225556. }
  225557. void File::createDirectoryInternal (const String& fileName) const
  225558. {
  225559. mkdir (fileName.toUTF8(), 0777);
  225560. }
  225561. int64 juce_fileSetPosition (void* handle, int64 pos)
  225562. {
  225563. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  225564. return pos;
  225565. return -1;
  225566. }
  225567. void FileInputStream::openHandle()
  225568. {
  225569. totalSize = file.getSize();
  225570. const int f = open (file.getFullPathName().toUTF8(), O_RDONLY, 00644);
  225571. if (f != -1)
  225572. fileHandle = (void*) f;
  225573. }
  225574. void FileInputStream::closeHandle()
  225575. {
  225576. if (fileHandle != 0)
  225577. {
  225578. close ((int) (pointer_sized_int) fileHandle);
  225579. fileHandle = 0;
  225580. }
  225581. }
  225582. size_t FileInputStream::readInternal (void* const buffer, const size_t numBytes)
  225583. {
  225584. if (fileHandle != 0)
  225585. return jmax ((ssize_t) 0, ::read ((int) (pointer_sized_int) fileHandle, buffer, numBytes));
  225586. return 0;
  225587. }
  225588. void FileOutputStream::openHandle()
  225589. {
  225590. if (file.exists())
  225591. {
  225592. const int f = open (file.getFullPathName().toUTF8(), O_RDWR, 00644);
  225593. if (f != -1)
  225594. {
  225595. currentPosition = lseek (f, 0, SEEK_END);
  225596. if (currentPosition >= 0)
  225597. fileHandle = (void*) f;
  225598. else
  225599. close (f);
  225600. }
  225601. }
  225602. else
  225603. {
  225604. const int f = open (file.getFullPathName().toUTF8(), O_RDWR + O_CREAT, 00644);
  225605. if (f != -1)
  225606. fileHandle = (void*) f;
  225607. }
  225608. }
  225609. void FileOutputStream::closeHandle()
  225610. {
  225611. if (fileHandle != 0)
  225612. {
  225613. close ((int) (pointer_sized_int) fileHandle);
  225614. fileHandle = 0;
  225615. }
  225616. }
  225617. int FileOutputStream::writeInternal (const void* const data, const int numBytes)
  225618. {
  225619. if (fileHandle != 0)
  225620. return (int) ::write ((int) (pointer_sized_int) fileHandle, data, numBytes);
  225621. return 0;
  225622. }
  225623. void FileOutputStream::flushInternal()
  225624. {
  225625. if (fileHandle != 0)
  225626. fsync ((int) (pointer_sized_int) fileHandle);
  225627. }
  225628. const File juce_getExecutableFile()
  225629. {
  225630. Dl_info exeInfo;
  225631. dladdr ((const void*) juce_getExecutableFile, &exeInfo);
  225632. return File::getCurrentWorkingDirectory().getChildFile (String::fromUTF8 (exeInfo.dli_fname));
  225633. }
  225634. int64 File::getBytesFreeOnVolume() const
  225635. {
  225636. struct statfs buf;
  225637. if (juce_doStatFS (*this, buf))
  225638. return (int64) buf.f_bsize * (int64) buf.f_bavail; // Note: this returns space available to non-super user
  225639. return 0;
  225640. }
  225641. int64 File::getVolumeTotalSize() const
  225642. {
  225643. struct statfs buf;
  225644. if (juce_doStatFS (*this, buf))
  225645. return (int64) buf.f_bsize * (int64) buf.f_blocks;
  225646. return 0;
  225647. }
  225648. const String File::getVolumeLabel() const
  225649. {
  225650. #if JUCE_MAC
  225651. struct VolAttrBuf
  225652. {
  225653. u_int32_t length;
  225654. attrreference_t mountPointRef;
  225655. char mountPointSpace [MAXPATHLEN];
  225656. } attrBuf;
  225657. struct attrlist attrList;
  225658. zerostruct (attrList);
  225659. attrList.bitmapcount = ATTR_BIT_MAP_COUNT;
  225660. attrList.volattr = ATTR_VOL_INFO | ATTR_VOL_NAME;
  225661. File f (*this);
  225662. for (;;)
  225663. {
  225664. if (getattrlist (f.getFullPathName().toUTF8(), &attrList, &attrBuf, sizeof (attrBuf), 0) == 0)
  225665. return String::fromUTF8 (((const char*) &attrBuf.mountPointRef) + attrBuf.mountPointRef.attr_dataoffset,
  225666. (int) attrBuf.mountPointRef.attr_length);
  225667. const File parent (f.getParentDirectory());
  225668. if (f == parent)
  225669. break;
  225670. f = parent;
  225671. }
  225672. #endif
  225673. return String::empty;
  225674. }
  225675. int File::getVolumeSerialNumber() const
  225676. {
  225677. return 0; // xxx
  225678. }
  225679. void juce_runSystemCommand (const String& command)
  225680. {
  225681. int result = system (command.toUTF8());
  225682. (void) result;
  225683. }
  225684. const String juce_getOutputFromCommand (const String& command)
  225685. {
  225686. // slight bodge here, as we just pipe the output into a temp file and read it...
  225687. const File tempFile (File::getSpecialLocation (File::tempDirectory)
  225688. .getNonexistentChildFile (String::toHexString (Random::getSystemRandom().nextInt()), ".tmp", false));
  225689. juce_runSystemCommand (command + " > " + tempFile.getFullPathName());
  225690. String result (tempFile.loadFileAsString());
  225691. tempFile.deleteFile();
  225692. return result;
  225693. }
  225694. class InterProcessLock::Pimpl
  225695. {
  225696. public:
  225697. Pimpl (const String& name, const int timeOutMillisecs)
  225698. : handle (0), refCount (1)
  225699. {
  225700. #if JUCE_MAC
  225701. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  225702. const File temp (File ("~/Library/Caches/Juce").getChildFile (name));
  225703. #else
  225704. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  225705. #endif
  225706. temp.create();
  225707. handle = open (temp.getFullPathName().toUTF8(), O_RDWR);
  225708. if (handle != 0)
  225709. {
  225710. struct flock fl;
  225711. zerostruct (fl);
  225712. fl.l_whence = SEEK_SET;
  225713. fl.l_type = F_WRLCK;
  225714. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  225715. for (;;)
  225716. {
  225717. const int result = fcntl (handle, F_SETLK, &fl);
  225718. if (result >= 0)
  225719. return;
  225720. if (errno != EINTR)
  225721. {
  225722. if (timeOutMillisecs == 0
  225723. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  225724. break;
  225725. Thread::sleep (10);
  225726. }
  225727. }
  225728. }
  225729. closeFile();
  225730. }
  225731. ~Pimpl()
  225732. {
  225733. closeFile();
  225734. }
  225735. void closeFile()
  225736. {
  225737. if (handle != 0)
  225738. {
  225739. struct flock fl;
  225740. zerostruct (fl);
  225741. fl.l_whence = SEEK_SET;
  225742. fl.l_type = F_UNLCK;
  225743. while (! (fcntl (handle, F_SETLKW, &fl) >= 0 || errno != EINTR))
  225744. {}
  225745. close (handle);
  225746. handle = 0;
  225747. }
  225748. }
  225749. int handle, refCount;
  225750. };
  225751. InterProcessLock::InterProcessLock (const String& name_)
  225752. : name (name_)
  225753. {
  225754. }
  225755. InterProcessLock::~InterProcessLock()
  225756. {
  225757. }
  225758. bool InterProcessLock::enter (const int timeOutMillisecs)
  225759. {
  225760. const ScopedLock sl (lock);
  225761. if (pimpl == 0)
  225762. {
  225763. pimpl = new Pimpl (name, timeOutMillisecs);
  225764. if (pimpl->handle == 0)
  225765. pimpl = 0;
  225766. }
  225767. else
  225768. {
  225769. pimpl->refCount++;
  225770. }
  225771. return pimpl != 0;
  225772. }
  225773. void InterProcessLock::exit()
  225774. {
  225775. const ScopedLock sl (lock);
  225776. // Trying to release the lock too many times!
  225777. jassert (pimpl != 0);
  225778. if (pimpl != 0 && --(pimpl->refCount) == 0)
  225779. pimpl = 0;
  225780. }
  225781. void JUCE_API juce_threadEntryPoint (void*);
  225782. void* threadEntryProc (void* userData)
  225783. {
  225784. JUCE_AUTORELEASEPOOL
  225785. juce_threadEntryPoint (userData);
  225786. return 0;
  225787. }
  225788. void* juce_createThread (void* userData)
  225789. {
  225790. pthread_t handle = 0;
  225791. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  225792. {
  225793. pthread_detach (handle);
  225794. return (void*) handle;
  225795. }
  225796. return 0;
  225797. }
  225798. void juce_killThread (void* handle)
  225799. {
  225800. if (handle != 0)
  225801. pthread_cancel ((pthread_t) handle);
  225802. }
  225803. void juce_setCurrentThreadName (const String& /*name*/)
  225804. {
  225805. }
  225806. bool juce_setThreadPriority (void* handle, int priority)
  225807. {
  225808. struct sched_param param;
  225809. int policy;
  225810. priority = jlimit (0, 10, priority);
  225811. if (handle == 0)
  225812. handle = (void*) pthread_self();
  225813. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) != 0)
  225814. return false;
  225815. policy = priority == 0 ? SCHED_OTHER : SCHED_RR;
  225816. const int minPriority = sched_get_priority_min (policy);
  225817. const int maxPriority = sched_get_priority_max (policy);
  225818. param.sched_priority = ((maxPriority - minPriority) * priority) / 10 + minPriority;
  225819. return pthread_setschedparam ((pthread_t) handle, policy, &param) == 0;
  225820. }
  225821. Thread::ThreadID Thread::getCurrentThreadId()
  225822. {
  225823. return (ThreadID) pthread_self();
  225824. }
  225825. void Thread::yield()
  225826. {
  225827. sched_yield();
  225828. }
  225829. /* Remove this macro if you're having problems compiling the cpu affinity
  225830. calls (the API for these has changed about quite a bit in various Linux
  225831. versions, and a lot of distros seem to ship with obsolete versions)
  225832. */
  225833. #if defined (CPU_ISSET) && ! defined (SUPPORT_AFFINITIES)
  225834. #define SUPPORT_AFFINITIES 1
  225835. #endif
  225836. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask)
  225837. {
  225838. #if SUPPORT_AFFINITIES
  225839. cpu_set_t affinity;
  225840. CPU_ZERO (&affinity);
  225841. for (int i = 0; i < 32; ++i)
  225842. if ((affinityMask & (1 << i)) != 0)
  225843. CPU_SET (i, &affinity);
  225844. /*
  225845. N.B. If this line causes a compile error, then you've probably not got the latest
  225846. version of glibc installed.
  225847. If you don't want to update your copy of glibc and don't care about cpu affinities,
  225848. then you can just disable all this stuff by setting the SUPPORT_AFFINITIES macro to 0.
  225849. */
  225850. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  225851. sched_yield();
  225852. #else
  225853. /* affinities aren't supported because either the appropriate header files weren't found,
  225854. or the SUPPORT_AFFINITIES macro was turned off
  225855. */
  225856. jassertfalse;
  225857. #endif
  225858. }
  225859. /*** End of inlined file: juce_posix_SharedCode.h ***/
  225860. /*** Start of inlined file: juce_mac_Files.mm ***/
  225861. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  225862. // compiled on its own).
  225863. #if JUCE_INCLUDED_FILE
  225864. /*
  225865. Note that a lot of methods that you'd expect to find in this file actually
  225866. live in juce_posix_SharedCode.h!
  225867. */
  225868. bool File::copyInternal (const File& dest) const
  225869. {
  225870. const ScopedAutoReleasePool pool;
  225871. NSFileManager* fm = [NSFileManager defaultManager];
  225872. return [fm fileExistsAtPath: juceStringToNS (fullPath)]
  225873. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  225874. && [fm copyItemAtPath: juceStringToNS (fullPath)
  225875. toPath: juceStringToNS (dest.getFullPathName())
  225876. error: nil];
  225877. #else
  225878. && [fm copyPath: juceStringToNS (fullPath)
  225879. toPath: juceStringToNS (dest.getFullPathName())
  225880. handler: nil];
  225881. #endif
  225882. }
  225883. void File::findFileSystemRoots (Array<File>& destArray)
  225884. {
  225885. destArray.add (File ("/"));
  225886. }
  225887. namespace
  225888. {
  225889. bool isFileOnDriveType (const File& f, const char* const* types)
  225890. {
  225891. struct statfs buf;
  225892. if (juce_doStatFS (f, buf))
  225893. {
  225894. const String type (buf.f_fstypename);
  225895. while (*types != 0)
  225896. if (type.equalsIgnoreCase (*types++))
  225897. return true;
  225898. }
  225899. return false;
  225900. }
  225901. bool juce_isHiddenFile (const String& path)
  225902. {
  225903. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6
  225904. const ScopedAutoReleasePool pool;
  225905. NSNumber* hidden = nil;
  225906. NSError* err = nil;
  225907. return [[NSURL fileURLWithPath: juceStringToNS (path)]
  225908. getResourceValue: &hidden forKey: NSURLIsHiddenKey error: &err]
  225909. && [hidden boolValue];
  225910. #else
  225911. #if JUCE_IOS
  225912. return File (path).getFileName().startsWithChar ('.');
  225913. #else
  225914. FSRef ref;
  225915. LSItemInfoRecord info;
  225916. return FSPathMakeRefWithOptions ((const UInt8*) path.toUTF8(), kFSPathMakeRefDoNotFollowLeafSymlink, &ref, 0) == noErr
  225917. && LSCopyItemInfoForRef (&ref, kLSRequestBasicFlagsOnly, &info) == noErr
  225918. && (info.flags & kLSItemInfoIsInvisible) != 0;
  225919. #endif
  225920. #endif
  225921. }
  225922. #if JUCE_IOS
  225923. const String getIOSSystemLocation (NSSearchPathDirectory type)
  225924. {
  225925. return nsStringToJuce ([NSSearchPathForDirectoriesInDomains (type, NSUserDomainMask, YES)
  225926. objectAtIndex: 0]);
  225927. }
  225928. #endif
  225929. }
  225930. bool File::isOnCDRomDrive() const
  225931. {
  225932. const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  225933. return isFileOnDriveType (*this, cdTypes);
  225934. }
  225935. bool File::isOnHardDisk() const
  225936. {
  225937. const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  225938. return ! (isOnCDRomDrive() || isFileOnDriveType (*this, nonHDTypes));
  225939. }
  225940. bool File::isOnRemovableDrive() const
  225941. {
  225942. #if JUCE_IOS
  225943. return false; // xxx is this possible?
  225944. #else
  225945. const ScopedAutoReleasePool pool;
  225946. BOOL removable = false;
  225947. [[NSWorkspace sharedWorkspace]
  225948. getFileSystemInfoForPath: juceStringToNS (getFullPathName())
  225949. isRemovable: &removable
  225950. isWritable: nil
  225951. isUnmountable: nil
  225952. description: nil
  225953. type: nil];
  225954. return removable;
  225955. #endif
  225956. }
  225957. bool File::isHidden() const
  225958. {
  225959. return juce_isHiddenFile (getFullPathName());
  225960. }
  225961. const char* juce_Argv0 = 0; // referenced from juce_Application.cpp
  225962. const File File::getSpecialLocation (const SpecialLocationType type)
  225963. {
  225964. const ScopedAutoReleasePool pool;
  225965. String resultPath;
  225966. switch (type)
  225967. {
  225968. case userHomeDirectory: resultPath = nsStringToJuce (NSHomeDirectory()); break;
  225969. #if JUCE_IOS
  225970. case userDocumentsDirectory: resultPath = getIOSSystemLocation (NSDocumentDirectory); break;
  225971. case userDesktopDirectory: resultPath = getIOSSystemLocation (NSDesktopDirectory); break;
  225972. case tempDirectory:
  225973. {
  225974. File tmp (getIOSSystemLocation (NSCachesDirectory));
  225975. tmp = tmp.getChildFile (juce_getExecutableFile().getFileNameWithoutExtension());
  225976. tmp.createDirectory();
  225977. return tmp.getFullPathName();
  225978. }
  225979. #else
  225980. case userDocumentsDirectory: resultPath = "~/Documents"; break;
  225981. case userDesktopDirectory: resultPath = "~/Desktop"; break;
  225982. case tempDirectory:
  225983. {
  225984. File tmp ("~/Library/Caches/" + juce_getExecutableFile().getFileNameWithoutExtension());
  225985. tmp.createDirectory();
  225986. return tmp.getFullPathName();
  225987. }
  225988. #endif
  225989. case userMusicDirectory: resultPath = "~/Music"; break;
  225990. case userMoviesDirectory: resultPath = "~/Movies"; break;
  225991. case userApplicationDataDirectory: resultPath = "~/Library"; break;
  225992. case commonApplicationDataDirectory: resultPath = "/Library"; break;
  225993. case globalApplicationsDirectory: resultPath = "/Applications"; break;
  225994. case invokedExecutableFile:
  225995. if (juce_Argv0 != 0)
  225996. return File (String::fromUTF8 (juce_Argv0));
  225997. // deliberate fall-through...
  225998. case currentExecutableFile:
  225999. return juce_getExecutableFile();
  226000. case currentApplicationFile:
  226001. {
  226002. const File exe (juce_getExecutableFile());
  226003. const File parent (exe.getParentDirectory());
  226004. #if JUCE_IOS
  226005. return parent;
  226006. #else
  226007. return parent.getFullPathName().endsWithIgnoreCase ("Contents/MacOS")
  226008. ? parent.getParentDirectory().getParentDirectory()
  226009. : exe;
  226010. #endif
  226011. }
  226012. case hostApplicationPath:
  226013. {
  226014. unsigned int size = 8192;
  226015. HeapBlock<char> buffer;
  226016. buffer.calloc (size + 8);
  226017. _NSGetExecutablePath (buffer.getData(), &size);
  226018. return String::fromUTF8 (buffer, size);
  226019. }
  226020. default:
  226021. jassertfalse; // unknown type?
  226022. break;
  226023. }
  226024. if (resultPath.isNotEmpty())
  226025. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  226026. return File::nonexistent;
  226027. }
  226028. const String File::getVersion() const
  226029. {
  226030. const ScopedAutoReleasePool pool;
  226031. String result;
  226032. NSBundle* bundle = [NSBundle bundleWithPath: juceStringToNS (getFullPathName())];
  226033. if (bundle != 0)
  226034. {
  226035. NSDictionary* info = [bundle infoDictionary];
  226036. if (info != 0)
  226037. {
  226038. NSString* name = [info valueForKey: @"CFBundleShortVersionString"];
  226039. if (name != nil)
  226040. result = nsStringToJuce (name);
  226041. }
  226042. }
  226043. return result;
  226044. }
  226045. const File File::getLinkedTarget() const
  226046. {
  226047. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  226048. NSString* dest = [[NSFileManager defaultManager] destinationOfSymbolicLinkAtPath: juceStringToNS (getFullPathName()) error: nil];
  226049. #else
  226050. // (the cast here avoids a deprecation warning)
  226051. NSString* dest = [((id) [NSFileManager defaultManager]) pathContentOfSymbolicLinkAtPath: juceStringToNS (getFullPathName())];
  226052. #endif
  226053. if (dest != nil)
  226054. return File (nsStringToJuce (dest));
  226055. return *this;
  226056. }
  226057. bool File::moveToTrash() const
  226058. {
  226059. if (! exists())
  226060. return true;
  226061. #if JUCE_IOS
  226062. return deleteFile(); //xxx is there a trashcan on the iPhone?
  226063. #else
  226064. const ScopedAutoReleasePool pool;
  226065. NSString* p = juceStringToNS (getFullPathName());
  226066. return [[NSWorkspace sharedWorkspace]
  226067. performFileOperation: NSWorkspaceRecycleOperation
  226068. source: [p stringByDeletingLastPathComponent]
  226069. destination: @""
  226070. files: [NSArray arrayWithObject: [p lastPathComponent]]
  226071. tag: nil ];
  226072. #endif
  226073. }
  226074. class DirectoryIterator::NativeIterator::Pimpl
  226075. {
  226076. public:
  226077. Pimpl (const File& directory, const String& wildCard_)
  226078. : parentDir (File::addTrailingSeparator (directory.getFullPathName())),
  226079. wildCard (wildCard_),
  226080. enumerator (0)
  226081. {
  226082. const ScopedAutoReleasePool pool;
  226083. enumerator = [[[NSFileManager defaultManager] enumeratorAtPath: juceStringToNS (directory.getFullPathName())] retain];
  226084. wildcardUTF8 = wildCard.toUTF8();
  226085. }
  226086. ~Pimpl()
  226087. {
  226088. [enumerator release];
  226089. }
  226090. bool next (String& filenameFound,
  226091. bool* const isDir, bool* const isHidden, int64* const fileSize,
  226092. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  226093. {
  226094. const ScopedAutoReleasePool pool;
  226095. for (;;)
  226096. {
  226097. NSString* file;
  226098. if (enumerator == 0 || (file = [enumerator nextObject]) == 0)
  226099. return false;
  226100. [enumerator skipDescendents];
  226101. filenameFound = nsStringToJuce (file);
  226102. if (fnmatch (wildcardUTF8, filenameFound.toUTF8(), FNM_CASEFOLD) != 0)
  226103. continue;
  226104. const String path (parentDir + filenameFound);
  226105. if (isDir != 0 || fileSize != 0 || modTime != 0 || creationTime != 0)
  226106. {
  226107. juce_statStruct info;
  226108. const bool statOk = juce_stat (path, info);
  226109. if (isDir != 0) *isDir = statOk && ((info.st_mode & S_IFDIR) != 0);
  226110. if (fileSize != 0) *fileSize = statOk ? info.st_size : 0;
  226111. if (modTime != 0) *modTime = statOk ? (int64) info.st_mtime * 1000 : 0;
  226112. if (creationTime != 0) *creationTime = statOk ? (int64) info.st_ctime * 1000 : 0;
  226113. }
  226114. if (isHidden != 0)
  226115. *isHidden = juce_isHiddenFile (path);
  226116. if (isReadOnly != 0)
  226117. *isReadOnly = access (path.toUTF8(), W_OK) != 0;
  226118. return true;
  226119. }
  226120. }
  226121. private:
  226122. String parentDir, wildCard;
  226123. const char* wildcardUTF8;
  226124. NSDirectoryEnumerator* enumerator;
  226125. Pimpl (const Pimpl&);
  226126. Pimpl& operator= (const Pimpl&);
  226127. };
  226128. DirectoryIterator::NativeIterator::NativeIterator (const File& directory, const String& wildCard)
  226129. : pimpl (new DirectoryIterator::NativeIterator::Pimpl (directory, wildCard))
  226130. {
  226131. }
  226132. DirectoryIterator::NativeIterator::~NativeIterator()
  226133. {
  226134. }
  226135. bool DirectoryIterator::NativeIterator::next (String& filenameFound,
  226136. bool* const isDir, bool* const isHidden, int64* const fileSize,
  226137. Time* const modTime, Time* const creationTime, bool* const isReadOnly)
  226138. {
  226139. return pimpl->next (filenameFound, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  226140. }
  226141. bool juce_launchExecutable (const String& pathAndArguments)
  226142. {
  226143. const char* const argv[4] = { "/bin/sh", "-c", pathAndArguments.toUTF8(), 0 };
  226144. const int cpid = fork();
  226145. if (cpid == 0)
  226146. {
  226147. // Child process
  226148. if (execve (argv[0], (char**) argv, 0) < 0)
  226149. exit (0);
  226150. }
  226151. else
  226152. {
  226153. if (cpid < 0)
  226154. return false;
  226155. }
  226156. return true;
  226157. }
  226158. bool PlatformUtilities::openDocument (const String& fileName, const String& parameters)
  226159. {
  226160. #if JUCE_IOS
  226161. return [[UIApplication sharedApplication] openURL: [NSURL fileURLWithPath: juceStringToNS (fileName)]];
  226162. #else
  226163. const ScopedAutoReleasePool pool;
  226164. if (parameters.isEmpty())
  226165. {
  226166. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)]
  226167. || [[NSWorkspace sharedWorkspace] openURL: [NSURL URLWithString: juceStringToNS (fileName)]];
  226168. }
  226169. bool ok = false;
  226170. if (PlatformUtilities::isBundle (fileName))
  226171. {
  226172. NSMutableArray* urls = [NSMutableArray array];
  226173. StringArray docs;
  226174. docs.addTokens (parameters, true);
  226175. for (int i = 0; i < docs.size(); ++i)
  226176. [urls addObject: juceStringToNS (docs[i])];
  226177. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  226178. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  226179. options: 0
  226180. additionalEventParamDescriptor: nil
  226181. launchIdentifiers: nil];
  226182. }
  226183. else if (File (fileName).exists())
  226184. {
  226185. ok = juce_launchExecutable ("\"" + fileName + "\" " + parameters);
  226186. }
  226187. return ok;
  226188. #endif
  226189. }
  226190. void File::revealToUser() const
  226191. {
  226192. #if ! JUCE_IOS
  226193. if (exists())
  226194. [[NSWorkspace sharedWorkspace] selectFile: juceStringToNS (getFullPathName()) inFileViewerRootedAtPath: @""];
  226195. else if (getParentDirectory().exists())
  226196. getParentDirectory().revealToUser();
  226197. #endif
  226198. }
  226199. #if ! JUCE_IOS
  226200. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  226201. {
  226202. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  226203. }
  226204. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  226205. {
  226206. char path [2048];
  226207. zerostruct (path);
  226208. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  226209. return PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 (path));
  226210. return String::empty;
  226211. }
  226212. #endif
  226213. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  226214. {
  226215. const ScopedAutoReleasePool pool;
  226216. #if JUCE_IOS || (defined (MAC_OS_X_VERSION_10_5) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_5)
  226217. NSDictionary* fileDict = [[NSFileManager defaultManager] attributesOfItemAtPath: juceStringToNS (filename) error: nil];
  226218. #else
  226219. // (the cast here avoids a deprecation warning)
  226220. NSDictionary* fileDict = [((id) [NSFileManager defaultManager]) fileAttributesAtPath: juceStringToNS (filename) traverseLink: NO];
  226221. #endif
  226222. return [fileDict fileHFSTypeCode];
  226223. }
  226224. bool PlatformUtilities::isBundle (const String& filename)
  226225. {
  226226. #if JUCE_IOS
  226227. return false; // xxx can't find a sensible way to do this without trying to open the bundle..
  226228. #else
  226229. const ScopedAutoReleasePool pool;
  226230. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  226231. #endif
  226232. }
  226233. #endif
  226234. /*** End of inlined file: juce_mac_Files.mm ***/
  226235. #if JUCE_IOS
  226236. /*** Start of inlined file: juce_iphone_MiscUtilities.mm ***/
  226237. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226238. // compiled on its own).
  226239. #if JUCE_INCLUDED_FILE
  226240. END_JUCE_NAMESPACE
  226241. @interface JuceAppStartupDelegate : NSObject <UIApplicationDelegate>
  226242. {
  226243. }
  226244. - (void) applicationDidFinishLaunching: (UIApplication*) application;
  226245. - (void) applicationWillTerminate: (UIApplication*) application;
  226246. @end
  226247. @implementation JuceAppStartupDelegate
  226248. - (void) applicationDidFinishLaunching: (UIApplication*) application
  226249. {
  226250. initialiseJuce_GUI();
  226251. if (! JUCEApplication::createInstance()->initialiseApp (String::empty))
  226252. exit (0);
  226253. }
  226254. - (void) applicationWillTerminate: (UIApplication*) application
  226255. {
  226256. JUCEApplication::appWillTerminateByForce();
  226257. }
  226258. @end
  226259. BEGIN_JUCE_NAMESPACE
  226260. int juce_iOSMain (int argc, const char* argv[])
  226261. {
  226262. return UIApplicationMain (argc, const_cast<char**> (argv), nil, @"JuceAppStartupDelegate");
  226263. }
  226264. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226265. {
  226266. pool = [[NSAutoreleasePool alloc] init];
  226267. }
  226268. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226269. {
  226270. [((NSAutoreleasePool*) pool) release];
  226271. }
  226272. void PlatformUtilities::beep()
  226273. {
  226274. //xxx
  226275. //AudioServicesPlaySystemSound ();
  226276. }
  226277. void PlatformUtilities::addItemToDock (const File& file)
  226278. {
  226279. }
  226280. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226281. END_JUCE_NAMESPACE
  226282. @interface JuceAlertBoxDelegate : NSObject
  226283. {
  226284. @public
  226285. bool clickedOk;
  226286. }
  226287. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex;
  226288. @end
  226289. @implementation JuceAlertBoxDelegate
  226290. - (void) alertView: (UIAlertView*) alertView clickedButtonAtIndex: (NSInteger) buttonIndex
  226291. {
  226292. clickedOk = (buttonIndex == 0);
  226293. alertView.hidden = true;
  226294. }
  226295. @end
  226296. BEGIN_JUCE_NAMESPACE
  226297. // (This function is used directly by other bits of code)
  226298. bool juce_iPhoneShowModalAlert (const String& title,
  226299. const String& bodyText,
  226300. NSString* okButtonText,
  226301. NSString* cancelButtonText)
  226302. {
  226303. const ScopedAutoReleasePool pool;
  226304. JuceAlertBoxDelegate* callback = [[JuceAlertBoxDelegate alloc] init];
  226305. UIAlertView* alert = [[UIAlertView alloc] initWithTitle: juceStringToNS (title)
  226306. message: juceStringToNS (bodyText)
  226307. delegate: callback
  226308. cancelButtonTitle: okButtonText
  226309. otherButtonTitles: cancelButtonText, nil];
  226310. [alert retain];
  226311. [alert show];
  226312. while (! alert.hidden && alert.superview != nil)
  226313. [[NSRunLoop mainRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  226314. const bool result = callback->clickedOk;
  226315. [alert release];
  226316. [callback release];
  226317. return result;
  226318. }
  226319. bool AlertWindow::showNativeDialogBox (const String& title,
  226320. const String& bodyText,
  226321. bool isOkCancel)
  226322. {
  226323. return juce_iPhoneShowModalAlert (title, bodyText,
  226324. @"OK",
  226325. isOkCancel ? @"Cancel" : nil);
  226326. }
  226327. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  226328. {
  226329. jassertfalse; // no such thing on the iphone!
  226330. return false;
  226331. }
  226332. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  226333. {
  226334. jassertfalse; // no such thing on the iphone!
  226335. return false;
  226336. }
  226337. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226338. {
  226339. [[UIApplication sharedApplication] setIdleTimerDisabled: ! isEnabled];
  226340. }
  226341. bool Desktop::isScreenSaverEnabled()
  226342. {
  226343. return ! [[UIApplication sharedApplication] isIdleTimerDisabled];
  226344. }
  226345. #endif
  226346. #endif
  226347. /*** End of inlined file: juce_iphone_MiscUtilities.mm ***/
  226348. #else
  226349. /*** Start of inlined file: juce_mac_MiscUtilities.mm ***/
  226350. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226351. // compiled on its own).
  226352. #if JUCE_INCLUDED_FILE
  226353. ScopedAutoReleasePool::ScopedAutoReleasePool()
  226354. {
  226355. pool = [[NSAutoreleasePool alloc] init];
  226356. }
  226357. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  226358. {
  226359. [((NSAutoreleasePool*) pool) release];
  226360. }
  226361. void PlatformUtilities::beep()
  226362. {
  226363. NSBeep();
  226364. }
  226365. void PlatformUtilities::addItemToDock (const File& file)
  226366. {
  226367. // check that it's not already there...
  226368. if (! juce_getOutputFromCommand ("defaults read com.apple.dock persistent-apps")
  226369. .containsIgnoreCase (file.getFullPathName()))
  226370. {
  226371. 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>"
  226372. + file.getFullPathName() + "</string><key>_CFURLStringType</key><integer>0</integer></dict></dict></dict>\"");
  226373. juce_runSystemCommand ("osascript -e \"tell application \\\"Dock\\\" to quit\"");
  226374. }
  226375. }
  226376. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226377. bool AlertWindow::showNativeDialogBox (const String& title,
  226378. const String& bodyText,
  226379. bool isOkCancel)
  226380. {
  226381. const ScopedAutoReleasePool pool;
  226382. return NSRunAlertPanel (juceStringToNS (title),
  226383. juceStringToNS (bodyText),
  226384. @"Ok",
  226385. isOkCancel ? @"Cancel" : nil,
  226386. nil) == NSAlertDefaultReturn;
  226387. }
  226388. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  226389. {
  226390. if (files.size() == 0)
  226391. return false;
  226392. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  226393. if (draggingSource == 0)
  226394. {
  226395. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226396. return false;
  226397. }
  226398. Component* sourceComp = draggingSource->getComponentUnderMouse();
  226399. if (sourceComp == 0)
  226400. {
  226401. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  226402. return false;
  226403. }
  226404. const ScopedAutoReleasePool pool;
  226405. NSView* view = (NSView*) sourceComp->getWindowHandle();
  226406. if (view == 0)
  226407. return false;
  226408. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  226409. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  226410. owner: nil];
  226411. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  226412. for (int i = 0; i < files.size(); ++i)
  226413. [filesArray addObject: juceStringToNS (files[i])];
  226414. [pboard setPropertyList: filesArray
  226415. forType: NSFilenamesPboardType];
  226416. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  226417. fromView: nil];
  226418. dragPosition.x -= 16;
  226419. dragPosition.y -= 16;
  226420. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  226421. at: dragPosition
  226422. offset: NSMakeSize (0, 0)
  226423. event: [[view window] currentEvent]
  226424. pasteboard: pboard
  226425. source: view
  226426. slideBack: YES];
  226427. return true;
  226428. }
  226429. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  226430. {
  226431. jassertfalse; // not implemented!
  226432. return false;
  226433. }
  226434. bool Desktop::canUseSemiTransparentWindows() throw()
  226435. {
  226436. return true;
  226437. }
  226438. const Point<int> Desktop::getMousePosition()
  226439. {
  226440. const ScopedAutoReleasePool pool;
  226441. const NSPoint p ([NSEvent mouseLocation]);
  226442. return Point<int> (roundToInt (p.x), roundToInt ([[[NSScreen screens] objectAtIndex: 0] frame].size.height - p.y));
  226443. }
  226444. void Desktop::setMousePosition (const Point<int>& newPosition)
  226445. {
  226446. // this rubbish needs to be done around the warp call, to avoid causing a
  226447. // bizarre glitch..
  226448. CGAssociateMouseAndMouseCursorPosition (false);
  226449. CGWarpMouseCursorPosition (CGPointMake (newPosition.getX(), newPosition.getY()));
  226450. CGAssociateMouseAndMouseCursorPosition (true);
  226451. }
  226452. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  226453. {
  226454. return upright;
  226455. }
  226456. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226457. class ScreenSaverDefeater : public Timer,
  226458. public DeletedAtShutdown
  226459. {
  226460. public:
  226461. ScreenSaverDefeater()
  226462. {
  226463. startTimer (10000);
  226464. timerCallback();
  226465. }
  226466. ~ScreenSaverDefeater() {}
  226467. void timerCallback()
  226468. {
  226469. if (Process::isForegroundProcess())
  226470. UpdateSystemActivity (UsrActivity);
  226471. }
  226472. };
  226473. static ScreenSaverDefeater* screenSaverDefeater = 0;
  226474. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226475. {
  226476. if (isEnabled)
  226477. deleteAndZero (screenSaverDefeater);
  226478. else if (screenSaverDefeater == 0)
  226479. screenSaverDefeater = new ScreenSaverDefeater();
  226480. }
  226481. bool Desktop::isScreenSaverEnabled()
  226482. {
  226483. return screenSaverDefeater == 0;
  226484. }
  226485. #else
  226486. static IOPMAssertionID screenSaverDisablerID = 0;
  226487. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  226488. {
  226489. if (isEnabled)
  226490. {
  226491. if (screenSaverDisablerID != 0)
  226492. {
  226493. IOPMAssertionRelease (screenSaverDisablerID);
  226494. screenSaverDisablerID = 0;
  226495. }
  226496. }
  226497. else
  226498. {
  226499. if (screenSaverDisablerID == 0)
  226500. {
  226501. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  226502. IOPMAssertionCreateWithName (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226503. CFSTR ("Juce"), &screenSaverDisablerID);
  226504. #else
  226505. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep, kIOPMAssertionLevelOn,
  226506. &screenSaverDisablerID);
  226507. #endif
  226508. }
  226509. }
  226510. }
  226511. bool Desktop::isScreenSaverEnabled()
  226512. {
  226513. return screenSaverDisablerID == 0;
  226514. }
  226515. #endif
  226516. void juce_updateMultiMonitorInfo (Array <Rectangle<int> >& monitorCoords, const bool clipToWorkArea)
  226517. {
  226518. const ScopedAutoReleasePool pool;
  226519. monitorCoords.clear();
  226520. NSArray* screens = [NSScreen screens];
  226521. const CGFloat mainScreenBottom = [[[NSScreen screens] objectAtIndex: 0] frame].size.height;
  226522. for (unsigned int i = 0; i < [screens count]; ++i)
  226523. {
  226524. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  226525. NSRect r = clipToWorkArea ? [s visibleFrame]
  226526. : [s frame];
  226527. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  226528. monitorCoords.add (convertToRectInt (r));
  226529. }
  226530. jassert (monitorCoords.size() > 0);
  226531. }
  226532. #endif
  226533. #endif
  226534. /*** End of inlined file: juce_mac_MiscUtilities.mm ***/
  226535. #endif
  226536. /*** Start of inlined file: juce_mac_Debugging.mm ***/
  226537. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226538. // compiled on its own).
  226539. #if JUCE_INCLUDED_FILE
  226540. void Logger::outputDebugString (const String& text)
  226541. {
  226542. std::cerr << text << std::endl;
  226543. }
  226544. JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger()
  226545. {
  226546. static char testResult = 0;
  226547. if (testResult == 0)
  226548. {
  226549. struct kinfo_proc info;
  226550. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  226551. size_t sz = sizeof (info);
  226552. sysctl (m, 4, &info, &sz, 0, 0);
  226553. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  226554. }
  226555. return testResult > 0;
  226556. }
  226557. JUCE_API bool JUCE_CALLTYPE Process::isRunningUnderDebugger()
  226558. {
  226559. return juce_isRunningUnderDebugger();
  226560. }
  226561. #endif
  226562. /*** End of inlined file: juce_mac_Debugging.mm ***/
  226563. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  226564. #if JUCE_IOS
  226565. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  226566. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226567. // compiled on its own).
  226568. #if JUCE_INCLUDED_FILE
  226569. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  226570. #define SUPPORT_10_4_FONTS 1
  226571. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  226572. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  226573. #define SUPPORT_ONLY_10_4_FONTS 1
  226574. #endif
  226575. END_JUCE_NAMESPACE
  226576. @interface NSFont (PrivateHack)
  226577. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  226578. @end
  226579. BEGIN_JUCE_NAMESPACE
  226580. #endif
  226581. class MacTypeface : public Typeface
  226582. {
  226583. public:
  226584. MacTypeface (const Font& font)
  226585. : Typeface (font.getTypefaceName())
  226586. {
  226587. const ScopedAutoReleasePool pool;
  226588. renderingTransform = CGAffineTransformIdentity;
  226589. bool needsItalicTransform = false;
  226590. #if JUCE_IOS
  226591. NSString* fontName = juceStringToNS (font.getTypefaceName());
  226592. if (font.isItalic() || font.isBold())
  226593. {
  226594. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  226595. for (NSString* i in familyFonts)
  226596. {
  226597. const String fn (nsStringToJuce (i));
  226598. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  226599. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  226600. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  226601. || afterDash.containsIgnoreCase ("italic")
  226602. || fn.endsWithIgnoreCase ("oblique")
  226603. || fn.endsWithIgnoreCase ("italic");
  226604. if (probablyBold == font.isBold()
  226605. && probablyItalic == font.isItalic())
  226606. {
  226607. fontName = i;
  226608. needsItalicTransform = false;
  226609. break;
  226610. }
  226611. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  226612. {
  226613. fontName = i;
  226614. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  226615. }
  226616. }
  226617. if (needsItalicTransform)
  226618. renderingTransform.c = 0.15f;
  226619. }
  226620. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  226621. const int ascender = abs (CGFontGetAscent (fontRef));
  226622. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  226623. ascent = ascender / totalHeight;
  226624. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226625. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  226626. #else
  226627. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  226628. if (font.isItalic())
  226629. {
  226630. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  226631. toHaveTrait: NSItalicFontMask];
  226632. if (newFont == nsFont)
  226633. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  226634. nsFont = newFont;
  226635. }
  226636. if (font.isBold())
  226637. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  226638. [nsFont retain];
  226639. ascent = std::abs ((float) [nsFont ascender]);
  226640. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  226641. ascent /= totalSize;
  226642. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  226643. if (needsItalicTransform)
  226644. {
  226645. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  226646. renderingTransform.c = 0.15f;
  226647. }
  226648. #if SUPPORT_ONLY_10_4_FONTS
  226649. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226650. if (atsFont == 0)
  226651. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226652. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226653. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226654. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226655. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226656. #else
  226657. #if SUPPORT_10_4_FONTS
  226658. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226659. {
  226660. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226661. if (atsFont == 0)
  226662. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  226663. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  226664. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  226665. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226666. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  226667. }
  226668. else
  226669. #endif
  226670. {
  226671. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  226672. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  226673. unitsToHeightScaleFactor = 1.0f / totalHeight;
  226674. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  226675. }
  226676. #endif
  226677. #endif
  226678. }
  226679. ~MacTypeface()
  226680. {
  226681. #if ! JUCE_IOS
  226682. [nsFont release];
  226683. #endif
  226684. if (fontRef != 0)
  226685. CGFontRelease (fontRef);
  226686. }
  226687. float getAscent() const
  226688. {
  226689. return ascent;
  226690. }
  226691. float getDescent() const
  226692. {
  226693. return 1.0f - ascent;
  226694. }
  226695. float getStringWidth (const String& text)
  226696. {
  226697. if (fontRef == 0 || text.isEmpty())
  226698. return 0;
  226699. const int length = text.length();
  226700. HeapBlock <CGGlyph> glyphs;
  226701. createGlyphsForString (text, length, glyphs);
  226702. float x = 0;
  226703. #if SUPPORT_ONLY_10_4_FONTS
  226704. HeapBlock <NSSize> advances (length);
  226705. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226706. for (int i = 0; i < length; ++i)
  226707. x += advances[i].width;
  226708. #else
  226709. #if SUPPORT_10_4_FONTS
  226710. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226711. {
  226712. HeapBlock <NSSize> advances (length);
  226713. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  226714. for (int i = 0; i < length; ++i)
  226715. x += advances[i].width;
  226716. }
  226717. else
  226718. #endif
  226719. {
  226720. HeapBlock <int> advances (length);
  226721. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226722. for (int i = 0; i < length; ++i)
  226723. x += advances[i];
  226724. }
  226725. #endif
  226726. return x * unitsToHeightScaleFactor;
  226727. }
  226728. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  226729. {
  226730. xOffsets.add (0);
  226731. if (fontRef == 0 || text.isEmpty())
  226732. return;
  226733. const int length = text.length();
  226734. HeapBlock <CGGlyph> glyphs;
  226735. createGlyphsForString (text, length, glyphs);
  226736. #if SUPPORT_ONLY_10_4_FONTS
  226737. HeapBlock <NSSize> advances (length);
  226738. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  226739. int x = 0;
  226740. for (int i = 0; i < length; ++i)
  226741. {
  226742. x += advances[i].width;
  226743. xOffsets.add (x * unitsToHeightScaleFactor);
  226744. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  226745. }
  226746. #else
  226747. #if SUPPORT_10_4_FONTS
  226748. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226749. {
  226750. HeapBlock <NSSize> advances (length);
  226751. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226752. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  226753. float x = 0;
  226754. for (int i = 0; i < length; ++i)
  226755. {
  226756. x += advances[i].width;
  226757. xOffsets.add (x * unitsToHeightScaleFactor);
  226758. resultGlyphs.add (nsGlyphs[i]);
  226759. }
  226760. }
  226761. else
  226762. #endif
  226763. {
  226764. HeapBlock <int> advances (length);
  226765. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  226766. {
  226767. int x = 0;
  226768. for (int i = 0; i < length; ++i)
  226769. {
  226770. x += advances [i];
  226771. xOffsets.add (x * unitsToHeightScaleFactor);
  226772. resultGlyphs.add (glyphs[i]);
  226773. }
  226774. }
  226775. }
  226776. #endif
  226777. }
  226778. bool getOutlineForGlyph (int glyphNumber, Path& path)
  226779. {
  226780. #if JUCE_IOS
  226781. return false;
  226782. #else
  226783. if (nsFont == 0)
  226784. return false;
  226785. // we might need to apply a transform to the path, so it mustn't have anything else in it
  226786. jassert (path.isEmpty());
  226787. const ScopedAutoReleasePool pool;
  226788. NSBezierPath* bez = [NSBezierPath bezierPath];
  226789. [bez moveToPoint: NSMakePoint (0, 0)];
  226790. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  226791. inFont: nsFont];
  226792. for (int i = 0; i < [bez elementCount]; ++i)
  226793. {
  226794. NSPoint p[3];
  226795. switch ([bez elementAtIndex: i associatedPoints: p])
  226796. {
  226797. case NSMoveToBezierPathElement:
  226798. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  226799. break;
  226800. case NSLineToBezierPathElement:
  226801. path.lineTo ((float) p[0].x, (float) -p[0].y);
  226802. break;
  226803. case NSCurveToBezierPathElement:
  226804. 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);
  226805. break;
  226806. case NSClosePathBezierPathElement:
  226807. path.closeSubPath();
  226808. break;
  226809. default:
  226810. jassertfalse;
  226811. break;
  226812. }
  226813. }
  226814. path.applyTransform (pathTransform);
  226815. return true;
  226816. #endif
  226817. }
  226818. juce_UseDebuggingNewOperator
  226819. CGFontRef fontRef;
  226820. float fontHeightToCGSizeFactor;
  226821. CGAffineTransform renderingTransform;
  226822. private:
  226823. float ascent, unitsToHeightScaleFactor;
  226824. #if JUCE_IOS
  226825. #else
  226826. NSFont* nsFont;
  226827. AffineTransform pathTransform;
  226828. #endif
  226829. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  226830. {
  226831. #if SUPPORT_10_4_FONTS
  226832. #if ! SUPPORT_ONLY_10_4_FONTS
  226833. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  226834. #endif
  226835. {
  226836. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  226837. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  226838. for (int i = 0; i < length; ++i)
  226839. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  226840. return;
  226841. }
  226842. #endif
  226843. #if ! SUPPORT_ONLY_10_4_FONTS
  226844. if (charToGlyphMapper == 0)
  226845. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  226846. glyphs.malloc (length);
  226847. for (int i = 0; i < length; ++i)
  226848. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  226849. #endif
  226850. }
  226851. #if ! SUPPORT_ONLY_10_4_FONTS
  226852. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  226853. class CharToGlyphMapper
  226854. {
  226855. public:
  226856. CharToGlyphMapper (CGFontRef fontRef)
  226857. : segCount (0), endCode (0), startCode (0), idDelta (0),
  226858. idRangeOffset (0), glyphIndexes (0)
  226859. {
  226860. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  226861. if (cmapTable != 0)
  226862. {
  226863. const int numSubtables = getValue16 (cmapTable, 2);
  226864. for (int i = 0; i < numSubtables; ++i)
  226865. {
  226866. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  226867. {
  226868. const int offset = getValue32 (cmapTable, i * 8 + 8);
  226869. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  226870. {
  226871. const int length = getValue16 (cmapTable, offset + 2);
  226872. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  226873. segCount = segCountX2 / 2;
  226874. const int endCodeOffset = offset + 14;
  226875. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  226876. const int idDeltaOffset = startCodeOffset + segCountX2;
  226877. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  226878. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  226879. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  226880. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  226881. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  226882. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  226883. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  226884. }
  226885. break;
  226886. }
  226887. }
  226888. CFRelease (cmapTable);
  226889. }
  226890. }
  226891. ~CharToGlyphMapper()
  226892. {
  226893. if (endCode != 0)
  226894. {
  226895. CFRelease (endCode);
  226896. CFRelease (startCode);
  226897. CFRelease (idDelta);
  226898. CFRelease (idRangeOffset);
  226899. CFRelease (glyphIndexes);
  226900. }
  226901. }
  226902. int getGlyphForCharacter (const juce_wchar c) const
  226903. {
  226904. for (int i = 0; i < segCount; ++i)
  226905. {
  226906. if (getValue16 (endCode, i * 2) >= c)
  226907. {
  226908. const int start = getValue16 (startCode, i * 2);
  226909. if (start > c)
  226910. break;
  226911. const int delta = getValue16 (idDelta, i * 2);
  226912. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  226913. if (rangeOffset == 0)
  226914. return delta + c;
  226915. else
  226916. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  226917. }
  226918. }
  226919. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  226920. return jmax (-1, (int) c - 29);
  226921. }
  226922. private:
  226923. int segCount;
  226924. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  226925. static uint16 getValue16 (CFDataRef data, const int index)
  226926. {
  226927. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  226928. }
  226929. static uint32 getValue32 (CFDataRef data, const int index)
  226930. {
  226931. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  226932. }
  226933. };
  226934. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  226935. #endif
  226936. MacTypeface (const MacTypeface&);
  226937. MacTypeface& operator= (const MacTypeface&);
  226938. };
  226939. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  226940. {
  226941. return new MacTypeface (font);
  226942. }
  226943. const StringArray Font::findAllTypefaceNames()
  226944. {
  226945. StringArray names;
  226946. const ScopedAutoReleasePool pool;
  226947. #if JUCE_IOS
  226948. NSArray* fonts = [UIFont familyNames];
  226949. #else
  226950. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  226951. #endif
  226952. for (unsigned int i = 0; i < [fonts count]; ++i)
  226953. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  226954. names.sort (true);
  226955. return names;
  226956. }
  226957. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  226958. {
  226959. #if JUCE_IOS
  226960. defaultSans = "Helvetica";
  226961. defaultSerif = "Times New Roman";
  226962. defaultFixed = "Courier New";
  226963. #else
  226964. defaultSans = "Lucida Grande";
  226965. defaultSerif = "Times New Roman";
  226966. defaultFixed = "Monaco";
  226967. #endif
  226968. }
  226969. #endif
  226970. /*** End of inlined file: juce_mac_Fonts.mm ***/
  226971. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  226972. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226973. // compiled on its own).
  226974. #if JUCE_INCLUDED_FILE
  226975. class CoreGraphicsImage : public Image::SharedImage
  226976. {
  226977. public:
  226978. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  226979. : Image::SharedImage (format_, width_, height_)
  226980. {
  226981. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  226982. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  226983. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  226984. imageData = imageDataAllocated;
  226985. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  226986. : CGColorSpaceCreateDeviceRGB();
  226987. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  226988. colourSpace, getCGImageFlags (format_));
  226989. CGColorSpaceRelease (colourSpace);
  226990. }
  226991. ~CoreGraphicsImage()
  226992. {
  226993. CGContextRelease (context);
  226994. }
  226995. Image::ImageType getType() const { return Image::NativeImage; }
  226996. LowLevelGraphicsContext* createLowLevelContext();
  226997. SharedImage* clone()
  226998. {
  226999. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  227000. memcpy (im->imageData, imageData, lineStride * height);
  227001. return im;
  227002. }
  227003. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  227004. {
  227005. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  227006. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  227007. {
  227008. return CGBitmapContextCreateImage (nativeImage->context);
  227009. }
  227010. else
  227011. {
  227012. const Image::BitmapData srcData (juceImage, false);
  227013. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  227014. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  227015. 8, srcData.pixelStride * 8, srcData.lineStride,
  227016. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  227017. 0, true, kCGRenderingIntentDefault);
  227018. CGDataProviderRelease (provider);
  227019. return imageRef;
  227020. }
  227021. }
  227022. #if JUCE_MAC
  227023. static NSImage* createNSImage (const Image& image)
  227024. {
  227025. const ScopedAutoReleasePool pool;
  227026. NSImage* im = [[NSImage alloc] init];
  227027. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  227028. [im lockFocus];
  227029. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  227030. CGImageRef imageRef = createImage (image, false, colourSpace);
  227031. CGColorSpaceRelease (colourSpace);
  227032. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  227033. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  227034. CGImageRelease (imageRef);
  227035. [im unlockFocus];
  227036. return im;
  227037. }
  227038. #endif
  227039. CGContextRef context;
  227040. HeapBlock<uint8> imageDataAllocated;
  227041. private:
  227042. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  227043. {
  227044. #if JUCE_BIG_ENDIAN
  227045. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  227046. #else
  227047. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  227048. #endif
  227049. }
  227050. };
  227051. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  227052. {
  227053. #if USE_COREGRAPHICS_RENDERING
  227054. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  227055. #else
  227056. return createSoftwareImage (format, width, height, clearImage);
  227057. #endif
  227058. }
  227059. class CoreGraphicsContext : public LowLevelGraphicsContext
  227060. {
  227061. public:
  227062. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  227063. : context (context_),
  227064. flipHeight (flipHeight_),
  227065. lastClipRectIsValid (false),
  227066. state (new SavedState()),
  227067. numGradientLookupEntries (0)
  227068. {
  227069. CGContextRetain (context);
  227070. CGContextSaveGState(context);
  227071. CGContextSetShouldSmoothFonts (context, true);
  227072. CGContextSetShouldAntialias (context, true);
  227073. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227074. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  227075. greyColourSpace = CGColorSpaceCreateDeviceGray();
  227076. gradientCallbacks.version = 0;
  227077. gradientCallbacks.evaluate = gradientCallback;
  227078. gradientCallbacks.releaseInfo = 0;
  227079. setFont (Font());
  227080. }
  227081. ~CoreGraphicsContext()
  227082. {
  227083. CGContextRestoreGState (context);
  227084. CGContextRelease (context);
  227085. CGColorSpaceRelease (rgbColourSpace);
  227086. CGColorSpaceRelease (greyColourSpace);
  227087. }
  227088. bool isVectorDevice() const { return false; }
  227089. void setOrigin (int x, int y)
  227090. {
  227091. CGContextTranslateCTM (context, x, -y);
  227092. if (lastClipRectIsValid)
  227093. lastClipRect.translate (-x, -y);
  227094. }
  227095. bool clipToRectangle (const Rectangle<int>& r)
  227096. {
  227097. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  227098. if (lastClipRectIsValid)
  227099. {
  227100. // This is actually incorrect, because the actual clip region may be complex, and
  227101. // clipping its bounds to a rect may not be right... But, removing this shortcut
  227102. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  227103. // when calculating the resultant clip bounds, and makes the same mistake!
  227104. lastClipRect = lastClipRect.getIntersection (r);
  227105. return ! lastClipRect.isEmpty();
  227106. }
  227107. return ! isClipEmpty();
  227108. }
  227109. bool clipToRectangleList (const RectangleList& clipRegion)
  227110. {
  227111. if (clipRegion.isEmpty())
  227112. {
  227113. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  227114. lastClipRectIsValid = true;
  227115. lastClipRect = Rectangle<int>();
  227116. return false;
  227117. }
  227118. else
  227119. {
  227120. const int numRects = clipRegion.getNumRectangles();
  227121. HeapBlock <CGRect> rects (numRects);
  227122. for (int i = 0; i < numRects; ++i)
  227123. {
  227124. const Rectangle<int>& r = clipRegion.getRectangle(i);
  227125. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  227126. }
  227127. CGContextClipToRects (context, rects, numRects);
  227128. lastClipRectIsValid = false;
  227129. return ! isClipEmpty();
  227130. }
  227131. }
  227132. void excludeClipRectangle (const Rectangle<int>& r)
  227133. {
  227134. RectangleList remaining (getClipBounds());
  227135. remaining.subtract (r);
  227136. clipToRectangleList (remaining);
  227137. lastClipRectIsValid = false;
  227138. }
  227139. void clipToPath (const Path& path, const AffineTransform& transform)
  227140. {
  227141. createPath (path, transform);
  227142. CGContextClip (context);
  227143. lastClipRectIsValid = false;
  227144. }
  227145. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  227146. {
  227147. if (! transform.isSingularity())
  227148. {
  227149. Image singleChannelImage (sourceImage);
  227150. if (sourceImage.getFormat() != Image::SingleChannel)
  227151. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  227152. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  227153. flip();
  227154. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  227155. applyTransform (t);
  227156. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  227157. CGContextClipToMask (context, r, image);
  227158. applyTransform (t.inverted());
  227159. flip();
  227160. CGImageRelease (image);
  227161. lastClipRectIsValid = false;
  227162. }
  227163. }
  227164. bool clipRegionIntersects (const Rectangle<int>& r)
  227165. {
  227166. return getClipBounds().intersects (r);
  227167. }
  227168. const Rectangle<int> getClipBounds() const
  227169. {
  227170. if (! lastClipRectIsValid)
  227171. {
  227172. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227173. lastClipRectIsValid = true;
  227174. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  227175. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  227176. roundToInt (bounds.size.width),
  227177. roundToInt (bounds.size.height));
  227178. }
  227179. return lastClipRect;
  227180. }
  227181. bool isClipEmpty() const
  227182. {
  227183. return getClipBounds().isEmpty();
  227184. }
  227185. void saveState()
  227186. {
  227187. CGContextSaveGState (context);
  227188. stateStack.add (new SavedState (*state));
  227189. }
  227190. void restoreState()
  227191. {
  227192. CGContextRestoreGState (context);
  227193. SavedState* const top = stateStack.getLast();
  227194. if (top != 0)
  227195. {
  227196. state = top;
  227197. stateStack.removeLast (1, false);
  227198. lastClipRectIsValid = false;
  227199. }
  227200. else
  227201. {
  227202. jassertfalse; // trying to pop with an empty stack!
  227203. }
  227204. }
  227205. void setFill (const FillType& fillType)
  227206. {
  227207. state->fillType = fillType;
  227208. if (fillType.isColour())
  227209. {
  227210. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  227211. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  227212. CGContextSetAlpha (context, 1.0f);
  227213. }
  227214. }
  227215. void setOpacity (float newOpacity)
  227216. {
  227217. state->fillType.setOpacity (newOpacity);
  227218. setFill (state->fillType);
  227219. }
  227220. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  227221. {
  227222. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  227223. ? kCGInterpolationLow
  227224. : kCGInterpolationHigh);
  227225. }
  227226. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  227227. {
  227228. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  227229. }
  227230. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  227231. {
  227232. if (replaceExistingContents)
  227233. {
  227234. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  227235. CGContextClearRect (context, cgRect);
  227236. #else
  227237. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  227238. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  227239. CGContextClearRect (context, cgRect);
  227240. else
  227241. #endif
  227242. CGContextSetBlendMode (context, kCGBlendModeCopy);
  227243. #endif
  227244. fillCGRect (cgRect, false);
  227245. CGContextSetBlendMode (context, kCGBlendModeNormal);
  227246. }
  227247. else
  227248. {
  227249. if (state->fillType.isColour())
  227250. {
  227251. CGContextFillRect (context, cgRect);
  227252. }
  227253. else if (state->fillType.isGradient())
  227254. {
  227255. CGContextSaveGState (context);
  227256. CGContextClipToRect (context, cgRect);
  227257. drawGradient();
  227258. CGContextRestoreGState (context);
  227259. }
  227260. else
  227261. {
  227262. CGContextSaveGState (context);
  227263. CGContextClipToRect (context, cgRect);
  227264. drawImage (state->fillType.image, state->fillType.transform, true);
  227265. CGContextRestoreGState (context);
  227266. }
  227267. }
  227268. }
  227269. void fillPath (const Path& path, const AffineTransform& transform)
  227270. {
  227271. CGContextSaveGState (context);
  227272. if (state->fillType.isColour())
  227273. {
  227274. flip();
  227275. applyTransform (transform);
  227276. createPath (path);
  227277. if (path.isUsingNonZeroWinding())
  227278. CGContextFillPath (context);
  227279. else
  227280. CGContextEOFillPath (context);
  227281. }
  227282. else
  227283. {
  227284. createPath (path, transform);
  227285. if (path.isUsingNonZeroWinding())
  227286. CGContextClip (context);
  227287. else
  227288. CGContextEOClip (context);
  227289. if (state->fillType.isGradient())
  227290. drawGradient();
  227291. else
  227292. drawImage (state->fillType.image, state->fillType.transform, true);
  227293. }
  227294. CGContextRestoreGState (context);
  227295. }
  227296. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  227297. {
  227298. const int iw = sourceImage.getWidth();
  227299. const int ih = sourceImage.getHeight();
  227300. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  227301. CGContextSaveGState (context);
  227302. CGContextSetAlpha (context, state->fillType.getOpacity());
  227303. flip();
  227304. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  227305. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  227306. if (fillEntireClipAsTiles)
  227307. {
  227308. #if JUCE_IOS
  227309. CGContextDrawTiledImage (context, imageRect, image);
  227310. #else
  227311. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  227312. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  227313. // if it's doing a transformation - it's quicker to just draw lots of images manually
  227314. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  227315. CGContextDrawTiledImage (context, imageRect, image);
  227316. else
  227317. #endif
  227318. {
  227319. // Fallback to manually doing a tiled fill on 10.4
  227320. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  227321. int x = 0, y = 0;
  227322. while (x > clip.origin.x) x -= iw;
  227323. while (y > clip.origin.y) y -= ih;
  227324. const int right = (int) (clip.origin.x + clip.size.width);
  227325. const int bottom = (int) (clip.origin.y + clip.size.height);
  227326. while (y < bottom)
  227327. {
  227328. for (int x2 = x; x2 < right; x2 += iw)
  227329. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  227330. y += ih;
  227331. }
  227332. }
  227333. #endif
  227334. }
  227335. else
  227336. {
  227337. CGContextDrawImage (context, imageRect, image);
  227338. }
  227339. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  227340. CGContextRestoreGState (context);
  227341. }
  227342. void drawLine (const Line<float>& line)
  227343. {
  227344. if (state->fillType.isColour())
  227345. {
  227346. CGContextSetLineCap (context, kCGLineCapSquare);
  227347. CGContextSetLineWidth (context, 1.0f);
  227348. CGContextSetRGBStrokeColor (context,
  227349. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  227350. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  227351. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  227352. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  227353. CGContextStrokeLineSegments (context, cgLine, 1);
  227354. }
  227355. else
  227356. {
  227357. Path p;
  227358. p.addLineSegment (line, 1.0f);
  227359. fillPath (p, AffineTransform::identity);
  227360. }
  227361. }
  227362. void drawVerticalLine (const int x, float top, float bottom)
  227363. {
  227364. if (state->fillType.isColour())
  227365. {
  227366. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227367. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  227368. #else
  227369. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227370. // the x co-ord slightly to trick it..
  227371. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  227372. #endif
  227373. }
  227374. else
  227375. {
  227376. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  227377. }
  227378. }
  227379. void drawHorizontalLine (const int y, float left, float right)
  227380. {
  227381. if (state->fillType.isColour())
  227382. {
  227383. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  227384. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  227385. #else
  227386. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  227387. // the x co-ord slightly to trick it..
  227388. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  227389. #endif
  227390. }
  227391. else
  227392. {
  227393. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  227394. }
  227395. }
  227396. void setFont (const Font& newFont)
  227397. {
  227398. if (state->font != newFont)
  227399. {
  227400. state->fontRef = 0;
  227401. state->font = newFont;
  227402. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  227403. if (mf != 0)
  227404. {
  227405. state->fontRef = mf->fontRef;
  227406. CGContextSetFont (context, state->fontRef);
  227407. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  227408. state->fontTransform = mf->renderingTransform;
  227409. state->fontTransform.a *= state->font.getHorizontalScale();
  227410. CGContextSetTextMatrix (context, state->fontTransform);
  227411. }
  227412. }
  227413. }
  227414. const Font getFont()
  227415. {
  227416. return state->font;
  227417. }
  227418. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  227419. {
  227420. if (state->fontRef != 0 && state->fillType.isColour())
  227421. {
  227422. if (transform.isOnlyTranslation())
  227423. {
  227424. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  227425. CGGlyph g = glyphNumber;
  227426. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  227427. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  227428. }
  227429. else
  227430. {
  227431. CGContextSaveGState (context);
  227432. flip();
  227433. applyTransform (transform);
  227434. CGAffineTransform t = state->fontTransform;
  227435. t.d = -t.d;
  227436. CGContextSetTextMatrix (context, t);
  227437. CGGlyph g = glyphNumber;
  227438. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  227439. CGContextRestoreGState (context);
  227440. }
  227441. }
  227442. else
  227443. {
  227444. Path p;
  227445. Font& f = state->font;
  227446. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  227447. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  227448. .followedBy (transform));
  227449. }
  227450. }
  227451. private:
  227452. CGContextRef context;
  227453. const CGFloat flipHeight;
  227454. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  227455. CGFunctionCallbacks gradientCallbacks;
  227456. mutable Rectangle<int> lastClipRect;
  227457. mutable bool lastClipRectIsValid;
  227458. struct SavedState
  227459. {
  227460. SavedState()
  227461. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  227462. {
  227463. }
  227464. SavedState (const SavedState& other)
  227465. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  227466. fontTransform (other.fontTransform)
  227467. {
  227468. }
  227469. ~SavedState()
  227470. {
  227471. }
  227472. FillType fillType;
  227473. Font font;
  227474. CGFontRef fontRef;
  227475. CGAffineTransform fontTransform;
  227476. };
  227477. ScopedPointer <SavedState> state;
  227478. OwnedArray <SavedState> stateStack;
  227479. HeapBlock <PixelARGB> gradientLookupTable;
  227480. int numGradientLookupEntries;
  227481. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  227482. {
  227483. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  227484. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  227485. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  227486. colour.unpremultiply();
  227487. outData[0] = colour.getRed() / 255.0f;
  227488. outData[1] = colour.getGreen() / 255.0f;
  227489. outData[2] = colour.getBlue() / 255.0f;
  227490. outData[3] = colour.getAlpha() / 255.0f;
  227491. }
  227492. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  227493. {
  227494. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  227495. --numGradientLookupEntries;
  227496. CGShadingRef result = 0;
  227497. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  227498. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  227499. if (gradient.isRadial)
  227500. {
  227501. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  227502. p1, gradient.point1.getDistanceFrom (gradient.point2),
  227503. function, true, true);
  227504. }
  227505. else
  227506. {
  227507. result = CGShadingCreateAxial (rgbColourSpace, p1,
  227508. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  227509. function, true, true);
  227510. }
  227511. CGFunctionRelease (function);
  227512. return result;
  227513. }
  227514. void drawGradient()
  227515. {
  227516. flip();
  227517. applyTransform (state->fillType.transform);
  227518. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  227519. // you draw a gradient with high quality interp enabled).
  227520. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  227521. CGContextSetAlpha (context, state->fillType.getOpacity());
  227522. CGContextDrawShading (context, shading);
  227523. CGShadingRelease (shading);
  227524. }
  227525. void createPath (const Path& path) const
  227526. {
  227527. CGContextBeginPath (context);
  227528. Path::Iterator i (path);
  227529. while (i.next())
  227530. {
  227531. switch (i.elementType)
  227532. {
  227533. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  227534. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  227535. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  227536. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  227537. case Path::Iterator::closePath: CGContextClosePath (context); break;
  227538. default: jassertfalse; break;
  227539. }
  227540. }
  227541. }
  227542. void createPath (const Path& path, const AffineTransform& transform) const
  227543. {
  227544. CGContextBeginPath (context);
  227545. Path::Iterator i (path);
  227546. while (i.next())
  227547. {
  227548. switch (i.elementType)
  227549. {
  227550. case Path::Iterator::startNewSubPath:
  227551. transform.transformPoint (i.x1, i.y1);
  227552. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  227553. break;
  227554. case Path::Iterator::lineTo:
  227555. transform.transformPoint (i.x1, i.y1);
  227556. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  227557. break;
  227558. case Path::Iterator::quadraticTo:
  227559. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  227560. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  227561. break;
  227562. case Path::Iterator::cubicTo:
  227563. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  227564. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  227565. break;
  227566. case Path::Iterator::closePath:
  227567. CGContextClosePath (context); break;
  227568. default:
  227569. jassertfalse;
  227570. break;
  227571. }
  227572. }
  227573. }
  227574. void flip() const
  227575. {
  227576. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  227577. }
  227578. void applyTransform (const AffineTransform& transform) const
  227579. {
  227580. CGAffineTransform t;
  227581. t.a = transform.mat00;
  227582. t.b = transform.mat10;
  227583. t.c = transform.mat01;
  227584. t.d = transform.mat11;
  227585. t.tx = transform.mat02;
  227586. t.ty = transform.mat12;
  227587. CGContextConcatCTM (context, t);
  227588. }
  227589. CoreGraphicsContext (const CoreGraphicsContext&);
  227590. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  227591. };
  227592. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  227593. {
  227594. return new CoreGraphicsContext (context, height);
  227595. }
  227596. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  227597. const Image juce_loadWithCoreImage (InputStream& input)
  227598. {
  227599. MemoryBlock data;
  227600. input.readIntoMemoryBlock (data, -1);
  227601. #if JUCE_IOS
  227602. JUCE_AUTORELEASEPOOL
  227603. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  227604. length: data.getSize()
  227605. freeWhenDone: NO]];
  227606. if (image != nil)
  227607. {
  227608. CGImageRef loadedImage = image.CGImage;
  227609. #else
  227610. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  227611. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  227612. CGDataProviderRelease (provider);
  227613. if (imageSource != 0)
  227614. {
  227615. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  227616. CFRelease (imageSource);
  227617. #endif
  227618. if (loadedImage != 0)
  227619. {
  227620. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  227621. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  227622. && alphaInfo != kCGImageAlphaNoneSkipLast
  227623. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  227624. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  227625. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  227626. hasAlphaChan, Image::NativeImage);
  227627. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  227628. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  227629. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  227630. CGContextFlush (cgImage->context);
  227631. #if ! JUCE_IOS
  227632. CFRelease (loadedImage);
  227633. #endif
  227634. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  227635. // to find out whether the file they just loaded the image from had an alpha channel or not.
  227636. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  227637. return image;
  227638. }
  227639. }
  227640. return Image::null;
  227641. }
  227642. #endif
  227643. #endif
  227644. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  227645. /*** Start of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  227646. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227647. // compiled on its own).
  227648. #if JUCE_INCLUDED_FILE
  227649. class UIViewComponentPeer;
  227650. END_JUCE_NAMESPACE
  227651. #define JuceUIView MakeObjCClassName(JuceUIView)
  227652. @interface JuceUIView : UIView <UITextViewDelegate>
  227653. {
  227654. @public
  227655. UIViewComponentPeer* owner;
  227656. UITextView* hiddenTextView;
  227657. }
  227658. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner withFrame: (CGRect) frame;
  227659. - (void) dealloc;
  227660. - (void) drawRect: (CGRect) r;
  227661. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event;
  227662. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event;
  227663. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event;
  227664. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event;
  227665. - (BOOL) becomeFirstResponder;
  227666. - (BOOL) resignFirstResponder;
  227667. - (BOOL) canBecomeFirstResponder;
  227668. - (void) asyncRepaint: (id) rect;
  227669. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text;
  227670. @end
  227671. #define JuceUIViewController MakeObjCClassName(JuceUIViewController)
  227672. @interface JuceUIViewController : UIViewController
  227673. {
  227674. }
  227675. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation;
  227676. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation;
  227677. @end
  227678. #define JuceUIWindow MakeObjCClassName(JuceUIWindow)
  227679. @interface JuceUIWindow : UIWindow
  227680. {
  227681. @private
  227682. UIViewComponentPeer* owner;
  227683. bool isZooming;
  227684. }
  227685. - (void) setOwner: (UIViewComponentPeer*) owner;
  227686. - (void) becomeKeyWindow;
  227687. @end
  227688. BEGIN_JUCE_NAMESPACE
  227689. class UIViewComponentPeer : public ComponentPeer,
  227690. public FocusChangeListener
  227691. {
  227692. public:
  227693. UIViewComponentPeer (Component* const component,
  227694. const int windowStyleFlags,
  227695. UIView* viewToAttachTo);
  227696. ~UIViewComponentPeer();
  227697. void* getNativeHandle() const;
  227698. void setVisible (bool shouldBeVisible);
  227699. void setTitle (const String& title);
  227700. void setPosition (int x, int y);
  227701. void setSize (int w, int h);
  227702. void setBounds (int x, int y, int w, int h, bool isNowFullScreen);
  227703. const Rectangle<int> getBounds() const;
  227704. const Rectangle<int> getBounds (const bool global) const;
  227705. const Point<int> getScreenPosition() const;
  227706. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  227707. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  227708. void setAlpha (float newAlpha);
  227709. void setMinimised (bool shouldBeMinimised);
  227710. bool isMinimised() const;
  227711. void setFullScreen (bool shouldBeFullScreen);
  227712. bool isFullScreen() const;
  227713. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  227714. const BorderSize getFrameSize() const;
  227715. bool setAlwaysOnTop (bool alwaysOnTop);
  227716. void toFront (bool makeActiveWindow);
  227717. void toBehind (ComponentPeer* other);
  227718. void setIcon (const Image& newIcon);
  227719. virtual void drawRect (CGRect r);
  227720. virtual bool canBecomeKeyWindow();
  227721. virtual bool windowShouldClose();
  227722. virtual void redirectMovedOrResized();
  227723. virtual CGRect constrainRect (CGRect r);
  227724. virtual void viewFocusGain();
  227725. virtual void viewFocusLoss();
  227726. bool isFocused() const;
  227727. void grabFocus();
  227728. void textInputRequired (const Point<int>& position);
  227729. virtual BOOL textViewReplaceCharacters (const Range<int>& range, const String& text);
  227730. void updateHiddenTextContent (TextInputTarget* target);
  227731. void globalFocusChanged (Component*);
  227732. virtual BOOL shouldRotate (UIInterfaceOrientation interfaceOrientation);
  227733. virtual void displayRotated();
  227734. void handleTouches (UIEvent* e, bool isDown, bool isUp, bool isCancel);
  227735. void repaint (const Rectangle<int>& area);
  227736. void performAnyPendingRepaintsNow();
  227737. juce_UseDebuggingNewOperator
  227738. UIWindow* window;
  227739. JuceUIView* view;
  227740. JuceUIViewController* controller;
  227741. bool isSharedWindow, fullScreen, insideDrawRect;
  227742. static ModifierKeys currentModifiers;
  227743. static int64 getMouseTime (UIEvent* e)
  227744. {
  227745. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  227746. + (int64) ([e timestamp] * 1000.0);
  227747. }
  227748. static const Rectangle<int> rotatedScreenPosToReal (const Rectangle<int>& r)
  227749. {
  227750. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227751. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227752. {
  227753. case UIInterfaceOrientationPortrait:
  227754. return r;
  227755. case UIInterfaceOrientationPortraitUpsideDown:
  227756. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227757. r.getWidth(), r.getHeight());
  227758. case UIInterfaceOrientationLandscapeLeft:
  227759. return Rectangle<int> (r.getY(), screen.getHeight() - r.getRight(),
  227760. r.getHeight(), r.getWidth());
  227761. case UIInterfaceOrientationLandscapeRight:
  227762. return Rectangle<int> (screen.getWidth() - r.getBottom(), r.getX(),
  227763. r.getHeight(), r.getWidth());
  227764. default: jassertfalse; // unknown orientation!
  227765. }
  227766. return r;
  227767. }
  227768. static const Rectangle<int> realScreenPosToRotated (const Rectangle<int>& r)
  227769. {
  227770. const Rectangle<int> screen (convertToRectInt ([[UIScreen mainScreen] bounds]));
  227771. switch ([[UIApplication sharedApplication] statusBarOrientation])
  227772. {
  227773. case UIInterfaceOrientationPortrait:
  227774. return r;
  227775. case UIInterfaceOrientationPortraitUpsideDown:
  227776. return Rectangle<int> (screen.getWidth() - r.getRight(), screen.getHeight() - r.getBottom(),
  227777. r.getWidth(), r.getHeight());
  227778. case UIInterfaceOrientationLandscapeLeft:
  227779. return Rectangle<int> (screen.getHeight() - r.getBottom(), r.getX(),
  227780. r.getHeight(), r.getWidth());
  227781. case UIInterfaceOrientationLandscapeRight:
  227782. return Rectangle<int> (r.getY(), screen.getWidth() - r.getRight(),
  227783. r.getHeight(), r.getWidth());
  227784. default: jassertfalse; // unknown orientation!
  227785. }
  227786. return r;
  227787. }
  227788. Array <UITouch*> currentTouches;
  227789. };
  227790. END_JUCE_NAMESPACE
  227791. @implementation JuceUIViewController
  227792. - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
  227793. {
  227794. JuceUIView* juceView = (JuceUIView*) [self view];
  227795. jassert (juceView != 0 && juceView->owner != 0);
  227796. return juceView->owner->shouldRotate (interfaceOrientation);
  227797. }
  227798. - (void) didRotateFromInterfaceOrientation: (UIInterfaceOrientation) fromInterfaceOrientation
  227799. {
  227800. JuceUIView* juceView = (JuceUIView*) [self view];
  227801. jassert (juceView != 0 && juceView->owner != 0);
  227802. juceView->owner->displayRotated();
  227803. }
  227804. @end
  227805. @implementation JuceUIView
  227806. - (JuceUIView*) initWithOwner: (UIViewComponentPeer*) owner_
  227807. withFrame: (CGRect) frame
  227808. {
  227809. [super initWithFrame: frame];
  227810. owner = owner_;
  227811. hiddenTextView = [[UITextView alloc] initWithFrame: CGRectMake (0, 0, 0, 0)];
  227812. [self addSubview: hiddenTextView];
  227813. hiddenTextView.delegate = self;
  227814. hiddenTextView.autocapitalizationType = UITextAutocapitalizationTypeNone;
  227815. hiddenTextView.autocorrectionType = UITextAutocorrectionTypeNo;
  227816. return self;
  227817. }
  227818. - (void) dealloc
  227819. {
  227820. [hiddenTextView removeFromSuperview];
  227821. [hiddenTextView release];
  227822. [super dealloc];
  227823. }
  227824. - (void) drawRect: (CGRect) r
  227825. {
  227826. if (owner != 0)
  227827. owner->drawRect (r);
  227828. }
  227829. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  227830. {
  227831. return false;
  227832. }
  227833. ModifierKeys UIViewComponentPeer::currentModifiers;
  227834. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  227835. {
  227836. return UIViewComponentPeer::currentModifiers;
  227837. }
  227838. void ModifierKeys::updateCurrentModifiers() throw()
  227839. {
  227840. currentModifiers = UIViewComponentPeer::currentModifiers;
  227841. }
  227842. JUCE_NAMESPACE::Point<int> juce_lastMousePos;
  227843. - (void) touchesBegan: (NSSet*) touches withEvent: (UIEvent*) event
  227844. {
  227845. if (owner != 0)
  227846. owner->handleTouches (event, true, false, false);
  227847. }
  227848. - (void) touchesMoved: (NSSet*) touches withEvent: (UIEvent*) event
  227849. {
  227850. if (owner != 0)
  227851. owner->handleTouches (event, false, false, false);
  227852. }
  227853. - (void) touchesEnded: (NSSet*) touches withEvent: (UIEvent*) event
  227854. {
  227855. if (owner != 0)
  227856. owner->handleTouches (event, false, true, false);
  227857. }
  227858. - (void) touchesCancelled: (NSSet*) touches withEvent: (UIEvent*) event
  227859. {
  227860. if (owner != 0)
  227861. owner->handleTouches (event, false, true, true);
  227862. [self touchesEnded: touches withEvent: event];
  227863. }
  227864. - (BOOL) becomeFirstResponder
  227865. {
  227866. if (owner != 0)
  227867. owner->viewFocusGain();
  227868. return true;
  227869. }
  227870. - (BOOL) resignFirstResponder
  227871. {
  227872. if (owner != 0)
  227873. owner->viewFocusLoss();
  227874. return true;
  227875. }
  227876. - (BOOL) canBecomeFirstResponder
  227877. {
  227878. return owner != 0 && owner->canBecomeKeyWindow();
  227879. }
  227880. - (void) asyncRepaint: (id) rect
  227881. {
  227882. CGRect* r = (CGRect*) [((NSData*) rect) bytes];
  227883. [self setNeedsDisplayInRect: *r];
  227884. }
  227885. - (BOOL) textView: (UITextView*) textView shouldChangeTextInRange: (NSRange) range replacementText: (NSString*) text
  227886. {
  227887. return owner->textViewReplaceCharacters (Range<int> (range.location, range.location + range.length),
  227888. nsStringToJuce (text));
  227889. }
  227890. @end
  227891. @implementation JuceUIWindow
  227892. - (void) setOwner: (UIViewComponentPeer*) owner_
  227893. {
  227894. owner = owner_;
  227895. isZooming = false;
  227896. }
  227897. - (void) becomeKeyWindow
  227898. {
  227899. [super becomeKeyWindow];
  227900. if (owner != 0)
  227901. owner->grabFocus();
  227902. }
  227903. @end
  227904. BEGIN_JUCE_NAMESPACE
  227905. UIViewComponentPeer::UIViewComponentPeer (Component* const component,
  227906. const int windowStyleFlags,
  227907. UIView* viewToAttachTo)
  227908. : ComponentPeer (component, windowStyleFlags),
  227909. window (0),
  227910. view (0), controller (0),
  227911. isSharedWindow (viewToAttachTo != 0),
  227912. fullScreen (false),
  227913. insideDrawRect (false)
  227914. {
  227915. CGRect r = convertToCGRect (component->getLocalBounds());
  227916. view = [[JuceUIView alloc] initWithOwner: this withFrame: r];
  227917. if (isSharedWindow)
  227918. {
  227919. window = [viewToAttachTo window];
  227920. [viewToAttachTo addSubview: view];
  227921. setVisible (component->isVisible());
  227922. }
  227923. else
  227924. {
  227925. controller = [[JuceUIViewController alloc] init];
  227926. controller.view = view;
  227927. r = convertToCGRect (rotatedScreenPosToReal (component->getBounds()));
  227928. r.origin.y = [[UIScreen mainScreen] bounds].size.height - (r.origin.y + r.size.height);
  227929. window = [[JuceUIWindow alloc] init];
  227930. window.frame = r;
  227931. window.opaque = component->isOpaque();
  227932. view.opaque = component->isOpaque();
  227933. window.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227934. view.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent: 0];
  227935. [((JuceUIWindow*) window) setOwner: this];
  227936. if (component->isAlwaysOnTop())
  227937. window.windowLevel = UIWindowLevelAlert;
  227938. [window addSubview: view];
  227939. view.frame = CGRectMake (0, 0, r.size.width, r.size.height);
  227940. view.hidden = ! component->isVisible();
  227941. window.hidden = ! component->isVisible();
  227942. view.multipleTouchEnabled = YES;
  227943. }
  227944. setTitle (component->getName());
  227945. Desktop::getInstance().addFocusChangeListener (this);
  227946. }
  227947. UIViewComponentPeer::~UIViewComponentPeer()
  227948. {
  227949. Desktop::getInstance().removeFocusChangeListener (this);
  227950. view->owner = 0;
  227951. [view removeFromSuperview];
  227952. [view release];
  227953. [controller release];
  227954. if (! isSharedWindow)
  227955. {
  227956. [((JuceUIWindow*) window) setOwner: 0];
  227957. [window release];
  227958. }
  227959. }
  227960. void* UIViewComponentPeer::getNativeHandle() const
  227961. {
  227962. return view;
  227963. }
  227964. void UIViewComponentPeer::setVisible (bool shouldBeVisible)
  227965. {
  227966. view.hidden = ! shouldBeVisible;
  227967. if (! isSharedWindow)
  227968. window.hidden = ! shouldBeVisible;
  227969. }
  227970. void UIViewComponentPeer::setTitle (const String& title)
  227971. {
  227972. // xxx is this possible?
  227973. }
  227974. void UIViewComponentPeer::setPosition (int x, int y)
  227975. {
  227976. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  227977. }
  227978. void UIViewComponentPeer::setSize (int w, int h)
  227979. {
  227980. setBounds (component->getX(), component->getY(), w, h, false);
  227981. }
  227982. void UIViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  227983. {
  227984. fullScreen = isNowFullScreen;
  227985. w = jmax (0, w);
  227986. h = jmax (0, h);
  227987. if (isSharedWindow)
  227988. {
  227989. CGRect r = CGRectMake ((float) x, (float) y, (float) w, (float) h);
  227990. if ([view frame].size.width != r.size.width
  227991. || [view frame].size.height != r.size.height)
  227992. [view setNeedsDisplay];
  227993. view.frame = r;
  227994. }
  227995. else
  227996. {
  227997. const Rectangle<int> bounds (rotatedScreenPosToReal (Rectangle<int> (x, y, w, h)));
  227998. window.frame = convertToCGRect (bounds);
  227999. view.frame = CGRectMake (0, 0, (float) bounds.getWidth(), (float) bounds.getHeight());
  228000. handleMovedOrResized();
  228001. }
  228002. }
  228003. const Rectangle<int> UIViewComponentPeer::getBounds (const bool global) const
  228004. {
  228005. CGRect r = [view frame];
  228006. if (global && [view window] != 0)
  228007. {
  228008. r = [view convertRect: r toView: nil];
  228009. CGRect wr = [[view window] frame];
  228010. const Rectangle<int> windowBounds (realScreenPosToRotated (convertToRectInt (wr)));
  228011. r.origin.x = windowBounds.getX();
  228012. r.origin.y = windowBounds.getY();
  228013. }
  228014. return convertToRectInt (r);
  228015. }
  228016. const Rectangle<int> UIViewComponentPeer::getBounds() const
  228017. {
  228018. return getBounds (! isSharedWindow);
  228019. }
  228020. const Point<int> UIViewComponentPeer::getScreenPosition() const
  228021. {
  228022. return getBounds (true).getPosition();
  228023. }
  228024. const Point<int> UIViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  228025. {
  228026. return relativePosition + getScreenPosition();
  228027. }
  228028. const Point<int> UIViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  228029. {
  228030. return screenPosition - getScreenPosition();
  228031. }
  228032. CGRect UIViewComponentPeer::constrainRect (CGRect r)
  228033. {
  228034. if (constrainer != 0)
  228035. {
  228036. CGRect current = [window frame];
  228037. current.origin.y = [[UIScreen mainScreen] bounds].size.height - current.origin.y - current.size.height;
  228038. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.origin.y - r.size.height;
  228039. Rectangle<int> pos (convertToRectInt (r));
  228040. Rectangle<int> original (convertToRectInt (current));
  228041. constrainer->checkBounds (pos, original,
  228042. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  228043. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  228044. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  228045. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  228046. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  228047. r.origin.x = pos.getX();
  228048. r.origin.y = [[UIScreen mainScreen] bounds].size.height - r.size.height - pos.getY();
  228049. r.size.width = pos.getWidth();
  228050. r.size.height = pos.getHeight();
  228051. }
  228052. return r;
  228053. }
  228054. void UIViewComponentPeer::setAlpha (float newAlpha)
  228055. {
  228056. [[view window] setAlpha: (CGFloat) newAlpha];
  228057. }
  228058. void UIViewComponentPeer::setMinimised (bool shouldBeMinimised)
  228059. {
  228060. }
  228061. bool UIViewComponentPeer::isMinimised() const
  228062. {
  228063. return false;
  228064. }
  228065. void UIViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  228066. {
  228067. if (! isSharedWindow)
  228068. {
  228069. Rectangle<int> r (shouldBeFullScreen ? Desktop::getInstance().getMainMonitorArea()
  228070. : lastNonFullscreenBounds);
  228071. if ((! shouldBeFullScreen) && r.isEmpty())
  228072. r = getBounds();
  228073. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  228074. if (! r.isEmpty())
  228075. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  228076. component->repaint();
  228077. }
  228078. }
  228079. bool UIViewComponentPeer::isFullScreen() const
  228080. {
  228081. return fullScreen;
  228082. }
  228083. namespace
  228084. {
  228085. Desktop::DisplayOrientation convertToJuceOrientation (UIInterfaceOrientation interfaceOrientation)
  228086. {
  228087. switch (interfaceOrientation)
  228088. {
  228089. case UIInterfaceOrientationPortrait: return Desktop::upright;
  228090. case UIInterfaceOrientationPortraitUpsideDown: return Desktop::upsideDown;
  228091. case UIInterfaceOrientationLandscapeLeft: return Desktop::rotatedClockwise;
  228092. case UIInterfaceOrientationLandscapeRight: return Desktop::rotatedAntiClockwise;
  228093. default: jassertfalse; // unknown orientation!
  228094. }
  228095. return Desktop::upright;
  228096. }
  228097. }
  228098. BOOL UIViewComponentPeer::shouldRotate (UIInterfaceOrientation interfaceOrientation)
  228099. {
  228100. return Desktop::getInstance().isOrientationEnabled (convertToJuceOrientation (interfaceOrientation));
  228101. }
  228102. void UIViewComponentPeer::displayRotated()
  228103. {
  228104. const Rectangle<int> oldArea (component->getBounds());
  228105. const Rectangle<int> oldDesktop (Desktop::getInstance().getMainMonitorArea());
  228106. Desktop::getInstance().refreshMonitorSizes();
  228107. if (fullScreen)
  228108. {
  228109. fullScreen = false;
  228110. setFullScreen (true);
  228111. }
  228112. else
  228113. {
  228114. const float l = oldArea.getX() / (float) oldDesktop.getWidth();
  228115. const float r = oldArea.getRight() / (float) oldDesktop.getWidth();
  228116. const float t = oldArea.getY() / (float) oldDesktop.getHeight();
  228117. const float b = oldArea.getBottom() / (float) oldDesktop.getHeight();
  228118. const Rectangle<int> newDesktop (Desktop::getInstance().getMainMonitorArea());
  228119. setBounds ((int) (l * newDesktop.getWidth()),
  228120. (int) (t * newDesktop.getHeight()),
  228121. (int) ((r - l) * newDesktop.getWidth()),
  228122. (int) ((b - t) * newDesktop.getHeight()),
  228123. false);
  228124. }
  228125. }
  228126. bool UIViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  228127. {
  228128. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  228129. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  228130. return false;
  228131. UIView* v = [view hitTest: CGPointMake ((float) position.getX(), (float) position.getY())
  228132. withEvent: nil];
  228133. if (trueIfInAChildWindow)
  228134. return v != nil;
  228135. return v == view;
  228136. }
  228137. const BorderSize UIViewComponentPeer::getFrameSize() const
  228138. {
  228139. return BorderSize();
  228140. }
  228141. bool UIViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  228142. {
  228143. if (! isSharedWindow)
  228144. window.windowLevel = alwaysOnTop ? UIWindowLevelAlert : UIWindowLevelNormal;
  228145. return true;
  228146. }
  228147. void UIViewComponentPeer::toFront (bool makeActiveWindow)
  228148. {
  228149. if (isSharedWindow)
  228150. [[view superview] bringSubviewToFront: view];
  228151. if (window != 0 && component->isVisible())
  228152. [window makeKeyAndVisible];
  228153. }
  228154. void UIViewComponentPeer::toBehind (ComponentPeer* other)
  228155. {
  228156. UIViewComponentPeer* const otherPeer = dynamic_cast <UIViewComponentPeer*> (other);
  228157. jassert (otherPeer != 0); // wrong type of window?
  228158. if (otherPeer != 0)
  228159. {
  228160. if (isSharedWindow)
  228161. {
  228162. [[view superview] insertSubview: view belowSubview: otherPeer->view];
  228163. }
  228164. else
  228165. {
  228166. jassertfalse; // don't know how to do this
  228167. }
  228168. }
  228169. }
  228170. void UIViewComponentPeer::setIcon (const Image& /*newIcon*/)
  228171. {
  228172. // to do..
  228173. }
  228174. void UIViewComponentPeer::handleTouches (UIEvent* event, const bool isDown, const bool isUp, bool isCancel)
  228175. {
  228176. NSArray* touches = [[event touchesForView: view] allObjects];
  228177. for (unsigned int i = 0; i < [touches count]; ++i)
  228178. {
  228179. UITouch* touch = [touches objectAtIndex: i];
  228180. CGPoint p = [touch locationInView: view];
  228181. const Point<int> pos ((int) p.x, (int) p.y);
  228182. juce_lastMousePos = pos + getScreenPosition();
  228183. const int64 time = getMouseTime (event);
  228184. int touchIndex = currentTouches.indexOf (touch);
  228185. if (touchIndex < 0)
  228186. {
  228187. touchIndex = currentTouches.size();
  228188. currentTouches.add (touch);
  228189. }
  228190. if (isDown)
  228191. {
  228192. currentModifiers = currentModifiers.withoutMouseButtons();
  228193. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  228194. currentModifiers = currentModifiers.withoutMouseButtons().withFlags (ModifierKeys::leftButtonModifier);
  228195. }
  228196. else if (isUp)
  228197. {
  228198. currentModifiers = currentModifiers.withoutMouseButtons();
  228199. currentTouches.remove (touchIndex);
  228200. }
  228201. if (isCancel)
  228202. currentTouches.clear();
  228203. handleMouseEvent (touchIndex, pos, currentModifiers, time);
  228204. }
  228205. }
  228206. static UIViewComponentPeer* currentlyFocusedPeer = 0;
  228207. void UIViewComponentPeer::viewFocusGain()
  228208. {
  228209. if (currentlyFocusedPeer != this)
  228210. {
  228211. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  228212. currentlyFocusedPeer->handleFocusLoss();
  228213. currentlyFocusedPeer = this;
  228214. handleFocusGain();
  228215. }
  228216. }
  228217. void UIViewComponentPeer::viewFocusLoss()
  228218. {
  228219. if (currentlyFocusedPeer == this)
  228220. {
  228221. currentlyFocusedPeer = 0;
  228222. handleFocusLoss();
  228223. }
  228224. }
  228225. void juce_HandleProcessFocusChange()
  228226. {
  228227. if (UIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  228228. {
  228229. if (Process::isForegroundProcess())
  228230. {
  228231. currentlyFocusedPeer->handleFocusGain();
  228232. ComponentPeer::bringModalComponentToFront();
  228233. }
  228234. else
  228235. {
  228236. currentlyFocusedPeer->handleFocusLoss();
  228237. // turn kiosk mode off if we lose focus..
  228238. Desktop::getInstance().setKioskModeComponent (0);
  228239. }
  228240. }
  228241. }
  228242. bool UIViewComponentPeer::isFocused() const
  228243. {
  228244. return isSharedWindow ? this == currentlyFocusedPeer
  228245. : (window != 0 && [window isKeyWindow]);
  228246. }
  228247. void UIViewComponentPeer::grabFocus()
  228248. {
  228249. if (window != 0)
  228250. {
  228251. [window makeKeyWindow];
  228252. viewFocusGain();
  228253. }
  228254. }
  228255. void UIViewComponentPeer::textInputRequired (const Point<int>&)
  228256. {
  228257. }
  228258. void UIViewComponentPeer::updateHiddenTextContent (TextInputTarget* target)
  228259. {
  228260. view->hiddenTextView.text = juceStringToNS (target->getTextInRange (Range<int> (0, target->getHighlightedRegion().getStart())));
  228261. view->hiddenTextView.selectedRange = NSMakeRange (target->getHighlightedRegion().getStart(), 0);
  228262. }
  228263. BOOL UIViewComponentPeer::textViewReplaceCharacters (const Range<int>& range, const String& text)
  228264. {
  228265. TextInputTarget* const target = findCurrentTextInputTarget();
  228266. if (target != 0)
  228267. {
  228268. const Range<int> currentSelection (target->getHighlightedRegion());
  228269. if (range.getLength() == 1 && text.isEmpty()) // (detect backspace)
  228270. if (currentSelection.isEmpty())
  228271. target->setHighlightedRegion (currentSelection.withStart (currentSelection.getStart() - 1));
  228272. target->insertTextAtCaret (text);
  228273. updateHiddenTextContent (target);
  228274. }
  228275. return NO;
  228276. }
  228277. void UIViewComponentPeer::globalFocusChanged (Component*)
  228278. {
  228279. TextInputTarget* const target = findCurrentTextInputTarget();
  228280. if (target != 0)
  228281. {
  228282. Component* comp = dynamic_cast<Component*> (target);
  228283. Point<int> pos (comp->relativePositionToOtherComponent (component, Point<int>()));
  228284. view->hiddenTextView.frame = CGRectMake (pos.getX(), pos.getY(), 0, 0);
  228285. updateHiddenTextContent (target);
  228286. [view->hiddenTextView becomeFirstResponder];
  228287. }
  228288. else
  228289. {
  228290. [view->hiddenTextView resignFirstResponder];
  228291. }
  228292. }
  228293. void UIViewComponentPeer::drawRect (CGRect r)
  228294. {
  228295. if (r.size.width < 1.0f || r.size.height < 1.0f)
  228296. return;
  228297. CGContextRef cg = UIGraphicsGetCurrentContext();
  228298. if (! component->isOpaque())
  228299. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  228300. CGContextConcatCTM (cg, CGAffineTransformMake (1, 0, 0, -1, 0, view.bounds.size.height));
  228301. CoreGraphicsContext g (cg, view.bounds.size.height);
  228302. insideDrawRect = true;
  228303. handlePaint (g);
  228304. insideDrawRect = false;
  228305. }
  228306. bool UIViewComponentPeer::canBecomeKeyWindow()
  228307. {
  228308. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  228309. }
  228310. bool UIViewComponentPeer::windowShouldClose()
  228311. {
  228312. if (! isValidPeer (this))
  228313. return YES;
  228314. handleUserClosingWindow();
  228315. return NO;
  228316. }
  228317. void UIViewComponentPeer::redirectMovedOrResized()
  228318. {
  228319. handleMovedOrResized();
  228320. }
  228321. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  228322. {
  228323. }
  228324. class AsyncRepaintMessage : public CallbackMessage
  228325. {
  228326. public:
  228327. UIViewComponentPeer* const peer;
  228328. const Rectangle<int> rect;
  228329. AsyncRepaintMessage (UIViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  228330. : peer (peer_), rect (rect_)
  228331. {
  228332. }
  228333. void messageCallback()
  228334. {
  228335. if (ComponentPeer::isValidPeer (peer))
  228336. peer->repaint (rect);
  228337. }
  228338. };
  228339. void UIViewComponentPeer::repaint (const Rectangle<int>& area)
  228340. {
  228341. if (insideDrawRect || ! MessageManager::getInstance()->isThisTheMessageThread())
  228342. {
  228343. (new AsyncRepaintMessage (this, area))->post();
  228344. }
  228345. else
  228346. {
  228347. [view setNeedsDisplayInRect: convertToCGRect (area)];
  228348. }
  228349. }
  228350. void UIViewComponentPeer::performAnyPendingRepaintsNow()
  228351. {
  228352. }
  228353. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  228354. {
  228355. return new UIViewComponentPeer (this, styleFlags, (UIView*) windowToAttachTo);
  228356. }
  228357. const Image juce_createIconForFile (const File& file)
  228358. {
  228359. return Image::null;
  228360. }
  228361. void Desktop::createMouseInputSources()
  228362. {
  228363. for (int i = 0; i < 10; ++i)
  228364. mouseSources.add (new MouseInputSource (i, false));
  228365. }
  228366. bool Desktop::canUseSemiTransparentWindows() throw()
  228367. {
  228368. return true;
  228369. }
  228370. const Point<int> Desktop::getMousePosition()
  228371. {
  228372. return juce_lastMousePos;
  228373. }
  228374. void Desktop::setMousePosition (const Point<int>&)
  228375. {
  228376. }
  228377. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  228378. {
  228379. return convertToJuceOrientation ([[UIApplication sharedApplication] statusBarOrientation]);
  228380. }
  228381. void juce_updateMultiMonitorInfo (Array <Rectangle <int> >& monitorCoords, const bool clipToWorkArea)
  228382. {
  228383. const ScopedAutoReleasePool pool;
  228384. monitorCoords.clear();
  228385. CGRect r = clipToWorkArea ? [[UIScreen mainScreen] applicationFrame]
  228386. : [[UIScreen mainScreen] bounds];
  228387. monitorCoords.add (UIViewComponentPeer::realScreenPosToRotated (convertToRectInt (r)));
  228388. }
  228389. const int KeyPress::spaceKey = ' ';
  228390. const int KeyPress::returnKey = 0x0d;
  228391. const int KeyPress::escapeKey = 0x1b;
  228392. const int KeyPress::backspaceKey = 0x7f;
  228393. const int KeyPress::leftKey = 0x1000;
  228394. const int KeyPress::rightKey = 0x1001;
  228395. const int KeyPress::upKey = 0x1002;
  228396. const int KeyPress::downKey = 0x1003;
  228397. const int KeyPress::pageUpKey = 0x1004;
  228398. const int KeyPress::pageDownKey = 0x1005;
  228399. const int KeyPress::endKey = 0x1006;
  228400. const int KeyPress::homeKey = 0x1007;
  228401. const int KeyPress::deleteKey = 0x1008;
  228402. const int KeyPress::insertKey = -1;
  228403. const int KeyPress::tabKey = 9;
  228404. const int KeyPress::F1Key = 0x2001;
  228405. const int KeyPress::F2Key = 0x2002;
  228406. const int KeyPress::F3Key = 0x2003;
  228407. const int KeyPress::F4Key = 0x2004;
  228408. const int KeyPress::F5Key = 0x2005;
  228409. const int KeyPress::F6Key = 0x2006;
  228410. const int KeyPress::F7Key = 0x2007;
  228411. const int KeyPress::F8Key = 0x2008;
  228412. const int KeyPress::F9Key = 0x2009;
  228413. const int KeyPress::F10Key = 0x200a;
  228414. const int KeyPress::F11Key = 0x200b;
  228415. const int KeyPress::F12Key = 0x200c;
  228416. const int KeyPress::F13Key = 0x200d;
  228417. const int KeyPress::F14Key = 0x200e;
  228418. const int KeyPress::F15Key = 0x200f;
  228419. const int KeyPress::F16Key = 0x2010;
  228420. const int KeyPress::numberPad0 = 0x30020;
  228421. const int KeyPress::numberPad1 = 0x30021;
  228422. const int KeyPress::numberPad2 = 0x30022;
  228423. const int KeyPress::numberPad3 = 0x30023;
  228424. const int KeyPress::numberPad4 = 0x30024;
  228425. const int KeyPress::numberPad5 = 0x30025;
  228426. const int KeyPress::numberPad6 = 0x30026;
  228427. const int KeyPress::numberPad7 = 0x30027;
  228428. const int KeyPress::numberPad8 = 0x30028;
  228429. const int KeyPress::numberPad9 = 0x30029;
  228430. const int KeyPress::numberPadAdd = 0x3002a;
  228431. const int KeyPress::numberPadSubtract = 0x3002b;
  228432. const int KeyPress::numberPadMultiply = 0x3002c;
  228433. const int KeyPress::numberPadDivide = 0x3002d;
  228434. const int KeyPress::numberPadSeparator = 0x3002e;
  228435. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  228436. const int KeyPress::numberPadEquals = 0x30030;
  228437. const int KeyPress::numberPadDelete = 0x30031;
  228438. const int KeyPress::playKey = 0x30000;
  228439. const int KeyPress::stopKey = 0x30001;
  228440. const int KeyPress::fastForwardKey = 0x30002;
  228441. const int KeyPress::rewindKey = 0x30003;
  228442. #endif
  228443. /*** End of inlined file: juce_iphone_UIViewComponentPeer.mm ***/
  228444. /*** Start of inlined file: juce_iphone_MessageManager.mm ***/
  228445. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228446. // compiled on its own).
  228447. #if JUCE_INCLUDED_FILE
  228448. struct CallbackMessagePayload
  228449. {
  228450. MessageCallbackFunction* function;
  228451. void* parameter;
  228452. void* volatile result;
  228453. bool volatile hasBeenExecuted;
  228454. };
  228455. END_JUCE_NAMESPACE
  228456. @interface JuceCustomMessageHandler : NSObject
  228457. {
  228458. }
  228459. - (void) performCallback: (id) info;
  228460. @end
  228461. @implementation JuceCustomMessageHandler
  228462. - (void) performCallback: (id) info
  228463. {
  228464. if ([info isKindOfClass: [NSData class]])
  228465. {
  228466. JUCE_NAMESPACE::CallbackMessagePayload* pl = (JUCE_NAMESPACE::CallbackMessagePayload*) [((NSData*) info) bytes];
  228467. if (pl != 0)
  228468. {
  228469. pl->result = (*pl->function) (pl->parameter);
  228470. pl->hasBeenExecuted = true;
  228471. }
  228472. }
  228473. else
  228474. {
  228475. jassertfalse; // should never get here!
  228476. }
  228477. }
  228478. @end
  228479. BEGIN_JUCE_NAMESPACE
  228480. void MessageManager::runDispatchLoop()
  228481. {
  228482. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228483. runDispatchLoopUntil (-1);
  228484. }
  228485. void MessageManager::stopDispatchLoop()
  228486. {
  228487. [[[UIApplication sharedApplication] delegate] applicationWillTerminate: [UIApplication sharedApplication]];
  228488. exit (0); // iPhone apps get no mercy..
  228489. }
  228490. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228491. {
  228492. const ScopedAutoReleasePool pool;
  228493. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228494. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228495. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228496. while (! quitMessagePosted)
  228497. {
  228498. const ScopedAutoReleasePool pool;
  228499. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228500. beforeDate: endDate];
  228501. if (millisecondsToRunFor >= 0 && Time::getMillisecondCounter() >= endTime)
  228502. break;
  228503. }
  228504. return ! quitMessagePosted;
  228505. }
  228506. namespace iOSMessageLoopHelpers
  228507. {
  228508. static CFRunLoopRef runLoop = 0;
  228509. static CFRunLoopSourceRef runLoopSource = 0;
  228510. static OwnedArray <Message, CriticalSection>* pendingMessages = 0;
  228511. static JuceCustomMessageHandler* juceCustomMessageHandler = 0;
  228512. void runLoopSourceCallback (void*)
  228513. {
  228514. if (pendingMessages != 0)
  228515. {
  228516. int numDispatched = 0;
  228517. do
  228518. {
  228519. Message* const nextMessage = pendingMessages->removeAndReturn (0);
  228520. if (nextMessage == 0)
  228521. return;
  228522. const ScopedAutoReleasePool pool;
  228523. MessageManager::getInstance()->deliverMessage (nextMessage);
  228524. } while (++numDispatched <= 4);
  228525. CFRunLoopSourceSignal (runLoopSource);
  228526. CFRunLoopWakeUp (runLoop);
  228527. }
  228528. }
  228529. }
  228530. void MessageManager::doPlatformSpecificInitialisation()
  228531. {
  228532. using namespace iOSMessageLoopHelpers;
  228533. pendingMessages = new OwnedArray <Message, CriticalSection>();
  228534. runLoop = CFRunLoopGetCurrent();
  228535. CFRunLoopSourceContext sourceContext;
  228536. zerostruct (sourceContext);
  228537. sourceContext.perform = runLoopSourceCallback;
  228538. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  228539. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  228540. if (juceCustomMessageHandler == 0)
  228541. juceCustomMessageHandler = [[JuceCustomMessageHandler alloc] init];
  228542. }
  228543. void MessageManager::doPlatformSpecificShutdown()
  228544. {
  228545. using namespace iOSMessageLoopHelpers;
  228546. CFRunLoopSourceInvalidate (runLoopSource);
  228547. CFRelease (runLoopSource);
  228548. runLoopSource = 0;
  228549. deleteAndZero (pendingMessages);
  228550. if (juceCustomMessageHandler != 0)
  228551. {
  228552. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceCustomMessageHandler];
  228553. [juceCustomMessageHandler release];
  228554. juceCustomMessageHandler = 0;
  228555. }
  228556. }
  228557. bool juce_postMessageToSystemQueue (Message* message)
  228558. {
  228559. using namespace iOSMessageLoopHelpers;
  228560. if (pendingMessages != 0)
  228561. {
  228562. pendingMessages->add (message);
  228563. CFRunLoopSourceSignal (runLoopSource);
  228564. CFRunLoopWakeUp (runLoop);
  228565. }
  228566. return true;
  228567. }
  228568. void MessageManager::broadcastMessage (const String& value)
  228569. {
  228570. }
  228571. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  228572. {
  228573. using namespace iOSMessageLoopHelpers;
  228574. if (isThisTheMessageThread())
  228575. {
  228576. return (*callback) (data);
  228577. }
  228578. else
  228579. {
  228580. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  228581. // deadlock because the message manager is blocked from running, so can never
  228582. // call your function..
  228583. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  228584. const ScopedAutoReleasePool pool;
  228585. CallbackMessagePayload cmp;
  228586. cmp.function = callback;
  228587. cmp.parameter = data;
  228588. cmp.result = 0;
  228589. cmp.hasBeenExecuted = false;
  228590. [juceCustomMessageHandler performSelectorOnMainThread: @selector (performCallback:)
  228591. withObject: [NSData dataWithBytesNoCopy: &cmp
  228592. length: sizeof (cmp)
  228593. freeWhenDone: NO]
  228594. waitUntilDone: YES];
  228595. return cmp.result;
  228596. }
  228597. }
  228598. #endif
  228599. /*** End of inlined file: juce_iphone_MessageManager.mm ***/
  228600. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  228601. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228602. // compiled on its own).
  228603. #if JUCE_INCLUDED_FILE
  228604. #if JUCE_MAC
  228605. END_JUCE_NAMESPACE
  228606. using namespace JUCE_NAMESPACE;
  228607. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  228608. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  228609. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  228610. #else
  228611. @interface JuceFileChooserDelegate : NSObject
  228612. #endif
  228613. {
  228614. StringArray* filters;
  228615. }
  228616. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  228617. - (void) dealloc;
  228618. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  228619. @end
  228620. @implementation JuceFileChooserDelegate
  228621. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  228622. {
  228623. [super init];
  228624. filters = filters_;
  228625. return self;
  228626. }
  228627. - (void) dealloc
  228628. {
  228629. delete filters;
  228630. [super dealloc];
  228631. }
  228632. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  228633. {
  228634. (void) sender;
  228635. const File f (nsStringToJuce (filename));
  228636. for (int i = filters->size(); --i >= 0;)
  228637. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  228638. return true;
  228639. return f.isDirectory();
  228640. }
  228641. @end
  228642. BEGIN_JUCE_NAMESPACE
  228643. void FileChooser::showPlatformDialog (Array<File>& results,
  228644. const String& title,
  228645. const File& currentFileOrDirectory,
  228646. const String& filter,
  228647. bool selectsDirectory,
  228648. bool selectsFiles,
  228649. bool isSaveDialogue,
  228650. bool warnAboutOverwritingExistingFiles,
  228651. bool selectMultipleFiles,
  228652. FilePreviewComponent* extraInfoComponent)
  228653. {
  228654. const ScopedAutoReleasePool pool;
  228655. StringArray* filters = new StringArray();
  228656. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  228657. filters->trim();
  228658. filters->removeEmptyStrings();
  228659. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  228660. [delegate autorelease];
  228661. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  228662. : [NSOpenPanel openPanel];
  228663. [panel setTitle: juceStringToNS (title)];
  228664. if (! isSaveDialogue)
  228665. {
  228666. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228667. [openPanel setCanChooseDirectories: selectsDirectory];
  228668. [openPanel setCanChooseFiles: selectsFiles];
  228669. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  228670. }
  228671. [panel setDelegate: delegate];
  228672. if (isSaveDialogue || selectsDirectory)
  228673. [panel setCanCreateDirectories: YES];
  228674. String directory, filename;
  228675. if (currentFileOrDirectory.isDirectory())
  228676. {
  228677. directory = currentFileOrDirectory.getFullPathName();
  228678. }
  228679. else
  228680. {
  228681. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  228682. filename = currentFileOrDirectory.getFileName();
  228683. }
  228684. if ([panel runModalForDirectory: juceStringToNS (directory)
  228685. file: juceStringToNS (filename)]
  228686. == NSOKButton)
  228687. {
  228688. if (isSaveDialogue)
  228689. {
  228690. results.add (File (nsStringToJuce ([panel filename])));
  228691. }
  228692. else
  228693. {
  228694. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  228695. NSArray* urls = [openPanel filenames];
  228696. for (unsigned int i = 0; i < [urls count]; ++i)
  228697. {
  228698. NSString* f = [urls objectAtIndex: i];
  228699. results.add (File (nsStringToJuce (f)));
  228700. }
  228701. }
  228702. }
  228703. [panel setDelegate: nil];
  228704. }
  228705. #else
  228706. void FileChooser::showPlatformDialog (Array<File>& results,
  228707. const String& title,
  228708. const File& currentFileOrDirectory,
  228709. const String& filter,
  228710. bool selectsDirectory,
  228711. bool selectsFiles,
  228712. bool isSaveDialogue,
  228713. bool warnAboutOverwritingExistingFiles,
  228714. bool selectMultipleFiles,
  228715. FilePreviewComponent* extraInfoComponent)
  228716. {
  228717. const ScopedAutoReleasePool pool;
  228718. jassertfalse; //xxx to do
  228719. }
  228720. #endif
  228721. #endif
  228722. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  228723. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  228724. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228725. // compiled on its own).
  228726. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  228727. #if JUCE_MAC
  228728. END_JUCE_NAMESPACE
  228729. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  228730. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  228731. {
  228732. CriticalSection* contextLock;
  228733. bool needsUpdate;
  228734. }
  228735. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  228736. - (bool) makeActive;
  228737. - (void) makeInactive;
  228738. - (void) reshape;
  228739. @end
  228740. @implementation ThreadSafeNSOpenGLView
  228741. - (id) initWithFrame: (NSRect) frameRect
  228742. pixelFormat: (NSOpenGLPixelFormat*) format
  228743. {
  228744. contextLock = new CriticalSection();
  228745. self = [super initWithFrame: frameRect pixelFormat: format];
  228746. if (self != nil)
  228747. [[NSNotificationCenter defaultCenter] addObserver: self
  228748. selector: @selector (_surfaceNeedsUpdate:)
  228749. name: NSViewGlobalFrameDidChangeNotification
  228750. object: self];
  228751. return self;
  228752. }
  228753. - (void) dealloc
  228754. {
  228755. [[NSNotificationCenter defaultCenter] removeObserver: self];
  228756. delete contextLock;
  228757. [super dealloc];
  228758. }
  228759. - (bool) makeActive
  228760. {
  228761. const ScopedLock sl (*contextLock);
  228762. if ([self openGLContext] == 0)
  228763. return false;
  228764. [[self openGLContext] makeCurrentContext];
  228765. if (needsUpdate)
  228766. {
  228767. [super update];
  228768. needsUpdate = false;
  228769. }
  228770. return true;
  228771. }
  228772. - (void) makeInactive
  228773. {
  228774. const ScopedLock sl (*contextLock);
  228775. [NSOpenGLContext clearCurrentContext];
  228776. }
  228777. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  228778. {
  228779. const ScopedLock sl (*contextLock);
  228780. needsUpdate = true;
  228781. }
  228782. - (void) update
  228783. {
  228784. const ScopedLock sl (*contextLock);
  228785. needsUpdate = true;
  228786. }
  228787. - (void) reshape
  228788. {
  228789. const ScopedLock sl (*contextLock);
  228790. needsUpdate = true;
  228791. }
  228792. @end
  228793. BEGIN_JUCE_NAMESPACE
  228794. class WindowedGLContext : public OpenGLContext
  228795. {
  228796. public:
  228797. WindowedGLContext (Component* const component,
  228798. const OpenGLPixelFormat& pixelFormat_,
  228799. NSOpenGLContext* sharedContext)
  228800. : renderContext (0),
  228801. pixelFormat (pixelFormat_)
  228802. {
  228803. jassert (component != 0);
  228804. NSOpenGLPixelFormatAttribute attribs [64];
  228805. int n = 0;
  228806. attribs[n++] = NSOpenGLPFADoubleBuffer;
  228807. attribs[n++] = NSOpenGLPFAAccelerated;
  228808. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  228809. attribs[n++] = NSOpenGLPFAColorSize;
  228810. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  228811. pixelFormat.greenBits,
  228812. pixelFormat.blueBits);
  228813. attribs[n++] = NSOpenGLPFAAlphaSize;
  228814. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  228815. attribs[n++] = NSOpenGLPFADepthSize;
  228816. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  228817. attribs[n++] = NSOpenGLPFAStencilSize;
  228818. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  228819. attribs[n++] = NSOpenGLPFAAccumSize;
  228820. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  228821. pixelFormat.accumulationBufferGreenBits,
  228822. pixelFormat.accumulationBufferBlueBits,
  228823. pixelFormat.accumulationBufferAlphaBits);
  228824. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  228825. attribs[n++] = NSOpenGLPFASampleBuffers;
  228826. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  228827. attribs[n++] = NSOpenGLPFAClosestPolicy;
  228828. attribs[n++] = NSOpenGLPFANoRecovery;
  228829. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  228830. NSOpenGLPixelFormat* format
  228831. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  228832. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228833. pixelFormat: format];
  228834. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  228835. shareContext: sharedContext] autorelease];
  228836. const GLint swapInterval = 1;
  228837. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  228838. [view setOpenGLContext: renderContext];
  228839. [format release];
  228840. viewHolder = new NSViewComponentInternal (view, component);
  228841. }
  228842. ~WindowedGLContext()
  228843. {
  228844. deleteContext();
  228845. viewHolder = 0;
  228846. }
  228847. void deleteContext()
  228848. {
  228849. makeInactive();
  228850. [renderContext clearDrawable];
  228851. [renderContext setView: nil];
  228852. [view setOpenGLContext: nil];
  228853. renderContext = nil;
  228854. }
  228855. bool makeActive() const throw()
  228856. {
  228857. jassert (renderContext != 0);
  228858. if ([renderContext view] != view)
  228859. [renderContext setView: view];
  228860. [view makeActive];
  228861. return isActive();
  228862. }
  228863. bool makeInactive() const throw()
  228864. {
  228865. [view makeInactive];
  228866. return true;
  228867. }
  228868. bool isActive() const throw()
  228869. {
  228870. return [NSOpenGLContext currentContext] == renderContext;
  228871. }
  228872. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  228873. void* getRawContext() const throw() { return renderContext; }
  228874. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  228875. {
  228876. }
  228877. void swapBuffers()
  228878. {
  228879. [renderContext flushBuffer];
  228880. }
  228881. bool setSwapInterval (const int numFramesPerSwap)
  228882. {
  228883. [renderContext setValues: (const GLint*) &numFramesPerSwap
  228884. forParameter: NSOpenGLCPSwapInterval];
  228885. return true;
  228886. }
  228887. int getSwapInterval() const
  228888. {
  228889. GLint numFrames = 0;
  228890. [renderContext getValues: &numFrames
  228891. forParameter: NSOpenGLCPSwapInterval];
  228892. return numFrames;
  228893. }
  228894. void repaint()
  228895. {
  228896. // we need to invalidate the juce view that holds this gl view, to make it
  228897. // cause a repaint callback
  228898. NSView* v = (NSView*) viewHolder->view;
  228899. NSRect r = [v frame];
  228900. // bit of a bodge here.. if we only invalidate the area of the gl component,
  228901. // it's completely covered by the NSOpenGLView, so the OS throws away the
  228902. // repaint message, thus never causing our paint() callback, and never repainting
  228903. // the comp. So invalidating just a little bit around the edge helps..
  228904. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  228905. }
  228906. void* getNativeWindowHandle() const { return viewHolder->view; }
  228907. juce_UseDebuggingNewOperator
  228908. NSOpenGLContext* renderContext;
  228909. ThreadSafeNSOpenGLView* view;
  228910. private:
  228911. OpenGLPixelFormat pixelFormat;
  228912. ScopedPointer <NSViewComponentInternal> viewHolder;
  228913. WindowedGLContext (const WindowedGLContext&);
  228914. WindowedGLContext& operator= (const WindowedGLContext&);
  228915. };
  228916. OpenGLContext* OpenGLComponent::createContext()
  228917. {
  228918. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  228919. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  228920. return (c->renderContext != 0) ? c.release() : 0;
  228921. }
  228922. void* OpenGLComponent::getNativeWindowHandle() const
  228923. {
  228924. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  228925. : 0;
  228926. }
  228927. void juce_glViewport (const int w, const int h)
  228928. {
  228929. glViewport (0, 0, w, h);
  228930. }
  228931. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  228932. OwnedArray <OpenGLPixelFormat>& results)
  228933. {
  228934. /* GLint attribs [64];
  228935. int n = 0;
  228936. attribs[n++] = AGL_RGBA;
  228937. attribs[n++] = AGL_DOUBLEBUFFER;
  228938. attribs[n++] = AGL_ACCELERATED;
  228939. attribs[n++] = AGL_NO_RECOVERY;
  228940. attribs[n++] = AGL_NONE;
  228941. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  228942. while (p != 0)
  228943. {
  228944. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  228945. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  228946. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  228947. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  228948. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  228949. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  228950. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  228951. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  228952. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  228953. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  228954. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  228955. results.add (pf);
  228956. p = aglNextPixelFormat (p);
  228957. }*/
  228958. //jassertfalse // can't see how you do this in cocoa!
  228959. }
  228960. #else
  228961. END_JUCE_NAMESPACE
  228962. @interface JuceGLView : UIView
  228963. {
  228964. }
  228965. + (Class) layerClass;
  228966. @end
  228967. @implementation JuceGLView
  228968. + (Class) layerClass
  228969. {
  228970. return [CAEAGLLayer class];
  228971. }
  228972. @end
  228973. BEGIN_JUCE_NAMESPACE
  228974. class GLESContext : public OpenGLContext
  228975. {
  228976. public:
  228977. GLESContext (UIViewComponentPeer* peer,
  228978. Component* const component_,
  228979. const OpenGLPixelFormat& pixelFormat_,
  228980. const GLESContext* const sharedContext,
  228981. NSUInteger apiType)
  228982. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  228983. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  228984. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  228985. {
  228986. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  228987. view.opaque = YES;
  228988. view.hidden = NO;
  228989. view.backgroundColor = [UIColor blackColor];
  228990. view.userInteractionEnabled = NO;
  228991. glLayer = (CAEAGLLayer*) [view layer];
  228992. [peer->view addSubview: view];
  228993. if (sharedContext != 0)
  228994. context = [[EAGLContext alloc] initWithAPI: apiType
  228995. sharegroup: [sharedContext->context sharegroup]];
  228996. else
  228997. context = [[EAGLContext alloc] initWithAPI: apiType];
  228998. createGLBuffers();
  228999. }
  229000. ~GLESContext()
  229001. {
  229002. deleteContext();
  229003. [view removeFromSuperview];
  229004. [view release];
  229005. freeGLBuffers();
  229006. }
  229007. void deleteContext()
  229008. {
  229009. makeInactive();
  229010. [context release];
  229011. context = nil;
  229012. }
  229013. bool makeActive() const throw()
  229014. {
  229015. jassert (context != 0);
  229016. [EAGLContext setCurrentContext: context];
  229017. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  229018. return true;
  229019. }
  229020. void swapBuffers()
  229021. {
  229022. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229023. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  229024. }
  229025. bool makeInactive() const throw()
  229026. {
  229027. return [EAGLContext setCurrentContext: nil];
  229028. }
  229029. bool isActive() const throw()
  229030. {
  229031. return [EAGLContext currentContext] == context;
  229032. }
  229033. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  229034. void* getRawContext() const throw() { return glLayer; }
  229035. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  229036. {
  229037. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  229038. if (lastWidth != w || lastHeight != h)
  229039. {
  229040. lastWidth = w;
  229041. lastHeight = h;
  229042. freeGLBuffers();
  229043. createGLBuffers();
  229044. }
  229045. }
  229046. bool setSwapInterval (const int numFramesPerSwap)
  229047. {
  229048. numFrames = numFramesPerSwap;
  229049. return true;
  229050. }
  229051. int getSwapInterval() const
  229052. {
  229053. return numFrames;
  229054. }
  229055. void repaint()
  229056. {
  229057. }
  229058. void createGLBuffers()
  229059. {
  229060. makeActive();
  229061. glGenFramebuffersOES (1, &frameBufferHandle);
  229062. glGenRenderbuffersOES (1, &colorBufferHandle);
  229063. glGenRenderbuffersOES (1, &depthBufferHandle);
  229064. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229065. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  229066. GLint width, height;
  229067. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  229068. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  229069. if (useDepthBuffer)
  229070. {
  229071. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  229072. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  229073. }
  229074. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  229075. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  229076. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  229077. if (useDepthBuffer)
  229078. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  229079. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  229080. }
  229081. void freeGLBuffers()
  229082. {
  229083. if (frameBufferHandle != 0)
  229084. {
  229085. glDeleteFramebuffersOES (1, &frameBufferHandle);
  229086. frameBufferHandle = 0;
  229087. }
  229088. if (colorBufferHandle != 0)
  229089. {
  229090. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  229091. colorBufferHandle = 0;
  229092. }
  229093. if (depthBufferHandle != 0)
  229094. {
  229095. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  229096. depthBufferHandle = 0;
  229097. }
  229098. }
  229099. juce_UseDebuggingNewOperator
  229100. private:
  229101. Component::SafePointer<Component> component;
  229102. OpenGLPixelFormat pixelFormat;
  229103. JuceGLView* view;
  229104. CAEAGLLayer* glLayer;
  229105. EAGLContext* context;
  229106. bool useDepthBuffer;
  229107. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  229108. int numFrames;
  229109. int lastWidth, lastHeight;
  229110. GLESContext (const GLESContext&);
  229111. GLESContext& operator= (const GLESContext&);
  229112. };
  229113. OpenGLContext* OpenGLComponent::createContext()
  229114. {
  229115. ScopedAutoReleasePool pool;
  229116. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  229117. if (peer != 0)
  229118. return new GLESContext (peer, this, preferredPixelFormat,
  229119. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  229120. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  229121. return 0;
  229122. }
  229123. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  229124. OwnedArray <OpenGLPixelFormat>& /*results*/)
  229125. {
  229126. }
  229127. void juce_glViewport (const int w, const int h)
  229128. {
  229129. glViewport (0, 0, w, h);
  229130. }
  229131. #endif
  229132. #endif
  229133. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  229134. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  229135. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229136. // compiled on its own).
  229137. #if JUCE_INCLUDED_FILE
  229138. #if JUCE_MAC
  229139. namespace MouseCursorHelpers
  229140. {
  229141. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  229142. {
  229143. NSImage* im = CoreGraphicsImage::createNSImage (image);
  229144. NSCursor* c = [[NSCursor alloc] initWithImage: im
  229145. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  229146. [im release];
  229147. return c;
  229148. }
  229149. static void* fromWebKitFile (const char* filename, float hx, float hy)
  229150. {
  229151. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  229152. BufferedInputStream buf (fileStream, 4096);
  229153. PNGImageFormat pngFormat;
  229154. Image im (pngFormat.decodeImage (buf));
  229155. if (im.isValid())
  229156. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  229157. jassertfalse;
  229158. return 0;
  229159. }
  229160. }
  229161. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  229162. {
  229163. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  229164. }
  229165. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  229166. {
  229167. const ScopedAutoReleasePool pool;
  229168. NSCursor* c = 0;
  229169. switch (type)
  229170. {
  229171. case NormalCursor: c = [NSCursor arrowCursor]; break;
  229172. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  229173. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  229174. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  229175. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  229176. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  229177. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  229178. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  229179. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  229180. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  229181. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  229182. case UpDownResizeCursor:
  229183. case TopEdgeResizeCursor:
  229184. case BottomEdgeResizeCursor:
  229185. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  229186. case TopLeftCornerResizeCursor:
  229187. case BottomRightCornerResizeCursor:
  229188. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  229189. case TopRightCornerResizeCursor:
  229190. case BottomLeftCornerResizeCursor:
  229191. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  229192. case UpDownLeftRightResizeCursor:
  229193. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  229194. default:
  229195. jassertfalse;
  229196. break;
  229197. }
  229198. [c retain];
  229199. return c;
  229200. }
  229201. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  229202. {
  229203. [((NSCursor*) cursorHandle) release];
  229204. }
  229205. void MouseCursor::showInAllWindows() const
  229206. {
  229207. showInWindow (0);
  229208. }
  229209. void MouseCursor::showInWindow (ComponentPeer*) const
  229210. {
  229211. [((NSCursor*) getHandle()) set];
  229212. }
  229213. #else
  229214. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  229215. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  229216. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  229217. void MouseCursor::showInAllWindows() const {}
  229218. void MouseCursor::showInWindow (ComponentPeer*) const {}
  229219. #endif
  229220. #endif
  229221. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  229222. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229223. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229224. // compiled on its own).
  229225. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  229226. #if JUCE_MAC
  229227. END_JUCE_NAMESPACE
  229228. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  229229. @interface DownloadClickDetector : NSObject
  229230. {
  229231. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  229232. }
  229233. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  229234. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229235. request: (NSURLRequest*) request
  229236. frame: (WebFrame*) frame
  229237. decisionListener: (id<WebPolicyDecisionListener>) listener;
  229238. @end
  229239. @implementation DownloadClickDetector
  229240. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  229241. {
  229242. [super init];
  229243. ownerComponent = ownerComponent_;
  229244. return self;
  229245. }
  229246. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  229247. request: (NSURLRequest*) request
  229248. frame: (WebFrame*) frame
  229249. decisionListener: (id <WebPolicyDecisionListener>) listener
  229250. {
  229251. (void) sender;
  229252. (void) request;
  229253. (void) frame;
  229254. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  229255. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  229256. [listener use];
  229257. else
  229258. [listener ignore];
  229259. }
  229260. @end
  229261. BEGIN_JUCE_NAMESPACE
  229262. class WebBrowserComponentInternal : public NSViewComponent
  229263. {
  229264. public:
  229265. WebBrowserComponentInternal (WebBrowserComponent* owner)
  229266. {
  229267. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  229268. frameName: @""
  229269. groupName: @""];
  229270. setView (webView);
  229271. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  229272. [webView setPolicyDelegate: clickListener];
  229273. }
  229274. ~WebBrowserComponentInternal()
  229275. {
  229276. [webView setPolicyDelegate: nil];
  229277. [clickListener release];
  229278. setView (0);
  229279. }
  229280. void goToURL (const String& url,
  229281. const StringArray* headers,
  229282. const MemoryBlock* postData)
  229283. {
  229284. NSMutableURLRequest* r
  229285. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  229286. cachePolicy: NSURLRequestUseProtocolCachePolicy
  229287. timeoutInterval: 30.0];
  229288. if (postData != 0 && postData->getSize() > 0)
  229289. {
  229290. [r setHTTPMethod: @"POST"];
  229291. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  229292. length: postData->getSize()]];
  229293. }
  229294. if (headers != 0)
  229295. {
  229296. for (int i = 0; i < headers->size(); ++i)
  229297. {
  229298. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  229299. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  229300. [r setValue: juceStringToNS (headerValue)
  229301. forHTTPHeaderField: juceStringToNS (headerName)];
  229302. }
  229303. }
  229304. stop();
  229305. [[webView mainFrame] loadRequest: r];
  229306. }
  229307. void goBack()
  229308. {
  229309. [webView goBack];
  229310. }
  229311. void goForward()
  229312. {
  229313. [webView goForward];
  229314. }
  229315. void stop()
  229316. {
  229317. [webView stopLoading: nil];
  229318. }
  229319. void refresh()
  229320. {
  229321. [webView reload: nil];
  229322. }
  229323. private:
  229324. WebView* webView;
  229325. DownloadClickDetector* clickListener;
  229326. };
  229327. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229328. : browser (0),
  229329. blankPageShown (false),
  229330. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  229331. {
  229332. setOpaque (true);
  229333. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  229334. }
  229335. WebBrowserComponent::~WebBrowserComponent()
  229336. {
  229337. deleteAndZero (browser);
  229338. }
  229339. void WebBrowserComponent::goToURL (const String& url,
  229340. const StringArray* headers,
  229341. const MemoryBlock* postData)
  229342. {
  229343. lastURL = url;
  229344. lastHeaders.clear();
  229345. if (headers != 0)
  229346. lastHeaders = *headers;
  229347. lastPostData.setSize (0);
  229348. if (postData != 0)
  229349. lastPostData = *postData;
  229350. blankPageShown = false;
  229351. browser->goToURL (url, headers, postData);
  229352. }
  229353. void WebBrowserComponent::stop()
  229354. {
  229355. browser->stop();
  229356. }
  229357. void WebBrowserComponent::goBack()
  229358. {
  229359. lastURL = String::empty;
  229360. blankPageShown = false;
  229361. browser->goBack();
  229362. }
  229363. void WebBrowserComponent::goForward()
  229364. {
  229365. lastURL = String::empty;
  229366. browser->goForward();
  229367. }
  229368. void WebBrowserComponent::refresh()
  229369. {
  229370. browser->refresh();
  229371. }
  229372. void WebBrowserComponent::paint (Graphics&)
  229373. {
  229374. }
  229375. void WebBrowserComponent::checkWindowAssociation()
  229376. {
  229377. if (isShowing())
  229378. {
  229379. if (blankPageShown)
  229380. goBack();
  229381. }
  229382. else
  229383. {
  229384. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  229385. {
  229386. // when the component becomes invisible, some stuff like flash
  229387. // carries on playing audio, so we need to force it onto a blank
  229388. // page to avoid this, (and send it back when it's made visible again).
  229389. blankPageShown = true;
  229390. browser->goToURL ("about:blank", 0, 0);
  229391. }
  229392. }
  229393. }
  229394. void WebBrowserComponent::reloadLastURL()
  229395. {
  229396. if (lastURL.isNotEmpty())
  229397. {
  229398. goToURL (lastURL, &lastHeaders, &lastPostData);
  229399. lastURL = String::empty;
  229400. }
  229401. }
  229402. void WebBrowserComponent::parentHierarchyChanged()
  229403. {
  229404. checkWindowAssociation();
  229405. }
  229406. void WebBrowserComponent::resized()
  229407. {
  229408. browser->setSize (getWidth(), getHeight());
  229409. }
  229410. void WebBrowserComponent::visibilityChanged()
  229411. {
  229412. checkWindowAssociation();
  229413. }
  229414. bool WebBrowserComponent::pageAboutToLoad (const String&)
  229415. {
  229416. return true;
  229417. }
  229418. #else
  229419. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  229420. {
  229421. }
  229422. WebBrowserComponent::~WebBrowserComponent()
  229423. {
  229424. }
  229425. void WebBrowserComponent::goToURL (const String& url,
  229426. const StringArray* headers,
  229427. const MemoryBlock* postData)
  229428. {
  229429. }
  229430. void WebBrowserComponent::stop()
  229431. {
  229432. }
  229433. void WebBrowserComponent::goBack()
  229434. {
  229435. }
  229436. void WebBrowserComponent::goForward()
  229437. {
  229438. }
  229439. void WebBrowserComponent::refresh()
  229440. {
  229441. }
  229442. void WebBrowserComponent::paint (Graphics& g)
  229443. {
  229444. }
  229445. void WebBrowserComponent::checkWindowAssociation()
  229446. {
  229447. }
  229448. void WebBrowserComponent::reloadLastURL()
  229449. {
  229450. }
  229451. void WebBrowserComponent::parentHierarchyChanged()
  229452. {
  229453. }
  229454. void WebBrowserComponent::resized()
  229455. {
  229456. }
  229457. void WebBrowserComponent::visibilityChanged()
  229458. {
  229459. }
  229460. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  229461. {
  229462. return true;
  229463. }
  229464. #endif
  229465. #endif
  229466. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  229467. /*** Start of inlined file: juce_iphone_Audio.cpp ***/
  229468. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229469. // compiled on its own).
  229470. #if JUCE_INCLUDED_FILE
  229471. class IPhoneAudioIODevice : public AudioIODevice
  229472. {
  229473. public:
  229474. IPhoneAudioIODevice (const String& deviceName)
  229475. : AudioIODevice (deviceName, "Audio"),
  229476. actualBufferSize (0),
  229477. isRunning (false),
  229478. audioUnit (0),
  229479. callback (0),
  229480. floatData (1, 2)
  229481. {
  229482. numInputChannels = 2;
  229483. numOutputChannels = 2;
  229484. preferredBufferSize = 0;
  229485. AudioSessionInitialize (0, 0, interruptionListenerStatic, this);
  229486. updateDeviceInfo();
  229487. }
  229488. ~IPhoneAudioIODevice()
  229489. {
  229490. close();
  229491. }
  229492. const StringArray getOutputChannelNames()
  229493. {
  229494. StringArray s;
  229495. s.add ("Left");
  229496. s.add ("Right");
  229497. return s;
  229498. }
  229499. const StringArray getInputChannelNames()
  229500. {
  229501. StringArray s;
  229502. if (audioInputIsAvailable)
  229503. {
  229504. s.add ("Left");
  229505. s.add ("Right");
  229506. }
  229507. return s;
  229508. }
  229509. int getNumSampleRates()
  229510. {
  229511. return 1;
  229512. }
  229513. double getSampleRate (int index)
  229514. {
  229515. return sampleRate;
  229516. }
  229517. int getNumBufferSizesAvailable()
  229518. {
  229519. return 1;
  229520. }
  229521. int getBufferSizeSamples (int index)
  229522. {
  229523. return getDefaultBufferSize();
  229524. }
  229525. int getDefaultBufferSize()
  229526. {
  229527. return 1024;
  229528. }
  229529. const String open (const BigInteger& inputChannels,
  229530. const BigInteger& outputChannels,
  229531. double sampleRate,
  229532. int bufferSize)
  229533. {
  229534. close();
  229535. lastError = String::empty;
  229536. preferredBufferSize = (bufferSize <= 0) ? getDefaultBufferSize() : bufferSize;
  229537. // xxx set up channel mapping
  229538. activeOutputChans = outputChannels;
  229539. activeOutputChans.setRange (2, activeOutputChans.getHighestBit(), false);
  229540. numOutputChannels = activeOutputChans.countNumberOfSetBits();
  229541. monoOutputChannelNumber = activeOutputChans.findNextSetBit (0);
  229542. activeInputChans = inputChannels;
  229543. activeInputChans.setRange (2, activeInputChans.getHighestBit(), false);
  229544. numInputChannels = activeInputChans.countNumberOfSetBits();
  229545. monoInputChannelNumber = activeInputChans.findNextSetBit (0);
  229546. AudioSessionSetActive (true);
  229547. UInt32 audioCategory = audioInputIsAvailable ? kAudioSessionCategory_PlayAndRecord
  229548. : kAudioSessionCategory_MediaPlayback;
  229549. AudioSessionSetProperty (kAudioSessionProperty_AudioCategory, sizeof (audioCategory), &audioCategory);
  229550. AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, propertyChangedStatic, this);
  229551. fixAudioRouteIfSetToReceiver();
  229552. updateDeviceInfo();
  229553. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229554. AudioSessionSetProperty (kAudioSessionProperty_PreferredHardwareIOBufferDuration, sizeof (bufferDuration), &bufferDuration);
  229555. actualBufferSize = preferredBufferSize;
  229556. prepareFloatBuffers();
  229557. isRunning = true;
  229558. propertyChanged (0, 0, 0); // creates and starts the AU
  229559. lastError = audioUnit != 0 ? "" : "Couldn't open the device";
  229560. return lastError;
  229561. }
  229562. void close()
  229563. {
  229564. if (isRunning)
  229565. {
  229566. isRunning = false;
  229567. AudioSessionSetActive (false);
  229568. if (audioUnit != 0)
  229569. {
  229570. AudioComponentInstanceDispose (audioUnit);
  229571. audioUnit = 0;
  229572. }
  229573. }
  229574. }
  229575. bool isOpen()
  229576. {
  229577. return isRunning;
  229578. }
  229579. int getCurrentBufferSizeSamples()
  229580. {
  229581. return actualBufferSize;
  229582. }
  229583. double getCurrentSampleRate()
  229584. {
  229585. return sampleRate;
  229586. }
  229587. int getCurrentBitDepth()
  229588. {
  229589. return 16;
  229590. }
  229591. const BigInteger getActiveOutputChannels() const
  229592. {
  229593. return activeOutputChans;
  229594. }
  229595. const BigInteger getActiveInputChannels() const
  229596. {
  229597. return activeInputChans;
  229598. }
  229599. int getOutputLatencyInSamples()
  229600. {
  229601. return 0; //xxx
  229602. }
  229603. int getInputLatencyInSamples()
  229604. {
  229605. return 0; //xxx
  229606. }
  229607. void start (AudioIODeviceCallback* callback_)
  229608. {
  229609. if (isRunning && callback != callback_)
  229610. {
  229611. if (callback_ != 0)
  229612. callback_->audioDeviceAboutToStart (this);
  229613. const ScopedLock sl (callbackLock);
  229614. callback = callback_;
  229615. }
  229616. }
  229617. void stop()
  229618. {
  229619. if (isRunning)
  229620. {
  229621. AudioIODeviceCallback* lastCallback;
  229622. {
  229623. const ScopedLock sl (callbackLock);
  229624. lastCallback = callback;
  229625. callback = 0;
  229626. }
  229627. if (lastCallback != 0)
  229628. lastCallback->audioDeviceStopped();
  229629. }
  229630. }
  229631. bool isPlaying()
  229632. {
  229633. return isRunning && callback != 0;
  229634. }
  229635. const String getLastError()
  229636. {
  229637. return lastError;
  229638. }
  229639. private:
  229640. CriticalSection callbackLock;
  229641. Float64 sampleRate;
  229642. int numInputChannels, numOutputChannels;
  229643. int preferredBufferSize;
  229644. int actualBufferSize;
  229645. bool isRunning;
  229646. String lastError;
  229647. AudioStreamBasicDescription format;
  229648. AudioUnit audioUnit;
  229649. UInt32 audioInputIsAvailable;
  229650. AudioIODeviceCallback* callback;
  229651. BigInteger activeOutputChans, activeInputChans;
  229652. AudioSampleBuffer floatData;
  229653. float* inputChannels[3];
  229654. float* outputChannels[3];
  229655. bool monoInputChannelNumber, monoOutputChannelNumber;
  229656. void prepareFloatBuffers()
  229657. {
  229658. floatData.setSize (numInputChannels + numOutputChannels, actualBufferSize);
  229659. zerostruct (inputChannels);
  229660. zerostruct (outputChannels);
  229661. for (int i = 0; i < numInputChannels; ++i)
  229662. inputChannels[i] = floatData.getSampleData (i);
  229663. for (int i = 0; i < numOutputChannels; ++i)
  229664. outputChannels[i] = floatData.getSampleData (i + numInputChannels);
  229665. }
  229666. OSStatus process (AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229667. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229668. {
  229669. OSStatus err = noErr;
  229670. if (audioInputIsAvailable)
  229671. err = AudioUnitRender (audioUnit, ioActionFlags, inTimeStamp, 1, inNumberFrames, ioData);
  229672. const ScopedLock sl (callbackLock);
  229673. if (callback != 0)
  229674. {
  229675. if (audioInputIsAvailable && numInputChannels > 0)
  229676. {
  229677. short* shortData = (short*) ioData->mBuffers[0].mData;
  229678. if (numInputChannels >= 2)
  229679. {
  229680. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229681. {
  229682. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229683. inputChannels[1][i] = *shortData++ * (1.0f / 32768.0f);
  229684. }
  229685. }
  229686. else
  229687. {
  229688. if (monoInputChannelNumber > 0)
  229689. ++shortData;
  229690. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229691. {
  229692. inputChannels[0][i] = *shortData++ * (1.0f / 32768.0f);
  229693. ++shortData;
  229694. }
  229695. }
  229696. }
  229697. else
  229698. {
  229699. for (int i = numInputChannels; --i >= 0;)
  229700. zeromem (inputChannels[i], sizeof (float) * inNumberFrames);
  229701. }
  229702. callback->audioDeviceIOCallback ((const float**) inputChannels, numInputChannels,
  229703. outputChannels, numOutputChannels,
  229704. (int) inNumberFrames);
  229705. short* shortData = (short*) ioData->mBuffers[0].mData;
  229706. int n = 0;
  229707. if (numOutputChannels >= 2)
  229708. {
  229709. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229710. {
  229711. shortData [n++] = (short) (outputChannels[0][i] * 32767.0f);
  229712. shortData [n++] = (short) (outputChannels[1][i] * 32767.0f);
  229713. }
  229714. }
  229715. else if (numOutputChannels == 1)
  229716. {
  229717. for (UInt32 i = 0; i < inNumberFrames; ++i)
  229718. {
  229719. const short s = (short) (outputChannels[monoOutputChannelNumber][i] * 32767.0f);
  229720. shortData [n++] = s;
  229721. shortData [n++] = s;
  229722. }
  229723. }
  229724. else
  229725. {
  229726. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229727. }
  229728. }
  229729. else
  229730. {
  229731. zeromem (ioData->mBuffers[0].mData, 2 * sizeof (short) * inNumberFrames);
  229732. }
  229733. return err;
  229734. }
  229735. void updateDeviceInfo()
  229736. {
  229737. UInt32 size = sizeof (sampleRate);
  229738. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareSampleRate, &size, &sampleRate);
  229739. size = sizeof (audioInputIsAvailable);
  229740. AudioSessionGetProperty (kAudioSessionProperty_AudioInputAvailable, &size, &audioInputIsAvailable);
  229741. }
  229742. void propertyChanged (AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229743. {
  229744. if (! isRunning)
  229745. return;
  229746. if (inPropertyValue != 0)
  229747. {
  229748. CFDictionaryRef routeChangeDictionary = (CFDictionaryRef) inPropertyValue;
  229749. CFNumberRef routeChangeReasonRef = (CFNumberRef) CFDictionaryGetValue (routeChangeDictionary,
  229750. CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
  229751. SInt32 routeChangeReason;
  229752. CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
  229753. if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
  229754. fixAudioRouteIfSetToReceiver();
  229755. }
  229756. updateDeviceInfo();
  229757. createAudioUnit();
  229758. AudioSessionSetActive (true);
  229759. if (audioUnit != 0)
  229760. {
  229761. UInt32 formatSize = sizeof (format);
  229762. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, &formatSize);
  229763. Float32 bufferDuration = preferredBufferSize / sampleRate;
  229764. UInt32 bufferDurationSize = sizeof (bufferDuration);
  229765. AudioSessionGetProperty (kAudioSessionProperty_CurrentHardwareIOBufferDuration, &bufferDurationSize, &bufferDurationSize);
  229766. actualBufferSize = (int) (sampleRate * bufferDuration + 0.5);
  229767. AudioOutputUnitStart (audioUnit);
  229768. }
  229769. }
  229770. void interruptionListener (UInt32 inInterruption)
  229771. {
  229772. /*if (inInterruption == kAudioSessionBeginInterruption)
  229773. {
  229774. isRunning = false;
  229775. AudioOutputUnitStop (audioUnit);
  229776. if (juce_iPhoneShowModalAlert ("Audio Interrupted",
  229777. "This could have been interrupted by another application or by unplugging a headset",
  229778. @"Resume",
  229779. @"Cancel"))
  229780. {
  229781. isRunning = true;
  229782. propertyChanged (0, 0, 0);
  229783. }
  229784. }*/
  229785. if (inInterruption == kAudioSessionEndInterruption)
  229786. {
  229787. isRunning = true;
  229788. AudioSessionSetActive (true);
  229789. AudioOutputUnitStart (audioUnit);
  229790. }
  229791. }
  229792. static OSStatus processStatic (void* inRefCon, AudioUnitRenderActionFlags* ioActionFlags, const AudioTimeStamp* inTimeStamp,
  229793. UInt32 inBusNumber, UInt32 inNumberFrames, AudioBufferList* ioData)
  229794. {
  229795. return ((IPhoneAudioIODevice*) inRefCon)->process (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  229796. }
  229797. static void propertyChangedStatic (void* inClientData, AudioSessionPropertyID inID, UInt32 inDataSize, const void* inPropertyValue)
  229798. {
  229799. ((IPhoneAudioIODevice*) inClientData)->propertyChanged (inID, inDataSize, inPropertyValue);
  229800. }
  229801. static void interruptionListenerStatic (void* inClientData, UInt32 inInterruption)
  229802. {
  229803. ((IPhoneAudioIODevice*) inClientData)->interruptionListener (inInterruption);
  229804. }
  229805. void resetFormat (const int numChannels)
  229806. {
  229807. memset (&format, 0, sizeof (format));
  229808. format.mFormatID = kAudioFormatLinearPCM;
  229809. format.mFormatFlags = kLinearPCMFormatFlagIsSignedInteger | kLinearPCMFormatFlagIsPacked;
  229810. format.mBitsPerChannel = 8 * sizeof (short);
  229811. format.mChannelsPerFrame = 2;
  229812. format.mFramesPerPacket = 1;
  229813. format.mBytesPerFrame = format.mBytesPerPacket = 2 * sizeof (short);
  229814. }
  229815. bool createAudioUnit()
  229816. {
  229817. if (audioUnit != 0)
  229818. {
  229819. AudioComponentInstanceDispose (audioUnit);
  229820. audioUnit = 0;
  229821. }
  229822. resetFormat (2);
  229823. AudioComponentDescription desc;
  229824. desc.componentType = kAudioUnitType_Output;
  229825. desc.componentSubType = kAudioUnitSubType_RemoteIO;
  229826. desc.componentManufacturer = kAudioUnitManufacturer_Apple;
  229827. desc.componentFlags = 0;
  229828. desc.componentFlagsMask = 0;
  229829. AudioComponent comp = AudioComponentFindNext (0, &desc);
  229830. AudioComponentInstanceNew (comp, &audioUnit);
  229831. if (audioUnit == 0)
  229832. return false;
  229833. const UInt32 one = 1;
  229834. AudioUnitSetProperty (audioUnit, kAudioOutputUnitProperty_EnableIO, kAudioUnitScope_Input, 1, &one, sizeof (one));
  229835. AudioChannelLayout layout;
  229836. layout.mChannelBitmap = 0;
  229837. layout.mNumberChannelDescriptions = 0;
  229838. layout.mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  229839. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Input, 0, &layout, sizeof (layout));
  229840. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_AudioChannelLayout, kAudioUnitScope_Output, 0, &layout, sizeof (layout));
  229841. AURenderCallbackStruct inputProc;
  229842. inputProc.inputProc = processStatic;
  229843. inputProc.inputProcRefCon = this;
  229844. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &inputProc, sizeof (inputProc));
  229845. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 0, &format, sizeof (format));
  229846. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &format, sizeof (format));
  229847. AudioUnitInitialize (audioUnit);
  229848. return true;
  229849. }
  229850. // If the routing is set to go through the receiver (i.e. the speaker, but quiet), this re-routes it
  229851. // to make it loud. Needed because by default when using an input + output, the output is kept quiet.
  229852. static void fixAudioRouteIfSetToReceiver()
  229853. {
  229854. CFStringRef audioRoute = 0;
  229855. UInt32 propertySize = sizeof (audioRoute);
  229856. if (AudioSessionGetProperty (kAudioSessionProperty_AudioRoute, &propertySize, &audioRoute) == noErr)
  229857. {
  229858. NSString* route = (NSString*) audioRoute;
  229859. //DBG ("audio route: " + nsStringToJuce (route));
  229860. if ([route hasPrefix: @"Receiver"])
  229861. {
  229862. UInt32 audioRouteOverride = kAudioSessionOverrideAudioRoute_Speaker;
  229863. AudioSessionSetProperty (kAudioSessionProperty_OverrideAudioRoute, sizeof (audioRouteOverride), &audioRouteOverride);
  229864. }
  229865. CFRelease (audioRoute);
  229866. }
  229867. }
  229868. IPhoneAudioIODevice (const IPhoneAudioIODevice&);
  229869. IPhoneAudioIODevice& operator= (const IPhoneAudioIODevice&);
  229870. };
  229871. class IPhoneAudioIODeviceType : public AudioIODeviceType
  229872. {
  229873. public:
  229874. IPhoneAudioIODeviceType()
  229875. : AudioIODeviceType ("iPhone Audio")
  229876. {
  229877. }
  229878. ~IPhoneAudioIODeviceType()
  229879. {
  229880. }
  229881. void scanForDevices()
  229882. {
  229883. }
  229884. const StringArray getDeviceNames (bool wantInputNames) const
  229885. {
  229886. StringArray s;
  229887. s.add ("iPhone Audio");
  229888. return s;
  229889. }
  229890. int getDefaultDeviceIndex (bool forInput) const
  229891. {
  229892. return 0;
  229893. }
  229894. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  229895. {
  229896. return device != 0 ? 0 : -1;
  229897. }
  229898. bool hasSeparateInputsAndOutputs() const { return false; }
  229899. AudioIODevice* createDevice (const String& outputDeviceName,
  229900. const String& inputDeviceName)
  229901. {
  229902. if (outputDeviceName.isNotEmpty() || inputDeviceName.isNotEmpty())
  229903. {
  229904. return new IPhoneAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  229905. : inputDeviceName);
  229906. }
  229907. return 0;
  229908. }
  229909. juce_UseDebuggingNewOperator
  229910. private:
  229911. IPhoneAudioIODeviceType (const IPhoneAudioIODeviceType&);
  229912. IPhoneAudioIODeviceType& operator= (const IPhoneAudioIODeviceType&);
  229913. };
  229914. AudioIODeviceType* juce_createAudioIODeviceType_iPhoneAudio()
  229915. {
  229916. return new IPhoneAudioIODeviceType();
  229917. }
  229918. #endif
  229919. /*** End of inlined file: juce_iphone_Audio.cpp ***/
  229920. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  229921. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229922. // compiled on its own).
  229923. #if JUCE_INCLUDED_FILE
  229924. #if JUCE_MAC
  229925. namespace CoreMidiHelpers
  229926. {
  229927. static bool logError (const OSStatus err, const int lineNum)
  229928. {
  229929. if (err == noErr)
  229930. return true;
  229931. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  229932. jassertfalse;
  229933. return false;
  229934. }
  229935. #undef CHECK_ERROR
  229936. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  229937. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229938. {
  229939. String result;
  229940. CFStringRef str = 0;
  229941. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229942. if (str != 0)
  229943. {
  229944. result = PlatformUtilities::cfStringToJuceString (str);
  229945. CFRelease (str);
  229946. str = 0;
  229947. }
  229948. MIDIEntityRef entity = 0;
  229949. MIDIEndpointGetEntity (endpoint, &entity);
  229950. if (entity == 0)
  229951. return result; // probably virtual
  229952. if (result.isEmpty())
  229953. {
  229954. // endpoint name has zero length - try the entity
  229955. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229956. if (str != 0)
  229957. {
  229958. result += PlatformUtilities::cfStringToJuceString (str);
  229959. CFRelease (str);
  229960. str = 0;
  229961. }
  229962. }
  229963. // now consider the device's name
  229964. MIDIDeviceRef device = 0;
  229965. MIDIEntityGetDevice (entity, &device);
  229966. if (device == 0)
  229967. return result;
  229968. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229969. if (str != 0)
  229970. {
  229971. const String s (PlatformUtilities::cfStringToJuceString (str));
  229972. CFRelease (str);
  229973. // if an external device has only one entity, throw away
  229974. // the endpoint name and just use the device name
  229975. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229976. {
  229977. result = s;
  229978. }
  229979. else if (! result.startsWithIgnoreCase (s))
  229980. {
  229981. // prepend the device name to the entity name
  229982. result = (s + " " + result).trimEnd();
  229983. }
  229984. }
  229985. return result;
  229986. }
  229987. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229988. {
  229989. String result;
  229990. // Does the endpoint have connections?
  229991. CFDataRef connections = 0;
  229992. int numConnections = 0;
  229993. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229994. if (connections != 0)
  229995. {
  229996. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  229997. if (numConnections > 0)
  229998. {
  229999. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  230000. for (int i = 0; i < numConnections; ++i, ++pid)
  230001. {
  230002. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  230003. MIDIObjectRef connObject;
  230004. MIDIObjectType connObjectType;
  230005. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  230006. if (err == noErr)
  230007. {
  230008. String s;
  230009. if (connObjectType == kMIDIObjectType_ExternalSource
  230010. || connObjectType == kMIDIObjectType_ExternalDestination)
  230011. {
  230012. // Connected to an external device's endpoint (10.3 and later).
  230013. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  230014. }
  230015. else
  230016. {
  230017. // Connected to an external device (10.2) (or something else, catch-all)
  230018. CFStringRef str = 0;
  230019. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  230020. if (str != 0)
  230021. {
  230022. s = PlatformUtilities::cfStringToJuceString (str);
  230023. CFRelease (str);
  230024. }
  230025. }
  230026. if (s.isNotEmpty())
  230027. {
  230028. if (result.isNotEmpty())
  230029. result += ", ";
  230030. result += s;
  230031. }
  230032. }
  230033. }
  230034. }
  230035. CFRelease (connections);
  230036. }
  230037. if (result.isNotEmpty())
  230038. return result;
  230039. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  230040. return getEndpointName (endpoint, false);
  230041. }
  230042. static MIDIClientRef getGlobalMidiClient()
  230043. {
  230044. static MIDIClientRef globalMidiClient = 0;
  230045. if (globalMidiClient == 0)
  230046. {
  230047. String name ("JUCE");
  230048. if (JUCEApplication::getInstance() != 0)
  230049. name = JUCEApplication::getInstance()->getApplicationName();
  230050. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  230051. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  230052. CFRelease (appName);
  230053. }
  230054. return globalMidiClient;
  230055. }
  230056. class MidiPortAndEndpoint
  230057. {
  230058. public:
  230059. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  230060. : port (port_), endPoint (endPoint_)
  230061. {
  230062. }
  230063. ~MidiPortAndEndpoint()
  230064. {
  230065. if (port != 0)
  230066. MIDIPortDispose (port);
  230067. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  230068. MIDIEndpointDispose (endPoint);
  230069. }
  230070. void send (const MIDIPacketList* const packets)
  230071. {
  230072. if (port != 0)
  230073. MIDISend (port, endPoint, packets);
  230074. else
  230075. MIDIReceived (endPoint, packets);
  230076. }
  230077. MIDIPortRef port;
  230078. MIDIEndpointRef endPoint;
  230079. };
  230080. class MidiPortAndCallback;
  230081. static CriticalSection callbackLock;
  230082. static Array<MidiPortAndCallback*> activeCallbacks;
  230083. class MidiPortAndCallback
  230084. {
  230085. public:
  230086. MidiPortAndCallback (MidiInputCallback& callback_)
  230087. : input (0), active (false), callback (callback_), concatenator (2048)
  230088. {
  230089. }
  230090. ~MidiPortAndCallback()
  230091. {
  230092. active = false;
  230093. {
  230094. const ScopedLock sl (callbackLock);
  230095. activeCallbacks.removeValue (this);
  230096. }
  230097. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  230098. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  230099. }
  230100. void handlePackets (const MIDIPacketList* const pktlist)
  230101. {
  230102. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  230103. const ScopedLock sl (callbackLock);
  230104. if (activeCallbacks.contains (this) && active)
  230105. {
  230106. const MIDIPacket* packet = &pktlist->packet[0];
  230107. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  230108. {
  230109. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  230110. input, callback);
  230111. packet = MIDIPacketNext (packet);
  230112. }
  230113. }
  230114. }
  230115. MidiInput* input;
  230116. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  230117. volatile bool active;
  230118. private:
  230119. MidiInputCallback& callback;
  230120. MidiDataConcatenator concatenator;
  230121. };
  230122. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  230123. {
  230124. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  230125. }
  230126. }
  230127. const StringArray MidiOutput::getDevices()
  230128. {
  230129. StringArray s;
  230130. const ItemCount num = MIDIGetNumberOfDestinations();
  230131. for (ItemCount i = 0; i < num; ++i)
  230132. {
  230133. MIDIEndpointRef dest = MIDIGetDestination (i);
  230134. if (dest != 0)
  230135. {
  230136. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  230137. if (name.isEmpty())
  230138. name = "<error>";
  230139. s.add (name);
  230140. }
  230141. else
  230142. {
  230143. s.add ("<error>");
  230144. }
  230145. }
  230146. return s;
  230147. }
  230148. int MidiOutput::getDefaultDeviceIndex()
  230149. {
  230150. return 0;
  230151. }
  230152. MidiOutput* MidiOutput::openDevice (int index)
  230153. {
  230154. MidiOutput* mo = 0;
  230155. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  230156. {
  230157. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  230158. CFStringRef pname;
  230159. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  230160. {
  230161. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  230162. MIDIPortRef port;
  230163. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  230164. {
  230165. mo = new MidiOutput();
  230166. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  230167. }
  230168. CFRelease (pname);
  230169. }
  230170. }
  230171. return mo;
  230172. }
  230173. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  230174. {
  230175. MidiOutput* mo = 0;
  230176. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  230177. MIDIEndpointRef endPoint;
  230178. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  230179. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  230180. {
  230181. mo = new MidiOutput();
  230182. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  230183. }
  230184. CFRelease (name);
  230185. return mo;
  230186. }
  230187. MidiOutput::~MidiOutput()
  230188. {
  230189. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230190. }
  230191. void MidiOutput::reset()
  230192. {
  230193. }
  230194. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  230195. {
  230196. return false;
  230197. }
  230198. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  230199. {
  230200. }
  230201. void MidiOutput::sendMessageNow (const MidiMessage& message)
  230202. {
  230203. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  230204. if (message.isSysEx())
  230205. {
  230206. const int maxPacketSize = 256;
  230207. int pos = 0, bytesLeft = message.getRawDataSize();
  230208. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  230209. HeapBlock <MIDIPacketList> packets;
  230210. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  230211. packets->numPackets = numPackets;
  230212. MIDIPacket* p = packets->packet;
  230213. for (int i = 0; i < numPackets; ++i)
  230214. {
  230215. p->timeStamp = 0;
  230216. p->length = jmin (maxPacketSize, bytesLeft);
  230217. memcpy (p->data, message.getRawData() + pos, p->length);
  230218. pos += p->length;
  230219. bytesLeft -= p->length;
  230220. p = MIDIPacketNext (p);
  230221. }
  230222. mpe->send (packets);
  230223. }
  230224. else
  230225. {
  230226. MIDIPacketList packets;
  230227. packets.numPackets = 1;
  230228. packets.packet[0].timeStamp = 0;
  230229. packets.packet[0].length = message.getRawDataSize();
  230230. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  230231. mpe->send (&packets);
  230232. }
  230233. }
  230234. const StringArray MidiInput::getDevices()
  230235. {
  230236. StringArray s;
  230237. const ItemCount num = MIDIGetNumberOfSources();
  230238. for (ItemCount i = 0; i < num; ++i)
  230239. {
  230240. MIDIEndpointRef source = MIDIGetSource (i);
  230241. if (source != 0)
  230242. {
  230243. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  230244. if (name.isEmpty())
  230245. name = "<error>";
  230246. s.add (name);
  230247. }
  230248. else
  230249. {
  230250. s.add ("<error>");
  230251. }
  230252. }
  230253. return s;
  230254. }
  230255. int MidiInput::getDefaultDeviceIndex()
  230256. {
  230257. return 0;
  230258. }
  230259. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  230260. {
  230261. jassert (callback != 0);
  230262. using namespace CoreMidiHelpers;
  230263. MidiInput* newInput = 0;
  230264. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  230265. {
  230266. MIDIEndpointRef endPoint = MIDIGetSource (index);
  230267. if (endPoint != 0)
  230268. {
  230269. CFStringRef name;
  230270. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  230271. {
  230272. MIDIClientRef client = getGlobalMidiClient();
  230273. if (client != 0)
  230274. {
  230275. MIDIPortRef port;
  230276. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230277. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  230278. {
  230279. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  230280. {
  230281. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  230282. newInput = new MidiInput (getDevices() [index]);
  230283. mpc->input = newInput;
  230284. newInput->internal = mpc;
  230285. const ScopedLock sl (callbackLock);
  230286. activeCallbacks.add (mpc.release());
  230287. }
  230288. else
  230289. {
  230290. CHECK_ERROR (MIDIPortDispose (port));
  230291. }
  230292. }
  230293. }
  230294. }
  230295. CFRelease (name);
  230296. }
  230297. }
  230298. return newInput;
  230299. }
  230300. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  230301. {
  230302. jassert (callback != 0);
  230303. using namespace CoreMidiHelpers;
  230304. MidiInput* mi = 0;
  230305. MIDIClientRef client = getGlobalMidiClient();
  230306. if (client != 0)
  230307. {
  230308. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  230309. mpc->active = false;
  230310. MIDIEndpointRef endPoint;
  230311. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  230312. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  230313. {
  230314. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  230315. mi = new MidiInput (deviceName);
  230316. mpc->input = mi;
  230317. mi->internal = mpc;
  230318. const ScopedLock sl (callbackLock);
  230319. activeCallbacks.add (mpc.release());
  230320. }
  230321. CFRelease (name);
  230322. }
  230323. return mi;
  230324. }
  230325. MidiInput::MidiInput (const String& name_)
  230326. : name (name_)
  230327. {
  230328. }
  230329. MidiInput::~MidiInput()
  230330. {
  230331. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  230332. }
  230333. void MidiInput::start()
  230334. {
  230335. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230336. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  230337. }
  230338. void MidiInput::stop()
  230339. {
  230340. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  230341. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  230342. }
  230343. #undef CHECK_ERROR
  230344. #else // Stubs for iOS...
  230345. MidiOutput::~MidiOutput() {}
  230346. void MidiOutput::reset() {}
  230347. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  230348. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  230349. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  230350. const StringArray MidiOutput::getDevices() { return StringArray(); }
  230351. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  230352. const StringArray MidiInput::getDevices() { return StringArray(); }
  230353. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  230354. #endif
  230355. #endif
  230356. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  230357. #else
  230358. /*** Start of inlined file: juce_mac_Fonts.mm ***/
  230359. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230360. // compiled on its own).
  230361. #if JUCE_INCLUDED_FILE
  230362. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  230363. #define SUPPORT_10_4_FONTS 1
  230364. #define NEW_CGFONT_FUNCTIONS_UNAVAILABLE (CGFontCreateWithFontName == 0)
  230365. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  230366. #define SUPPORT_ONLY_10_4_FONTS 1
  230367. #endif
  230368. END_JUCE_NAMESPACE
  230369. @interface NSFont (PrivateHack)
  230370. - (NSGlyph) _defaultGlyphForChar: (unichar) theChar;
  230371. @end
  230372. BEGIN_JUCE_NAMESPACE
  230373. #endif
  230374. class MacTypeface : public Typeface
  230375. {
  230376. public:
  230377. MacTypeface (const Font& font)
  230378. : Typeface (font.getTypefaceName())
  230379. {
  230380. const ScopedAutoReleasePool pool;
  230381. renderingTransform = CGAffineTransformIdentity;
  230382. bool needsItalicTransform = false;
  230383. #if JUCE_IOS
  230384. NSString* fontName = juceStringToNS (font.getTypefaceName());
  230385. if (font.isItalic() || font.isBold())
  230386. {
  230387. NSArray* familyFonts = [UIFont fontNamesForFamilyName: juceStringToNS (font.getTypefaceName())];
  230388. for (NSString* i in familyFonts)
  230389. {
  230390. const String fn (nsStringToJuce (i));
  230391. const String afterDash (fn.fromFirstOccurrenceOf ("-", false, false));
  230392. const bool probablyBold = afterDash.containsIgnoreCase ("bold") || fn.endsWithIgnoreCase ("bold");
  230393. const bool probablyItalic = afterDash.containsIgnoreCase ("oblique")
  230394. || afterDash.containsIgnoreCase ("italic")
  230395. || fn.endsWithIgnoreCase ("oblique")
  230396. || fn.endsWithIgnoreCase ("italic");
  230397. if (probablyBold == font.isBold()
  230398. && probablyItalic == font.isItalic())
  230399. {
  230400. fontName = i;
  230401. needsItalicTransform = false;
  230402. break;
  230403. }
  230404. else if (probablyBold && (! probablyItalic) && probablyBold == font.isBold())
  230405. {
  230406. fontName = i;
  230407. needsItalicTransform = true; // not ideal, so carry on in case we find a better one
  230408. }
  230409. }
  230410. if (needsItalicTransform)
  230411. renderingTransform.c = 0.15f;
  230412. }
  230413. fontRef = CGFontCreateWithFontName ((CFStringRef) fontName);
  230414. const int ascender = abs (CGFontGetAscent (fontRef));
  230415. const float totalHeight = ascender + abs (CGFontGetDescent (fontRef));
  230416. ascent = ascender / totalHeight;
  230417. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230418. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / totalHeight;
  230419. #else
  230420. nsFont = [NSFont fontWithName: juceStringToNS (font.getTypefaceName()) size: 1024];
  230421. if (font.isItalic())
  230422. {
  230423. NSFont* newFont = [[NSFontManager sharedFontManager] convertFont: nsFont
  230424. toHaveTrait: NSItalicFontMask];
  230425. if (newFont == nsFont)
  230426. needsItalicTransform = true; // couldn't find a proper italic version, so fake it with a transform..
  230427. nsFont = newFont;
  230428. }
  230429. if (font.isBold())
  230430. nsFont = [[NSFontManager sharedFontManager] convertFont: nsFont toHaveTrait: NSBoldFontMask];
  230431. [nsFont retain];
  230432. ascent = std::abs ((float) [nsFont ascender]);
  230433. float totalSize = ascent + std::abs ((float) [nsFont descender]);
  230434. ascent /= totalSize;
  230435. pathTransform = AffineTransform::identity.scale (1.0f / totalSize, 1.0f / totalSize);
  230436. if (needsItalicTransform)
  230437. {
  230438. pathTransform = pathTransform.sheared (-0.15f, 0.0f);
  230439. renderingTransform.c = 0.15f;
  230440. }
  230441. #if SUPPORT_ONLY_10_4_FONTS
  230442. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230443. if (atsFont == 0)
  230444. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230445. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230446. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230447. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230448. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230449. #else
  230450. #if SUPPORT_10_4_FONTS
  230451. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230452. {
  230453. ATSFontRef atsFont = ATSFontFindFromName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230454. if (atsFont == 0)
  230455. atsFont = ATSFontFindFromPostScriptName ((CFStringRef) [nsFont fontName], kATSOptionFlagsDefault);
  230456. fontRef = CGFontCreateWithPlatformFont (&atsFont);
  230457. const float totalHeight = std::abs ([nsFont ascender]) + std::abs ([nsFont descender]);
  230458. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230459. fontHeightToCGSizeFactor = 1024.0f / totalHeight;
  230460. }
  230461. else
  230462. #endif
  230463. {
  230464. fontRef = CGFontCreateWithFontName ((CFStringRef) [nsFont fontName]);
  230465. const int totalHeight = abs (CGFontGetAscent (fontRef)) + abs (CGFontGetDescent (fontRef));
  230466. unitsToHeightScaleFactor = 1.0f / totalHeight;
  230467. fontHeightToCGSizeFactor = CGFontGetUnitsPerEm (fontRef) / (float) totalHeight;
  230468. }
  230469. #endif
  230470. #endif
  230471. }
  230472. ~MacTypeface()
  230473. {
  230474. #if ! JUCE_IOS
  230475. [nsFont release];
  230476. #endif
  230477. if (fontRef != 0)
  230478. CGFontRelease (fontRef);
  230479. }
  230480. float getAscent() const
  230481. {
  230482. return ascent;
  230483. }
  230484. float getDescent() const
  230485. {
  230486. return 1.0f - ascent;
  230487. }
  230488. float getStringWidth (const String& text)
  230489. {
  230490. if (fontRef == 0 || text.isEmpty())
  230491. return 0;
  230492. const int length = text.length();
  230493. HeapBlock <CGGlyph> glyphs;
  230494. createGlyphsForString (text, length, glyphs);
  230495. float x = 0;
  230496. #if SUPPORT_ONLY_10_4_FONTS
  230497. HeapBlock <NSSize> advances (length);
  230498. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230499. for (int i = 0; i < length; ++i)
  230500. x += advances[i].width;
  230501. #else
  230502. #if SUPPORT_10_4_FONTS
  230503. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230504. {
  230505. HeapBlock <NSSize> advances (length);
  230506. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast<NSGlyph*> (glyphs.getData()) count: length];
  230507. for (int i = 0; i < length; ++i)
  230508. x += advances[i].width;
  230509. }
  230510. else
  230511. #endif
  230512. {
  230513. HeapBlock <int> advances (length);
  230514. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230515. for (int i = 0; i < length; ++i)
  230516. x += advances[i];
  230517. }
  230518. #endif
  230519. return x * unitsToHeightScaleFactor;
  230520. }
  230521. void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
  230522. {
  230523. xOffsets.add (0);
  230524. if (fontRef == 0 || text.isEmpty())
  230525. return;
  230526. const int length = text.length();
  230527. HeapBlock <CGGlyph> glyphs;
  230528. createGlyphsForString (text, length, glyphs);
  230529. #if SUPPORT_ONLY_10_4_FONTS
  230530. HeapBlock <NSSize> advances (length);
  230531. [nsFont getAdvancements: advances forGlyphs: reinterpret_cast <NSGlyph*> (glyphs.getData()) count: length];
  230532. int x = 0;
  230533. for (int i = 0; i < length; ++i)
  230534. {
  230535. x += advances[i].width;
  230536. xOffsets.add (x * unitsToHeightScaleFactor);
  230537. resultGlyphs.add (reinterpret_cast <NSGlyph*> (glyphs.getData())[i]);
  230538. }
  230539. #else
  230540. #if SUPPORT_10_4_FONTS
  230541. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230542. {
  230543. HeapBlock <NSSize> advances (length);
  230544. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230545. [nsFont getAdvancements: advances forGlyphs: nsGlyphs count: length];
  230546. float x = 0;
  230547. for (int i = 0; i < length; ++i)
  230548. {
  230549. x += advances[i].width;
  230550. xOffsets.add (x * unitsToHeightScaleFactor);
  230551. resultGlyphs.add (nsGlyphs[i]);
  230552. }
  230553. }
  230554. else
  230555. #endif
  230556. {
  230557. HeapBlock <int> advances (length);
  230558. if (CGFontGetGlyphAdvances (fontRef, glyphs, length, advances))
  230559. {
  230560. int x = 0;
  230561. for (int i = 0; i < length; ++i)
  230562. {
  230563. x += advances [i];
  230564. xOffsets.add (x * unitsToHeightScaleFactor);
  230565. resultGlyphs.add (glyphs[i]);
  230566. }
  230567. }
  230568. }
  230569. #endif
  230570. }
  230571. bool getOutlineForGlyph (int glyphNumber, Path& path)
  230572. {
  230573. #if JUCE_IOS
  230574. return false;
  230575. #else
  230576. if (nsFont == 0)
  230577. return false;
  230578. // we might need to apply a transform to the path, so it mustn't have anything else in it
  230579. jassert (path.isEmpty());
  230580. const ScopedAutoReleasePool pool;
  230581. NSBezierPath* bez = [NSBezierPath bezierPath];
  230582. [bez moveToPoint: NSMakePoint (0, 0)];
  230583. [bez appendBezierPathWithGlyph: (NSGlyph) glyphNumber
  230584. inFont: nsFont];
  230585. for (int i = 0; i < [bez elementCount]; ++i)
  230586. {
  230587. NSPoint p[3];
  230588. switch ([bez elementAtIndex: i associatedPoints: p])
  230589. {
  230590. case NSMoveToBezierPathElement:
  230591. path.startNewSubPath ((float) p[0].x, (float) -p[0].y);
  230592. break;
  230593. case NSLineToBezierPathElement:
  230594. path.lineTo ((float) p[0].x, (float) -p[0].y);
  230595. break;
  230596. case NSCurveToBezierPathElement:
  230597. 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);
  230598. break;
  230599. case NSClosePathBezierPathElement:
  230600. path.closeSubPath();
  230601. break;
  230602. default:
  230603. jassertfalse;
  230604. break;
  230605. }
  230606. }
  230607. path.applyTransform (pathTransform);
  230608. return true;
  230609. #endif
  230610. }
  230611. juce_UseDebuggingNewOperator
  230612. CGFontRef fontRef;
  230613. float fontHeightToCGSizeFactor;
  230614. CGAffineTransform renderingTransform;
  230615. private:
  230616. float ascent, unitsToHeightScaleFactor;
  230617. #if JUCE_IOS
  230618. #else
  230619. NSFont* nsFont;
  230620. AffineTransform pathTransform;
  230621. #endif
  230622. void createGlyphsForString (const juce_wchar* const text, const int length, HeapBlock <CGGlyph>& glyphs)
  230623. {
  230624. #if SUPPORT_10_4_FONTS
  230625. #if ! SUPPORT_ONLY_10_4_FONTS
  230626. if (NEW_CGFONT_FUNCTIONS_UNAVAILABLE)
  230627. #endif
  230628. {
  230629. glyphs.malloc (sizeof (NSGlyph) * length, 1);
  230630. NSGlyph* const nsGlyphs = reinterpret_cast<NSGlyph*> (glyphs.getData());
  230631. for (int i = 0; i < length; ++i)
  230632. nsGlyphs[i] = (NSGlyph) [nsFont _defaultGlyphForChar: text[i]];
  230633. return;
  230634. }
  230635. #endif
  230636. #if ! SUPPORT_ONLY_10_4_FONTS
  230637. if (charToGlyphMapper == 0)
  230638. charToGlyphMapper = new CharToGlyphMapper (fontRef);
  230639. glyphs.malloc (length);
  230640. for (int i = 0; i < length; ++i)
  230641. glyphs[i] = (CGGlyph) charToGlyphMapper->getGlyphForCharacter (text[i]);
  230642. #endif
  230643. }
  230644. #if ! SUPPORT_ONLY_10_4_FONTS
  230645. // Reads a CGFontRef's character map table to convert unicode into glyph numbers
  230646. class CharToGlyphMapper
  230647. {
  230648. public:
  230649. CharToGlyphMapper (CGFontRef fontRef)
  230650. : segCount (0), endCode (0), startCode (0), idDelta (0),
  230651. idRangeOffset (0), glyphIndexes (0)
  230652. {
  230653. CFDataRef cmapTable = CGFontCopyTableForTag (fontRef, 'cmap');
  230654. if (cmapTable != 0)
  230655. {
  230656. const int numSubtables = getValue16 (cmapTable, 2);
  230657. for (int i = 0; i < numSubtables; ++i)
  230658. {
  230659. if (getValue16 (cmapTable, i * 8 + 4) == 0) // check for platform ID of 0
  230660. {
  230661. const int offset = getValue32 (cmapTable, i * 8 + 8);
  230662. if (getValue16 (cmapTable, offset) == 4) // check that it's format 4..
  230663. {
  230664. const int length = getValue16 (cmapTable, offset + 2);
  230665. const int segCountX2 = getValue16 (cmapTable, offset + 6);
  230666. segCount = segCountX2 / 2;
  230667. const int endCodeOffset = offset + 14;
  230668. const int startCodeOffset = endCodeOffset + 2 + segCountX2;
  230669. const int idDeltaOffset = startCodeOffset + segCountX2;
  230670. const int idRangeOffsetOffset = idDeltaOffset + segCountX2;
  230671. const int glyphIndexesOffset = idRangeOffsetOffset + segCountX2;
  230672. endCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + endCodeOffset, segCountX2);
  230673. startCode = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + startCodeOffset, segCountX2);
  230674. idDelta = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idDeltaOffset, segCountX2);
  230675. idRangeOffset = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + idRangeOffsetOffset, segCountX2);
  230676. glyphIndexes = CFDataCreate (kCFAllocatorDefault, CFDataGetBytePtr (cmapTable) + glyphIndexesOffset, offset + length - glyphIndexesOffset);
  230677. }
  230678. break;
  230679. }
  230680. }
  230681. CFRelease (cmapTable);
  230682. }
  230683. }
  230684. ~CharToGlyphMapper()
  230685. {
  230686. if (endCode != 0)
  230687. {
  230688. CFRelease (endCode);
  230689. CFRelease (startCode);
  230690. CFRelease (idDelta);
  230691. CFRelease (idRangeOffset);
  230692. CFRelease (glyphIndexes);
  230693. }
  230694. }
  230695. int getGlyphForCharacter (const juce_wchar c) const
  230696. {
  230697. for (int i = 0; i < segCount; ++i)
  230698. {
  230699. if (getValue16 (endCode, i * 2) >= c)
  230700. {
  230701. const int start = getValue16 (startCode, i * 2);
  230702. if (start > c)
  230703. break;
  230704. const int delta = getValue16 (idDelta, i * 2);
  230705. const int rangeOffset = getValue16 (idRangeOffset, i * 2);
  230706. if (rangeOffset == 0)
  230707. return delta + c;
  230708. else
  230709. return getValue16 (glyphIndexes, 2 * ((rangeOffset / 2) + (c - start) - (segCount - i)));
  230710. }
  230711. }
  230712. // If we failed to find it "properly", this dodgy fall-back seems to do the trick for most fonts!
  230713. return jmax (-1, (int) c - 29);
  230714. }
  230715. private:
  230716. int segCount;
  230717. CFDataRef endCode, startCode, idDelta, idRangeOffset, glyphIndexes;
  230718. static uint16 getValue16 (CFDataRef data, const int index)
  230719. {
  230720. return CFSwapInt16BigToHost (*(UInt16*) (CFDataGetBytePtr (data) + index));
  230721. }
  230722. static uint32 getValue32 (CFDataRef data, const int index)
  230723. {
  230724. return CFSwapInt32BigToHost (*(UInt32*) (CFDataGetBytePtr (data) + index));
  230725. }
  230726. };
  230727. ScopedPointer <CharToGlyphMapper> charToGlyphMapper;
  230728. #endif
  230729. MacTypeface (const MacTypeface&);
  230730. MacTypeface& operator= (const MacTypeface&);
  230731. };
  230732. const Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
  230733. {
  230734. return new MacTypeface (font);
  230735. }
  230736. const StringArray Font::findAllTypefaceNames()
  230737. {
  230738. StringArray names;
  230739. const ScopedAutoReleasePool pool;
  230740. #if JUCE_IOS
  230741. NSArray* fonts = [UIFont familyNames];
  230742. #else
  230743. NSArray* fonts = [[NSFontManager sharedFontManager] availableFontFamilies];
  230744. #endif
  230745. for (unsigned int i = 0; i < [fonts count]; ++i)
  230746. names.add (nsStringToJuce ((NSString*) [fonts objectAtIndex: i]));
  230747. names.sort (true);
  230748. return names;
  230749. }
  230750. void Font::getPlatformDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed)
  230751. {
  230752. #if JUCE_IOS
  230753. defaultSans = "Helvetica";
  230754. defaultSerif = "Times New Roman";
  230755. defaultFixed = "Courier New";
  230756. #else
  230757. defaultSans = "Lucida Grande";
  230758. defaultSerif = "Times New Roman";
  230759. defaultFixed = "Monaco";
  230760. #endif
  230761. }
  230762. #endif
  230763. /*** End of inlined file: juce_mac_Fonts.mm ***/
  230764. // (must go before juce_mac_CoreGraphicsContext.mm)
  230765. /*** Start of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  230766. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  230767. // compiled on its own).
  230768. #if JUCE_INCLUDED_FILE
  230769. class CoreGraphicsImage : public Image::SharedImage
  230770. {
  230771. public:
  230772. CoreGraphicsImage (const Image::PixelFormat format_, const int width_, const int height_, const bool clearImage)
  230773. : Image::SharedImage (format_, width_, height_)
  230774. {
  230775. pixelStride = format_ == Image::RGB ? 3 : ((format_ == Image::ARGB) ? 4 : 1);
  230776. lineStride = (pixelStride * jmax (1, width) + 3) & ~3;
  230777. imageDataAllocated.allocate (lineStride * jmax (1, height), clearImage);
  230778. imageData = imageDataAllocated;
  230779. CGColorSpaceRef colourSpace = (format == Image::SingleChannel) ? CGColorSpaceCreateDeviceGray()
  230780. : CGColorSpaceCreateDeviceRGB();
  230781. context = CGBitmapContextCreate (imageData, width, height, 8, lineStride,
  230782. colourSpace, getCGImageFlags (format_));
  230783. CGColorSpaceRelease (colourSpace);
  230784. }
  230785. ~CoreGraphicsImage()
  230786. {
  230787. CGContextRelease (context);
  230788. }
  230789. Image::ImageType getType() const { return Image::NativeImage; }
  230790. LowLevelGraphicsContext* createLowLevelContext();
  230791. SharedImage* clone()
  230792. {
  230793. CoreGraphicsImage* im = new CoreGraphicsImage (format, width, height, false);
  230794. memcpy (im->imageData, imageData, lineStride * height);
  230795. return im;
  230796. }
  230797. static CGImageRef createImage (const Image& juceImage, const bool forAlpha, CGColorSpaceRef colourSpace)
  230798. {
  230799. const CoreGraphicsImage* nativeImage = dynamic_cast <const CoreGraphicsImage*> (juceImage.getSharedImage());
  230800. if (nativeImage != 0 && (juceImage.getFormat() == Image::SingleChannel || ! forAlpha))
  230801. {
  230802. return CGBitmapContextCreateImage (nativeImage->context);
  230803. }
  230804. else
  230805. {
  230806. const Image::BitmapData srcData (juceImage, false);
  230807. CGDataProviderRef provider = CGDataProviderCreateWithData (0, srcData.data, srcData.lineStride * srcData.height, 0);
  230808. CGImageRef imageRef = CGImageCreate (srcData.width, srcData.height,
  230809. 8, srcData.pixelStride * 8, srcData.lineStride,
  230810. colourSpace, getCGImageFlags (juceImage.getFormat()), provider,
  230811. 0, true, kCGRenderingIntentDefault);
  230812. CGDataProviderRelease (provider);
  230813. return imageRef;
  230814. }
  230815. }
  230816. #if JUCE_MAC
  230817. static NSImage* createNSImage (const Image& image)
  230818. {
  230819. const ScopedAutoReleasePool pool;
  230820. NSImage* im = [[NSImage alloc] init];
  230821. [im setSize: NSMakeSize (image.getWidth(), image.getHeight())];
  230822. [im lockFocus];
  230823. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  230824. CGImageRef imageRef = createImage (image, false, colourSpace);
  230825. CGColorSpaceRelease (colourSpace);
  230826. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  230827. CGContextDrawImage (cg, CGRectMake (0, 0, image.getWidth(), image.getHeight()), imageRef);
  230828. CGImageRelease (imageRef);
  230829. [im unlockFocus];
  230830. return im;
  230831. }
  230832. #endif
  230833. CGContextRef context;
  230834. HeapBlock<uint8> imageDataAllocated;
  230835. private:
  230836. static CGBitmapInfo getCGImageFlags (const Image::PixelFormat& format)
  230837. {
  230838. #if JUCE_BIG_ENDIAN
  230839. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Big) : kCGBitmapByteOrderDefault;
  230840. #else
  230841. return format == Image::ARGB ? (kCGImageAlphaPremultipliedFirst | kCGBitmapByteOrder32Little) : kCGBitmapByteOrderDefault;
  230842. #endif
  230843. }
  230844. };
  230845. Image::SharedImage* Image::SharedImage::createNativeImage (PixelFormat format, int width, int height, bool clearImage)
  230846. {
  230847. #if USE_COREGRAPHICS_RENDERING
  230848. return new CoreGraphicsImage (format == RGB ? ARGB : format, width, height, clearImage);
  230849. #else
  230850. return createSoftwareImage (format, width, height, clearImage);
  230851. #endif
  230852. }
  230853. class CoreGraphicsContext : public LowLevelGraphicsContext
  230854. {
  230855. public:
  230856. CoreGraphicsContext (CGContextRef context_, const float flipHeight_)
  230857. : context (context_),
  230858. flipHeight (flipHeight_),
  230859. lastClipRectIsValid (false),
  230860. state (new SavedState()),
  230861. numGradientLookupEntries (0)
  230862. {
  230863. CGContextRetain (context);
  230864. CGContextSaveGState(context);
  230865. CGContextSetShouldSmoothFonts (context, true);
  230866. CGContextSetShouldAntialias (context, true);
  230867. CGContextSetBlendMode (context, kCGBlendModeNormal);
  230868. rgbColourSpace = CGColorSpaceCreateDeviceRGB();
  230869. greyColourSpace = CGColorSpaceCreateDeviceGray();
  230870. gradientCallbacks.version = 0;
  230871. gradientCallbacks.evaluate = gradientCallback;
  230872. gradientCallbacks.releaseInfo = 0;
  230873. setFont (Font());
  230874. }
  230875. ~CoreGraphicsContext()
  230876. {
  230877. CGContextRestoreGState (context);
  230878. CGContextRelease (context);
  230879. CGColorSpaceRelease (rgbColourSpace);
  230880. CGColorSpaceRelease (greyColourSpace);
  230881. }
  230882. bool isVectorDevice() const { return false; }
  230883. void setOrigin (int x, int y)
  230884. {
  230885. CGContextTranslateCTM (context, x, -y);
  230886. if (lastClipRectIsValid)
  230887. lastClipRect.translate (-x, -y);
  230888. }
  230889. bool clipToRectangle (const Rectangle<int>& r)
  230890. {
  230891. CGContextClipToRect (context, CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()));
  230892. if (lastClipRectIsValid)
  230893. {
  230894. // This is actually incorrect, because the actual clip region may be complex, and
  230895. // clipping its bounds to a rect may not be right... But, removing this shortcut
  230896. // doesn't actually fix anything because CoreGraphics also ignores complex regions
  230897. // when calculating the resultant clip bounds, and makes the same mistake!
  230898. lastClipRect = lastClipRect.getIntersection (r);
  230899. return ! lastClipRect.isEmpty();
  230900. }
  230901. return ! isClipEmpty();
  230902. }
  230903. bool clipToRectangleList (const RectangleList& clipRegion)
  230904. {
  230905. if (clipRegion.isEmpty())
  230906. {
  230907. CGContextClipToRect (context, CGRectMake (0, 0, 0, 0));
  230908. lastClipRectIsValid = true;
  230909. lastClipRect = Rectangle<int>();
  230910. return false;
  230911. }
  230912. else
  230913. {
  230914. const int numRects = clipRegion.getNumRectangles();
  230915. HeapBlock <CGRect> rects (numRects);
  230916. for (int i = 0; i < numRects; ++i)
  230917. {
  230918. const Rectangle<int>& r = clipRegion.getRectangle(i);
  230919. rects[i] = CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight());
  230920. }
  230921. CGContextClipToRects (context, rects, numRects);
  230922. lastClipRectIsValid = false;
  230923. return ! isClipEmpty();
  230924. }
  230925. }
  230926. void excludeClipRectangle (const Rectangle<int>& r)
  230927. {
  230928. RectangleList remaining (getClipBounds());
  230929. remaining.subtract (r);
  230930. clipToRectangleList (remaining);
  230931. lastClipRectIsValid = false;
  230932. }
  230933. void clipToPath (const Path& path, const AffineTransform& transform)
  230934. {
  230935. createPath (path, transform);
  230936. CGContextClip (context);
  230937. lastClipRectIsValid = false;
  230938. }
  230939. void clipToImageAlpha (const Image& sourceImage, const AffineTransform& transform)
  230940. {
  230941. if (! transform.isSingularity())
  230942. {
  230943. Image singleChannelImage (sourceImage);
  230944. if (sourceImage.getFormat() != Image::SingleChannel)
  230945. singleChannelImage = sourceImage.convertedToFormat (Image::SingleChannel);
  230946. CGImageRef image = CoreGraphicsImage::createImage (singleChannelImage, true, greyColourSpace);
  230947. flip();
  230948. AffineTransform t (AffineTransform::scale (1.0f, -1.0f).translated (0, sourceImage.getHeight()).followedBy (transform));
  230949. applyTransform (t);
  230950. CGRect r = CGRectMake (0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  230951. CGContextClipToMask (context, r, image);
  230952. applyTransform (t.inverted());
  230953. flip();
  230954. CGImageRelease (image);
  230955. lastClipRectIsValid = false;
  230956. }
  230957. }
  230958. bool clipRegionIntersects (const Rectangle<int>& r)
  230959. {
  230960. return getClipBounds().intersects (r);
  230961. }
  230962. const Rectangle<int> getClipBounds() const
  230963. {
  230964. if (! lastClipRectIsValid)
  230965. {
  230966. CGRect bounds = CGRectIntegral (CGContextGetClipBoundingBox (context));
  230967. lastClipRectIsValid = true;
  230968. lastClipRect.setBounds (roundToInt (bounds.origin.x),
  230969. roundToInt (flipHeight - (bounds.origin.y + bounds.size.height)),
  230970. roundToInt (bounds.size.width),
  230971. roundToInt (bounds.size.height));
  230972. }
  230973. return lastClipRect;
  230974. }
  230975. bool isClipEmpty() const
  230976. {
  230977. return getClipBounds().isEmpty();
  230978. }
  230979. void saveState()
  230980. {
  230981. CGContextSaveGState (context);
  230982. stateStack.add (new SavedState (*state));
  230983. }
  230984. void restoreState()
  230985. {
  230986. CGContextRestoreGState (context);
  230987. SavedState* const top = stateStack.getLast();
  230988. if (top != 0)
  230989. {
  230990. state = top;
  230991. stateStack.removeLast (1, false);
  230992. lastClipRectIsValid = false;
  230993. }
  230994. else
  230995. {
  230996. jassertfalse; // trying to pop with an empty stack!
  230997. }
  230998. }
  230999. void setFill (const FillType& fillType)
  231000. {
  231001. state->fillType = fillType;
  231002. if (fillType.isColour())
  231003. {
  231004. CGContextSetRGBFillColor (context, fillType.colour.getFloatRed(), fillType.colour.getFloatGreen(),
  231005. fillType.colour.getFloatBlue(), fillType.colour.getFloatAlpha());
  231006. CGContextSetAlpha (context, 1.0f);
  231007. }
  231008. }
  231009. void setOpacity (float newOpacity)
  231010. {
  231011. state->fillType.setOpacity (newOpacity);
  231012. setFill (state->fillType);
  231013. }
  231014. void setInterpolationQuality (Graphics::ResamplingQuality quality)
  231015. {
  231016. CGContextSetInterpolationQuality (context, quality == Graphics::lowResamplingQuality
  231017. ? kCGInterpolationLow
  231018. : kCGInterpolationHigh);
  231019. }
  231020. void fillRect (const Rectangle<int>& r, const bool replaceExistingContents)
  231021. {
  231022. fillCGRect (CGRectMake (r.getX(), flipHeight - r.getBottom(), r.getWidth(), r.getHeight()), replaceExistingContents);
  231023. }
  231024. void fillCGRect (const CGRect& cgRect, const bool replaceExistingContents)
  231025. {
  231026. if (replaceExistingContents)
  231027. {
  231028. #if MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_5
  231029. CGContextClearRect (context, cgRect);
  231030. #else
  231031. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231032. if (CGContextDrawLinearGradient == 0) // (just a way of checking whether we're running in 10.5 or later)
  231033. CGContextClearRect (context, cgRect);
  231034. else
  231035. #endif
  231036. CGContextSetBlendMode (context, kCGBlendModeCopy);
  231037. #endif
  231038. fillCGRect (cgRect, false);
  231039. CGContextSetBlendMode (context, kCGBlendModeNormal);
  231040. }
  231041. else
  231042. {
  231043. if (state->fillType.isColour())
  231044. {
  231045. CGContextFillRect (context, cgRect);
  231046. }
  231047. else if (state->fillType.isGradient())
  231048. {
  231049. CGContextSaveGState (context);
  231050. CGContextClipToRect (context, cgRect);
  231051. drawGradient();
  231052. CGContextRestoreGState (context);
  231053. }
  231054. else
  231055. {
  231056. CGContextSaveGState (context);
  231057. CGContextClipToRect (context, cgRect);
  231058. drawImage (state->fillType.image, state->fillType.transform, true);
  231059. CGContextRestoreGState (context);
  231060. }
  231061. }
  231062. }
  231063. void fillPath (const Path& path, const AffineTransform& transform)
  231064. {
  231065. CGContextSaveGState (context);
  231066. if (state->fillType.isColour())
  231067. {
  231068. flip();
  231069. applyTransform (transform);
  231070. createPath (path);
  231071. if (path.isUsingNonZeroWinding())
  231072. CGContextFillPath (context);
  231073. else
  231074. CGContextEOFillPath (context);
  231075. }
  231076. else
  231077. {
  231078. createPath (path, transform);
  231079. if (path.isUsingNonZeroWinding())
  231080. CGContextClip (context);
  231081. else
  231082. CGContextEOClip (context);
  231083. if (state->fillType.isGradient())
  231084. drawGradient();
  231085. else
  231086. drawImage (state->fillType.image, state->fillType.transform, true);
  231087. }
  231088. CGContextRestoreGState (context);
  231089. }
  231090. void drawImage (const Image& sourceImage, const AffineTransform& transform, const bool fillEntireClipAsTiles)
  231091. {
  231092. const int iw = sourceImage.getWidth();
  231093. const int ih = sourceImage.getHeight();
  231094. CGImageRef image = CoreGraphicsImage::createImage (sourceImage, false, rgbColourSpace);
  231095. CGContextSaveGState (context);
  231096. CGContextSetAlpha (context, state->fillType.getOpacity());
  231097. flip();
  231098. applyTransform (AffineTransform::scale (1.0f, -1.0f).translated (0, ih).followedBy (transform));
  231099. CGRect imageRect = CGRectMake (0, 0, iw, ih);
  231100. if (fillEntireClipAsTiles)
  231101. {
  231102. #if JUCE_IOS
  231103. CGContextDrawTiledImage (context, imageRect, image);
  231104. #else
  231105. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  231106. // There's a bug in CGContextDrawTiledImage that makes it incredibly slow
  231107. // if it's doing a transformation - it's quicker to just draw lots of images manually
  231108. if (CGContextDrawTiledImage != 0 && transform.isOnlyTranslation())
  231109. CGContextDrawTiledImage (context, imageRect, image);
  231110. else
  231111. #endif
  231112. {
  231113. // Fallback to manually doing a tiled fill on 10.4
  231114. CGRect clip = CGRectIntegral (CGContextGetClipBoundingBox (context));
  231115. int x = 0, y = 0;
  231116. while (x > clip.origin.x) x -= iw;
  231117. while (y > clip.origin.y) y -= ih;
  231118. const int right = (int) (clip.origin.x + clip.size.width);
  231119. const int bottom = (int) (clip.origin.y + clip.size.height);
  231120. while (y < bottom)
  231121. {
  231122. for (int x2 = x; x2 < right; x2 += iw)
  231123. CGContextDrawImage (context, CGRectMake (x2, y, iw, ih), image);
  231124. y += ih;
  231125. }
  231126. }
  231127. #endif
  231128. }
  231129. else
  231130. {
  231131. CGContextDrawImage (context, imageRect, image);
  231132. }
  231133. CGImageRelease (image); // (This causes a memory bug in iPhone sim 3.0 - try upgrading to a later version if you hit this)
  231134. CGContextRestoreGState (context);
  231135. }
  231136. void drawLine (const Line<float>& line)
  231137. {
  231138. if (state->fillType.isColour())
  231139. {
  231140. CGContextSetLineCap (context, kCGLineCapSquare);
  231141. CGContextSetLineWidth (context, 1.0f);
  231142. CGContextSetRGBStrokeColor (context,
  231143. state->fillType.colour.getFloatRed(), state->fillType.colour.getFloatGreen(),
  231144. state->fillType.colour.getFloatBlue(), state->fillType.colour.getFloatAlpha());
  231145. CGPoint cgLine[] = { { (CGFloat) line.getStartX(), flipHeight - (CGFloat) line.getStartY() },
  231146. { (CGFloat) line.getEndX(), flipHeight - (CGFloat) line.getEndY() } };
  231147. CGContextStrokeLineSegments (context, cgLine, 1);
  231148. }
  231149. else
  231150. {
  231151. Path p;
  231152. p.addLineSegment (line, 1.0f);
  231153. fillPath (p, AffineTransform::identity);
  231154. }
  231155. }
  231156. void drawVerticalLine (const int x, float top, float bottom)
  231157. {
  231158. if (state->fillType.isColour())
  231159. {
  231160. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231161. CGContextFillRect (context, CGRectMake (x, flipHeight - bottom, 1.0f, bottom - top));
  231162. #else
  231163. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231164. // the x co-ord slightly to trick it..
  231165. CGContextFillRect (context, CGRectMake (x + 1.0f / 256.0f, flipHeight - bottom, 1.0f + 1.0f / 256.0f, bottom - top));
  231166. #endif
  231167. }
  231168. else
  231169. {
  231170. fillCGRect (CGRectMake ((float) x, flipHeight - bottom, 1.0f, bottom - top), false);
  231171. }
  231172. }
  231173. void drawHorizontalLine (const int y, float left, float right)
  231174. {
  231175. if (state->fillType.isColour())
  231176. {
  231177. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_5
  231178. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + 1.0f), right - left, 1.0f));
  231179. #else
  231180. // On Leopard, unless both co-ordinates are non-integer, it disables anti-aliasing, so nudge
  231181. // the x co-ord slightly to trick it..
  231182. CGContextFillRect (context, CGRectMake (left, flipHeight - (y + (1.0f + 1.0f / 256.0f)), right - left, 1.0f + 1.0f / 256.0f));
  231183. #endif
  231184. }
  231185. else
  231186. {
  231187. fillCGRect (CGRectMake (left, flipHeight - (y + 1), right - left, 1.0f), false);
  231188. }
  231189. }
  231190. void setFont (const Font& newFont)
  231191. {
  231192. if (state->font != newFont)
  231193. {
  231194. state->fontRef = 0;
  231195. state->font = newFont;
  231196. MacTypeface* mf = dynamic_cast <MacTypeface*> (state->font.getTypeface());
  231197. if (mf != 0)
  231198. {
  231199. state->fontRef = mf->fontRef;
  231200. CGContextSetFont (context, state->fontRef);
  231201. CGContextSetFontSize (context, state->font.getHeight() * mf->fontHeightToCGSizeFactor);
  231202. state->fontTransform = mf->renderingTransform;
  231203. state->fontTransform.a *= state->font.getHorizontalScale();
  231204. CGContextSetTextMatrix (context, state->fontTransform);
  231205. }
  231206. }
  231207. }
  231208. const Font getFont()
  231209. {
  231210. return state->font;
  231211. }
  231212. void drawGlyph (int glyphNumber, const AffineTransform& transform)
  231213. {
  231214. if (state->fontRef != 0 && state->fillType.isColour())
  231215. {
  231216. if (transform.isOnlyTranslation())
  231217. {
  231218. CGContextSetTextMatrix (context, state->fontTransform); // have to set this each time, as it's not saved as part of the state
  231219. CGGlyph g = glyphNumber;
  231220. CGContextShowGlyphsAtPoint (context, transform.getTranslationX(),
  231221. flipHeight - roundToInt (transform.getTranslationY()), &g, 1);
  231222. }
  231223. else
  231224. {
  231225. CGContextSaveGState (context);
  231226. flip();
  231227. applyTransform (transform);
  231228. CGAffineTransform t = state->fontTransform;
  231229. t.d = -t.d;
  231230. CGContextSetTextMatrix (context, t);
  231231. CGGlyph g = glyphNumber;
  231232. CGContextShowGlyphsAtPoint (context, 0, 0, &g, 1);
  231233. CGContextRestoreGState (context);
  231234. }
  231235. }
  231236. else
  231237. {
  231238. Path p;
  231239. Font& f = state->font;
  231240. f.getTypeface()->getOutlineForGlyph (glyphNumber, p);
  231241. fillPath (p, AffineTransform::scale (f.getHeight() * f.getHorizontalScale(), f.getHeight())
  231242. .followedBy (transform));
  231243. }
  231244. }
  231245. private:
  231246. CGContextRef context;
  231247. const CGFloat flipHeight;
  231248. CGColorSpaceRef rgbColourSpace, greyColourSpace;
  231249. CGFunctionCallbacks gradientCallbacks;
  231250. mutable Rectangle<int> lastClipRect;
  231251. mutable bool lastClipRectIsValid;
  231252. struct SavedState
  231253. {
  231254. SavedState()
  231255. : font (1.0f), fontRef (0), fontTransform (CGAffineTransformIdentity)
  231256. {
  231257. }
  231258. SavedState (const SavedState& other)
  231259. : fillType (other.fillType), font (other.font), fontRef (other.fontRef),
  231260. fontTransform (other.fontTransform)
  231261. {
  231262. }
  231263. ~SavedState()
  231264. {
  231265. }
  231266. FillType fillType;
  231267. Font font;
  231268. CGFontRef fontRef;
  231269. CGAffineTransform fontTransform;
  231270. };
  231271. ScopedPointer <SavedState> state;
  231272. OwnedArray <SavedState> stateStack;
  231273. HeapBlock <PixelARGB> gradientLookupTable;
  231274. int numGradientLookupEntries;
  231275. static void gradientCallback (void* info, const CGFloat* inData, CGFloat* outData)
  231276. {
  231277. const CoreGraphicsContext* const g = static_cast <const CoreGraphicsContext*> (info);
  231278. const int index = roundToInt (g->numGradientLookupEntries * inData[0]);
  231279. PixelARGB colour (g->gradientLookupTable [jlimit (0, g->numGradientLookupEntries, index)]);
  231280. colour.unpremultiply();
  231281. outData[0] = colour.getRed() / 255.0f;
  231282. outData[1] = colour.getGreen() / 255.0f;
  231283. outData[2] = colour.getBlue() / 255.0f;
  231284. outData[3] = colour.getAlpha() / 255.0f;
  231285. }
  231286. CGShadingRef createGradient (const AffineTransform& transform, ColourGradient gradient)
  231287. {
  231288. numGradientLookupEntries = gradient.createLookupTable (transform, gradientLookupTable);
  231289. --numGradientLookupEntries;
  231290. CGShadingRef result = 0;
  231291. CGFunctionRef function = CGFunctionCreate (this, 1, 0, 4, 0, &gradientCallbacks);
  231292. CGPoint p1 (CGPointMake (gradient.point1.getX(), gradient.point1.getY()));
  231293. if (gradient.isRadial)
  231294. {
  231295. result = CGShadingCreateRadial (rgbColourSpace, p1, 0,
  231296. p1, gradient.point1.getDistanceFrom (gradient.point2),
  231297. function, true, true);
  231298. }
  231299. else
  231300. {
  231301. result = CGShadingCreateAxial (rgbColourSpace, p1,
  231302. CGPointMake (gradient.point2.getX(), gradient.point2.getY()),
  231303. function, true, true);
  231304. }
  231305. CGFunctionRelease (function);
  231306. return result;
  231307. }
  231308. void drawGradient()
  231309. {
  231310. flip();
  231311. applyTransform (state->fillType.transform);
  231312. CGContextSetInterpolationQuality (context, kCGInterpolationDefault); // (This is required for 10.4, where there's a crash if
  231313. // you draw a gradient with high quality interp enabled).
  231314. CGShadingRef shading = createGradient (state->fillType.transform, *(state->fillType.gradient));
  231315. CGContextSetAlpha (context, state->fillType.getOpacity());
  231316. CGContextDrawShading (context, shading);
  231317. CGShadingRelease (shading);
  231318. }
  231319. void createPath (const Path& path) const
  231320. {
  231321. CGContextBeginPath (context);
  231322. Path::Iterator i (path);
  231323. while (i.next())
  231324. {
  231325. switch (i.elementType)
  231326. {
  231327. case Path::Iterator::startNewSubPath: CGContextMoveToPoint (context, i.x1, i.y1); break;
  231328. case Path::Iterator::lineTo: CGContextAddLineToPoint (context, i.x1, i.y1); break;
  231329. case Path::Iterator::quadraticTo: CGContextAddQuadCurveToPoint (context, i.x1, i.y1, i.x2, i.y2); break;
  231330. case Path::Iterator::cubicTo: CGContextAddCurveToPoint (context, i.x1, i.y1, i.x2, i.y2, i.x3, i.y3); break;
  231331. case Path::Iterator::closePath: CGContextClosePath (context); break;
  231332. default: jassertfalse; break;
  231333. }
  231334. }
  231335. }
  231336. void createPath (const Path& path, const AffineTransform& transform) const
  231337. {
  231338. CGContextBeginPath (context);
  231339. Path::Iterator i (path);
  231340. while (i.next())
  231341. {
  231342. switch (i.elementType)
  231343. {
  231344. case Path::Iterator::startNewSubPath:
  231345. transform.transformPoint (i.x1, i.y1);
  231346. CGContextMoveToPoint (context, i.x1, flipHeight - i.y1);
  231347. break;
  231348. case Path::Iterator::lineTo:
  231349. transform.transformPoint (i.x1, i.y1);
  231350. CGContextAddLineToPoint (context, i.x1, flipHeight - i.y1);
  231351. break;
  231352. case Path::Iterator::quadraticTo:
  231353. transform.transformPoints (i.x1, i.y1, i.x2, i.y2);
  231354. CGContextAddQuadCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2);
  231355. break;
  231356. case Path::Iterator::cubicTo:
  231357. transform.transformPoints (i.x1, i.y1, i.x2, i.y2, i.x3, i.y3);
  231358. CGContextAddCurveToPoint (context, i.x1, flipHeight - i.y1, i.x2, flipHeight - i.y2, i.x3, flipHeight - i.y3);
  231359. break;
  231360. case Path::Iterator::closePath:
  231361. CGContextClosePath (context); break;
  231362. default:
  231363. jassertfalse;
  231364. break;
  231365. }
  231366. }
  231367. }
  231368. void flip() const
  231369. {
  231370. CGContextConcatCTM (context, CGAffineTransformMake (1, 0, 0, -1, 0, flipHeight));
  231371. }
  231372. void applyTransform (const AffineTransform& transform) const
  231373. {
  231374. CGAffineTransform t;
  231375. t.a = transform.mat00;
  231376. t.b = transform.mat10;
  231377. t.c = transform.mat01;
  231378. t.d = transform.mat11;
  231379. t.tx = transform.mat02;
  231380. t.ty = transform.mat12;
  231381. CGContextConcatCTM (context, t);
  231382. }
  231383. CoreGraphicsContext (const CoreGraphicsContext&);
  231384. CoreGraphicsContext& operator= (const CoreGraphicsContext&);
  231385. };
  231386. LowLevelGraphicsContext* CoreGraphicsImage::createLowLevelContext()
  231387. {
  231388. return new CoreGraphicsContext (context, height);
  231389. }
  231390. #if USE_COREGRAPHICS_RENDERING && ! DONT_USE_COREIMAGE_LOADER
  231391. const Image juce_loadWithCoreImage (InputStream& input)
  231392. {
  231393. MemoryBlock data;
  231394. input.readIntoMemoryBlock (data, -1);
  231395. #if JUCE_IOS
  231396. JUCE_AUTORELEASEPOOL
  231397. UIImage* image = [UIImage imageWithData: [NSData dataWithBytesNoCopy: data.getData()
  231398. length: data.getSize()
  231399. freeWhenDone: NO]];
  231400. if (image != nil)
  231401. {
  231402. CGImageRef loadedImage = image.CGImage;
  231403. #else
  231404. CGDataProviderRef provider = CGDataProviderCreateWithData (0, data.getData(), data.getSize(), 0);
  231405. CGImageSourceRef imageSource = CGImageSourceCreateWithDataProvider (provider, 0);
  231406. CGDataProviderRelease (provider);
  231407. if (imageSource != 0)
  231408. {
  231409. CGImageRef loadedImage = CGImageSourceCreateImageAtIndex (imageSource, 0, 0);
  231410. CFRelease (imageSource);
  231411. #endif
  231412. if (loadedImage != 0)
  231413. {
  231414. CGImageAlphaInfo alphaInfo = CGImageGetAlphaInfo (loadedImage);
  231415. const bool hasAlphaChan = (alphaInfo != kCGImageAlphaNone
  231416. && alphaInfo != kCGImageAlphaNoneSkipLast
  231417. && alphaInfo != kCGImageAlphaNoneSkipFirst);
  231418. Image image (Image::ARGB, // (CoreImage doesn't work with 24-bit images)
  231419. (int) CGImageGetWidth (loadedImage), (int) CGImageGetHeight (loadedImage),
  231420. hasAlphaChan, Image::NativeImage);
  231421. CoreGraphicsImage* const cgImage = dynamic_cast<CoreGraphicsImage*> (image.getSharedImage());
  231422. jassert (cgImage != 0); // if USE_COREGRAPHICS_RENDERING is set, the CoreGraphicsImage class should have been used.
  231423. CGContextDrawImage (cgImage->context, CGRectMake (0, 0, image.getWidth(), image.getHeight()), loadedImage);
  231424. CGContextFlush (cgImage->context);
  231425. #if ! JUCE_IOS
  231426. CFRelease (loadedImage);
  231427. #endif
  231428. // Because it's impossible to create a truly 24-bit CG image, this flag allows a user
  231429. // to find out whether the file they just loaded the image from had an alpha channel or not.
  231430. image.getProperties()->set ("originalImageHadAlpha", hasAlphaChan);
  231431. return image;
  231432. }
  231433. }
  231434. return Image::null;
  231435. }
  231436. #endif
  231437. #endif
  231438. /*** End of inlined file: juce_mac_CoreGraphicsContext.mm ***/
  231439. /*** Start of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  231440. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  231441. // compiled on its own).
  231442. #if JUCE_INCLUDED_FILE
  231443. class NSViewComponentPeer;
  231444. END_JUCE_NAMESPACE
  231445. @interface NSEvent (JuceDeviceDelta)
  231446. - (float) deviceDeltaX;
  231447. - (float) deviceDeltaY;
  231448. @end
  231449. #define JuceNSView MakeObjCClassName(JuceNSView)
  231450. @interface JuceNSView : NSView<NSTextInput>
  231451. {
  231452. @public
  231453. NSViewComponentPeer* owner;
  231454. NSNotificationCenter* notificationCenter;
  231455. String* stringBeingComposed;
  231456. bool textWasInserted;
  231457. }
  231458. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  231459. - (void) dealloc;
  231460. - (BOOL) isOpaque;
  231461. - (void) drawRect: (NSRect) r;
  231462. - (void) mouseDown: (NSEvent*) ev;
  231463. - (void) asyncMouseDown: (NSEvent*) ev;
  231464. - (void) mouseUp: (NSEvent*) ev;
  231465. - (void) asyncMouseUp: (NSEvent*) ev;
  231466. - (void) mouseDragged: (NSEvent*) ev;
  231467. - (void) mouseMoved: (NSEvent*) ev;
  231468. - (void) mouseEntered: (NSEvent*) ev;
  231469. - (void) mouseExited: (NSEvent*) ev;
  231470. - (void) rightMouseDown: (NSEvent*) ev;
  231471. - (void) rightMouseDragged: (NSEvent*) ev;
  231472. - (void) rightMouseUp: (NSEvent*) ev;
  231473. - (void) otherMouseDown: (NSEvent*) ev;
  231474. - (void) otherMouseDragged: (NSEvent*) ev;
  231475. - (void) otherMouseUp: (NSEvent*) ev;
  231476. - (void) scrollWheel: (NSEvent*) ev;
  231477. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  231478. - (void) frameChanged: (NSNotification*) n;
  231479. - (void) viewDidMoveToWindow;
  231480. - (void) keyDown: (NSEvent*) ev;
  231481. - (void) keyUp: (NSEvent*) ev;
  231482. // NSTextInput Methods
  231483. - (void) insertText: (id) aString;
  231484. - (void) doCommandBySelector: (SEL) aSelector;
  231485. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selRange;
  231486. - (void) unmarkText;
  231487. - (BOOL) hasMarkedText;
  231488. - (long) conversationIdentifier;
  231489. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange;
  231490. - (NSRange) markedRange;
  231491. - (NSRange) selectedRange;
  231492. - (NSRect) firstRectForCharacterRange: (NSRange) theRange;
  231493. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint;
  231494. - (NSArray*) validAttributesForMarkedText;
  231495. - (void) flagsChanged: (NSEvent*) ev;
  231496. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231497. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  231498. #endif
  231499. - (BOOL) becomeFirstResponder;
  231500. - (BOOL) resignFirstResponder;
  231501. - (BOOL) acceptsFirstResponder;
  231502. - (void) asyncRepaint: (id) rect;
  231503. - (NSArray*) getSupportedDragTypes;
  231504. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  231505. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  231506. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  231507. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  231508. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  231509. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  231510. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  231511. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  231512. @end
  231513. #define JuceNSWindow MakeObjCClassName(JuceNSWindow)
  231514. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  231515. @interface JuceNSWindow : NSWindow <NSWindowDelegate>
  231516. #else
  231517. @interface JuceNSWindow : NSWindow
  231518. #endif
  231519. {
  231520. @private
  231521. NSViewComponentPeer* owner;
  231522. bool isZooming;
  231523. }
  231524. - (void) setOwner: (NSViewComponentPeer*) owner;
  231525. - (BOOL) canBecomeKeyWindow;
  231526. - (void) becomeKeyWindow;
  231527. - (BOOL) windowShouldClose: (id) window;
  231528. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  231529. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  231530. - (void) zoom: (id) sender;
  231531. @end
  231532. BEGIN_JUCE_NAMESPACE
  231533. class NSViewComponentPeer : public ComponentPeer
  231534. {
  231535. public:
  231536. NSViewComponentPeer (Component* const component,
  231537. const int windowStyleFlags,
  231538. NSView* viewToAttachTo);
  231539. ~NSViewComponentPeer();
  231540. void* getNativeHandle() const;
  231541. void setVisible (bool shouldBeVisible);
  231542. void setTitle (const String& title);
  231543. void setPosition (int x, int y);
  231544. void setSize (int w, int h);
  231545. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  231546. const Rectangle<int> getBounds (const bool global) const;
  231547. const Rectangle<int> getBounds() const;
  231548. const Point<int> getScreenPosition() const;
  231549. const Point<int> relativePositionToGlobal (const Point<int>& relativePosition);
  231550. const Point<int> globalPositionToRelative (const Point<int>& screenPosition);
  231551. void setAlpha (float newAlpha);
  231552. void setMinimised (bool shouldBeMinimised);
  231553. bool isMinimised() const;
  231554. void setFullScreen (bool shouldBeFullScreen);
  231555. bool isFullScreen() const;
  231556. bool contains (const Point<int>& position, bool trueIfInAChildWindow) const;
  231557. const BorderSize getFrameSize() const;
  231558. bool setAlwaysOnTop (bool alwaysOnTop);
  231559. void toFront (bool makeActiveWindow);
  231560. void toBehind (ComponentPeer* other);
  231561. void setIcon (const Image& newIcon);
  231562. const StringArray getAvailableRenderingEngines();
  231563. int getCurrentRenderingEngine() throw();
  231564. void setCurrentRenderingEngine (int index);
  231565. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  231566. for example having more than one juce plugin loaded into a host, then when a
  231567. method is called, the actual code that runs might actually be in a different module
  231568. than the one you expect... So any calls to library functions or statics that are
  231569. made inside obj-c methods will probably end up getting executed in a different DLL's
  231570. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  231571. To work around this insanity, I'm only allowing obj-c methods to make calls to
  231572. virtual methods of an object that's known to live inside the right module's space.
  231573. */
  231574. virtual void redirectMouseDown (NSEvent* ev);
  231575. virtual void redirectMouseUp (NSEvent* ev);
  231576. virtual void redirectMouseDrag (NSEvent* ev);
  231577. virtual void redirectMouseMove (NSEvent* ev);
  231578. virtual void redirectMouseEnter (NSEvent* ev);
  231579. virtual void redirectMouseExit (NSEvent* ev);
  231580. virtual void redirectMouseWheel (NSEvent* ev);
  231581. void sendMouseEvent (NSEvent* ev);
  231582. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  231583. virtual bool redirectKeyDown (NSEvent* ev);
  231584. virtual bool redirectKeyUp (NSEvent* ev);
  231585. virtual void redirectModKeyChange (NSEvent* ev);
  231586. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231587. virtual bool redirectPerformKeyEquivalent (NSEvent* ev);
  231588. #endif
  231589. virtual BOOL sendDragCallback (int type, id <NSDraggingInfo> sender);
  231590. virtual bool isOpaque();
  231591. virtual void drawRect (NSRect r);
  231592. virtual bool canBecomeKeyWindow();
  231593. virtual bool windowShouldClose();
  231594. virtual void redirectMovedOrResized();
  231595. virtual void viewMovedToWindow();
  231596. virtual NSRect constrainRect (NSRect r);
  231597. static void showArrowCursorIfNeeded();
  231598. static void updateModifiers (NSEvent* e);
  231599. static void updateKeysDown (NSEvent* ev, bool isKeyDown);
  231600. static int getKeyCodeFromEvent (NSEvent* ev)
  231601. {
  231602. const String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  231603. int keyCode = unmodified[0];
  231604. if (keyCode == 0x19) // (backwards-tab)
  231605. keyCode = '\t';
  231606. else if (keyCode == 0x03) // (enter)
  231607. keyCode = '\r';
  231608. else
  231609. keyCode = (int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode);
  231610. if (([ev modifierFlags] & NSNumericPadKeyMask) != 0)
  231611. {
  231612. const int numPadConversions[] = { '0', KeyPress::numberPad0, '1', KeyPress::numberPad1,
  231613. '2', KeyPress::numberPad2, '3', KeyPress::numberPad3,
  231614. '4', KeyPress::numberPad4, '5', KeyPress::numberPad5,
  231615. '6', KeyPress::numberPad6, '7', KeyPress::numberPad7,
  231616. '8', KeyPress::numberPad8, '9', KeyPress::numberPad9,
  231617. '+', KeyPress::numberPadAdd, '-', KeyPress::numberPadSubtract,
  231618. '*', KeyPress::numberPadMultiply, '/', KeyPress::numberPadDivide,
  231619. '.', KeyPress::numberPadDecimalPoint, '=', KeyPress::numberPadEquals };
  231620. for (int i = 0; i < numElementsInArray (numPadConversions); i += 2)
  231621. if (keyCode == numPadConversions [i])
  231622. keyCode = numPadConversions [i + 1];
  231623. }
  231624. return keyCode;
  231625. }
  231626. static int64 getMouseTime (NSEvent* e)
  231627. {
  231628. return (Time::currentTimeMillis() - Time::getMillisecondCounter())
  231629. + (int64) ([e timestamp] * 1000.0);
  231630. }
  231631. static const Point<int> getMousePos (NSEvent* e, NSView* view)
  231632. {
  231633. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  231634. return Point<int> (roundToInt (p.x), roundToInt ([view frame].size.height - p.y));
  231635. }
  231636. static int getModifierForButtonNumber (const NSInteger num)
  231637. {
  231638. return num == 0 ? ModifierKeys::leftButtonModifier
  231639. : (num == 1 ? ModifierKeys::rightButtonModifier
  231640. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  231641. }
  231642. virtual void viewFocusGain();
  231643. virtual void viewFocusLoss();
  231644. bool isFocused() const;
  231645. void grabFocus();
  231646. void textInputRequired (const Point<int>& position);
  231647. void repaint (const Rectangle<int>& area);
  231648. void performAnyPendingRepaintsNow();
  231649. juce_UseDebuggingNewOperator
  231650. NSWindow* window;
  231651. JuceNSView* view;
  231652. bool isSharedWindow, fullScreen, insideDrawRect, usingCoreGraphics, recursiveToFrontCall;
  231653. static ModifierKeys currentModifiers;
  231654. static ComponentPeer* currentlyFocusedPeer;
  231655. static Array<int> keysCurrentlyDown;
  231656. };
  231657. END_JUCE_NAMESPACE
  231658. @implementation JuceNSView
  231659. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  231660. withFrame: (NSRect) frame
  231661. {
  231662. [super initWithFrame: frame];
  231663. owner = owner_;
  231664. stringBeingComposed = 0;
  231665. textWasInserted = false;
  231666. notificationCenter = [NSNotificationCenter defaultCenter];
  231667. [notificationCenter addObserver: self
  231668. selector: @selector (frameChanged:)
  231669. name: NSViewFrameDidChangeNotification
  231670. object: self];
  231671. if (! owner_->isSharedWindow)
  231672. {
  231673. [notificationCenter addObserver: self
  231674. selector: @selector (frameChanged:)
  231675. name: NSWindowDidMoveNotification
  231676. object: owner_->window];
  231677. }
  231678. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  231679. return self;
  231680. }
  231681. - (void) dealloc
  231682. {
  231683. [notificationCenter removeObserver: self];
  231684. delete stringBeingComposed;
  231685. [super dealloc];
  231686. }
  231687. - (void) drawRect: (NSRect) r
  231688. {
  231689. if (owner != 0)
  231690. owner->drawRect (r);
  231691. }
  231692. - (BOOL) isOpaque
  231693. {
  231694. return owner == 0 || owner->isOpaque();
  231695. }
  231696. - (void) mouseDown: (NSEvent*) ev
  231697. {
  231698. if (JUCEApplication::isStandaloneApp())
  231699. [self asyncMouseDown: ev];
  231700. else
  231701. // In some host situations, the host will stop modal loops from working
  231702. // correctly if they're called from a mouse event, so we'll trigger
  231703. // the event asynchronously..
  231704. [self performSelectorOnMainThread: @selector (asyncMouseDown:)
  231705. withObject: ev
  231706. waitUntilDone: NO];
  231707. }
  231708. - (void) asyncMouseDown: (NSEvent*) ev
  231709. {
  231710. if (owner != 0)
  231711. owner->redirectMouseDown (ev);
  231712. }
  231713. - (void) mouseUp: (NSEvent*) ev
  231714. {
  231715. if (! JUCEApplication::isStandaloneApp())
  231716. [self asyncMouseUp: ev];
  231717. else
  231718. // In some host situations, the host will stop modal loops from working
  231719. // correctly if they're called from a mouse event, so we'll trigger
  231720. // the event asynchronously..
  231721. [self performSelectorOnMainThread: @selector (asyncMouseUp:)
  231722. withObject: ev
  231723. waitUntilDone: NO];
  231724. }
  231725. - (void) asyncMouseUp: (NSEvent*) ev
  231726. {
  231727. if (owner != 0)
  231728. owner->redirectMouseUp (ev);
  231729. }
  231730. - (void) mouseDragged: (NSEvent*) ev
  231731. {
  231732. if (owner != 0)
  231733. owner->redirectMouseDrag (ev);
  231734. }
  231735. - (void) mouseMoved: (NSEvent*) ev
  231736. {
  231737. if (owner != 0)
  231738. owner->redirectMouseMove (ev);
  231739. }
  231740. - (void) mouseEntered: (NSEvent*) ev
  231741. {
  231742. if (owner != 0)
  231743. owner->redirectMouseEnter (ev);
  231744. }
  231745. - (void) mouseExited: (NSEvent*) ev
  231746. {
  231747. if (owner != 0)
  231748. owner->redirectMouseExit (ev);
  231749. }
  231750. - (void) rightMouseDown: (NSEvent*) ev
  231751. {
  231752. [self mouseDown: ev];
  231753. }
  231754. - (void) rightMouseDragged: (NSEvent*) ev
  231755. {
  231756. [self mouseDragged: ev];
  231757. }
  231758. - (void) rightMouseUp: (NSEvent*) ev
  231759. {
  231760. [self mouseUp: ev];
  231761. }
  231762. - (void) otherMouseDown: (NSEvent*) ev
  231763. {
  231764. [self mouseDown: ev];
  231765. }
  231766. - (void) otherMouseDragged: (NSEvent*) ev
  231767. {
  231768. [self mouseDragged: ev];
  231769. }
  231770. - (void) otherMouseUp: (NSEvent*) ev
  231771. {
  231772. [self mouseUp: ev];
  231773. }
  231774. - (void) scrollWheel: (NSEvent*) ev
  231775. {
  231776. if (owner != 0)
  231777. owner->redirectMouseWheel (ev);
  231778. }
  231779. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  231780. {
  231781. (void) ev;
  231782. return YES;
  231783. }
  231784. - (void) frameChanged: (NSNotification*) n
  231785. {
  231786. (void) n;
  231787. if (owner != 0)
  231788. owner->redirectMovedOrResized();
  231789. }
  231790. - (void) viewDidMoveToWindow
  231791. {
  231792. if (owner != 0)
  231793. owner->viewMovedToWindow();
  231794. }
  231795. - (void) asyncRepaint: (id) rect
  231796. {
  231797. NSRect* r = (NSRect*) [((NSData*) rect) bytes];
  231798. [self setNeedsDisplayInRect: *r];
  231799. }
  231800. - (void) keyDown: (NSEvent*) ev
  231801. {
  231802. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231803. textWasInserted = false;
  231804. if (target != 0)
  231805. [self interpretKeyEvents: [NSArray arrayWithObject: ev]];
  231806. else
  231807. deleteAndZero (stringBeingComposed);
  231808. if ((! textWasInserted) && (owner == 0 || ! owner->redirectKeyDown (ev)))
  231809. [super keyDown: ev];
  231810. }
  231811. - (void) keyUp: (NSEvent*) ev
  231812. {
  231813. if (owner == 0 || ! owner->redirectKeyUp (ev))
  231814. [super keyUp: ev];
  231815. }
  231816. - (void) insertText: (id) aString
  231817. {
  231818. // This commits multi-byte text when return is pressed, or after every keypress for western keyboards
  231819. NSString* newText = [aString isKindOfClass: [NSAttributedString class]] ? [aString string] : aString;
  231820. if ([newText length] > 0)
  231821. {
  231822. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231823. if (target != 0)
  231824. {
  231825. target->insertTextAtCaret (nsStringToJuce (newText));
  231826. textWasInserted = true;
  231827. }
  231828. }
  231829. deleteAndZero (stringBeingComposed);
  231830. }
  231831. - (void) doCommandBySelector: (SEL) aSelector
  231832. {
  231833. (void) aSelector;
  231834. }
  231835. - (void) setMarkedText: (id) aString selectedRange: (NSRange) selectionRange
  231836. {
  231837. (void) selectionRange;
  231838. if (stringBeingComposed == 0)
  231839. stringBeingComposed = new String();
  231840. *stringBeingComposed = nsStringToJuce ([aString isKindOfClass:[NSAttributedString class]] ? [aString string] : aString);
  231841. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231842. if (target != 0)
  231843. {
  231844. const Range<int> currentHighlight (target->getHighlightedRegion());
  231845. target->insertTextAtCaret (*stringBeingComposed);
  231846. target->setHighlightedRegion (currentHighlight.withLength (stringBeingComposed->length()));
  231847. textWasInserted = true;
  231848. }
  231849. }
  231850. - (void) unmarkText
  231851. {
  231852. if (stringBeingComposed != 0)
  231853. {
  231854. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231855. if (target != 0)
  231856. {
  231857. target->insertTextAtCaret (*stringBeingComposed);
  231858. textWasInserted = true;
  231859. }
  231860. }
  231861. deleteAndZero (stringBeingComposed);
  231862. }
  231863. - (BOOL) hasMarkedText
  231864. {
  231865. return stringBeingComposed != 0;
  231866. }
  231867. - (long) conversationIdentifier
  231868. {
  231869. return (long) (pointer_sized_int) self;
  231870. }
  231871. - (NSAttributedString*) attributedSubstringFromRange: (NSRange) theRange
  231872. {
  231873. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231874. if (target != 0)
  231875. {
  231876. const Range<int> r ((int) theRange.location,
  231877. (int) (theRange.location + theRange.length));
  231878. return [[[NSAttributedString alloc] initWithString: juceStringToNS (target->getTextInRange (r))] autorelease];
  231879. }
  231880. return nil;
  231881. }
  231882. - (NSRange) markedRange
  231883. {
  231884. return stringBeingComposed != 0 ? NSMakeRange (0, stringBeingComposed->length())
  231885. : NSMakeRange (NSNotFound, 0);
  231886. }
  231887. - (NSRange) selectedRange
  231888. {
  231889. TextInputTarget* const target = owner->findCurrentTextInputTarget();
  231890. if (target != 0)
  231891. {
  231892. const Range<int> highlight (target->getHighlightedRegion());
  231893. if (! highlight.isEmpty())
  231894. return NSMakeRange (highlight.getStart(), highlight.getLength());
  231895. }
  231896. return NSMakeRange (NSNotFound, 0);
  231897. }
  231898. - (NSRect) firstRectForCharacterRange: (NSRange) theRange
  231899. {
  231900. (void) theRange;
  231901. JUCE_NAMESPACE::Component* const comp = dynamic_cast <JUCE_NAMESPACE::Component*> (owner->findCurrentTextInputTarget());
  231902. if (comp == 0)
  231903. return NSMakeRect (0, 0, 0, 0);
  231904. const Rectangle<int> bounds (comp->getScreenBounds());
  231905. return NSMakeRect (bounds.getX(),
  231906. [[[NSScreen screens] objectAtIndex: 0] frame].size.height - bounds.getY(),
  231907. bounds.getWidth(),
  231908. bounds.getHeight());
  231909. }
  231910. - (NSUInteger) characterIndexForPoint: (NSPoint) thePoint
  231911. {
  231912. (void) thePoint;
  231913. return NSNotFound;
  231914. }
  231915. - (NSArray*) validAttributesForMarkedText
  231916. {
  231917. return [NSArray array];
  231918. }
  231919. - (void) flagsChanged: (NSEvent*) ev
  231920. {
  231921. if (owner != 0)
  231922. owner->redirectModKeyChange (ev);
  231923. }
  231924. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  231925. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  231926. {
  231927. if (owner != 0 && owner->redirectPerformKeyEquivalent (ev))
  231928. return true;
  231929. return [super performKeyEquivalent: ev];
  231930. }
  231931. #endif
  231932. - (BOOL) becomeFirstResponder
  231933. {
  231934. if (owner != 0)
  231935. owner->viewFocusGain();
  231936. return true;
  231937. }
  231938. - (BOOL) resignFirstResponder
  231939. {
  231940. if (owner != 0)
  231941. owner->viewFocusLoss();
  231942. return true;
  231943. }
  231944. - (BOOL) acceptsFirstResponder
  231945. {
  231946. return owner != 0 && owner->canBecomeKeyWindow();
  231947. }
  231948. - (NSArray*) getSupportedDragTypes
  231949. {
  231950. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  231951. }
  231952. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  231953. {
  231954. return owner != 0 && owner->sendDragCallback (type, sender);
  231955. }
  231956. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  231957. {
  231958. if ([self sendDragCallback: 0 sender: sender])
  231959. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231960. else
  231961. return NSDragOperationNone;
  231962. }
  231963. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  231964. {
  231965. if ([self sendDragCallback: 0 sender: sender])
  231966. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  231967. else
  231968. return NSDragOperationNone;
  231969. }
  231970. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  231971. {
  231972. [self sendDragCallback: 1 sender: sender];
  231973. }
  231974. - (void) draggingExited: (id <NSDraggingInfo>) sender
  231975. {
  231976. [self sendDragCallback: 1 sender: sender];
  231977. }
  231978. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  231979. {
  231980. (void) sender;
  231981. return YES;
  231982. }
  231983. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  231984. {
  231985. return [self sendDragCallback: 2 sender: sender];
  231986. }
  231987. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  231988. {
  231989. (void) sender;
  231990. }
  231991. @end
  231992. @implementation JuceNSWindow
  231993. - (void) setOwner: (NSViewComponentPeer*) owner_
  231994. {
  231995. owner = owner_;
  231996. isZooming = false;
  231997. }
  231998. - (BOOL) canBecomeKeyWindow
  231999. {
  232000. return owner != 0 && owner->canBecomeKeyWindow();
  232001. }
  232002. - (void) becomeKeyWindow
  232003. {
  232004. [super becomeKeyWindow];
  232005. if (owner != 0)
  232006. owner->grabFocus();
  232007. }
  232008. - (BOOL) windowShouldClose: (id) window
  232009. {
  232010. (void) window;
  232011. return owner == 0 || owner->windowShouldClose();
  232012. }
  232013. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  232014. {
  232015. (void) screen;
  232016. if (owner != 0)
  232017. frameRect = owner->constrainRect (frameRect);
  232018. return frameRect;
  232019. }
  232020. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  232021. {
  232022. (void) window;
  232023. if (isZooming)
  232024. return proposedFrameSize;
  232025. NSRect frameRect = [self frame];
  232026. frameRect.origin.y -= proposedFrameSize.height - frameRect.size.height;
  232027. frameRect.size = proposedFrameSize;
  232028. if (owner != 0)
  232029. frameRect = owner->constrainRect (frameRect);
  232030. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  232031. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  232032. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  232033. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  232034. return frameRect.size;
  232035. }
  232036. - (void) zoom: (id) sender
  232037. {
  232038. isZooming = true;
  232039. [super zoom: sender];
  232040. isZooming = false;
  232041. }
  232042. - (void) windowWillMove: (NSNotification*) notification
  232043. {
  232044. (void) notification;
  232045. if (JUCE_NAMESPACE::Component::getCurrentlyModalComponent() != 0
  232046. && owner->getComponent()->isCurrentlyBlockedByAnotherModalComponent()
  232047. && (owner->getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowHasTitleBar) != 0)
  232048. JUCE_NAMESPACE::Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  232049. }
  232050. @end
  232051. BEGIN_JUCE_NAMESPACE
  232052. ModifierKeys NSViewComponentPeer::currentModifiers;
  232053. ComponentPeer* NSViewComponentPeer::currentlyFocusedPeer = 0;
  232054. Array<int> NSViewComponentPeer::keysCurrentlyDown;
  232055. bool KeyPress::isKeyCurrentlyDown (const int keyCode)
  232056. {
  232057. if (NSViewComponentPeer::keysCurrentlyDown.contains (keyCode))
  232058. return true;
  232059. if (keyCode >= 'A' && keyCode <= 'Z'
  232060. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toLowerCase ((juce_wchar) keyCode)))
  232061. return true;
  232062. if (keyCode >= 'a' && keyCode <= 'z'
  232063. && NSViewComponentPeer::keysCurrentlyDown.contains ((int) CharacterFunctions::toUpperCase ((juce_wchar) keyCode)))
  232064. return true;
  232065. return false;
  232066. }
  232067. void NSViewComponentPeer::updateModifiers (NSEvent* e)
  232068. {
  232069. int m = 0;
  232070. if (([e modifierFlags] & NSShiftKeyMask) != 0) m |= ModifierKeys::shiftModifier;
  232071. if (([e modifierFlags] & NSControlKeyMask) != 0) m |= ModifierKeys::ctrlModifier;
  232072. if (([e modifierFlags] & NSAlternateKeyMask) != 0) m |= ModifierKeys::altModifier;
  232073. if (([e modifierFlags] & NSCommandKeyMask) != 0) m |= ModifierKeys::commandModifier;
  232074. currentModifiers = currentModifiers.withOnlyMouseButtons().withFlags (m);
  232075. }
  232076. void NSViewComponentPeer::updateKeysDown (NSEvent* ev, bool isKeyDown)
  232077. {
  232078. updateModifiers (ev);
  232079. int keyCode = getKeyCodeFromEvent (ev);
  232080. if (keyCode != 0)
  232081. {
  232082. if (isKeyDown)
  232083. keysCurrentlyDown.addIfNotAlreadyThere (keyCode);
  232084. else
  232085. keysCurrentlyDown.removeValue (keyCode);
  232086. }
  232087. }
  232088. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  232089. {
  232090. return NSViewComponentPeer::currentModifiers;
  232091. }
  232092. void ModifierKeys::updateCurrentModifiers() throw()
  232093. {
  232094. currentModifiers = NSViewComponentPeer::currentModifiers;
  232095. }
  232096. NSViewComponentPeer::NSViewComponentPeer (Component* const component_,
  232097. const int windowStyleFlags,
  232098. NSView* viewToAttachTo)
  232099. : ComponentPeer (component_, windowStyleFlags),
  232100. window (0),
  232101. view (0),
  232102. isSharedWindow (viewToAttachTo != 0),
  232103. fullScreen (false),
  232104. insideDrawRect (false),
  232105. #if USE_COREGRAPHICS_RENDERING
  232106. usingCoreGraphics (true),
  232107. #else
  232108. usingCoreGraphics (false),
  232109. #endif
  232110. recursiveToFrontCall (false)
  232111. {
  232112. NSRect r = NSMakeRect (0, 0, (float) component->getWidth(),(float) component->getHeight());
  232113. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  232114. [view setPostsFrameChangedNotifications: YES];
  232115. if (isSharedWindow)
  232116. {
  232117. window = [viewToAttachTo window];
  232118. [viewToAttachTo addSubview: view];
  232119. }
  232120. else
  232121. {
  232122. r.origin.x = (float) component->getX();
  232123. r.origin.y = (float) component->getY();
  232124. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  232125. unsigned int style = 0;
  232126. if ((windowStyleFlags & windowHasTitleBar) == 0)
  232127. style = NSBorderlessWindowMask;
  232128. else
  232129. style = NSTitledWindowMask;
  232130. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  232131. style |= NSMiniaturizableWindowMask;
  232132. if ((windowStyleFlags & windowHasCloseButton) != 0)
  232133. style |= NSClosableWindowMask;
  232134. if ((windowStyleFlags & windowIsResizable) != 0)
  232135. style |= NSResizableWindowMask;
  232136. window = [[JuceNSWindow alloc] initWithContentRect: r
  232137. styleMask: style
  232138. backing: NSBackingStoreBuffered
  232139. defer: YES];
  232140. [((JuceNSWindow*) window) setOwner: this];
  232141. [window orderOut: nil];
  232142. [window setDelegate: (JuceNSWindow*) window];
  232143. [window setOpaque: component->isOpaque()];
  232144. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  232145. if (component->isAlwaysOnTop())
  232146. [window setLevel: NSFloatingWindowLevel];
  232147. [window setContentView: view];
  232148. [window setAutodisplay: YES];
  232149. [window setAcceptsMouseMovedEvents: YES];
  232150. // We'll both retain and also release this on closing because plugin hosts can unexpectedly
  232151. // close the window for us, and also tend to get cause trouble if setReleasedWhenClosed is NO.
  232152. [window setReleasedWhenClosed: YES];
  232153. [window retain];
  232154. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  232155. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  232156. }
  232157. const float alpha = component->getAlpha();
  232158. if (alpha < 1.0f)
  232159. setAlpha (alpha);
  232160. setTitle (component->getName());
  232161. }
  232162. NSViewComponentPeer::~NSViewComponentPeer()
  232163. {
  232164. view->owner = 0;
  232165. [view removeFromSuperview];
  232166. [view release];
  232167. if (! isSharedWindow)
  232168. {
  232169. [((JuceNSWindow*) window) setOwner: 0];
  232170. [window close];
  232171. [window release];
  232172. }
  232173. }
  232174. void* NSViewComponentPeer::getNativeHandle() const
  232175. {
  232176. return view;
  232177. }
  232178. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  232179. {
  232180. if (isSharedWindow)
  232181. {
  232182. [view setHidden: ! shouldBeVisible];
  232183. }
  232184. else
  232185. {
  232186. if (shouldBeVisible)
  232187. {
  232188. [window orderFront: nil];
  232189. handleBroughtToFront();
  232190. }
  232191. else
  232192. {
  232193. [window orderOut: nil];
  232194. }
  232195. }
  232196. }
  232197. void NSViewComponentPeer::setTitle (const String& title)
  232198. {
  232199. const ScopedAutoReleasePool pool;
  232200. if (! isSharedWindow)
  232201. [window setTitle: juceStringToNS (title)];
  232202. }
  232203. void NSViewComponentPeer::setPosition (int x, int y)
  232204. {
  232205. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  232206. }
  232207. void NSViewComponentPeer::setSize (int w, int h)
  232208. {
  232209. setBounds (component->getX(), component->getY(), w, h, false);
  232210. }
  232211. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, bool isNowFullScreen)
  232212. {
  232213. fullScreen = isNowFullScreen;
  232214. NSRect r = NSMakeRect ((float) x, (float) y, (float) jmax (0, w), (float) jmax (0, h));
  232215. if (isSharedWindow)
  232216. {
  232217. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232218. if ([view frame].size.width != r.size.width
  232219. || [view frame].size.height != r.size.height)
  232220. [view setNeedsDisplay: true];
  232221. [view setFrame: r];
  232222. }
  232223. else
  232224. {
  232225. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - (r.origin.y + r.size.height);
  232226. [window setFrame: [window frameRectForContentRect: r]
  232227. display: true];
  232228. }
  232229. }
  232230. const Rectangle<int> NSViewComponentPeer::getBounds (const bool global) const
  232231. {
  232232. NSRect r = [view frame];
  232233. if (global && [view window] != 0)
  232234. {
  232235. r = [view convertRect: r toView: nil];
  232236. NSRect wr = [[view window] frame];
  232237. r.origin.x += wr.origin.x;
  232238. r.origin.y += wr.origin.y;
  232239. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232240. }
  232241. else
  232242. {
  232243. r.origin.y = [[view superview] frame].size.height - r.origin.y - r.size.height;
  232244. }
  232245. return Rectangle<int> (convertToRectInt (r));
  232246. }
  232247. const Rectangle<int> NSViewComponentPeer::getBounds() const
  232248. {
  232249. return getBounds (! isSharedWindow);
  232250. }
  232251. const Point<int> NSViewComponentPeer::getScreenPosition() const
  232252. {
  232253. return getBounds (true).getPosition();
  232254. }
  232255. const Point<int> NSViewComponentPeer::relativePositionToGlobal (const Point<int>& relativePosition)
  232256. {
  232257. return relativePosition + getScreenPosition();
  232258. }
  232259. const Point<int> NSViewComponentPeer::globalPositionToRelative (const Point<int>& screenPosition)
  232260. {
  232261. return screenPosition - getScreenPosition();
  232262. }
  232263. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  232264. {
  232265. if (constrainer != 0)
  232266. {
  232267. NSRect current = [window frame];
  232268. current.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - current.origin.y - current.size.height;
  232269. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.origin.y - r.size.height;
  232270. Rectangle<int> pos (convertToRectInt (r));
  232271. Rectangle<int> original (convertToRectInt (current));
  232272. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MIN_ALLOWED >= MAC_OS_X_VERSION_10_6
  232273. if ([window inLiveResize])
  232274. #else
  232275. if ([window respondsToSelector: @selector (inLiveResize)]
  232276. && [window performSelector: @selector (inLiveResize)])
  232277. #endif
  232278. {
  232279. constrainer->checkBounds (pos, original,
  232280. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232281. false, false, true, true);
  232282. }
  232283. else
  232284. {
  232285. constrainer->checkBounds (pos, original,
  232286. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  232287. pos.getY() != original.getY() && pos.getBottom() == original.getBottom(),
  232288. pos.getX() != original.getX() && pos.getRight() == original.getRight(),
  232289. pos.getY() == original.getY() && pos.getBottom() != original.getBottom(),
  232290. pos.getX() == original.getX() && pos.getRight() != original.getRight());
  232291. }
  232292. r.origin.x = pos.getX();
  232293. r.origin.y = [[[NSScreen screens] objectAtIndex: 0] frame].size.height - r.size.height - pos.getY();
  232294. r.size.width = pos.getWidth();
  232295. r.size.height = pos.getHeight();
  232296. }
  232297. return r;
  232298. }
  232299. void NSViewComponentPeer::setAlpha (float newAlpha)
  232300. {
  232301. if (! isSharedWindow)
  232302. [window setAlphaValue: (CGFloat) newAlpha];
  232303. else
  232304. [view setAlphaValue: (CGFloat) newAlpha];
  232305. }
  232306. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  232307. {
  232308. if (! isSharedWindow)
  232309. {
  232310. if (shouldBeMinimised)
  232311. [window miniaturize: nil];
  232312. else
  232313. [window deminiaturize: nil];
  232314. }
  232315. }
  232316. bool NSViewComponentPeer::isMinimised() const
  232317. {
  232318. return window != 0 && [window isMiniaturized];
  232319. }
  232320. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  232321. {
  232322. if (! isSharedWindow)
  232323. {
  232324. Rectangle<int> r (lastNonFullscreenBounds);
  232325. setMinimised (false);
  232326. if (fullScreen != shouldBeFullScreen)
  232327. {
  232328. if (shouldBeFullScreen && (getStyleFlags() & windowHasTitleBar) != 0)
  232329. {
  232330. fullScreen = true;
  232331. [window performZoom: nil];
  232332. }
  232333. else
  232334. {
  232335. if (shouldBeFullScreen)
  232336. r = Desktop::getInstance().getMainMonitorArea();
  232337. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  232338. if (r != getComponent()->getBounds() && ! r.isEmpty())
  232339. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  232340. }
  232341. }
  232342. }
  232343. }
  232344. bool NSViewComponentPeer::isFullScreen() const
  232345. {
  232346. return fullScreen;
  232347. }
  232348. bool NSViewComponentPeer::contains (const Point<int>& position, bool trueIfInAChildWindow) const
  232349. {
  232350. if (((unsigned int) position.getX()) >= (unsigned int) component->getWidth()
  232351. || ((unsigned int) position.getY()) >= (unsigned int) component->getHeight())
  232352. return false;
  232353. NSPoint p;
  232354. p.x = (float) position.getX();
  232355. p.y = (float) position.getY();
  232356. NSView* v = [view hitTest: p];
  232357. if (trueIfInAChildWindow)
  232358. return v != nil;
  232359. return v == view;
  232360. }
  232361. const BorderSize NSViewComponentPeer::getFrameSize() const
  232362. {
  232363. BorderSize b;
  232364. if (! isSharedWindow)
  232365. {
  232366. NSRect v = [view convertRect: [view frame] toView: nil];
  232367. NSRect w = [window frame];
  232368. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  232369. b.setBottom ((int) v.origin.y);
  232370. b.setLeft ((int) v.origin.x);
  232371. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  232372. }
  232373. return b;
  232374. }
  232375. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  232376. {
  232377. if (! isSharedWindow)
  232378. {
  232379. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  232380. : NSNormalWindowLevel];
  232381. }
  232382. return true;
  232383. }
  232384. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  232385. {
  232386. if (isSharedWindow)
  232387. {
  232388. [[view superview] addSubview: view
  232389. positioned: NSWindowAbove
  232390. relativeTo: nil];
  232391. }
  232392. if (window != 0 && component->isVisible())
  232393. {
  232394. if (makeActiveWindow)
  232395. [window makeKeyAndOrderFront: nil];
  232396. else
  232397. [window orderFront: nil];
  232398. if (! recursiveToFrontCall)
  232399. {
  232400. recursiveToFrontCall = true;
  232401. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232402. handleBroughtToFront();
  232403. recursiveToFrontCall = false;
  232404. }
  232405. }
  232406. }
  232407. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  232408. {
  232409. NSViewComponentPeer* const otherPeer = dynamic_cast <NSViewComponentPeer*> (other);
  232410. jassert (otherPeer != 0); // wrong type of window?
  232411. if (otherPeer != 0)
  232412. {
  232413. if (isSharedWindow)
  232414. {
  232415. [[view superview] addSubview: view
  232416. positioned: NSWindowBelow
  232417. relativeTo: otherPeer->view];
  232418. }
  232419. else
  232420. {
  232421. [window orderWindow: NSWindowBelow
  232422. relativeTo: otherPeer->window != 0 ? [otherPeer->window windowNumber]
  232423. : nil ];
  232424. }
  232425. }
  232426. }
  232427. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  232428. {
  232429. // to do..
  232430. }
  232431. void NSViewComponentPeer::viewFocusGain()
  232432. {
  232433. if (currentlyFocusedPeer != this)
  232434. {
  232435. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  232436. currentlyFocusedPeer->handleFocusLoss();
  232437. currentlyFocusedPeer = this;
  232438. handleFocusGain();
  232439. }
  232440. }
  232441. void NSViewComponentPeer::viewFocusLoss()
  232442. {
  232443. if (currentlyFocusedPeer == this)
  232444. {
  232445. currentlyFocusedPeer = 0;
  232446. handleFocusLoss();
  232447. }
  232448. }
  232449. void juce_HandleProcessFocusChange()
  232450. {
  232451. NSViewComponentPeer::keysCurrentlyDown.clear();
  232452. if (NSViewComponentPeer::isValidPeer (NSViewComponentPeer::currentlyFocusedPeer))
  232453. {
  232454. if (Process::isForegroundProcess())
  232455. {
  232456. NSViewComponentPeer::currentlyFocusedPeer->handleFocusGain();
  232457. ComponentPeer::bringModalComponentToFront();
  232458. }
  232459. else
  232460. {
  232461. NSViewComponentPeer::currentlyFocusedPeer->handleFocusLoss();
  232462. // turn kiosk mode off if we lose focus..
  232463. Desktop::getInstance().setKioskModeComponent (0);
  232464. }
  232465. }
  232466. }
  232467. bool NSViewComponentPeer::isFocused() const
  232468. {
  232469. return isSharedWindow ? this == currentlyFocusedPeer
  232470. : (window != 0 && [window isKeyWindow]);
  232471. }
  232472. void NSViewComponentPeer::grabFocus()
  232473. {
  232474. if (window != 0)
  232475. {
  232476. [window makeKeyWindow];
  232477. [window makeFirstResponder: view];
  232478. viewFocusGain();
  232479. }
  232480. }
  232481. void NSViewComponentPeer::textInputRequired (const Point<int>&)
  232482. {
  232483. }
  232484. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  232485. {
  232486. String unicode (nsStringToJuce ([ev characters]));
  232487. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  232488. int keyCode = getKeyCodeFromEvent (ev);
  232489. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  232490. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  232491. if (unicode.isNotEmpty() || keyCode != 0)
  232492. {
  232493. if (isKeyDown)
  232494. {
  232495. bool used = false;
  232496. while (unicode.length() > 0)
  232497. {
  232498. juce_wchar textCharacter = unicode[0];
  232499. unicode = unicode.substring (1);
  232500. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232501. textCharacter = 0;
  232502. used = handleKeyUpOrDown (true) || used;
  232503. used = handleKeyPress (keyCode, textCharacter) || used;
  232504. }
  232505. return used;
  232506. }
  232507. else
  232508. {
  232509. if (handleKeyUpOrDown (false))
  232510. return true;
  232511. }
  232512. }
  232513. return false;
  232514. }
  232515. bool NSViewComponentPeer::redirectKeyDown (NSEvent* ev)
  232516. {
  232517. updateKeysDown (ev, true);
  232518. bool used = handleKeyEvent (ev, true);
  232519. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  232520. {
  232521. // for command keys, the key-up event is thrown away, so simulate one..
  232522. updateKeysDown (ev, false);
  232523. used = (isValidPeer (this) && handleKeyEvent (ev, false)) || used;
  232524. }
  232525. // (If we're running modally, don't allow unused keystrokes to be passed
  232526. // along to other blocked views..)
  232527. if (Component::getCurrentlyModalComponent() != 0)
  232528. used = true;
  232529. return used;
  232530. }
  232531. bool NSViewComponentPeer::redirectKeyUp (NSEvent* ev)
  232532. {
  232533. updateKeysDown (ev, false);
  232534. return handleKeyEvent (ev, false)
  232535. || Component::getCurrentlyModalComponent() != 0;
  232536. }
  232537. void NSViewComponentPeer::redirectModKeyChange (NSEvent* ev)
  232538. {
  232539. keysCurrentlyDown.clear();
  232540. handleKeyUpOrDown (true);
  232541. updateModifiers (ev);
  232542. handleModifierKeysChange();
  232543. }
  232544. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  232545. bool NSViewComponentPeer::redirectPerformKeyEquivalent (NSEvent* ev)
  232546. {
  232547. if ([ev type] == NSKeyDown)
  232548. return redirectKeyDown (ev);
  232549. else if ([ev type] == NSKeyUp)
  232550. return redirectKeyUp (ev);
  232551. return false;
  232552. }
  232553. #endif
  232554. void NSViewComponentPeer::sendMouseEvent (NSEvent* ev)
  232555. {
  232556. updateModifiers (ev);
  232557. handleMouseEvent (0, getMousePos (ev, view), currentModifiers, getMouseTime (ev));
  232558. }
  232559. void NSViewComponentPeer::redirectMouseDown (NSEvent* ev)
  232560. {
  232561. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232562. sendMouseEvent (ev);
  232563. }
  232564. void NSViewComponentPeer::redirectMouseUp (NSEvent* ev)
  232565. {
  232566. currentModifiers = currentModifiers.withoutFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232567. sendMouseEvent (ev);
  232568. showArrowCursorIfNeeded();
  232569. }
  232570. void NSViewComponentPeer::redirectMouseDrag (NSEvent* ev)
  232571. {
  232572. currentModifiers = currentModifiers.withFlags (getModifierForButtonNumber ([ev buttonNumber]));
  232573. sendMouseEvent (ev);
  232574. }
  232575. void NSViewComponentPeer::redirectMouseMove (NSEvent* ev)
  232576. {
  232577. currentModifiers = currentModifiers.withoutMouseButtons();
  232578. sendMouseEvent (ev);
  232579. showArrowCursorIfNeeded();
  232580. }
  232581. void NSViewComponentPeer::redirectMouseEnter (NSEvent* ev)
  232582. {
  232583. Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
  232584. currentModifiers = currentModifiers.withoutMouseButtons();
  232585. sendMouseEvent (ev);
  232586. }
  232587. void NSViewComponentPeer::redirectMouseExit (NSEvent* ev)
  232588. {
  232589. currentModifiers = currentModifiers.withoutMouseButtons();
  232590. sendMouseEvent (ev);
  232591. }
  232592. void NSViewComponentPeer::redirectMouseWheel (NSEvent* ev)
  232593. {
  232594. updateModifiers (ev);
  232595. float x = 0, y = 0;
  232596. @try
  232597. {
  232598. x = [ev deviceDeltaX] * 0.5f;
  232599. y = [ev deviceDeltaY] * 0.5f;
  232600. }
  232601. @catch (...)
  232602. {}
  232603. if (x == 0 && y == 0)
  232604. {
  232605. x = [ev deltaX] * 10.0f;
  232606. y = [ev deltaY] * 10.0f;
  232607. }
  232608. handleMouseWheel (0, getMousePos (ev, view), getMouseTime (ev), x, y);
  232609. }
  232610. void NSViewComponentPeer::showArrowCursorIfNeeded()
  232611. {
  232612. MouseInputSource& mouse = Desktop::getInstance().getMainMouseSource();
  232613. if (mouse.getComponentUnderMouse() == 0
  232614. && Desktop::getInstance().findComponentAt (mouse.getScreenPosition()) == 0)
  232615. {
  232616. [[NSCursor arrowCursor] set];
  232617. }
  232618. }
  232619. BOOL NSViewComponentPeer::sendDragCallback (int type, id <NSDraggingInfo> sender)
  232620. {
  232621. NSString* bestType
  232622. = [[sender draggingPasteboard] availableTypeFromArray: [view getSupportedDragTypes]];
  232623. if (bestType == nil)
  232624. return false;
  232625. NSPoint p = [view convertPoint: [sender draggingLocation] fromView: nil];
  232626. const Point<int> pos ((int) p.x, (int) ([view frame].size.height - p.y));
  232627. StringArray files;
  232628. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  232629. if (list == nil)
  232630. return false;
  232631. if ([list isKindOfClass: [NSArray class]])
  232632. {
  232633. NSArray* items = (NSArray*) list;
  232634. for (unsigned int i = 0; i < [items count]; ++i)
  232635. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  232636. }
  232637. if (files.size() == 0)
  232638. return false;
  232639. if (type == 0)
  232640. handleFileDragMove (files, pos);
  232641. else if (type == 1)
  232642. handleFileDragExit (files);
  232643. else if (type == 2)
  232644. handleFileDragDrop (files, pos);
  232645. return true;
  232646. }
  232647. bool NSViewComponentPeer::isOpaque()
  232648. {
  232649. return component == 0 || component->isOpaque();
  232650. }
  232651. void NSViewComponentPeer::drawRect (NSRect r)
  232652. {
  232653. if (r.size.width < 1.0f || r.size.height < 1.0f)
  232654. return;
  232655. CGContextRef cg = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
  232656. if (! component->isOpaque())
  232657. CGContextClearRect (cg, CGContextGetClipBoundingBox (cg));
  232658. #if USE_COREGRAPHICS_RENDERING
  232659. if (usingCoreGraphics)
  232660. {
  232661. CoreGraphicsContext context (cg, (float) [view frame].size.height);
  232662. insideDrawRect = true;
  232663. handlePaint (context);
  232664. insideDrawRect = false;
  232665. }
  232666. else
  232667. #endif
  232668. {
  232669. Image temp (getComponent()->isOpaque() ? Image::RGB : Image::ARGB,
  232670. (int) (r.size.width + 0.5f),
  232671. (int) (r.size.height + 0.5f),
  232672. ! getComponent()->isOpaque());
  232673. const int xOffset = -roundToInt (r.origin.x);
  232674. const int yOffset = -roundToInt ([view frame].size.height - (r.origin.y + r.size.height));
  232675. const NSRect* rects = 0;
  232676. NSInteger numRects = 0;
  232677. [view getRectsBeingDrawn: &rects count: &numRects];
  232678. const Rectangle<int> clipBounds (temp.getBounds());
  232679. RectangleList clip;
  232680. for (int i = 0; i < numRects; ++i)
  232681. {
  232682. clip.addWithoutMerging (clipBounds.getIntersection (Rectangle<int> (roundToInt (rects[i].origin.x) + xOffset,
  232683. roundToInt ([view frame].size.height - (rects[i].origin.y + rects[i].size.height)) + yOffset,
  232684. roundToInt (rects[i].size.width),
  232685. roundToInt (rects[i].size.height))));
  232686. }
  232687. if (! clip.isEmpty())
  232688. {
  232689. LowLevelGraphicsSoftwareRenderer context (temp, xOffset, yOffset, clip);
  232690. insideDrawRect = true;
  232691. handlePaint (context);
  232692. insideDrawRect = false;
  232693. CGColorSpaceRef colourSpace = CGColorSpaceCreateDeviceRGB();
  232694. CGImageRef image = CoreGraphicsImage::createImage (temp, false, colourSpace);
  232695. CGColorSpaceRelease (colourSpace);
  232696. CGContextDrawImage (cg, CGRectMake (r.origin.x, r.origin.y, temp.getWidth(), temp.getHeight()), image);
  232697. CGImageRelease (image);
  232698. }
  232699. }
  232700. }
  232701. const StringArray NSViewComponentPeer::getAvailableRenderingEngines()
  232702. {
  232703. StringArray s (ComponentPeer::getAvailableRenderingEngines());
  232704. #if USE_COREGRAPHICS_RENDERING
  232705. s.add ("CoreGraphics Renderer");
  232706. #endif
  232707. return s;
  232708. }
  232709. int NSViewComponentPeer::getCurrentRenderingEngine() throw()
  232710. {
  232711. return usingCoreGraphics ? 1 : 0;
  232712. }
  232713. void NSViewComponentPeer::setCurrentRenderingEngine (int index)
  232714. {
  232715. #if USE_COREGRAPHICS_RENDERING
  232716. if (usingCoreGraphics != (index > 0))
  232717. {
  232718. usingCoreGraphics = index > 0;
  232719. [view setNeedsDisplay: true];
  232720. }
  232721. #endif
  232722. }
  232723. bool NSViewComponentPeer::canBecomeKeyWindow()
  232724. {
  232725. return (getStyleFlags() & JUCE_NAMESPACE::ComponentPeer::windowIgnoresKeyPresses) == 0;
  232726. }
  232727. bool NSViewComponentPeer::windowShouldClose()
  232728. {
  232729. if (! isValidPeer (this))
  232730. return YES;
  232731. handleUserClosingWindow();
  232732. return NO;
  232733. }
  232734. void NSViewComponentPeer::redirectMovedOrResized()
  232735. {
  232736. handleMovedOrResized();
  232737. }
  232738. void NSViewComponentPeer::viewMovedToWindow()
  232739. {
  232740. if (isSharedWindow)
  232741. window = [view window];
  232742. }
  232743. void Desktop::createMouseInputSources()
  232744. {
  232745. mouseSources.add (new MouseInputSource (0, true));
  232746. }
  232747. void juce_setKioskComponent (Component* kioskModeComponent, bool enableOrDisable, bool allowMenusAndBars)
  232748. {
  232749. // Very annoyingly, this function has to use the old SetSystemUIMode function,
  232750. // which is in Carbon.framework. But, because there's no Cocoa equivalent, it
  232751. // is apparently still available in 64-bit apps..
  232752. if (enableOrDisable)
  232753. {
  232754. SetSystemUIMode (kUIModeAllSuppressed, allowMenusAndBars ? kUIOptionAutoShowMenuBar : 0);
  232755. kioskModeComponent->setBounds (Desktop::getInstance().getMainMonitorArea (false));
  232756. }
  232757. else
  232758. {
  232759. SetSystemUIMode (kUIModeNormal, 0);
  232760. }
  232761. }
  232762. class AsyncRepaintMessage : public CallbackMessage
  232763. {
  232764. public:
  232765. NSViewComponentPeer* const peer;
  232766. const Rectangle<int> rect;
  232767. AsyncRepaintMessage (NSViewComponentPeer* const peer_, const Rectangle<int>& rect_)
  232768. : peer (peer_), rect (rect_)
  232769. {
  232770. }
  232771. void messageCallback()
  232772. {
  232773. if (ComponentPeer::isValidPeer (peer))
  232774. peer->repaint (rect);
  232775. }
  232776. };
  232777. void NSViewComponentPeer::repaint (const Rectangle<int>& area)
  232778. {
  232779. if (insideDrawRect)
  232780. {
  232781. (new AsyncRepaintMessage (this, area))->post();
  232782. }
  232783. else
  232784. {
  232785. [view setNeedsDisplayInRect: NSMakeRect ((float) area.getX(), [view frame].size.height - (float) area.getBottom(),
  232786. (float) area.getWidth(), (float) area.getHeight())];
  232787. }
  232788. }
  232789. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  232790. {
  232791. [view displayIfNeeded];
  232792. }
  232793. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  232794. {
  232795. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  232796. }
  232797. const Image juce_createIconForFile (const File& file)
  232798. {
  232799. const ScopedAutoReleasePool pool;
  232800. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  232801. CoreGraphicsImage* result = new CoreGraphicsImage (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  232802. [NSGraphicsContext saveGraphicsState];
  232803. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: result->context flipped: false]];
  232804. [image drawAtPoint: NSMakePoint (0, 0)
  232805. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  232806. operation: NSCompositeSourceOver fraction: 1.0f];
  232807. [[NSGraphicsContext currentContext] flushGraphics];
  232808. [NSGraphicsContext restoreGraphicsState];
  232809. return Image (result);
  232810. }
  232811. const int KeyPress::spaceKey = ' ';
  232812. const int KeyPress::returnKey = 0x0d;
  232813. const int KeyPress::escapeKey = 0x1b;
  232814. const int KeyPress::backspaceKey = 0x7f;
  232815. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  232816. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  232817. const int KeyPress::upKey = NSUpArrowFunctionKey;
  232818. const int KeyPress::downKey = NSDownArrowFunctionKey;
  232819. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  232820. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  232821. const int KeyPress::endKey = NSEndFunctionKey;
  232822. const int KeyPress::homeKey = NSHomeFunctionKey;
  232823. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  232824. const int KeyPress::insertKey = -1;
  232825. const int KeyPress::tabKey = 9;
  232826. const int KeyPress::F1Key = NSF1FunctionKey;
  232827. const int KeyPress::F2Key = NSF2FunctionKey;
  232828. const int KeyPress::F3Key = NSF3FunctionKey;
  232829. const int KeyPress::F4Key = NSF4FunctionKey;
  232830. const int KeyPress::F5Key = NSF5FunctionKey;
  232831. const int KeyPress::F6Key = NSF6FunctionKey;
  232832. const int KeyPress::F7Key = NSF7FunctionKey;
  232833. const int KeyPress::F8Key = NSF8FunctionKey;
  232834. const int KeyPress::F9Key = NSF9FunctionKey;
  232835. const int KeyPress::F10Key = NSF10FunctionKey;
  232836. const int KeyPress::F11Key = NSF1FunctionKey;
  232837. const int KeyPress::F12Key = NSF12FunctionKey;
  232838. const int KeyPress::F13Key = NSF13FunctionKey;
  232839. const int KeyPress::F14Key = NSF14FunctionKey;
  232840. const int KeyPress::F15Key = NSF15FunctionKey;
  232841. const int KeyPress::F16Key = NSF16FunctionKey;
  232842. const int KeyPress::numberPad0 = 0x30020;
  232843. const int KeyPress::numberPad1 = 0x30021;
  232844. const int KeyPress::numberPad2 = 0x30022;
  232845. const int KeyPress::numberPad3 = 0x30023;
  232846. const int KeyPress::numberPad4 = 0x30024;
  232847. const int KeyPress::numberPad5 = 0x30025;
  232848. const int KeyPress::numberPad6 = 0x30026;
  232849. const int KeyPress::numberPad7 = 0x30027;
  232850. const int KeyPress::numberPad8 = 0x30028;
  232851. const int KeyPress::numberPad9 = 0x30029;
  232852. const int KeyPress::numberPadAdd = 0x3002a;
  232853. const int KeyPress::numberPadSubtract = 0x3002b;
  232854. const int KeyPress::numberPadMultiply = 0x3002c;
  232855. const int KeyPress::numberPadDivide = 0x3002d;
  232856. const int KeyPress::numberPadSeparator = 0x3002e;
  232857. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  232858. const int KeyPress::numberPadEquals = 0x30030;
  232859. const int KeyPress::numberPadDelete = 0x30031;
  232860. const int KeyPress::playKey = 0x30000;
  232861. const int KeyPress::stopKey = 0x30001;
  232862. const int KeyPress::fastForwardKey = 0x30002;
  232863. const int KeyPress::rewindKey = 0x30003;
  232864. #endif
  232865. /*** End of inlined file: juce_mac_NSViewComponentPeer.mm ***/
  232866. /*** Start of inlined file: juce_mac_MouseCursor.mm ***/
  232867. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232868. // compiled on its own).
  232869. #if JUCE_INCLUDED_FILE
  232870. #if JUCE_MAC
  232871. namespace MouseCursorHelpers
  232872. {
  232873. static void* createFromImage (const Image& image, float hotspotX, float hotspotY)
  232874. {
  232875. NSImage* im = CoreGraphicsImage::createNSImage (image);
  232876. NSCursor* c = [[NSCursor alloc] initWithImage: im
  232877. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  232878. [im release];
  232879. return c;
  232880. }
  232881. static void* fromWebKitFile (const char* filename, float hx, float hy)
  232882. {
  232883. FileInputStream fileStream (String ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources/") + filename);
  232884. BufferedInputStream buf (fileStream, 4096);
  232885. PNGImageFormat pngFormat;
  232886. Image im (pngFormat.decodeImage (buf));
  232887. if (im.isValid())
  232888. return createFromImage (im, hx * im.getWidth(), hy * im.getHeight());
  232889. jassertfalse;
  232890. return 0;
  232891. }
  232892. }
  232893. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY)
  232894. {
  232895. return MouseCursorHelpers::createFromImage (image, (float) hotspotX, (float) hotspotY);
  232896. }
  232897. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type)
  232898. {
  232899. const ScopedAutoReleasePool pool;
  232900. NSCursor* c = 0;
  232901. switch (type)
  232902. {
  232903. case NormalCursor: c = [NSCursor arrowCursor]; break;
  232904. case NoCursor: return createMouseCursorFromImage (Image (Image::ARGB, 8, 8, true), 0, 0);
  232905. case DraggingHandCursor: c = [NSCursor openHandCursor]; break;
  232906. case WaitCursor: c = [NSCursor arrowCursor]; break; // avoid this on the mac, let the OS provide the beachball
  232907. case IBeamCursor: c = [NSCursor IBeamCursor]; break;
  232908. case PointingHandCursor: c = [NSCursor pointingHandCursor]; break;
  232909. case LeftRightResizeCursor: c = [NSCursor resizeLeftRightCursor]; break;
  232910. case LeftEdgeResizeCursor: c = [NSCursor resizeLeftCursor]; break;
  232911. case RightEdgeResizeCursor: c = [NSCursor resizeRightCursor]; break;
  232912. case CrosshairCursor: c = [NSCursor crosshairCursor]; break;
  232913. case CopyingCursor: return MouseCursorHelpers::fromWebKitFile ("copyCursor.png", 0, 0);
  232914. case UpDownResizeCursor:
  232915. case TopEdgeResizeCursor:
  232916. case BottomEdgeResizeCursor:
  232917. return MouseCursorHelpers::fromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  232918. case TopLeftCornerResizeCursor:
  232919. case BottomRightCornerResizeCursor:
  232920. return MouseCursorHelpers::fromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  232921. case TopRightCornerResizeCursor:
  232922. case BottomLeftCornerResizeCursor:
  232923. return MouseCursorHelpers::fromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  232924. case UpDownLeftRightResizeCursor:
  232925. return MouseCursorHelpers::fromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  232926. default:
  232927. jassertfalse;
  232928. break;
  232929. }
  232930. [c retain];
  232931. return c;
  232932. }
  232933. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool /*isStandard*/)
  232934. {
  232935. [((NSCursor*) cursorHandle) release];
  232936. }
  232937. void MouseCursor::showInAllWindows() const
  232938. {
  232939. showInWindow (0);
  232940. }
  232941. void MouseCursor::showInWindow (ComponentPeer*) const
  232942. {
  232943. [((NSCursor*) getHandle()) set];
  232944. }
  232945. #else
  232946. void* MouseCursor::createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) { return 0; }
  232947. void* MouseCursor::createStandardMouseCursor (MouseCursor::StandardCursorType type) { return 0; }
  232948. void MouseCursor::deleteMouseCursor (void* const cursorHandle, const bool isStandard) {}
  232949. void MouseCursor::showInAllWindows() const {}
  232950. void MouseCursor::showInWindow (ComponentPeer*) const {}
  232951. #endif
  232952. #endif
  232953. /*** End of inlined file: juce_mac_MouseCursor.mm ***/
  232954. /*** Start of inlined file: juce_mac_NSViewComponent.mm ***/
  232955. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  232956. // compiled on its own).
  232957. #if JUCE_INCLUDED_FILE
  232958. class NSViewComponentInternal : public ComponentMovementWatcher
  232959. {
  232960. Component* const owner;
  232961. NSViewComponentPeer* currentPeer;
  232962. bool wasShowing;
  232963. public:
  232964. NSView* const view;
  232965. NSViewComponentInternal (NSView* const view_, Component* const owner_)
  232966. : ComponentMovementWatcher (owner_),
  232967. owner (owner_),
  232968. currentPeer (0),
  232969. wasShowing (false),
  232970. view (view_)
  232971. {
  232972. [view_ retain];
  232973. if (owner_->isShowing())
  232974. componentPeerChanged();
  232975. }
  232976. ~NSViewComponentInternal()
  232977. {
  232978. [view removeFromSuperview];
  232979. [view release];
  232980. }
  232981. void componentMovedOrResized (Component& comp, bool wasMoved, bool wasResized)
  232982. {
  232983. ComponentMovementWatcher::componentMovedOrResized (comp, wasMoved, wasResized);
  232984. // The ComponentMovementWatcher version of this method avoids calling
  232985. // us when the top-level comp is resized, but for an NSView we need to know this
  232986. // because with inverted co-ords, we need to update the position even if the
  232987. // top-left pos hasn't changed
  232988. if (comp.isOnDesktop() && wasResized)
  232989. componentMovedOrResized (wasMoved, wasResized);
  232990. }
  232991. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  232992. {
  232993. Component* const topComp = owner->getTopLevelComponent();
  232994. if (topComp->getPeer() != 0)
  232995. {
  232996. const Point<int> pos (owner->relativePositionToOtherComponent (topComp, Point<int>()));
  232997. NSRect r = NSMakeRect ((float) pos.getX(), (float) pos.getY(), (float) owner->getWidth(), (float) owner->getHeight());
  232998. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  232999. [view setFrame: r];
  233000. }
  233001. }
  233002. void componentPeerChanged()
  233003. {
  233004. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  233005. if (currentPeer != peer)
  233006. {
  233007. if ([view superview] != nil)
  233008. [view removeFromSuperview]; // Must be careful not to call this unless it's required - e.g. some Apple AU views
  233009. // override the call and use it as a sign that they're being deleted, which breaks everything..
  233010. currentPeer = peer;
  233011. if (peer != 0)
  233012. {
  233013. [peer->view addSubview: view];
  233014. componentMovedOrResized (false, false);
  233015. }
  233016. }
  233017. [view setHidden: ! owner->isShowing()];
  233018. }
  233019. void componentVisibilityChanged (Component&)
  233020. {
  233021. componentPeerChanged();
  233022. }
  233023. const Rectangle<int> getViewBounds() const
  233024. {
  233025. NSRect r = [view frame];
  233026. return Rectangle<int> (0, 0, (int) r.size.width, (int) r.size.height);
  233027. }
  233028. juce_UseDebuggingNewOperator
  233029. private:
  233030. NSViewComponentInternal (const NSViewComponentInternal&);
  233031. NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  233032. };
  233033. NSViewComponent::NSViewComponent()
  233034. {
  233035. }
  233036. NSViewComponent::~NSViewComponent()
  233037. {
  233038. }
  233039. void NSViewComponent::setView (void* view)
  233040. {
  233041. if (view != getView())
  233042. {
  233043. if (view != 0)
  233044. info = new NSViewComponentInternal ((NSView*) view, this);
  233045. else
  233046. info = 0;
  233047. }
  233048. }
  233049. void* NSViewComponent::getView() const
  233050. {
  233051. return info == 0 ? 0 : info->view;
  233052. }
  233053. void NSViewComponent::resizeToFitView()
  233054. {
  233055. if (info != 0)
  233056. setBounds (info->getViewBounds());
  233057. }
  233058. void NSViewComponent::paint (Graphics&)
  233059. {
  233060. }
  233061. #endif
  233062. /*** End of inlined file: juce_mac_NSViewComponent.mm ***/
  233063. /*** Start of inlined file: juce_mac_AppleRemote.mm ***/
  233064. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233065. // compiled on its own).
  233066. #if JUCE_INCLUDED_FILE
  233067. AppleRemoteDevice::AppleRemoteDevice()
  233068. : device (0),
  233069. queue (0),
  233070. remoteId (0)
  233071. {
  233072. }
  233073. AppleRemoteDevice::~AppleRemoteDevice()
  233074. {
  233075. stop();
  233076. }
  233077. namespace
  233078. {
  233079. io_object_t getAppleRemoteDevice()
  233080. {
  233081. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  233082. io_iterator_t iter = 0;
  233083. io_object_t iod = 0;
  233084. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  233085. && iter != 0)
  233086. {
  233087. iod = IOIteratorNext (iter);
  233088. }
  233089. IOObjectRelease (iter);
  233090. return iod;
  233091. }
  233092. bool createAppleRemoteInterface (io_object_t iod, void** device)
  233093. {
  233094. jassert (*device == 0);
  233095. io_name_t classname;
  233096. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  233097. {
  233098. IOCFPlugInInterface** cfPlugInInterface = 0;
  233099. SInt32 score = 0;
  233100. if (IOCreatePlugInInterfaceForService (iod,
  233101. kIOHIDDeviceUserClientTypeID,
  233102. kIOCFPlugInInterfaceID,
  233103. &cfPlugInInterface,
  233104. &score) == kIOReturnSuccess)
  233105. {
  233106. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  233107. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  233108. device);
  233109. (void) hr;
  233110. (*cfPlugInInterface)->Release (cfPlugInInterface);
  233111. }
  233112. }
  233113. return *device != 0;
  233114. }
  233115. void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  233116. {
  233117. if (result == kIOReturnSuccess)
  233118. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  233119. }
  233120. }
  233121. bool AppleRemoteDevice::start (const bool inExclusiveMode)
  233122. {
  233123. if (queue != 0)
  233124. return true;
  233125. stop();
  233126. bool result = false;
  233127. io_object_t iod = getAppleRemoteDevice();
  233128. if (iod != 0)
  233129. {
  233130. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  233131. result = true;
  233132. else
  233133. stop();
  233134. IOObjectRelease (iod);
  233135. }
  233136. return result;
  233137. }
  233138. void AppleRemoteDevice::stop()
  233139. {
  233140. if (queue != 0)
  233141. {
  233142. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  233143. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  233144. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  233145. queue = 0;
  233146. }
  233147. if (device != 0)
  233148. {
  233149. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  233150. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  233151. device = 0;
  233152. }
  233153. }
  233154. bool AppleRemoteDevice::isActive() const
  233155. {
  233156. return queue != 0;
  233157. }
  233158. bool AppleRemoteDevice::open (const bool openInExclusiveMode)
  233159. {
  233160. Array <int> cookies;
  233161. CFArrayRef elements;
  233162. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  233163. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  233164. return false;
  233165. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  233166. {
  233167. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  233168. // get the cookie
  233169. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  233170. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  233171. continue;
  233172. long number;
  233173. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  233174. continue;
  233175. cookies.add ((int) number);
  233176. }
  233177. CFRelease (elements);
  233178. if ((*(IOHIDDeviceInterface**) device)
  233179. ->open ((IOHIDDeviceInterface**) device,
  233180. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  233181. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  233182. {
  233183. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  233184. if (queue != 0)
  233185. {
  233186. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  233187. for (int i = 0; i < cookies.size(); ++i)
  233188. {
  233189. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  233190. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  233191. }
  233192. CFRunLoopSourceRef eventSource;
  233193. if ((*(IOHIDQueueInterface**) queue)
  233194. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  233195. {
  233196. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  233197. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  233198. {
  233199. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  233200. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  233201. return true;
  233202. }
  233203. }
  233204. }
  233205. }
  233206. return false;
  233207. }
  233208. void AppleRemoteDevice::handleCallbackInternal()
  233209. {
  233210. int totalValues = 0;
  233211. AbsoluteTime nullTime = { 0, 0 };
  233212. char cookies [12];
  233213. int numCookies = 0;
  233214. while (numCookies < numElementsInArray (cookies))
  233215. {
  233216. IOHIDEventStruct e;
  233217. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  233218. break;
  233219. if ((int) e.elementCookie == 19)
  233220. {
  233221. remoteId = e.value;
  233222. buttonPressed (switched, false);
  233223. }
  233224. else
  233225. {
  233226. totalValues += e.value;
  233227. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  233228. }
  233229. }
  233230. cookies [numCookies++] = 0;
  233231. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  233232. static const char buttonPatterns[] =
  233233. {
  233234. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  233235. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  233236. 0x1f, 0x1d, 0x1c, 0x12, 0,
  233237. 0x1f, 0x1e, 0x1c, 0x12, 0,
  233238. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  233239. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  233240. 0x1f, 0x12, 0x04, 0x02, 0,
  233241. 0x1f, 0x12, 0x03, 0x02, 0,
  233242. 0x1f, 0x12, 0x1f, 0x12, 0,
  233243. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  233244. 19, 0
  233245. };
  233246. int buttonNum = (int) menuButton;
  233247. int i = 0;
  233248. while (i < numElementsInArray (buttonPatterns))
  233249. {
  233250. if (strcmp (cookies, buttonPatterns + i) == 0)
  233251. {
  233252. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  233253. break;
  233254. }
  233255. i += (int) strlen (buttonPatterns + i) + 1;
  233256. ++buttonNum;
  233257. }
  233258. }
  233259. #endif
  233260. /*** End of inlined file: juce_mac_AppleRemote.mm ***/
  233261. /*** Start of inlined file: juce_mac_OpenGLComponent.mm ***/
  233262. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233263. // compiled on its own).
  233264. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  233265. #if JUCE_MAC
  233266. END_JUCE_NAMESPACE
  233267. #define ThreadSafeNSOpenGLView MakeObjCClassName(ThreadSafeNSOpenGLView)
  233268. @interface ThreadSafeNSOpenGLView : NSOpenGLView
  233269. {
  233270. CriticalSection* contextLock;
  233271. bool needsUpdate;
  233272. }
  233273. - (id) initWithFrame: (NSRect) frameRect pixelFormat: (NSOpenGLPixelFormat*) format;
  233274. - (bool) makeActive;
  233275. - (void) makeInactive;
  233276. - (void) reshape;
  233277. @end
  233278. @implementation ThreadSafeNSOpenGLView
  233279. - (id) initWithFrame: (NSRect) frameRect
  233280. pixelFormat: (NSOpenGLPixelFormat*) format
  233281. {
  233282. contextLock = new CriticalSection();
  233283. self = [super initWithFrame: frameRect pixelFormat: format];
  233284. if (self != nil)
  233285. [[NSNotificationCenter defaultCenter] addObserver: self
  233286. selector: @selector (_surfaceNeedsUpdate:)
  233287. name: NSViewGlobalFrameDidChangeNotification
  233288. object: self];
  233289. return self;
  233290. }
  233291. - (void) dealloc
  233292. {
  233293. [[NSNotificationCenter defaultCenter] removeObserver: self];
  233294. delete contextLock;
  233295. [super dealloc];
  233296. }
  233297. - (bool) makeActive
  233298. {
  233299. const ScopedLock sl (*contextLock);
  233300. if ([self openGLContext] == 0)
  233301. return false;
  233302. [[self openGLContext] makeCurrentContext];
  233303. if (needsUpdate)
  233304. {
  233305. [super update];
  233306. needsUpdate = false;
  233307. }
  233308. return true;
  233309. }
  233310. - (void) makeInactive
  233311. {
  233312. const ScopedLock sl (*contextLock);
  233313. [NSOpenGLContext clearCurrentContext];
  233314. }
  233315. - (void) _surfaceNeedsUpdate: (NSNotification*) notification
  233316. {
  233317. const ScopedLock sl (*contextLock);
  233318. needsUpdate = true;
  233319. }
  233320. - (void) update
  233321. {
  233322. const ScopedLock sl (*contextLock);
  233323. needsUpdate = true;
  233324. }
  233325. - (void) reshape
  233326. {
  233327. const ScopedLock sl (*contextLock);
  233328. needsUpdate = true;
  233329. }
  233330. @end
  233331. BEGIN_JUCE_NAMESPACE
  233332. class WindowedGLContext : public OpenGLContext
  233333. {
  233334. public:
  233335. WindowedGLContext (Component* const component,
  233336. const OpenGLPixelFormat& pixelFormat_,
  233337. NSOpenGLContext* sharedContext)
  233338. : renderContext (0),
  233339. pixelFormat (pixelFormat_)
  233340. {
  233341. jassert (component != 0);
  233342. NSOpenGLPixelFormatAttribute attribs [64];
  233343. int n = 0;
  233344. attribs[n++] = NSOpenGLPFADoubleBuffer;
  233345. attribs[n++] = NSOpenGLPFAAccelerated;
  233346. attribs[n++] = NSOpenGLPFAMPSafe; // NSOpenGLPFAAccelerated, NSOpenGLPFAMultiScreen, NSOpenGLPFASingleRenderer
  233347. attribs[n++] = NSOpenGLPFAColorSize;
  233348. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  233349. pixelFormat.greenBits,
  233350. pixelFormat.blueBits);
  233351. attribs[n++] = NSOpenGLPFAAlphaSize;
  233352. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  233353. attribs[n++] = NSOpenGLPFADepthSize;
  233354. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  233355. attribs[n++] = NSOpenGLPFAStencilSize;
  233356. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  233357. attribs[n++] = NSOpenGLPFAAccumSize;
  233358. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  233359. pixelFormat.accumulationBufferGreenBits,
  233360. pixelFormat.accumulationBufferBlueBits,
  233361. pixelFormat.accumulationBufferAlphaBits);
  233362. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  233363. attribs[n++] = NSOpenGLPFASampleBuffers;
  233364. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  233365. attribs[n++] = NSOpenGLPFAClosestPolicy;
  233366. attribs[n++] = NSOpenGLPFANoRecovery;
  233367. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  233368. NSOpenGLPixelFormat* format
  233369. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  233370. view = [[ThreadSafeNSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  233371. pixelFormat: format];
  233372. renderContext = [[[NSOpenGLContext alloc] initWithFormat: format
  233373. shareContext: sharedContext] autorelease];
  233374. const GLint swapInterval = 1;
  233375. [renderContext setValues: &swapInterval forParameter: NSOpenGLCPSwapInterval];
  233376. [view setOpenGLContext: renderContext];
  233377. [format release];
  233378. viewHolder = new NSViewComponentInternal (view, component);
  233379. }
  233380. ~WindowedGLContext()
  233381. {
  233382. deleteContext();
  233383. viewHolder = 0;
  233384. }
  233385. void deleteContext()
  233386. {
  233387. makeInactive();
  233388. [renderContext clearDrawable];
  233389. [renderContext setView: nil];
  233390. [view setOpenGLContext: nil];
  233391. renderContext = nil;
  233392. }
  233393. bool makeActive() const throw()
  233394. {
  233395. jassert (renderContext != 0);
  233396. if ([renderContext view] != view)
  233397. [renderContext setView: view];
  233398. [view makeActive];
  233399. return isActive();
  233400. }
  233401. bool makeInactive() const throw()
  233402. {
  233403. [view makeInactive];
  233404. return true;
  233405. }
  233406. bool isActive() const throw()
  233407. {
  233408. return [NSOpenGLContext currentContext] == renderContext;
  233409. }
  233410. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233411. void* getRawContext() const throw() { return renderContext; }
  233412. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233413. {
  233414. }
  233415. void swapBuffers()
  233416. {
  233417. [renderContext flushBuffer];
  233418. }
  233419. bool setSwapInterval (const int numFramesPerSwap)
  233420. {
  233421. [renderContext setValues: (const GLint*) &numFramesPerSwap
  233422. forParameter: NSOpenGLCPSwapInterval];
  233423. return true;
  233424. }
  233425. int getSwapInterval() const
  233426. {
  233427. GLint numFrames = 0;
  233428. [renderContext getValues: &numFrames
  233429. forParameter: NSOpenGLCPSwapInterval];
  233430. return numFrames;
  233431. }
  233432. void repaint()
  233433. {
  233434. // we need to invalidate the juce view that holds this gl view, to make it
  233435. // cause a repaint callback
  233436. NSView* v = (NSView*) viewHolder->view;
  233437. NSRect r = [v frame];
  233438. // bit of a bodge here.. if we only invalidate the area of the gl component,
  233439. // it's completely covered by the NSOpenGLView, so the OS throws away the
  233440. // repaint message, thus never causing our paint() callback, and never repainting
  233441. // the comp. So invalidating just a little bit around the edge helps..
  233442. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  233443. }
  233444. void* getNativeWindowHandle() const { return viewHolder->view; }
  233445. juce_UseDebuggingNewOperator
  233446. NSOpenGLContext* renderContext;
  233447. ThreadSafeNSOpenGLView* view;
  233448. private:
  233449. OpenGLPixelFormat pixelFormat;
  233450. ScopedPointer <NSViewComponentInternal> viewHolder;
  233451. WindowedGLContext (const WindowedGLContext&);
  233452. WindowedGLContext& operator= (const WindowedGLContext&);
  233453. };
  233454. OpenGLContext* OpenGLComponent::createContext()
  233455. {
  233456. ScopedPointer<WindowedGLContext> c (new WindowedGLContext (this, preferredPixelFormat,
  233457. contextToShareListsWith != 0 ? (NSOpenGLContext*) contextToShareListsWith->getRawContext() : 0));
  233458. return (c->renderContext != 0) ? c.release() : 0;
  233459. }
  233460. void* OpenGLComponent::getNativeWindowHandle() const
  233461. {
  233462. return context != 0 ? static_cast<WindowedGLContext*> (static_cast<OpenGLContext*> (context))->getNativeWindowHandle()
  233463. : 0;
  233464. }
  233465. void juce_glViewport (const int w, const int h)
  233466. {
  233467. glViewport (0, 0, w, h);
  233468. }
  233469. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233470. OwnedArray <OpenGLPixelFormat>& results)
  233471. {
  233472. /* GLint attribs [64];
  233473. int n = 0;
  233474. attribs[n++] = AGL_RGBA;
  233475. attribs[n++] = AGL_DOUBLEBUFFER;
  233476. attribs[n++] = AGL_ACCELERATED;
  233477. attribs[n++] = AGL_NO_RECOVERY;
  233478. attribs[n++] = AGL_NONE;
  233479. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  233480. while (p != 0)
  233481. {
  233482. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  233483. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  233484. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  233485. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  233486. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  233487. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  233488. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  233489. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  233490. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  233491. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  233492. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  233493. results.add (pf);
  233494. p = aglNextPixelFormat (p);
  233495. }*/
  233496. //jassertfalse // can't see how you do this in cocoa!
  233497. }
  233498. #else
  233499. END_JUCE_NAMESPACE
  233500. @interface JuceGLView : UIView
  233501. {
  233502. }
  233503. + (Class) layerClass;
  233504. @end
  233505. @implementation JuceGLView
  233506. + (Class) layerClass
  233507. {
  233508. return [CAEAGLLayer class];
  233509. }
  233510. @end
  233511. BEGIN_JUCE_NAMESPACE
  233512. class GLESContext : public OpenGLContext
  233513. {
  233514. public:
  233515. GLESContext (UIViewComponentPeer* peer,
  233516. Component* const component_,
  233517. const OpenGLPixelFormat& pixelFormat_,
  233518. const GLESContext* const sharedContext,
  233519. NSUInteger apiType)
  233520. : component (component_), pixelFormat (pixelFormat_), glLayer (0), context (0),
  233521. useDepthBuffer (pixelFormat_.depthBufferBits > 0), frameBufferHandle (0), colorBufferHandle (0),
  233522. depthBufferHandle (0), lastWidth (0), lastHeight (0)
  233523. {
  233524. view = [[JuceGLView alloc] initWithFrame: CGRectMake (0, 0, 64, 64)];
  233525. view.opaque = YES;
  233526. view.hidden = NO;
  233527. view.backgroundColor = [UIColor blackColor];
  233528. view.userInteractionEnabled = NO;
  233529. glLayer = (CAEAGLLayer*) [view layer];
  233530. [peer->view addSubview: view];
  233531. if (sharedContext != 0)
  233532. context = [[EAGLContext alloc] initWithAPI: apiType
  233533. sharegroup: [sharedContext->context sharegroup]];
  233534. else
  233535. context = [[EAGLContext alloc] initWithAPI: apiType];
  233536. createGLBuffers();
  233537. }
  233538. ~GLESContext()
  233539. {
  233540. deleteContext();
  233541. [view removeFromSuperview];
  233542. [view release];
  233543. freeGLBuffers();
  233544. }
  233545. void deleteContext()
  233546. {
  233547. makeInactive();
  233548. [context release];
  233549. context = nil;
  233550. }
  233551. bool makeActive() const throw()
  233552. {
  233553. jassert (context != 0);
  233554. [EAGLContext setCurrentContext: context];
  233555. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233556. return true;
  233557. }
  233558. void swapBuffers()
  233559. {
  233560. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233561. [context presentRenderbuffer: GL_RENDERBUFFER_OES];
  233562. }
  233563. bool makeInactive() const throw()
  233564. {
  233565. return [EAGLContext setCurrentContext: nil];
  233566. }
  233567. bool isActive() const throw()
  233568. {
  233569. return [EAGLContext currentContext] == context;
  233570. }
  233571. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  233572. void* getRawContext() const throw() { return glLayer; }
  233573. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  233574. {
  233575. view.frame = CGRectMake ((CGFloat) x, (CGFloat) y, (CGFloat) w, (CGFloat) h);
  233576. if (lastWidth != w || lastHeight != h)
  233577. {
  233578. lastWidth = w;
  233579. lastHeight = h;
  233580. freeGLBuffers();
  233581. createGLBuffers();
  233582. }
  233583. }
  233584. bool setSwapInterval (const int numFramesPerSwap)
  233585. {
  233586. numFrames = numFramesPerSwap;
  233587. return true;
  233588. }
  233589. int getSwapInterval() const
  233590. {
  233591. return numFrames;
  233592. }
  233593. void repaint()
  233594. {
  233595. }
  233596. void createGLBuffers()
  233597. {
  233598. makeActive();
  233599. glGenFramebuffersOES (1, &frameBufferHandle);
  233600. glGenRenderbuffersOES (1, &colorBufferHandle);
  233601. glGenRenderbuffersOES (1, &depthBufferHandle);
  233602. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233603. [context renderbufferStorage: GL_RENDERBUFFER_OES fromDrawable: glLayer];
  233604. GLint width, height;
  233605. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_WIDTH_OES, &width);
  233606. glGetRenderbufferParameterivOES (GL_RENDERBUFFER_OES, GL_RENDERBUFFER_HEIGHT_OES, &height);
  233607. if (useDepthBuffer)
  233608. {
  233609. glBindRenderbufferOES (GL_RENDERBUFFER_OES, depthBufferHandle);
  233610. glRenderbufferStorageOES (GL_RENDERBUFFER_OES, GL_DEPTH_COMPONENT16_OES, width, height);
  233611. }
  233612. glBindRenderbufferOES (GL_RENDERBUFFER_OES, colorBufferHandle);
  233613. glBindFramebufferOES (GL_FRAMEBUFFER_OES, frameBufferHandle);
  233614. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_COLOR_ATTACHMENT0_OES, GL_RENDERBUFFER_OES, colorBufferHandle);
  233615. if (useDepthBuffer)
  233616. glFramebufferRenderbufferOES (GL_FRAMEBUFFER_OES, GL_DEPTH_ATTACHMENT_OES, GL_RENDERBUFFER_OES, depthBufferHandle);
  233617. jassert (glCheckFramebufferStatusOES (GL_FRAMEBUFFER_OES) == GL_FRAMEBUFFER_COMPLETE_OES);
  233618. }
  233619. void freeGLBuffers()
  233620. {
  233621. if (frameBufferHandle != 0)
  233622. {
  233623. glDeleteFramebuffersOES (1, &frameBufferHandle);
  233624. frameBufferHandle = 0;
  233625. }
  233626. if (colorBufferHandle != 0)
  233627. {
  233628. glDeleteRenderbuffersOES (1, &colorBufferHandle);
  233629. colorBufferHandle = 0;
  233630. }
  233631. if (depthBufferHandle != 0)
  233632. {
  233633. glDeleteRenderbuffersOES (1, &depthBufferHandle);
  233634. depthBufferHandle = 0;
  233635. }
  233636. }
  233637. juce_UseDebuggingNewOperator
  233638. private:
  233639. Component::SafePointer<Component> component;
  233640. OpenGLPixelFormat pixelFormat;
  233641. JuceGLView* view;
  233642. CAEAGLLayer* glLayer;
  233643. EAGLContext* context;
  233644. bool useDepthBuffer;
  233645. GLuint frameBufferHandle, colorBufferHandle, depthBufferHandle;
  233646. int numFrames;
  233647. int lastWidth, lastHeight;
  233648. GLESContext (const GLESContext&);
  233649. GLESContext& operator= (const GLESContext&);
  233650. };
  233651. OpenGLContext* OpenGLComponent::createContext()
  233652. {
  233653. ScopedAutoReleasePool pool;
  233654. UIViewComponentPeer* peer = dynamic_cast <UIViewComponentPeer*> (getPeer());
  233655. if (peer != 0)
  233656. return new GLESContext (peer, this, preferredPixelFormat,
  233657. dynamic_cast <const GLESContext*> (contextToShareListsWith),
  233658. type == openGLES2 ? kEAGLRenderingAPIOpenGLES2 : kEAGLRenderingAPIOpenGLES1);
  233659. return 0;
  233660. }
  233661. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  233662. OwnedArray <OpenGLPixelFormat>& /*results*/)
  233663. {
  233664. }
  233665. void juce_glViewport (const int w, const int h)
  233666. {
  233667. glViewport (0, 0, w, h);
  233668. }
  233669. #endif
  233670. #endif
  233671. /*** End of inlined file: juce_mac_OpenGLComponent.mm ***/
  233672. /*** Start of inlined file: juce_mac_MainMenu.mm ***/
  233673. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  233674. // compiled on its own).
  233675. #if JUCE_INCLUDED_FILE
  233676. class JuceMainMenuHandler;
  233677. END_JUCE_NAMESPACE
  233678. using namespace JUCE_NAMESPACE;
  233679. #define JuceMenuCallback MakeObjCClassName(JuceMenuCallback)
  233680. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  233681. @interface JuceMenuCallback : NSObject <NSMenuDelegate>
  233682. #else
  233683. @interface JuceMenuCallback : NSObject
  233684. #endif
  233685. {
  233686. JuceMainMenuHandler* owner;
  233687. }
  233688. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  233689. - (void) dealloc;
  233690. - (void) menuItemInvoked: (id) menu;
  233691. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233692. @end
  233693. BEGIN_JUCE_NAMESPACE
  233694. class JuceMainMenuHandler : private MenuBarModel::Listener,
  233695. private DeletedAtShutdown
  233696. {
  233697. public:
  233698. static JuceMainMenuHandler* instance;
  233699. JuceMainMenuHandler()
  233700. : currentModel (0),
  233701. lastUpdateTime (0)
  233702. {
  233703. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  233704. }
  233705. ~JuceMainMenuHandler()
  233706. {
  233707. setMenu (0);
  233708. jassert (instance == this);
  233709. instance = 0;
  233710. [callback release];
  233711. }
  233712. void setMenu (MenuBarModel* const newMenuBarModel)
  233713. {
  233714. if (currentModel != newMenuBarModel)
  233715. {
  233716. if (currentModel != 0)
  233717. currentModel->removeListener (this);
  233718. currentModel = newMenuBarModel;
  233719. if (currentModel != 0)
  233720. currentModel->addListener (this);
  233721. menuBarItemsChanged (0);
  233722. }
  233723. }
  233724. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  233725. const String& name, const int menuId, const int tag)
  233726. {
  233727. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  233728. action: nil
  233729. keyEquivalent: @""];
  233730. [item setTag: tag];
  233731. NSMenu* sub = createMenu (child, name, menuId, tag);
  233732. [parent setSubmenu: sub forItem: item];
  233733. [sub setAutoenablesItems: false];
  233734. [sub release];
  233735. }
  233736. void updateSubMenu (NSMenuItem* parentItem, const PopupMenu& menuToCopy,
  233737. const String& name, const int menuId, const int tag)
  233738. {
  233739. [parentItem setTag: tag];
  233740. NSMenu* menu = [parentItem submenu];
  233741. [menu setTitle: juceStringToNS (name)];
  233742. while ([menu numberOfItems] > 0)
  233743. [menu removeItemAtIndex: 0];
  233744. PopupMenu::MenuItemIterator iter (menuToCopy);
  233745. while (iter.next())
  233746. addMenuItem (iter, menu, menuId, tag);
  233747. [menu setAutoenablesItems: false];
  233748. [menu update];
  233749. }
  233750. void menuBarItemsChanged (MenuBarModel*)
  233751. {
  233752. lastUpdateTime = Time::getMillisecondCounter();
  233753. StringArray menuNames;
  233754. if (currentModel != 0)
  233755. menuNames = currentModel->getMenuBarNames();
  233756. NSMenu* menuBar = [NSApp mainMenu];
  233757. while ([menuBar numberOfItems] > 1 + menuNames.size())
  233758. [menuBar removeItemAtIndex: [menuBar numberOfItems] - 1];
  233759. int menuId = 1;
  233760. for (int i = 0; i < menuNames.size(); ++i)
  233761. {
  233762. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  233763. if (i >= [menuBar numberOfItems] - 1)
  233764. addSubMenu (menuBar, menu, menuNames[i], menuId, i);
  233765. else
  233766. updateSubMenu ([menuBar itemAtIndex: 1 + i], menu, menuNames[i], menuId, i);
  233767. }
  233768. }
  233769. static void flashMenuBar (NSMenu* menu)
  233770. {
  233771. if ([[menu title] isEqualToString: @"Apple"])
  233772. return;
  233773. [menu retain];
  233774. const unichar f35Key = NSF35FunctionKey;
  233775. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  233776. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  233777. action: nil
  233778. keyEquivalent: f35String];
  233779. [item setTarget: nil];
  233780. [menu insertItem: item atIndex: [menu numberOfItems]];
  233781. [item release];
  233782. if ([menu indexOfItem: item] >= 0)
  233783. {
  233784. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  233785. location: NSZeroPoint
  233786. modifierFlags: NSCommandKeyMask
  233787. timestamp: 0
  233788. windowNumber: 0
  233789. context: [NSGraphicsContext currentContext]
  233790. characters: f35String
  233791. charactersIgnoringModifiers: f35String
  233792. isARepeat: NO
  233793. keyCode: 0];
  233794. [menu performKeyEquivalent: f35Event];
  233795. if ([menu indexOfItem: item] >= 0)
  233796. [menu removeItem: item]; // (this throws if the item isn't actually in the menu)
  233797. }
  233798. [menu release];
  233799. }
  233800. static NSMenuItem* findMenuItem (NSMenu* const menu, const ApplicationCommandTarget::InvocationInfo& info)
  233801. {
  233802. for (NSInteger i = [menu numberOfItems]; --i >= 0;)
  233803. {
  233804. NSMenuItem* m = [menu itemAtIndex: i];
  233805. if ([m tag] == info.commandID)
  233806. return m;
  233807. if ([m submenu] != 0)
  233808. {
  233809. NSMenuItem* found = findMenuItem ([m submenu], info);
  233810. if (found != 0)
  233811. return found;
  233812. }
  233813. }
  233814. return 0;
  233815. }
  233816. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  233817. {
  233818. NSMenuItem* item = findMenuItem ([NSApp mainMenu], info);
  233819. if (item != 0)
  233820. flashMenuBar ([item menu]);
  233821. }
  233822. void updateMenus()
  233823. {
  233824. if (Time::getMillisecondCounter() > lastUpdateTime + 500)
  233825. menuBarItemsChanged (0);
  233826. }
  233827. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  233828. {
  233829. if (currentModel != 0)
  233830. {
  233831. if (commandManager != 0)
  233832. {
  233833. ApplicationCommandTarget::InvocationInfo info (commandId);
  233834. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  233835. commandManager->invoke (info, true);
  233836. }
  233837. currentModel->menuItemSelected (commandId, topLevelIndex);
  233838. }
  233839. }
  233840. MenuBarModel* currentModel;
  233841. uint32 lastUpdateTime;
  233842. void addMenuItem (PopupMenu::MenuItemIterator& iter, NSMenu* menuToAddTo,
  233843. const int topLevelMenuId, const int topLevelIndex)
  233844. {
  233845. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf ("<end>", false, true));
  233846. if (text == 0)
  233847. text = @"";
  233848. if (iter.isSeparator)
  233849. {
  233850. [menuToAddTo addItem: [NSMenuItem separatorItem]];
  233851. }
  233852. else if (iter.isSectionHeader)
  233853. {
  233854. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233855. action: nil
  233856. keyEquivalent: @""];
  233857. [item setEnabled: false];
  233858. }
  233859. else if (iter.subMenu != 0)
  233860. {
  233861. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233862. action: nil
  233863. keyEquivalent: @""];
  233864. [item setTag: iter.itemId];
  233865. [item setEnabled: iter.isEnabled];
  233866. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, topLevelMenuId, topLevelIndex);
  233867. [sub setDelegate: nil];
  233868. [menuToAddTo setSubmenu: sub forItem: item];
  233869. [sub release];
  233870. }
  233871. else
  233872. {
  233873. NSMenuItem* item = [menuToAddTo addItemWithTitle: text
  233874. action: @selector (menuItemInvoked:)
  233875. keyEquivalent: @""];
  233876. [item setTag: iter.itemId];
  233877. [item setEnabled: iter.isEnabled];
  233878. [item setState: iter.isTicked ? NSOnState : NSOffState];
  233879. [item setTarget: (id) callback];
  233880. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  233881. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  233882. [item setRepresentedObject: info];
  233883. if (iter.commandManager != 0)
  233884. {
  233885. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  233886. ->getKeyPressesAssignedToCommand (iter.itemId));
  233887. if (keyPresses.size() > 0)
  233888. {
  233889. const KeyPress& kp = keyPresses.getReference(0);
  233890. if (kp.getKeyCode() != KeyPress::backspaceKey
  233891. && kp.getKeyCode() != KeyPress::deleteKey) // (adding these is annoying because it flashes the menu bar
  233892. // every time you press the key while editing text)
  233893. {
  233894. juce_wchar key = kp.getTextCharacter();
  233895. if (kp.getKeyCode() == KeyPress::backspaceKey)
  233896. key = NSBackspaceCharacter;
  233897. else if (kp.getKeyCode() == KeyPress::deleteKey)
  233898. key = NSDeleteCharacter;
  233899. else if (key == 0)
  233900. key = (juce_wchar) kp.getKeyCode();
  233901. unsigned int mods = 0;
  233902. if (kp.getModifiers().isShiftDown())
  233903. mods |= NSShiftKeyMask;
  233904. if (kp.getModifiers().isCtrlDown())
  233905. mods |= NSControlKeyMask;
  233906. if (kp.getModifiers().isAltDown())
  233907. mods |= NSAlternateKeyMask;
  233908. if (kp.getModifiers().isCommandDown())
  233909. mods |= NSCommandKeyMask;
  233910. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  233911. [item setKeyEquivalentModifierMask: mods];
  233912. }
  233913. }
  233914. }
  233915. }
  233916. }
  233917. JuceMenuCallback* callback;
  233918. private:
  233919. NSMenu* createMenu (const PopupMenu menu,
  233920. const String& menuName,
  233921. const int topLevelMenuId,
  233922. const int topLevelIndex)
  233923. {
  233924. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  233925. [m setAutoenablesItems: false];
  233926. [m setDelegate: callback];
  233927. PopupMenu::MenuItemIterator iter (menu);
  233928. while (iter.next())
  233929. addMenuItem (iter, m, topLevelMenuId, topLevelIndex);
  233930. [m update];
  233931. return m;
  233932. }
  233933. };
  233934. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  233935. END_JUCE_NAMESPACE
  233936. @implementation JuceMenuCallback
  233937. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  233938. {
  233939. [super init];
  233940. owner = owner_;
  233941. return self;
  233942. }
  233943. - (void) dealloc
  233944. {
  233945. [super dealloc];
  233946. }
  233947. - (void) menuItemInvoked: (id) menu
  233948. {
  233949. NSMenuItem* item = (NSMenuItem*) menu;
  233950. if ([[item representedObject] isKindOfClass: [NSArray class]])
  233951. {
  233952. // 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
  233953. // our own components, which may have wanted to intercept it. So, rather than dispatching directly, we'll feed it back
  233954. // into the focused component and let it trigger the menu item indirectly.
  233955. NSEvent* e = [NSApp currentEvent];
  233956. if ([e type] == NSKeyDown || [e type] == NSKeyUp)
  233957. {
  233958. if (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent() != 0)
  233959. {
  233960. JUCE_NAMESPACE::NSViewComponentPeer* peer = dynamic_cast <JUCE_NAMESPACE::NSViewComponentPeer*> (JUCE_NAMESPACE::Component::getCurrentlyFocusedComponent()->getPeer());
  233961. if (peer != 0)
  233962. {
  233963. if ([e type] == NSKeyDown)
  233964. peer->redirectKeyDown (e);
  233965. else
  233966. peer->redirectKeyUp (e);
  233967. return;
  233968. }
  233969. }
  233970. }
  233971. NSArray* info = (NSArray*) [item representedObject];
  233972. owner->invoke ((int) [item tag],
  233973. (ApplicationCommandManager*) (pointer_sized_int)
  233974. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  233975. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  233976. }
  233977. }
  233978. - (void) menuNeedsUpdate: (NSMenu*) menu;
  233979. {
  233980. (void) menu;
  233981. if (JuceMainMenuHandler::instance != 0)
  233982. JuceMainMenuHandler::instance->updateMenus();
  233983. }
  233984. @end
  233985. BEGIN_JUCE_NAMESPACE
  233986. namespace MainMenuHelpers
  233987. {
  233988. NSMenu* createStandardAppMenu (NSMenu* menu, const String& appName, const PopupMenu* extraItems)
  233989. {
  233990. if (extraItems != 0 && JuceMainMenuHandler::instance != 0 && extraItems->getNumItems() > 0)
  233991. {
  233992. PopupMenu::MenuItemIterator iter (*extraItems);
  233993. while (iter.next())
  233994. JuceMainMenuHandler::instance->addMenuItem (iter, menu, 0, -1);
  233995. [menu addItem: [NSMenuItem separatorItem]];
  233996. }
  233997. NSMenuItem* item;
  233998. // Services...
  233999. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Services", nil)
  234000. action: nil keyEquivalent: @""];
  234001. [menu addItem: item];
  234002. [item release];
  234003. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  234004. [menu setSubmenu: servicesMenu forItem: item];
  234005. [NSApp setServicesMenu: servicesMenu];
  234006. [servicesMenu release];
  234007. [menu addItem: [NSMenuItem separatorItem]];
  234008. // Hide + Show stuff...
  234009. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Hide " + appName)
  234010. action: @selector (hide:) keyEquivalent: @"h"];
  234011. [item setTarget: NSApp];
  234012. [menu addItem: item];
  234013. [item release];
  234014. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Hide Others", nil)
  234015. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  234016. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  234017. [item setTarget: NSApp];
  234018. [menu addItem: item];
  234019. [item release];
  234020. item = [[NSMenuItem alloc] initWithTitle: NSLocalizedString (@"Show All", nil)
  234021. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  234022. [item setTarget: NSApp];
  234023. [menu addItem: item];
  234024. [item release];
  234025. [menu addItem: [NSMenuItem separatorItem]];
  234026. // Quit item....
  234027. item = [[NSMenuItem alloc] initWithTitle: juceStringToNS ("Quit " + appName)
  234028. action: @selector (terminate:) keyEquivalent: @"q"];
  234029. [item setTarget: NSApp];
  234030. [menu addItem: item];
  234031. [item release];
  234032. return menu;
  234033. }
  234034. // Since our app has no NIB, this initialises a standard app menu...
  234035. void rebuildMainMenu (const PopupMenu* extraItems)
  234036. {
  234037. // this can't be used in a plugin!
  234038. jassert (JUCEApplication::isStandaloneApp());
  234039. if (JUCEApplication::getInstance() != 0)
  234040. {
  234041. const ScopedAutoReleasePool pool;
  234042. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  234043. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  234044. NSMenu* appMenu = [[NSMenu alloc] initWithTitle: @"Apple"];
  234045. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  234046. [mainMenu setSubmenu: appMenu forItem: item];
  234047. [NSApp setMainMenu: mainMenu];
  234048. MainMenuHelpers::createStandardAppMenu (appMenu, JUCEApplication::getInstance()->getApplicationName(), extraItems);
  234049. [appMenu release];
  234050. [mainMenu release];
  234051. }
  234052. }
  234053. }
  234054. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel,
  234055. const PopupMenu* extraAppleMenuItems)
  234056. {
  234057. if (getMacMainMenu() != newMenuBarModel)
  234058. {
  234059. const ScopedAutoReleasePool pool;
  234060. if (newMenuBarModel == 0)
  234061. {
  234062. delete JuceMainMenuHandler::instance;
  234063. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  234064. jassert (extraAppleMenuItems == 0); // you can't specify some extra items without also supplying a model
  234065. extraAppleMenuItems = 0;
  234066. }
  234067. else
  234068. {
  234069. if (JuceMainMenuHandler::instance == 0)
  234070. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  234071. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  234072. }
  234073. }
  234074. MainMenuHelpers::rebuildMainMenu (extraAppleMenuItems);
  234075. if (newMenuBarModel != 0)
  234076. newMenuBarModel->menuItemsChanged();
  234077. }
  234078. MenuBarModel* MenuBarModel::getMacMainMenu()
  234079. {
  234080. return JuceMainMenuHandler::instance != 0
  234081. ? JuceMainMenuHandler::instance->currentModel : 0;
  234082. }
  234083. void juce_initialiseMacMainMenu()
  234084. {
  234085. if (JuceMainMenuHandler::instance == 0)
  234086. MainMenuHelpers::rebuildMainMenu (0);
  234087. }
  234088. #endif
  234089. /*** End of inlined file: juce_mac_MainMenu.mm ***/
  234090. /*** Start of inlined file: juce_mac_FileChooser.mm ***/
  234091. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234092. // compiled on its own).
  234093. #if JUCE_INCLUDED_FILE
  234094. #if JUCE_MAC
  234095. END_JUCE_NAMESPACE
  234096. using namespace JUCE_NAMESPACE;
  234097. #define JuceFileChooserDelegate MakeObjCClassName(JuceFileChooserDelegate)
  234098. #if defined (MAC_OS_X_VERSION_10_6) && MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
  234099. @interface JuceFileChooserDelegate : NSObject <NSOpenSavePanelDelegate>
  234100. #else
  234101. @interface JuceFileChooserDelegate : NSObject
  234102. #endif
  234103. {
  234104. StringArray* filters;
  234105. }
  234106. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  234107. - (void) dealloc;
  234108. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  234109. @end
  234110. @implementation JuceFileChooserDelegate
  234111. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  234112. {
  234113. [super init];
  234114. filters = filters_;
  234115. return self;
  234116. }
  234117. - (void) dealloc
  234118. {
  234119. delete filters;
  234120. [super dealloc];
  234121. }
  234122. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  234123. {
  234124. (void) sender;
  234125. const File f (nsStringToJuce (filename));
  234126. for (int i = filters->size(); --i >= 0;)
  234127. if (f.getFileName().matchesWildcard ((*filters)[i], true))
  234128. return true;
  234129. return f.isDirectory();
  234130. }
  234131. @end
  234132. BEGIN_JUCE_NAMESPACE
  234133. void FileChooser::showPlatformDialog (Array<File>& results,
  234134. const String& title,
  234135. const File& currentFileOrDirectory,
  234136. const String& filter,
  234137. bool selectsDirectory,
  234138. bool selectsFiles,
  234139. bool isSaveDialogue,
  234140. bool warnAboutOverwritingExistingFiles,
  234141. bool selectMultipleFiles,
  234142. FilePreviewComponent* extraInfoComponent)
  234143. {
  234144. const ScopedAutoReleasePool pool;
  234145. StringArray* filters = new StringArray();
  234146. filters->addTokens (filter.replaceCharacters (",:", ";;"), ";", String::empty);
  234147. filters->trim();
  234148. filters->removeEmptyStrings();
  234149. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  234150. [delegate autorelease];
  234151. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  234152. : [NSOpenPanel openPanel];
  234153. [panel setTitle: juceStringToNS (title)];
  234154. if (! isSaveDialogue)
  234155. {
  234156. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  234157. [openPanel setCanChooseDirectories: selectsDirectory];
  234158. [openPanel setCanChooseFiles: selectsFiles];
  234159. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  234160. }
  234161. [panel setDelegate: delegate];
  234162. if (isSaveDialogue || selectsDirectory)
  234163. [panel setCanCreateDirectories: YES];
  234164. String directory, filename;
  234165. if (currentFileOrDirectory.isDirectory())
  234166. {
  234167. directory = currentFileOrDirectory.getFullPathName();
  234168. }
  234169. else
  234170. {
  234171. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  234172. filename = currentFileOrDirectory.getFileName();
  234173. }
  234174. if ([panel runModalForDirectory: juceStringToNS (directory)
  234175. file: juceStringToNS (filename)]
  234176. == NSOKButton)
  234177. {
  234178. if (isSaveDialogue)
  234179. {
  234180. results.add (File (nsStringToJuce ([panel filename])));
  234181. }
  234182. else
  234183. {
  234184. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  234185. NSArray* urls = [openPanel filenames];
  234186. for (unsigned int i = 0; i < [urls count]; ++i)
  234187. {
  234188. NSString* f = [urls objectAtIndex: i];
  234189. results.add (File (nsStringToJuce (f)));
  234190. }
  234191. }
  234192. }
  234193. [panel setDelegate: nil];
  234194. }
  234195. #else
  234196. void FileChooser::showPlatformDialog (Array<File>& results,
  234197. const String& title,
  234198. const File& currentFileOrDirectory,
  234199. const String& filter,
  234200. bool selectsDirectory,
  234201. bool selectsFiles,
  234202. bool isSaveDialogue,
  234203. bool warnAboutOverwritingExistingFiles,
  234204. bool selectMultipleFiles,
  234205. FilePreviewComponent* extraInfoComponent)
  234206. {
  234207. const ScopedAutoReleasePool pool;
  234208. jassertfalse; //xxx to do
  234209. }
  234210. #endif
  234211. #endif
  234212. /*** End of inlined file: juce_mac_FileChooser.mm ***/
  234213. /*** Start of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234214. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234215. // compiled on its own).
  234216. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  234217. END_JUCE_NAMESPACE
  234218. #define NonInterceptingQTMovieView MakeObjCClassName(NonInterceptingQTMovieView)
  234219. @interface NonInterceptingQTMovieView : QTMovieView
  234220. {
  234221. }
  234222. - (id) initWithFrame: (NSRect) frame;
  234223. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent;
  234224. - (NSView*) hitTest: (NSPoint) p;
  234225. @end
  234226. @implementation NonInterceptingQTMovieView
  234227. - (id) initWithFrame: (NSRect) frame
  234228. {
  234229. self = [super initWithFrame: frame];
  234230. [self setNextResponder: [self superview]];
  234231. return self;
  234232. }
  234233. - (void) dealloc
  234234. {
  234235. [super dealloc];
  234236. }
  234237. - (NSView*) hitTest: (NSPoint) point
  234238. {
  234239. return [self isControllerVisible] ? [super hitTest: point] : nil;
  234240. }
  234241. - (BOOL) acceptsFirstMouse: (NSEvent*) theEvent
  234242. {
  234243. return YES;
  234244. }
  234245. @end
  234246. BEGIN_JUCE_NAMESPACE
  234247. #define theMovie (static_cast <QTMovie*> (movie))
  234248. QuickTimeMovieComponent::QuickTimeMovieComponent()
  234249. : movie (0)
  234250. {
  234251. setOpaque (true);
  234252. setVisible (true);
  234253. QTMovieView* view = [[NonInterceptingQTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  234254. setView (view);
  234255. [view release];
  234256. }
  234257. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  234258. {
  234259. closeMovie();
  234260. setView (0);
  234261. }
  234262. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  234263. {
  234264. return true;
  234265. }
  234266. static QTMovie* openMovieFromStream (InputStream* movieStream, File& movieFile)
  234267. {
  234268. // unfortunately, QTMovie objects can only be created on the main thread..
  234269. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234270. QTMovie* movie = 0;
  234271. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  234272. if (fin != 0)
  234273. {
  234274. movieFile = fin->getFile();
  234275. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  234276. error: nil];
  234277. }
  234278. else
  234279. {
  234280. MemoryBlock temp;
  234281. movieStream->readIntoMemoryBlock (temp);
  234282. const char* const suffixesToTry[] = { ".mov", ".mp3", ".avi", ".m4a" };
  234283. for (int i = 0; i < numElementsInArray (suffixesToTry); ++i)
  234284. {
  234285. movie = [QTMovie movieWithDataReference: [QTDataReference dataReferenceWithReferenceToData: [NSData dataWithBytes: temp.getData()
  234286. length: temp.getSize()]
  234287. name: [NSString stringWithUTF8String: suffixesToTry[i]]
  234288. MIMEType: @""]
  234289. error: nil];
  234290. if (movie != 0)
  234291. break;
  234292. }
  234293. }
  234294. return movie;
  234295. }
  234296. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  234297. const bool isControllerVisible_)
  234298. {
  234299. return loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible_);
  234300. }
  234301. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  234302. const bool controllerVisible_)
  234303. {
  234304. closeMovie();
  234305. if (getPeer() == 0)
  234306. {
  234307. // To open a movie, this component must be visible inside a functioning window, so that
  234308. // the QT control can be assigned to the window.
  234309. jassertfalse;
  234310. return false;
  234311. }
  234312. movie = openMovieFromStream (movieStream, movieFile);
  234313. [theMovie retain];
  234314. QTMovieView* view = (QTMovieView*) getView();
  234315. [view setMovie: theMovie];
  234316. [view setControllerVisible: controllerVisible_];
  234317. setLooping (looping);
  234318. return movie != nil;
  234319. }
  234320. bool QuickTimeMovieComponent::loadMovie (const URL& movieURL,
  234321. const bool isControllerVisible_)
  234322. {
  234323. // unfortunately, QTMovie objects can only be created on the main thread..
  234324. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  234325. closeMovie();
  234326. if (getPeer() == 0)
  234327. {
  234328. // To open a movie, this component must be visible inside a functioning window, so that
  234329. // the QT control can be assigned to the window.
  234330. jassertfalse;
  234331. return false;
  234332. }
  234333. NSURL* url = [NSURL URLWithString: juceStringToNS (movieURL.toString (true))];
  234334. NSError* err;
  234335. if ([QTMovie canInitWithURL: url])
  234336. movie = [QTMovie movieWithURL: url error: &err];
  234337. [theMovie retain];
  234338. QTMovieView* view = (QTMovieView*) getView();
  234339. [view setMovie: theMovie];
  234340. [view setControllerVisible: controllerVisible];
  234341. setLooping (looping);
  234342. return movie != nil;
  234343. }
  234344. void QuickTimeMovieComponent::closeMovie()
  234345. {
  234346. stop();
  234347. QTMovieView* view = (QTMovieView*) getView();
  234348. [view setMovie: nil];
  234349. [theMovie release];
  234350. movie = 0;
  234351. movieFile = File::nonexistent;
  234352. }
  234353. bool QuickTimeMovieComponent::isMovieOpen() const
  234354. {
  234355. return movie != nil;
  234356. }
  234357. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  234358. {
  234359. return movieFile;
  234360. }
  234361. void QuickTimeMovieComponent::play()
  234362. {
  234363. [theMovie play];
  234364. }
  234365. void QuickTimeMovieComponent::stop()
  234366. {
  234367. [theMovie stop];
  234368. }
  234369. bool QuickTimeMovieComponent::isPlaying() const
  234370. {
  234371. return movie != 0 && [theMovie rate] != 0;
  234372. }
  234373. void QuickTimeMovieComponent::setPosition (const double seconds)
  234374. {
  234375. if (movie != 0)
  234376. {
  234377. QTTime t;
  234378. t.timeValue = (uint64) (100000.0 * seconds);
  234379. t.timeScale = 100000;
  234380. t.flags = 0;
  234381. [theMovie setCurrentTime: t];
  234382. }
  234383. }
  234384. double QuickTimeMovieComponent::getPosition() const
  234385. {
  234386. if (movie == 0)
  234387. return 0.0;
  234388. QTTime t = [theMovie currentTime];
  234389. return t.timeValue / (double) t.timeScale;
  234390. }
  234391. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  234392. {
  234393. [theMovie setRate: newSpeed];
  234394. }
  234395. double QuickTimeMovieComponent::getMovieDuration() const
  234396. {
  234397. if (movie == 0)
  234398. return 0.0;
  234399. QTTime t = [theMovie duration];
  234400. return t.timeValue / (double) t.timeScale;
  234401. }
  234402. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  234403. {
  234404. looping = shouldLoop;
  234405. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  234406. forKey: QTMovieLoopsAttribute];
  234407. }
  234408. bool QuickTimeMovieComponent::isLooping() const
  234409. {
  234410. return looping;
  234411. }
  234412. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  234413. {
  234414. [theMovie setVolume: newVolume];
  234415. }
  234416. float QuickTimeMovieComponent::getMovieVolume() const
  234417. {
  234418. return movie != 0 ? [theMovie volume] : 0.0f;
  234419. }
  234420. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  234421. {
  234422. width = 0;
  234423. height = 0;
  234424. if (movie != 0)
  234425. {
  234426. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  234427. width = (int) s.width;
  234428. height = (int) s.height;
  234429. }
  234430. }
  234431. void QuickTimeMovieComponent::paint (Graphics& g)
  234432. {
  234433. if (movie == 0)
  234434. g.fillAll (Colours::black);
  234435. }
  234436. bool QuickTimeMovieComponent::isControllerVisible() const
  234437. {
  234438. return controllerVisible;
  234439. }
  234440. void QuickTimeMovieComponent::goToStart()
  234441. {
  234442. setPosition (0.0);
  234443. }
  234444. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle<int>& spaceToFitWithin,
  234445. const RectanglePlacement& placement)
  234446. {
  234447. int normalWidth, normalHeight;
  234448. getMovieNormalSize (normalWidth, normalHeight);
  234449. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  234450. {
  234451. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  234452. placement.applyTo (x, y, w, h,
  234453. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  234454. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  234455. if (w > 0 && h > 0)
  234456. {
  234457. setBounds (roundToInt (x), roundToInt (y),
  234458. roundToInt (w), roundToInt (h));
  234459. }
  234460. }
  234461. else
  234462. {
  234463. setBounds (spaceToFitWithin);
  234464. }
  234465. }
  234466. #if ! (JUCE_MAC && JUCE_64BIT)
  234467. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  234468. {
  234469. if (movieStream == 0)
  234470. return false;
  234471. File file;
  234472. QTMovie* movie = openMovieFromStream (movieStream, file);
  234473. if (movie != nil)
  234474. result = [movie quickTimeMovie];
  234475. return movie != nil;
  234476. }
  234477. #endif
  234478. #endif
  234479. /*** End of inlined file: juce_mac_QuickTimeMovieComponent.mm ***/
  234480. /*** Start of inlined file: juce_mac_AudioCDBurner.mm ***/
  234481. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234482. // compiled on its own).
  234483. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  234484. const int kilobytesPerSecond1x = 176;
  234485. END_JUCE_NAMESPACE
  234486. #define OpenDiskDevice MakeObjCClassName(OpenDiskDevice)
  234487. @interface OpenDiskDevice : NSObject
  234488. {
  234489. @public
  234490. DRDevice* device;
  234491. NSMutableArray* tracks;
  234492. bool underrunProtection;
  234493. }
  234494. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device;
  234495. - (void) dealloc;
  234496. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  234497. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234498. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed;
  234499. @end
  234500. #define AudioTrackProducer MakeObjCClassName(AudioTrackProducer)
  234501. @interface AudioTrackProducer : NSObject
  234502. {
  234503. JUCE_NAMESPACE::AudioSource* source;
  234504. int readPosition, lengthInFrames;
  234505. }
  234506. - (AudioTrackProducer*) init: (int) lengthInFrames;
  234507. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  234508. - (void) dealloc;
  234509. - (void) setupTrackProperties: (DRTrack*) track;
  234510. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  234511. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  234512. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  234513. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  234514. toMedia:(NSDictionary*)mediaInfo;
  234515. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  234516. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  234517. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234518. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234519. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234520. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234521. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234522. ioFlags:(uint32_t*)flags;
  234523. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  234524. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  234525. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  234526. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  234527. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  234528. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  234529. ioFlags:(uint32_t*)flags;
  234530. @end
  234531. @implementation OpenDiskDevice
  234532. - (OpenDiskDevice*) initWithDRDevice: (DRDevice*) device_
  234533. {
  234534. [super init];
  234535. device = device_;
  234536. tracks = [[NSMutableArray alloc] init];
  234537. underrunProtection = true;
  234538. return self;
  234539. }
  234540. - (void) dealloc
  234541. {
  234542. [tracks release];
  234543. [super dealloc];
  234544. }
  234545. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  234546. {
  234547. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  234548. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  234549. [p setupTrackProperties: t];
  234550. [tracks addObject: t];
  234551. [t release];
  234552. [p release];
  234553. }
  234554. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  234555. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting speed: (int) burnSpeed
  234556. {
  234557. DRBurn* burn = [DRBurn burnForDevice: device];
  234558. if (! [device acquireExclusiveAccess])
  234559. {
  234560. *error = "Couldn't open or write to the CD device";
  234561. return;
  234562. }
  234563. [device acquireMediaReservation];
  234564. NSMutableDictionary* d = [[burn properties] mutableCopy];
  234565. [d autorelease];
  234566. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  234567. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  234568. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount) forKey: DRBurnCompletionActionKey];
  234569. if (burnSpeed > 0)
  234570. [d setObject: [NSNumber numberWithFloat: burnSpeed * JUCE_NAMESPACE::kilobytesPerSecond1x] forKey: DRBurnRequestedSpeedKey];
  234571. if (! underrunProtection)
  234572. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnUnderrunProtectionKey];
  234573. [burn setProperties: d];
  234574. [burn writeLayout: tracks];
  234575. for (;;)
  234576. {
  234577. JUCE_NAMESPACE::Thread::sleep (300);
  234578. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  234579. if (listener != 0 && listener->audioCDBurnProgress (progress))
  234580. {
  234581. [burn abort];
  234582. *error = "User cancelled the write operation";
  234583. break;
  234584. }
  234585. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  234586. {
  234587. *error = "Write operation failed";
  234588. break;
  234589. }
  234590. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  234591. {
  234592. break;
  234593. }
  234594. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  234595. objectForKey: DRErrorStatusErrorStringKey];
  234596. if ([err length] > 0)
  234597. {
  234598. *error = JUCE_NAMESPACE::String::fromUTF8 ([err UTF8String]);
  234599. break;
  234600. }
  234601. }
  234602. [device releaseMediaReservation];
  234603. [device releaseExclusiveAccess];
  234604. }
  234605. @end
  234606. @implementation AudioTrackProducer
  234607. - (AudioTrackProducer*) init: (int) lengthInFrames_
  234608. {
  234609. lengthInFrames = lengthInFrames_;
  234610. readPosition = 0;
  234611. return self;
  234612. }
  234613. - (void) setupTrackProperties: (DRTrack*) track
  234614. {
  234615. NSMutableDictionary* p = [[track properties] mutableCopy];
  234616. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  234617. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  234618. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  234619. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  234620. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  234621. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  234622. [track setProperties: p];
  234623. [p release];
  234624. }
  234625. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  234626. {
  234627. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  234628. if (s != nil)
  234629. s->source = source_;
  234630. return s;
  234631. }
  234632. - (void) dealloc
  234633. {
  234634. if (source != 0)
  234635. {
  234636. source->releaseResources();
  234637. delete source;
  234638. }
  234639. [super dealloc];
  234640. }
  234641. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  234642. {
  234643. }
  234644. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  234645. {
  234646. return true;
  234647. }
  234648. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  234649. {
  234650. return lengthInFrames;
  234651. }
  234652. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  234653. toMedia: (NSDictionary*) mediaInfo
  234654. {
  234655. if (source != 0)
  234656. source->prepareToPlay (44100 / 75, 44100);
  234657. readPosition = 0;
  234658. return true;
  234659. }
  234660. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  234661. {
  234662. if (source != 0)
  234663. source->prepareToPlay (44100 / 75, 44100);
  234664. return true;
  234665. }
  234666. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  234667. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234668. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234669. {
  234670. if (source != 0)
  234671. {
  234672. const int numSamples = JUCE_NAMESPACE::jmin ((int) bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  234673. if (numSamples > 0)
  234674. {
  234675. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  234676. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  234677. info.buffer = &tempBuffer;
  234678. info.startSample = 0;
  234679. info.numSamples = numSamples;
  234680. source->getNextAudioBlock (info);
  234681. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Int16,
  234682. JUCE_NAMESPACE::AudioData::LittleEndian,
  234683. JUCE_NAMESPACE::AudioData::Interleaved,
  234684. JUCE_NAMESPACE::AudioData::NonConst> CDSampleFormat;
  234685. typedef JUCE_NAMESPACE::AudioData::Pointer <JUCE_NAMESPACE::AudioData::Float32,
  234686. JUCE_NAMESPACE::AudioData::NativeEndian,
  234687. JUCE_NAMESPACE::AudioData::NonInterleaved,
  234688. JUCE_NAMESPACE::AudioData::Const> SourceSampleFormat;
  234689. CDSampleFormat left (buffer, 2);
  234690. left.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (0)), numSamples);
  234691. CDSampleFormat right (buffer + 2, 2);
  234692. right.convertSamples (SourceSampleFormat (tempBuffer.getSampleData (1)), numSamples);
  234693. readPosition += numSamples;
  234694. }
  234695. return numSamples * 4;
  234696. }
  234697. return 0;
  234698. }
  234699. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  234700. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  234701. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  234702. ioFlags: (uint32_t*) flags
  234703. {
  234704. zeromem (buffer, bufferLength);
  234705. return bufferLength;
  234706. }
  234707. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  234708. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  234709. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  234710. {
  234711. return true;
  234712. }
  234713. @end
  234714. BEGIN_JUCE_NAMESPACE
  234715. class AudioCDBurner::Pimpl : public Timer
  234716. {
  234717. public:
  234718. Pimpl (AudioCDBurner& owner_, const int deviceIndex)
  234719. : device (0), owner (owner_)
  234720. {
  234721. DRDevice* dev = [[DRDevice devices] objectAtIndex: deviceIndex];
  234722. if (dev != 0)
  234723. {
  234724. device = [[OpenDiskDevice alloc] initWithDRDevice: dev];
  234725. lastState = getDiskState();
  234726. startTimer (1000);
  234727. }
  234728. }
  234729. ~Pimpl()
  234730. {
  234731. stopTimer();
  234732. [device release];
  234733. }
  234734. void timerCallback()
  234735. {
  234736. const DiskState state = getDiskState();
  234737. if (state != lastState)
  234738. {
  234739. lastState = state;
  234740. owner.sendChangeMessage (&owner);
  234741. }
  234742. }
  234743. DiskState getDiskState() const
  234744. {
  234745. if ([device->device isValid])
  234746. {
  234747. NSDictionary* status = [device->device status];
  234748. NSString* state = [status objectForKey: DRDeviceMediaStateKey];
  234749. if ([state isEqualTo: DRDeviceMediaStateNone])
  234750. {
  234751. if ([[status objectForKey: DRDeviceIsTrayOpenKey] boolValue])
  234752. return trayOpen;
  234753. return noDisc;
  234754. }
  234755. if ([state isEqualTo: DRDeviceMediaStateMediaPresent])
  234756. {
  234757. if ([[[status objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceMediaBlocksFreeKey] intValue] > 0)
  234758. return writableDiskPresent;
  234759. else
  234760. return readOnlyDiskPresent;
  234761. }
  234762. }
  234763. return unknown;
  234764. }
  234765. bool openTray() { return [device->device isValid] && [device->device ejectMedia]; }
  234766. const Array<int> getAvailableWriteSpeeds() const
  234767. {
  234768. Array<int> results;
  234769. if ([device->device isValid])
  234770. {
  234771. NSArray* speeds = [[[device->device status] objectForKey: DRDeviceMediaInfoKey] objectForKey: DRDeviceBurnSpeedsKey];
  234772. for (unsigned int i = 0; i < [speeds count]; ++i)
  234773. {
  234774. const int kbPerSec = [[speeds objectAtIndex: i] intValue];
  234775. results.add (kbPerSec / kilobytesPerSecond1x);
  234776. }
  234777. }
  234778. return results;
  234779. }
  234780. bool setBufferUnderrunProtection (const bool shouldBeEnabled)
  234781. {
  234782. if ([device->device isValid])
  234783. {
  234784. device->underrunProtection = shouldBeEnabled;
  234785. return shouldBeEnabled && [[[device->device status] objectForKey: DRDeviceCanUnderrunProtectCDKey] boolValue];
  234786. }
  234787. return false;
  234788. }
  234789. int getNumAvailableAudioBlocks() const
  234790. {
  234791. return [[[[device->device status] objectForKey: DRDeviceMediaInfoKey]
  234792. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  234793. }
  234794. OpenDiskDevice* device;
  234795. private:
  234796. DiskState lastState;
  234797. AudioCDBurner& owner;
  234798. };
  234799. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  234800. {
  234801. pimpl = new Pimpl (*this, deviceIndex);
  234802. }
  234803. AudioCDBurner::~AudioCDBurner()
  234804. {
  234805. }
  234806. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  234807. {
  234808. ScopedPointer <AudioCDBurner> b (new AudioCDBurner (deviceIndex));
  234809. if (b->pimpl->device == 0)
  234810. b = 0;
  234811. return b.release();
  234812. }
  234813. namespace
  234814. {
  234815. NSArray* findDiskBurnerDevices()
  234816. {
  234817. NSMutableArray* results = [NSMutableArray array];
  234818. NSArray* devs = [DRDevice devices];
  234819. for (int i = 0; i < [devs count]; ++i)
  234820. {
  234821. NSDictionary* dic = [[devs objectAtIndex: i] info];
  234822. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  234823. if (name != nil)
  234824. [results addObject: name];
  234825. }
  234826. return results;
  234827. }
  234828. }
  234829. const StringArray AudioCDBurner::findAvailableDevices()
  234830. {
  234831. NSArray* names = findDiskBurnerDevices();
  234832. StringArray s;
  234833. for (unsigned int i = 0; i < [names count]; ++i)
  234834. s.add (String::fromUTF8 ([[names objectAtIndex: i] UTF8String]));
  234835. return s;
  234836. }
  234837. AudioCDBurner::DiskState AudioCDBurner::getDiskState() const
  234838. {
  234839. return pimpl->getDiskState();
  234840. }
  234841. bool AudioCDBurner::isDiskPresent() const
  234842. {
  234843. return getDiskState() == writableDiskPresent;
  234844. }
  234845. bool AudioCDBurner::openTray()
  234846. {
  234847. return pimpl->openTray();
  234848. }
  234849. AudioCDBurner::DiskState AudioCDBurner::waitUntilStateChange (int timeOutMilliseconds)
  234850. {
  234851. const int64 timeout = Time::currentTimeMillis() + timeOutMilliseconds;
  234852. DiskState oldState = getDiskState();
  234853. DiskState newState = oldState;
  234854. while (newState == oldState && Time::currentTimeMillis() < timeout)
  234855. {
  234856. newState = getDiskState();
  234857. Thread::sleep (100);
  234858. }
  234859. return newState;
  234860. }
  234861. const Array<int> AudioCDBurner::getAvailableWriteSpeeds() const
  234862. {
  234863. return pimpl->getAvailableWriteSpeeds();
  234864. }
  234865. bool AudioCDBurner::setBufferUnderrunProtection (const bool shouldBeEnabled)
  234866. {
  234867. return pimpl->setBufferUnderrunProtection (shouldBeEnabled);
  234868. }
  234869. int AudioCDBurner::getNumAvailableAudioBlocks() const
  234870. {
  234871. return pimpl->getNumAvailableAudioBlocks();
  234872. }
  234873. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  234874. {
  234875. if ([pimpl->device->device isValid])
  234876. {
  234877. [pimpl->device addSourceTrack: source numSamples: numSamps];
  234878. return true;
  234879. }
  234880. return false;
  234881. }
  234882. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  234883. bool ejectDiscAfterwards,
  234884. bool performFakeBurnForTesting,
  234885. int writeSpeed)
  234886. {
  234887. String error ("Couldn't open or write to the CD device");
  234888. if ([pimpl->device->device isValid])
  234889. {
  234890. error = String::empty;
  234891. [pimpl->device burn: listener
  234892. errorString: &error
  234893. ejectAfterwards: ejectDiscAfterwards
  234894. isFake: performFakeBurnForTesting
  234895. speed: writeSpeed];
  234896. }
  234897. return error;
  234898. }
  234899. #endif
  234900. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234901. void AudioCDReader::ejectDisk()
  234902. {
  234903. const ScopedAutoReleasePool p;
  234904. [[NSWorkspace sharedWorkspace] unmountAndEjectDeviceAtPath: juceStringToNS (volumeDir.getFullPathName())];
  234905. }
  234906. #endif
  234907. /*** End of inlined file: juce_mac_AudioCDBurner.mm ***/
  234908. /*** Start of inlined file: juce_mac_AudioCDReader.mm ***/
  234909. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  234910. // compiled on its own).
  234911. #if JUCE_INCLUDED_FILE && JUCE_USE_CDREADER
  234912. namespace CDReaderHelpers
  234913. {
  234914. inline const XmlElement* getElementForKey (const XmlElement& xml, const String& key)
  234915. {
  234916. forEachXmlChildElementWithTagName (xml, child, "key")
  234917. if (child->getAllSubText().trim() == key)
  234918. return child->getNextElement();
  234919. return 0;
  234920. }
  234921. static int getIntValueForKey (const XmlElement& xml, const String& key, int defaultValue = -1)
  234922. {
  234923. const XmlElement* const block = getElementForKey (xml, key);
  234924. return block != 0 ? block->getAllSubText().trim().getIntValue() : defaultValue;
  234925. }
  234926. // Get the track offsets for a CD given an XmlElement representing its TOC.Plist.
  234927. // Returns NULL on success, otherwise a const char* representing an error.
  234928. static const char* getTrackOffsets (XmlDocument& xmlDocument, Array<int>& offsets)
  234929. {
  234930. const ScopedPointer<XmlElement> xml (xmlDocument.getDocumentElement());
  234931. if (xml == 0)
  234932. return "Couldn't parse XML in file";
  234933. const XmlElement* const dict = xml->getChildByName ("dict");
  234934. if (dict == 0)
  234935. return "Couldn't get top level dictionary";
  234936. const XmlElement* const sessions = getElementForKey (*dict, "Sessions");
  234937. if (sessions == 0)
  234938. return "Couldn't find sessions key";
  234939. const XmlElement* const session = sessions->getFirstChildElement();
  234940. if (session == 0)
  234941. return "Couldn't find first session";
  234942. const int leadOut = getIntValueForKey (*session, "Leadout Block");
  234943. if (leadOut < 0)
  234944. return "Couldn't find Leadout Block";
  234945. const XmlElement* const trackArray = getElementForKey (*session, "Track Array");
  234946. if (trackArray == 0)
  234947. return "Couldn't find Track Array";
  234948. forEachXmlChildElement (*trackArray, track)
  234949. {
  234950. const int trackValue = getIntValueForKey (*track, "Start Block");
  234951. if (trackValue < 0)
  234952. return "Couldn't find Start Block in the track";
  234953. offsets.add (trackValue * AudioCDReader::samplesPerFrame - 88200);
  234954. }
  234955. offsets.add (leadOut * AudioCDReader::samplesPerFrame - 88200);
  234956. return 0;
  234957. }
  234958. static void findDevices (Array<File>& cds)
  234959. {
  234960. File volumes ("/Volumes");
  234961. volumes.findChildFiles (cds, File::findDirectories, false);
  234962. for (int i = cds.size(); --i >= 0;)
  234963. if (! cds.getReference(i).getChildFile (".TOC.plist").exists())
  234964. cds.remove (i);
  234965. }
  234966. struct TrackSorter
  234967. {
  234968. static int getCDTrackNumber (const File& file)
  234969. {
  234970. return file.getFileName().initialSectionContainingOnly ("0123456789").getIntValue();
  234971. }
  234972. static int compareElements (const File& first, const File& second)
  234973. {
  234974. const int firstTrack = getCDTrackNumber (first);
  234975. const int secondTrack = getCDTrackNumber (second);
  234976. jassert (firstTrack > 0 && secondTrack > 0);
  234977. return firstTrack - secondTrack;
  234978. }
  234979. };
  234980. }
  234981. const StringArray AudioCDReader::getAvailableCDNames()
  234982. {
  234983. Array<File> cds;
  234984. CDReaderHelpers::findDevices (cds);
  234985. StringArray names;
  234986. for (int i = 0; i < cds.size(); ++i)
  234987. names.add (cds.getReference(i).getFileName());
  234988. return names;
  234989. }
  234990. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  234991. {
  234992. Array<File> cds;
  234993. CDReaderHelpers::findDevices (cds);
  234994. if (cds[index].exists())
  234995. return new AudioCDReader (cds[index]);
  234996. return 0;
  234997. }
  234998. AudioCDReader::AudioCDReader (const File& volume)
  234999. : AudioFormatReader (0, "CD Audio"),
  235000. volumeDir (volume),
  235001. currentReaderTrack (-1),
  235002. reader (0)
  235003. {
  235004. sampleRate = 44100.0;
  235005. bitsPerSample = 16;
  235006. numChannels = 2;
  235007. usesFloatingPointData = false;
  235008. refreshTrackLengths();
  235009. }
  235010. AudioCDReader::~AudioCDReader()
  235011. {
  235012. }
  235013. void AudioCDReader::refreshTrackLengths()
  235014. {
  235015. tracks.clear();
  235016. trackStartSamples.clear();
  235017. lengthInSamples = 0;
  235018. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, "*.aiff");
  235019. CDReaderHelpers::TrackSorter sorter;
  235020. tracks.sort (sorter);
  235021. const File toc (volumeDir.getChildFile (".TOC.plist"));
  235022. if (toc.exists())
  235023. {
  235024. XmlDocument doc (toc);
  235025. const char* error = CDReaderHelpers::getTrackOffsets (doc, trackStartSamples);
  235026. (void) error; // could be logged..
  235027. lengthInSamples = trackStartSamples.getLast() - trackStartSamples.getFirst();
  235028. }
  235029. }
  235030. bool AudioCDReader::readSamples (int** destSamples, int numDestChannels, int startOffsetInDestBuffer,
  235031. int64 startSampleInFile, int numSamples)
  235032. {
  235033. while (numSamples > 0)
  235034. {
  235035. int track = -1;
  235036. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  235037. {
  235038. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  235039. {
  235040. track = i;
  235041. break;
  235042. }
  235043. }
  235044. if (track < 0)
  235045. return false;
  235046. if (track != currentReaderTrack)
  235047. {
  235048. reader = 0;
  235049. FileInputStream* const in = tracks [track].createInputStream();
  235050. if (in != 0)
  235051. {
  235052. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  235053. AiffAudioFormat format;
  235054. reader = format.createReaderFor (bin, true);
  235055. if (reader == 0)
  235056. currentReaderTrack = -1;
  235057. else
  235058. currentReaderTrack = track;
  235059. }
  235060. }
  235061. if (reader == 0)
  235062. return false;
  235063. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  235064. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  235065. reader->readSamples (destSamples, numDestChannels, startOffsetInDestBuffer, startPos, numAvailable);
  235066. numSamples -= numAvailable;
  235067. startSampleInFile += numAvailable;
  235068. }
  235069. return true;
  235070. }
  235071. bool AudioCDReader::isCDStillPresent() const
  235072. {
  235073. return volumeDir.exists();
  235074. }
  235075. bool AudioCDReader::isTrackAudio (int trackNum) const
  235076. {
  235077. return tracks [trackNum].hasFileExtension (".aiff");
  235078. }
  235079. void AudioCDReader::enableIndexScanning (bool b)
  235080. {
  235081. // any way to do this on a Mac??
  235082. }
  235083. int AudioCDReader::getLastIndex() const
  235084. {
  235085. return 0;
  235086. }
  235087. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  235088. {
  235089. return Array <int>();
  235090. }
  235091. #endif
  235092. /*** End of inlined file: juce_mac_AudioCDReader.mm ***/
  235093. /*** Start of inlined file: juce_mac_MessageManager.mm ***/
  235094. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235095. // compiled on its own).
  235096. #if JUCE_INCLUDED_FILE
  235097. /* When you use multiple DLLs which share similarly-named obj-c classes - like
  235098. for example having more than one juce plugin loaded into a host, then when a
  235099. method is called, the actual code that runs might actually be in a different module
  235100. than the one you expect... So any calls to library functions or statics that are
  235101. made inside obj-c methods will probably end up getting executed in a different DLL's
  235102. memory space. Not a great thing to happen - this obviously leads to bizarre crashes.
  235103. To work around this insanity, I'm only allowing obj-c methods to make calls to
  235104. virtual methods of an object that's known to live inside the right module's space.
  235105. */
  235106. class AppDelegateRedirector
  235107. {
  235108. public:
  235109. AppDelegateRedirector()
  235110. {
  235111. #if MAC_OS_X_VERSION_MIN_REQUIRED > MAC_OS_X_VERSION_10_4
  235112. runLoop = CFRunLoopGetMain();
  235113. #else
  235114. runLoop = CFRunLoopGetCurrent();
  235115. #endif
  235116. CFRunLoopSourceContext sourceContext;
  235117. zerostruct (sourceContext);
  235118. sourceContext.info = this;
  235119. sourceContext.perform = runLoopSourceCallback;
  235120. runLoopSource = CFRunLoopSourceCreate (kCFAllocatorDefault, 1, &sourceContext);
  235121. CFRunLoopAddSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  235122. }
  235123. virtual ~AppDelegateRedirector()
  235124. {
  235125. CFRunLoopRemoveSource (runLoop, runLoopSource, kCFRunLoopCommonModes);
  235126. CFRunLoopSourceInvalidate (runLoopSource);
  235127. CFRelease (runLoopSource);
  235128. }
  235129. virtual NSApplicationTerminateReply shouldTerminate()
  235130. {
  235131. if (JUCEApplication::getInstance() != 0)
  235132. {
  235133. JUCEApplication::getInstance()->systemRequestedQuit();
  235134. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  235135. return NSTerminateCancel;
  235136. }
  235137. return NSTerminateNow;
  235138. }
  235139. virtual void willTerminate()
  235140. {
  235141. JUCEApplication::appWillTerminateByForce();
  235142. }
  235143. virtual BOOL openFile (NSString* filename)
  235144. {
  235145. if (JUCEApplication::getInstance() != 0)
  235146. {
  235147. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  235148. return YES;
  235149. }
  235150. return NO;
  235151. }
  235152. virtual void openFiles (NSArray* filenames)
  235153. {
  235154. StringArray files;
  235155. for (unsigned int i = 0; i < [filenames count]; ++i)
  235156. {
  235157. String filename (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  235158. if (filename.containsChar (' '))
  235159. filename = filename.quoted('"');
  235160. files.add (filename);
  235161. }
  235162. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  235163. {
  235164. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (" "));
  235165. }
  235166. }
  235167. virtual void focusChanged()
  235168. {
  235169. juce_HandleProcessFocusChange();
  235170. }
  235171. struct CallbackMessagePayload
  235172. {
  235173. MessageCallbackFunction* function;
  235174. void* parameter;
  235175. void* volatile result;
  235176. bool volatile hasBeenExecuted;
  235177. };
  235178. virtual void performCallback (CallbackMessagePayload* pl)
  235179. {
  235180. pl->result = (*pl->function) (pl->parameter);
  235181. pl->hasBeenExecuted = true;
  235182. }
  235183. virtual void deleteSelf()
  235184. {
  235185. delete this;
  235186. }
  235187. void postMessage (Message* const m)
  235188. {
  235189. messages.add (m);
  235190. CFRunLoopSourceSignal (runLoopSource);
  235191. CFRunLoopWakeUp (runLoop);
  235192. }
  235193. private:
  235194. CFRunLoopRef runLoop;
  235195. CFRunLoopSourceRef runLoopSource;
  235196. OwnedArray <Message, CriticalSection> messages;
  235197. void runLoopCallback()
  235198. {
  235199. int numDispatched = 0;
  235200. do
  235201. {
  235202. Message* const nextMessage = messages.removeAndReturn (0);
  235203. if (nextMessage == 0)
  235204. return;
  235205. const ScopedAutoReleasePool pool;
  235206. MessageManager::getInstance()->deliverMessage (nextMessage);
  235207. } while (++numDispatched <= 4);
  235208. CFRunLoopSourceSignal (runLoopSource);
  235209. CFRunLoopWakeUp (runLoop);
  235210. }
  235211. static void runLoopSourceCallback (void* info)
  235212. {
  235213. static_cast <AppDelegateRedirector*> (info)->runLoopCallback();
  235214. }
  235215. };
  235216. END_JUCE_NAMESPACE
  235217. using namespace JUCE_NAMESPACE;
  235218. #define JuceAppDelegate MakeObjCClassName(JuceAppDelegate)
  235219. @interface JuceAppDelegate : NSObject
  235220. {
  235221. @private
  235222. id oldDelegate;
  235223. @public
  235224. AppDelegateRedirector* redirector;
  235225. }
  235226. - (JuceAppDelegate*) init;
  235227. - (void) dealloc;
  235228. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  235229. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  235230. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  235231. - (void) applicationWillTerminate: (NSNotification*) aNotification;
  235232. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  235233. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  235234. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  235235. - (void) performCallback: (id) info;
  235236. - (void) dummyMethod;
  235237. @end
  235238. @implementation JuceAppDelegate
  235239. - (JuceAppDelegate*) init
  235240. {
  235241. [super init];
  235242. redirector = new AppDelegateRedirector();
  235243. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  235244. if (JUCEApplication::isStandaloneApp())
  235245. {
  235246. oldDelegate = [NSApp delegate];
  235247. [NSApp setDelegate: self];
  235248. }
  235249. else
  235250. {
  235251. oldDelegate = 0;
  235252. [center addObserver: self selector: @selector (applicationDidResignActive:)
  235253. name: NSApplicationDidResignActiveNotification object: NSApp];
  235254. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  235255. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  235256. [center addObserver: self selector: @selector (applicationWillUnhide:)
  235257. name: NSApplicationWillUnhideNotification object: NSApp];
  235258. }
  235259. return self;
  235260. }
  235261. - (void) dealloc
  235262. {
  235263. if (oldDelegate != 0)
  235264. [NSApp setDelegate: oldDelegate];
  235265. redirector->deleteSelf();
  235266. [super dealloc];
  235267. }
  235268. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  235269. {
  235270. (void) app;
  235271. return redirector->shouldTerminate();
  235272. }
  235273. - (void) applicationWillTerminate: (NSNotification*) aNotification
  235274. {
  235275. (void) aNotification;
  235276. redirector->willTerminate();
  235277. }
  235278. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  235279. {
  235280. (void) app;
  235281. return redirector->openFile (filename);
  235282. }
  235283. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  235284. {
  235285. (void) sender;
  235286. return redirector->openFiles (filenames);
  235287. }
  235288. - (void) applicationDidBecomeActive: (NSNotification*) notification
  235289. {
  235290. (void) notification;
  235291. redirector->focusChanged();
  235292. }
  235293. - (void) applicationDidResignActive: (NSNotification*) notification
  235294. {
  235295. (void) notification;
  235296. redirector->focusChanged();
  235297. }
  235298. - (void) applicationWillUnhide: (NSNotification*) notification
  235299. {
  235300. (void) notification;
  235301. redirector->focusChanged();
  235302. }
  235303. - (void) performCallback: (id) info
  235304. {
  235305. if ([info isKindOfClass: [NSData class]])
  235306. {
  235307. AppDelegateRedirector::CallbackMessagePayload* pl
  235308. = (AppDelegateRedirector::CallbackMessagePayload*) [((NSData*) info) bytes];
  235309. if (pl != 0)
  235310. redirector->performCallback (pl);
  235311. }
  235312. else
  235313. {
  235314. jassertfalse; // should never get here!
  235315. }
  235316. }
  235317. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  235318. @end
  235319. BEGIN_JUCE_NAMESPACE
  235320. static JuceAppDelegate* juceAppDelegate = 0;
  235321. void MessageManager::runDispatchLoop()
  235322. {
  235323. if (! quitMessagePosted) // check that the quit message wasn't already posted..
  235324. {
  235325. const ScopedAutoReleasePool pool;
  235326. // must only be called by the message thread!
  235327. jassert (isThisTheMessageThread());
  235328. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  235329. @try
  235330. {
  235331. [NSApp run];
  235332. }
  235333. @catch (NSException* e)
  235334. {
  235335. // An AppKit exception will kill the app, but at least this provides a chance to log it.,
  235336. std::runtime_error ex (std::string ("NSException: ") + [[e name] UTF8String] + ", Reason:" + [[e reason] UTF8String]);
  235337. JUCEApplication::sendUnhandledException (&ex, __FILE__, __LINE__);
  235338. }
  235339. @finally
  235340. {
  235341. }
  235342. #else
  235343. [NSApp run];
  235344. #endif
  235345. }
  235346. }
  235347. void MessageManager::stopDispatchLoop()
  235348. {
  235349. quitMessagePosted = true;
  235350. [NSApp stop: nil];
  235351. [NSApp activateIgnoringOtherApps: YES]; // (if the app is inactive, it sits there and ignores the quit request until the next time it gets activated)
  235352. [NSEvent startPeriodicEventsAfterDelay: 0 withPeriod: 0.1];
  235353. }
  235354. namespace
  235355. {
  235356. bool isEventBlockedByModalComps (NSEvent* e)
  235357. {
  235358. if (Component::getNumCurrentlyModalComponents() == 0)
  235359. return false;
  235360. NSWindow* const w = [e window];
  235361. if (w == 0 || [w worksWhenModal])
  235362. return false;
  235363. bool isKey = false, isInputAttempt = false;
  235364. switch ([e type])
  235365. {
  235366. case NSKeyDown:
  235367. case NSKeyUp:
  235368. isKey = isInputAttempt = true;
  235369. break;
  235370. case NSLeftMouseDown:
  235371. case NSRightMouseDown:
  235372. case NSOtherMouseDown:
  235373. isInputAttempt = true;
  235374. break;
  235375. case NSLeftMouseDragged:
  235376. case NSRightMouseDragged:
  235377. case NSLeftMouseUp:
  235378. case NSRightMouseUp:
  235379. case NSOtherMouseUp:
  235380. case NSOtherMouseDragged:
  235381. if (Desktop::getInstance().getDraggingMouseSource(0) != 0)
  235382. return false;
  235383. break;
  235384. case NSMouseMoved:
  235385. case NSMouseEntered:
  235386. case NSMouseExited:
  235387. case NSCursorUpdate:
  235388. case NSScrollWheel:
  235389. case NSTabletPoint:
  235390. case NSTabletProximity:
  235391. break;
  235392. default:
  235393. return false;
  235394. }
  235395. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  235396. {
  235397. ComponentPeer* const peer = ComponentPeer::getPeer (i);
  235398. NSView* const compView = (NSView*) peer->getNativeHandle();
  235399. if ([compView window] == w)
  235400. {
  235401. if (isKey)
  235402. {
  235403. if (compView == [w firstResponder])
  235404. return false;
  235405. }
  235406. else
  235407. {
  235408. NSViewComponentPeer* nsViewPeer = dynamic_cast<NSViewComponentPeer*> (peer);
  235409. if ((nsViewPeer == 0 || ! nsViewPeer->isSharedWindow)
  235410. ? NSPointInRect ([e locationInWindow], NSMakeRect (0, 0, [w frame].size.width, [w frame].size.height))
  235411. : NSPointInRect ([compView convertPoint: [e locationInWindow] fromView: nil], [compView bounds]))
  235412. return false;
  235413. }
  235414. }
  235415. }
  235416. if (isInputAttempt)
  235417. {
  235418. if (! [NSApp isActive])
  235419. [NSApp activateIgnoringOtherApps: YES];
  235420. Component* const modal = Component::getCurrentlyModalComponent (0);
  235421. if (modal != 0)
  235422. modal->inputAttemptWhenModal();
  235423. }
  235424. return true;
  235425. }
  235426. }
  235427. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  235428. {
  235429. jassert (isThisTheMessageThread()); // must only be called by the message thread
  235430. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  235431. while (! quitMessagePosted)
  235432. {
  235433. const ScopedAutoReleasePool pool;
  235434. CFRunLoopRunInMode (kCFRunLoopDefaultMode, 0.001, true);
  235435. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  235436. untilDate: [NSDate dateWithTimeIntervalSinceNow: 0.001]
  235437. inMode: NSDefaultRunLoopMode
  235438. dequeue: YES];
  235439. if (e != 0 && ! isEventBlockedByModalComps (e))
  235440. [NSApp sendEvent: e];
  235441. if (Time::getMillisecondCounter() >= endTime)
  235442. break;
  235443. }
  235444. return ! quitMessagePosted;
  235445. }
  235446. void MessageManager::doPlatformSpecificInitialisation()
  235447. {
  235448. if (juceAppDelegate == 0)
  235449. juceAppDelegate = [[JuceAppDelegate alloc] init];
  235450. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  235451. // correctly (needed prior to 10.5)
  235452. if (! [NSThread isMultiThreaded])
  235453. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  235454. toTarget: juceAppDelegate
  235455. withObject: nil];
  235456. }
  235457. void MessageManager::doPlatformSpecificShutdown()
  235458. {
  235459. if (juceAppDelegate != 0)
  235460. {
  235461. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  235462. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  235463. [juceAppDelegate release];
  235464. juceAppDelegate = 0;
  235465. }
  235466. }
  235467. bool juce_postMessageToSystemQueue (Message* message)
  235468. {
  235469. juceAppDelegate->redirector->postMessage (message);
  235470. return true;
  235471. }
  235472. void MessageManager::broadcastMessage (const String& value)
  235473. {
  235474. }
  235475. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback, void* data)
  235476. {
  235477. if (isThisTheMessageThread())
  235478. {
  235479. return (*callback) (data);
  235480. }
  235481. else
  235482. {
  235483. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  235484. // deadlock because the message manager is blocked from running, so can never
  235485. // call your function..
  235486. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  235487. const ScopedAutoReleasePool pool;
  235488. AppDelegateRedirector::CallbackMessagePayload cmp;
  235489. cmp.function = callback;
  235490. cmp.parameter = data;
  235491. cmp.result = 0;
  235492. cmp.hasBeenExecuted = false;
  235493. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  235494. withObject: [NSData dataWithBytesNoCopy: &cmp
  235495. length: sizeof (cmp)
  235496. freeWhenDone: NO]
  235497. waitUntilDone: YES];
  235498. return cmp.result;
  235499. }
  235500. }
  235501. #endif
  235502. /*** End of inlined file: juce_mac_MessageManager.mm ***/
  235503. /*** Start of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235504. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235505. // compiled on its own).
  235506. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  235507. #if JUCE_MAC
  235508. END_JUCE_NAMESPACE
  235509. #define DownloadClickDetector MakeObjCClassName(DownloadClickDetector)
  235510. @interface DownloadClickDetector : NSObject
  235511. {
  235512. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  235513. }
  235514. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  235515. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235516. request: (NSURLRequest*) request
  235517. frame: (WebFrame*) frame
  235518. decisionListener: (id<WebPolicyDecisionListener>) listener;
  235519. @end
  235520. @implementation DownloadClickDetector
  235521. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  235522. {
  235523. [super init];
  235524. ownerComponent = ownerComponent_;
  235525. return self;
  235526. }
  235527. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  235528. request: (NSURLRequest*) request
  235529. frame: (WebFrame*) frame
  235530. decisionListener: (id <WebPolicyDecisionListener>) listener
  235531. {
  235532. (void) sender;
  235533. (void) request;
  235534. (void) frame;
  235535. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  235536. if (ownerComponent->pageAboutToLoad (nsStringToJuce ([url absoluteString])))
  235537. [listener use];
  235538. else
  235539. [listener ignore];
  235540. }
  235541. @end
  235542. BEGIN_JUCE_NAMESPACE
  235543. class WebBrowserComponentInternal : public NSViewComponent
  235544. {
  235545. public:
  235546. WebBrowserComponentInternal (WebBrowserComponent* owner)
  235547. {
  235548. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  235549. frameName: @""
  235550. groupName: @""];
  235551. setView (webView);
  235552. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  235553. [webView setPolicyDelegate: clickListener];
  235554. }
  235555. ~WebBrowserComponentInternal()
  235556. {
  235557. [webView setPolicyDelegate: nil];
  235558. [clickListener release];
  235559. setView (0);
  235560. }
  235561. void goToURL (const String& url,
  235562. const StringArray* headers,
  235563. const MemoryBlock* postData)
  235564. {
  235565. NSMutableURLRequest* r
  235566. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  235567. cachePolicy: NSURLRequestUseProtocolCachePolicy
  235568. timeoutInterval: 30.0];
  235569. if (postData != 0 && postData->getSize() > 0)
  235570. {
  235571. [r setHTTPMethod: @"POST"];
  235572. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  235573. length: postData->getSize()]];
  235574. }
  235575. if (headers != 0)
  235576. {
  235577. for (int i = 0; i < headers->size(); ++i)
  235578. {
  235579. const String headerName ((*headers)[i].upToFirstOccurrenceOf (":", false, false).trim());
  235580. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (":", false, false).trim());
  235581. [r setValue: juceStringToNS (headerValue)
  235582. forHTTPHeaderField: juceStringToNS (headerName)];
  235583. }
  235584. }
  235585. stop();
  235586. [[webView mainFrame] loadRequest: r];
  235587. }
  235588. void goBack()
  235589. {
  235590. [webView goBack];
  235591. }
  235592. void goForward()
  235593. {
  235594. [webView goForward];
  235595. }
  235596. void stop()
  235597. {
  235598. [webView stopLoading: nil];
  235599. }
  235600. void refresh()
  235601. {
  235602. [webView reload: nil];
  235603. }
  235604. private:
  235605. WebView* webView;
  235606. DownloadClickDetector* clickListener;
  235607. };
  235608. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235609. : browser (0),
  235610. blankPageShown (false),
  235611. unloadPageWhenBrowserIsHidden (unloadPageWhenBrowserIsHidden_)
  235612. {
  235613. setOpaque (true);
  235614. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  235615. }
  235616. WebBrowserComponent::~WebBrowserComponent()
  235617. {
  235618. deleteAndZero (browser);
  235619. }
  235620. void WebBrowserComponent::goToURL (const String& url,
  235621. const StringArray* headers,
  235622. const MemoryBlock* postData)
  235623. {
  235624. lastURL = url;
  235625. lastHeaders.clear();
  235626. if (headers != 0)
  235627. lastHeaders = *headers;
  235628. lastPostData.setSize (0);
  235629. if (postData != 0)
  235630. lastPostData = *postData;
  235631. blankPageShown = false;
  235632. browser->goToURL (url, headers, postData);
  235633. }
  235634. void WebBrowserComponent::stop()
  235635. {
  235636. browser->stop();
  235637. }
  235638. void WebBrowserComponent::goBack()
  235639. {
  235640. lastURL = String::empty;
  235641. blankPageShown = false;
  235642. browser->goBack();
  235643. }
  235644. void WebBrowserComponent::goForward()
  235645. {
  235646. lastURL = String::empty;
  235647. browser->goForward();
  235648. }
  235649. void WebBrowserComponent::refresh()
  235650. {
  235651. browser->refresh();
  235652. }
  235653. void WebBrowserComponent::paint (Graphics&)
  235654. {
  235655. }
  235656. void WebBrowserComponent::checkWindowAssociation()
  235657. {
  235658. if (isShowing())
  235659. {
  235660. if (blankPageShown)
  235661. goBack();
  235662. }
  235663. else
  235664. {
  235665. if (unloadPageWhenBrowserIsHidden && ! blankPageShown)
  235666. {
  235667. // when the component becomes invisible, some stuff like flash
  235668. // carries on playing audio, so we need to force it onto a blank
  235669. // page to avoid this, (and send it back when it's made visible again).
  235670. blankPageShown = true;
  235671. browser->goToURL ("about:blank", 0, 0);
  235672. }
  235673. }
  235674. }
  235675. void WebBrowserComponent::reloadLastURL()
  235676. {
  235677. if (lastURL.isNotEmpty())
  235678. {
  235679. goToURL (lastURL, &lastHeaders, &lastPostData);
  235680. lastURL = String::empty;
  235681. }
  235682. }
  235683. void WebBrowserComponent::parentHierarchyChanged()
  235684. {
  235685. checkWindowAssociation();
  235686. }
  235687. void WebBrowserComponent::resized()
  235688. {
  235689. browser->setSize (getWidth(), getHeight());
  235690. }
  235691. void WebBrowserComponent::visibilityChanged()
  235692. {
  235693. checkWindowAssociation();
  235694. }
  235695. bool WebBrowserComponent::pageAboutToLoad (const String&)
  235696. {
  235697. return true;
  235698. }
  235699. #else
  235700. WebBrowserComponent::WebBrowserComponent (const bool unloadPageWhenBrowserIsHidden_)
  235701. {
  235702. }
  235703. WebBrowserComponent::~WebBrowserComponent()
  235704. {
  235705. }
  235706. void WebBrowserComponent::goToURL (const String& url,
  235707. const StringArray* headers,
  235708. const MemoryBlock* postData)
  235709. {
  235710. }
  235711. void WebBrowserComponent::stop()
  235712. {
  235713. }
  235714. void WebBrowserComponent::goBack()
  235715. {
  235716. }
  235717. void WebBrowserComponent::goForward()
  235718. {
  235719. }
  235720. void WebBrowserComponent::refresh()
  235721. {
  235722. }
  235723. void WebBrowserComponent::paint (Graphics& g)
  235724. {
  235725. }
  235726. void WebBrowserComponent::checkWindowAssociation()
  235727. {
  235728. }
  235729. void WebBrowserComponent::reloadLastURL()
  235730. {
  235731. }
  235732. void WebBrowserComponent::parentHierarchyChanged()
  235733. {
  235734. }
  235735. void WebBrowserComponent::resized()
  235736. {
  235737. }
  235738. void WebBrowserComponent::visibilityChanged()
  235739. {
  235740. }
  235741. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  235742. {
  235743. return true;
  235744. }
  235745. #endif
  235746. #endif
  235747. /*** End of inlined file: juce_mac_WebBrowserComponent.mm ***/
  235748. /*** Start of inlined file: juce_mac_CoreAudio.cpp ***/
  235749. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  235750. // compiled on its own).
  235751. #if JUCE_INCLUDED_FILE
  235752. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235753. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  235754. #endif
  235755. #undef log
  235756. #if JUCE_COREAUDIO_LOGGING_ENABLED
  235757. #define log(a) Logger::writeToLog (a)
  235758. #else
  235759. #define log(a)
  235760. #endif
  235761. #undef OK
  235762. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  235763. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  235764. {
  235765. if (err == noErr)
  235766. return true;
  235767. Logger::writeToLog ("CoreAudio error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  235768. jassertfalse;
  235769. return false;
  235770. }
  235771. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  235772. #else
  235773. #define OK(a) (a == noErr)
  235774. #endif
  235775. class CoreAudioInternal : public Timer
  235776. {
  235777. public:
  235778. CoreAudioInternal (AudioDeviceID id)
  235779. : inputLatency (0),
  235780. outputLatency (0),
  235781. callback (0),
  235782. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  235783. audioProcID (0),
  235784. #endif
  235785. isSlaveDevice (false),
  235786. deviceID (id),
  235787. started (false),
  235788. sampleRate (0),
  235789. bufferSize (512),
  235790. numInputChans (0),
  235791. numOutputChans (0),
  235792. callbacksAllowed (true),
  235793. numInputChannelInfos (0),
  235794. numOutputChannelInfos (0)
  235795. {
  235796. jassert (deviceID != 0);
  235797. updateDetailsFromDevice();
  235798. AudioObjectPropertyAddress pa;
  235799. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235800. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235801. pa.mElement = kAudioObjectPropertyElementWildcard;
  235802. AudioObjectAddPropertyListener (deviceID, &pa, deviceListenerProc, this);
  235803. }
  235804. ~CoreAudioInternal()
  235805. {
  235806. AudioObjectPropertyAddress pa;
  235807. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  235808. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235809. pa.mElement = kAudioObjectPropertyElementWildcard;
  235810. AudioObjectRemovePropertyListener (deviceID, &pa, deviceListenerProc, this);
  235811. stop (false);
  235812. }
  235813. void allocateTempBuffers()
  235814. {
  235815. const int tempBufSize = bufferSize + 4;
  235816. audioBuffer.calloc ((numInputChans + numOutputChans) * tempBufSize);
  235817. tempInputBuffers.calloc (numInputChans + 2);
  235818. tempOutputBuffers.calloc (numOutputChans + 2);
  235819. int i, count = 0;
  235820. for (i = 0; i < numInputChans; ++i)
  235821. tempInputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235822. for (i = 0; i < numOutputChans; ++i)
  235823. tempOutputBuffers[i] = audioBuffer + count++ * tempBufSize;
  235824. }
  235825. // returns the number of actual available channels
  235826. void fillInChannelInfo (const bool input)
  235827. {
  235828. int chanNum = 0;
  235829. UInt32 size;
  235830. AudioObjectPropertyAddress pa;
  235831. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  235832. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  235833. pa.mElement = kAudioObjectPropertyElementMaster;
  235834. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235835. {
  235836. HeapBlock <AudioBufferList> bufList;
  235837. bufList.calloc (size, 1);
  235838. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  235839. {
  235840. const int numStreams = bufList->mNumberBuffers;
  235841. for (int i = 0; i < numStreams; ++i)
  235842. {
  235843. const AudioBuffer& b = bufList->mBuffers[i];
  235844. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  235845. {
  235846. String name;
  235847. {
  235848. char channelName [256];
  235849. zerostruct (channelName);
  235850. UInt32 nameSize = sizeof (channelName);
  235851. UInt32 channelNum = chanNum + 1;
  235852. pa.mSelector = kAudioDevicePropertyChannelName;
  235853. if (AudioObjectGetPropertyData (deviceID, &pa, sizeof (channelNum), &channelNum, &nameSize, channelName) == noErr)
  235854. name = String::fromUTF8 (channelName, nameSize);
  235855. }
  235856. if (input)
  235857. {
  235858. if (activeInputChans[chanNum])
  235859. {
  235860. inputChannelInfo [numInputChannelInfos].streamNum = i;
  235861. inputChannelInfo [numInputChannelInfos].dataOffsetSamples = j;
  235862. inputChannelInfo [numInputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235863. ++numInputChannelInfos;
  235864. }
  235865. if (name.isEmpty())
  235866. name << "Input " << (chanNum + 1);
  235867. inChanNames.add (name);
  235868. }
  235869. else
  235870. {
  235871. if (activeOutputChans[chanNum])
  235872. {
  235873. outputChannelInfo [numOutputChannelInfos].streamNum = i;
  235874. outputChannelInfo [numOutputChannelInfos].dataOffsetSamples = j;
  235875. outputChannelInfo [numOutputChannelInfos].dataStrideSamples = b.mNumberChannels;
  235876. ++numOutputChannelInfos;
  235877. }
  235878. if (name.isEmpty())
  235879. name << "Output " << (chanNum + 1);
  235880. outChanNames.add (name);
  235881. }
  235882. ++chanNum;
  235883. }
  235884. }
  235885. }
  235886. }
  235887. }
  235888. void updateDetailsFromDevice()
  235889. {
  235890. stopTimer();
  235891. if (deviceID == 0)
  235892. return;
  235893. const ScopedLock sl (callbackLock);
  235894. Float64 sr;
  235895. UInt32 size = sizeof (Float64);
  235896. AudioObjectPropertyAddress pa;
  235897. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  235898. pa.mScope = kAudioObjectPropertyScopeWildcard;
  235899. pa.mElement = kAudioObjectPropertyElementMaster;
  235900. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &sr)))
  235901. sampleRate = sr;
  235902. UInt32 framesPerBuf;
  235903. size = sizeof (framesPerBuf);
  235904. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  235905. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &framesPerBuf)))
  235906. {
  235907. bufferSize = framesPerBuf;
  235908. allocateTempBuffers();
  235909. }
  235910. bufferSizes.clear();
  235911. pa.mSelector = kAudioDevicePropertyBufferFrameSizeRange;
  235912. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235913. {
  235914. HeapBlock <AudioValueRange> ranges;
  235915. ranges.calloc (size, 1);
  235916. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235917. {
  235918. bufferSizes.add ((int) ranges[0].mMinimum);
  235919. for (int i = 32; i < 2048; i += 32)
  235920. {
  235921. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235922. {
  235923. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  235924. {
  235925. bufferSizes.addIfNotAlreadyThere (i);
  235926. break;
  235927. }
  235928. }
  235929. }
  235930. if (bufferSize > 0)
  235931. bufferSizes.addIfNotAlreadyThere (bufferSize);
  235932. }
  235933. }
  235934. if (bufferSizes.size() == 0 && bufferSize > 0)
  235935. bufferSizes.add (bufferSize);
  235936. sampleRates.clear();
  235937. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  235938. String rates;
  235939. pa.mSelector = kAudioDevicePropertyAvailableNominalSampleRates;
  235940. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  235941. {
  235942. HeapBlock <AudioValueRange> ranges;
  235943. ranges.calloc (size, 1);
  235944. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, ranges)))
  235945. {
  235946. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  235947. {
  235948. bool ok = false;
  235949. for (int j = size / (int) sizeof (AudioValueRange); --j >= 0;)
  235950. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  235951. ok = true;
  235952. if (ok)
  235953. {
  235954. sampleRates.add (possibleRates[i]);
  235955. rates << possibleRates[i] << ' ';
  235956. }
  235957. }
  235958. }
  235959. }
  235960. if (sampleRates.size() == 0 && sampleRate > 0)
  235961. {
  235962. sampleRates.add (sampleRate);
  235963. rates << sampleRate;
  235964. }
  235965. log ("sr: " + rates);
  235966. inputLatency = 0;
  235967. outputLatency = 0;
  235968. UInt32 lat;
  235969. size = sizeof (lat);
  235970. pa.mSelector = kAudioDevicePropertyLatency;
  235971. pa.mScope = kAudioDevicePropertyScopeInput;
  235972. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235973. inputLatency = (int) lat;
  235974. pa.mScope = kAudioDevicePropertyScopeOutput;
  235975. size = sizeof (lat);
  235976. if (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &lat) == noErr)
  235977. outputLatency = (int) lat;
  235978. log ("lat: " + String (inputLatency) + " " + String (outputLatency));
  235979. inChanNames.clear();
  235980. outChanNames.clear();
  235981. inputChannelInfo.calloc (numInputChans + 2);
  235982. numInputChannelInfos = 0;
  235983. outputChannelInfo.calloc (numOutputChans + 2);
  235984. numOutputChannelInfos = 0;
  235985. fillInChannelInfo (true);
  235986. fillInChannelInfo (false);
  235987. }
  235988. const StringArray getSources (bool input)
  235989. {
  235990. StringArray s;
  235991. HeapBlock <OSType> types;
  235992. const int num = getAllDataSourcesForDevice (deviceID, types);
  235993. for (int i = 0; i < num; ++i)
  235994. {
  235995. AudioValueTranslation avt;
  235996. char buffer[256];
  235997. avt.mInputData = &(types[i]);
  235998. avt.mInputDataSize = sizeof (UInt32);
  235999. avt.mOutputData = buffer;
  236000. avt.mOutputDataSize = 256;
  236001. UInt32 transSize = sizeof (avt);
  236002. AudioObjectPropertyAddress pa;
  236003. pa.mSelector = kAudioDevicePropertyDataSourceNameForID;
  236004. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236005. pa.mElement = kAudioObjectPropertyElementMaster;
  236006. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &transSize, &avt)))
  236007. {
  236008. DBG (buffer);
  236009. s.add (buffer);
  236010. }
  236011. }
  236012. return s;
  236013. }
  236014. int getCurrentSourceIndex (bool input) const
  236015. {
  236016. OSType currentSourceID = 0;
  236017. UInt32 size = sizeof (currentSourceID);
  236018. int result = -1;
  236019. AudioObjectPropertyAddress pa;
  236020. pa.mSelector = kAudioDevicePropertyDataSource;
  236021. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236022. pa.mElement = kAudioObjectPropertyElementMaster;
  236023. if (deviceID != 0)
  236024. {
  236025. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &currentSourceID)))
  236026. {
  236027. HeapBlock <OSType> types;
  236028. const int num = getAllDataSourcesForDevice (deviceID, types);
  236029. for (int i = 0; i < num; ++i)
  236030. {
  236031. if (types[num] == currentSourceID)
  236032. {
  236033. result = i;
  236034. break;
  236035. }
  236036. }
  236037. }
  236038. }
  236039. return result;
  236040. }
  236041. void setCurrentSourceIndex (int index, bool input)
  236042. {
  236043. if (deviceID != 0)
  236044. {
  236045. HeapBlock <OSType> types;
  236046. const int num = getAllDataSourcesForDevice (deviceID, types);
  236047. if (((unsigned int) index) < (unsigned int) num)
  236048. {
  236049. AudioObjectPropertyAddress pa;
  236050. pa.mSelector = kAudioDevicePropertyDataSource;
  236051. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236052. pa.mElement = kAudioObjectPropertyElementMaster;
  236053. OSType typeId = types[index];
  236054. OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (typeId), &typeId));
  236055. }
  236056. }
  236057. }
  236058. const String reopen (const BigInteger& inputChannels,
  236059. const BigInteger& outputChannels,
  236060. double newSampleRate,
  236061. int bufferSizeSamples)
  236062. {
  236063. String error;
  236064. log ("CoreAudio reopen");
  236065. callbacksAllowed = false;
  236066. stopTimer();
  236067. stop (false);
  236068. activeInputChans = inputChannels;
  236069. activeInputChans.setRange (inChanNames.size(),
  236070. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  236071. false);
  236072. activeOutputChans = outputChannels;
  236073. activeOutputChans.setRange (outChanNames.size(),
  236074. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  236075. false);
  236076. numInputChans = activeInputChans.countNumberOfSetBits();
  236077. numOutputChans = activeOutputChans.countNumberOfSetBits();
  236078. // set sample rate
  236079. AudioObjectPropertyAddress pa;
  236080. pa.mSelector = kAudioDevicePropertyNominalSampleRate;
  236081. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236082. pa.mElement = kAudioObjectPropertyElementMaster;
  236083. Float64 sr = newSampleRate;
  236084. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (sr), &sr)))
  236085. {
  236086. error = "Couldn't change sample rate";
  236087. }
  236088. else
  236089. {
  236090. // change buffer size
  236091. UInt32 framesPerBuf = bufferSizeSamples;
  236092. pa.mSelector = kAudioDevicePropertyBufferFrameSize;
  236093. if (! OK (AudioObjectSetPropertyData (deviceID, &pa, 0, 0, sizeof (framesPerBuf), &framesPerBuf)))
  236094. {
  236095. error = "Couldn't change buffer size";
  236096. }
  236097. else
  236098. {
  236099. // Annoyingly, after changing the rate and buffer size, some devices fail to
  236100. // correctly report their new settings until some random time in the future, so
  236101. // after calling updateDetailsFromDevice, we need to manually bodge these values
  236102. // to make sure we're using the correct numbers..
  236103. updateDetailsFromDevice();
  236104. sampleRate = newSampleRate;
  236105. bufferSize = bufferSizeSamples;
  236106. if (sampleRates.size() == 0)
  236107. error = "Device has no available sample-rates";
  236108. else if (bufferSizes.size() == 0)
  236109. error = "Device has no available buffer-sizes";
  236110. else if (inputDevice != 0)
  236111. error = inputDevice->reopen (inputChannels,
  236112. outputChannels,
  236113. newSampleRate,
  236114. bufferSizeSamples);
  236115. }
  236116. }
  236117. callbacksAllowed = true;
  236118. return error;
  236119. }
  236120. bool start (AudioIODeviceCallback* cb)
  236121. {
  236122. if (! started)
  236123. {
  236124. callback = 0;
  236125. if (deviceID != 0)
  236126. {
  236127. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  236128. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, this)))
  236129. #else
  236130. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, this, &audioProcID)))
  236131. #endif
  236132. {
  236133. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  236134. {
  236135. started = true;
  236136. }
  236137. else
  236138. {
  236139. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  236140. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  236141. #else
  236142. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  236143. audioProcID = 0;
  236144. #endif
  236145. }
  236146. }
  236147. }
  236148. }
  236149. if (started)
  236150. {
  236151. const ScopedLock sl (callbackLock);
  236152. callback = cb;
  236153. }
  236154. if (inputDevice != 0)
  236155. return started && inputDevice->start (cb);
  236156. else
  236157. return started;
  236158. }
  236159. void stop (bool leaveInterruptRunning)
  236160. {
  236161. {
  236162. const ScopedLock sl (callbackLock);
  236163. callback = 0;
  236164. }
  236165. if (started
  236166. && (deviceID != 0)
  236167. && ! leaveInterruptRunning)
  236168. {
  236169. OK (AudioDeviceStop (deviceID, audioIOProc));
  236170. #if MAC_OS_X_VERSION_MIN_REQUIRED < MAC_OS_X_VERSION_10_5
  236171. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  236172. #else
  236173. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  236174. audioProcID = 0;
  236175. #endif
  236176. started = false;
  236177. { const ScopedLock sl (callbackLock); }
  236178. // wait until it's definately stopped calling back..
  236179. for (int i = 40; --i >= 0;)
  236180. {
  236181. Thread::sleep (50);
  236182. UInt32 running = 0;
  236183. UInt32 size = sizeof (running);
  236184. AudioObjectPropertyAddress pa;
  236185. pa.mSelector = kAudioDevicePropertyDeviceIsRunning;
  236186. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236187. pa.mElement = kAudioObjectPropertyElementMaster;
  236188. OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, &running));
  236189. if (running == 0)
  236190. break;
  236191. }
  236192. const ScopedLock sl (callbackLock);
  236193. }
  236194. if (inputDevice != 0)
  236195. inputDevice->stop (leaveInterruptRunning);
  236196. }
  236197. double getSampleRate() const
  236198. {
  236199. return sampleRate;
  236200. }
  236201. int getBufferSize() const
  236202. {
  236203. return bufferSize;
  236204. }
  236205. void audioCallback (const AudioBufferList* inInputData,
  236206. AudioBufferList* outOutputData)
  236207. {
  236208. int i;
  236209. const ScopedLock sl (callbackLock);
  236210. if (callback != 0)
  236211. {
  236212. if (inputDevice == 0)
  236213. {
  236214. for (i = numInputChans; --i >= 0;)
  236215. {
  236216. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  236217. float* dest = tempInputBuffers [i];
  236218. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  236219. + info.dataOffsetSamples;
  236220. const int stride = info.dataStrideSamples;
  236221. if (stride != 0) // if this is zero, info is invalid
  236222. {
  236223. for (int j = bufferSize; --j >= 0;)
  236224. {
  236225. *dest++ = *src;
  236226. src += stride;
  236227. }
  236228. }
  236229. }
  236230. }
  236231. if (! isSlaveDevice)
  236232. {
  236233. if (inputDevice == 0)
  236234. {
  236235. callback->audioDeviceIOCallback (const_cast<const float**> (tempInputBuffers.getData()),
  236236. numInputChans,
  236237. tempOutputBuffers,
  236238. numOutputChans,
  236239. bufferSize);
  236240. }
  236241. else
  236242. {
  236243. jassert (inputDevice->bufferSize == bufferSize);
  236244. // Sometimes the two linked devices seem to get their callbacks in
  236245. // parallel, so we need to lock both devices to stop the input data being
  236246. // changed while inside our callback..
  236247. const ScopedLock sl2 (inputDevice->callbackLock);
  236248. callback->audioDeviceIOCallback (const_cast<const float**> (inputDevice->tempInputBuffers.getData()),
  236249. inputDevice->numInputChans,
  236250. tempOutputBuffers,
  236251. numOutputChans,
  236252. bufferSize);
  236253. }
  236254. for (i = numOutputChans; --i >= 0;)
  236255. {
  236256. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236257. const float* src = tempOutputBuffers [i];
  236258. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236259. + info.dataOffsetSamples;
  236260. const int stride = info.dataStrideSamples;
  236261. if (stride != 0) // if this is zero, info is invalid
  236262. {
  236263. for (int j = bufferSize; --j >= 0;)
  236264. {
  236265. *dest = *src++;
  236266. dest += stride;
  236267. }
  236268. }
  236269. }
  236270. }
  236271. }
  236272. else
  236273. {
  236274. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  236275. {
  236276. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  236277. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  236278. + info.dataOffsetSamples;
  236279. const int stride = info.dataStrideSamples;
  236280. if (stride != 0) // if this is zero, info is invalid
  236281. {
  236282. for (int j = bufferSize; --j >= 0;)
  236283. {
  236284. *dest = 0.0f;
  236285. dest += stride;
  236286. }
  236287. }
  236288. }
  236289. }
  236290. }
  236291. // called by callbacks
  236292. void deviceDetailsChanged()
  236293. {
  236294. if (callbacksAllowed)
  236295. startTimer (100);
  236296. }
  236297. void timerCallback()
  236298. {
  236299. stopTimer();
  236300. log ("CoreAudio device changed callback");
  236301. const double oldSampleRate = sampleRate;
  236302. const int oldBufferSize = bufferSize;
  236303. updateDetailsFromDevice();
  236304. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  236305. {
  236306. callbacksAllowed = false;
  236307. stop (false);
  236308. updateDetailsFromDevice();
  236309. callbacksAllowed = true;
  236310. }
  236311. }
  236312. CoreAudioInternal* getRelatedDevice() const
  236313. {
  236314. UInt32 size = 0;
  236315. ScopedPointer <CoreAudioInternal> result;
  236316. AudioObjectPropertyAddress pa;
  236317. pa.mSelector = kAudioDevicePropertyRelatedDevices;
  236318. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236319. pa.mElement = kAudioObjectPropertyElementMaster;
  236320. if (deviceID != 0
  236321. && AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size) == noErr
  236322. && size > 0)
  236323. {
  236324. HeapBlock <AudioDeviceID> devs;
  236325. devs.calloc (size, 1);
  236326. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, devs)))
  236327. {
  236328. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  236329. {
  236330. if (devs[i] != deviceID && devs[i] != 0)
  236331. {
  236332. result = new CoreAudioInternal (devs[i]);
  236333. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  236334. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  236335. if (thisIsInput != otherIsInput
  236336. || (inChanNames.size() + outChanNames.size() == 0)
  236337. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  236338. break;
  236339. result = 0;
  236340. }
  236341. }
  236342. }
  236343. }
  236344. return result.release();
  236345. }
  236346. juce_UseDebuggingNewOperator
  236347. int inputLatency, outputLatency;
  236348. BigInteger activeInputChans, activeOutputChans;
  236349. StringArray inChanNames, outChanNames;
  236350. Array <double> sampleRates;
  236351. Array <int> bufferSizes;
  236352. AudioIODeviceCallback* callback;
  236353. #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
  236354. AudioDeviceIOProcID audioProcID;
  236355. #endif
  236356. ScopedPointer<CoreAudioInternal> inputDevice;
  236357. bool isSlaveDevice;
  236358. private:
  236359. CriticalSection callbackLock;
  236360. AudioDeviceID deviceID;
  236361. bool started;
  236362. double sampleRate;
  236363. int bufferSize;
  236364. HeapBlock <float> audioBuffer;
  236365. int numInputChans, numOutputChans;
  236366. bool callbacksAllowed;
  236367. struct CallbackDetailsForChannel
  236368. {
  236369. int streamNum;
  236370. int dataOffsetSamples;
  236371. int dataStrideSamples;
  236372. };
  236373. int numInputChannelInfos, numOutputChannelInfos;
  236374. HeapBlock <CallbackDetailsForChannel> inputChannelInfo, outputChannelInfo;
  236375. HeapBlock <float*> tempInputBuffers, tempOutputBuffers;
  236376. CoreAudioInternal (const CoreAudioInternal&);
  236377. CoreAudioInternal& operator= (const CoreAudioInternal&);
  236378. static OSStatus audioIOProc (AudioDeviceID /*inDevice*/,
  236379. const AudioTimeStamp* /*inNow*/,
  236380. const AudioBufferList* inInputData,
  236381. const AudioTimeStamp* /*inInputTime*/,
  236382. AudioBufferList* outOutputData,
  236383. const AudioTimeStamp* /*inOutputTime*/,
  236384. void* device)
  236385. {
  236386. static_cast <CoreAudioInternal*> (device)->audioCallback (inInputData, outOutputData);
  236387. return noErr;
  236388. }
  236389. static OSStatus deviceListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236390. {
  236391. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236392. switch (pa->mSelector)
  236393. {
  236394. case kAudioDevicePropertyBufferSize:
  236395. case kAudioDevicePropertyBufferFrameSize:
  236396. case kAudioDevicePropertyNominalSampleRate:
  236397. case kAudioDevicePropertyStreamFormat:
  236398. case kAudioDevicePropertyDeviceIsAlive:
  236399. intern->deviceDetailsChanged();
  236400. break;
  236401. case kAudioDevicePropertyBufferSizeRange:
  236402. case kAudioDevicePropertyVolumeScalar:
  236403. case kAudioDevicePropertyMute:
  236404. case kAudioDevicePropertyPlayThru:
  236405. case kAudioDevicePropertyDataSource:
  236406. case kAudioDevicePropertyDeviceIsRunning:
  236407. break;
  236408. }
  236409. return noErr;
  236410. }
  236411. static int getAllDataSourcesForDevice (AudioDeviceID deviceID, HeapBlock <OSType>& types)
  236412. {
  236413. AudioObjectPropertyAddress pa;
  236414. pa.mSelector = kAudioDevicePropertyDataSources;
  236415. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236416. pa.mElement = kAudioObjectPropertyElementMaster;
  236417. UInt32 size = 0;
  236418. if (deviceID != 0
  236419. && OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236420. {
  236421. types.calloc (size, 1);
  236422. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, types)))
  236423. return size / (int) sizeof (OSType);
  236424. }
  236425. return 0;
  236426. }
  236427. };
  236428. class CoreAudioIODevice : public AudioIODevice
  236429. {
  236430. public:
  236431. CoreAudioIODevice (const String& deviceName,
  236432. AudioDeviceID inputDeviceId,
  236433. const int inputIndex_,
  236434. AudioDeviceID outputDeviceId,
  236435. const int outputIndex_)
  236436. : AudioIODevice (deviceName, "CoreAudio"),
  236437. inputIndex (inputIndex_),
  236438. outputIndex (outputIndex_),
  236439. isOpen_ (false),
  236440. isStarted (false)
  236441. {
  236442. CoreAudioInternal* device = 0;
  236443. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  236444. {
  236445. jassert (inputDeviceId != 0);
  236446. device = new CoreAudioInternal (inputDeviceId);
  236447. }
  236448. else
  236449. {
  236450. device = new CoreAudioInternal (outputDeviceId);
  236451. if (inputDeviceId != 0)
  236452. {
  236453. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  236454. device->inputDevice = secondDevice;
  236455. secondDevice->isSlaveDevice = true;
  236456. }
  236457. }
  236458. internal = device;
  236459. AudioObjectPropertyAddress pa;
  236460. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236461. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236462. pa.mElement = kAudioObjectPropertyElementWildcard;
  236463. AudioObjectAddPropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236464. }
  236465. ~CoreAudioIODevice()
  236466. {
  236467. AudioObjectPropertyAddress pa;
  236468. pa.mSelector = kAudioObjectPropertySelectorWildcard;
  236469. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236470. pa.mElement = kAudioObjectPropertyElementWildcard;
  236471. AudioObjectRemovePropertyListener (kAudioObjectSystemObject, &pa, hardwareListenerProc, internal);
  236472. }
  236473. const StringArray getOutputChannelNames()
  236474. {
  236475. return internal->outChanNames;
  236476. }
  236477. const StringArray getInputChannelNames()
  236478. {
  236479. if (internal->inputDevice != 0)
  236480. return internal->inputDevice->inChanNames;
  236481. else
  236482. return internal->inChanNames;
  236483. }
  236484. int getNumSampleRates()
  236485. {
  236486. return internal->sampleRates.size();
  236487. }
  236488. double getSampleRate (int index)
  236489. {
  236490. return internal->sampleRates [index];
  236491. }
  236492. int getNumBufferSizesAvailable()
  236493. {
  236494. return internal->bufferSizes.size();
  236495. }
  236496. int getBufferSizeSamples (int index)
  236497. {
  236498. return internal->bufferSizes [index];
  236499. }
  236500. int getDefaultBufferSize()
  236501. {
  236502. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  236503. if (getBufferSizeSamples(i) >= 512)
  236504. return getBufferSizeSamples(i);
  236505. return 512;
  236506. }
  236507. const String open (const BigInteger& inputChannels,
  236508. const BigInteger& outputChannels,
  236509. double sampleRate,
  236510. int bufferSizeSamples)
  236511. {
  236512. isOpen_ = true;
  236513. if (bufferSizeSamples <= 0)
  236514. bufferSizeSamples = getDefaultBufferSize();
  236515. lastError = internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  236516. isOpen_ = lastError.isEmpty();
  236517. return lastError;
  236518. }
  236519. void close()
  236520. {
  236521. isOpen_ = false;
  236522. internal->stop (false);
  236523. }
  236524. bool isOpen()
  236525. {
  236526. return isOpen_;
  236527. }
  236528. int getCurrentBufferSizeSamples()
  236529. {
  236530. return internal != 0 ? internal->getBufferSize() : 512;
  236531. }
  236532. double getCurrentSampleRate()
  236533. {
  236534. return internal != 0 ? internal->getSampleRate() : 0;
  236535. }
  236536. int getCurrentBitDepth()
  236537. {
  236538. return 32; // no way to find out, so just assume it's high..
  236539. }
  236540. const BigInteger getActiveOutputChannels() const
  236541. {
  236542. return internal != 0 ? internal->activeOutputChans : BigInteger();
  236543. }
  236544. const BigInteger getActiveInputChannels() const
  236545. {
  236546. BigInteger chans;
  236547. if (internal != 0)
  236548. {
  236549. chans = internal->activeInputChans;
  236550. if (internal->inputDevice != 0)
  236551. chans |= internal->inputDevice->activeInputChans;
  236552. }
  236553. return chans;
  236554. }
  236555. int getOutputLatencyInSamples()
  236556. {
  236557. if (internal == 0)
  236558. return 0;
  236559. // this seems like a good guess at getting the latency right - comparing
  236560. // this with a round-trip measurement, it gets it to within a few millisecs
  236561. // for the built-in mac soundcard
  236562. return internal->outputLatency + internal->getBufferSize() * 2;
  236563. }
  236564. int getInputLatencyInSamples()
  236565. {
  236566. if (internal == 0)
  236567. return 0;
  236568. return internal->inputLatency + internal->getBufferSize() * 2;
  236569. }
  236570. void start (AudioIODeviceCallback* callback)
  236571. {
  236572. if (internal != 0 && ! isStarted)
  236573. {
  236574. if (callback != 0)
  236575. callback->audioDeviceAboutToStart (this);
  236576. isStarted = true;
  236577. internal->start (callback);
  236578. }
  236579. }
  236580. void stop()
  236581. {
  236582. if (isStarted && internal != 0)
  236583. {
  236584. AudioIODeviceCallback* const lastCallback = internal->callback;
  236585. isStarted = false;
  236586. internal->stop (true);
  236587. if (lastCallback != 0)
  236588. lastCallback->audioDeviceStopped();
  236589. }
  236590. }
  236591. bool isPlaying()
  236592. {
  236593. if (internal->callback == 0)
  236594. isStarted = false;
  236595. return isStarted;
  236596. }
  236597. const String getLastError()
  236598. {
  236599. return lastError;
  236600. }
  236601. int inputIndex, outputIndex;
  236602. juce_UseDebuggingNewOperator
  236603. private:
  236604. ScopedPointer<CoreAudioInternal> internal;
  236605. bool isOpen_, isStarted;
  236606. String lastError;
  236607. static OSStatus hardwareListenerProc (AudioDeviceID /*inDevice*/, UInt32 /*inLine*/, const AudioObjectPropertyAddress* pa, void* inClientData)
  236608. {
  236609. CoreAudioInternal* const intern = static_cast <CoreAudioInternal*> (inClientData);
  236610. switch (pa->mSelector)
  236611. {
  236612. case kAudioHardwarePropertyDevices:
  236613. intern->deviceDetailsChanged();
  236614. break;
  236615. case kAudioHardwarePropertyDefaultOutputDevice:
  236616. case kAudioHardwarePropertyDefaultInputDevice:
  236617. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  236618. break;
  236619. }
  236620. return noErr;
  236621. }
  236622. CoreAudioIODevice (const CoreAudioIODevice&);
  236623. CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  236624. };
  236625. class CoreAudioIODeviceType : public AudioIODeviceType
  236626. {
  236627. public:
  236628. CoreAudioIODeviceType()
  236629. : AudioIODeviceType ("CoreAudio"),
  236630. hasScanned (false)
  236631. {
  236632. }
  236633. ~CoreAudioIODeviceType()
  236634. {
  236635. }
  236636. void scanForDevices()
  236637. {
  236638. hasScanned = true;
  236639. inputDeviceNames.clear();
  236640. outputDeviceNames.clear();
  236641. inputIds.clear();
  236642. outputIds.clear();
  236643. UInt32 size;
  236644. AudioObjectPropertyAddress pa;
  236645. pa.mSelector = kAudioHardwarePropertyDevices;
  236646. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236647. pa.mElement = kAudioObjectPropertyElementMaster;
  236648. if (OK (AudioObjectGetPropertyDataSize (kAudioObjectSystemObject, &pa, 0, 0, &size)))
  236649. {
  236650. HeapBlock <AudioDeviceID> devs;
  236651. devs.calloc (size, 1);
  236652. if (OK (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, devs)))
  236653. {
  236654. const int num = size / (int) sizeof (AudioDeviceID);
  236655. for (int i = 0; i < num; ++i)
  236656. {
  236657. char name [1024];
  236658. size = sizeof (name);
  236659. pa.mSelector = kAudioDevicePropertyDeviceName;
  236660. if (OK (AudioObjectGetPropertyData (devs[i], &pa, 0, 0, &size, name)))
  236661. {
  236662. const String nameString (String::fromUTF8 (name, (int) strlen (name)));
  236663. const int numIns = getNumChannels (devs[i], true);
  236664. const int numOuts = getNumChannels (devs[i], false);
  236665. if (numIns > 0)
  236666. {
  236667. inputDeviceNames.add (nameString);
  236668. inputIds.add (devs[i]);
  236669. }
  236670. if (numOuts > 0)
  236671. {
  236672. outputDeviceNames.add (nameString);
  236673. outputIds.add (devs[i]);
  236674. }
  236675. }
  236676. }
  236677. }
  236678. }
  236679. inputDeviceNames.appendNumbersToDuplicates (false, true);
  236680. outputDeviceNames.appendNumbersToDuplicates (false, true);
  236681. }
  236682. const StringArray getDeviceNames (bool wantInputNames) const
  236683. {
  236684. jassert (hasScanned); // need to call scanForDevices() before doing this
  236685. if (wantInputNames)
  236686. return inputDeviceNames;
  236687. else
  236688. return outputDeviceNames;
  236689. }
  236690. int getDefaultDeviceIndex (bool forInput) const
  236691. {
  236692. jassert (hasScanned); // need to call scanForDevices() before doing this
  236693. AudioDeviceID deviceID;
  236694. UInt32 size = sizeof (deviceID);
  236695. // if they're asking for any input channels at all, use the default input, so we
  236696. // get the built-in mic rather than the built-in output with no inputs..
  236697. AudioObjectPropertyAddress pa;
  236698. pa.mSelector = forInput ? kAudioHardwarePropertyDefaultInputDevice : kAudioHardwarePropertyDefaultOutputDevice;
  236699. pa.mScope = kAudioObjectPropertyScopeWildcard;
  236700. pa.mElement = kAudioObjectPropertyElementMaster;
  236701. if (AudioObjectGetPropertyData (kAudioObjectSystemObject, &pa, 0, 0, &size, &deviceID) == noErr)
  236702. {
  236703. if (forInput)
  236704. {
  236705. for (int i = inputIds.size(); --i >= 0;)
  236706. if (inputIds[i] == deviceID)
  236707. return i;
  236708. }
  236709. else
  236710. {
  236711. for (int i = outputIds.size(); --i >= 0;)
  236712. if (outputIds[i] == deviceID)
  236713. return i;
  236714. }
  236715. }
  236716. return 0;
  236717. }
  236718. int getIndexOfDevice (AudioIODevice* device, bool asInput) const
  236719. {
  236720. jassert (hasScanned); // need to call scanForDevices() before doing this
  236721. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  236722. if (d == 0)
  236723. return -1;
  236724. return asInput ? d->inputIndex
  236725. : d->outputIndex;
  236726. }
  236727. bool hasSeparateInputsAndOutputs() const { return true; }
  236728. AudioIODevice* createDevice (const String& outputDeviceName,
  236729. const String& inputDeviceName)
  236730. {
  236731. jassert (hasScanned); // need to call scanForDevices() before doing this
  236732. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  236733. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  236734. String deviceName (outputDeviceName);
  236735. if (deviceName.isEmpty())
  236736. deviceName = inputDeviceName;
  236737. if (index >= 0)
  236738. return new CoreAudioIODevice (deviceName,
  236739. inputIds [inputIndex],
  236740. inputIndex,
  236741. outputIds [outputIndex],
  236742. outputIndex);
  236743. return 0;
  236744. }
  236745. juce_UseDebuggingNewOperator
  236746. private:
  236747. StringArray inputDeviceNames, outputDeviceNames;
  236748. Array <AudioDeviceID> inputIds, outputIds;
  236749. bool hasScanned;
  236750. static int getNumChannels (AudioDeviceID deviceID, bool input)
  236751. {
  236752. int total = 0;
  236753. UInt32 size;
  236754. AudioObjectPropertyAddress pa;
  236755. pa.mSelector = kAudioDevicePropertyStreamConfiguration;
  236756. pa.mScope = input ? kAudioDevicePropertyScopeInput : kAudioDevicePropertyScopeOutput;
  236757. pa.mElement = kAudioObjectPropertyElementMaster;
  236758. if (OK (AudioObjectGetPropertyDataSize (deviceID, &pa, 0, 0, &size)))
  236759. {
  236760. HeapBlock <AudioBufferList> bufList;
  236761. bufList.calloc (size, 1);
  236762. if (OK (AudioObjectGetPropertyData (deviceID, &pa, 0, 0, &size, bufList)))
  236763. {
  236764. const int numStreams = bufList->mNumberBuffers;
  236765. for (int i = 0; i < numStreams; ++i)
  236766. {
  236767. const AudioBuffer& b = bufList->mBuffers[i];
  236768. total += b.mNumberChannels;
  236769. }
  236770. }
  236771. }
  236772. return total;
  236773. }
  236774. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  236775. CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  236776. };
  236777. AudioIODeviceType* juce_createAudioIODeviceType_CoreAudio()
  236778. {
  236779. return new CoreAudioIODeviceType();
  236780. }
  236781. #undef log
  236782. #endif
  236783. /*** End of inlined file: juce_mac_CoreAudio.cpp ***/
  236784. /*** Start of inlined file: juce_mac_CoreMidi.cpp ***/
  236785. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  236786. // compiled on its own).
  236787. #if JUCE_INCLUDED_FILE
  236788. #if JUCE_MAC
  236789. namespace CoreMidiHelpers
  236790. {
  236791. static bool logError (const OSStatus err, const int lineNum)
  236792. {
  236793. if (err == noErr)
  236794. return true;
  236795. Logger::writeToLog ("CoreMidi error: " + String (lineNum) + " - " + String::toHexString ((int) err));
  236796. jassertfalse;
  236797. return false;
  236798. }
  236799. #undef CHECK_ERROR
  236800. #define CHECK_ERROR(a) CoreMidiHelpers::logError (a, __LINE__)
  236801. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  236802. {
  236803. String result;
  236804. CFStringRef str = 0;
  236805. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  236806. if (str != 0)
  236807. {
  236808. result = PlatformUtilities::cfStringToJuceString (str);
  236809. CFRelease (str);
  236810. str = 0;
  236811. }
  236812. MIDIEntityRef entity = 0;
  236813. MIDIEndpointGetEntity (endpoint, &entity);
  236814. if (entity == 0)
  236815. return result; // probably virtual
  236816. if (result.isEmpty())
  236817. {
  236818. // endpoint name has zero length - try the entity
  236819. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  236820. if (str != 0)
  236821. {
  236822. result += PlatformUtilities::cfStringToJuceString (str);
  236823. CFRelease (str);
  236824. str = 0;
  236825. }
  236826. }
  236827. // now consider the device's name
  236828. MIDIDeviceRef device = 0;
  236829. MIDIEntityGetDevice (entity, &device);
  236830. if (device == 0)
  236831. return result;
  236832. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  236833. if (str != 0)
  236834. {
  236835. const String s (PlatformUtilities::cfStringToJuceString (str));
  236836. CFRelease (str);
  236837. // if an external device has only one entity, throw away
  236838. // the endpoint name and just use the device name
  236839. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  236840. {
  236841. result = s;
  236842. }
  236843. else if (! result.startsWithIgnoreCase (s))
  236844. {
  236845. // prepend the device name to the entity name
  236846. result = (s + " " + result).trimEnd();
  236847. }
  236848. }
  236849. return result;
  236850. }
  236851. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  236852. {
  236853. String result;
  236854. // Does the endpoint have connections?
  236855. CFDataRef connections = 0;
  236856. int numConnections = 0;
  236857. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  236858. if (connections != 0)
  236859. {
  236860. numConnections = (int) (CFDataGetLength (connections) / sizeof (MIDIUniqueID));
  236861. if (numConnections > 0)
  236862. {
  236863. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  236864. for (int i = 0; i < numConnections; ++i, ++pid)
  236865. {
  236866. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  236867. MIDIObjectRef connObject;
  236868. MIDIObjectType connObjectType;
  236869. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  236870. if (err == noErr)
  236871. {
  236872. String s;
  236873. if (connObjectType == kMIDIObjectType_ExternalSource
  236874. || connObjectType == kMIDIObjectType_ExternalDestination)
  236875. {
  236876. // Connected to an external device's endpoint (10.3 and later).
  236877. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  236878. }
  236879. else
  236880. {
  236881. // Connected to an external device (10.2) (or something else, catch-all)
  236882. CFStringRef str = 0;
  236883. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  236884. if (str != 0)
  236885. {
  236886. s = PlatformUtilities::cfStringToJuceString (str);
  236887. CFRelease (str);
  236888. }
  236889. }
  236890. if (s.isNotEmpty())
  236891. {
  236892. if (result.isNotEmpty())
  236893. result += ", ";
  236894. result += s;
  236895. }
  236896. }
  236897. }
  236898. }
  236899. CFRelease (connections);
  236900. }
  236901. if (result.isNotEmpty())
  236902. return result;
  236903. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  236904. return getEndpointName (endpoint, false);
  236905. }
  236906. static MIDIClientRef getGlobalMidiClient()
  236907. {
  236908. static MIDIClientRef globalMidiClient = 0;
  236909. if (globalMidiClient == 0)
  236910. {
  236911. String name ("JUCE");
  236912. if (JUCEApplication::getInstance() != 0)
  236913. name = JUCEApplication::getInstance()->getApplicationName();
  236914. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  236915. CHECK_ERROR (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  236916. CFRelease (appName);
  236917. }
  236918. return globalMidiClient;
  236919. }
  236920. class MidiPortAndEndpoint
  236921. {
  236922. public:
  236923. MidiPortAndEndpoint (MIDIPortRef port_, MIDIEndpointRef endPoint_)
  236924. : port (port_), endPoint (endPoint_)
  236925. {
  236926. }
  236927. ~MidiPortAndEndpoint()
  236928. {
  236929. if (port != 0)
  236930. MIDIPortDispose (port);
  236931. if (port == 0 && endPoint != 0) // if port == 0, it means we created the endpoint, so it's safe to delete it
  236932. MIDIEndpointDispose (endPoint);
  236933. }
  236934. void send (const MIDIPacketList* const packets)
  236935. {
  236936. if (port != 0)
  236937. MIDISend (port, endPoint, packets);
  236938. else
  236939. MIDIReceived (endPoint, packets);
  236940. }
  236941. MIDIPortRef port;
  236942. MIDIEndpointRef endPoint;
  236943. };
  236944. class MidiPortAndCallback;
  236945. static CriticalSection callbackLock;
  236946. static Array<MidiPortAndCallback*> activeCallbacks;
  236947. class MidiPortAndCallback
  236948. {
  236949. public:
  236950. MidiPortAndCallback (MidiInputCallback& callback_)
  236951. : input (0), active (false), callback (callback_), concatenator (2048)
  236952. {
  236953. }
  236954. ~MidiPortAndCallback()
  236955. {
  236956. active = false;
  236957. {
  236958. const ScopedLock sl (callbackLock);
  236959. activeCallbacks.removeValue (this);
  236960. }
  236961. if (portAndEndpoint != 0 && portAndEndpoint->port != 0)
  236962. CHECK_ERROR (MIDIPortDisconnectSource (portAndEndpoint->port, portAndEndpoint->endPoint));
  236963. }
  236964. void handlePackets (const MIDIPacketList* const pktlist)
  236965. {
  236966. const double time = Time::getMillisecondCounterHiRes() * 0.001;
  236967. const ScopedLock sl (callbackLock);
  236968. if (activeCallbacks.contains (this) && active)
  236969. {
  236970. const MIDIPacket* packet = &pktlist->packet[0];
  236971. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  236972. {
  236973. concatenator.pushMidiData (packet->data, (int) packet->length, time,
  236974. input, callback);
  236975. packet = MIDIPacketNext (packet);
  236976. }
  236977. }
  236978. }
  236979. MidiInput* input;
  236980. ScopedPointer<MidiPortAndEndpoint> portAndEndpoint;
  236981. volatile bool active;
  236982. private:
  236983. MidiInputCallback& callback;
  236984. MidiDataConcatenator concatenator;
  236985. };
  236986. static void midiInputProc (const MIDIPacketList* pktlist, void* readProcRefCon, void* /*srcConnRefCon*/)
  236987. {
  236988. static_cast <MidiPortAndCallback*> (readProcRefCon)->handlePackets (pktlist);
  236989. }
  236990. }
  236991. const StringArray MidiOutput::getDevices()
  236992. {
  236993. StringArray s;
  236994. const ItemCount num = MIDIGetNumberOfDestinations();
  236995. for (ItemCount i = 0; i < num; ++i)
  236996. {
  236997. MIDIEndpointRef dest = MIDIGetDestination (i);
  236998. if (dest != 0)
  236999. {
  237000. String name (CoreMidiHelpers::getConnectedEndpointName (dest));
  237001. if (name.isEmpty())
  237002. name = "<error>";
  237003. s.add (name);
  237004. }
  237005. else
  237006. {
  237007. s.add ("<error>");
  237008. }
  237009. }
  237010. return s;
  237011. }
  237012. int MidiOutput::getDefaultDeviceIndex()
  237013. {
  237014. return 0;
  237015. }
  237016. MidiOutput* MidiOutput::openDevice (int index)
  237017. {
  237018. MidiOutput* mo = 0;
  237019. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  237020. {
  237021. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  237022. CFStringRef pname;
  237023. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  237024. {
  237025. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  237026. MIDIPortRef port;
  237027. if (client != 0 && CHECK_ERROR (MIDIOutputPortCreate (client, pname, &port)))
  237028. {
  237029. mo = new MidiOutput();
  237030. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (port, endPoint);
  237031. }
  237032. CFRelease (pname);
  237033. }
  237034. }
  237035. return mo;
  237036. }
  237037. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  237038. {
  237039. MidiOutput* mo = 0;
  237040. MIDIClientRef client = CoreMidiHelpers::getGlobalMidiClient();
  237041. MIDIEndpointRef endPoint;
  237042. CFStringRef name = PlatformUtilities::juceStringToCFString (deviceName);
  237043. if (client != 0 && CHECK_ERROR (MIDISourceCreate (client, name, &endPoint)))
  237044. {
  237045. mo = new MidiOutput();
  237046. mo->internal = new CoreMidiHelpers::MidiPortAndEndpoint (0, endPoint);
  237047. }
  237048. CFRelease (name);
  237049. return mo;
  237050. }
  237051. MidiOutput::~MidiOutput()
  237052. {
  237053. delete static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  237054. }
  237055. void MidiOutput::reset()
  237056. {
  237057. }
  237058. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/)
  237059. {
  237060. return false;
  237061. }
  237062. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/)
  237063. {
  237064. }
  237065. void MidiOutput::sendMessageNow (const MidiMessage& message)
  237066. {
  237067. CoreMidiHelpers::MidiPortAndEndpoint* const mpe = static_cast<CoreMidiHelpers::MidiPortAndEndpoint*> (internal);
  237068. if (message.isSysEx())
  237069. {
  237070. const int maxPacketSize = 256;
  237071. int pos = 0, bytesLeft = message.getRawDataSize();
  237072. const int numPackets = (bytesLeft + maxPacketSize - 1) / maxPacketSize;
  237073. HeapBlock <MIDIPacketList> packets;
  237074. packets.malloc (32 * numPackets + message.getRawDataSize(), 1);
  237075. packets->numPackets = numPackets;
  237076. MIDIPacket* p = packets->packet;
  237077. for (int i = 0; i < numPackets; ++i)
  237078. {
  237079. p->timeStamp = 0;
  237080. p->length = jmin (maxPacketSize, bytesLeft);
  237081. memcpy (p->data, message.getRawData() + pos, p->length);
  237082. pos += p->length;
  237083. bytesLeft -= p->length;
  237084. p = MIDIPacketNext (p);
  237085. }
  237086. mpe->send (packets);
  237087. }
  237088. else
  237089. {
  237090. MIDIPacketList packets;
  237091. packets.numPackets = 1;
  237092. packets.packet[0].timeStamp = 0;
  237093. packets.packet[0].length = message.getRawDataSize();
  237094. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  237095. mpe->send (&packets);
  237096. }
  237097. }
  237098. const StringArray MidiInput::getDevices()
  237099. {
  237100. StringArray s;
  237101. const ItemCount num = MIDIGetNumberOfSources();
  237102. for (ItemCount i = 0; i < num; ++i)
  237103. {
  237104. MIDIEndpointRef source = MIDIGetSource (i);
  237105. if (source != 0)
  237106. {
  237107. String name (CoreMidiHelpers::getConnectedEndpointName (source));
  237108. if (name.isEmpty())
  237109. name = "<error>";
  237110. s.add (name);
  237111. }
  237112. else
  237113. {
  237114. s.add ("<error>");
  237115. }
  237116. }
  237117. return s;
  237118. }
  237119. int MidiInput::getDefaultDeviceIndex()
  237120. {
  237121. return 0;
  237122. }
  237123. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  237124. {
  237125. jassert (callback != 0);
  237126. using namespace CoreMidiHelpers;
  237127. MidiInput* newInput = 0;
  237128. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  237129. {
  237130. MIDIEndpointRef endPoint = MIDIGetSource (index);
  237131. if (endPoint != 0)
  237132. {
  237133. CFStringRef name;
  237134. if (CHECK_ERROR (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &name)))
  237135. {
  237136. MIDIClientRef client = getGlobalMidiClient();
  237137. if (client != 0)
  237138. {
  237139. MIDIPortRef port;
  237140. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  237141. if (CHECK_ERROR (MIDIInputPortCreate (client, name, midiInputProc, mpc, &port)))
  237142. {
  237143. if (CHECK_ERROR (MIDIPortConnectSource (port, endPoint, 0)))
  237144. {
  237145. mpc->portAndEndpoint = new MidiPortAndEndpoint (port, endPoint);
  237146. newInput = new MidiInput (getDevices() [index]);
  237147. mpc->input = newInput;
  237148. newInput->internal = mpc;
  237149. const ScopedLock sl (callbackLock);
  237150. activeCallbacks.add (mpc.release());
  237151. }
  237152. else
  237153. {
  237154. CHECK_ERROR (MIDIPortDispose (port));
  237155. }
  237156. }
  237157. }
  237158. }
  237159. CFRelease (name);
  237160. }
  237161. }
  237162. return newInput;
  237163. }
  237164. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  237165. {
  237166. jassert (callback != 0);
  237167. using namespace CoreMidiHelpers;
  237168. MidiInput* mi = 0;
  237169. MIDIClientRef client = getGlobalMidiClient();
  237170. if (client != 0)
  237171. {
  237172. ScopedPointer <MidiPortAndCallback> mpc (new MidiPortAndCallback (*callback));
  237173. mpc->active = false;
  237174. MIDIEndpointRef endPoint;
  237175. CFStringRef name = PlatformUtilities::juceStringToCFString(deviceName);
  237176. if (CHECK_ERROR (MIDIDestinationCreate (client, name, midiInputProc, mpc, &endPoint)))
  237177. {
  237178. mpc->portAndEndpoint = new MidiPortAndEndpoint (0, endPoint);
  237179. mi = new MidiInput (deviceName);
  237180. mpc->input = mi;
  237181. mi->internal = mpc;
  237182. const ScopedLock sl (callbackLock);
  237183. activeCallbacks.add (mpc.release());
  237184. }
  237185. CFRelease (name);
  237186. }
  237187. return mi;
  237188. }
  237189. MidiInput::MidiInput (const String& name_)
  237190. : name (name_)
  237191. {
  237192. }
  237193. MidiInput::~MidiInput()
  237194. {
  237195. delete static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal);
  237196. }
  237197. void MidiInput::start()
  237198. {
  237199. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237200. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = true;
  237201. }
  237202. void MidiInput::stop()
  237203. {
  237204. const ScopedLock sl (CoreMidiHelpers::callbackLock);
  237205. static_cast<CoreMidiHelpers::MidiPortAndCallback*> (internal)->active = false;
  237206. }
  237207. #undef CHECK_ERROR
  237208. #else // Stubs for iOS...
  237209. MidiOutput::~MidiOutput() {}
  237210. void MidiOutput::reset() {}
  237211. bool MidiOutput::getVolume (float& /*leftVol*/, float& /*rightVol*/) { return false; }
  237212. void MidiOutput::setVolume (float /*leftVol*/, float /*rightVol*/) {}
  237213. void MidiOutput::sendMessageNow (const MidiMessage& message) {}
  237214. const StringArray MidiOutput::getDevices() { return StringArray(); }
  237215. MidiOutput* MidiOutput::openDevice (int index) { return 0; }
  237216. const StringArray MidiInput::getDevices() { return StringArray(); }
  237217. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback) { return 0; }
  237218. #endif
  237219. #endif
  237220. /*** End of inlined file: juce_mac_CoreMidi.cpp ***/
  237221. /*** Start of inlined file: juce_mac_CameraDevice.mm ***/
  237222. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  237223. // compiled on its own).
  237224. #if JUCE_INCLUDED_FILE && JUCE_USE_CAMERA
  237225. #if ! JUCE_QUICKTIME
  237226. #error "On the Mac, cameras use Quicktime, so if you turn on JUCE_USE_CAMERA, you also need to enable JUCE_QUICKTIME"
  237227. #endif
  237228. #define QTCaptureCallbackDelegate MakeObjCClassName(QTCaptureCallbackDelegate)
  237229. class QTCameraDeviceInteral;
  237230. END_JUCE_NAMESPACE
  237231. @interface QTCaptureCallbackDelegate : NSObject
  237232. {
  237233. @public
  237234. CameraDevice* owner;
  237235. QTCameraDeviceInteral* internal;
  237236. int64 firstPresentationTime;
  237237. int64 averageTimeOffset;
  237238. }
  237239. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner internalDev: (QTCameraDeviceInteral*) d;
  237240. - (void) dealloc;
  237241. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237242. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237243. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237244. fromConnection: (QTCaptureConnection*) connection;
  237245. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237246. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237247. fromConnection: (QTCaptureConnection*) connection;
  237248. @end
  237249. BEGIN_JUCE_NAMESPACE
  237250. class QTCameraDeviceInteral
  237251. {
  237252. public:
  237253. QTCameraDeviceInteral (CameraDevice* owner, int index)
  237254. {
  237255. const ScopedAutoReleasePool pool;
  237256. session = [[QTCaptureSession alloc] init];
  237257. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237258. device = (QTCaptureDevice*) [devs objectAtIndex: index];
  237259. input = 0;
  237260. audioInput = 0;
  237261. audioDevice = 0;
  237262. fileOutput = 0;
  237263. imageOutput = 0;
  237264. callbackDelegate = [[QTCaptureCallbackDelegate alloc] initWithOwner: owner
  237265. internalDev: this];
  237266. NSError* err = 0;
  237267. [device retain];
  237268. [device open: &err];
  237269. if (err == 0)
  237270. {
  237271. input = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237272. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: device];
  237273. [session addInput: input error: &err];
  237274. if (err == 0)
  237275. {
  237276. resetFile();
  237277. imageOutput = [[QTCaptureDecompressedVideoOutput alloc] init];
  237278. [imageOutput setDelegate: callbackDelegate];
  237279. if (err == 0)
  237280. {
  237281. [session startRunning];
  237282. return;
  237283. }
  237284. }
  237285. }
  237286. openingError = nsStringToJuce ([err description]);
  237287. DBG (openingError);
  237288. }
  237289. ~QTCameraDeviceInteral()
  237290. {
  237291. [session stopRunning];
  237292. [session removeOutput: imageOutput];
  237293. [session release];
  237294. [input release];
  237295. [device release];
  237296. [audioDevice release];
  237297. [audioInput release];
  237298. [fileOutput release];
  237299. [imageOutput release];
  237300. [callbackDelegate release];
  237301. }
  237302. void resetFile()
  237303. {
  237304. [fileOutput recordToOutputFileURL: nil];
  237305. [session removeOutput: fileOutput];
  237306. [fileOutput release];
  237307. fileOutput = [[QTCaptureMovieFileOutput alloc] init];
  237308. [session removeInput: audioInput];
  237309. [audioInput release];
  237310. audioInput = 0;
  237311. [audioDevice release];
  237312. audioDevice = 0;
  237313. [fileOutput setDelegate: callbackDelegate];
  237314. }
  237315. void addDefaultAudioInput()
  237316. {
  237317. NSError* err = nil;
  237318. audioDevice = [QTCaptureDevice defaultInputDeviceWithMediaType: QTMediaTypeSound];
  237319. if ([audioDevice open: &err])
  237320. [audioDevice retain];
  237321. else
  237322. audioDevice = nil;
  237323. if (audioDevice != 0)
  237324. {
  237325. audioInput = [[QTCaptureDeviceInput alloc] initWithDevice: audioDevice];
  237326. [session addInput: audioInput error: &err];
  237327. }
  237328. }
  237329. void addListener (CameraDevice::Listener* listenerToAdd)
  237330. {
  237331. const ScopedLock sl (listenerLock);
  237332. if (listeners.size() == 0)
  237333. [session addOutput: imageOutput error: nil];
  237334. listeners.addIfNotAlreadyThere (listenerToAdd);
  237335. }
  237336. void removeListener (CameraDevice::Listener* listenerToRemove)
  237337. {
  237338. const ScopedLock sl (listenerLock);
  237339. listeners.removeValue (listenerToRemove);
  237340. if (listeners.size() == 0)
  237341. [session removeOutput: imageOutput];
  237342. }
  237343. void callListeners (CIImage* frame, int w, int h)
  237344. {
  237345. CoreGraphicsImage* cgImage = new CoreGraphicsImage (Image::ARGB, w, h, false);
  237346. Image image (cgImage);
  237347. CIContext* cic = [CIContext contextWithCGContext: cgImage->context options: nil];
  237348. [cic drawImage: frame inRect: CGRectMake (0, 0, w, h) fromRect: CGRectMake (0, 0, w, h)];
  237349. CGContextFlush (cgImage->context);
  237350. const ScopedLock sl (listenerLock);
  237351. for (int i = listeners.size(); --i >= 0;)
  237352. {
  237353. CameraDevice::Listener* const l = listeners[i];
  237354. if (l != 0)
  237355. l->imageReceived (image);
  237356. }
  237357. }
  237358. QTCaptureDevice* device;
  237359. QTCaptureDeviceInput* input;
  237360. QTCaptureDevice* audioDevice;
  237361. QTCaptureDeviceInput* audioInput;
  237362. QTCaptureSession* session;
  237363. QTCaptureMovieFileOutput* fileOutput;
  237364. QTCaptureDecompressedVideoOutput* imageOutput;
  237365. QTCaptureCallbackDelegate* callbackDelegate;
  237366. String openingError;
  237367. Array<CameraDevice::Listener*> listeners;
  237368. CriticalSection listenerLock;
  237369. };
  237370. END_JUCE_NAMESPACE
  237371. @implementation QTCaptureCallbackDelegate
  237372. - (QTCaptureCallbackDelegate*) initWithOwner: (CameraDevice*) owner_
  237373. internalDev: (QTCameraDeviceInteral*) d
  237374. {
  237375. [super init];
  237376. owner = owner_;
  237377. internal = d;
  237378. firstPresentationTime = 0;
  237379. averageTimeOffset = 0;
  237380. return self;
  237381. }
  237382. - (void) dealloc
  237383. {
  237384. [super dealloc];
  237385. }
  237386. - (void) captureOutput: (QTCaptureOutput*) captureOutput
  237387. didOutputVideoFrame: (CVImageBufferRef) videoFrame
  237388. withSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237389. fromConnection: (QTCaptureConnection*) connection
  237390. {
  237391. if (internal->listeners.size() > 0)
  237392. {
  237393. const ScopedAutoReleasePool pool;
  237394. internal->callListeners ([CIImage imageWithCVImageBuffer: videoFrame],
  237395. CVPixelBufferGetWidth (videoFrame),
  237396. CVPixelBufferGetHeight (videoFrame));
  237397. }
  237398. }
  237399. - (void) captureOutput: (QTCaptureFileOutput*) captureOutput
  237400. didOutputSampleBuffer: (QTSampleBuffer*) sampleBuffer
  237401. fromConnection: (QTCaptureConnection*) connection
  237402. {
  237403. const Time now (Time::getCurrentTime());
  237404. #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
  237405. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: QTSampleBufferHostTimeAttribute];
  237406. #else
  237407. NSNumber* hosttime = (NSNumber*) [sampleBuffer attributeForKey: @"hostTime"];
  237408. #endif
  237409. int64 presentationTime = (hosttime != nil)
  237410. ? ((int64) AudioConvertHostTimeToNanos ([hosttime unsignedLongLongValue]) / 1000000 + 40)
  237411. : (([sampleBuffer presentationTime].timeValue * 1000) / [sampleBuffer presentationTime].timeScale + 50);
  237412. const int64 timeDiff = now.toMilliseconds() - presentationTime;
  237413. if (firstPresentationTime == 0)
  237414. {
  237415. firstPresentationTime = presentationTime;
  237416. averageTimeOffset = timeDiff;
  237417. }
  237418. else
  237419. {
  237420. averageTimeOffset = (averageTimeOffset * 120 + timeDiff * 8) / 128;
  237421. }
  237422. }
  237423. @end
  237424. BEGIN_JUCE_NAMESPACE
  237425. class QTCaptureViewerComp : public NSViewComponent
  237426. {
  237427. public:
  237428. QTCaptureViewerComp (CameraDevice* const cameraDevice, QTCameraDeviceInteral* const internal)
  237429. {
  237430. const ScopedAutoReleasePool pool;
  237431. captureView = [[QTCaptureView alloc] init];
  237432. [captureView setCaptureSession: internal->session];
  237433. setSize (640, 480); // xxx need to somehow get the movie size - how?
  237434. setView (captureView);
  237435. }
  237436. ~QTCaptureViewerComp()
  237437. {
  237438. setView (0);
  237439. [captureView setCaptureSession: nil];
  237440. [captureView release];
  237441. }
  237442. QTCaptureView* captureView;
  237443. };
  237444. CameraDevice::CameraDevice (const String& name_, int index)
  237445. : name (name_)
  237446. {
  237447. isRecording = false;
  237448. internal = new QTCameraDeviceInteral (this, index);
  237449. }
  237450. CameraDevice::~CameraDevice()
  237451. {
  237452. stopRecording();
  237453. delete static_cast <QTCameraDeviceInteral*> (internal);
  237454. internal = 0;
  237455. }
  237456. Component* CameraDevice::createViewerComponent()
  237457. {
  237458. return new QTCaptureViewerComp (this, static_cast <QTCameraDeviceInteral*> (internal));
  237459. }
  237460. const String CameraDevice::getFileExtension()
  237461. {
  237462. return ".mov";
  237463. }
  237464. void CameraDevice::startRecordingToFile (const File& file, int quality)
  237465. {
  237466. stopRecording();
  237467. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237468. d->callbackDelegate->firstPresentationTime = 0;
  237469. file.deleteFile();
  237470. // In some versions of QT (e.g. on 10.5), if you record video without audio, the speed comes
  237471. // out wrong, so we'll put some audio in there too..,
  237472. d->addDefaultAudioInput();
  237473. [d->session addOutput: d->fileOutput error: nil];
  237474. NSEnumerator* connectionEnumerator = [[d->fileOutput connections] objectEnumerator];
  237475. for (;;)
  237476. {
  237477. QTCaptureConnection* connection = [connectionEnumerator nextObject];
  237478. if (connection == 0)
  237479. break;
  237480. QTCompressionOptions* options = 0;
  237481. NSString* mediaType = [connection mediaType];
  237482. if ([mediaType isEqualToString: QTMediaTypeVideo])
  237483. options = [QTCompressionOptions compressionOptionsWithIdentifier:
  237484. quality >= 1 ? @"QTCompressionOptionsSD480SizeH264Video"
  237485. : @"QTCompressionOptions240SizeH264Video"];
  237486. else if ([mediaType isEqualToString: QTMediaTypeSound])
  237487. options = [QTCompressionOptions compressionOptionsWithIdentifier: @"QTCompressionOptionsHighQualityAACAudio"];
  237488. [d->fileOutput setCompressionOptions: options forConnection: connection];
  237489. }
  237490. [d->fileOutput recordToOutputFileURL: [NSURL fileURLWithPath: juceStringToNS (file.getFullPathName())]];
  237491. isRecording = true;
  237492. }
  237493. const Time CameraDevice::getTimeOfFirstRecordedFrame() const
  237494. {
  237495. QTCameraDeviceInteral* const d = static_cast <QTCameraDeviceInteral*> (internal);
  237496. if (d->callbackDelegate->firstPresentationTime != 0)
  237497. return Time (d->callbackDelegate->firstPresentationTime + d->callbackDelegate->averageTimeOffset);
  237498. return Time();
  237499. }
  237500. void CameraDevice::stopRecording()
  237501. {
  237502. if (isRecording)
  237503. {
  237504. static_cast <QTCameraDeviceInteral*> (internal)->resetFile();
  237505. isRecording = false;
  237506. }
  237507. }
  237508. void CameraDevice::addListener (Listener* listenerToAdd)
  237509. {
  237510. if (listenerToAdd != 0)
  237511. static_cast <QTCameraDeviceInteral*> (internal)->addListener (listenerToAdd);
  237512. }
  237513. void CameraDevice::removeListener (Listener* listenerToRemove)
  237514. {
  237515. if (listenerToRemove != 0)
  237516. static_cast <QTCameraDeviceInteral*> (internal)->removeListener (listenerToRemove);
  237517. }
  237518. const StringArray CameraDevice::getAvailableDevices()
  237519. {
  237520. const ScopedAutoReleasePool pool;
  237521. StringArray results;
  237522. NSArray* devs = [QTCaptureDevice inputDevicesWithMediaType: QTMediaTypeVideo];
  237523. for (int i = 0; i < (int) [devs count]; ++i)
  237524. {
  237525. QTCaptureDevice* dev = (QTCaptureDevice*) [devs objectAtIndex: i];
  237526. results.add (nsStringToJuce ([dev localizedDisplayName]));
  237527. }
  237528. return results;
  237529. }
  237530. CameraDevice* CameraDevice::openDevice (int index,
  237531. int minWidth, int minHeight,
  237532. int maxWidth, int maxHeight)
  237533. {
  237534. ScopedPointer <CameraDevice> d (new CameraDevice (getAvailableDevices() [index], index));
  237535. if (static_cast <QTCameraDeviceInteral*> (d->internal)->openingError.isEmpty())
  237536. return d.release();
  237537. return 0;
  237538. }
  237539. #endif
  237540. /*** End of inlined file: juce_mac_CameraDevice.mm ***/
  237541. #endif
  237542. #endif
  237543. END_JUCE_NAMESPACE
  237544. #endif
  237545. /*** End of inlined file: juce_mac_NativeCode.mm ***/
  237546. #endif
  237547. #endif